xref: /freebsd/contrib/llvm-project/clang/lib/Driver/ToolChains/FreeBSD.cpp (revision ba7b7f94c239ce43343d7af403734fdc941b7664)
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_s);
273   Args.AddAllArgs(CmdArgs, options::OPT_t);
274   Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
275   Args.AddAllArgs(CmdArgs, options::OPT_r);
276 
277   if (D.isUsingLTO()) {
278     assert(!Inputs.empty() && "Must have at least one input.");
279     addLTOOptions(ToolChain, Args, CmdArgs, Output, Inputs[0],
280                   D.getLTOMode() == LTOK_Thin);
281   }
282 
283   bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
284   bool NeedsXRayDeps = addXRayRuntime(ToolChain, Args, CmdArgs);
285   addLinkerCompressDebugSectionsOption(ToolChain, Args, CmdArgs);
286   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
287 
288   unsigned Major = ToolChain.getTriple().getOSMajorVersion();
289   bool Profiling = Args.hasArg(options::OPT_pg) && Major != 0 && Major < 14;
290   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs,
291                    options::OPT_r)) {
292     // Use the static OpenMP runtime with -static-openmp
293     bool StaticOpenMP = Args.hasArg(options::OPT_static_openmp) &&
294                         !Args.hasArg(options::OPT_static);
295     addOpenMPRuntime(CmdArgs, ToolChain, Args, StaticOpenMP);
296 
297     if (D.CCCIsCXX()) {
298       if (ToolChain.ShouldLinkCXXStdlib(Args))
299         ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
300       if (Profiling)
301         CmdArgs.push_back("-lm_p");
302       else
303         CmdArgs.push_back("-lm");
304     }
305     if (NeedsSanitizerDeps)
306       linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
307     if (NeedsXRayDeps)
308       linkXRayRuntimeDeps(ToolChain, CmdArgs);
309     // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
310     // the default system libraries. Just mimic this for now.
311     if (Profiling)
312       CmdArgs.push_back("-lgcc_p");
313     else
314       CmdArgs.push_back("-lgcc");
315     if (Args.hasArg(options::OPT_static)) {
316       CmdArgs.push_back("-lgcc_eh");
317     } else if (Profiling) {
318       CmdArgs.push_back("-lgcc_eh_p");
319     } else {
320       CmdArgs.push_back("--as-needed");
321       CmdArgs.push_back("-lgcc_s");
322       CmdArgs.push_back("--no-as-needed");
323     }
324 
325     if (Args.hasArg(options::OPT_pthread)) {
326       if (Profiling)
327         CmdArgs.push_back("-lpthread_p");
328       else
329         CmdArgs.push_back("-lpthread");
330     }
331 
332     if (Profiling) {
333       if (Args.hasArg(options::OPT_shared))
334         CmdArgs.push_back("-lc");
335       else
336         CmdArgs.push_back("-lc_p");
337       CmdArgs.push_back("-lgcc_p");
338     } else {
339       CmdArgs.push_back("-lc");
340       CmdArgs.push_back("-lgcc");
341     }
342 
343     if (Args.hasArg(options::OPT_static)) {
344       CmdArgs.push_back("-lgcc_eh");
345     } else if (Profiling) {
346       CmdArgs.push_back("-lgcc_eh_p");
347     } else {
348       CmdArgs.push_back("--as-needed");
349       CmdArgs.push_back("-lgcc_s");
350       CmdArgs.push_back("--no-as-needed");
351     }
352   }
353 
354   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles,
355                    options::OPT_r)) {
356     if (Args.hasArg(options::OPT_shared) || IsPIE)
357       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
358     else
359       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
360     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
361   }
362 
363   ToolChain.addProfileRTLibs(Args, CmdArgs);
364 
365   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
366   C.addCommand(std::make_unique<Command>(JA, *this,
367                                          ResponseFileSupport::AtFileCurCP(),
368                                          Exec, CmdArgs, Inputs, Output));
369 }
370 
371 /// FreeBSD - FreeBSD tool chain which can call as(1) and ld(1) directly.
372 
373 FreeBSD::FreeBSD(const Driver &D, const llvm::Triple &Triple,
374                  const ArgList &Args)
375     : Generic_ELF(D, Triple, Args) {
376 
377   // When targeting 32-bit platforms, look for '/usr/lib32/crt1.o' and fall
378   // back to '/usr/lib' if it doesn't exist.
379   if (Triple.isArch32Bit() &&
380       D.getVFS().exists(concat(getDriver().SysRoot, "/usr/lib32/crt1.o")))
381     getFilePaths().push_back(concat(getDriver().SysRoot, "/usr/lib32"));
382   else
383     getFilePaths().push_back(concat(getDriver().SysRoot, "/usr/lib"));
384 }
385 
386 unsigned FreeBSD::GetDefaultDwarfVersion() const {
387   unsigned Major = getTriple().getOSMajorVersion();
388   if (Major >= 12 || Major == 0)
389     return 4;
390   return 2;
391 }
392 
393 void FreeBSD::AddClangSystemIncludeArgs(
394     const llvm::opt::ArgList &DriverArgs,
395     llvm::opt::ArgStringList &CC1Args) const {
396   const Driver &D = getDriver();
397 
398   if (DriverArgs.hasArg(clang::driver::options::OPT_nostdinc))
399     return;
400 
401   if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
402     SmallString<128> Dir(D.ResourceDir);
403     llvm::sys::path::append(Dir, "include");
404     addSystemInclude(DriverArgs, CC1Args, Dir.str());
405   }
406 
407   if (DriverArgs.hasArg(options::OPT_nostdlibinc))
408     return;
409 
410   // Check for configure-time C include directories.
411   StringRef CIncludeDirs(C_INCLUDE_DIRS);
412   if (CIncludeDirs != "") {
413     SmallVector<StringRef, 5> dirs;
414     CIncludeDirs.split(dirs, ":");
415     for (StringRef dir : dirs) {
416       StringRef Prefix =
417           llvm::sys::path::is_absolute(dir) ? StringRef(D.SysRoot) : "";
418       addExternCSystemInclude(DriverArgs, CC1Args, Prefix + dir);
419     }
420     return;
421   }
422 
423   addExternCSystemInclude(DriverArgs, CC1Args,
424                           concat(D.SysRoot, "/usr/include"));
425 }
426 
427 void FreeBSD::addLibCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
428                                     llvm::opt::ArgStringList &CC1Args) const {
429   addSystemInclude(DriverArgs, CC1Args,
430                    concat(getDriver().SysRoot, "/usr/include/c++/v1"));
431 }
432 
433 void FreeBSD::AddCXXStdlibLibArgs(const ArgList &Args,
434                                   ArgStringList &CmdArgs) const {
435   unsigned Major = getTriple().getOSMajorVersion();
436   bool Profiling = Args.hasArg(options::OPT_pg) && Major != 0 && Major < 14;
437 
438   CmdArgs.push_back(Profiling ? "-lc++_p" : "-lc++");
439   if (Args.hasArg(options::OPT_fexperimental_library))
440     CmdArgs.push_back("-lc++experimental");
441 }
442 
443 void FreeBSD::AddCudaIncludeArgs(const ArgList &DriverArgs,
444                                  ArgStringList &CC1Args) const {
445   CudaInstallation->AddCudaIncludeArgs(DriverArgs, CC1Args);
446 }
447 
448 void FreeBSD::AddHIPIncludeArgs(const ArgList &DriverArgs,
449                                 ArgStringList &CC1Args) const {
450   RocmInstallation->AddHIPIncludeArgs(DriverArgs, CC1Args);
451 }
452 
453 Tool *FreeBSD::buildAssembler() const {
454   return new tools::freebsd::Assembler(*this);
455 }
456 
457 Tool *FreeBSD::buildLinker() const { return new tools::freebsd::Linker(*this); }
458 
459 bool FreeBSD::HasNativeLLVMSupport() const { return true; }
460 
461 ToolChain::UnwindTableLevel
462 FreeBSD::getDefaultUnwindTableLevel(const ArgList &Args) const {
463   return UnwindTableLevel::Asynchronous;
464 }
465 
466 bool FreeBSD::isPIEDefault(const llvm::opt::ArgList &Args) const {
467   return getSanitizerArgs(Args).requiresPIE();
468 }
469 
470 SanitizerMask FreeBSD::getSupportedSanitizers() const {
471   const bool IsAArch64 = getTriple().getArch() == llvm::Triple::aarch64;
472   const bool IsX86 = getTriple().getArch() == llvm::Triple::x86;
473   const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
474   const bool IsMIPS64 = getTriple().isMIPS64();
475   SanitizerMask Res = ToolChain::getSupportedSanitizers();
476   Res |= SanitizerKind::Address;
477   Res |= SanitizerKind::PointerCompare;
478   Res |= SanitizerKind::PointerSubtract;
479   Res |= SanitizerKind::Vptr;
480   if (IsAArch64 || IsX86_64 || IsMIPS64) {
481     Res |= SanitizerKind::Leak;
482     Res |= SanitizerKind::Thread;
483   }
484   if (IsAArch64 || IsX86 || IsX86_64) {
485     Res |= SanitizerKind::SafeStack;
486     Res |= SanitizerKind::Fuzzer;
487     Res |= SanitizerKind::FuzzerNoLink;
488   }
489   if (IsAArch64 || IsX86_64) {
490     Res |= SanitizerKind::KernelAddress;
491     Res |= SanitizerKind::KernelMemory;
492     Res |= SanitizerKind::Memory;
493   }
494   return Res;
495 }
496 
497 void FreeBSD::addClangTargetOptions(const ArgList &DriverArgs,
498                                     ArgStringList &CC1Args,
499                                     Action::OffloadKind) const {
500   unsigned Major = getTriple().getOSMajorVersion();
501   if (!DriverArgs.hasFlag(options::OPT_fuse_init_array,
502                           options::OPT_fno_use_init_array,
503                           (Major >= 12 || Major == 0)))
504     CC1Args.push_back("-fno-use-init-array");
505 }
506