llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

[clang][Serialization] PCH/AST writer emits an uninitialised Int64Result for value-dependent immediate invocations, making PCH output non-reproducible

Open RobL371 opened this issue 2 months ago • 2 comments

Full disclosure: this entry was written by an AI under my supervision. This occurred while trying to make our builds reproducible. I have personally verified the claims below.

Versions: clang 19.1.6 and 22.1.8 (x86_64 Linux). main has the same code.

Reproducer (a.h, two lines):

consteval int f(int x) { return x; }
template <int N> struct S { static constexpr int v = f(N); };
$ for p in 1 2; do MALLOC_PERTURB_=$p clang++ -std=c++20 -x c++-header -Xclang -emit-pch -o a$p.pch a.h; done
$ sha256sum a1.pch a2.pch      # differ
$ llvm-bcanalyzer -dump a1.pch | grep -m1 -o 'UnknownCode171.*op7=[-0-9]*'
UnknownCode171 op0=10 op1=104 op2=1 op3=0 op4=0 op5=0 op6=1 op7=-72340172838076674

171 is EXPR_CONSTANT in this build's ASTBitCodes.h. The operands are ResultKind=1 (Int64 storage), APValueKind=0 (none), BitWidth=0, IsImmediateInvocation=1, and op7 is glibc's fill byte (0xFEFEFEFEFEFEFEFE for MALLOC_PERTURB_=1, 0xFDFD… for =2): the trailing uint64_t was never written. op0=10 is Instantiation|Value-dependent.

Cause. Sema::CheckForImmediateInvocation (SemaExpr.cpp) creates the ConstantExpr with getStorageKind(Decl->getReturnType()), so an int-returning consteval call gets Int64 storage, and deliberately does not evaluate it when Res->isValueDependent() ("should not be immediately evaluated until they are instantiated"). ConstantExpr::ConstantExpr (Expr.cpp) does not initialise the trailing uint64_t. ASTStmtWriter::VisitConstantExpr (ASTWriterStmt.cpp) writes E->Int64Result() whenever the storage kind is Int64, without checking that a result was stored (APValueKind != None). The template pattern is serialised with the node, so every PCH containing a value-dependent immediate invocation carries uninitialised heap bytes.

Impact. Without MALLOC_PERTURB_ the bytes are usually zero, but not always: #include <chrono> alone (libstdc++ 14, hh_mm_ss<_Duration>:: fractional_width = {_S_fractional_width()}) produces PCHs that differ between plain back-to-back runs on the same machine, and an 80 MB production PCH differed in ~2,000 bytes (one operand's VBR width shifts every later offset). That defeats caching and reproducible-build checks of anything that uses PCHs with clang.

Fix. Two independent changes address it; either one alone makes the output deterministic. They are complementary, not alternatives that conflict: A removes the read of the never-written slot (the actual UB) and stops serialising a meaningless operand; B makes the slot deterministic at construction, which also protects every other consumer of Int64Result(). Applying both is reasonable. If only one is taken, A is the real fix and is what this report proposes; B is a one-line hardening. Both apply cleanly to release/22.x and main (the touched functions are identical there), individually and together.

Option A — serialise the result only when one was stored (writer + reader):

--- a/clang/lib/Serialization/ASTWriterStmt.cpp	2026-09-30 11:08:24.937375573 -0400
+++ b/clang/lib/Serialization/ASTWriterStmt.cpp	2026-09-30 11:08:56.835484469 -0400
@@ -658,15 +658,23 @@
   // HasCleanup not serialized since we can just query the APValue.
   Record.push_back(E->ConstantExprBits.IsImmediateInvocation);
 
