[clang] [clang][driver] Enable '-flto' on bare-metal (PR #94738)

via cfe-commits cfe-commits at lists.llvm.org
Fri Jun 7 02:13:26 PDT 2024


https://github.com/walkerkd created https://github.com/llvm/llvm-project/pull/94738

Pass the linker LTO options enabled by the clang '-flto' command line options when targeting bare-metal.

>From 8150a6529be5a3be65e49d5440c576d856d404d5 Mon Sep 17 00:00:00 2001
From: Keith Walker <keith.walker at arm.com>
Date: Thu, 6 Jun 2024 15:14:49 +0100
Subject: [PATCH] [clang][driver] Enable '-flto' on bare-metal

Pass the linker LTO options enabled by the clang '-flto' command
line options when targeting bare-metal.
---
 clang/lib/Driver/ToolChains/BareMetal.cpp | 15 +++++++++++++++
 clang/test/Driver/baremetal-ld.c          |  6 ++++++
 2 files changed, 21 insertions(+)
 create mode 100644 clang/test/Driver/baremetal-ld.c

diff --git a/clang/lib/Driver/ToolChains/BareMetal.cpp b/clang/lib/Driver/ToolChains/BareMetal.cpp
index 221c481579240..d1bd7821414ec 100644
--- a/clang/lib/Driver/ToolChains/BareMetal.cpp
+++ b/clang/lib/Driver/ToolChains/BareMetal.cpp
@@ -429,6 +429,7 @@ void baremetal::Linker::ConstructJob(Compilation &C, const JobAction &JA,
   ArgStringList CmdArgs;
 
   auto &TC = static_cast<const toolchains::BareMetal &>(getToolChain());
+  const Driver &D = getToolChain().getDriver();
   const llvm::Triple::ArchType Arch = TC.getArch();
   const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
 
@@ -466,6 +467,20 @@ void baremetal::Linker::ConstructJob(Compilation &C, const JobAction &JA,
     TC.AddLinkRuntimeLib(Args, CmdArgs);
   }
 
+
+  if (D.isUsingLTO()) {
+    assert(!Inputs.empty() && "Must have at least one input.");
+    // Find the first filename InputInfo object.
+    auto Input = llvm::find_if(
+        Inputs, [](const InputInfo &II) -> bool { return II.isFilename(); });
+    if (Input == Inputs.end())
+      // For a very rare case, all of the inputs to the linker are
+      // InputArg. If that happens, just use the first InputInfo.
+      Input = Inputs.begin();
+
+    addLTOOptions(TC, Args, CmdArgs, Output, *Input,
+                  D.getLTOMode() == LTOK_Thin);
+  }
   if (TC.getTriple().isRISCV())
     CmdArgs.push_back("-X");
 
diff --git a/clang/test/Driver/baremetal-ld.c b/clang/test/Driver/baremetal-ld.c
new file mode 100644
index 0000000000000..ec61b42b6f487
--- /dev/null
+++ b/clang/test/Driver/baremetal-ld.c
@@ -0,0 +1,6 @@
+// RUN: %clang -### --target=armv7-unknown-none-eabi -mcpu=cortex-m4 --sysroot= -fuse-ld=ld %s 2>&1 | FileCheck --check-prefix=NOLTO %s
+// NOLTO: {{".*ld.*"}} {{.*}}
+// NOLTO-NOT: "-plugin-opt=mcpu"
+
+// RUN: %clang -### --target=armv7-unknown-none-eabi -mcpu=cortex-m4 --sysroot= -fuse-ld=ld -flto -O3 %s 2>&1 | FileCheck --check-prefix=LTO %s
+// LTO: {{".*ld.*"}} {{.*}} "-plugin-opt=mcpu=cortex-m4" "-plugin-opt=O3"



More information about the cfe-commits mailing list