Index: test/SemaCXX/const-cast.cpp
===================================================================
--- test/SemaCXX/const-cast.cpp	(revision 0)
+++ test/SemaCXX/const-cast.cpp	(revision 0)
@@ -0,0 +1,56 @@
+// RUN: clang -fsyntax-only -verify %s
+
+// See if aliasing can confuse this baby.
+typedef char c;
+typedef c *cp;
+typedef cp *cpp;
+typedef cpp *cppp;
+typedef cppp &cpppr;
+typedef const cppp &cpppcr;
+typedef const char cc;
+typedef cc *ccp;
+typedef volatile ccp ccvp;
+typedef ccvp *ccvpp;
+typedef const volatile ccvpp ccvpcvp;
+typedef ccvpcvp *ccvpcvpp;
+typedef int iar[100];
+typedef iar &iarr;
+typedef int (*f)(int);
+
+char ***good_const_cast_test(ccvpcvpp var)
+{
+  // Cast away deep consts and volatiles.
+  char ***var2 = const_cast<cppp>(var);
+  char ***const &var3 = static_cast<cpppcr>(var2); // Different bug.
+  // Const reference to reference.
+  char ***&var4 = const_cast<cpppr>(var3);
+  // Drop reference. Intentionally without qualifier change.
+  char *** var5 = const_cast<cppp>(var4);
+  const int ar[100] = {0};
+  int (&rar)[100] = const_cast<iarr>(ar); // expected-warning {{statement was disambiguated as declaration}} expected-error {{const_cast from 'int const [100]' to 'iarr' is not allowed}}
+  // Array decay. Intentionally without qualifier change.
+  int *pi = const_cast<int*>(ar);
+  f fp = 0;
+  // Don't misidentify fn** as a function pointer.
+  f *fpp = const_cast<f*>(&fp);
+  return var4;
+}
+
+short *bad_const_cast_test(char const *volatile *const volatile *var)
+{
+  // Different pointer levels.
+  char **var2 = const_cast<char**>(var); // expected-error {{const_cast from 'char const *volatile *const volatile *' to 'char **' is not allowed}}
+  // Different final type.
+  short ***var3 = const_cast<short***>(var); // expected-error {{const_cast from 'char const *volatile *const volatile *' to 'short ***' is not allowed}}
+  // Rvalue to reference.
+  char ***&var4 = const_cast<cpppr>(&var2); // expected-error {{const_cast from rvalue to reference type 'cpppr'}}
+  // Non-pointer.
+  char v = const_cast<char>(**var2); // expected-error {{const_cast to 'char', which is not a reference, pointer-to-object, or pointer-to-data-member}}
+  const int *ar[100] = {0};
+  // Not even lenient g++ accepts this.
+  int *(*rar)[100] = const_cast<int *(*)[100]>(&ar); // expected-error {{const_cast from 'int const *(*)[100]' to 'int *(*)[100]' is not allowed}}
+  f fp1 = 0;
+  // Function pointers.
+  f fp2 = const_cast<f>(fp1); // expected-error {{const_cast to 'f', which is not a reference, pointer-to-object, or pointer-to-data-member}}
+  return **var3;
+}
Index: include/clang/Basic/DiagnosticKinds.def
===================================================================
--- include/clang/Basic/DiagnosticKinds.def	(revision 57905)
+++ include/clang/Basic/DiagnosticKinds.def	(working copy)
@@ -1037,6 +1037,25 @@
      "initializer of a builtin type can only take one argument")
 DIAG(err_value_init_for_array_type, ERROR,
      "array types cannot be value-initialized")