-  switch (E->getResultStorageKind()) {
-  case ConstantResultStorageKind::None:
-    break;
-  case ConstantResultStorageKind::Int64:
-    Record.push_back(E->Int64Result());
-    break;
-  case ConstantResultStorageKind::APValue:
-    Record.AddAPValue(E->APValueResult());
-    break;
+  // The storage kind is chosen from the expression's type when the node is
+  // created, before any result exists, and a value-dependent immediate
+  // invocation in a template pattern never gets one (Sema defers its
+  // evaluation to instantiation). Only serialize the trailing storage when a
+  // result was actually stored; the Int64 slot is otherwise uninitialized
+  // memory. The reader keys off the same APValueKind field.
+  if (E->hasAPValueResult()) {
+    switch (E->getResultStorageKind()) {
+    case ConstantResultStorageKind::None:
+      break;
+    case ConstantResultStorageKind::Int64:
+      Record.push_back(E->Int64Result());
+      break;
+    case ConstantResultStorageKind::APValue:
+      Record.AddAPValue(E->APValueResult());
+      break;
+    }
   }
 
   Record.AddStmt(E->getSubExpr());
--- a/clang/lib/Serialization/ASTReaderStmt.cpp	2026-09-30 11:08:24.937995902 -0400
+++ b/clang/lib/Serialization/ASTReaderStmt.cpp	2026-09-30 11:08:56.835858917 -0400
@@ -568,21 +568,25 @@
   E->ConstantExprBits.HasCleanup = false; // Not serialized, see below.
   E->ConstantExprBits.IsImmediateInvocation = Record.readInt();
 
-  switch (StorageKind) {
-  case ConstantResultStorageKind::None:
-    break;
+  // The result storage is only present when a result was stored
+  // (APValueKind != None); see ASTStmtWriter::VisitConstantExpr.
+  if (E->hasAPValueResult()) {
+    switch (StorageKind) {
+    case ConstantResultStorageKind::None:
+      break;
 
-  case ConstantResultStorageKind::Int64:
-    E->Int64Result() = Record.readInt();
-    break;
+    case ConstantResultStorageKind::Int64:
+      E->Int64Result() = Record.readInt();
+      break;
 
-  case ConstantResultStorageKind::APValue:
-    E->APValueResult() = Record.readAPValue();
-    if (E->APValueResult().needsCleanup()) {
-      E->ConstantExprBits.HasCleanup = true;
-      Record.getContext().addDestruction(&E->APValueResult());
+    case ConstantResultStorageKind::APValue:
+      E->APValueResult() = Record.readAPValue();
+      if (E->APValueResult().needsCleanup()) {
+        E->ConstantExprBits.HasCleanup = true;
+        Record.getContext().addDestruction(&E->APValueResult());
+      }
+      break;
     }
-    break;
   }
 
   E->setSubExpr(Record.readSubExpr());

Option B — zero-initialise the tail-allocated slot in both constructors:

--- a/clang/lib/AST/Expr.cpp	2026-09-30 11:08:24.938868737 -0400
+++ b/clang/lib/AST/Expr.cpp	2026-09-30 11:08:56.836988685 -0400
@@ -331,6 +331,12 @@
 
   if (StorageKind == ConstantResultStorageKind::APValue)
     ::new (getTrailingObjects<APValue>()) APValue();
+  // The Int64 slot is tail-allocated from the ASTContext and otherwise left
+  // indeterminate. A node whose result is never set (a value-dependent
+  // immediate invocation) would carry those bytes into the AST writer, so
+  // start it at zero, as the APValue slot starts at None.
+  else if (StorageKind == ConstantResultStorageKind::Int64)
+    Int64Result() = 0;
 }
 
 ConstantExpr *ConstantExpr::Create(const ASTContext &Context, Expr *E,
@@ -361,6 +367,8 @@
 
   if (StorageKind == ConstantResultStorageKind::APValue)
     ::new (getTrailingObjects<APValue>()) APValue();
+  else if (StorageKind == ConstantResultStorageKind::Int64)
+    Int64Result() = 0;
 }
 
 ConstantExpr *ConstantExpr::CreateEmpty(const ASTContext &Context,

Note that A changes the on-disk record for these nodes (the operand is omitted), so a PCH written by a fixed compiler is not readable by an unfixed one and vice versa; that is already true of any clang version change and needs no version bump. B does not change the format.

Regression test (clang/test/PCH/consteval-value-dependent-deterministic.cpp): two independent emissions must be byte-identical, and the PCH must still be usable. The MALLOC_PERTURB_ runs make the defect visible on glibc without relying on allocator luck; on other platforms they degrade to plain repeats.

// RUN: rm -rf %t && mkdir -p %t
// RUN: env MALLOC_PERTURB_=1 %clang_cc1 -std=c++20 -x c++-header -emit-pch -fno-pch-timestamp -o %t/a1.pch %s
// RUN: env MALLOC_PERTURB_=2 %clang_cc1 -std=c++20 -x c++-header -emit-pch -fno-pch-timestamp -o %t/a2.pch %s
// RUN: cmp %t/a1.pch %t/a2.pch
// RUN: %clang_cc1 -std=c++20 -include-pch %t/a1.pch -fsyntax-only -verify -DUSE %s
// expected-no-diagnostics
#ifndef HEADER
#define HEADER
consteval int f(int x) { return x; }
// A value-dependent immediate invocation: Sema defers its evaluation to
// instantiation, so the ConstantExpr in the pattern never receives a result.
template <int N> struct S { static constexpr int v = f(N); };
template <int N> int g() { return f(N); }
#endif
#ifdef USE
static_assert(S<3>::v == 3);
int use() { return g<4>(); }
#endif

Related: #221998 (same writer defect, seen through nested consteval calls in a C++23 module; closed without a fix).

RobL371 avatar Sep 30 '26 15:09 RobL371

@llvm/issue-subscribers-clang-frontend

Author: RobL371

**Full disclosure: this entry was written by an AI under my supervision. This occurred while trying to make our builds reproducible. I have personally verified the claims below.**

Versions: clang 19.1.6 and 22.1.8 (x86_64 Linux). main has the same code.

Reproducer (a.h, two lines):

consteval int f(int x) { return x; }
template &lt;int N&gt; struct S { static constexpr int v = f(N); };
$ for p in 1 2; do MALLOC_PERTURB_=$p clang++ -std=c++20 -x c++-header -Xclang -emit-pch -o a$p.pch a.h; done
$ sha256sum a1.pch a2.pch      # differ
$ llvm-bcanalyzer -dump a1.pch | grep -m1 -o 'UnknownCode171.*op7=[-0-9]*'
UnknownCode171 op0=10 op1=104 op2=1 op3=0 op4=0 op5=0 op6=1 op7=-72340172838076674

171 is EXPR_CONSTANT in this build's ASTBitCodes.h. The operands are ResultKind=1 (Int64 storage), APValueKind=0 (none), BitWidth=0, IsImmediateInvocation=1, and op7 is glibc's fill byte (0xFEFEFEFEFEFEFEFE for MALLOC_PERTURB_=1, 0xFDFD… for =2): the trailing uint64_t was never written. op0=10 is Instantiation|Value-dependent.

Cause. Sema::CheckForImmediateInvocation (SemaExpr.cpp) creates the ConstantExpr with getStorageKind(Decl-&gt;getReturnType()), so an int-returning consteval call gets Int64 storage, and deliberately does not evaluate it when Res-&gt;isValueDependent() ("should not be immediately evaluated until they are instantiated"). ConstantExpr::ConstantExpr (Expr.cpp) does not initialise the trailing uint64_t. ASTStmtWriter::VisitConstantExpr (ASTWriterStmt.cpp) writes E-&gt;Int64Result() whenever the storage kind is Int64, without checking that a result was stored (APValueKind != None). The template pattern is serialised with the node, so every PCH containing a value-dependent immediate invocation carries uninitialised heap bytes.

Impact. Without MALLOC_PERTURB_ the bytes are usually zero, but not always: #include &lt;chrono&gt; alone (libstdc++ 14, hh_mm_ss&lt;_Duration&gt;:: fractional_width = {_S_fractional_width()}) produces PCHs that differ between plain back-to-back runs on the same machine, and an 80 MB production PCH differed in ~2,000 bytes (one operand's VBR width shifts every later offset). That defeats caching and reproducible-build checks of anything that uses PCHs with clang.

Fix. Two independent changes address it; either one alone makes the output deterministic. They are complementary, not alternatives that conflict: A removes the read of the never-written slot (the actual UB) and stops serialising a meaningless operand; B makes the slot deterministic at construction, which also protects every other consumer of Int64Result(). Applying both is reasonable. If only one is taken, A is the real fix and is what this report proposes; B is a one-line hardening. Both apply cleanly to release/22.x and main (the touched functions are identical there), individually and together.

Option A — serialise the result only when one was stored (writer + reader):

--- a/clang/lib/Serialization/ASTWriterStmt.cpp	2026-09-30 11:08:24.937375573 -0400
+++ b/clang/lib/Serialization/ASTWriterStmt.cpp	2026-09-30 11:08:56.835484469 -0400
@@ -658,15 +658,23 @@
   // HasCleanup not serialized since we can just query the APValue.
   Record.push_back(E-&gt;ConstantExprBits.IsImmediateInvocation);
 
-  switch (E-&gt;getResultStorageKind()) {
-  case ConstantResultStorageKind::None:
-    break;
-  case ConstantResultStorageKind::Int64:
-    Record.push_back(E-&gt;Int64Result());
-    break;
-  case ConstantResultStorageKind::APValue:
-    Record.AddAPValue(E-&gt;APValueResult());
-    break;
+  // The storage kind is chosen from the expression's type when the node is
+  // created, before any result exists, and a value-dependent immediate
+  // invocation in a template pattern never gets one (Sema defers its
+  // evaluation to instantiation). Only serialize the trailing storage when a
+  // result was actually stored; the Int64 slot is otherwise uninitialized
+  // memory. The reader keys off the same APValueKind field.
+  if (E-&gt;hasAPValueResult()) {
+    switch (E-&gt;getResultStorageKind()) {
+    case ConstantResultStorageKind::None:
+      break;
+    case ConstantResultStorageKind::Int64:
+      Record.push_back(E-&gt;Int64Result());
+      break;
+    case ConstantResultStorageKind::APValue:
+      Record.AddAPValue(E-&gt;APValueResult());
+      break;
+    }
   }
 
   Record.AddStmt(E-&gt;getSubExpr());
--- a/clang/lib/Serialization/ASTReaderStmt.cpp	2026-09-30 11:08:24.937995902 -0400
+++ b/clang/lib/Serialization/ASTReaderStmt.cpp	2026-09-30 11:08:56.835858917 -0400
@@ -568,21 +568,25 @@
   E-&gt;ConstantExprBits.HasCleanup = false; // Not serialized, see below.
   E-&gt;ConstantExprBits.IsImmediateInvocation = Record.readInt();
 
-  switch (StorageKind) {
-  case ConstantResultStorageKind::None:
-    break;
+  // The result storage is only present when a result was stored
+  // (APValueKind != None); see ASTStmtWriter::VisitConstantExpr.
+  if (E-&gt;hasAPValueResult()) {
+    switch (StorageKind) {
+    case ConstantResultStorageKind::None:
+      break;
 
-  case ConstantResultStorageKind::Int64:
-    E-&gt;Int64Result() = Record.readInt();
-    break;
+    case ConstantResultStorageKind::Int64:
+      E-&gt;Int64Result() = Record.readInt();
+      break;
 
-  case ConstantResultStorageKind::APValue:
-    E-&gt;APValueResult() = Record.readAPValue();
-    if (E-&gt;APValueResult().needsCleanup()) {
-      E-&gt;ConstantExprBits.HasCleanup = true;
-      Record.getContext().addDestruction(&amp;E-&gt;APValueResult());
+    case ConstantResultStorageKind::APValue:
+      E-&gt;APValueResult() = Record.readAPValue();
+      if (E-&gt;APValueResult().needsCleanup()) {
+        E-&gt;ConstantExprBits.HasCleanup = true;
+        Record.getContext().addDestruction(&amp;E-&gt;APValueResult());
+      }
+      break;
     }
-    break;
   }
 
   E-&gt;setSubExpr(Record.readSubExpr());

Option B — zero-initialise the tail-allocated slot in both constructors:

--- a/clang/lib/AST/Expr.cpp	2026-09-30 11:08:24.938868737 -0400
+++ b/clang/lib/AST/Expr.cpp	2026-09-30 11:08:56.836988685 -0400
@@ -331,6 +331,12 @@
 
   if (StorageKind == ConstantResultStorageKind::APValue)
     ::new (getTrailingObjects&lt;APValue&gt;()) APValue();
+  // The Int64 slot is tail-allocated from the ASTContext and otherwise left
+  // indeterminate. A node whose result is never set (a value-dependent
+  // immediate invocation) would carry those bytes into the AST writer, so
+  // start it at zero, as the APValue slot starts at None.
+  else if (StorageKind == ConstantResultStorageKind::Int64)
+    Int64Result() = 0;
 }
 
 ConstantExpr *ConstantExpr::Create(const ASTContext &amp;Context, Expr *E,
@@ -361,6 +367,8 @@
 
   if (StorageKind == ConstantResultStorageKind::APValue)
     ::new (getTrailingObjects&lt;APValue&gt;()) APValue();
+  else if (StorageKind == ConstantResultStorageKind::Int64)
+    Int64Result() = 0;
 }
 
 ConstantExpr *ConstantExpr::CreateEmpty(const ASTContext &amp;Context,

Note that A changes the on-disk record for these nodes (the operand is omitted), so a PCH written by a fixed compiler is not readable by an unfixed one and vice versa; that is already true of any clang version change and needs no version bump. B does not change the format.

Regression test (clang/test/PCH/consteval-value-dependent-deterministic.cpp): two independent emissions must be byte-identical, and the PCH must still be usable. The MALLOC_PERTURB_ runs make the defect visible on glibc without relying on allocator luck; on other platforms they degrade to plain repeats.

// RUN: rm -rf %t &amp;&amp; mkdir -p %t
// RUN: env MALLOC_PERTURB_=1 %clang_cc1 -std=c++20 -x c++-header -emit-pch -fno-pch-timestamp -o %t/a1.pch %s
// RUN: env MALLOC_PERTURB_=2 %clang_cc1 -std=c++20 -x c++-header -emit-pch -fno-pch-timestamp -o %t/a2.pch %s
// RUN: cmp %t/a1.pch %t/a2.pch
// RUN: %clang_cc1 -std=c++20 -include-pch %t/a1.pch -fsyntax-only -verify -DUSE %s
// expected-no-diagnostics
#ifndef HEADER
#define HEADER
consteval int f(int x) { return x; }
// A value-dependent immediate invocation: Sema defers its evaluation to
// instantiation, so the ConstantExpr in the pattern never receives a result.
template &lt;int N&gt; struct S { static constexpr int v = f(N); };
template &lt;int N&gt; int g() { return f(N); }
#endif
#ifdef USE
static_assert(S&lt;3&gt;::v == 3);
int use() { return g&lt;4&gt;(); }
#endif

Related: #221998 (same writer defect, seen through nested consteval calls in a C++23 module; closed without a fix).

I also hit this same issue and fixed locally for my case with just the second hunk of the option B. Same root cause but a module repro too.

export module m;
consteval int f(int n) { return n; }
template <int N> int g() {
  int s = 0;
  s += f(N); s += f(N); s += f(N); s += f(N);
  s += f(N); s += f(N); s += f(N); s += f(N);
  return s;
}

zngos avatar Nov 02 '26 12:11 zngos