Question about __builtin_object_size


I have question about __builtin_object_size behaviour. LLVM for __builtin_object_size function doesn't calculate correct value when pointer is used only in __builtin_object_size function call, and never after that. For this case LLVM as result generates 0 or -1 depends of second argument of __builtin_object_size function. Is this correct behaviour or it should work as gcc (gcc calculates correct value for this case) ?

Example for this issue:

include <assert.h>
int main() {
struct V { char buf1[10];
            int b;
            char buf2[10];
           } var;

           char *p = &var.buf1[1], *q = &var.b;
           assert (__builtin_object_size (p, 0) == sizeof (var) - 1);
           return 0;


What version of clang/LLVM are you using? George (cc’ed ) has improved __builtin_object_size support in Clang recently.



This is an artifact of how LLVM works. Essentially, LLVM detects that var is unused and deletes it before it tries to lower the llvm.objectsize (which is what clang lowers __builtin_object_size to) call to a constant. While this isn’t ideal, I don’t think it realistically a problem, because var must be otherwise unused for this behavior to occur, and the whole purpose of objectsize functions (so far) is to insert bounds checks when a variable is used.

If this quirk is causing real problems for you, please let me know and I’ll see what I can do about fixing it. :slight_smile:

Thanks for pointing this out!

Thank you for replies. I’m using trunk version. I have problem in some tests with this behaviour. I also have fix for this problem just need an opinion if this should be fixed in clang. I can post patch on phabricator if you want to take a look.


Patch is certainly welcome.