[Interest] How does one use Q_ASSUME?

Elvis Stansvik elvstone at gmail.com
Sun May 26 14:10:46 CEST 2019


Den sön 26 maj 2019 kl 12:37 skrev René J. V. Bertin <rjvbertin at gmail.com>:
>
> Giuseppe D'Angelo via Interest wrote:
>
> Hi,
>
> > On the other hand, Q_ASSUME(cond) tells the compiler that cond is true,
>
> After reading the MS doc I sort of understand how you can use the construct to
> implement a Q_UNREACHABLE (but in the example given I don't see the codegen
> advantage of `default: Q_UNREACHABLE` vs. not adding a `default:` at all).

It's a bit subtle, but in the MS example, if you were to remove the
default: altogether, the compiler would have to generate instructions
to check if p is 1, else check if p is 2. With the default: added with
the unreachable hint, it's enough for it to generate instructions to
check if p is 1, because if it isn't, then it is 2 for sure (because
the default:, which covers every other value of p, is unreachable).

HTH,
Elvis

>
> > Look here at a possible example at how it can improve codegen:
> >
> > https://gcc.godbolt.org/z/KlWBRY
>
> Not really, I'm afraid.
>
> The only thing that's evident to me from there is that there is much fewer
> generated machine code when you add the assume statement. I don't see at all why
> that would be, what difference it would make for the loop that it is always
> iterated over a multiple of 16. I thought the difference might be in evaluating
> the `i < count` expression, but even after trying to factor that out the
> difference remains:
> https://gcc.godbolt.org/z/2Zclp5
>
> Take home message for me is that this is a construct that's probably useful only
> if you have very intimate knowledge about code generation, and thus not very
> cross-platform/compiler (and even less cross-architecture). Except for the
> Q_UNREACHABLE thing.
>
> What I was hoping it might do is what the Qt documentation suggests, a more
> graceful version of a Q_ASSERT. That is, a version that does the usual abort in
> debug builds, but becomes a regular if in production code. I've seen too many
> examples of coding where a Q_ASSERT is used to guard against situations that are
> *assumed* never to occur, and then forgotten (or the devs assume everyone else
> uses debug/development builds). In many if not most of those cases it's trivial
> to add a graceful handling of the situation.
>
> R
>
> _______________________________________________
> Interest mailing list
> Interest at qt-project.org
> https://lists.qt-project.org/listinfo/interest



More information about the Interest mailing list