[Interest] How does one use Q_ASSUME?

Elvis Stansvik elvstone at gmail.com
Sun May 26 17:55:33 CEST 2019

Den sön 26 maj 2019 kl 17:15 skrev Thiago Macieira <thiago.macieira at intel.com>:
> On Saturday, 25 May 2019 02:43:11 PDT Giuseppe D'Angelo via Interest wrote:
> > On the other hand, Q_ASSUME(cond) tells the compiler that cond is true,
> > always. If cond is actually false at runtime, you have undefined
> > behavior. And since undefined behavior cannot happen, the compiler is
> > free to optimize the following code assuming that cond is true.
> Please be careful with Q_ASSUME and GCC. Unlike the other three major
> compilers, it does not have __assume or __builtin_assume. So Q_ASSUME
> implements by the if {} else __builtin_unreachable() expression that Peppe's
> link shows. That has two important side-effects:
> 1) sometimes, the compare-and-branch isn't removed. You end up with worse code
> than not assuming at all.
> 2) unlike the other compilers, the conditional is actually in evaluated
> context. So make sure you only Q_ASSUME on variables, never on function calls.
> GCC will call them, the others won't. This is the same rule as Q_ASSERT, btw.

The way Q_ASSUME is defined, isn't that true for non-GCC too?

#define Q_ASSUME(Expr) \
    do {\
        const bool valueOfExpression = Expr;\
        Q_ASSERT_X(valueOfExpression, "Q_ASSUME()", "Assumption in
Q_ASSUME(\"" #Expr "\") was not correct");\
    } while (false)

Won't Expr be evaluated at the const bool valueOfExpression = Expr; ?


> My idea with Q_ASSUME was to make Q_ASSERT expand to it when asserts are
> disabled. After all, calling a [[noreturn]] function is the same as having a
> __builtin_unreachable() after that function call, right?
> Unfortunately, because of the issues above, it couldn't be done.
> PS: Q_UNREACHABLE() is implemented on MSVC with __assume(false).
> --
> Thiago Macieira - thiago.macieira (AT) intel.com
>   Software Architect - Intel System Software Products
> _______________________________________________
> Interest mailing list
> Interest at qt-project.org
> https://lists.qt-project.org/listinfo/interest

More information about the Interest mailing list