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

Quentin Colombet via llvm-dev llvm-dev at lists.llvm.org
Wed Jun 12 10:11:07 PDT 2019

> On Jun 12, 2019, at 9:54 AM, David Greene via llvm-dev <llvm-dev at lists.llvm.org> wrote:
> 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.

FWIW. If you care about optimization, signed size_t is probably the way to go in general.

Int type will incur a sign extension for any address accesses on 64-bit platform (32-bit to 64-bit extension).
Unsigned on the other hand creates zero extension which are most of the time free.

Thus, unsigned is sometimes better for codegen than signed, in particular in a compiler code base where vectorization is not really a thing.

Anyway, it seems to me that there are enough people on both sides of the fence that this shouldn’t be in the coding standard.

My 2c.


> 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
> _______________________________________________
> LLVM Developers mailing list
> llvm-dev at lists.llvm.org
> https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-dev

More information about the llvm-dev mailing list