5

Clang and GCC define a bunch of builtin functions I'll use the example of remainder here:

__builtin_sqrt(x)

However, standard C99 defines the following in math.h

sqrt(x)

What's the point of clang defining a builtin for a method that already exists? I'd have thought common math functions such as sqrt would be optimised by the backend so doesn't really need a builtin. This builtins are less portable than standard c, for obvious reasons.

H Bellamy
  • 22,405
  • 23
  • 76
  • 114
  • 1
    You should not use __builtin_sqrt directly. You should use sqrt. The compiler will recognize that sqrt is a function it knows and replace it with __builtin_sqrt. At the time this was implemented, gcc did not have the notion of internal function, it only had builtins, which were available to users, so __builtin_sqrt ended up working in user code, but that's a historical accident. – Marc Glisse Mar 08 '17 at 11:02
  • @MarcGlisse why not use it directly? Not even with `#ifdef`s to get compiler specific builtins? If not, why not? – SO_fix_the_vote_sorting_bug May 17 '21 at 18:20
  • 1
    @jdk1.0 Why use longer, non-portable code when the standard code is equivalent? – Marc Glisse May 17 '21 at 19:05

1 Answers1

6

From gcc manual:

GCC normally generates special code to handle certain built-in functions more efficiently; for instance, calls to alloca may become single instructions which adjust the stack directly, and calls to memcpy may become inline copy loops. The resulting code is often both smaller and faster, but since the function calls no longer appear as such, you cannot set a breakpoint on those calls, nor can you change the behavior of the functions by linking with a different library. In addition, when a function is recognized as a built-in function, GCC may use information about that function to warn about problems with calls to that function, or to generate more efficient code, even if the resulting code still contains calls to that function. For example, warnings are given with -Wformat for bad calls to printf when printf is built in and strlen is known not to modify global memory.

Library functions are external to the compiler, so it cannot reason about them to the same extent as builtins. For example, compiler might use builtins in constant folding, eg. replace __builtin_sqrt(1) with 1 whereas it generally cannot do the same with call to library sqrt(1).

Using builtins does not affect portability, because they implement the Standard C, so they have the same semantics.

Les
  • 10,335
  • 4
  • 40
  • 60