[builtins] Allow compiling the builtins without libc headers

When compiled with -ffreestanding, we should not assume that headers
declaring functions such as abort() are available. While the compiler may
still emit calls to those functions [1], we should not require the headers
to build compiler-rt since that can result in a cyclic dependency graph:
The compiler-rt functions might be required to build libc.so, but the libc
headers such as stdlib.h might only be available once libc has been built.

[1] From https://gcc.gnu.org/onlinedocs/gcc/Standards.html:
GCC requires the freestanding environment provide memcpy, memmove,
memset and memcmp. Finally, if __builtin_trap is used, and the target
does not implement the trap pattern, then GCC emits a call to abort.

Reviewed By: phosek

Differential Revision: https://reviews.llvm.org/D103876
This commit is contained in:
Alex Richardson 2021-06-15 09:08:59 +01:00
parent c11032ad9a
commit 244601f472
3 changed files with 13 additions and 17 deletions

View File

@ -24,11 +24,15 @@
//===----------------------------------------------------------------------===//
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>
#include "assembly.h"
// We use __builtin_mem* here to avoid dependencies on libc-provided headers.
#define memcpy __builtin_memcpy
#define memcmp __builtin_memcmp
// Clang objects if you redefine a builtin. This little hack allows us to
// define a function with the same name as an intrinsic.
#pragma redefine_extname __atomic_load_c SYMBOL_NAME(__atomic_load)

View File

@ -7,7 +7,9 @@
//===----------------------------------------------------------------------===//
#include "int_lib.h"
#if defined(__linux__)
#include <assert.h>
#endif
#include <stddef.h>
#if __APPLE__

View File

@ -33,35 +33,25 @@ void __compilerrt_abort_impl(const char *file, int line, const char *function) {
NORETURN extern void __assert_rtn(const char *func, const char *file, int line,
const char *message);
#ifndef _WIN32
__attribute__((weak))
__attribute__((visibility("hidden")))
#endif
void __compilerrt_abort_impl(const char *file, int line, const char *function) {
__assert_rtn(function, file, line, "libcompiler_rt abort");
}
#elif __Fuchsia__
#ifndef _WIN32
__attribute__((weak))
__attribute__((visibility("hidden")))
#endif
void __compilerrt_abort_impl(const char *file, int line, const char *function) {
__builtin_trap();
}
#else
// Get the system definition of abort()
#include <stdlib.h>
#ifndef _WIN32
__attribute__((weak))
__attribute__((visibility("hidden")))
#endif
void __compilerrt_abort_impl(const char *file, int line, const char *function) {
abort();
#if !__STDC_HOSTED__
// Avoid depending on libc when compiling with -ffreestanding.
__builtin_trap();
#else
__builtin_abort();
#endif
}
#endif