[clang] [clang][bytecode] Fix bitcasting from null pointers (PR #116999)

via cfe-commits cfe-commits at lists.llvm.org
Wed Nov 20 08:16:31 PST 2024


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-clang

Author: Timm Baeder (tbaederr)

<details>
<summary>Changes</summary>

This looks a little ugly now, I should wait for #<!-- -->116843.

---
Full diff: https://github.com/llvm/llvm-project/pull/116999.diff


2 Files Affected:

- (modified) clang/lib/AST/ByteCode/InterpBuiltinBitCast.cpp (+12-2) 
- (modified) clang/test/AST/ByteCode/builtin-bit-cast.cpp (+2) 


``````````diff
diff --git a/clang/lib/AST/ByteCode/InterpBuiltinBitCast.cpp b/clang/lib/AST/ByteCode/InterpBuiltinBitCast.cpp
index 7e8853d3469317..a5de8c3f6dcae3 100644
--- a/clang/lib/AST/ByteCode/InterpBuiltinBitCast.cpp
+++ b/clang/lib/AST/ByteCode/InterpBuiltinBitCast.cpp
@@ -299,6 +299,9 @@ static bool readPointerToBuffer(const Context &Ctx, const Pointer &FromPtr,
                    llvm::sys::IsLittleEndianHost);
   bool BigEndianTarget = ASTCtx.getTargetInfo().isBigEndian();
 
+  uint64_t PointerSizeInBits =
+      ASTCtx.getTargetInfo().getPointerWidth(LangAS::Default);
+
   return enumeratePointerFields(
       FromPtr, Ctx,
       [&](const Pointer &P, PrimType T, size_t BitOffset,
@@ -310,8 +313,15 @@ static bool readPointerToBuffer(const Context &Ctx, const Pointer &FromPtr,
 
         assert(P.isInitialized());
         // nullptr_t is a PT_Ptr for us, but it's still not std::is_pointer_v.
-        if (T == PT_Ptr)
-          assert(false && "Implement casting to pointer types");
+        if (T == PT_Ptr) {
+          assert(P.getType()->isNullPtrType());
+          std::byte Zeroes[] = {std::byte{0}, std::byte{0}, std::byte{0},
+                                std::byte{0}, std::byte{0}, std::byte{0},
+                                std::byte{0}, std::byte{0}};
+          assert(PointerSizeInBits <= (8 * 8));
+          Buffer.pushData(Zeroes, PointerSizeInBits, BigEndianTarget);
+          return true;
+        }
 
         CharUnits ObjectReprChars = ASTCtx.getTypeSizeInChars(P.getType());
         unsigned BitWidth = ASTCtx.toBits(ObjectReprChars);
diff --git a/clang/test/AST/ByteCode/builtin-bit-cast.cpp b/clang/test/AST/ByteCode/builtin-bit-cast.cpp
index 60e8c3a615c5e6..fbaff4ba226d58 100644
--- a/clang/test/AST/ByteCode/builtin-bit-cast.cpp
+++ b/clang/test/AST/ByteCode/builtin-bit-cast.cpp
@@ -135,6 +135,8 @@ namespace simple {
   /// diagnoses it.
   static_assert(__builtin_bit_cast(intptr_t, nullptr) == 0); // ref-error {{not an integral constant expression}} \
                                                              // ref-note {{indeterminate value can only initialize an object}}
+
+  constexpr int test_from_nullptr_pass = (__builtin_bit_cast(unsigned char[8], nullptr), 0);
 }
 
 namespace Fail {

``````````

</details>


https://github.com/llvm/llvm-project/pull/116999


More information about the cfe-commits mailing list