Create valid LValue to represent null pointers in constant exprs
authorTim Northover <tnorthover@apple.com>
Fri, 26 May 2017 02:16:00 +0000 (02:16 +0000)
committerTim Northover <tnorthover@apple.com>
Fri, 26 May 2017 02:16:00 +0000 (02:16 +0000)
We were leaving the SubobjectDesignator in a surprising situation, where
it was allegedly valid but didn't actually refer to a type. This caused
a crash later on.

This patch fills out the SubobjectDesignator with the pointee type (as
happens in other evaluations of constant pointers) so that we don't
crash later.

llvm-svn: 303957

clang/lib/AST/ExprConstant.cpp
clang/test/SemaCXX/null-cast.cpp [new file with mode: 0644]

index bd8b3ab..c19812e 100644 (file)
@@ -1230,8 +1230,7 @@ namespace {
       IsNullPtr = V.isNullPointer();
     }
 
-    void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false,
-             bool IsNullPtr_ = false, uint64_t Offset_ = 0) {
+    void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false) {
 #ifndef NDEBUG
       // We only allow a few types of invalid bases. Enforce that here.
       if (BInvalid) {
@@ -1242,11 +1241,20 @@ namespace {
 #endif
 
       Base = B;
-      Offset = CharUnits::fromQuantity(Offset_);
+      Offset = CharUnits::fromQuantity(0);
       InvalidBase = BInvalid;
       CallIndex = I;
       Designator = SubobjectDesignator(getType(B));
-      IsNullPtr = IsNullPtr_;
+      IsNullPtr = false;
+    }
+
+    void setNull(QualType PointerTy, uint64_t TargetVal) {
+      Base = (Expr *)nullptr;
+      Offset = CharUnits::fromQuantity(TargetVal);
+      InvalidBase = false;
+      CallIndex = 0;
+      Designator = SubobjectDesignator(PointerTy->getPointeeType());
+      IsNullPtr = true;
     }
 
     void setInvalid(APValue::LValueBase B, unsigned I = 0) {
@@ -5494,8 +5502,8 @@ public:
     return true;
   }
   bool ZeroInitialization(const Expr *E) {
-    auto Offset = Info.Ctx.getTargetNullPointerValue(E->getType());
-    Result.set((Expr*)nullptr, 0, false, true, Offset);
+    auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
+    Result.setNull(E->getType(), TargetVal);
     return true;
   }
 
diff --git a/clang/test/SemaCXX/null-cast.cpp b/clang/test/SemaCXX/null-cast.cpp
new file mode 100644 (file)
index 0000000..c80ab8f
--- /dev/null
@@ -0,0 +1,8 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+struct A {};
+struct B : virtual A {};
+
+void foo() {
+  (void)static_cast<A&>(*(B *)0); // expected-warning {{binding dereferenced null pointer to reference has undefined behavior}}
+}