Skip to content

ECMA-335 augment: bool values must be exactly 0 or 1 #138234

Todo

Description

@EgorBo

Proposal

Add a section to docs/design/specs/Ecma-335-Augments.md stating that a CLI bool is either 0 (false) or 1 (true). Any other bit pattern is an invalid Boolean value. Consuming one gives unspecified results, but memory safety must still hold.

This matches what Roslyn, the BCL, the VM and the documentation already assume today. The only place that still holds the ECMA "any non-zero is true" rule is the JIT, and it pays for that with missed optimizations.

What ECMA-335 says today

§III.1.1.2 Boolean data type (PDF p.319):

A CLI Boolean type occupies 1 byte in memory. A bit pattern of all zeroes denotes a value of false. A bit pattern with any one or more bits set (analogous to a non-zero integer) denotes a value of true.

Partition IV, System.Boolean:

the representation of false is all-bits-zero, and the representation of true is unspecified except that it shall have at least one bit set.

The spec contradicts this rule in several places:

  • §II.23.3 (custom attribute blobs): "A bool is a single byte with value 0 (false) or 1 (true)".
  • §I.8.2.5.1 (identity): two value-type values are identical "if and only if the bit sequences of the values are the same". So a true stored as 1 and a true stored as 2 are both true but not identical.
  • ceq/cgt/clt always push exactly 0 or 1.

Reality: everything above the JIT already assumes 0/1

Roslyn

Documented in Boolean Representation.md:

The C# and VB compilers represent true and false with the single byte values 1 and 0, respectively, and assume that any boolean values that they are working with are restricted to being represented by these two underlying values. [...] it is the programmer's responsibility to normalize such incoming values.

Codegen follows from that:

C# IL
x == y ceq
x & y and
x && y (simple right operand, also in Debug and in branch position) and
x == true x
switch (b) { case true: } ldc.i4.1; beq

BCL

  • Boolean.Equals is m_value == obj, a raw byte compare. Boolean.CompareTo is not antisymmetric for non-0/1 values. GetHashCode normalizes.
  • RuntimeHelpers.IsBitwiseEquatable<bool>() is true on CoreCLR (jitinterface.cpp), NativeAOT/crossgen2 (RuntimeHelpersIntrinsics.cs) and Mono. As a result every vectorized IndexOf/Contains/SequenceEqual/Count compares bytes.
  • ValueType.Equals/GetHashCode use the memcmp fast path for structs with bool fields. Only R4/R8 fields are excluded (comutilnative.cpp, NativeAOT ComparerIntrinsics.cs).
  • Interlocked.CompareExchange<bool> and Interlocked.And<bool> do byte arithmetic.

Docs

  • Unsafe code best practices say "anything other than 0 or 1 likely leads to unreliable behavior".
  • The System.Boolean API docs say "A value of 1 represents true; a value of 0 represents false".

Non-normalized bools are already broken today

A bool holding byte 2 prints True and takes the if (b) branch, but it is not equal to true. In practice the runtime has 255 distinct values of true.

static bool Mk(byte v) => Unsafe.BitCast<byte, bool>(v);

static void Main() {
    bool one = Mk(1), two = Mk(2); // both "true" per ECMA
    Console.WriteLine(one == two);                                       // False
    Console.WriteLine(one.Equals(two));                                  // False
    Console.WriteLine(EqualityComparer<bool>.Default.Equals(one, two));  // False
    Console.WriteLine(one && two);                                       // False (Roslyn emits `and`)
    Console.WriteLine(one & two);                                        // False
    Console.WriteLine($"{two.CompareTo(true)} {true.CompareTo(two)}");   // 1 1
    Console.WriteLine(Array.IndexOf(new[] { false, two }, true));        // -1
    Console.WriteLine(new[] { false, two }.AsSpan().IndexOf(true));      // -1
    Console.WriteLine(new HashSet<bool> { one }.Contains(two));          // False
    Console.WriteLine(new HashSet<bool> { true, two, false }.Count);     // 3
    Console.WriteLine(new SortedSet<bool> { true, two, false }.Count);   // 3
    Console.WriteLine(new S { B = one }.Equals(new S { B = two }));      // False (memcmp fast path)
    bool loc = two;
    Interlocked.And(ref loc, true);
    Console.WriteLine(loc);                                              // False
}
struct S { public bool B; }

More observed results with the same setup:

  • Array.Sort(new bool[] { 2, 1, 0, 2, 1, 0, 1, 2 }) (written as raw bytes) produces [0, 0, 2, 1, 2, 1, 1, 2], which is not sorted.
  • span.Count(true) + span.Count(false) != span.Length.
  • Dictionary<bool, T> can hold both true and 2 as separate keys.

Every output above was identical across these configurations:

  • FullOpts (TieredCompilation=0) and MinOpts
  • R2R on and off
  • the CoreCLR interpreter
  • x64 and arm64 codegen

So these results don't depend on tiering or on any JIT optimization. They follow directly from the IL Roslyn emits and from how the BCL and VM implement equality.

