last day (14 days later) » 

3:54 AM
11
Q: How to guide GCC optimizations based on assertions without runtime cost?

LyingOnTheSkyI have a macro used all over my code that in debug mode does: #define contract(condition) \ if (!(condition)) \ throw exception("a contract has been violated"); ... but in release mode: #define contract(condition) \ if (!(condition)) \ __builtin_unreachable(); What t...

 
@paul why you changed the tag to C++?
 
throw is not C but is C++
 
Why not using #ifdef DNDEBUG?
 
@LiranFunaro that's what I use to change the functionality of this macro between debug and release, what do you mean?
 
Why not wrap the condition as well with #ifdef and prevent the compiler from even seeing it?
 
3:54 AM
@LiranFunaro because I want the optimization from the __builtin_unreachable().
Why the downvote?
 
@Living Shouldn't be contract violations be checked at compile time? Otherwise (for simple pre-and post-conditions) an assert()should already do. Can you elaborate about what you're trying to do a bit more please?
 
Then in the release version, just change it to if(true)
 
@LiranFunaro then undefined behavior always happen, and the compiler will optimize the following code...
@πάνταῥεῖ I am trying to help the compiler optimize my code based on assumption I make. Something dynamic like a variable (the i example) cannot be checked at compile-time.
 
@Lying There are things like branch prediction hints.
 
Not sure why this question gets such a bad reception, it's pretty interesting.
 
3:54 AM
I think the downvotes are because people doesn't understand the question, including myself (it is not explained well). But it does seem interesting. (I didn't downvote it).
 
@πάνταῥεῖ it's a hint to the compiler that most of the times something will happen, but if (!(x)) unreachable() is that something will always happen.
@LiranFunaro is there a particular line in the question which seem to confuse you? anything will help...
 
Either you have compile-time static assertions or you want run-time assertions. If you want them to be removed in the release version, use the established assert way. It is still not clear what you want to accomplish actually, but from what is given, it looks like an XY problem or a broken system architecture. Never ever write code relying on a specific optimisation of a specific toolchain with a specific version, for a specific architecture compiled on a specific time on a specific host, ... - got it??
 
I'm missing the answer to what is the behavior you are trying to accomplish?
 
@LiranFunaro Force the compiler assume things on the code, to make more optimizations.
 
@LyingOnTheSky Could you be more specific?
 
3:54 AM
@Olaf so I want a third thing, at debug mode, run-time assertion, and at release mode optimization based on the condition in the assertion.
 
@LyingOnTheSky: Any compiler assuming more than the standard allows is broken by definition.
 
@LiranFunaro For example use a hypothetical container that always does bounds checking, and to remove it you can contract(i < container.size()); in the loop, to potentially optimize the bounds check.
@Olaf not really, sometimes the code is so complex, it just stops trying to prove something and compile very bad code.
 
@LyingOnTheSky: That's not a third way. It looks like you have some missconception how assertions (static and dynamic) and debugging/release targets work.
 
@LyingOnTheSky Either you know before compilation that this is always true, then just remove it in the release mode. Or you don't, then how could the compiler know that? You could suggest the compiler to predict that this is true (something like the kernel's likely). This might improve the branch prediction performance.
 
@Olaf the 'third way' implied that I want something else beside those two.
 
3:54 AM
"not really, sometimes the code is so complex, it just stops trying to prove something and compile very bad code." - As I wrote: XY problem. clean the code/refactor the architecture, etc. Profile, then optimise; such situations often occur with premature optimisations using a bad interface.
Your "third way" implies some missconceptions, not that it exists. "I can't fly flapping my arms" - "flap faster and hopld feathers in your hands".
 
@Olaf: This seems perfectly reasonable to me. The idea is to provide additional information to the optimizer which, for one reason or another, it is unable to deduce itself. Say that the default switch case is unused and thus no range check is required in a tight virtual-machine instruction dispatch loop for instance. Anyway I gather the problem here is that if statement may have side-effects which require evaluation. MSVC avoids this issue by using a __assume construct instead for optimizer hints, but to be honest I am not certain how to avoid the hit here.
 
@Olaf you don't think enough about the possibilities of it... what if LTO is too expensive for you, and you want to make the compiler assume things in other sources? what about assuming things in other libraries which are codes that the compiler can't see (can't optimize based on)?
 
@LyingOnTheSky I've made a substantial edit, in hope of making the question clearer. Do not hesitate to rollback if you don't like it :)
 
@doynax: Omitting the default case is almost always a bad idea. Even if all cases have been handled, providing this case helps catch spurious modifications of the controlling expression, e.g. due to external influence (something which should be accounted for e.g. in embedded systems). But there is no problem omitting this case when using an enum; all modern compilers warn if you don't handle all values - that's what warnings are for. And that's not a matter of debug or release either.
@harold: #ifndef NDEBUG #define contract(condition) (void) #else .... That's basically what assert does.
 
