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