xref: /freebsd/contrib/llvm-project/clang/lib/Driver/ToolChains/AIX.cpp (revision 5ca8e32633c4ffbbcd6762e5888b6a4ba0708c6c)
1 //===--- AIX.cpp - AIX 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 "AIX.h"
10 #include "Arch/PPC.h"
11 #include "CommonArgs.h"
12 #include "clang/Driver/Compilation.h"
13 #include "clang/Driver/Options.h"
14 #include "clang/Driver/SanitizerArgs.h"
15 #include "llvm/ADT/StringExtras.h"
16 #include "llvm/Option/ArgList.h"
17 #include "llvm/ProfileData/InstrProf.h"
18 #include "llvm/Support/Path.h"
19 
20 using AIX = clang::driver::toolchains::AIX;
21 using namespace clang::driver;
22 using namespace clang::driver::tools;
23 using namespace clang::driver::toolchains;
24 
25 using namespace llvm::opt;
26 using namespace llvm::sys;
27 
28 void aix::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   const Driver &D = getToolChain().getDriver();
34   ArgStringList CmdArgs;
35 
36   const bool IsArch32Bit = getToolChain().getTriple().isArch32Bit();
37   const bool IsArch64Bit = getToolChain().getTriple().isArch64Bit();
38   // Only support 32 and 64 bit.
39   if (!IsArch32Bit && !IsArch64Bit)
40     llvm_unreachable("Unsupported bit width value.");
41 
42   if (Arg *A = C.getArgs().getLastArg(options::OPT_G)) {
43     D.Diag(diag::err_drv_unsupported_opt_for_target)
44         << A->getSpelling() << D.getTargetTriple();
45   }
46 
47   // Specify the mode in which the as(1) command operates.
48   if (IsArch32Bit) {
49     CmdArgs.push_back("-a32");
50   } else {
51     // Must be 64-bit, otherwise asserted already.
52     CmdArgs.push_back("-a64");
53   }
54 
55   // Accept any mixture of instructions.
56   // On Power for AIX and Linux, this behaviour matches that of GCC for both the
57   // user-provided assembler source case and the compiler-produced assembler
58   // source case. Yet XL with user-provided assembler source would not add this.
59   CmdArgs.push_back("-many");
60 
61   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
62 
63   // Specify assembler output file.
64   assert((Output.isFilename() || Output.isNothing()) && "Invalid output.");
65   if (Output.isFilename()) {
66     CmdArgs.push_back("-o");
67     CmdArgs.push_back(Output.getFilename());
68   }
69 
70   // Specify assembler input file.
71   // The system assembler on AIX takes exactly one input file. The driver is
72   // expected to invoke as(1) separately for each assembler source input file.
73   if (Inputs.size() != 1)
74     llvm_unreachable("Invalid number of input files.");
75   const InputInfo &II = Inputs[0];
76   assert((II.isFilename() || II.isNothing()) && "Invalid input.");
77   if (II.isFilename())
78     CmdArgs.push_back(II.getFilename());
79 
80   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
81   C.addCommand(std::make_unique<Command>(JA, *this, ResponseFileSupport::None(),
82                                          Exec, CmdArgs, Inputs, Output));
83 }
84 
85 // Determine whether there are any linker options that supply an export list
86 // (or equivalent information about what to export) being sent to the linker.
87 static bool hasExportListLinkerOpts(const ArgStringList &CmdArgs) {
88   for (size_t i = 0, Size = CmdArgs.size(); i < Size; ++i) {
89     llvm::StringRef ArgString(CmdArgs[i]);
90 
91     if (ArgString.startswith("-bE:") || ArgString.startswith("-bexport:") ||
92         ArgString == "-bexpall" || ArgString == "-bexpfull")
93       return true;
94 
95     // If we split -b option, check the next opt.
96     if (ArgString == "-b" && i + 1 < Size) {
97       ++i;
98       llvm::StringRef ArgNextString(CmdArgs[i]);
99       if (ArgNextString.startswith("E:") ||
100           ArgNextString.startswith("export:") || ArgNextString == "expall" ||
101           ArgNextString == "expfull")
102         return true;
103     }
104   }
105   return false;
106 }
107 
108 void aix::Linker::ConstructJob(Compilation &C, const JobAction &JA,
109                                const InputInfo &Output,
110                                const InputInfoList &Inputs, const ArgList &Args,
111                                const char *LinkingOutput) const {
112   const AIX &ToolChain = static_cast<const AIX &>(getToolChain());
113   const Driver &D = ToolChain.getDriver();
114   ArgStringList CmdArgs;
115 
116   const bool IsArch32Bit = ToolChain.getTriple().isArch32Bit();
117   const bool IsArch64Bit = ToolChain.getTriple().isArch64Bit();
118   // Only support 32 and 64 bit.
119   if (!(IsArch32Bit || IsArch64Bit))
120     llvm_unreachable("Unsupported bit width value.");
121 
122   if (Arg *A = C.getArgs().getLastArg(options::OPT_G)) {
123     D.Diag(diag::err_drv_unsupported_opt_for_target)
124         << A->getSpelling() << D.getTargetTriple();
125   }
126 
127   // Force static linking when "-static" is present.
128   if (Args.hasArg(options::OPT_static))
129     CmdArgs.push_back("-bnso");
130 
131   // Add options for shared libraries.
132   if (Args.hasArg(options::OPT_shared)) {
133     CmdArgs.push_back("-bM:SRE");
134     CmdArgs.push_back("-bnoentry");
135   }
136 
137   if (Args.hasFlag(options::OPT_mxcoff_roptr, options::OPT_mno_xcoff_roptr,
138                    false)) {
139     if (Args.hasArg(options::OPT_shared))
140       D.Diag(diag::err_roptr_cannot_build_shared);
141 
142     // The `-mxcoff-roptr` option places constants in RO sections as much as
143     // possible. Then `-bforceimprw` changes such sections to RW if they contain
144     // imported symbols that need to be resolved.
145     CmdArgs.push_back("-bforceimprw");
146   }
147 
148   // PGO instrumentation generates symbols belonging to special sections, and
149   // the linker needs to place all symbols in a particular section together in
150   // memory; the AIX linker does that under an option.
151   if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
152                     false) ||
153        Args.hasFlag(options::OPT_fprofile_generate,
154                     options::OPT_fno_profile_generate, false) ||
155        Args.hasFlag(options::OPT_fprofile_generate_EQ,
156                     options::OPT_fno_profile_generate, false) ||
157        Args.hasFlag(options::OPT_fprofile_instr_generate,
158                     options::OPT_fno_profile_instr_generate, false) ||
159        Args.hasFlag(options::OPT_fprofile_instr_generate_EQ,
160                     options::OPT_fno_profile_instr_generate, false) ||
161        Args.hasFlag(options::OPT_fcs_profile_generate,
162                     options::OPT_fno_profile_generate, false) ||
163        Args.hasFlag(options::OPT_fcs_profile_generate_EQ,
164                     options::OPT_fno_profile_generate, false) ||
165        Args.hasArg(options::OPT_fcreate_profile) ||
166        Args.hasArg(options::OPT_coverage))
167     CmdArgs.push_back("-bdbg:namedsects:ss");
168 
169   if (Arg *A =
170           Args.getLastArg(clang::driver::options::OPT_mxcoff_build_id_EQ)) {
171     StringRef BuildId = A->getValue();
172     if (BuildId[0] != '0' || BuildId[1] != 'x' ||
173         BuildId.find_if_not(llvm::isHexDigit, 2) != StringRef::npos)
174       ToolChain.getDriver().Diag(diag::err_drv_unsupported_option_argument)
175           << A->getSpelling() << BuildId;
176     else {
177       std::string LinkerFlag = "-bdbg:ldrinfo:xcoff_binary_id:0x";
178       if (BuildId.size() % 2) // Prepend a 0 if odd number of digits.
179         LinkerFlag += "0";
180       LinkerFlag += BuildId.drop_front(2).lower();
181       CmdArgs.push_back(Args.MakeArgString(LinkerFlag));
182     }
183   }
184 
185   // Specify linker output file.
186   assert((Output.isFilename() || Output.isNothing()) && "Invalid output.");
187   if (Output.isFilename()) {
188     CmdArgs.push_back("-o");
189     CmdArgs.push_back(Output.getFilename());
190   }
191 
192   // Set linking mode (i.e., 32/64-bit) and the address of
193   // text and data sections based on arch bit width.
194   if (IsArch32Bit) {
195     CmdArgs.push_back("-b32");
196     CmdArgs.push_back("-bpT:0x10000000");
197     CmdArgs.push_back("-bpD:0x20000000");
198   } else {
199     // Must be 64-bit, otherwise asserted already.
200     CmdArgs.push_back("-b64");
201     CmdArgs.push_back("-bpT:0x100000000");
202     CmdArgs.push_back("-bpD:0x110000000");
203   }
204 
205   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles,
206                    options::OPT_shared, options::OPT_r)) {
207     auto getCrt0Basename = [&Args, IsArch32Bit] {
208       if (Arg *A = Args.getLastArgNoClaim(options::OPT_p, options::OPT_pg)) {
209         // Enable gprofiling when "-pg" is specified.
210         if (A->getOption().matches(options::OPT_pg))
211           return IsArch32Bit ? "gcrt0.o" : "gcrt0_64.o";
212         // Enable profiling when "-p" is specified.
213         return IsArch32Bit ? "mcrt0.o" : "mcrt0_64.o";
214       }
215       return IsArch32Bit ? "crt0.o" : "crt0_64.o";
216     };
217 
218     CmdArgs.push_back(
219         Args.MakeArgString(ToolChain.GetFilePath(getCrt0Basename())));
220 
221     CmdArgs.push_back(Args.MakeArgString(
222         ToolChain.GetFilePath(IsArch32Bit ? "crti.o" : "crti_64.o")));
223   }
224 
225   // Collect all static constructor and destructor functions in both C and CXX
226   // language link invocations. This has to come before AddLinkerInputs as the
227   // implied option needs to precede any other '-bcdtors' settings or
228   // '-bnocdtors' that '-Wl' might forward.
229   CmdArgs.push_back("-bcdtors:all:0:s");
230 
231   // Specify linker input file(s).
232   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
233 
234   if (D.isUsingLTO()) {
235     assert(!Inputs.empty() && "Must have at least one input.");
236     addLTOOptions(ToolChain, Args, CmdArgs, Output, Inputs[0],
237                   D.getLTOMode() == LTOK_Thin);
238   }
239 
240   if (Args.hasArg(options::OPT_shared) && !hasExportListLinkerOpts(CmdArgs)) {
241 
242     const char *CreateExportListExec = Args.MakeArgString(
243         path::parent_path(ToolChain.getDriver().ClangExecutable) +
244         "/llvm-nm");
245     ArgStringList CreateExportCmdArgs;
246 
247     std::string CreateExportListPath =
248         C.getDriver().GetTemporaryPath("CreateExportList", "exp");
249     const char *ExportList =
250         C.addTempFile(C.getArgs().MakeArgString(CreateExportListPath));
251 
252     for (const auto &II : Inputs)
253       if (II.isFilename())
254         CreateExportCmdArgs.push_back(II.getFilename());
255 
256     CreateExportCmdArgs.push_back("--export-symbols");
257     CreateExportCmdArgs.push_back("-X");
258     if (IsArch32Bit) {
259       CreateExportCmdArgs.push_back("32");
260     } else {
261       // Must be 64-bit, otherwise asserted already.
262       CreateExportCmdArgs.push_back("64");
263     }
264 
265     auto ExpCommand = std::make_unique<Command>(
266         JA, *this, ResponseFileSupport::None(), CreateExportListExec,
267         CreateExportCmdArgs, Inputs, Output);
268     ExpCommand->setRedirectFiles(
269         {std::nullopt, std::string(ExportList), std::nullopt});
270     C.addCommand(std::move(ExpCommand));
271     CmdArgs.push_back(Args.MakeArgString(llvm::Twine("-bE:") + ExportList));
272   }
273 
274   // Add directory to library search path.
275   Args.AddAllArgs(CmdArgs, options::OPT_L);
276   if (!Args.hasArg(options::OPT_r)) {
277     ToolChain.AddFilePathLibArgs(Args, CmdArgs);
278     ToolChain.addProfileRTLibs(Args, CmdArgs);
279 
280     if (getToolChain().ShouldLinkCXXStdlib(Args))
281       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
282 
283     if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
284       AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
285 
286       // Add OpenMP runtime if -fopenmp is specified.
287       if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
288                        options::OPT_fno_openmp, false)) {
289         switch (ToolChain.getDriver().getOpenMPRuntime(Args)) {
290         case Driver::OMPRT_OMP:
291           CmdArgs.push_back("-lomp");
292           break;
293         case Driver::OMPRT_IOMP5:
294           CmdArgs.push_back("-liomp5");
295           break;
296         case Driver::OMPRT_GOMP:
297           CmdArgs.push_back("-lgomp");
298           break;
299         case Driver::OMPRT_Unknown:
300           // Already diagnosed.
301           break;
302         }
303       }
304 
305       // Support POSIX threads if "-pthreads" or "-pthread" is present.
306       if (Args.hasArg(options::OPT_pthreads, options::OPT_pthread))
307         CmdArgs.push_back("-lpthreads");
308 
309       if (D.CCCIsCXX())
310         CmdArgs.push_back("-lm");
311 
312       CmdArgs.push_back("-lc");
313 
314       if (Args.hasArgNoClaim(options::OPT_p, options::OPT_pg)) {
315         CmdArgs.push_back(Args.MakeArgString((llvm::Twine("-L") + D.SysRoot) +
316                                              "/lib/profiled"));
317         CmdArgs.push_back(Args.MakeArgString((llvm::Twine("-L") + D.SysRoot) +
318                                              "/usr/lib/profiled"));
319       }
320     }
321   }
322 
323   const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
324   C.addCommand(std::make_unique<Command>(JA, *this, ResponseFileSupport::None(),
325                                          Exec, CmdArgs, Inputs, Output));
326 }
327 
328 /// AIX - AIX tool chain which can call as(1) and ld(1) directly.
329 AIX::AIX(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
330     : ToolChain(D, Triple, Args) {
331   getProgramPaths().push_back(getDriver().getInstalledDir());
332   if (getDriver().getInstalledDir() != getDriver().Dir)
333     getProgramPaths().push_back(getDriver().Dir);
334 
335   ParseInlineAsmUsingAsmParser = Args.hasFlag(
336       options::OPT_fintegrated_as, options::OPT_fno_integrated_as, true);
337   getLibraryPaths().push_back(getDriver().SysRoot + "/usr/lib");
338 }
339 
340 // Returns the effective header sysroot path to use.
341 // This comes from either -isysroot or --sysroot.
342 llvm::StringRef
343 AIX::GetHeaderSysroot(const llvm::opt::ArgList &DriverArgs) const {
344   if (DriverArgs.hasArg(options::OPT_isysroot))
345     return DriverArgs.getLastArgValue(options::OPT_isysroot);
346   if (!getDriver().SysRoot.empty())
347     return getDriver().SysRoot;
348   return "/";
349 }
350 
351 void AIX::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
352                                     ArgStringList &CC1Args) const {
353   // Return if -nostdinc is specified as a driver option.
354   if (DriverArgs.hasArg(options::OPT_nostdinc))
355     return;
356 
357   llvm::StringRef Sysroot = GetHeaderSysroot(DriverArgs);
358   const Driver &D = getDriver();
359 
360   if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
361     SmallString<128> P(D.ResourceDir);
362     // Add the PowerPC intrinsic headers (<resource>/include/ppc_wrappers)
363     path::append(P, "include", "ppc_wrappers");
364     addSystemInclude(DriverArgs, CC1Args, P);
365     // Add the Clang builtin headers (<resource>/include)
366     addSystemInclude(DriverArgs, CC1Args, path::parent_path(P.str()));
367   }
368 
369   // Return if -nostdlibinc is specified as a driver option.
370   if (DriverArgs.hasArg(options::OPT_nostdlibinc))
371     return;
372 
373   // Add <sysroot>/usr/include.
374   SmallString<128> UP(Sysroot);
375   path::append(UP, "/usr/include");
376   addSystemInclude(DriverArgs, CC1Args, UP.str());
377 }
378 
379 void AIX::AddClangCXXStdlibIncludeArgs(
380     const llvm::opt::ArgList &DriverArgs,
381     llvm::opt::ArgStringList &CC1Args) const {
382 
383   if (DriverArgs.hasArg(options::OPT_nostdinc) ||
384       DriverArgs.hasArg(options::OPT_nostdincxx) ||
385       DriverArgs.hasArg(options::OPT_nostdlibinc))
386     return;
387 
388   switch (GetCXXStdlibType(DriverArgs)) {
389   case ToolChain::CST_Libstdcxx:
390     llvm::report_fatal_error(
391         "picking up libstdc++ headers is unimplemented on AIX");
392   case ToolChain::CST_Libcxx: {
393     llvm::StringRef Sysroot = GetHeaderSysroot(DriverArgs);
394     SmallString<128> PathCPP(Sysroot);
395     llvm::sys::path::append(PathCPP, "opt/IBM/openxlCSDK", "include", "c++",
396                             "v1");
397     addSystemInclude(DriverArgs, CC1Args, PathCPP.str());
398     // Required in order to suppress conflicting C++ overloads in the system
399     // libc headers that were used by XL C++.
400     CC1Args.push_back("-D__LIBC_NO_CPP_MATH_OVERLOADS__");
401     return;
402   }
403   }
404 
405   llvm_unreachable("Unexpected C++ library type; only libc++ is supported.");
406 }
407 
408 void AIX::AddCXXStdlibLibArgs(const llvm::opt::ArgList &Args,
409                               llvm::opt::ArgStringList &CmdArgs) const {
410   switch (GetCXXStdlibType(Args)) {
411   case ToolChain::CST_Libstdcxx:
412     llvm::report_fatal_error("linking libstdc++ unimplemented on AIX");
413   case ToolChain::CST_Libcxx:
414     CmdArgs.push_back("-lc++");
415     if (Args.hasArg(options::OPT_fexperimental_library))
416       CmdArgs.push_back("-lc++experimental");
417     CmdArgs.push_back("-lc++abi");
418     return;
419   }
420 
421   llvm_unreachable("Unexpected C++ library type; only libc++ is supported.");
422 }
423 
424 void AIX::addClangTargetOptions(
425     const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CC1Args,
426     Action::OffloadKind DeviceOffloadingKind) const {
427   Args.AddLastArg(CC1Args, options::OPT_mignore_xcoff_visibility);
428   Args.AddLastArg(CC1Args, options::OPT_mdefault_visibility_export_mapping_EQ);
429   Args.addOptInFlag(CC1Args, options::OPT_mxcoff_roptr, options::OPT_mno_xcoff_roptr);
430 
431   if (Args.hasFlag(options::OPT_fxl_pragma_pack,
432                    options::OPT_fno_xl_pragma_pack, true))
433     CC1Args.push_back("-fxl-pragma-pack");
434 }
435 
436 void AIX::addProfileRTLibs(const llvm::opt::ArgList &Args,
437                            llvm::opt::ArgStringList &CmdArgs) const {
438   // Add linker option -u__llvm_profile_runtime to cause runtime
439   // initialization to occur.
440   if (needsProfileRT(Args))
441     CmdArgs.push_back(Args.MakeArgString(
442         Twine("-u", llvm::getInstrProfRuntimeHookVarName())));
443   ToolChain::addProfileRTLibs(Args, CmdArgs);
444 }
445 
446 ToolChain::CXXStdlibType AIX::GetDefaultCXXStdlibType() const {
447   return ToolChain::CST_Libcxx;
448 }
449 
450 ToolChain::RuntimeLibType AIX::GetDefaultRuntimeLibType() const {
451   return ToolChain::RLT_CompilerRT;
452 }
453 
454 auto AIX::buildAssembler() const -> Tool * { return new aix::Assembler(*this); }
455 
456 auto AIX::buildLinker() const -> Tool * { return new aix::Linker(*this); }
457