ANDROID: kbuild: add support for Clang LTO
This change adds the configuration option CONFIG_LTO_CLANG, and
build system support for Clang's Link Time Optimization (LTO). In
preparation for LTO support with other compilers, potentially common
parts of the changes are gated behind CONFIG_LTO instead.
With -flto, instead of object files, Clang produces LLVM bitcode,
which is compiled into a native object at link time, allowing the
final binary to be optimized globally. For more details, see:
https://llvm.org/docs/LinkTimeOptimization.html
While the kernel normally uses GNU ld for linking, LLVM supports LTO
only with LLD or GNU gold linkers. This change assumes LLD is used.
Bug: 145210207
Change-Id: If1164ff33d073358ee7d4bba84cbb06c349c4a88
Signed-off-by: Sami Tolvanen <samitolvanen@google.com>
diff --git a/Makefile b/Makefile
index 80e78ab..3f0530e 100644
--- a/Makefile
+++ b/Makefile
@@ -654,6 +654,16 @@
export RETPOLINE_CFLAGS
export RETPOLINE_VDSO_CFLAGS
+# Make toolchain changes before including arch/$(SRCARCH)/Makefile to ensure
+# ar/cc/ld-* macros return correct values.
+ifdef CONFIG_LTO_CLANG
+# LTO produces LLVM IR instead of object files. Use llvm-ar and llvm-nm, so we
+# can process these.
+AR := llvm-ar
+LLVM_NM := llvm-nm
+export LLVM_NM
+endif
+
include arch/$(SRCARCH)/Makefile
ifdef need-config
@@ -856,6 +866,22 @@
export CC_FLAGS_SCS
endif
+ifdef CONFIG_LTO_CLANG
+ifdef CONFIG_THINLTO
+CC_FLAGS_LTO_CLANG := -flto=thin $(call cc-option, -fsplit-lto-unit)
+KBUILD_LDFLAGS += --thinlto-cache-dir=.thinlto-cache
+else
+CC_FLAGS_LTO_CLANG := -flto
+endif
+CC_FLAGS_LTO_CLANG += -fvisibility=default
+endif
+
+ifdef CONFIG_LTO
+CC_FLAGS_LTO := $(CC_FLAGS_LTO_CLANG)
+KBUILD_CFLAGS += $(CC_FLAGS_LTO)
+export CC_FLAGS_LTO
+endif
+
# arch Makefile may override CC so keep this after arch Makefile is included
NOSTDINC_FLAGS += -nostdinc -isystem $(shell $(CC) -print-file-name=include)
@@ -1682,7 +1708,8 @@
-o -name modules.builtin -o -name '.tmp_*.o.*' \
-o -name '*.c.[012]*.*' \
-o -name '*.ll' \
- -o -name '*.gcno' \) -type f -print | xargs rm -f
+ -o -name '*.gcno' \
+ -o -name '*.*.symversions' \) -type f -print | xargs rm -f
# Generate tags for editors
# ---------------------------------------------------------------------------