1//===--- FreeBSD.cpp - FreeBSD ToolChain Implementations --------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "FreeBSD.h"
10#include "Arch/ARM.h"
11#include "Arch/Mips.h"
12#include "Arch/Sparc.h"
13#include "clang/Config/config.h"
14#include "clang/Driver/CommonArgs.h"
15#include "clang/Driver/Compilation.h"
16#include "clang/Driver/SanitizerArgs.h"
17#include "clang/Options/Options.h"
18#include "llvm/Option/ArgList.h"
19#include "llvm/Support/VirtualFileSystem.h"
20
21using namespace clang::driver;
22using namespace clang::driver::tools;
23using namespace clang::driver::toolchains;
24using namespace clang;
25using namespace llvm::opt;
26
27void freebsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
28 const InputInfo &Output,
29 const InputInfoList &Inputs,
30 const ArgList &Args,
31 const char *LinkingOutput) const {
32 const auto &ToolChain = static_cast<const FreeBSD &>(getToolChain());
33 const auto &D = getToolChain().getDriver();
34 const llvm::Triple &Triple = ToolChain.getTriple();
35 ArgStringList CmdArgs;
36
37 claimNoWarnArgs(Args);
38
39 // When building 32-bit code on FreeBSD/amd64, we have to explicitly
40 // instruct as in the base system to assemble 32-bit code.
41 switch (ToolChain.getArch()) {
42 default:
43 break;
44 case llvm::Triple::x86:
45 CmdArgs.push_back(Elt: "--32");
46 break;
47 case llvm::Triple::ppc:
48 case llvm::Triple::ppcle:
49 CmdArgs.push_back(Elt: "-a32");
50 break;
51 case llvm::Triple::mips:
52 case llvm::Triple::mipsel:
53 case llvm::Triple::mips64:
54 case llvm::Triple::mips64el: {
55 StringRef CPUName;
56 StringRef ABIName;
57 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
58
59 CmdArgs.push_back(Elt: "-march");
60 CmdArgs.push_back(Elt: CPUName.data());
61
62 CmdArgs.push_back(Elt: "-mabi");
63 CmdArgs.push_back(Elt: mips::getGnuCompatibleMipsABIName(ABI: ABIName).data());
64
65 if (Triple.isLittleEndian())
66 CmdArgs.push_back(Elt: "-EL");
67 else
68 CmdArgs.push_back(Elt: "-EB");
69
70 if (Arg *A = Args.getLastArg(Ids: options::OPT_G)) {
71 StringRef v = A->getValue();
72 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-G" + v));
73 A->claim();
74 }
75
76 AddAssemblerKPIC(ToolChain, Args, CmdArgs);
77 break;
78 }
79 case llvm::Triple::arm:
80 case llvm::Triple::armeb:
81 case llvm::Triple::thumb:
82 case llvm::Triple::thumbeb: {
83 arm::FloatABI ABI = arm::getARMFloatABI(TC: ToolChain, Args);
84
85 if (ABI == arm::FloatABI::Hard)
86 CmdArgs.push_back(Elt: "-mfpu=vfp");
87 else
88 CmdArgs.push_back(Elt: "-mfpu=softvfp");
89
90 CmdArgs.push_back(Elt: "-meabi=5");
91 break;
92 }
93 case llvm::Triple::sparcv9: {
94 std::string CPU = getCPUName(D, Args, T: Triple);
95 CmdArgs.push_back(Elt: sparc::getSparcAsmModeForCPU(Name: CPU, Triple));
96 AddAssemblerKPIC(ToolChain, Args, CmdArgs);
97 break;
98 }
99 }
100
101 for (const Arg *A : Args.filtered(Ids: options::OPT_ffile_prefix_map_EQ,
102 Ids: options::OPT_fdebug_prefix_map_EQ)) {
103 StringRef Map = A->getValue();
104 if (!Map.contains(C: '='))
105 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
106 << Map << A->getOption().getName();
107 else {
108 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "--debug-prefix-map"));
109 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Map));
110 }
111 A->claim();
112 }
113
114 Args.AddAllArgValues(Output&: CmdArgs, Id0: options::OPT_Wa_COMMA, Id1: options::OPT_Xassembler);
115
116 CmdArgs.push_back(Elt: "-o");
117 CmdArgs.push_back(Elt: Output.getFilename());
118
119 for (const auto &II : Inputs)
120 CmdArgs.push_back(Elt: II.getFilename());
121
122 const char *Exec = Args.MakeArgString(Str: ToolChain.GetProgramPath(Name: "as"));
123 C.addCommand(Cmd: std::make_unique<Command>(args: JA, args: *this,
124 args: ResponseFileSupport::AtFileCurCP(),
125 args&: Exec, args&: CmdArgs, args: Inputs, args: Output));
126}
127
128void freebsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
129 const InputInfo &Output,
130 const InputInfoList &Inputs,
131 const ArgList &Args,
132 const char *LinkingOutput) const {
133 const auto &ToolChain = static_cast<const FreeBSD &>(getToolChain());
134 const Driver &D = ToolChain.getDriver();
135 const llvm::Triple &Triple = ToolChain.getTriple();
136 const llvm::Triple::ArchType Arch = ToolChain.getArch();
137 ArgStringList CmdArgs;
138
139 // Silence warning for "clang -g foo.o -o foo"
140 Args.ClaimAllArgs(Id0: options::OPT_g_Group);
141 // and "clang -emit-llvm foo.o -o foo"
142 Args.ClaimAllArgs(Id0: options::OPT_emit_llvm);
143 // and for "clang -w foo.o -o foo". Other warning options are already
144 // handled somewhere else.
145 Args.ClaimAllArgs(Id0: options::OPT_w);
146
147 if (!D.SysRoot.empty())
148 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "--sysroot=" + D.SysRoot));
149
150 CmdArgs.push_back(Elt: "--eh-frame-hdr");
151
152 // Explicitly set the linker emulation for platforms that might not
153 // be the default emulation for the linker.
154 switch (Arch) {
155 case llvm::Triple::x86:
156 CmdArgs.push_back(Elt: "-m");
157 CmdArgs.push_back(Elt: "elf_i386_fbsd");
158 break;
159 case llvm::Triple::ppc:
160 CmdArgs.push_back(Elt: "-m");
161 CmdArgs.push_back(Elt: "elf32ppc_fbsd");
162 break;
163 case llvm::Triple::ppcle:
164 CmdArgs.push_back(Elt: "-m");
165 // Use generic -- only usage is for freestanding.
166 CmdArgs.push_back(Elt: "elf32lppc");
167 break;
168 case llvm::Triple::mips:
169 CmdArgs.push_back(Elt: "-m");
170 CmdArgs.push_back(Elt: "elf32btsmip_fbsd");
171 break;
172 case llvm::Triple::mipsel:
173 CmdArgs.push_back(Elt: "-m");
174 CmdArgs.push_back(Elt: "elf32ltsmip_fbsd");
175 break;
176 case llvm::Triple::mips64:
177 CmdArgs.push_back(Elt: "-m");
178 if (tools::mips::hasMipsAbiArg(Args, Value: "n32"))
179 CmdArgs.push_back(Elt: "elf32btsmipn32_fbsd");
180 else
181 CmdArgs.push_back(Elt: "elf64btsmip_fbsd");
182 break;
183 case llvm::Triple::mips64el:
184 CmdArgs.push_back(Elt: "-m");
185 if (tools::mips::hasMipsAbiArg(Args, Value: "n32"))
186 CmdArgs.push_back(Elt: "elf32ltsmipn32_fbsd");
187 else
188 CmdArgs.push_back(Elt: "elf64ltsmip_fbsd");
189 break;
190 case llvm::Triple::riscv64:
191 CmdArgs.push_back(Elt: "-m");
192 CmdArgs.push_back(Elt: "elf64lriscv");
193 break;
194 case llvm::Triple::loongarch64:
195 CmdArgs.push_back(Elt: "-m");
196 CmdArgs.push_back(Elt: "elf64loongarch");
197 break;
198 default:
199 break;
200 }
201
202 if (Triple.isLoongArch64() || Triple.isRISCV64()) {
203 CmdArgs.push_back(Elt: "-X");
204 if (Args.hasArg(Ids: options::OPT_mno_relax))
205 CmdArgs.push_back(Elt: "--no-relax");
206 }
207
208 const bool IsShared = Args.hasArg(Ids: options::OPT_shared);
209 if (IsShared)
210 CmdArgs.push_back(Elt: "-shared");
211 bool IsPIE = false;
212 if (Args.hasArg(Ids: options::OPT_static)) {
213 CmdArgs.push_back(Elt: "-static");
214 } else if (!Args.hasArg(Ids: options::OPT_r)) {
215 if (Args.hasArg(Ids: options::OPT_rdynamic))
216 CmdArgs.push_back(Elt: "-export-dynamic");
217 if (!IsShared) {
218 IsPIE = Args.hasFlag(Pos: options::OPT_pie, Neg: options::OPT_no_pie,
219 Default: ToolChain.isPIEDefault(Args));
220 if (IsPIE)
221 CmdArgs.push_back(Elt: "-pie");
222 CmdArgs.push_back(Elt: "-dynamic-linker");
223 CmdArgs.push_back(Elt: "/libexec/ld-elf.so.1");
224 }
225 if (Arch == llvm::Triple::arm || Triple.isX86())
226 CmdArgs.push_back(Elt: "--hash-style=both");
227 }
228
229 if (Arg *A = Args.getLastArg(Ids: options::OPT_G)) {
230 if (ToolChain.getTriple().isMIPS()) {
231 StringRef v = A->getValue();
232 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-G" + v));
233 A->claim();
234 }
235 }
236
237 assert((Output.isFilename() || Output.isNothing()) && "Invalid output.");
238 if (Output.isFilename()) {
239 CmdArgs.push_back(Elt: "-o");
240 CmdArgs.push_back(Elt: Output.getFilename());
241 }
242
243 if (!Args.hasArg(Ids: options::OPT_nostdlib, Ids: options::OPT_nostartfiles,
244 Ids: options::OPT_r)) {
245 const char *crt1 = nullptr;
246 if (!Args.hasArg(Ids: options::OPT_shared)) {
247 if (Args.hasArg(Ids: options::OPT_pg))
248 crt1 = "gcrt1.o";
249 else if (IsPIE)
250 crt1 = "Scrt1.o";
251 else
252 crt1 = "crt1.o";
253 }
254 if (crt1)
255 CmdArgs.push_back(Elt: Args.MakeArgString(Str: ToolChain.GetFilePath(Name: crt1)));
256
257 // LoongArch does not provide the obsolete _init/_fini interface.
258 if (ToolChain.getArch() != llvm::Triple::loongarch64)
259 CmdArgs.push_back(Elt: Args.MakeArgString(Str: ToolChain.GetFilePath(Name: "crti.o")));
260
261 const char *crtbegin = nullptr;
262 if (Args.hasArg(Ids: options::OPT_static))
263 crtbegin = "crtbeginT.o";
264 else if (Args.hasArg(Ids: options::OPT_shared) || IsPIE)
265 crtbegin = "crtbeginS.o";
266 else
267 crtbegin = "crtbegin.o";
268
269 CmdArgs.push_back(Elt: Args.MakeArgString(Str: ToolChain.GetFilePath(Name: crtbegin)));
270 }
271
272 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_L);
273 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
274 Args.addAllArgs(Output&: CmdArgs,
275 Ids: {options::OPT_T_Group, options::OPT_s, options::OPT_t});
276
277 if (auto LTO = ToolChain.getLTOMode(Args); LTO != LTOK_None)
278 addLTOOptions(ToolChain, Args, CmdArgs, Output, Inputs, IsThinLTO: LTO == LTOK_Thin);
279
280 bool NeedsSanitizerDeps = addSanitizerRuntimes(TC: ToolChain, Args, CmdArgs, C);
281 bool NeedsXRayDeps = addXRayRuntime(TC: ToolChain, Args, CmdArgs);
282 addLinkerCompressDebugSectionsOption(TC: ToolChain, Args, CmdArgs);
283 AddLinkerInputs(TC: ToolChain, Inputs, Args, CmdArgs, JA);
284
285 unsigned Major = ToolChain.getTriple().getOSMajorVersion();
286 bool Profiling = Args.hasArg(Ids: options::OPT_pg) && Major != 0 && Major < 14;
287 if (!Args.hasArg(Ids: options::OPT_nostdlib, Ids: options::OPT_nodefaultlibs,
288 Ids: options::OPT_r)) {
289 // Use the static OpenMP runtime with -static-openmp
290 bool StaticOpenMP = Args.hasArg(Ids: options::OPT_static_openmp) &&
291 !Args.hasArg(Ids: options::OPT_static);
292 addOpenMPRuntime(C, CmdArgs, TC: ToolChain, Args, ForceStaticHostRuntime: StaticOpenMP);
293
294 if (D.CCCIsCXX()) {
295 if (ToolChain.ShouldLinkCXXStdlib(Args))
296 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
297 if (Profiling)
298 CmdArgs.push_back(Elt: "-lm_p");
299 else
300 CmdArgs.push_back(Elt: "-lm");
301 }
302
303 // Silence warnings when linking C code with a C++ '-stdlib' argument.
304 Args.ClaimAllArgs(Id0: options::OPT_stdlib_EQ);
305
306 // Additional linker set-up and flags for Fortran. This is required in order
307 // to generate executables. As Fortran runtime depends on the C runtime,
308 // these dependencies need to be listed before the C runtime below (i.e.
309 // AddRunTimeLibs).
310 if (D.IsFlangMode() &&
311 !Args.hasArg(Ids: options::OPT_nostdlib, Ids: options::OPT_nodefaultlibs)) {
312 ToolChain.addFortranRuntimeLibraryPath(Args, CmdArgs);
313 ToolChain.addFortranRuntimeLibs(Args, CmdArgs);
314 if (Profiling)
315 CmdArgs.push_back(Elt: "-lm_p");
316 else
317 CmdArgs.push_back(Elt: "-lm");
318 }
319
320 if (NeedsSanitizerDeps)
321 linkSanitizerRuntimeDeps(TC: ToolChain, Args, CmdArgs);
322 if (NeedsXRayDeps)
323 linkXRayRuntimeDeps(TC: ToolChain, Args, CmdArgs);
324 // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
325 // the default system libraries. Just mimic this for now.
326 if (Profiling)
327 CmdArgs.push_back(Elt: "-lgcc_p");
328 else
329 CmdArgs.push_back(Elt: "-lgcc");
330 if (Args.hasArg(Ids: options::OPT_static)) {
331 CmdArgs.push_back(Elt: "-lgcc_eh");
332 } else if (Profiling) {
333 CmdArgs.push_back(Elt: "-lgcc_eh_p");
334 } else {
335 CmdArgs.push_back(Elt: "--as-needed");
336 CmdArgs.push_back(Elt: "-lgcc_s");
337 CmdArgs.push_back(Elt: "--no-as-needed");
338 }
339
340 if (Args.hasArg(Ids: options::OPT_pthread)) {
341 if (Profiling)
342 CmdArgs.push_back(Elt: "-lpthread_p");
343 else
344 CmdArgs.push_back(Elt: "-lpthread");
345 }
346
347 if (Profiling) {
348 if (Args.hasArg(Ids: options::OPT_shared))
349 CmdArgs.push_back(Elt: "-lc");
350 else
351 CmdArgs.push_back(Elt: "-lc_p");
352 CmdArgs.push_back(Elt: "-lgcc_p");
353 } else {
354 CmdArgs.push_back(Elt: "-lc");
355 CmdArgs.push_back(Elt: "-lgcc");
356 }
357
358 if (Args.hasArg(Ids: options::OPT_static)) {
359 CmdArgs.push_back(Elt: "-lgcc_eh");
360 } else if (Profiling) {
361 CmdArgs.push_back(Elt: "-lgcc_eh_p");
362 } else {
363 CmdArgs.push_back(Elt: "--as-needed");
364 CmdArgs.push_back(Elt: "-lgcc_s");
365 CmdArgs.push_back(Elt: "--no-as-needed");
366 }
367 }
368
369 if (!Args.hasArg(Ids: options::OPT_nostdlib, Ids: options::OPT_nostartfiles,
370 Ids: options::OPT_r)) {
371 const char *crtend = nullptr;
372 if (Args.hasArg(Ids: options::OPT_shared) || IsPIE)
373 crtend = "crtendS.o";
374 else
375 crtend = "crtend.o";
376 CmdArgs.push_back(Elt: Args.MakeArgString(Str: ToolChain.GetFilePath(Name: crtend)));
377 if (ToolChain.getArch() != llvm::Triple::loongarch64)
378 CmdArgs.push_back(Elt: Args.MakeArgString(Str: ToolChain.GetFilePath(Name: "crtn.o")));
379 }
380
381 ToolChain.addProfileRTLibs(Args, CmdArgs);
382
383 const char *Exec = Args.MakeArgString(Str: getToolChain().GetLinkerPath());
384 C.addCommand(Cmd: std::make_unique<Command>(args: JA, args: *this,
385 args: ResponseFileSupport::AtFileCurCP(),
386 args&: Exec, args&: CmdArgs, args: Inputs, args: Output));
387}
388
389/// FreeBSD - FreeBSD tool chain which can call as(1) and ld(1) directly.
390
391FreeBSD::FreeBSD(const Driver &D, const llvm::Triple &Triple,
392 const ArgList &Args)
393 : Generic_ELF(D, Triple, Args) {
394
395 // When targeting 32-bit platforms, look for '/usr/lib32/crt1.o' and fall
396 // back to '/usr/lib' if it doesn't exist.
397 if (Triple.isArch32Bit() &&
398 D.getVFS().exists(Path: concat(Path: getDriver().SysRoot, A: "/usr/lib32/crt1.o")))
399 getFilePaths().push_back(Elt: concat(Path: getDriver().SysRoot, A: "/usr/lib32"));
400 else
401 getFilePaths().push_back(Elt: concat(Path: getDriver().SysRoot, A: "/usr/lib"));
402}
403
404void FreeBSD::AddClangSystemIncludeArgs(
405 const llvm::opt::ArgList &DriverArgs,
406 llvm::opt::ArgStringList &CC1Args) const {
407 const Driver &D = getDriver();
408
409 if (DriverArgs.hasArg(Ids: options::OPT_nostdinc))
410 return;
411
412 if (!DriverArgs.hasArg(Ids: options::OPT_nobuiltininc)) {
413 SmallString<128> Dir(D.ResourceDir);
414 llvm::sys::path::append(path&: Dir, a: "include");
415 addSystemInclude(DriverArgs, CC1Args, Path: Dir.str());
416 }
417
418 if (DriverArgs.hasArg(Ids: options::OPT_nostdlibinc))
419 return;
420
421 // Check for configure-time C include directories.
422 StringRef CIncludeDirs(C_INCLUDE_DIRS);
423 if (CIncludeDirs != "") {
424 SmallVector<StringRef, 5> dirs;
425 CIncludeDirs.split(A&: dirs, Separator: ":");
426 for (StringRef dir : dirs) {
427 StringRef Prefix =
428 llvm::sys::path::is_absolute(path: dir) ? StringRef(D.SysRoot) : "";
429 addExternCSystemInclude(DriverArgs, CC1Args, Path: Prefix + dir);
430 }
431 return;
432 }
433
434 addExternCSystemInclude(DriverArgs, CC1Args,
435 Path: concat(Path: D.SysRoot, A: "/usr/include"));
436}
437
438void FreeBSD::AddCXXStdlibLibArgs(const ArgList &Args,
439 ArgStringList &CmdArgs) const {
440 Generic_ELF::AddCXXStdlibLibArgs(Args, CmdArgs);
441 unsigned Major = getTriple().getOSMajorVersion();
442 bool SuffixedLib = Args.hasArg(Ids: options::OPT_pg) && Major != 0 && Major < 14;
443 if (SuffixedLib && GetCXXStdlibType(Args) == CST_Libcxx)
444 std::replace_if(
445 first: CmdArgs.begin(), last: CmdArgs.end(),
446 pred: [](const char *S) { return StringRef(S) == "-lc++"; }, new_value: "-lc++_p");
447}
448
449void FreeBSD::AddCudaIncludeArgs(const ArgList &DriverArgs,
450 ArgStringList &CC1Args) const {
451 CudaInstallation->AddCudaIncludeArgs(DriverArgs, CC1Args);
452}
453
454void FreeBSD::AddHIPIncludeArgs(const ArgList &DriverArgs,
455 ArgStringList &CC1Args) const {
456 RocmInstallation->AddHIPIncludeArgs(DriverArgs, CC1Args);
457}
458
459Tool *FreeBSD::buildAssembler() const {
460 return new tools::freebsd::Assembler(*this);
461}
462
463Tool *FreeBSD::buildLinker() const { return new tools::freebsd::Linker(*this); }
464
465bool FreeBSD::HasNativeLLVMSupport() const { return true; }
466
467ToolChain::UnwindTableLevel
468FreeBSD::getDefaultUnwindTableLevel(const ArgList &Args) const {
469 return UnwindTableLevel::Asynchronous;
470}
471
472bool FreeBSD::isPIEDefault(const llvm::opt::ArgList &Args) const {
473 // The FreeBSD base system builds with PIE by default since 13.1.
474 VersionTuple OSVersion = getTriple().getOSVersion();
475 if (OSVersion.getMajor() != 0 && OSVersion < VersionTuple(13, 1))
476 return getSanitizerArgs(JobArgs: Args).requiresPIE();
477 return true;
478}
479
480SanitizerMask
481FreeBSD::getSupportedSanitizers(BoundArch BA,
482 Action::OffloadKind DeviceOffloadKind) const {
483 const bool IsAArch64 = getTriple().getArch() == llvm::Triple::aarch64;
484 const bool IsX86 = getTriple().getArch() == llvm::Triple::x86;
485 const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
486 const bool IsMIPS64 = getTriple().isMIPS64();
487 const bool IsRISCV64 = getTriple().getArch() == llvm::Triple::riscv64;
488 SanitizerMask Res = ToolChain::getSupportedSanitizers(BA, DeviceOffloadKind);
489 Res |= SanitizerKind::Address;
490 Res |= SanitizerKind::PointerCompare;
491 Res |= SanitizerKind::PointerSubtract;
492 Res |= SanitizerKind::Vptr;
493 if (IsAArch64 || IsX86_64 || IsMIPS64) {
494 Res |= SanitizerKind::Leak;
495 Res |= SanitizerKind::Thread;
496 }
497 if (IsAArch64 || IsX86 || IsX86_64) {
498 Res |= SanitizerKind::SafeStack;
499 Res |= SanitizerKind::Fuzzer;
500 Res |= SanitizerKind::FuzzerNoLink;
501 }
502 if (IsAArch64 || IsX86_64 || IsRISCV64) {
503 Res |= SanitizerKind::KernelAddress;
504 Res |= SanitizerKind::KernelMemory;
505 Res |= SanitizerKind::Memory;
506 }
507 return Res;
508}
509