What are intrinsics?
Can anyone explain what they are and why I would need them? What kind of applications am I building if I need to use intrinsics?
Solution 1:
An intrinsic function is a function which the compiler implements directly when possible, rather than linking to a library-provided implementation of the function.
A common example is strncpy()
.
For short strings, making a function call to strncpy()
, which involves setting up a 'stack frame' with a return address, will consume more time than the actual copying of bytes does. Worse, the effect on CPU pre-fetch buffers will stall the CPU execution for several clock cycles.
Instead, the intrinsic function is implemented by the compiler in lieu of a function call. In the example of strncpy()
, the byte-copying code is emitted directly at the place where strncpy()
is invoked.
Similar to this strncpy()
example, every intrinsic function is implemented directly as in-line code if required constraints are met.
A non-intrinsic copy of the intrinsic function usually still exists in the standard library, in case the address of the function is needed.
As compared to inline functions, the intrinsic function is provided by the compiler. There isn't a place in the source code of a C program where the intrinsic function is written, nor is there a library implementation that must be linked to. An inline function is different in that the compiler reads the source code for the inline function, but is similar in that later it may emit a compiled translation of the inline function directly into the object code, omitting the overhead of a function call.
In short, the practical difference between an intrinsic funciton and an inline function is that intrinsic functions are "present" even if you have not #include
the needed header file which contains the function declaration. For an inline function, the header file with the function declaration must be #include
'd (or otherwise declared) first.
Solution 2:
Normally, "intrinsics" refers to functions that are built-in -- i.e. most standard library functions that the compiler can/will generate inline instead of calling an actual function in the library. For example, a call like: memset(array1, 10, 0)
could be compiled for an x86 as something like:
mov ecx, 10
xor eax, eax
mov edi, offset FLAT:array1
rep stosb
Intrinsics like this are purely an optimization. "Needing" intrinsics would most likely be a situation where the compiler supports intrinsics that let you generate code that the compiler can't (or usually won't) generate directly. For an obvious example, quite a few compilers for x86 have "MMX Intrinsics" that let you use "functions" that are really just direct representations of MMX instructions.