Supported ways to get a non-0/1 bool (no Unsafe at the use site)

  • [assembly: DisableRuntimeMarshalling]: P/Invokes, delegate* unmanaged, [UnmanagedCallersOnly] and blittable structs with bool fields pass the native byte through as-is. This is documented (Compatibility.md), and the test PInvokeAssemblyMarshallingDisabled/PInvokes.cs NoBooleanNormalization asserts it. Native code returning a Windows BOOLEAN or flags & 4 as uint8_t is common.
  • Raw byte copies: Buffer.BlockCopy from byte[] to bool[], MemoryMarshal.Cast/Read<bool>, MemoryMappedViewAccessor.Read<bool>, and ArrayPool<bool> arrays reused after byte-level writes.
  • Reflection: custom attribute instances get the raw blob byte, while CustomAttributeData normalizes the same byte. The two APIs disagree for blob value 2.
  • IL: any stind.i1/stfld bool of an int is a truncating store. The spec's own example in §II.14.5 stores not(false) (0xFF) into a bool field.

When runtime marshalling is enabled, the built-in marshallers (VM, NativeAOT, LibraryImport generator) all normalize to 0/1.

Cost of the current wording

The JIT is the only component that follows ECMA here, and that has cost both correctness bugs and performance.

Prior discussion

Proposed augment text

Boolean representation

Section "III.1.1.2 Boolean data type" is replaced with: A CLI Boolean type occupies 1 byte in memory. The bit pattern 0x00 denotes false and the bit pattern 0x01 denotes true. All other bit patterns are invalid Boolean values. The result of any operation that consumes an invalid Boolean value (including branches, comparisons, conversions and calls) is unspecified, but it shall not compromise memory safety or type safety. For the purpose of stack operations boolean values are treated as unsigned 1-byte integers (§III.1.1.1).

In Partition IV, the representation of true for System.Boolean is changed to the value 1.

The example in section "II.14.5 Method pointers" is changed to use ldc.i4.1; xor instead of not to toggle the Boolean field.

Native data type bool in II.7.4 (4-byte Win32 BOOL) is unaffected. Marshalling from native Boolean representations to a CLI bool is expected to normalize to 0/1 when runtime marshalling is enabled.

Open questions

  • Should DisableRuntimeMarshalling (and [UnmanagedCallersOnly]/delegate* unmanaged<bool>) start normalizing, or stay documented as "the caller must pass 0/1"?
  • Metadata readers: keep accepting 0xFF in constant and attribute blobs, since some writers emit it (BlobReader.cs)?

Activity

  1. added
    untriaged
    on Nov 24, 2026
  2. added
    area-CodeGen-coreclr
    on Nov 24, 2026
  3. EgorBo commented on Nov 24, 2026

    @EgorBo
    MemberAuthor

    cc @jkotas @dotnet/jit-contrib

  4. dotnet-policy-service commented on Nov 24, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @JulieLeeMSFT, @jakobbotsch
    See info in area-owners.md if you want to be subscribed.

  5. jkotas commented on Nov 24, 2026

    @jkotas
    Member

    Managed C++ says hello...

  6. EgorBo commented on Nov 24, 2026

    @EgorBo
    MemberAuthor

    Managed C++ says hello...

    I guess my point is - we either fix all the places (APIs, VM) where we assume it's 0/1 only or change the spec, it seems like Managed C++ technically faces with bugs then.

  7. jkotas commented on Nov 24, 2026

    @jkotas
    Member

    it seems like Managed C++ technically faces with bugs then.

    Not necessarily. For interop with C#, managed C++ just needs to ensure that they do not return or store de-normalized bool values where C# can see them. The codegen can use de-normalized bool values internally any way it wants without impacting C# interop.

  8. EgorBo commented on Nov 24, 2026

    @EgorBo
    MemberAuthor

    it seems like Managed C++ technically faces with bugs then.

    Not necessarily. For interop with C#, managed C++ just needs to ensure that they do not return or store de-normalized bool values where C# can see them. The codegen can use de-normalized bool values internally any way it wants without impacting C# interop.

    @jkotas btw, lack of managed C++ on non-Windows allows us to make the 0/1 assumption in jit?

  9. hamarb123 commented on Nov 24, 2026

    @hamarb123
    Contributor

    Could we also add a new compilation relaxation bit, or similar attribute/flag (this one would be free ito dll size tho iirc), and get roslyn to emit it for C# (either based on the bit definiton or some runtime feature field presence), which would allow all C# code to benefit (the majority case), while allowing us to keep the behaviour in IL and C++/CLI and other langs that might rely on it as-is (unless they choose to opt-in via this mechanism)?

    Edit: this would be similar to exception wrapping; and would also be similar to us interpreting lack of [UnscopedRef] as non-escaping based on the c# ref safety rules version on the dll; and is also similar to the disable marshalling attribute too (but ofc this is not automatically emitted by roslyn); so the idea has some precendent.

  10. tannergooding commented on Nov 24, 2026

    @tannergooding
    Member

    You can still have other languages that expect or deal with bools that are values other than 0/1.

    As it is today, other languages and interop in general is free to handle and normalize their "non-standard" bools as they see fit. If you start enforcing that it can only be 0/1 then they have no recourse to fix things themselves.

    I'm extremely skeptical that this would provide meaningful benefit, particularly compared to other considerations like IPA and simply tracking that a bool was never produced by something that could've been different.

    Devs who already know or expect it to be normalized can even get it converted for zero-cost using Unsafe.BitCast already (it just emits the movzx eax, al that a byte would do), so if it is truly some perf critical edge case you have options.

  11. am11 commented on Nov 25, 2026

    @am11
    Member

    @EgorBo, for if-conversion, #135757 normalizes it in value numbing to exactly 0 or 1 then rest of the phases can fold stuff with confidence.

  12. removed
    untriaged
    on Nov 25, 2026
  13. added this to the 12.0.0 milestone on Nov 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area-CodeGen-coreclr

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions