[llvm-dev] [RFC] Coding Standards: "prefer `int` for regular arithmetic, use `unsigned` only for bitmask and when you intend to rely on wrapping behavior."

David Greene via llvm-dev llvm-dev at lists.llvm.org
Wed Jun 12 09:54:04 PDT 2019


Jake Ehrlich via llvm-dev <llvm-dev at lists.llvm.org> writes:

> This whole debate seems kind of odd to me. I don't know that cases
> where it isn't clear what type to use come up that often. If a value
> can truly never be negative you should use an unsigned value. If a
> value can be negative, you should use a signed value. Anecdotal
> evidence in my case is that the vast majority of values are unsigned
> by this rule.
>
> Is there a reason to use a signed value when you know a value will
> never be negative?

Since this thread is really long, I want to make sure to address this
specific point even though it's been covered elsewhere.

One reason to prefer signed is optimization.  The compiler simply cannot
optimize code with unsigned as well as it can with signed, because of
unsigned's breaking of standard integer algebra.  This affects
everything from simple expression simplification to vectorization and
parallelization.  Using unsigned can have serious performance
consequences.  Because of the nature of the work I do, I see it all the
time.

Some have said this is premature optimization but to me there is no
additional mental load with signed.  In fact it's less for me than
unsigned because of the mental gymnastics I have to go through to verify
code that uses unsigned.

                             -David


More information about the llvm-dev mailing list