[cfe-dev] Incongruency in __builtin_constant_p with pointer argument

Enea Zaffanella zaffanella at cs.unipr.it
Thu Apr 28 03:27:07 PDT 2011


Il 28/04/2011 10:48, Miles Bader ha scritto:
> Abramo Bagnara <abramo.bagnara at gmail.com>
> writes:
>> I think that clang is right to consider pointer to static memory region
>> to be constant at compile-time and hence candidate to constant-folding.
>> (note that the documentation does not say "constant with a known value
>> at compile-time", but "value known to be constant at compile time").
> 
> Whatever wording is in the documentation, I think people tend to _use_
> __builtin_constant_p as if it means "the value is known to the
> compiler/optimizer, and so most of the calculation can be done at
> compile-time."  A "constant" known only at link-time would break this
> assumption.
> 
> So if consistency is necessary (I dunno), it seems better to follow gcc
> and declare them both non-__builtin_constant_p.
> 
> -Miles


The documentation of gcc (4.5.1) says:

> A return of 0 does not indicate that the value is not a constant,
> but merely that GCC cannot prove it is a constant
> with the specified value of the -O option.

Hence, the behavior changes depending on the use of -O.
If you use -O1 or above, gcc will return 1 on those pointers too.

clang/llvm seems to be a bit inconsistent in this respect.
If you compile the following program with -O:
===========================
#include <stdio.h>
#include <string.h>

static const int a = 10;
static const char * const str = "aaa";

int main() {
  printf("%d\n", (int) strlen("aaa"));
  printf("%d\n", (int) strlen(str));
  printf("%d\n", a);
  printf("%d\n", __builtin_constant_p("aaa"));
  printf("%d\n", __builtin_constant_p(str));
  printf("%d\n", __builtin_constant_p(a));
}
===========================

it will optimize expression
    strlen(str)
to the integer value 3 (hence, clang/llvm is able to compute the value
at compile time), yet returning 0 for __builtin_constant_p(str).
The same happens for the string literal "aaa".

If you repeat the experiment without setting -O, then it won't be able
to optimize expression strlen(str), but it will still be able to turn
strlen("aaa") to 3, yet returning 0 for __builtin_constant_p("aaa").

Enea.



More information about the cfe-dev mailing list