[cfe-dev] [RFC] Introduce overflow builtins

Dave Zarzycki zarzycki at apple.com
Sun Apr 1 22:30:33 PDT 2012


On Apr 1, 2012, at 9:10 PM, Xi Wang <xi.wang at gmail.com> wrote:

>> The patch does not validate that the correct intrinsic is used. For example:
>> 
>> /tmp/llvm/b $ cat of.c
>> int example(int x, int y, int z);
>> int example(int x, int y, int z) {
>> 	if (__builtin_uadd_with_overflow(&x, y, z)) __builtin_trap();
>> 	return x;
>> }
>> 
>> /tmp/llvm/b $ ./Debug+Asserts/bin/clang -Weverything -Os -c of.c
>> /tmp/llvm/b $ echo $?
>> 0
>> /tmp/llvm/b $
> 
> Oops, you are right.  But once we have __builtin_add_with_overflow that infers the sign, __builtin_add_with_overflow(&x, y, z) then means signed addition overflow --- seems that we don't need this validation anymore?

Yup! :-)

Also, this error could be more clear:

+def err_overflow_builtin_pointer_size : Error<
+  "first argument to overflow builtin must be a pointer to 2, 4, or 8 "
+  "type (%0 invalid)">;

To:

+def err_overflow_builtin_pointer_size : Error<
+  "first argument to overflow builtin must be a pointer to a 16-bit, 32-bit, or 64-bit integer "
+  "type (%0 invalid)">;



If you are really motivated in this problem space, then here are some followup ideas to consider:

1) Make __builtin_mul_with_overflow() return the "high" half of the result instead of a bool. You should be able to use the normal LLVM multiplication intrinsics for this instead of llvm.*mul.with.overflow.*.

The rest require hacking on LLVM first:

2) Make __builtin_*_with_overflow work with 8-bit integers.
3) Add __builtin_add_with_carry() and __builtin_sub_with_borrow().

I hope that these goals also excite you too! :-)

davez



More information about the cfe-dev mailing list