]> granicus.if.org Git - clang/commitdiff
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.

git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@303957 91177308-0d34-0410-b5e6-96231b3b80d8

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

index bd8b3abd92758cc6c6986ef3405c49939e8330ee..c19812e341c03209eda05090661cc3f7d44c8fe4 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/test/SemaCXX/null-cast.cpp b/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}}
+}