137 points · by jstanley · 4y ago · 62 comments
The tagged pointer type has the advantage of holding real pointers, meaning that any machine[0] that sticks extra information onto its pointers transparently just works. And reading the int half of the union to check if the pointer is valid should always be sound, but I'm not 100% sure on that. Architectures that don't enforce alignment are also probably not the sort of thing we care about running on, and I doubt there's a way for an optimizer to legally screw over programs that depend on pointer alignment being there on architectures where it has to be there.
But, then again, that's what we said about int-to-pointer casts...
[0] Real or virtual. Remember that when you compile your program with an optimizing compiler or JIT, it is executing on two architectures:
1. The compiler's expression/AST interpreter, which enforces ISO C undefined behavior rules
2. The target architecture, where those undefined behaviors become merely unspecified.
Note that there are some implementation-dependent factors here which I'm not getting into.
> And reading the int half of the union to check if the pointer is valid should always be sound, but I'm not 100% sure on that.
After various alias problems a while back (Linux kernel folks had some words), everyone got together and agreed that you can do type punning through a union... you just get the byte representation of one type, reinterpreted as the byte representation of another type. This was codified a few C standards ago and it's fairly explicit in the spec now.
I'll also just mention that you don't need an architecture than enforces alignment--you just need an allocator that returns aligned pointers.
(I'm going to ignore your use of the term "generally" to acknowledge that there are exceptions, because I want to elaborate on a particular exception that highlights an error in reasoning that I believe most programmers make when they manipulate memory addresses and then cast them straight to pointers.)
On CHERI, pure integer addressing can be turned off. In that case, pointers cannot necessarily be derived from integers alone. This is because CHERI implements pointer capabilities in hardware. You have to use special capability-preserving instructions to handle them, or else they permanently become invalid.
You can still manipulate memory addresses, but you generally cannot use them directly without them being part of a valid pointer. So it's valid to take a memory address, but invalid to try to use it directly.
I personally consider it unsound to try to transmute an integer into a pointer. It doesn't make sense, because [pointers are not necessarily memory addresses](https://www.ralfj.de/blog/2018/07/24/pointers-and-bytes.html). The Rust programming language is also considering taking this stance -- they already have a lint against treating pointers as integers, and with it an option to forbid it, though I'm unsure what the status on that is (it will probably remain optional forever).
This doesn't necessarily make it wrong or incorrect if the language allows for it, but I would advise not doing so, unless it's a domain-specific optimization (i.e. there is a fallback for architectures where it does not apply).
C [optionally] supports converting pointers to intptr_t (or uintptr_t), not to any integer type (even with nominally sufficient width), and certainly not to a floating point type, which is how NaN boxing works.
In CHERI intptr_t requires special treatment by the compiler. Plus, the nominal width of both pointers and intptr_t double in size--128-bits on 64-bit architectures. Most environments don't even have a 128-bit floating point type, even when the hardware might support it. (According to Wikipedia, Fortran is an exception, but it's still uncommon in C and other popular language environments.)
Yes it's optional, but it's "generally" supported.
> (even with nominally sufficient width)
C99 says: "Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behavior is undefined. The result need not be in the range of values of any integer type."
I'm not entirely sure how I'm supposed to parse that, but it sounds like if the result is in range of an integer then it's supposed to work?
I guess you could technically say all results have a zillion added to the actual value? Rules lawyering gets annoying pretty fast.
> and certainly not to a floating point type, which is how NaN boxing works
NaN boxing works by converting to an integer type first. What it does with the bits afterwards is not important to C, as long as it reconstructs the same integer before converting back.
I’m going to have to say that you’re definitely wrong about that, because when I read the C standard, it seems pretty clear to me. From N2176 (C17 draft) §6.3.2.3:
> An integer may be converted to any pointer type. Except as previously specified, the result is implementation-defined, might not be correctly aligned, might not point to an entity of the referenced type, and might be a trap representation.
> Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behavior is undefined. The result need not be in the range of values of any integer type.
As I said, there are some implementation-dependent factors here, but it should be clear that casting a pointer to and from an integer is OK, depending on the implementation, and depending on what integer type—and it’s not just limited to intptr types. The C standard guarantees that you can always cast to and from intptr_t / uintptr_t (if it exists), and other casts are implementation-defined. Relying on implementation-defined behavior is ok.
There’s nothing here that requires casting to float. You’re passing around a union which has both a float and a uint64_t in it.
It's worth noting that Rust is experimenting with making this not so free for one to do:
https://doc.rust-lang.org/std/ptr/index.html#pointer-usize-p...
So then, that is pretty much just a variation on pointer tagging. When the pointer has certain bits set in certain ways, it represents something else, including a full double.
To defend against undefined behaviors not going the way you want, you have tests. Programming language run-times are easily testable.
If your language's compiler compiles itself and a sizeable library, and all kinds of tests pass, it's unlikely that there is any hidden time bomb in value tagging scheme due to the undefined behavior of aliasing or pointer/integer conversion.
ISO C doesn't guarantee that if some line of code performing some undefined conversion has worked a million times, it will work for the million-and-first time. In practice, there is no reasonable translation scheme from C to machine code which would have that hostile behavior; it would have to be contrived with a hidden counter.
According to the spec in a system with 64-bit FP registers 32-bit floats are stored (in the registers) with the upper 32-bits as 0xffff_ffff - a NaN for 64-bit FP values (the same for systems with 128-bit floats) - this catches (some) code that mixes 32/64 bit floats without conversion
https://leonardschuetz.ch/blog/nan-boxing/
https://anniecherkaev.com/the-secret-life-of-nan
Is NaN-boxing actually used in the major browser JS engines?
JavaScriptCore uses a tweaked NaN-box [1]: values are stored via a NaN box minus a constant, which avoids requiring a mask when chasing pointers. This makes pointers cheaper but floating point operations more expensive.
SpiderMonkey and Hermes both use straight NaN-boxing to my knowledge.
https://github.com/WebKit/WebKit/blob/ec6b5337e777f9b460ec6b...
This, unfortunately, is an artificial limitation; negative nans may correspond to canonical addresses, but most oses won't let you map negative memory, keeping it all to themselves.
So assuming pointers are at most 49 bits you're fine.
How many people see the “let a” example as “the variable ‘a’ keeps changing shape/type” and how many see it as, “three different things were created and the variable ‘a’ kept getting reassigned to point at the newest one.”
Or is this not really a distinction people see?
Anyone finding things dead in the water like this has to use ./configure --no-nan-boxing.
Another issue I ran into is that when I tested with gcc 12.2 on a RISC-V machine, the double to integer conversion code threw a weird uninitialized warning, not just the warning about strict aliasing against the use of u in the second line:
ucnum u = coerce(ucnum, num) - NAN_FLNUM_DELTA;
return *coerce(double *, &u);
I added pragmas to suppress that. Anyway, everything built and tests passed on that installation.https://source.android.com/docs/security/test/tagged-pointer...
Android is tagging the top byte of a pointer to check for misuses, like a pointer into the stack being passed to free() and such.
I have successfully worked around it. The only pointers affected by this that we care about are Lisp heap objects. These are allocated in large block.
When we allocate a heap block, we clear the top 16 bits of the pointer, and save that value in heap->tag.
Then, if and when we free that heap block, instead of calling free(heap), we first mask back the heap->tag that we stripped away and free the resulting pointer.
Everything builds on a Pixel 4a; tests pass.
In spite of the rude language in that Android documentation, whereby some troglodytes disparage the work of their superiors, and give grave admonishments, it's possible to peacefully coexist.
https://www.kylheku.com/cgit/txr/commit/?id=073e4a84090b11fd...
I'm rolling out a release; it's going to be enabled by default on 64 bits by the build configure script. I tested on PPC, RISC-V, AArch64, X86-64 so far. I will do Loongarch64 and Mips64 also.
I developed my own "flavor" of NaN boxing, which gets us the maximum width of fixnum integers, and harmonizes with the pointer tagging scheme (which is still there, configurable at build time).
Some of the decisions made were to keep the code base common between the pointer tagging and NaN boxing. This arises in the arithmetic library code.
The representation is "pointer favoring"; so floating-point values are not represented as themselves; an offset has to be added to their integer image.
I chose the offset 0x0004 0000 0000 0000. What this means is that in the upper 16 bits, the values 0x0000, 0x0001, 0x0002 and 0x0003 can be used as tags for whatever purpose. We make the 0x0000 one denote pointers. Floating-point values start at 0x0004.
This fits perfectly into TXR Lisp which has two tag bits in the pointer tagging scheme: tags 0, 1, 2 and 3. We keep exactly the same tags.
When the upper 14 bits are all 1 (0xFFFC), which is the non-signaling NaN, the remaining 50 bits are a fixnum integer: the most we can have.
So we have 48 bit pointers, 50 bit integers, plus three addititional kinds of values that have 48 bits of room. Under the pointer tagging scheme, the three values are characters, integers and C string literals.
Since we otherwise represent integers under NaN, one of the tags, TAG_NUM (value 1) is not actually used. The function which returns a value's tag fakes out this TAG_NUM value when it detects a NaN-coded integer, which has no such tag.
This value must be returned because tons of code depends on it. There has to be compatibility between pointer tagging and NaN boxing not to have to rewrite a bunch of code in two ways.
fixnum-max is 562949953421311, which is still astronomically large. It can represent 5.6 trillion dollars, in integer cents. We could do the accounting of some large multi-nationals in fixnums.
We will never need an array index that cannot fit into this. (Proof: pointers are 48 bits under this scheme, so using positive integers, we can enumerate every nybble.)
We can seek 562 terabytes into a file, which doesn't seem too shabby.
There are situations in which having anything less than the full 64 bits in the integer hurts, like externally imposed bitfields and masks.
[1]: https://docs.microsoft.com/en-us/windows/win32/api/oaidl/ns-...
Congratulations, you have just ruined your software's forward c11y.
Those 16 bits aren't going to stay reserved forever.
Moreover, a single program could even take advantage of a "low heap" that stores metadata, and can have 48-bit pointers pointing to it, and a "high heap" of the actual large data (whose addresses take the full 64 bits, but may include tagged pointers to the low heap without doubling the memory footprint of the already humongous 256TB)
How long will it be until 256TB of RAM (which is what 48 bits will address) becomes even remotely common in a single system? Even 256GB, 1024x less, is not common today, except in huge servers.
How long will it take to change the implementation when/if it does?
I've seen far too much "future proofing" that makes the present worse, for a future that might never even happen.
In that case, we can NaN-box the quad float and have up to 112 bits of pointer space to play with. Lets assume we double the number of pointer bits to 96 - we can support YiBs of address space.
On a 32-bit system, it seems tagged pointers have the advantage:
nanb 18.562s - NaN boxing
nanb2 17.484s - tagged pointer
nanb3 25.468s - tagged structure
nanb3 with pack(1) 26.000s
nanb4 20.093s - tagged union
nanb4 with pack(1) 19.109s
I also tried with pack(1) to see if cache effects would show up, and although it made the tagged structure slightly slower, indeed you can see that the tagged union became faster without alignment padding.No, C does NOT allow that! C++ theoretically allows to reorder sections with different access specifiers (public, protected, private), but I don't think any compiler actually does this. It would just create a big mess for little gain.
I retrofitted NaN boxing into a production Lisp implementation literally in one evening and morning, with minimal impact to all the existing code in the implementation that is built around the pointer tagging scheme that existed for 13 years. It's nicely delimited with #if CONFIG_NAN_BOXING.
Accumulator-incrementing loop on pointer tagging:
This is the TXR Lisp interactive listener of TXR 281.
Quit with :quit or Ctrl-D on an empty line. Ctrl-X ? for cheatsheet.
1> (compile-toplevel '(for ((i 1.0) (acc 0.0)) ((< i 100000000.0) acc) ((inc acc i) (inc i))))
#<sys:vm-desc: 188b8d0>
2> (pprof [*1])
malloc bytes: 0
gc heap bytes: 6399999936
total: 6399999936
milliseconds: 5860
4.99999995e15
NaN Boxing: This is the TXR Lisp interactive listener of TXR 281.
Quit with :quit or Ctrl-D on an empty line. Ctrl-X ? for cheatsheet.
1> (compile-toplevel '(for ((i 1.0) (acc 0.0)) ((< i 100000000.0) acc) ((inc acc i) (inc i))))
#<sys:vm-desc: 24b7dc0>
2> (pprof [*1])
malloc bytes: 0
gc heap bytes: 0
total: 0
milliseconds: 4079
4.99999995e15
The speedup is 43.6% here. 3> (/ (- 5860 4079) 4079)
0.436626624172591
This is not native code. The difference would be more emphasized in native code.However, code that doesn't do floating-point calculation (or even some that does) will see a small performance penalty due to the more complex access to all values. That is a bummer.
At least users can choose; if you don't care about floating-point, build it with pointer tagging.