+
+// C++ casts
+DIAG(err_bad_cxx_cast_generic, ERROR,
+     "%0 from '%2' to '%1' is not allowed")
+DIAG(err_bad_cxx_cast_rvalue, ERROR,
+     "%0 from rvalue to reference type '%1'")
+DIAG(err_bad_cxx_cast_const_away, ERROR,
+     "%0 from '%2' to '%1' casts away constness")
+DIAG(err_bad_const_cast_dest, ERROR,
+     "const_cast to '%0', which is not a reference, pointer-to-object, "
+     "or pointer-to-data-member")
+DIAG(err_bad_reinterpret_cast_same_type, ERROR,
+     "source and destination type of reinterpret_cast are not distinct")
+DIAG(ext_reinterpret_cast_fn_obj, EXTENSION,
+     "reinterpret_cast between pointer-to-function and pointer-to-object is "
+     "an extension")
+DIAG(err_bad_reinterpret_cast_small_int, ERROR,
+     "cast from pointer to smaller type '%0' loses information")
+
 DIAG(err_invalid_use_of_function_type, ERROR,
      "a function type is not allowed here")
 DIAG(err_invalid_use_of_array_type, ERROR,
Index: lib/Sema/SemaExprCXX.cpp
===================================================================
--- lib/Sema/SemaExprCXX.cpp	(revision 57905)
+++ lib/Sema/SemaExprCXX.cpp	(working copy)
@@ -27,22 +27,351 @@
                     SourceLocation LParenLoc, ExprTy *E,
                     SourceLocation RParenLoc) {
   CXXCastExpr::Opcode Op;
+  Expr *Ex = (Expr*)E;
+  QualType DestType = QualType::getFromOpaquePtr(Ty);
 
   switch (Kind) {
   default: assert(0 && "Unknown C++ cast!");
-  case tok::kw_const_cast:       Op = CXXCastExpr::ConstCast;       break;
-  case tok::kw_dynamic_cast:     Op = CXXCastExpr::DynamicCast;     break;
-  case tok::kw_reinterpret_cast: Op = CXXCastExpr::ReinterpretCast; break;
-  case tok::kw_static_cast:      Op = CXXCastExpr::StaticCast;      break;
+  case tok::kw_const_cast:
+    Op = CXXCastExpr::ConstCast;
+    CheckConstCast(OpLoc, Ex, DestType);
+    break;
+  case tok::kw_dynamic_cast:
+    Op = CXXCastExpr::DynamicCast;
+    break;
+  case tok::kw_reinterpret_cast:
+    Op = CXXCastExpr::ReinterpretCast;
+    CheckReinterpretCast(OpLoc, Ex, DestType);
+    break;
+  case tok::kw_static_cast:
+    Op = CXXCastExpr::StaticCast;
+    break;
   }
   
-  return new CXXCastExpr(Op, QualType::getFromOpaquePtr(Ty), (Expr*)E, OpLoc);
+  return new CXXCastExpr(Op, DestType, Ex, OpLoc);
 }
 
+/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
+/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
+/// like this:
+/// const char *str = "literal";
+/// legacy_function(const_cast\<char*\>(str));
+void
+Sema::CheckConstCast(SourceLocation OpLoc, Expr *&SrcExpr, QualType DestType)
+{
+  QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
+
+  DestType = Context.getCanonicalType(DestType);
+  QualType SrcType = SrcExpr->getType();
+  if (const ReferenceType *DestTypeTmp = DestType->getAsReferenceType()) {
+    if (SrcExpr->isLvalue(Context) != Expr::LV_Valid) {
+      // Cannot cast non-lvalue to reference type.
+      Diag(OpLoc, diag::err_bad_cxx_cast_rvalue,
+        "const_cast", OrigDestType.getAsString());
+      return;
+    }
+
+    // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
+    //   [...] if a pointer to T1 can be [cast] to the type pointer to T2.
+    DestType = Context.getPointerType(DestTypeTmp->getPointeeType());
+    if (const ReferenceType *SrcTypeTmp = SrcType->getAsReferenceType()) {
+      // FIXME: This shouldn't actually be possible, but right now it is.
+      SrcType = SrcTypeTmp->getPointeeType();
+    }
+    SrcType = Context.getPointerType(SrcType);
+  } else {
+    // C++ 5.2.11p1: Otherwise, the result is an rvalue and the
+    //   lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
+    //   conversions are performed on the expression.
+    DefaultFunctionArrayConversion(SrcExpr);
+    SrcType = SrcExpr->getType();
+  }
+
+  if (!DestType->isPointerType()) {
+    // Cannot cast to non-pointer, non-reference type. Note that, if DestType
+    // was a reference type, we converted it to a pointer above.
+    // C++ 5.2.11p3: For two pointer types [...]
+    Diag(OpLoc, diag::err_bad_const_cast_dest, OrigDestType.getAsString());
+    return;
+  }
+  if (DestType->isFunctionPointerType()) {
+    // Cannot cast direct function pointers.
+    // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
+    // T is the ultimate pointee of source and target type.
+    Diag(OpLoc, diag::err_bad_const_cast_dest, OrigDestType.getAsString());
+    return;
+  }
+  SrcType = Context.getCanonicalType(SrcType);
+
+  // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
+  // completely equal.
+  // FIXME: const_cast should probably not be able to convert between pointers
+  // to different address spaces.
+  // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
+  // in multi-level pointers may change, but the level count must be the same,
+  // as must be the final pointee type.
+  const PointerType *SrcTypeTmp, *DestTypeTmp;
+  while (SrcType != DestType &&
+    (SrcTypeTmp = SrcType->getAsPointerType()) &&
+    (DestTypeTmp = DestType->getAsPointerType()))
+  {
+    SrcType = SrcTypeTmp->getPointeeType().getUnqualifiedType();
+    DestType = DestTypeTmp->getPointeeType().getUnqualifiedType();
+  }
+
+  // Doug Gregor said to disallow this until users complain.
+#if 0
+  // If we end up with constant arrays of equal size, unwrap those too. A cast
+  // from const int [N] to int (&)[N] is invalid by my reading of the
+  // standard, but g++ accepts it even with -ansi -pedantic.
+  // No more than one level, though, so don't embed this in the unwrap loop
+  // above.
+  const ConstantArrayType *SrcTypeArr, *DestTypeArr;
+  if ((SrcTypeArr = Context.getAsConstantArrayType(SrcType)) &&
+     (DestTypeArr = Context.getAsConstantArrayType(DestType)))
+  {
+    if (SrcTypeArr->getSize() != DestTypeArr->getSize()) {
+      // Different array sizes.
+      Diag(OpLoc, diag::err_bad_cxx_cast_generic, "const_cast",
+        OrigDestType.getAsString(), OrigSrcType.getAsString());
+      return;
+    }
+    SrcType = SrcTypeArr->getElementType().getUnqualifiedType();
+    DestType = DestTypeArr->getElementType().getUnqualifiedType();
+  }
+#endif
+
+  // Since we're dealing in canonical types, the remainder must be the same.
+  if (SrcType != DestType) {
+    // Cast between unrelated types.
+    Diag(OpLoc, diag::err_bad_cxx_cast_generic, "const_cast",
+      OrigDestType.getAsString(), OrigSrcType.getAsString());
+    return;
+  }
+}
+
+/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
+/// valid.
+/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
+/// like this:
+/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
+void
+Sema::CheckReinterpretCast(SourceLocation OpLoc, Expr *&SrcExpr,
+                           QualType DestType)
+{
+  QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
+
+  DestType = Context.getCanonicalType(DestType);
+  QualType SrcType = SrcExpr->getType();
+  if (const ReferenceType *DestTypeTmp = DestType->getAsReferenceType()) {
+    if (SrcExpr->isLvalue(Context) != Expr::LV_Valid) {
+      // Cannot cast non-lvalue to reference type.
+      Diag(OpLoc, diag::err_bad_cxx_cast_rvalue,
+        "reinterpret_cast", OrigDestType.getAsString());
+      return;
+    }
+
+    // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
+    //   same effect as the conversion *reinterpret_cast<T*>(&x) with the
+    //   built-in & and * operators.
+    // This code does this transformation for the checked types.
+    DestType = Context.getPointerType(DestTypeTmp->getPointeeType());
+    if (const ReferenceType *SrcTypeTmp = SrcType->getAsReferenceType()) {
+      // FIXME: This shouldn't actually be possible, but right now it is.
+      SrcType = SrcTypeTmp->getPointeeType();
+    }
+    SrcType = Context.getPointerType(SrcType);
+  } else {
+    // C++ 5.2.10p1: [...] the lvalue-to-rvalue, array-to-pointer, and
+    //   function-to-pointer standard conversions are performed on the
+    //   expression v.
+    DefaultFunctionArrayConversion(SrcExpr);
+    SrcType = SrcExpr->getType();
+  }
+
+  // Canonicalize source for comparison.
+  SrcType = Context.getCanonicalType(SrcType);
+
+  bool destIsPtr = DestType->isPointerType();
+  bool srcIsPtr = SrcType->isPointerType();
+  if (!destIsPtr && !srcIsPtr) {
+    // Except for std::nullptr_t->integer, which is not supported yet, and
+    // lvalue->reference, which is handled above, at least one of the two
+    // arguments must be a pointer.
+    Diag(OpLoc, diag::err_bad_cxx_cast_generic, "reinterpret_cast",
+      OrigDestType.getAsString(), OrigSrcType.getAsString());
+    return;
+  }
+
+  if (SrcType == DestType) {
+    // C++ 5.2.10p2 has a note that mentions that, subject to all other
+    // restrictions, a cast to the same type is allowed. The intent is not
+    // entirely clear here, since all other paragraphs explicitly forbid casts
+    // to the same type. However, the behavior of compilers is pretty consistent
+    // on this point: allow same-type conversion if the involved are pointers,
+    // disallow otherwise.
+    return;
+  }
+
+  if (DestType->isIntegralType()) {
+    assert(srcIsPtr);
+    // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
+    //   type large enough to hold it.
+    if (Context.getTypeSize(SrcType) > Context.getTypeSize(DestType)) {
+      Diag(OpLoc, diag::err_bad_reinterpret_cast_small_int,
+        OrigDestType.getAsString());
+    }
+    return;
+  }
+
+  if (SrcType->isIntegralType() || SrcType->isEnumeralType()) {
+    assert(destIsPtr);
+    // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
+    //   converted to a pointer.
+    return;
+  }
+
+  if (!destIsPtr || !srcIsPtr) {
+    // With the valid non-pointer conversions out of the way, we can be even
+    // more stringent.
+    Diag(OpLoc, diag::err_bad_cxx_cast_generic, "reinterpret_cast",
+      OrigDestType.getAsString(), OrigSrcType.getAsString());
+    return;
+  }
+
+  // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
+  // Casting away constness is mainly defined in C++ 5.2.11p8. The incredibly
+  // complex description there essentially means: for the shared pointer levels,
+  // the cv qualification must be the same in both types, except for the
+  // outermost level, where the target cv may be greater than the source cv.
+
+  // Unwrap outermost level.
+  const PointerType *SrcTypeTmp = SrcType->getAsPointerType();
+  const PointerType *DestTypeTmp = DestType->getAsPointerType();
+  assert(SrcTypeTmp && DestTypeTmp);
+
+  SrcType = SrcTypeTmp->getPointeeType();
+  DestType = DestTypeTmp->getPointeeType();
+  // DestType may be more CVR-qualified than SrcType.
+  unsigned SrcQual = SrcType.getCVRQualifiers();
+  if ((SrcQual & DestType.getCVRQualifiers()) != SrcQual) {
+    Diag(OpLoc, diag::err_bad_cxx_cast_const_away, "reinterpret_cast",
+      OrigDestType.getAsString(), OrigSrcType.getAsString());
+    return;
+  }
+
+  bool deepPtr = false;
+
+  // Unwrap the pointers. Terminate early if the types are completely equal.
+  while (SrcType != DestType &&
+    (SrcTypeTmp = SrcType->getAsPointerType()) &&
+    (DestTypeTmp = DestType->getAsPointerType()))
+  {
+    deepPtr = true;
+    SrcType = SrcTypeTmp->getPointeeType();
+    DestType = DestTypeTmp->getPointeeType();
+    // Qualifiers must be identical at later levels.
+    if (SrcType.getCVRQualifiers() != DestType.getCVRQualifiers()) {
+      Diag(OpLoc, diag::err_bad_cxx_cast_const_away, "reinterpret_cast",
+        OrigDestType.getAsString(), OrigSrcType.getAsString());
+      return;
+    }
+  }
+
+  if (SrcType == DestType) {
+    // See above for the similar check.
+    return;
+  }
+
+  if(deepPtr) {
+    // If we unwrapped more than one level, we're not dealing with function or
+    // member pointers at the top level. This means we're done.
+    return;
+  }
+
+  // We have stripped away all indirections from at least one of the types.
+
+  // As for members, we don't have them yet.
+
+  if (SrcType->isObjectType() || SrcType->isVoidType()) {
+    if (DestType->isObjectType() || DestType->isVoidType()) {
+      // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
+      //   a pointer to an object of different type.
+      // Void pointers are not specified, but supported by G++.
+      return;
+    }
+    if (DestType->isFunctionType()) {
+      // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
+      //   an object type or vice versa is conditionally-supported.
+      // Compilers support it in C++03 too, though, because it's necessary for
+      // casting the return value of dlsym() and GetProcAddress().
+      if (!getLangOptions().CPlusPlus0x) {
+        Diag(OpLoc, diag::ext_reinterpret_cast_fn_obj);
+      }
+      return;
+    }
+  } else if (SrcType->isFunctionType()) {
+    if (DestType->isFunctionType()) {
+      // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
+      // a pointer to a function of a different type.
+      return;
+    }
+    if (DestType->isObjectType() || DestType->isVoidType()) {
+      // See above.
+      if (!getLangOptions().CPlusPlus0x) {
+        Diag(OpLoc, diag::ext_reinterpret_cast_fn_obj);
+      }
+      return;
+    }
+  }
+  // TODO: Add handling for member pointers when we have such a thing.
+
+  // We made it here. Whatever remains, it's got to be invalid.
+  Diag(OpLoc, diag::err_bad_cxx_cast_generic, "reinterpret_cast",
+    OrigDestType.getAsString(), OrigSrcType.getAsString());
+}
+
+/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
+/// 5.2.9/1 sets the ground rule of disallowing casting away constness.
+/// 5.2.9/2 permits everything allowed for direct-init, deferring to 8.5.
+///   Note: for class destination, that's overload resolution over dest's
+///   constructors. Src's conversions are only considered in overload choice.
+///   For any other destination, that's just the clause 4 standards convs.
+/// 5.2.9/4 permits static_cast&lt;cv void>(anything), which is a no-op.
+/// 5.2.9/5 permits explicit non-dynamic downcasts for lvalue-to-reference.
+/// 5.2.9/6 permits reversing all implicit conversions except lvalue-to-rvalue,
+///   function-to-pointer, array decay and to-bool, with some further
+///   restrictions. Defers to 4.
+/// 5.2.9/7 permits integer-to-enum conversion. Interesting note: if the integer
+///   does not correspond to an enum value, the result is unspecified - but it
+///   still has to be some value of the enum. I don't think any compiler
+///   complies with that.
+/// 5.2.9/8 is 5.2.9/5 for pointers.
+/// 5.2.9/9 messes with member pointers. TODO. No need to think about that yet.
+/// 5.2.9/10 permits void* to T*.
+void
+Sema::CheckStaticCast(SourceLocation OpLoc, Expr *&SrcExpr, QualType DestType)
+{
+#if 0
+  QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
+  DestType = Context.getCanonicalType(DestType);
+  // Tests are ordered by simplicity and a wild guess at commonness.
+
+  if (const BuiltinType *BuiltinDest = DestType->getAsBuiltinType()) {
+    // 5.2.9/4
+    if (BuiltinDest->getKind() == BuiltinType::Void) {
+      return;
+    }
+
+    // Primitive conversions for 5.2.9/2 and 6.
+  }
+#endif
+}
+
 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
 Action::ExprResult
 Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
-  assert((Kind != tok::kw_true || Kind != tok::kw_false) &&
+  assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
          "Unknown C++ Boolean value!");
   return new CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
 }
Index: lib/Sema/SemaExpr.cpp
===================================================================
--- lib/Sema/SemaExpr.cpp	(revision 57905)
+++ lib/Sema/SemaExpr.cpp	(working copy)
@@ -1730,7 +1730,7 @@
   // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
   // expressions that surpress this implicit conversion (&, sizeof).
   //
-  // Suppress this for references: C99 8.5.3p5.  FIXME: revisit when references
+  // Suppress this for references: C++ 8.5.3p5.  FIXME: revisit when references
   // are better understood.
   if (!lhsType->isReferenceType())
     DefaultFunctionArrayConversion(rExpr);
Index: lib/Sema/Sema.cpp
===================================================================
--- lib/Sema/Sema.cpp	(revision 57905)
+++ lib/Sema/Sema.cpp	(working copy)
@@ -181,6 +181,13 @@
   return true;
 }
 
+bool Sema::Diag(SourceLocation Loc, unsigned DiagID, const std::string &Msg1,
+                const std::string &Msg2, const std::string &Msg3) {
+  std::string MsgArr[] = { Msg1, Msg2, Msg3 };
+  PP.getDiagnostics().Report(PP.getFullLoc(Loc), DiagID,  MsgArr, 3);
+  return true;
+}
+
 bool Sema::Diag(SourceLocation Loc, unsigned DiagID, const SourceRange& Range) {
   PP.getDiagnostics().Report(PP.getFullLoc(Loc), DiagID, 0, 0, &Range,1);
   return true;
Index: lib/Sema/Sema.h
===================================================================
--- lib/Sema/Sema.h	(revision 57905)
+++ lib/Sema/Sema.h	(working copy)
@@ -229,6 +229,8 @@
   bool Diag(SourceLocation Loc, unsigned DiagID, const std::string &Msg);
   bool Diag(SourceLocation Loc, unsigned DiagID, const std::string &Msg1,
             const std::string &Msg2);
+  bool Diag(SourceLocation Loc, unsigned DiagId, const std::string &Msg1,
+            const std::string &Msg2, const std::string &Msg3);
 
   /// More expressive diagnostic helpers for expressions (say that 6 times:-)
   bool Diag(SourceLocation Loc, unsigned DiagID, const SourceRange& R1);
@@ -648,6 +650,12 @@
                                    SourceLocation LParenLoc, ExprTy *E,
                                    SourceLocation RParenLoc);
 
+  // Helpers for ActOnCXXCasts
+  void CheckConstCast(SourceLocation OpLoc, Expr *&SrcExpr, QualType DestType);
+  void CheckReinterpretCast(SourceLocation OpLoc, Expr *&SrcExpr,
+                            QualType DestType);
+  void CheckStaticCast(SourceLocation OpLoc, Expr *&SrcExpr, QualType DestType);
+
   //// ActOnCXXThis -  Parse 'this' pointer.
   virtual ExprResult ActOnCXXThis(SourceLocation ThisLoc);
 