@Olaf in my (Quentin's actually) example it will return i and not 1.
 
3:54 AM
@Olaf: Shrug. It is a trade-off between optimization and defensive coding. Much like when a modern compiler infers UB leaves out tests for cases which are impossible in compliant code. In a safety-critical system where you don't want to trust your execution environment you'll need to dial down both the human and machine optimizations, while in other applications different trade-offs may be warranted.
 
@Quentin thanks, it surprise me that you don't comment much but you actually my got question... (the edit proved it)
 
@harold: I should have used ifdef instead of ifndef. But that does not change the concept!
 
You could have two kinds of expressions. One for debug and one for release. The release expression might be more permissive but will allow the compiler to make some optimization. For example, in debug if(i < c.size()), in release if(i<1024). This might be a hassle...
 
@Quentin: Please provide a reference to the standard what "UB propagation" is.
 
@Olaf ignoring the condition completely misses the point though, because it tells the compiler nothing and the point was to tell it something.
 
3:54 AM
@LiranFunaro you can do contract(c.count() == 1024); for (size_t i = 0; i < 1024; ... to do that. (and "hope" that the compiler understand that i is under 1024)
 
@LyingOnTheSky But this will still result in a function call with possible side-effect.
 
@Olaf it is no standard term that I know of. I mean all of the optimizations that a compiler can perform in all directions by assuming UB doesn't happen. Does this have a more-or-less "offical" name?
 
@LiranFunaro I got what you wanted to prevent... it's rare to have fixed size container, but good example.
 
@LyingOnTheSky Not fixed, but a limit on its size will suffice.
 
I don’t know exactly how to use it correctly (I’ve tried and didn’t get the results I expect), but I think __builtin_constant_p is the tool you use to accomplish this.
 
3:54 AM
incidentally, if you aren't already familiar with it, you should check out static_assert -- en.cppreference.com/w/cpp/language/static_assert
 
@RobStarling No offense, but you are not the first to misunderstand this question. (the problem is that it's similar to another popular question, which is completely different)
@DanielH you want me to turn it into an answer?
 
@LyingOnTheSky Never mind, it won’t actually work. I think doing what you suggested would negate the optimization. It only returns true if the compiler already knows the value, but if it does then there’s no point to using your contract macro.
 
@DanielH the searching for answer continues then, thanks, I didn't check it that far.
@LiranFunaro not so sure about it... __builtin_expect does not eliminate the evaluation of an expression, but makes the compiler make certain execution path faster than others. I still don't get why 1024 though.
 
@LyingOnTheSky I removed the __builtin_expect. I checked it wrong. It doesn't help. 1024 is an example. You should use a specific number that you can be sure your container will never exceed.
It seems to me that it's not the side-effect that is your problem, but the fact that the compiler cannot possibly tell anything about your condition because it missing the information of the possible values returning from the function call. You could either simulate the function call on release, i.e., replace it with a constant. Or accept that there is nothing the compiler do to optimize the function.
 
It is just painful to watch so many people misunderstand this question, or deny the validity of the requirements, and turn around and criticize the original poster and talk down to them. It is informative though in seeing how many people do not understand optimizing compilers as well as they think they do. I think this question is very good but I strongly suspect that what you ask is not possible, will have to think more.
 
3:54 AM
I was hoping to employ the expression building technique that the catch test framework uses to at least distinguish between rvalue/lvalue. It prepends a specific object before the condition expression, which is then unwrapped piece by piece through operators. But I think once you unwrap any part of the expression with an operator, you do force it's evaluation.
 
In this question about expressions with side-effects (and, coincidentally, about asserts), the common consensus is that GCC does not and could not expose this. I think the could not part is ridiculous (it couldn’t be perfect, but it could be as good as the rest of the optimizer), but I would believe that it doesn’t.
 
Clang has __builtin_assume which seems to be exactly what you want. I quote: "The argument itself is never evaluated, so any side effects of the expression will be discarded." And as doynax said, MSVC has __assume. Apparently GCC doesn't have such a dedicated intrinsic.
 
 
4 hours later…
8:13 AM
@Oktalist So this is a mess on GCC, but trivial on Clang... Sad :(
 
 
9 hours later…
4:45 PM
Knowing about __assume (and __builtin_assume, this seems to be a duplicate of stackoverflow.com/questions/25667901/assume-clause-in-gcc, which also says it can’t be done if the compiler can’t prove the contract is side-effect free.
 

last day (14 days later) »