You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Recently we had a few discussions on how to support C++ volatile. Some discussion thread started in this CL (the CL itself was not terribly relevant though; the discussions went in the comments below) and the CG meeting on July 24. While the discussion in the CG meeting was very informative, the topic is not directly relevant with the wasm spec itself, so maybe this repo is a better place for future discussions.
Summary of discussions so far:
LLVM's -fms-volatile option turns volatiles into atomics, and this option is the default for MSVC, so there is a precedent for turning volatiles into atomic operations by default in LLVM.
asm.js fastcomp also currently converts volatiles to atomics.
@jfbastien suggested we should be user friendly by converting volatiles into atomics. For larger sizes not supported naturally by wasm, we can even tear them, because volatiles can tear. If we turn volatile load/stores into regular load stores, the volatile's guarantee that every byte should be touched only once per instruction is not satisfied anymore.
Some people expressed concerns that by converting volatiles into sequentially consistent atomics, we are making it too strong, and if we support relaxed memory models in future, code that used to work might break.
@sunfishcode suggested we'd better be consistent with other targets, and people who what to use that feature should turn on the option.
I'm not suggesting -fms-volatile, just pointing out the precedent! In particular, I think the transformation from volatile in LLVM IR to seq_cst which tear when not lock-free should occur when lowering to WebAssembly (i.e. the LLVM optimizer sees volatile).
I'm not suggesting -fms-volatile, just pointing out the precedent!
Sorry for the inaccuracies. Fixed them.
In particular, I think the transformation from volatile in LLVM IR to seq_cst which tear when not lock-free should occur when lowering to WebAssembly (i.e. the LLVM optimizer sees volatile).
Do you mean by non-atomic volatiles by 'not lock-free'?
Also, is the reason you think we should do it late is to distinguish volatiles from atomics, I think?
store volatile i32 should become a single atomic store because it's guaranteed to be lock-free on WebAssembly.
store volatile i128 (or anything which isn't guaranteed lock-free on WebAssembly) should become as many atomic stores as are required so that each sub atomic store is lock-free.
-fms-volatile does turn out to be a little more subtle than just "translate volatile to atomic", so it may not be the best solution here. On the other hand, it already exists, and might be close enough for practical purposes, so it's worth considering.
My main concern is, if we've decided that users using volatile aren't intending to ask for strict volatile semantics, giving them strict volatile semantics as long as we can through the optimizer seems unhelpful. It seems better to add atomic in the frontend, if that's what we think is needed.
This is in part because compiler writers are being encouraged to optimize atomics. We can't just look at what one optimizer does today; we need to consider that more optimizations might be added in target-independent code in the future, and possibly what other optimizers might do. The most straightforward approach seems to be to describe whatever we decide the desired semantics are, from the frontend.
Atomic and volatile are two completly unrelated concepts. Volatile is for things like memory mapped IO pins on uCs and such stuff, it only means that all reads and writes to it must really be performed, but nothing else. Atomic only means that reading and writing to a variable always result in a consistent state, and nothing else. One doesn't imply the other, they can't replace the other one. Treating volatile as atomic makes no sense to me. And optimizing volatile would be completly crazy, it's a devs way of telling the compiler it can't know what will happen if it uses it, so the compiler can't make any assumptions for volatile variables, and thus can't optimize them. And if some devs use the wrong one in their code, then the code is just wrong and should be fixed, but even then there is already an option to work arround that.
My main concern is, if we've decided that users using volatile aren't intending to ask for strict volatile semantics, giving them strict volatile semantics as long as we can through the optimizer seems unhelpful. It seems better to add atomic in the frontend, if that's what we think is needed.
This is in the context of pre-existing code migrating to WebAssembly. In that context the code already has volatile semantics from the compiler, and what we're trying to do is to preserve some of the ordering guarantees such that the VM's optimizer doesn't mess things up. With that double context, I don't see why adding atomic in the frontend is better. Can you explain?
This is in part because compiler writers are being encouraged to optimize atomics.
Guilty :-)
It's worth noting that these optimizations are valid for atomic, but often not for volatile (exception in limited circumstances). Transforming volatile to pure atomic, say in the clang frontend, would lose some semantics which I believe are important.
It's also important to notice that the optimizations allowed on WebAssembly's own atomics are vastly different from those allowed in C++.
@Daniel-Abrecht We are aware of that, but mostly in old code some people have used volatiles for similar purposes, so we are discussing what to do considering user-friendliness. Comments in this CL has details how this discussion started.
One of the differences between volatile and atomic in the spec is that volatile does not, by itself, communicate between threads. To make the kind of code under discussion here work, we'd need to interpret volatile in source code as a construct that does.
Let's say we decide to do that. LLVM IR hasn't been a party to this decision though, so if we leave it as plain volatile in LLVM IR, the optimizer will interpret it that to mean it doesn't communicate between threads. An optimization that reasons about the places where communication between threads could occur could break our code (without even "optimizing volatile" per se, but rather by reasoning about where atomics etc. do and don't occur).
Consider the reason why the -fms-volatile flag itself was added to clang. If a traditional treatment of volatile was sufficient to let legacy code survive the optimizer, why was this flag needed? It's that the optimizer is reasoning about atomics and volatiles today, in ways that actually matter, including to the very kind of legacy code that this whole conversation is about.
I'm making a very different point: we're considering x86 code which mistakenly uses volatile for a variety of reasons. That code Happens To Work™, in LLVM, today. LLVM, in these circumstances, applies its usual volatile optimizations and the x86 goes TSO on it. Now the developer wants to transition to WebAssembly. The LLVM optimizations were and still are semantics preserving (in the sense that the broken program semantics are nonetheless preserved). The problem is in LLVM IR → WebAssembly translation: we have 3 choices.
Refuse all volatile inputs.
Transform to non-atomic.
Transform to seq_cst atomic.
Here's how I value each option and why:
Is user hostile. I'm working on deprecating much of volatile in C++ itself, and WebAssembly is absolutely the wrong place to start preaching. Compilers should be doing that job, and only when users are ready for it (i.e. upgrade to C++20 and get a deprecation warning, upgrade to C++23 and get compile error, all the while tooling helps you upgrade).
Is invalid because the WebAssembly optimizer lost information, and code is now optimizable in a manner which doesn't preserve the (broken!) program semantics anymore. WebAssembly doesn't need to come in and be a pedant about it because it has a clear and simple way to be nice. Again, this isn't the time and place to snark at users. Remember that atomic didn't exist in C++ before C++11, pthread wasn't perfect and definitely wasn't available everywhere.
Is the only choice we have.
Consider the reason why the -fms-volatile flag itself was added to clang. If a traditional treatment of volatile was sufficient to let legacy code survive the optimizer, why was this flag needed? It's that the optimizer is reasoning about atomics and volatiles today, in ways that actually matter, including to the very kind of legacy code that this whole conversation is about.
No, it was added to clang to match the precise behavior of MSVC, because broken code which targeted Windows assumed that behavior, and clang decided to be nice to those mistaken users and grant them the same behavior. If these users want to target WebAssembly they should use -fms-volatile, but that's a separate discussion from what we should do as the default for all other developers.
I applaud C++ standards-level work to fix volatile, and agree that it's not something we should try to do through wasm.
The problem is in LLVM IR → WebAssembly translation
As far as I'm aware, the actual problem here is that there is C++ code which people wish to port to wasm, and it sometimes doesn't work. We aren't constrained to solve it in any particular place in the toolchain, as long as we solve the actual problem.
Is invalid because the WebAssembly optimizer lost information, and code is now optimizable in a manner which doesn't preserve the (broken!) program semantics anymore.
The only standard that applies is the C++ standard, where volatile doesn't imply communication. What's valid is for the optimizer or wasm engine to break the kinds of programs we're discussing. But we're looking at our options outside the scope of the standard (without breaking programs that do follow the rules), so I don't rule out 2. here.
No, it was added to clang to match the precise behavior of MSVC, because broken code which targeted Windows assumed that behavior, and clang decided to be nice to those mistaken users and grant them the same behavior.
Take another look:
code developed on some existing platform
uses volatile to communicate between threads, works as intended on existing platform
mostly works on new platform, but has some problems related to volatile
compiler writers decide to modify the compiler to help
Other than subtle details, this is the same situation. Eerily similar. It's so similar, that -fms-volatile is practically the solution already, with the only apparent questions being whether it's worth adding a whole new option to do the same thing with minor differences, and whether it should be on by default.
I grant that -fms-volatile may not be precisely what we might want, but I also observe that the general approach of addressing this issue in the front-end is more robust, easier to explain to users, easier to implement consistently in case other compilers want to do the same thing, more manageable in the case of LTO between libraries where some are legacy code and some are not, and it's the place where other clang developers have already fixed practically the same problem in a different context.
Even though it doesn't make the same guarantees about ordering, the standard does say that volatile operations should not be optimized out, that implementations cannot change the number of operations on a volatile object. Hoisting them out of a loop clearly violates that rule.
The unusual thing here is that currently the only way to observe that violation in existing embeddings is with another thread.
The C and C++ standards don't define volatile in terms of optimizations, and you can get away with a lot under the as-if clause. LLVM does, though it only discusses IR-level optimization and backends, and doesn't say anything about the ISA. And in fact, some physical platforms do reorder accesses which were originally marked volatile. What wasm engines are doing here isn't fundamentally different from a cache hierarchy that doesn't propagate stores between cores without explicit synchronization.
To be sure, I'm not opposed to supporting C code like this. What I'm saying is, the robust way is to translate volatile as atomic, in the frontend. And in fact, clang already has code to do this, in -fms-volatile. So the main question is how best to present this for users.
The C and C++ standards don't define volatile in terms of optimizations
That's incorrect.
K&R:
The purpose of volatile is to force an implementation to suppress optimization that could otherwise occur. For example, for a machine with memory-mapped input/output, a pointer to a device register might be declared as a pointer to volatile, in order to prevent the compiler from removing apparently redundant references through the pointer.
D&E C++:
To match ANSI C, the volatile modifier was introduced to help optimizer implementers.
C++17 Standard, [dcl.type.cv]:
The semantics of an access through a volatile glvalue are implementation-defined. If an attempt is made to access an object defined with a volatile-qualified type through the use of a non-volatile glvalue, the behavior is undefined.
[ Note: volatile is a hint to the implementation to avoid aggressive optimization involving the object because the value of the object might be changed by means undetectable by an implementation. Furthermore, for some implementations, volatile might indicate that special hardware instructions are required to access the object. See [intro.execution] for detailed semantics. In general, the semantics of volatile are intended to be the same in C++ as they are in C. —end note]
C17 Standard:
A volatile declaration may be used to describe an object corresponding to a memory-mapped input/output port or an object accessed by an asynchronously interrupting function. Actions on objects so declared shall not be "optimized out" by an implementation or reordered except as permitted by the rules for evaluating expressions.
You cannot get away with much under the as-if rule when it comes to volatile. I've explained why transforming volatile to atomic in the frontend isn't sufficient. At a minimum you should do volatile atomic. I've also explained why that's a bad idea.
I honestly don't understand what you're trying to drive to. The approach I propose is eminently simple and I believe entirely correct, which also being nice to developers. I'd like to understand why you don't like it. It seems from the discussion above that we're not talking about the same volatile?
Those C and C++ quotes that talk about optimization are non-normative notes. And the K&R quote is in what K&R calls "commentary material", which is roughly K&R's version of non-normative notes. And the D&E quote above doesn't say much. In short, they all want memory-mapped I/O to work, but none of these documents has the vocabulary to describe what that means in normative text.
In wasm, there is no memory-mapped I/O (and signals and setjmp are another matter). An external observer couldn't reliably tell the difference between i32.load ...; drop and drop under any circumstances (assuming the load doesn't trap). The C++ standard doesn't say "you have to do a load on the machine" anywhere, even though compiler writers often think that way. It just says that whatever side effects are supposed to happen on the platform do happen. So if there are no side effects on the platform, there's no need for a literal load instruction to occur.
This is an aggressive and potentially surprising interpretation, though it's still conforming. Fortunately there's a place where we can be "nice to developers", and it's in the frontend, because:
This ensures that whatever semantics we decide that we need are consistently preserved through the entire optimization pipeline, even in the event of a compiler upgrade with new optimizations. Or the user tweaks their code and it inlines differently and different optimizations apply. Or a library changes. And so on.
Being friendly only in the backend comes with the risk that code could come to depend on it, which could put an awkward burden on us, the maintainers, when we want to release new versions, if anything has changed in the front-end or middle-end which breaks the code.
Non-C/C++ front-end writers producing LLVM IR can be reasonably expected to follow standards better than legacy C/C++ code, particularly when it comes to rules as simple and well-known in today's era as "don't use volatile for threads".
-fms-volatile is already a thing in clang, and (to the level of detail we're discussing at this point), it's already exactly what we need here. The code is already there, it already works on wasm, we just need to decide what the UI should be
-fms-volatile is also an indication that other people, faced with the same problem, also decided that the right place to solve the problem is in the front-end.
If we want to handle corner cases like bitfields, enums, various struct cases, and so on, and explain the rules to end users, we'll need the frontend, because we won't always know what these are in LLVM IR.
Semantics consisting of "volatile through the optimizer, and atomic after that" are pretty tricky to reason about, and could be awkward to implement precisely in another C compiler wishing to be compatible with wasm.
Wasm is not the only platform where volatile isn't sufficient for threads (even if the consequences are sometimes different, the basic problem is the same), so it's good to look for solutions which we can share with other backends. -fms-volatile works for all backends.
So this is eminently simple, I believe entirely correct, and nice to developers. And it's easier for us to maintain. And it's more robust. And it's easier to explain to end users. And it's how other people have solved this problem. And we can in fact share the code with them.
I don't think you're understand standards well enough if your interpretation of non-normative notes and design rationale is "they're non-normative," however confusing this may be. Standards aren't perfect gems which are entirely correct, and the committee is well aware of how poorly worded volatile is.
This ensures that whatever semantics we decide that we need are consistently preserved through the entire optimization pipeline, even in the event of a compiler upgrade with new optimizations. Or the user tweaks their code and it inlines differently and different optimizations apply. Or a library changes. And so on.
Transforming volatile to atomic in the frontend does not do what you describe here. Further, doing this in the frontend needlessly creates a weird platform divergence.
Being friendly only in the backend comes with the risk that code could come to depend on it, which could put an awkward burden on us, the maintainers, when we want to release new versions, if anything has changed in the front-end or middle-end which breaks the code.
The same applies to changes in the frontend with one difference: if what I propose breaks then it does so for all platforms, whereas with your proposal it only does so for WebAssembly.
*Non-C/C++ front-end writers producing LLVM IR can be reasonably expected to follow standards better than legacy C/C++ code, particularly when it comes to rules as simple and well-known in today's era as "don't use volatile for threads".
I don't think we're talking about languages other than C and C++. I suggest starting a separate thread for those.
-fms-volatile is already a thing in clang, and (to the level of detail we're discussing at this point), it's already exactly what we need here. The code is already there, it already works on wasm, we just need to decide what the UI should be
As I've explained, it's not exactly what we need. Users can opt-in to it, but it doesn't have the right semantics.
-fms-volatile is also an indication that other people, faced with the same problem, also decided that the right place to solve the problem is in the front-end.
Your understanding of how this flag came to be is historically inaccurate. This flag exists to match MSVC's x86 behavior. MSVC's x86 behavior exists because people who implemented MSVC had a mistaken understanding of what volatile meant (from a time when that mistaken understanding was common), they now regard it as a mistake they're stuck with. Thankfully for them that "mistake" isn't very costly on x86. It is on ARM, which is why MSVC has different behavior for volatile when targeting ARM.
If we want to handle corner cases like bitfields, enums, various struct cases, and so on, and explain the rules to end users, we'll need the frontend, because we won't always know what these are in LLVM IR.
This isn't WebAssembly's fight. I'm going to fix the languages (C and C++) and teach the frontend to do the right thing for all platforms.
Semantics consisting of "volatile through the optimizer, and atomic after that" are pretty tricky to reason about, and could be awkward to implement precisely in another C compiler wishing to be compatible with wasm.
Other C compilers can make their own choices, and if they go down the same route then they'll offer the same volatile semantics as with their own non-WebAssembly target. Developers aren't porting code from LLVM-wasm to GCC-wasm, they're porting code from LLVM-x86 or LLVM-arm to LLVM-wasm.
Let's get back to what I asked earlier:
I honestly don't understand what you're trying to drive to. The approach I propose is eminently simple and I believe entirely correct, which also being nice to developers. I'd like to understand why you don't like it. It seems from the discussion above that we're not talking about the same volatile?
I still don't understand what you think is flawed with the approach I propose. I've systematically explained why what you propose is flawed, often I've made the exact same point and they don't seem to get through. I don't think we're talking about the same thing, and we're going in circles. This is very unproductive.
I used confusing language in some of my earlier posts. When I talked about "translating volatile to atomic", I should have said "translationg volatile to volatile atomic". This preserves the volatileness as long as possible, and it is what -fms-volatile does.
JF's standards proposal about volatile is now published. It doesn't appear to deprecate or clarify any aspects of volatile discussed in this issue.
I have spoken with other C++ committee members who agreed that my interpretation of volatile and the footnotes quoted above are within the intent of the standard.
I still find the following solution best:
By default, have the wasm backend ignore volatile qualifiers, as it does now.
If needed, enable the -fms-volatile flag for use on wasm targets.
I have spoken with other C++ committee members who agreed that my interpretation of volatile and the footnotes quoted above are within the intent of the standard.
Who have you spoken to? Very few people in the committee actually understand volatile. If you're going to appeal to authority, I'd like to know which authority and how authoritative it is.
What is your interpretation of volatile that they agree with? Forgive me, but this thread is long and needs summarizing.
Which are the "footnotes quoted above" which "are within the intent of the standard"? Your earlier argument was that footnotes didn't matter because they're non-normative.
I don't think you're looking for feedback here, is that correct?
Who have you spoken to? Very few people in the committee actually understand volatile. If you're going to appeal to authority, I'd like to know which authority and how authoritative it is.
Ok, I appeal to Richard Smith, editor of the C++ standard, who I caught up with several months ago and asked about this topic.
What is your interpretation of volatile that they agree with? Forgive me, but this thread is long and needs summarizing.
It's conforming to lower C++ volatile accesses into regular non-atomic accesses at the wasm level.
Which are the "footnotes quoted above" which "are within the intent of the standard"? Your earlier argument was that footnotes didn't matter because they're non-normative.
I mean these footnotes. And yes, these notes provide guidance to avoid "optimization", not requirements. This reflects how many C++ implementations work, but isn't how volatile is defined.
I don't think you're looking for feedback here, is that correct?
Some of the difficulty in the earlier discussion may have been due to my mistake of describing -fms-volatile as "translate volatile to atomic" instead of "translate volatile to volatile atomic". I'm correcting that now, so perhaps we can proceed to discuss -fms-volatile as part of the overall strategy here.
I propose that -fms-volatile is the best way to support legacy C++ code which uses volatile to communicate between threads (short of changing the code). In particular, it's better than translating volatile to atomic in the wasm backend, because (a) there's precedent for it -- -fms-volatile already exists (b) it's easier to explain to users what -fms-volatile does, in terms of their own code rather than compiler internals, and (c) if atomic is actually what's needed, we should use it throughout the optimizer, not just in the backend. A downside is that this solution doesn't automatically help non-C/C++ frontends, however I think it's acceptable to just ask such frontends to fix the problem on their end.
If we agree on that, we can then discuss whether to enable -fms-volatile by default on wasm. I propose we don't, because that would make us different from other targets, because code might come to implicitly depend on it, and because it might exacerbate confusion among users about what volatile really implies. I even see this as being aligned with the spirit of "Deprecating Volatile" -- we can't get rid of volatile entirely, but we can reduce its scope to just the things that really need it.
Something we haven't talked about (I think?) is adding a diagnostic in clang, only when compiling for a wasm target, to the effect that volatile doesn't have the semantics developers expect on a wasm VM. IIUC a big part of your worry is exactly this: volatile really doesn't have semantics, but people mistakenly use it (either because they wrote the code before C++11 atomic, or because they don't know better e.g. coming from Java).
The trick here would be to only apply the diagnostic when generating volatile memory accesses: there are "valid" C++ type system uses for volatile when going silly generic programming (to change overload preference).
With a diagnostic (call it -Wvolatile for now) it seems like it's pretty much impossible to inadvertently rely on behavior, and we can suggest using -Wno-volatileor-fms-volatile as a solution to the diagnostic. Enabling either would squelch the warning.
I think that meets what you outline? And it also nudges code bases towards a more correct / current usage of the language.
Activity
[-]Volatile support[/-][+]C++ volatile support[/+]aheejin commentedon Aug 6, 2018
@dschuff @conrad-watt
jfbastien commentedon Aug 6, 2018
I'm not suggesting
-fms-volatile, just pointing out the precedent! In particular, I think the transformation fromvolatilein LLVM IR to seq_cst which tear when not lock-free should occur when lowering to WebAssembly (i.e. the LLVM optimizer seesvolatile).aheejin commentedon Aug 7, 2018
@jfbastien
Sorry for the inaccuracies. Fixed them.
Do you mean by non-atomic volatiles by 'not lock-free'?
Also, is the reason you think we should do it late is to distinguish volatiles from atomics, I think?
jfbastien commentedon Aug 7, 2018
I mean:
store volatile i32should become a single atomic store because it's guaranteed to be lock-free on WebAssembly.store volatile i128(or anything which isn't guaranteed lock-free on WebAssembly) should become as many atomic stores as are required so that each sub atomic store is lock-free.aheejin commentedon Aug 7, 2018
@jfbastien Thanks for the clarification!
@sunfishcode Do you have any concerns or suggestions so far?
sunfishcode commentedon Aug 8, 2018
-fms-volatile does turn out to be a little more subtle than just "translate volatile to atomic", so it may not be the best solution here. On the other hand, it already exists, and might be close enough for practical purposes, so it's worth considering.
My main concern is, if we've decided that users using volatile aren't intending to ask for strict volatile semantics, giving them strict volatile semantics as long as we can through the optimizer seems unhelpful. It seems better to add atomic in the frontend, if that's what we think is needed.
This is in part because compiler writers are being encouraged to optimize atomics. We can't just look at what one optimizer does today; we need to consider that more optimizations might be added in target-independent code in the future, and possibly what other optimizers might do. The most straightforward approach seems to be to describe whatever we decide the desired semantics are, from the frontend.
Daniel-Abrecht commentedon Aug 8, 2018
Atomic and volatile are two completly unrelated concepts. Volatile is for things like memory mapped IO pins on uCs and such stuff, it only means that all reads and writes to it must really be performed, but nothing else. Atomic only means that reading and writing to a variable always result in a consistent state, and nothing else. One doesn't imply the other, they can't replace the other one. Treating volatile as atomic makes no sense to me. And optimizing volatile would be completly crazy, it's a devs way of telling the compiler it can't know what will happen if it uses it, so the compiler can't make any assumptions for volatile variables, and thus can't optimize them. And if some devs use the wrong one in their code, then the code is just wrong and should be fixed, but even then there is already an option to work arround that.
jfbastien commentedon Aug 8, 2018
@Daniel-Abrecht I think you're missing much of the context for this discussion.
jfbastien commentedon Aug 8, 2018
@sunfishcode
This is in the context of pre-existing code migrating to WebAssembly. In that context the code already has volatile semantics from the compiler, and what we're trying to do is to preserve some of the ordering guarantees such that the VM's optimizer doesn't mess things up. With that double context, I don't see why adding atomic in the frontend is better. Can you explain?
Guilty :-)
It's worth noting that these optimizations are valid for atomic, but often not for volatile (exception in limited circumstances). Transforming volatile to pure atomic, say in the clang frontend, would lose some semantics which I believe are important.
It's also important to notice that the optimizations allowed on WebAssembly's own atomics are vastly different from those allowed in C++.
aheejin commentedon Aug 8, 2018
@Daniel-Abrecht We are aware of that, but mostly in old code some people have used volatiles for similar purposes, so we are discussing what to do considering user-friendliness. Comments in this CL has details how this discussion started.
sunfishcode commentedon Aug 9, 2018
One of the differences between volatile and atomic in the spec is that volatile does not, by itself, communicate between threads. To make the kind of code under discussion here work, we'd need to interpret volatile in source code as a construct that does.
Let's say we decide to do that. LLVM IR hasn't been a party to this decision though, so if we leave it as plain
volatilein LLVM IR, the optimizer will interpret it that to mean it doesn't communicate between threads. An optimization that reasons about the places where communication between threads could occur could break our code (without even "optimizing volatile" per se, but rather by reasoning about where atomics etc. do and don't occur).Consider the reason why the -fms-volatile flag itself was added to clang. If a traditional treatment of volatile was sufficient to let legacy code survive the optimizer, why was this flag needed? It's that the optimizer is reasoning about atomics and volatiles today, in ways that actually matter, including to the very kind of legacy code that this whole conversation is about.
jfbastien commentedon Aug 9, 2018
I'm making a very different point: we're considering x86 code which mistakenly uses volatile for a variety of reasons. That code Happens To Work™, in LLVM, today. LLVM, in these circumstances, applies its usual
volatileoptimizations and the x86 goes TSO on it. Now the developer wants to transition to WebAssembly. The LLVM optimizations were and still are semantics preserving (in the sense that the broken program semantics are nonetheless preserved). The problem is in LLVM IR → WebAssembly translation: we have 3 choices.volatileinputs.seq_cstatomic.Here's how I value each option and why:
volatilein C++ itself, and WebAssembly is absolutely the wrong place to start preaching. Compilers should be doing that job, and only when users are ready for it (i.e. upgrade to C++20 and get a deprecation warning, upgrade to C++23 and get compile error, all the while tooling helps you upgrade).No, it was added to clang to match the precise behavior of MSVC, because broken code which targeted Windows assumed that behavior, and clang decided to be nice to those mistaken users and grant them the same behavior. If these users want to target WebAssembly they should use
-fms-volatile, but that's a separate discussion from what we should do as the default for all other developers.sunfishcode commentedon Aug 9, 2018
I applaud C++ standards-level work to fix volatile, and agree that it's not something we should try to do through wasm.
As far as I'm aware, the actual problem here is that there is C++ code which people wish to port to wasm, and it sometimes doesn't work. We aren't constrained to solve it in any particular place in the toolchain, as long as we solve the actual problem.
The only standard that applies is the C++ standard, where volatile doesn't imply communication. What's valid is for the optimizer or wasm engine to break the kinds of programs we're discussing. But we're looking at our options outside the scope of the standard (without breaking programs that do follow the rules), so I don't rule out 2. here.
Take another look:
Other than subtle details, this is the same situation. Eerily similar. It's so similar, that -fms-volatile is practically the solution already, with the only apparent questions being whether it's worth adding a whole new option to do the same thing with minor differences, and whether it should be on by default.
I grant that -fms-volatile may not be precisely what we might want, but I also observe that the general approach of addressing this issue in the front-end is more robust, easier to explain to users, easier to implement consistently in case other compilers want to do the same thing, more manageable in the case of LTO between libraries where some are legacy code and some are not, and it's the place where other clang developers have already fixed practically the same problem in a different context.
aheejin commentedon Aug 10, 2018
@jfbastien What was the broken semantics that MSVC programmers used and how it is different from the kind of legacy program we are trying to support?
7 remaining items
dschuff commentedon Aug 23, 2018
Even though it doesn't make the same guarantees about ordering, the standard does say that volatile operations should not be optimized out, that implementations cannot change the number of operations on a volatile object. Hoisting them out of a loop clearly violates that rule.
The unusual thing here is that currently the only way to observe that violation in existing embeddings is with another thread.
sunfishcode commentedon Aug 23, 2018
The C and C++ standards don't define volatile in terms of optimizations, and you can get away with a lot under the as-if clause. LLVM does, though it only discusses IR-level optimization and backends, and doesn't say anything about the ISA. And in fact, some physical platforms do reorder accesses which were originally marked volatile. What wasm engines are doing here isn't fundamentally different from a cache hierarchy that doesn't propagate stores between cores without explicit synchronization.
To be sure, I'm not opposed to supporting C code like this. What I'm saying is, the robust way is to translate volatile as atomic, in the frontend. And in fact, clang already has code to do this, in -fms-volatile. So the main question is how best to present this for users.
jfbastien commentedon Aug 23, 2018
That's incorrect.
K&R:
D&E C++:
C++17 Standard, [dcl.type.cv]:
C17 Standard:
You cannot get away with much under the as-if rule when it comes to
volatile. I've explained why transforming volatile to atomic in the frontend isn't sufficient. At a minimum you should do volatile atomic. I've also explained why that's a bad idea.I honestly don't understand what you're trying to drive to. The approach I propose is eminently simple and I believe entirely correct, which also being nice to developers. I'd like to understand why you don't like it. It seems from the discussion above that we're not talking about the same volatile?
sunfishcode commentedon Aug 24, 2018
Those C and C++ quotes that talk about optimization are non-normative notes. And the K&R quote is in what K&R calls "commentary material", which is roughly K&R's version of non-normative notes. And the D&E quote above doesn't say much. In short, they all want memory-mapped I/O to work, but none of these documents has the vocabulary to describe what that means in normative text.
In wasm, there is no memory-mapped I/O (and signals and setjmp are another matter). An external observer couldn't reliably tell the difference between
i32.load ...; dropanddropunder any circumstances (assuming the load doesn't trap). The C++ standard doesn't say "you have to do a load on the machine" anywhere, even though compiler writers often think that way. It just says that whatever side effects are supposed to happen on the platform do happen. So if there are no side effects on the platform, there's no need for a literalloadinstruction to occur.This is an aggressive and potentially surprising interpretation, though it's still conforming. Fortunately there's a place where we can be "nice to developers", and it's in the frontend, because:
So this is eminently simple, I believe entirely correct, and nice to developers. And it's easier for us to maintain. And it's more robust. And it's easier to explain to end users. And it's how other people have solved this problem. And we can in fact share the code with them.
jfbastien commentedon Aug 24, 2018
I don't think you're understand standards well enough if your interpretation of non-normative notes and design rationale is "they're non-normative," however confusing this may be. Standards aren't perfect gems which are entirely correct, and the committee is well aware of how poorly worded volatile is.
Transforming volatile to atomic in the frontend does not do what you describe here. Further, doing this in the frontend needlessly creates a weird platform divergence.
The same applies to changes in the frontend with one difference: if what I propose breaks then it does so for all platforms, whereas with your proposal it only does so for WebAssembly.
I don't think we're talking about languages other than C and C++. I suggest starting a separate thread for those.
As I've explained, it's not exactly what we need. Users can opt-in to it, but it doesn't have the right semantics.
Your understanding of how this flag came to be is historically inaccurate. This flag exists to match MSVC's x86 behavior. MSVC's x86 behavior exists because people who implemented MSVC had a mistaken understanding of what volatile meant (from a time when that mistaken understanding was common), they now regard it as a mistake they're stuck with. Thankfully for them that "mistake" isn't very costly on x86. It is on ARM, which is why MSVC has different behavior for volatile when targeting ARM.
This isn't WebAssembly's fight. I'm going to fix the languages (C and C++) and teach the frontend to do the right thing for all platforms.
Other C compilers can make their own choices, and if they go down the same route then they'll offer the same volatile semantics as with their own non-WebAssembly target. Developers aren't porting code from LLVM-wasm to GCC-wasm, they're porting code from LLVM-x86 or LLVM-arm to LLVM-wasm.
Let's get back to what I asked earlier:
I still don't understand what you think is flawed with the approach I propose. I've systematically explained why what you propose is flawed, often I've made the exact same point and they don't seem to get through. I don't think we're talking about the same thing, and we're going in circles. This is very unproductive.
sunfishcode commentedon Aug 24, 2018
If you've stated, anywhere in this thread, why -fms-volatile isn't the semantics we want here, I can't find it.
jfbastien commentedon Aug 24, 2018
#60 (comment)
sunfishcode commentedon Aug 24, 2018
-fms-volatile transforms volatile to volatile atomic.
sunfishcode commentedon Jun 16, 2019
Here's an update on the current status:
I used confusing language in some of my earlier posts. When I talked about "translating volatile to atomic", I should have said "translationg volatile to volatile atomic". This preserves the volatileness as long as possible, and it is what -fms-volatile does.
JF's standards proposal about
volatileis now published. It doesn't appear to deprecate or clarify any aspects ofvolatilediscussed in this issue.I have spoken with other C++ committee members who agreed that my interpretation of
volatileand the footnotes quoted above are within the intent of the standard.I still find the following solution best:
jfbastien commentedon Jun 17, 2019
volatile. If you're going to appeal to authority, I'd like to know which authority and how authoritative it is.volatilethat they agree with? Forgive me, but this thread is long and needs summarizing.I don't think you're looking for feedback here, is that correct?
sunfishcode commentedon Jun 18, 2019
Ok, I appeal to Richard Smith, editor of the C++ standard, who I caught up with several months ago and asked about this topic.
It's conforming to lower C++ volatile accesses into regular non-atomic accesses at the wasm level.
I mean these footnotes. And yes, these notes provide guidance to avoid "optimization", not requirements. This reflects how many C++ implementations work, but isn't how volatile is defined.
Some of the difficulty in the earlier discussion may have been due to my mistake of describing -fms-volatile as "translate volatile to atomic" instead of "translate volatile to volatile atomic". I'm correcting that now, so perhaps we can proceed to discuss -fms-volatile as part of the overall strategy here.
I propose that -fms-volatile is the best way to support legacy C++ code which uses volatile to communicate between threads (short of changing the code). In particular, it's better than translating volatile to atomic in the wasm backend, because (a) there's precedent for it -- -fms-volatile already exists (b) it's easier to explain to users what -fms-volatile does, in terms of their own code rather than compiler internals, and (c) if atomic is actually what's needed, we should use it throughout the optimizer, not just in the backend. A downside is that this solution doesn't automatically help non-C/C++ frontends, however I think it's acceptable to just ask such frontends to fix the problem on their end.
If we agree on that, we can then discuss whether to enable -fms-volatile by default on wasm. I propose we don't, because that would make us different from other targets, because code might come to implicitly depend on it, and because it might exacerbate confusion among users about what volatile really implies. I even see this as being aligned with the spirit of "Deprecating Volatile" -- we can't get rid of volatile entirely, but we can reduce its scope to just the things that really need it.
jfbastien commentedon Jun 18, 2019
OK I think I now understand your update, thanks!
Something we haven't talked about (I think?) is adding a diagnostic in clang, only when compiling for a wasm target, to the effect that
volatiledoesn't have the semantics developers expect on a wasm VM. IIUC a big part of your worry is exactly this:volatilereally doesn't have semantics, but people mistakenly use it (either because they wrote the code before C++11 atomic, or because they don't know better e.g. coming from Java).The trick here would be to only apply the diagnostic when generating
volatilememory accesses: there are "valid" C++ type system uses forvolatilewhen going silly generic programming (to change overload preference).With a diagnostic (call it
-Wvolatilefor now) it seems like it's pretty much impossible to inadvertently rely on behavior, and we can suggest using-Wno-volatileor-fms-volatileas a solution to the diagnostic. Enabling either would squelch the warning.I think that meets what you outline? And it also nudges code bases towards a more correct / current usage of the language.
sunfishcode commentedon Jun 24, 2019
Yeah, a
-Wvolatile(or whatever we end up calling it) as you describe it here makes sense to me.sunfishcode commentedon Mar 19, 2022
To summarize: