1 | //===- ToolChain.cpp - Collections of tools for one platform --------------===// |
---|---|
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 "clang/Driver/ToolChain.h" |
10 | #include "ToolChains/Arch/AArch64.h" |
11 | #include "ToolChains/Arch/ARM.h" |
12 | #include "ToolChains/Arch/RISCV.h" |
13 | #include "ToolChains/Clang.h" |
14 | #include "ToolChains/Flang.h" |
15 | #include "ToolChains/InterfaceStubs.h" |
16 | #include "clang/Basic/ObjCRuntime.h" |
17 | #include "clang/Basic/Sanitizers.h" |
18 | #include "clang/Config/config.h" |
19 | #include "clang/Driver/Action.h" |
20 | #include "clang/Driver/CommonArgs.h" |
21 | #include "clang/Driver/Driver.h" |
22 | #include "clang/Driver/InputInfo.h" |
23 | #include "clang/Driver/Job.h" |
24 | #include "clang/Driver/Options.h" |
25 | #include "clang/Driver/SanitizerArgs.h" |
26 | #include "clang/Driver/XRayArgs.h" |
27 | #include "llvm/ADT/SmallString.h" |
28 | #include "llvm/ADT/StringExtras.h" |
29 | #include "llvm/ADT/StringRef.h" |
30 | #include "llvm/ADT/Twine.h" |
31 | #include "llvm/Config/llvm-config.h" |
32 | #include "llvm/MC/MCTargetOptions.h" |
33 | #include "llvm/MC/TargetRegistry.h" |
34 | #include "llvm/Option/Arg.h" |
35 | #include "llvm/Option/ArgList.h" |
36 | #include "llvm/Option/OptTable.h" |
37 | #include "llvm/Option/Option.h" |
38 | #include "llvm/Support/ErrorHandling.h" |
39 | #include "llvm/Support/FileSystem.h" |
40 | #include "llvm/Support/FileUtilities.h" |
41 | #include "llvm/Support/Path.h" |
42 | #include "llvm/Support/Process.h" |
43 | #include "llvm/Support/VersionTuple.h" |
44 | #include "llvm/Support/VirtualFileSystem.h" |
45 | #include "llvm/TargetParser/AArch64TargetParser.h" |
46 | #include "llvm/TargetParser/RISCVISAInfo.h" |
47 | #include "llvm/TargetParser/TargetParser.h" |
48 | #include "llvm/TargetParser/Triple.h" |
49 | #include <cassert> |
50 | #include <cstddef> |
51 | #include <cstring> |
52 | #include <string> |
53 | |
54 | using namespace clang; |
55 | using namespace driver; |
56 | using namespace tools; |
57 | using namespace llvm; |
58 | using namespace llvm::opt; |
59 | |
60 | static llvm::opt::Arg *GetRTTIArgument(const ArgList &Args) { |
61 | return Args.getLastArg(options::OPT_mkernel, options::OPT_fapple_kext, |
62 | options::OPT_fno_rtti, options::OPT_frtti); |
63 | } |
64 | |
65 | static ToolChain::RTTIMode CalculateRTTIMode(const ArgList &Args, |
66 | const llvm::Triple &Triple, |
67 | const Arg *CachedRTTIArg) { |
68 | // Explicit rtti/no-rtti args |
69 | if (CachedRTTIArg) { |
70 | if (CachedRTTIArg->getOption().matches(options::ID: OPT_frtti)) |
71 | return ToolChain::RM_Enabled; |
72 | else |
73 | return ToolChain::RM_Disabled; |
74 | } |
75 | |
76 | // -frtti is default, except for the PS4/PS5 and DriverKit. |
77 | bool NoRTTI = Triple.isPS() || Triple.isDriverKit(); |
78 | return NoRTTI ? ToolChain::RM_Disabled : ToolChain::RM_Enabled; |
79 | } |
80 | |
81 | static ToolChain::ExceptionsMode CalculateExceptionsMode(const ArgList &Args) { |
82 | if (Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions, |
83 | true)) { |
84 | return ToolChain::EM_Enabled; |
85 | } |
86 | return ToolChain::EM_Disabled; |
87 | } |
88 | |
89 | ToolChain::ToolChain(const Driver &D, const llvm::Triple &T, |
90 | const ArgList &Args) |
91 | : D(D), Triple(T), Args(Args), CachedRTTIArg(GetRTTIArgument(Args)), |
92 | CachedRTTIMode(CalculateRTTIMode(Args, Triple, CachedRTTIArg)), |
93 | CachedExceptionsMode(CalculateExceptionsMode(Args)) { |
94 | auto addIfExists = [this](path_list &List, const std::string &Path) { |
95 | if (getVFS().exists(Path)) |
96 | List.push_back(Elt: Path); |
97 | }; |
98 | |
99 | if (std::optional<std::string> Path = getRuntimePath()) |
100 | getLibraryPaths().push_back(Elt: *Path); |
101 | if (std::optional<std::string> Path = getStdlibPath()) |
102 | getFilePaths().push_back(Elt: *Path); |
103 | for (const auto &Path : getArchSpecificLibPaths()) |
104 | addIfExists(getFilePaths(), Path); |
105 | } |
106 | |
107 | llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>> |
108 | ToolChain::executeToolChainProgram(StringRef Executable) const { |
109 | llvm::SmallString<64> OutputFile; |
110 | llvm::sys::fs::createTemporaryFile(Prefix: "toolchain-program", Suffix: "txt", ResultPath&: OutputFile, |
111 | Flags: llvm::sys::fs::OF_Text); |
112 | llvm::FileRemover OutputRemover(OutputFile.c_str()); |
113 | std::optional<llvm::StringRef> Redirects[] = { |
114 | {""}, |
115 | OutputFile.str(), |
116 | {""}, |
117 | }; |
118 | |
119 | std::string ErrorMessage; |
120 | int SecondsToWait = 60; |
121 | if (std::optional<std::string> Str = |
122 | llvm::sys::Process::GetEnv(name: "CLANG_TOOLCHAIN_PROGRAM_TIMEOUT")) { |
123 | if (!llvm::to_integer(S: *Str, Num&: SecondsToWait)) |
124 | return llvm::createStringError(EC: std::error_code(), |
125 | S: "CLANG_TOOLCHAIN_PROGRAM_TIMEOUT expected " |
126 | "an integer, got '"+ |
127 | *Str + "'"); |
128 | SecondsToWait = std::max(a: SecondsToWait, b: 0); // infinite |
129 | } |
130 | if (llvm::sys::ExecuteAndWait(Program: Executable, Args: {Executable}, Env: {}, Redirects, |
131 | SecondsToWait, |
132 | /*MemoryLimit=*/0, ErrMsg: &ErrorMessage)) |
133 | return llvm::createStringError(EC: std::error_code(), |
134 | S: Executable + ": "+ ErrorMessage); |
135 | |
136 | llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> OutputBuf = |
137 | llvm::MemoryBuffer::getFile(Filename: OutputFile.c_str()); |
138 | if (!OutputBuf) |
139 | return llvm::createStringError(EC: OutputBuf.getError(), |
140 | S: "Failed to read stdout of "+ Executable + |
141 | ": "+ OutputBuf.getError().message()); |
142 | return std::move(*OutputBuf); |
143 | } |
144 | |
145 | void ToolChain::setTripleEnvironment(llvm::Triple::EnvironmentType Env) { |
146 | Triple.setEnvironment(Env); |
147 | if (EffectiveTriple != llvm::Triple()) |
148 | EffectiveTriple.setEnvironment(Env); |
149 | } |
150 | |
151 | ToolChain::~ToolChain() = default; |
152 | |
153 | llvm::vfs::FileSystem &ToolChain::getVFS() const { |
154 | return getDriver().getVFS(); |
155 | } |
156 | |
157 | bool ToolChain::useIntegratedAs() const { |
158 | return Args.hasFlag(options::OPT_fintegrated_as, |
159 | options::OPT_fno_integrated_as, |
160 | IsIntegratedAssemblerDefault()); |
161 | } |
162 | |
163 | bool ToolChain::useIntegratedBackend() const { |
164 | assert( |
165 | ((IsIntegratedBackendDefault() && IsIntegratedBackendSupported()) || |
166 | (!IsIntegratedBackendDefault() || IsNonIntegratedBackendSupported())) && |
167 | "(Non-)integrated backend set incorrectly!"); |
168 | |
169 | bool IBackend = Args.hasFlag(options::OPT_fintegrated_objemitter, |
170 | options::OPT_fno_integrated_objemitter, |
171 | IsIntegratedBackendDefault()); |
172 | |
173 | // Diagnose when integrated-objemitter options are not supported by this |
174 | // toolchain. |
175 | unsigned DiagID; |
176 | if ((IBackend && !IsIntegratedBackendSupported()) || |
177 | (!IBackend && !IsNonIntegratedBackendSupported())) |
178 | DiagID = clang::diag::err_drv_unsupported_opt_for_target; |
179 | else |
180 | DiagID = clang::diag::warn_drv_unsupported_opt_for_target; |
181 | Arg *A = Args.getLastArg(options::OPT_fno_integrated_objemitter); |
182 | if (A && !IsNonIntegratedBackendSupported()) |
183 | D.Diag(DiagID) << A->getAsString(Args) << Triple.getTriple(); |
184 | A = Args.getLastArg(options::OPT_fintegrated_objemitter); |
185 | if (A && !IsIntegratedBackendSupported()) |
186 | D.Diag(DiagID) << A->getAsString(Args) << Triple.getTriple(); |
187 | |
188 | return IBackend; |
189 | } |
190 | |
191 | bool ToolChain::useRelaxRelocations() const { |
192 | return ENABLE_X86_RELAX_RELOCATIONS; |
193 | } |
194 | |
195 | bool ToolChain::defaultToIEEELongDouble() const { |
196 | return PPC_LINUX_DEFAULT_IEEELONGDOUBLE && getTriple().isOSLinux(); |
197 | } |
198 | |
199 | static void processMultilibCustomFlags(Multilib::flags_list &List, |
200 | const llvm::opt::ArgList &Args) { |
201 | for (const Arg *MultilibFlagArg : |
202 | Args.filtered(options::OPT_fmultilib_flag)) { |
203 | List.push_back(MultilibFlagArg->getAsString(Args)); |
204 | MultilibFlagArg->claim(); |
205 | } |
206 | } |
207 | |
208 | static void getAArch64MultilibFlags(const Driver &D, |
209 | const llvm::Triple &Triple, |
210 | const llvm::opt::ArgList &Args, |
211 | Multilib::flags_list &Result) { |
212 | std::vector<StringRef> Features; |
213 | tools::aarch64::getAArch64TargetFeatures(D, Triple, Args, Features, |
214 | /*ForAS=*/false, |
215 | /*ForMultilib=*/true); |
216 | const auto UnifiedFeatures = tools::unifyTargetFeatures(Features); |
217 | llvm::DenseSet<StringRef> FeatureSet(UnifiedFeatures.begin(), |
218 | UnifiedFeatures.end()); |
219 | std::vector<std::string> MArch; |
220 | for (const auto &Ext : AArch64::Extensions) |
221 | if (!Ext.UserVisibleName.empty()) |
222 | if (FeatureSet.contains(Ext.PosTargetFeature)) |
223 | MArch.push_back(Ext.UserVisibleName.str()); |
224 | for (const auto &Ext : AArch64::Extensions) |
225 | if (!Ext.UserVisibleName.empty()) |
226 | if (FeatureSet.contains(Ext.NegTargetFeature)) |
227 | MArch.push_back(("no"+ Ext.UserVisibleName).str()); |
228 | StringRef ArchName; |
229 | for (const auto &ArchInfo : AArch64::ArchInfos) |
230 | if (FeatureSet.contains(ArchInfo->ArchFeature)) |
231 | ArchName = ArchInfo->Name; |
232 | assert(!ArchName.empty() && "at least one architecture should be found"); |
233 | MArch.insert(position: MArch.begin(), x: ("-march="+ ArchName).str()); |
234 | Result.push_back(x: llvm::join(R&: MArch, Separator: "+")); |
235 | |
236 | const Arg *BranchProtectionArg = |
237 | Args.getLastArgNoClaim(options::OPT_mbranch_protection_EQ); |
238 | if (BranchProtectionArg) { |
239 | Result.push_back(x: BranchProtectionArg->getAsString(Args)); |
240 | } |
241 | |
242 | if (FeatureSet.contains(V: "+strict-align")) |
243 | Result.push_back(x: "-mno-unaligned-access"); |
244 | else |
245 | Result.push_back(x: "-munaligned-access"); |
246 | |
247 | if (Arg *Endian = Args.getLastArg(options::OPT_mbig_endian, |
248 | options::OPT_mlittle_endian)) { |
249 | if (Endian->getOption().matches(options::ID: OPT_mbig_endian)) |
250 | Result.push_back(x: Endian->getAsString(Args)); |
251 | } |
252 | |
253 | const Arg *ABIArg = Args.getLastArgNoClaim(options::OPT_mabi_EQ); |
254 | if (ABIArg) { |
255 | Result.push_back(x: ABIArg->getAsString(Args)); |
256 | } |
257 | |
258 | processMultilibCustomFlags(List&: Result, Args); |
259 | } |
260 | |
261 | static void getARMMultilibFlags(const Driver &D, |
262 | const llvm::Triple &Triple, |
263 | const llvm::opt::ArgList &Args, |
264 | Multilib::flags_list &Result) { |
265 | std::vector<StringRef> Features; |
266 | llvm::ARM::FPUKind FPUKind = tools::arm::getARMTargetFeatures( |
267 | D, Triple, Args, Features, ForAS: false /*ForAs*/, ForMultilib: true /*ForMultilib*/); |
268 | const auto UnifiedFeatures = tools::unifyTargetFeatures(Features); |
269 | llvm::DenseSet<StringRef> FeatureSet(UnifiedFeatures.begin(), |
270 | UnifiedFeatures.end()); |
271 | std::vector<std::string> MArch; |
272 | for (const auto &Ext : ARM::ARCHExtNames) |
273 | if (!Ext.Name.empty()) |
274 | if (FeatureSet.contains(V: Ext.Feature)) |
275 | MArch.push_back(x: Ext.Name.str()); |
276 | for (const auto &Ext : ARM::ARCHExtNames) |
277 | if (!Ext.Name.empty()) |
278 | if (FeatureSet.contains(V: Ext.NegFeature)) |
279 | MArch.push_back(x: ("no"+ Ext.Name).str()); |
280 | MArch.insert(position: MArch.begin(), x: ("-march="+ Triple.getArchName()).str()); |
281 | Result.push_back(x: llvm::join(R&: MArch, Separator: "+")); |
282 | |
283 | switch (FPUKind) { |
284 | #define ARM_FPU(NAME, KIND, VERSION, NEON_SUPPORT, RESTRICTION) \ |
285 | case llvm::ARM::KIND: \ |
286 | Result.push_back("-mfpu=" NAME); \ |
287 | break; |
288 | #include "llvm/TargetParser/ARMTargetParser.def" |
289 | default: |
290 | llvm_unreachable("Invalid FPUKind"); |
291 | } |
292 | |
293 | switch (arm::getARMFloatABI(D, Triple, Args)) { |
294 | case arm::FloatABI::Soft: |
295 | Result.push_back(x: "-mfloat-abi=soft"); |
296 | break; |
297 | case arm::FloatABI::SoftFP: |
298 | Result.push_back(x: "-mfloat-abi=softfp"); |
299 | break; |
300 | case arm::FloatABI::Hard: |
301 | Result.push_back(x: "-mfloat-abi=hard"); |
302 | break; |
303 | case arm::FloatABI::Invalid: |
304 | llvm_unreachable("Invalid float ABI"); |
305 | } |
306 | |
307 | const Arg *BranchProtectionArg = |
308 | Args.getLastArgNoClaim(options::OPT_mbranch_protection_EQ); |
309 | if (BranchProtectionArg) { |
310 | Result.push_back(x: BranchProtectionArg->getAsString(Args)); |
311 | } |
312 | |
313 | if (FeatureSet.contains(V: "+strict-align")) |
314 | Result.push_back(x: "-mno-unaligned-access"); |
315 | else |
316 | Result.push_back(x: "-munaligned-access"); |
317 | |
318 | if (Arg *Endian = Args.getLastArg(options::OPT_mbig_endian, |
319 | options::OPT_mlittle_endian)) { |
320 | if (Endian->getOption().matches(options::ID: OPT_mbig_endian)) |
321 | Result.push_back(x: Endian->getAsString(Args)); |
322 | } |
323 | processMultilibCustomFlags(List&: Result, Args); |
324 | } |
325 | |
326 | static void getRISCVMultilibFlags(const Driver &D, const llvm::Triple &Triple, |
327 | const llvm::opt::ArgList &Args, |
328 | Multilib::flags_list &Result) { |
329 | std::string Arch = riscv::getRISCVArch(Args, Triple); |
330 | // Canonicalize arch for easier matching |
331 | auto ISAInfo = llvm::RISCVISAInfo::parseArchString( |
332 | Arch, /*EnableExperimentalExtensions*/ EnableExperimentalExtension: true); |
333 | if (!llvm::errorToBool(Err: ISAInfo.takeError())) |
334 | Result.push_back(x: "-march="+ (*ISAInfo)->toString()); |
335 | |
336 | Result.push_back(x: ("-mabi="+ riscv::getRISCVABI(Args, Triple)).str()); |
337 | } |
338 | |
339 | Multilib::flags_list |
340 | ToolChain::getMultilibFlags(const llvm::opt::ArgList &Args) const { |
341 | using namespace clang::driver::options; |
342 | |
343 | std::vector<std::string> Result; |
344 | const llvm::Triple Triple(ComputeEffectiveClangTriple(Args)); |
345 | Result.push_back(x: "--target="+ Triple.str()); |
346 | |
347 | switch (Triple.getArch()) { |
348 | case llvm::Triple::aarch64: |
349 | case llvm::Triple::aarch64_32: |
350 | case llvm::Triple::aarch64_be: |
351 | getAArch64MultilibFlags(D, Triple, Args, Result); |
352 | break; |
353 | case llvm::Triple::arm: |
354 | case llvm::Triple::armeb: |
355 | case llvm::Triple::thumb: |
356 | case llvm::Triple::thumbeb: |
357 | getARMMultilibFlags(D, Triple, Args, Result); |
358 | break; |
359 | case llvm::Triple::riscv32: |
360 | case llvm::Triple::riscv64: |
361 | getRISCVMultilibFlags(D, Triple, Args, Result); |
362 | break; |
363 | default: |
364 | break; |
365 | } |
366 | |
367 | // Include fno-exceptions and fno-rtti |
368 | // to improve multilib selection |
369 | if (getRTTIMode() == ToolChain::RTTIMode::RM_Disabled) |
370 | Result.push_back(x: "-fno-rtti"); |
371 | else |
372 | Result.push_back(x: "-frtti"); |
373 | |
374 | if (getExceptionsMode() == ToolChain::ExceptionsMode::EM_Disabled) |
375 | Result.push_back(x: "-fno-exceptions"); |
376 | else |
377 | Result.push_back(x: "-fexceptions"); |
378 | |
379 | // Sort and remove duplicates. |
380 | std::sort(first: Result.begin(), last: Result.end()); |
381 | Result.erase(first: llvm::unique(R&: Result), last: Result.end()); |
382 | return Result; |
383 | } |
384 | |
385 | SanitizerArgs |
386 | ToolChain::getSanitizerArgs(const llvm::opt::ArgList &JobArgs) const { |
387 | SanitizerArgs SanArgs(*this, JobArgs, !SanitizerArgsChecked); |
388 | SanitizerArgsChecked = true; |
389 | return SanArgs; |
390 | } |
391 | |
392 | const XRayArgs ToolChain::getXRayArgs(const llvm::opt::ArgList &JobArgs) const { |
393 | XRayArgs XRayArguments(*this, JobArgs); |
394 | return XRayArguments; |
395 | } |
396 | |
397 | namespace { |
398 | |
399 | struct DriverSuffix { |
400 | const char *Suffix; |
401 | const char *ModeFlag; |
402 | }; |
403 | |
404 | } // namespace |
405 | |
406 | static const DriverSuffix *FindDriverSuffix(StringRef ProgName, size_t &Pos) { |
407 | // A list of known driver suffixes. Suffixes are compared against the |
408 | // program name in order. If there is a match, the frontend type is updated as |
409 | // necessary by applying the ModeFlag. |
410 | static const DriverSuffix DriverSuffixes[] = { |
411 | {.Suffix: "clang", .ModeFlag: nullptr}, |
412 | {.Suffix: "clang++", .ModeFlag: "--driver-mode=g++"}, |
413 | {.Suffix: "clang-c++", .ModeFlag: "--driver-mode=g++"}, |
414 | {.Suffix: "clang-cc", .ModeFlag: nullptr}, |
415 | {.Suffix: "clang-cpp", .ModeFlag: "--driver-mode=cpp"}, |
416 | {.Suffix: "clang-g++", .ModeFlag: "--driver-mode=g++"}, |
417 | {.Suffix: "clang-gcc", .ModeFlag: nullptr}, |
418 | {.Suffix: "clang-cl", .ModeFlag: "--driver-mode=cl"}, |
419 | {.Suffix: "cc", .ModeFlag: nullptr}, |
420 | {.Suffix: "cpp", .ModeFlag: "--driver-mode=cpp"}, |
421 | {.Suffix: "cl", .ModeFlag: "--driver-mode=cl"}, |
422 | {.Suffix: "++", .ModeFlag: "--driver-mode=g++"}, |
423 | {.Suffix: "flang", .ModeFlag: "--driver-mode=flang"}, |
424 | // For backwards compatibility, we create a symlink for `flang` called |
425 | // `flang-new`. This will be removed in the future. |
426 | {.Suffix: "flang-new", .ModeFlag: "--driver-mode=flang"}, |
427 | {.Suffix: "clang-dxc", .ModeFlag: "--driver-mode=dxc"}, |
428 | }; |
429 | |
430 | for (const auto &DS : DriverSuffixes) { |
431 | StringRef Suffix(DS.Suffix); |
432 | if (ProgName.ends_with(Suffix)) { |
433 | Pos = ProgName.size() - Suffix.size(); |
434 | return &DS; |
435 | } |
436 | } |
437 | return nullptr; |
438 | } |
439 | |
440 | /// Normalize the program name from argv[0] by stripping the file extension if |
441 | /// present and lower-casing the string on Windows. |
442 | static std::string normalizeProgramName(llvm::StringRef Argv0) { |
443 | std::string ProgName = std::string(llvm::sys::path::filename(path: Argv0)); |
444 | if (is_style_windows(S: llvm::sys::path::Style::native)) { |
445 | // Transform to lowercase for case insensitive file systems. |
446 | std::transform(first: ProgName.begin(), last: ProgName.end(), result: ProgName.begin(), |
447 | unary_op: ::tolower); |
448 | } |
449 | return ProgName; |
450 | } |
451 | |
452 | static const DriverSuffix *parseDriverSuffix(StringRef ProgName, size_t &Pos) { |
453 | // Try to infer frontend type and default target from the program name by |
454 | // comparing it against DriverSuffixes in order. |
455 | |
456 | // If there is a match, the function tries to identify a target as prefix. |
457 | // E.g. "x86_64-linux-clang" as interpreted as suffix "clang" with target |
458 | // prefix "x86_64-linux". If such a target prefix is found, it may be |
459 | // added via -target as implicit first argument. |
460 | const DriverSuffix *DS = FindDriverSuffix(ProgName, Pos); |
461 | |
462 | if (!DS && ProgName.ends_with(Suffix: ".exe")) { |
463 | // Try again after stripping the executable suffix: |
464 | // clang++.exe -> clang++ |
465 | ProgName = ProgName.drop_back(N: StringRef(".exe").size()); |
466 | DS = FindDriverSuffix(ProgName, Pos); |
467 | } |
468 | |
469 | if (!DS) { |
470 | // Try again after stripping any trailing version number: |
471 | // clang++3.5 -> clang++ |
472 | ProgName = ProgName.rtrim(Chars: "0123456789."); |
473 | DS = FindDriverSuffix(ProgName, Pos); |
474 | } |
475 | |
476 | if (!DS) { |
477 | // Try again after stripping trailing -component. |
478 | // clang++-tot -> clang++ |
479 | ProgName = ProgName.slice(Start: 0, End: ProgName.rfind(C: '-')); |
480 | DS = FindDriverSuffix(ProgName, Pos); |
481 | } |
482 | return DS; |
483 | } |
484 | |
485 | ParsedClangName |
486 | ToolChain::getTargetAndModeFromProgramName(StringRef PN) { |
487 | std::string ProgName = normalizeProgramName(Argv0: PN); |
488 | size_t SuffixPos; |
489 | const DriverSuffix *DS = parseDriverSuffix(ProgName, Pos&: SuffixPos); |
490 | if (!DS) |
491 | return {}; |
492 | size_t SuffixEnd = SuffixPos + strlen(s: DS->Suffix); |
493 | |
494 | size_t LastComponent = ProgName.rfind(c: '-', pos: SuffixPos); |
495 | if (LastComponent == std::string::npos) |
496 | return ParsedClangName(ProgName.substr(pos: 0, n: SuffixEnd), DS->ModeFlag); |
497 | std::string ModeSuffix = ProgName.substr(pos: LastComponent + 1, |
498 | n: SuffixEnd - LastComponent - 1); |
499 | |
500 | // Infer target from the prefix. |
501 | StringRef Prefix(ProgName); |
502 | Prefix = Prefix.slice(Start: 0, End: LastComponent); |
503 | std::string IgnoredError; |
504 | bool IsRegistered = llvm::TargetRegistry::lookupTarget(TripleStr: Prefix, Error&: IgnoredError); |
505 | return ParsedClangName{std::string(Prefix), ModeSuffix, DS->ModeFlag, |
506 | IsRegistered}; |
507 | } |
508 | |
509 | StringRef ToolChain::getDefaultUniversalArchName() const { |
510 | // In universal driver terms, the arch name accepted by -arch isn't exactly |
511 | // the same as the ones that appear in the triple. Roughly speaking, this is |
512 | // an inverse of the darwin::getArchTypeForDarwinArchName() function. |
513 | switch (Triple.getArch()) { |
514 | case llvm::Triple::aarch64: { |
515 | if (getTriple().isArm64e()) |
516 | return "arm64e"; |
517 | return "arm64"; |
518 | } |
519 | case llvm::Triple::aarch64_32: |
520 | return "arm64_32"; |
521 | case llvm::Triple::ppc: |
522 | return "ppc"; |
523 | case llvm::Triple::ppcle: |
524 | return "ppcle"; |
525 | case llvm::Triple::ppc64: |
526 | return "ppc64"; |
527 | case llvm::Triple::ppc64le: |
528 | return "ppc64le"; |
529 | default: |
530 | return Triple.getArchName(); |
531 | } |
532 | } |
533 | |
534 | std::string ToolChain::getInputFilename(const InputInfo &Input) const { |
535 | return Input.getFilename(); |
536 | } |
537 | |
538 | ToolChain::UnwindTableLevel |
539 | ToolChain::getDefaultUnwindTableLevel(const ArgList &Args) const { |
540 | return UnwindTableLevel::None; |
541 | } |
542 | |
543 | Tool *ToolChain::getClang() const { |
544 | if (!Clang) |
545 | Clang.reset(p: new tools::Clang(*this, useIntegratedBackend())); |
546 | return Clang.get(); |
547 | } |
548 | |
549 | Tool *ToolChain::getFlang() const { |
550 | if (!Flang) |
551 | Flang.reset(p: new tools::Flang(*this)); |
552 | return Flang.get(); |
553 | } |
554 | |
555 | Tool *ToolChain::buildAssembler() const { |
556 | return new tools::ClangAs(*this); |
557 | } |
558 | |
559 | Tool *ToolChain::buildLinker() const { |
560 | llvm_unreachable("Linking is not supported by this toolchain"); |
561 | } |
562 | |
563 | Tool *ToolChain::buildStaticLibTool() const { |
564 | llvm_unreachable("Creating static lib is not supported by this toolchain"); |
565 | } |
566 | |
567 | Tool *ToolChain::getAssemble() const { |
568 | if (!Assemble) |
569 | Assemble.reset(p: buildAssembler()); |
570 | return Assemble.get(); |
571 | } |
572 | |
573 | Tool *ToolChain::getClangAs() const { |
574 | if (!Assemble) |
575 | Assemble.reset(p: new tools::ClangAs(*this)); |
576 | return Assemble.get(); |
577 | } |
578 | |
579 | Tool *ToolChain::getLink() const { |
580 | if (!Link) |
581 | Link.reset(p: buildLinker()); |
582 | return Link.get(); |
583 | } |
584 | |
585 | Tool *ToolChain::getStaticLibTool() const { |
586 | if (!StaticLibTool) |
587 | StaticLibTool.reset(p: buildStaticLibTool()); |
588 | return StaticLibTool.get(); |
589 | } |
590 | |
591 | Tool *ToolChain::getIfsMerge() const { |
592 | if (!IfsMerge) |
593 | IfsMerge.reset(p: new tools::ifstool::Merger(*this)); |
594 | return IfsMerge.get(); |
595 | } |
596 | |
597 | Tool *ToolChain::getOffloadBundler() const { |
598 | if (!OffloadBundler) |
599 | OffloadBundler.reset(p: new tools::OffloadBundler(*this)); |
600 | return OffloadBundler.get(); |
601 | } |
602 | |
603 | Tool *ToolChain::getOffloadPackager() const { |
604 | if (!OffloadPackager) |
605 | OffloadPackager.reset(p: new tools::OffloadPackager(*this)); |
606 | return OffloadPackager.get(); |
607 | } |
608 | |
609 | Tool *ToolChain::getLinkerWrapper() const { |
610 | if (!LinkerWrapper) |
611 | LinkerWrapper.reset(p: new tools::LinkerWrapper(*this, getLink())); |
612 | return LinkerWrapper.get(); |
613 | } |
614 | |
615 | Tool *ToolChain::getTool(Action::ActionClass AC) const { |
616 | switch (AC) { |
617 | case Action::AssembleJobClass: |
618 | return getAssemble(); |
619 | |
620 | case Action::IfsMergeJobClass: |
621 | return getIfsMerge(); |
622 | |
623 | case Action::LinkJobClass: |
624 | return getLink(); |
625 | |
626 | case Action::StaticLibJobClass: |
627 | return getStaticLibTool(); |
628 | |
629 | case Action::InputClass: |
630 | case Action::BindArchClass: |
631 | case Action::OffloadClass: |
632 | case Action::LipoJobClass: |
633 | case Action::DsymutilJobClass: |
634 | case Action::VerifyDebugInfoJobClass: |
635 | case Action::BinaryAnalyzeJobClass: |
636 | case Action::BinaryTranslatorJobClass: |
637 | llvm_unreachable("Invalid tool kind."); |
638 | |
639 | case Action::CompileJobClass: |
640 | case Action::PrecompileJobClass: |
641 | case Action::PreprocessJobClass: |
642 | case Action::ExtractAPIJobClass: |
643 | case Action::AnalyzeJobClass: |
644 | case Action::VerifyPCHJobClass: |
645 | case Action::BackendJobClass: |
646 | return getClang(); |
647 | |
648 | case Action::OffloadBundlingJobClass: |
649 | case Action::OffloadUnbundlingJobClass: |
650 | return getOffloadBundler(); |
651 | |
652 | case Action::OffloadPackagerJobClass: |
653 | return getOffloadPackager(); |
654 | case Action::LinkerWrapperJobClass: |
655 | return getLinkerWrapper(); |
656 | } |
657 | |
658 | llvm_unreachable("Invalid tool kind."); |
659 | } |
660 | |
661 | static StringRef getArchNameForCompilerRTLib(const ToolChain &TC, |
662 | const ArgList &Args) { |
663 | const llvm::Triple &Triple = TC.getTriple(); |
664 | bool IsWindows = Triple.isOSWindows(); |
665 | |
666 | if (TC.isBareMetal()) |
667 | return Triple.getArchName(); |
668 | |
669 | if (TC.getArch() == llvm::Triple::arm || TC.getArch() == llvm::Triple::armeb) |
670 | return (arm::getARMFloatABI(TC, Args) == arm::FloatABI::Hard && !IsWindows) |
671 | ? "armhf" |
672 | : "arm"; |
673 | |
674 | // For historic reasons, Android library is using i686 instead of i386. |
675 | if (TC.getArch() == llvm::Triple::x86 && Triple.isAndroid()) |
676 | return "i686"; |
677 | |
678 | if (TC.getArch() == llvm::Triple::x86_64 && Triple.isX32()) |
679 | return "x32"; |
680 | |
681 | return llvm::Triple::getArchTypeName(Kind: TC.getArch()); |
682 | } |
683 | |
684 | StringRef ToolChain::getOSLibName() const { |
685 | if (Triple.isOSDarwin()) |
686 | return "darwin"; |
687 | |
688 | switch (Triple.getOS()) { |
689 | case llvm::Triple::FreeBSD: |
690 | return "freebsd"; |
691 | case llvm::Triple::NetBSD: |
692 | return "netbsd"; |
693 | case llvm::Triple::OpenBSD: |
694 | return "openbsd"; |
695 | case llvm::Triple::Solaris: |
696 | return "sunos"; |
697 | case llvm::Triple::AIX: |
698 | return "aix"; |
699 | default: |
700 | return getOS(); |
701 | } |
702 | } |
703 | |
704 | std::string ToolChain::getCompilerRTPath() const { |
705 | SmallString<128> Path(getDriver().ResourceDir); |
706 | if (isBareMetal()) { |
707 | llvm::sys::path::append(path&: Path, a: "lib", b: getOSLibName()); |
708 | if (!SelectedMultilibs.empty()) { |
709 | Path += SelectedMultilibs.back().gccSuffix(); |
710 | } |
711 | } else if (Triple.isOSUnknown()) { |
712 | llvm::sys::path::append(path&: Path, a: "lib"); |
713 | } else { |
714 | llvm::sys::path::append(path&: Path, a: "lib", b: getOSLibName()); |
715 | } |
716 | return std::string(Path); |
717 | } |
718 | |
719 | std::string ToolChain::getCompilerRTBasename(const ArgList &Args, |
720 | StringRef Component, |
721 | FileType Type) const { |
722 | std::string CRTAbsolutePath = getCompilerRT(Args, Component, Type); |
723 | return llvm::sys::path::filename(path: CRTAbsolutePath).str(); |
724 | } |
725 | |
726 | std::string ToolChain::buildCompilerRTBasename(const llvm::opt::ArgList &Args, |
727 | StringRef Component, |
728 | FileType Type, bool AddArch, |
729 | bool IsFortran) const { |
730 | const llvm::Triple &TT = getTriple(); |
731 | bool IsITANMSVCWindows = |
732 | TT.isWindowsMSVCEnvironment() || TT.isWindowsItaniumEnvironment(); |
733 | |
734 | const char *Prefix = |
735 | IsITANMSVCWindows || Type == ToolChain::FT_Object ? "": "lib"; |
736 | const char *Suffix; |
737 | switch (Type) { |
738 | case ToolChain::FT_Object: |
739 | Suffix = IsITANMSVCWindows ? ".obj": ".o"; |
740 | break; |
741 | case ToolChain::FT_Static: |
742 | Suffix = IsITANMSVCWindows ? ".lib": ".a"; |
743 | break; |
744 | case ToolChain::FT_Shared: |
745 | if (TT.isOSWindows()) |
746 | Suffix = TT.isWindowsGNUEnvironment() ? ".dll.a": ".lib"; |
747 | else if (TT.isOSAIX()) |
748 | Suffix = ".a"; |
749 | else |
750 | Suffix = ".so"; |
751 | break; |
752 | } |
753 | |
754 | std::string ArchAndEnv; |
755 | if (AddArch) { |
756 | StringRef Arch = getArchNameForCompilerRTLib(TC: *this, Args); |
757 | const char *Env = TT.isAndroid() ? "-android": ""; |
758 | ArchAndEnv = ("-"+ Arch + Env).str(); |
759 | } |
760 | |
761 | std::string LibName = IsFortran ? "flang_rt.": "clang_rt."; |
762 | return (Prefix + Twine(LibName) + Component + ArchAndEnv + Suffix).str(); |
763 | } |
764 | |
765 | std::string ToolChain::getCompilerRT(const ArgList &Args, StringRef Component, |
766 | FileType Type, bool IsFortran) const { |
767 | // Check for runtime files in the new layout without the architecture first. |
768 | std::string CRTBasename = buildCompilerRTBasename( |
769 | Args, Component, Type, /*AddArch=*/false, IsFortran); |
770 | SmallString<128> Path; |
771 | for (const auto &LibPath : getLibraryPaths()) { |
772 | SmallString<128> P(LibPath); |
773 | llvm::sys::path::append(path&: P, a: CRTBasename); |
774 | if (getVFS().exists(Path: P)) |
775 | return std::string(P); |
776 | if (Path.empty()) |
777 | Path = P; |
778 | } |
779 | |
780 | // Check the filename for the old layout if the new one does not exist. |
781 | CRTBasename = buildCompilerRTBasename(Args, Component, Type, |
782 | /*AddArch=*/!IsFortran, IsFortran); |
783 | SmallString<128> OldPath(getCompilerRTPath()); |
784 | llvm::sys::path::append(path&: OldPath, a: CRTBasename); |
785 | if (Path.empty() || getVFS().exists(Path: OldPath)) |
786 | return std::string(OldPath); |
787 | |
788 | // If none is found, use a file name from the new layout, which may get |
789 | // printed in an error message, aiding users in knowing what Clang is |
790 | // looking for. |
791 | return std::string(Path); |
792 | } |
793 | |
794 | const char *ToolChain::getCompilerRTArgString(const llvm::opt::ArgList &Args, |
795 | StringRef Component, |
796 | FileType Type, |
797 | bool isFortran) const { |
798 | return Args.MakeArgString(Str: getCompilerRT(Args, Component, Type, IsFortran: isFortran)); |
799 | } |
800 | |
801 | /// Add Fortran runtime libs |
802 | void ToolChain::addFortranRuntimeLibs(const ArgList &Args, |
803 | llvm::opt::ArgStringList &CmdArgs) const { |
804 | // Link flang_rt.runtime |
805 | // These are handled earlier on Windows by telling the frontend driver to |
806 | // add the correct libraries to link against as dependents in the object |
807 | // file. |
808 | if (!getTriple().isKnownWindowsMSVCEnvironment()) { |
809 | StringRef F128LibName = getDriver().getFlangF128MathLibrary(); |
810 | F128LibName.consume_front_insensitive(Prefix: "lib"); |
811 | if (!F128LibName.empty()) { |
812 | bool AsNeeded = !getTriple().isOSAIX(); |
813 | CmdArgs.push_back(Elt: "-lflang_rt.quadmath"); |
814 | if (AsNeeded) |
815 | addAsNeededOption(TC: *this, Args, CmdArgs, /*as_needed=*/true); |
816 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-l"+ F128LibName)); |
817 | if (AsNeeded) |
818 | addAsNeededOption(TC: *this, Args, CmdArgs, /*as_needed=*/false); |
819 | } |
820 | addFlangRTLibPath(Args, CmdArgs); |
821 | |
822 | // needs libexecinfo for backtrace functions |
823 | if (getTriple().isOSFreeBSD() || getTriple().isOSNetBSD() || |
824 | getTriple().isOSOpenBSD() || getTriple().isOSDragonFly()) |
825 | CmdArgs.push_back(Elt: "-lexecinfo"); |
826 | } |
827 | |
828 | // libomp needs libatomic for atomic operations if using libgcc |
829 | if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ, |
830 | options::OPT_fno_openmp, false)) { |
831 | Driver::OpenMPRuntimeKind OMPRuntime = getDriver().getOpenMPRuntime(Args); |
832 | ToolChain::RuntimeLibType RuntimeLib = GetRuntimeLibType(Args); |
833 | if (OMPRuntime == Driver::OMPRT_OMP && RuntimeLib == ToolChain::RLT_Libgcc) |
834 | CmdArgs.push_back(Elt: "-latomic"); |
835 | } |
836 | } |
837 | |
838 | void ToolChain::addFortranRuntimeLibraryPath(const llvm::opt::ArgList &Args, |
839 | ArgStringList &CmdArgs) const { |
840 | // Default to the <driver-path>/../lib directory. This works fine on the |
841 | // platforms that we have tested so far. We will probably have to re-fine |
842 | // this in the future. In particular, on some platforms, we may need to use |
843 | // lib64 instead of lib. |
844 | SmallString<256> DefaultLibPath = |
845 | llvm::sys::path::parent_path(path: getDriver().Dir); |
846 | llvm::sys::path::append(path&: DefaultLibPath, a: "lib"); |
847 | if (getTriple().isKnownWindowsMSVCEnvironment()) |
848 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-libpath:"+ DefaultLibPath)); |
849 | else |
850 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-L"+ DefaultLibPath)); |
851 | } |
852 | |
853 | void ToolChain::addFlangRTLibPath(const ArgList &Args, |
854 | llvm::opt::ArgStringList &CmdArgs) const { |
855 | // Link static flang_rt.runtime.a or shared flang_rt.runtime.so. |
856 | // On AIX, default to static flang-rt. |
857 | if (Args.hasFlag(options::OPT_static_libflangrt, |
858 | options::OPT_shared_libflangrt, getTriple().isOSAIX())) |
859 | CmdArgs.push_back( |
860 | Elt: getCompilerRTArgString(Args, Component: "runtime", Type: ToolChain::FT_Static, isFortran: true)); |
861 | else { |
862 | CmdArgs.push_back(Elt: "-lflang_rt.runtime"); |
863 | addArchSpecificRPath(TC: *this, Args, CmdArgs); |
864 | } |
865 | } |
866 | |
867 | // Android target triples contain a target version. If we don't have libraries |
868 | // for the exact target version, we should fall back to the next newest version |
869 | // or a versionless path, if any. |
870 | std::optional<std::string> |
871 | ToolChain::getFallbackAndroidTargetPath(StringRef BaseDir) const { |
872 | llvm::Triple TripleWithoutLevel(getTriple()); |
873 | TripleWithoutLevel.setEnvironmentName("android"); // remove any version number |
874 | const std::string &TripleWithoutLevelStr = TripleWithoutLevel.str(); |
875 | unsigned TripleVersion = getTriple().getEnvironmentVersion().getMajor(); |
876 | unsigned BestVersion = 0; |
877 | |
878 | SmallString<32> TripleDir; |
879 | bool UsingUnversionedDir = false; |
880 | std::error_code EC; |
881 | for (llvm::vfs::directory_iterator LI = getVFS().dir_begin(Dir: BaseDir, EC), LE; |
882 | !EC && LI != LE; LI = LI.increment(EC)) { |
883 | StringRef DirName = llvm::sys::path::filename(path: LI->path()); |
884 | StringRef DirNameSuffix = DirName; |
885 | if (DirNameSuffix.consume_front(Prefix: TripleWithoutLevelStr)) { |
886 | if (DirNameSuffix.empty() && TripleDir.empty()) { |
887 | TripleDir = DirName; |
888 | UsingUnversionedDir = true; |
889 | } else { |
890 | unsigned Version; |
891 | if (!DirNameSuffix.getAsInteger(Radix: 10, Result&: Version) && Version > BestVersion && |
892 | Version < TripleVersion) { |
893 | BestVersion = Version; |
894 | TripleDir = DirName; |
895 | UsingUnversionedDir = false; |
896 | } |
897 | } |
898 | } |
899 | } |
900 | |
901 | if (TripleDir.empty()) |
902 | return {}; |
903 | |
904 | SmallString<128> P(BaseDir); |
905 | llvm::sys::path::append(path&: P, a: TripleDir); |
906 | if (UsingUnversionedDir) |
907 | D.Diag(diag::DiagID: warn_android_unversioned_fallback) << P << getTripleString(); |
908 | return std::string(P); |
909 | } |
910 | |
911 | llvm::Triple ToolChain::getTripleWithoutOSVersion() const { |
912 | return (Triple.hasEnvironment() |
913 | ? llvm::Triple(Triple.getArchName(), Triple.getVendorName(), |
914 | llvm::Triple::getOSTypeName(Kind: Triple.getOS()), |
915 | llvm::Triple::getEnvironmentTypeName( |
916 | Kind: Triple.getEnvironment())) |
917 | : llvm::Triple(Triple.getArchName(), Triple.getVendorName(), |
918 | llvm::Triple::getOSTypeName(Kind: Triple.getOS()))); |
919 | } |
920 | |
921 | std::optional<std::string> |
922 | ToolChain::getTargetSubDirPath(StringRef BaseDir) const { |
923 | auto getPathForTriple = |
924 | [&](const llvm::Triple &Triple) -> std::optional<std::string> { |
925 | SmallString<128> P(BaseDir); |
926 | llvm::sys::path::append(path&: P, a: Triple.str()); |
927 | if (getVFS().exists(Path: P)) |
928 | return std::string(P); |
929 | return {}; |
930 | }; |
931 | |
932 | const llvm::Triple &T = getTriple(); |
933 | if (auto Path = getPathForTriple(T)) |
934 | return *Path; |
935 | |
936 | if (T.isOSAIX()) { |
937 | llvm::Triple AIXTriple; |
938 | if (T.getEnvironment() == Triple::UnknownEnvironment) { |
939 | // Strip unknown environment and the OS version from the triple. |
940 | AIXTriple = llvm::Triple(T.getArchName(), T.getVendorName(), |
941 | llvm::Triple::getOSTypeName(Kind: T.getOS())); |
942 | } else { |
943 | // Strip the OS version from the triple. |
944 | AIXTriple = getTripleWithoutOSVersion(); |
945 | } |
946 | if (auto Path = getPathForTriple(AIXTriple)) |
947 | return *Path; |
948 | } |
949 | |
950 | if (T.isOSzOS() && |
951 | (!T.getOSVersion().empty() || !T.getEnvironmentVersion().empty())) { |
952 | // Build the triple without version information |
953 | const llvm::Triple &TripleWithoutVersion = getTripleWithoutOSVersion(); |
954 | if (auto Path = getPathForTriple(TripleWithoutVersion)) |
955 | return *Path; |
956 | } |
957 | |
958 | // When building with per target runtime directories, various ways of naming |
959 | // the Arm architecture may have been normalised to simply "arm". |
960 | // For example "armv8l" (Armv8 AArch32 little endian) is replaced with "arm". |
961 | // Since an armv8l system can use libraries built for earlier architecture |
962 | // versions assuming endian and float ABI match. |
963 | // |
964 | // Original triple: armv8l-unknown-linux-gnueabihf |
965 | // Runtime triple: arm-unknown-linux-gnueabihf |
966 | // |
967 | // We do not do this for armeb (big endian) because doing so could make us |
968 | // select little endian libraries. In addition, all known armeb triples only |
969 | // use the "armeb" architecture name. |
970 | // |
971 | // M profile Arm is bare metal and we know they will not be using the per |
972 | // target runtime directory layout. |
973 | if (T.getArch() == Triple::arm && !T.isArmMClass()) { |
974 | llvm::Triple ArmTriple = T; |
975 | ArmTriple.setArch(Kind: Triple::arm); |
976 | if (auto Path = getPathForTriple(ArmTriple)) |
977 | return *Path; |
978 | } |
979 | |
980 | if (T.isAndroid()) |
981 | return getFallbackAndroidTargetPath(BaseDir); |
982 | |
983 | return {}; |
984 | } |
985 | |
986 | std::optional<std::string> ToolChain::getRuntimePath() const { |
987 | SmallString<128> P(D.ResourceDir); |
988 | llvm::sys::path::append(path&: P, a: "lib"); |
989 | if (auto Ret = getTargetSubDirPath(BaseDir: P)) |
990 | return Ret; |
991 | // Darwin does not use per-target runtime directory. |
992 | if (Triple.isOSDarwin()) |
993 | return {}; |
994 | |
995 | llvm::sys::path::append(path&: P, a: Triple.str()); |
996 | return std::string(P); |
997 | } |
998 | |
999 | std::optional<std::string> ToolChain::getStdlibPath() const { |
1000 | SmallString<128> P(D.Dir); |
1001 | llvm::sys::path::append(path&: P, a: "..", b: "lib"); |
1002 | return getTargetSubDirPath(BaseDir: P); |
1003 | } |
1004 | |
1005 | std::optional<std::string> ToolChain::getStdlibIncludePath() const { |
1006 | SmallString<128> P(D.Dir); |
1007 | llvm::sys::path::append(path&: P, a: "..", b: "include"); |
1008 | return getTargetSubDirPath(BaseDir: P); |
1009 | } |
1010 | |
1011 | ToolChain::path_list ToolChain::getArchSpecificLibPaths() const { |
1012 | path_list Paths; |
1013 | |
1014 | auto AddPath = [&](const ArrayRef<StringRef> &SS) { |
1015 | SmallString<128> Path(getDriver().ResourceDir); |
1016 | llvm::sys::path::append(path&: Path, a: "lib"); |
1017 | for (auto &S : SS) |
1018 | llvm::sys::path::append(path&: Path, a: S); |
1019 | Paths.push_back(Elt: std::string(Path)); |
1020 | }; |
1021 | |
1022 | AddPath({getTriple().str()}); |
1023 | AddPath({getOSLibName(), llvm::Triple::getArchTypeName(Kind: getArch())}); |
1024 | return Paths; |
1025 | } |
1026 | |
1027 | bool ToolChain::needsProfileRT(const ArgList &Args) { |
1028 | if (Args.hasArg(options::OPT_noprofilelib)) |
1029 | return false; |
1030 | |
1031 | return Args.hasArg(options::OPT_fprofile_generate) || |
1032 | Args.hasArg(options::OPT_fprofile_generate_EQ) || |
1033 | Args.hasArg(options::OPT_fcs_profile_generate) || |
1034 | Args.hasArg(options::OPT_fcs_profile_generate_EQ) || |
1035 | Args.hasArg(options::OPT_fprofile_instr_generate) || |
1036 | Args.hasArg(options::OPT_fprofile_instr_generate_EQ) || |
1037 | Args.hasArg(options::OPT_fcreate_profile) || |
1038 | Args.hasArg(options::OPT_fprofile_generate_cold_function_coverage) || |
1039 | Args.hasArg(options::OPT_fprofile_generate_cold_function_coverage_EQ); |
1040 | } |
1041 | |
1042 | bool ToolChain::needsGCovInstrumentation(const llvm::opt::ArgList &Args) { |
1043 | return Args.hasArg(options::OPT_coverage) || |
1044 | Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs, |
1045 | false); |
1046 | } |
1047 | |
1048 | Tool *ToolChain::SelectTool(const JobAction &JA) const { |
1049 | if (D.IsFlangMode() && getDriver().ShouldUseFlangCompiler(JA)) return getFlang(); |
1050 | if (getDriver().ShouldUseClangCompiler(JA)) return getClang(); |
1051 | Action::ActionClass AC = JA.getKind(); |
1052 | if (AC == Action::AssembleJobClass && useIntegratedAs() && |
1053 | !getTriple().isOSAIX()) |
1054 | return getClangAs(); |
1055 | return getTool(AC); |
1056 | } |
1057 | |
1058 | std::string ToolChain::GetFilePath(const char *Name) const { |
1059 | return D.GetFilePath(Name, TC: *this); |
1060 | } |
1061 | |
1062 | std::string ToolChain::GetProgramPath(const char *Name) const { |
1063 | return D.GetProgramPath(Name, TC: *this); |
1064 | } |
1065 | |
1066 | std::string ToolChain::GetLinkerPath(bool *LinkerIsLLD) const { |
1067 | if (LinkerIsLLD) |
1068 | *LinkerIsLLD = false; |
1069 | |
1070 | // Get -fuse-ld= first to prevent -Wunused-command-line-argument. -fuse-ld= is |
1071 | // considered as the linker flavor, e.g. "bfd", "gold", or "lld". |
1072 | const Arg* A = Args.getLastArg(options::OPT_fuse_ld_EQ); |
1073 | StringRef UseLinker = A ? A->getValue() : CLANG_DEFAULT_LINKER; |
1074 | |
1075 | // --ld-path= takes precedence over -fuse-ld= and specifies the executable |
1076 | // name. -B, COMPILER_PATH and PATH and consulted if the value does not |
1077 | // contain a path component separator. |
1078 | // -fuse-ld=lld can be used with --ld-path= to inform clang that the binary |
1079 | // that --ld-path= points to is lld. |
1080 | if (const Arg *A = Args.getLastArg(options::OPT_ld_path_EQ)) { |
1081 | std::string Path(A->getValue()); |
1082 | if (!Path.empty()) { |
1083 | if (llvm::sys::path::parent_path(path: Path).empty()) |
1084 | Path = GetProgramPath(Name: A->getValue()); |
1085 | if (llvm::sys::fs::can_execute(Path)) { |
1086 | if (LinkerIsLLD) |
1087 | *LinkerIsLLD = UseLinker == "lld"; |
1088 | return std::string(Path); |
1089 | } |
1090 | } |
1091 | getDriver().Diag(diag::DiagID: err_drv_invalid_linker_name) << A->getAsString(Args); |
1092 | return GetProgramPath(Name: getDefaultLinker()); |
1093 | } |
1094 | // If we're passed -fuse-ld= with no argument, or with the argument ld, |
1095 | // then use whatever the default system linker is. |
1096 | if (UseLinker.empty() || UseLinker == "ld") { |
1097 | const char *DefaultLinker = getDefaultLinker(); |
1098 | if (llvm::sys::path::is_absolute(path: DefaultLinker)) |
1099 | return std::string(DefaultLinker); |
1100 | else |
1101 | return GetProgramPath(Name: DefaultLinker); |
1102 | } |
1103 | |
1104 | // Extending -fuse-ld= to an absolute or relative path is unexpected. Checking |
1105 | // for the linker flavor is brittle. In addition, prepending "ld." or "ld64." |
1106 | // to a relative path is surprising. This is more complex due to priorities |
1107 | // among -B, COMPILER_PATH and PATH. --ld-path= should be used instead. |
1108 | if (UseLinker.contains('/')) |
1109 | getDriver().Diag(diag::warn_drv_fuse_ld_path); |
1110 | |
1111 | if (llvm::sys::path::is_absolute(path: UseLinker)) { |
1112 | // If we're passed what looks like an absolute path, don't attempt to |
1113 | // second-guess that. |
1114 | if (llvm::sys::fs::can_execute(Path: UseLinker)) |
1115 | return std::string(UseLinker); |
1116 | } else { |
1117 | llvm::SmallString<8> LinkerName; |
1118 | if (Triple.isOSDarwin()) |
1119 | LinkerName.append(RHS: "ld64."); |
1120 | else |
1121 | LinkerName.append(RHS: "ld."); |
1122 | LinkerName.append(RHS: UseLinker); |
1123 | |
1124 | std::string LinkerPath(GetProgramPath(Name: LinkerName.c_str())); |
1125 | if (llvm::sys::fs::can_execute(Path: LinkerPath)) { |
1126 | if (LinkerIsLLD) |
1127 | *LinkerIsLLD = UseLinker == "lld"; |
1128 | return LinkerPath; |
1129 | } |
1130 | } |
1131 | |
1132 | if (A) |
1133 | getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args); |
1134 | |
1135 | return GetProgramPath(Name: getDefaultLinker()); |
1136 | } |
1137 | |
1138 | std::string ToolChain::GetStaticLibToolPath() const { |
1139 | // TODO: Add support for static lib archiving on Windows |
1140 | if (Triple.isOSDarwin()) |
1141 | return GetProgramPath(Name: "libtool"); |
1142 | return GetProgramPath(Name: "llvm-ar"); |
1143 | } |
1144 | |
1145 | types::ID ToolChain::LookupTypeForExtension(StringRef Ext) const { |
1146 | types::ID id = types::lookupTypeForExtension(Ext); |
1147 | |
1148 | // Flang always runs the preprocessor and has no notion of "preprocessed |
1149 | // fortran". Here, TY_PP_Fortran is coerced to TY_Fortran to avoid treating |
1150 | // them differently. |
1151 | if (D.IsFlangMode() && id == types::TY_PP_Fortran) |
1152 | id = types::TY_Fortran; |
1153 | |
1154 | return id; |
1155 | } |
1156 | |
1157 | bool ToolChain::HasNativeLLVMSupport() const { |
1158 | return false; |
1159 | } |
1160 | |
1161 | bool ToolChain::isCrossCompiling() const { |
1162 | llvm::Triple HostTriple(LLVM_HOST_TRIPLE); |
1163 | switch (HostTriple.getArch()) { |
1164 | // The A32/T32/T16 instruction sets are not separate architectures in this |
1165 | // context. |
1166 | case llvm::Triple::arm: |
1167 | case llvm::Triple::armeb: |
1168 | case llvm::Triple::thumb: |
1169 | case llvm::Triple::thumbeb: |
1170 | return getArch() != llvm::Triple::arm && getArch() != llvm::Triple::thumb && |
1171 | getArch() != llvm::Triple::armeb && getArch() != llvm::Triple::thumbeb; |
1172 | default: |
1173 | return HostTriple.getArch() != getArch(); |
1174 | } |
1175 | } |
1176 | |
1177 | ObjCRuntime ToolChain::getDefaultObjCRuntime(bool isNonFragile) const { |
1178 | return ObjCRuntime(isNonFragile ? ObjCRuntime::GNUstep : ObjCRuntime::GCC, |
1179 | VersionTuple()); |
1180 | } |
1181 | |
1182 | llvm::ExceptionHandling |
1183 | ToolChain::GetExceptionModel(const llvm::opt::ArgList &Args) const { |
1184 | return llvm::ExceptionHandling::None; |
1185 | } |
1186 | |
1187 | bool ToolChain::isThreadModelSupported(const StringRef Model) const { |
1188 | if (Model == "single") { |
1189 | // FIXME: 'single' is only supported on ARM and WebAssembly so far. |
1190 | return Triple.getArch() == llvm::Triple::arm || |
1191 | Triple.getArch() == llvm::Triple::armeb || |
1192 | Triple.getArch() == llvm::Triple::thumb || |
1193 | Triple.getArch() == llvm::Triple::thumbeb || Triple.isWasm(); |
1194 | } else if (Model == "posix") |
1195 | return true; |
1196 | |
1197 | return false; |
1198 | } |
1199 | |
1200 | std::string ToolChain::ComputeLLVMTriple(const ArgList &Args, |
1201 | types::ID InputType) const { |
1202 | switch (getTriple().getArch()) { |
1203 | default: |
1204 | return getTripleString(); |
1205 | |
1206 | case llvm::Triple::x86_64: { |
1207 | llvm::Triple Triple = getTriple(); |
1208 | if (!Triple.isOSBinFormatMachO()) |
1209 | return getTripleString(); |
1210 | |
1211 | if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) { |
1212 | // x86_64h goes in the triple. Other -march options just use the |
1213 | // vanilla triple we already have. |
1214 | StringRef MArch = A->getValue(); |
1215 | if (MArch == "x86_64h") |
1216 | Triple.setArchName(MArch); |
1217 | } |
1218 | return Triple.getTriple(); |
1219 | } |
1220 | case llvm::Triple::aarch64: { |
1221 | llvm::Triple Triple = getTriple(); |
1222 | tools::aarch64::setPAuthABIInTriple(D: getDriver(), Args, triple&: Triple); |
1223 | if (!Triple.isOSBinFormatMachO()) |
1224 | return Triple.getTriple(); |
1225 | |
1226 | if (Triple.isArm64e()) |
1227 | return Triple.getTriple(); |
1228 | |
1229 | // FIXME: older versions of ld64 expect the "arm64" component in the actual |
1230 | // triple string and query it to determine whether an LTO file can be |
1231 | // handled. Remove this when we don't care any more. |
1232 | Triple.setArchName("arm64"); |
1233 | return Triple.getTriple(); |
1234 | } |
1235 | case llvm::Triple::aarch64_32: |
1236 | return getTripleString(); |
1237 | case llvm::Triple::amdgcn: { |
1238 | llvm::Triple Triple = getTriple(); |
1239 | if (Args.getLastArgValue(options::OPT_mcpu_EQ) == "amdgcnspirv") |
1240 | Triple.setArch(Kind: llvm::Triple::ArchType::spirv64); |
1241 | return Triple.getTriple(); |
1242 | } |
1243 | case llvm::Triple::arm: |
1244 | case llvm::Triple::armeb: |
1245 | case llvm::Triple::thumb: |
1246 | case llvm::Triple::thumbeb: { |
1247 | llvm::Triple Triple = getTriple(); |
1248 | tools::arm::setArchNameInTriple(D: getDriver(), Args, InputType, Triple); |
1249 | tools::arm::setFloatABIInTriple(D: getDriver(), Args, triple&: Triple); |
1250 | return Triple.getTriple(); |
1251 | } |
1252 | } |
1253 | } |
1254 | |
1255 | std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args, |
1256 | types::ID InputType) const { |
1257 | return ComputeLLVMTriple(Args, InputType); |
1258 | } |
1259 | |
1260 | std::string ToolChain::computeSysRoot() const { |
1261 | return D.SysRoot; |
1262 | } |
1263 | |
1264 | void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs, |
1265 | ArgStringList &CC1Args) const { |
1266 | // Each toolchain should provide the appropriate include flags. |
1267 | } |
1268 | |
1269 | void ToolChain::addClangTargetOptions( |
1270 | const ArgList &DriverArgs, ArgStringList &CC1Args, |
1271 | Action::OffloadKind DeviceOffloadKind) const {} |
1272 | |
1273 | void ToolChain::addClangCC1ASTargetOptions(const ArgList &Args, |
1274 | ArgStringList &CC1ASArgs) const {} |
1275 | |
1276 | void ToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {} |
1277 | |
1278 | void ToolChain::addProfileRTLibs(const llvm::opt::ArgList &Args, |
1279 | llvm::opt::ArgStringList &CmdArgs) const { |
1280 | if (!needsProfileRT(Args) && !needsGCovInstrumentation(Args)) |
1281 | return; |
1282 | |
1283 | CmdArgs.push_back(Elt: getCompilerRTArgString(Args, Component: "profile")); |
1284 | } |
1285 | |
1286 | ToolChain::RuntimeLibType ToolChain::GetRuntimeLibType( |
1287 | const ArgList &Args) const { |
1288 | if (runtimeLibType) |
1289 | return *runtimeLibType; |
1290 | |
1291 | const Arg* A = Args.getLastArg(options::OPT_rtlib_EQ); |
1292 | StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_RTLIB; |
1293 | |
1294 | // Only use "platform" in tests to override CLANG_DEFAULT_RTLIB! |
1295 | if (LibName == "compiler-rt") |
1296 | runtimeLibType = ToolChain::RLT_CompilerRT; |
1297 | else if (LibName == "libgcc") |
1298 | runtimeLibType = ToolChain::RLT_Libgcc; |
1299 | else if (LibName == "platform") |
1300 | runtimeLibType = GetDefaultRuntimeLibType(); |
1301 | else { |
1302 | if (A) |
1303 | getDriver().Diag(diag::err_drv_invalid_rtlib_name) |
1304 | << A->getAsString(Args); |
1305 | |
1306 | runtimeLibType = GetDefaultRuntimeLibType(); |
1307 | } |
1308 | |
1309 | return *runtimeLibType; |
1310 | } |
1311 | |
1312 | ToolChain::UnwindLibType ToolChain::GetUnwindLibType( |
1313 | const ArgList &Args) const { |
1314 | if (unwindLibType) |
1315 | return *unwindLibType; |
1316 | |
1317 | const Arg *A = Args.getLastArg(options::OPT_unwindlib_EQ); |
1318 | StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_UNWINDLIB; |
1319 | |
1320 | if (LibName == "none") |
1321 | unwindLibType = ToolChain::UNW_None; |
1322 | else if (LibName == "platform"|| LibName == "") { |
1323 | ToolChain::RuntimeLibType RtLibType = GetRuntimeLibType(Args); |
1324 | if (RtLibType == ToolChain::RLT_CompilerRT) { |
1325 | if (getTriple().isAndroid() || getTriple().isOSAIX()) |
1326 | unwindLibType = ToolChain::UNW_CompilerRT; |
1327 | else |
1328 | unwindLibType = ToolChain::UNW_None; |
1329 | } else if (RtLibType == ToolChain::RLT_Libgcc) |
1330 | unwindLibType = ToolChain::UNW_Libgcc; |
1331 | } else if (LibName == "libunwind") { |
1332 | if (GetRuntimeLibType(Args) == RLT_Libgcc) |
1333 | getDriver().Diag(diag::err_drv_incompatible_unwindlib); |
1334 | unwindLibType = ToolChain::UNW_CompilerRT; |
1335 | } else if (LibName == "libgcc") |
1336 | unwindLibType = ToolChain::UNW_Libgcc; |
1337 | else { |
1338 | if (A) |
1339 | getDriver().Diag(diag::err_drv_invalid_unwindlib_name) |
1340 | << A->getAsString(Args); |
1341 | |
1342 | unwindLibType = GetDefaultUnwindLibType(); |
1343 | } |
1344 | |
1345 | return *unwindLibType; |
1346 | } |
1347 | |
1348 | ToolChain::CXXStdlibType ToolChain::GetCXXStdlibType(const ArgList &Args) const{ |
1349 | if (cxxStdlibType) |
1350 | return *cxxStdlibType; |
1351 | |
1352 | const Arg *A = Args.getLastArg(options::OPT_stdlib_EQ); |
1353 | StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_CXX_STDLIB; |
1354 | |
1355 | // Only use "platform" in tests to override CLANG_DEFAULT_CXX_STDLIB! |
1356 | if (LibName == "libc++") |
1357 | cxxStdlibType = ToolChain::CST_Libcxx; |
1358 | else if (LibName == "libstdc++") |
1359 | cxxStdlibType = ToolChain::CST_Libstdcxx; |
1360 | else if (LibName == "platform") |
1361 | cxxStdlibType = GetDefaultCXXStdlibType(); |
1362 | else { |
1363 | if (A) |
1364 | getDriver().Diag(diag::err_drv_invalid_stdlib_name) |
1365 | << A->getAsString(Args); |
1366 | |
1367 | cxxStdlibType = GetDefaultCXXStdlibType(); |
1368 | } |
1369 | |
1370 | return *cxxStdlibType; |
1371 | } |
1372 | |
1373 | /// Utility function to add a system framework directory to CC1 arguments. |
1374 | void ToolChain::addSystemFrameworkInclude(const llvm::opt::ArgList &DriverArgs, |
1375 | llvm::opt::ArgStringList &CC1Args, |
1376 | const Twine &Path) { |
1377 | CC1Args.push_back(Elt: "-internal-iframework"); |
1378 | CC1Args.push_back(Elt: DriverArgs.MakeArgString(Str: Path)); |
1379 | } |
1380 | |
1381 | /// Utility function to add a system include directory to CC1 arguments. |
1382 | void ToolChain::addSystemInclude(const ArgList &DriverArgs, |
1383 | ArgStringList &CC1Args, const Twine &Path) { |
1384 | CC1Args.push_back(Elt: "-internal-isystem"); |
1385 | CC1Args.push_back(Elt: DriverArgs.MakeArgString(Str: Path)); |
1386 | } |
1387 | |
1388 | /// Utility function to add a system include directory with extern "C" |
1389 | /// semantics to CC1 arguments. |
1390 | /// |
1391 | /// Note that this should be used rarely, and only for directories that |
1392 | /// historically and for legacy reasons are treated as having implicit extern |
1393 | /// "C" semantics. These semantics are *ignored* by and large today, but its |
1394 | /// important to preserve the preprocessor changes resulting from the |
1395 | /// classification. |
1396 | void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs, |
1397 | ArgStringList &CC1Args, |
1398 | const Twine &Path) { |
1399 | CC1Args.push_back(Elt: "-internal-externc-isystem"); |
1400 | CC1Args.push_back(Elt: DriverArgs.MakeArgString(Str: Path)); |
1401 | } |
1402 | |
1403 | void ToolChain::addExternCSystemIncludeIfExists(const ArgList &DriverArgs, |
1404 | ArgStringList &CC1Args, |
1405 | const Twine &Path) { |
1406 | if (llvm::sys::fs::exists(Path)) |
1407 | addExternCSystemInclude(DriverArgs, CC1Args, Path); |
1408 | } |
1409 | |
1410 | /// Utility function to add a list of system framework directories to CC1. |
1411 | void ToolChain::addSystemFrameworkIncludes(const ArgList &DriverArgs, |
1412 | ArgStringList &CC1Args, |
1413 | ArrayRef<StringRef> Paths) { |
1414 | for (const auto &Path : Paths) { |
1415 | CC1Args.push_back(Elt: "-internal-iframework"); |
1416 | CC1Args.push_back(Elt: DriverArgs.MakeArgString(Str: Path)); |
1417 | } |
1418 | } |
1419 | |
1420 | /// Utility function to add a list of system include directories to CC1. |
1421 | void ToolChain::addSystemIncludes(const ArgList &DriverArgs, |
1422 | ArgStringList &CC1Args, |
1423 | ArrayRef<StringRef> Paths) { |
1424 | for (const auto &Path : Paths) { |
1425 | CC1Args.push_back(Elt: "-internal-isystem"); |
1426 | CC1Args.push_back(Elt: DriverArgs.MakeArgString(Str: Path)); |
1427 | } |
1428 | } |
1429 | |
1430 | std::string ToolChain::concat(StringRef Path, const Twine &A, const Twine &B, |
1431 | const Twine &C, const Twine &D) { |
1432 | SmallString<128> Result(Path); |
1433 | llvm::sys::path::append(path&: Result, style: llvm::sys::path::Style::posix, a: A, b: B, c: C, d: D); |
1434 | return std::string(Result); |
1435 | } |
1436 | |
1437 | std::string ToolChain::detectLibcxxVersion(StringRef IncludePath) const { |
1438 | std::error_code EC; |
1439 | int MaxVersion = 0; |
1440 | std::string MaxVersionString; |
1441 | SmallString<128> Path(IncludePath); |
1442 | llvm::sys::path::append(path&: Path, a: "c++"); |
1443 | for (llvm::vfs::directory_iterator LI = getVFS().dir_begin(Dir: Path, EC), LE; |
1444 | !EC && LI != LE; LI = LI.increment(EC)) { |
1445 | StringRef VersionText = llvm::sys::path::filename(path: LI->path()); |
1446 | int Version; |
1447 | if (VersionText[0] == 'v' && |
1448 | !VersionText.substr(Start: 1).getAsInteger(Radix: 10, Result&: Version)) { |
1449 | if (Version > MaxVersion) { |
1450 | MaxVersion = Version; |
1451 | MaxVersionString = std::string(VersionText); |
1452 | } |
1453 | } |
1454 | } |
1455 | if (!MaxVersion) |
1456 | return ""; |
1457 | return MaxVersionString; |
1458 | } |
1459 | |
1460 | void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs, |
1461 | ArgStringList &CC1Args) const { |
1462 | // Header search paths should be handled by each of the subclasses. |
1463 | // Historically, they have not been, and instead have been handled inside of |
1464 | // the CC1-layer frontend. As the logic is hoisted out, this generic function |
1465 | // will slowly stop being called. |
1466 | // |
1467 | // While it is being called, replicate a bit of a hack to propagate the |
1468 | // '-stdlib=' flag down to CC1 so that it can in turn customize the C++ |
1469 | // header search paths with it. Once all systems are overriding this |
1470 | // function, the CC1 flag and this line can be removed. |
1471 | DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ); |
1472 | } |
1473 | |
1474 | void ToolChain::AddClangCXXStdlibIsystemArgs( |
1475 | const llvm::opt::ArgList &DriverArgs, |
1476 | llvm::opt::ArgStringList &CC1Args) const { |
1477 | DriverArgs.ClaimAllArgs(options::OPT_stdlibxx_isystem); |
1478 | // This intentionally only looks at -nostdinc++, and not -nostdinc or |
1479 | // -nostdlibinc. The purpose of -stdlib++-isystem is to support toolchain |
1480 | // setups with non-standard search logic for the C++ headers, while still |
1481 | // allowing users of the toolchain to bring their own C++ headers. Such a |
1482 | // toolchain likely also has non-standard search logic for the C headers and |
1483 | // uses -nostdinc to suppress the default logic, but -stdlib++-isystem should |
1484 | // still work in that case and only be suppressed by an explicit -nostdinc++ |
1485 | // in a project using the toolchain. |
1486 | if (!DriverArgs.hasArg(options::OPT_nostdincxx)) |
1487 | for (const auto &P : |
1488 | DriverArgs.getAllArgValues(options::OPT_stdlibxx_isystem)) |
1489 | addSystemInclude(DriverArgs, CC1Args, P); |
1490 | } |
1491 | |
1492 | bool ToolChain::ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const { |
1493 | return getDriver().CCCIsCXX() && |
1494 | !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs, |
1495 | options::OPT_nostdlibxx); |
1496 | } |
1497 | |
1498 | void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args, |
1499 | ArgStringList &CmdArgs) const { |
1500 | assert(!Args.hasArg(options::OPT_nostdlibxx) && |
1501 | "should not have called this"); |
1502 | CXXStdlibType Type = GetCXXStdlibType(Args); |
1503 | |
1504 | switch (Type) { |
1505 | case ToolChain::CST_Libcxx: |
1506 | CmdArgs.push_back(Elt: "-lc++"); |
1507 | if (Args.hasArg(options::OPT_fexperimental_library)) |
1508 | CmdArgs.push_back(Elt: "-lc++experimental"); |
1509 | break; |
1510 | |
1511 | case ToolChain::CST_Libstdcxx: |
1512 | CmdArgs.push_back(Elt: "-lstdc++"); |
1513 | break; |
1514 | } |
1515 | } |
1516 | |
1517 | void ToolChain::AddFilePathLibArgs(const ArgList &Args, |
1518 | ArgStringList &CmdArgs) const { |
1519 | for (const auto &LibPath : getFilePaths()) |
1520 | if(LibPath.length() > 0) |
1521 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: StringRef("-L") + LibPath)); |
1522 | } |
1523 | |
1524 | void ToolChain::AddCCKextLibArgs(const ArgList &Args, |
1525 | ArgStringList &CmdArgs) const { |
1526 | CmdArgs.push_back(Elt: "-lcc_kext"); |
1527 | } |
1528 | |
1529 | bool ToolChain::isFastMathRuntimeAvailable(const ArgList &Args, |
1530 | std::string &Path) const { |
1531 | // Don't implicitly link in mode-changing libraries in a shared library, since |
1532 | // this can have very deleterious effects. See the various links from |
1533 | // https://github.com/llvm/llvm-project/issues/57589 for more information. |
1534 | bool Default = !Args.hasArgNoClaim(options::OPT_shared); |
1535 | |
1536 | // Do not check for -fno-fast-math or -fno-unsafe-math when -Ofast passed |
1537 | // (to keep the linker options consistent with gcc and clang itself). |
1538 | if (Default && !isOptimizationLevelFast(Args)) { |
1539 | // Check if -ffast-math or -funsafe-math. |
1540 | Arg *A = Args.getLastArg( |
1541 | options::OPT_ffast_math, options::OPT_fno_fast_math, |
1542 | options::OPT_funsafe_math_optimizations, |
1543 | options::OPT_fno_unsafe_math_optimizations, options::OPT_ffp_model_EQ); |
1544 | |
1545 | if (!A || A->getOption().getID() == options::OPT_fno_fast_math || |
1546 | A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations) |
1547 | Default = false; |
1548 | if (A && A->getOption().getID() == options::OPT_ffp_model_EQ) { |
1549 | StringRef Model = A->getValue(); |
1550 | if (Model != "fast"&& Model != "aggressive") |
1551 | Default = false; |
1552 | } |
1553 | } |
1554 | |
1555 | // Whatever decision came as a result of the above implicit settings, either |
1556 | // -mdaz-ftz or -mno-daz-ftz is capable of overriding it. |
1557 | if (!Args.hasFlag(options::OPT_mdaz_ftz, options::OPT_mno_daz_ftz, Default)) |
1558 | return false; |
1559 | |
1560 | // If crtfastmath.o exists add it to the arguments. |
1561 | Path = GetFilePath(Name: "crtfastmath.o"); |
1562 | return (Path != "crtfastmath.o"); // Not found. |
1563 | } |
1564 | |
1565 | bool ToolChain::addFastMathRuntimeIfAvailable(const ArgList &Args, |
1566 | ArgStringList &CmdArgs) const { |
1567 | std::string Path; |
1568 | if (isFastMathRuntimeAvailable(Args, Path)) { |
1569 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: Path)); |
1570 | return true; |
1571 | } |
1572 | |
1573 | return false; |
1574 | } |
1575 | |
1576 | Expected<SmallVector<std::string>> |
1577 | ToolChain::getSystemGPUArchs(const llvm::opt::ArgList &Args) const { |
1578 | return SmallVector<std::string>(); |
1579 | } |
1580 | |
1581 | SanitizerMask ToolChain::getSupportedSanitizers() const { |
1582 | // Return sanitizers which don't require runtime support and are not |
1583 | // platform dependent. |
1584 | |
1585 | SanitizerMask Res = |
1586 | (SanitizerKind::Undefined & ~SanitizerKind::Vptr) | |
1587 | (SanitizerKind::CFI & ~SanitizerKind::CFIICall) | |
1588 | SanitizerKind::CFICastStrict | SanitizerKind::FloatDivideByZero | |
1589 | SanitizerKind::KCFI | SanitizerKind::UnsignedIntegerOverflow | |
1590 | SanitizerKind::UnsignedShiftBase | SanitizerKind::ImplicitConversion | |
1591 | SanitizerKind::Nullability | SanitizerKind::LocalBounds; |
1592 | if (getTriple().getArch() == llvm::Triple::x86 || |
1593 | getTriple().getArch() == llvm::Triple::x86_64 || |
1594 | getTriple().getArch() == llvm::Triple::arm || |
1595 | getTriple().getArch() == llvm::Triple::thumb || getTriple().isWasm() || |
1596 | getTriple().isAArch64() || getTriple().isRISCV() || |
1597 | getTriple().isLoongArch64()) |
1598 | Res |= SanitizerKind::CFIICall; |
1599 | if (getTriple().getArch() == llvm::Triple::x86_64 || |
1600 | getTriple().isAArch64(PointerWidth: 64) || getTriple().isRISCV()) |
1601 | Res |= SanitizerKind::ShadowCallStack; |
1602 | if (getTriple().isAArch64(PointerWidth: 64)) |
1603 | Res |= SanitizerKind::MemTag; |
1604 | return Res; |
1605 | } |
1606 | |
1607 | void ToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs, |
1608 | ArgStringList &CC1Args) const {} |
1609 | |
1610 | void ToolChain::AddHIPIncludeArgs(const ArgList &DriverArgs, |
1611 | ArgStringList &CC1Args) const {} |
1612 | |
1613 | void ToolChain::addSYCLIncludeArgs(const ArgList &DriverArgs, |
1614 | ArgStringList &CC1Args) const {} |
1615 | |
1616 | llvm::SmallVector<ToolChain::BitCodeLibraryInfo, 12> |
1617 | ToolChain::getDeviceLibs(const ArgList &DriverArgs) const { |
1618 | return {}; |
1619 | } |
1620 | |
1621 | void ToolChain::AddIAMCUIncludeArgs(const ArgList &DriverArgs, |
1622 | ArgStringList &CC1Args) const {} |
1623 | |
1624 | static VersionTuple separateMSVCFullVersion(unsigned Version) { |
1625 | if (Version < 100) |
1626 | return VersionTuple(Version); |
1627 | |
1628 | if (Version < 10000) |
1629 | return VersionTuple(Version / 100, Version % 100); |
1630 | |
1631 | unsigned Build = 0, Factor = 1; |
1632 | for (; Version > 10000; Version = Version / 10, Factor = Factor * 10) |
1633 | Build = Build + (Version % 10) * Factor; |
1634 | return VersionTuple(Version / 100, Version % 100, Build); |
1635 | } |
1636 | |
1637 | VersionTuple |
1638 | ToolChain::computeMSVCVersion(const Driver *D, |
1639 | const llvm::opt::ArgList &Args) const { |
1640 | const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version); |
1641 | const Arg *MSCompatibilityVersion = |
1642 | Args.getLastArg(options::OPT_fms_compatibility_version); |
1643 | |
1644 | if (MSCVersion && MSCompatibilityVersion) { |
1645 | if (D) |
1646 | D->Diag(diag::err_drv_argument_not_allowed_with) |
1647 | << MSCVersion->getAsString(Args) |
1648 | << MSCompatibilityVersion->getAsString(Args); |
1649 | return VersionTuple(); |
1650 | } |
1651 | |
1652 | if (MSCompatibilityVersion) { |
1653 | VersionTuple MSVT; |
1654 | if (MSVT.tryParse(string: MSCompatibilityVersion->getValue())) { |
1655 | if (D) |
1656 | D->Diag(diag::err_drv_invalid_value) |
1657 | << MSCompatibilityVersion->getAsString(Args) |
1658 | << MSCompatibilityVersion->getValue(); |
1659 | } else { |
1660 | return MSVT; |
1661 | } |
1662 | } |
1663 | |
1664 | if (MSCVersion) { |
1665 | unsigned Version = 0; |
1666 | if (StringRef(MSCVersion->getValue()).getAsInteger(Radix: 10, Result&: Version)) { |
1667 | if (D) |
1668 | D->Diag(diag::err_drv_invalid_value) |
1669 | << MSCVersion->getAsString(Args) << MSCVersion->getValue(); |
1670 | } else { |
1671 | return separateMSVCFullVersion(Version); |
1672 | } |
1673 | } |
1674 | |
1675 | return VersionTuple(); |
1676 | } |
1677 | |
1678 | llvm::opt::DerivedArgList *ToolChain::TranslateOpenMPTargetArgs( |
1679 | const llvm::opt::DerivedArgList &Args, bool SameTripleAsHost, |
1680 | SmallVectorImpl<llvm::opt::Arg *> &AllocatedArgs) const { |
1681 | DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs()); |
1682 | const OptTable &Opts = getDriver().getOpts(); |
1683 | bool Modified = false; |
1684 | |
1685 | // Handle -Xopenmp-target flags |
1686 | for (auto *A : Args) { |
1687 | // Exclude flags which may only apply to the host toolchain. |
1688 | // Do not exclude flags when the host triple (AuxTriple) |
1689 | // matches the current toolchain triple. If it is not present |
1690 | // at all, target and host share a toolchain. |
1691 | if (A->getOption().matches(options::OPT_m_Group)) { |
1692 | // Pass code object version to device toolchain |
1693 | // to correctly set metadata in intermediate files. |
1694 | if (SameTripleAsHost || |
1695 | A->getOption().matches(options::OPT_mcode_object_version_EQ)) |
1696 | DAL->append(A); |
1697 | else |
1698 | Modified = true; |
1699 | continue; |
1700 | } |
1701 | |
1702 | unsigned Index; |
1703 | unsigned Prev; |
1704 | bool XOpenMPTargetNoTriple = |
1705 | A->getOption().matches(options::OPT_Xopenmp_target); |
1706 | |
1707 | if (A->getOption().matches(options::OPT_Xopenmp_target_EQ)) { |
1708 | llvm::Triple TT(getOpenMPTriple(TripleStr: A->getValue(N: 0))); |
1709 | |
1710 | // Passing device args: -Xopenmp-target=<triple> -opt=val. |
1711 | if (TT.getTriple() == getTripleString()) |
1712 | Index = Args.getBaseArgs().MakeIndex(String0: A->getValue(N: 1)); |
1713 | else |
1714 | continue; |
1715 | } else if (XOpenMPTargetNoTriple) { |
1716 | // Passing device args: -Xopenmp-target -opt=val. |
1717 | Index = Args.getBaseArgs().MakeIndex(String0: A->getValue(N: 0)); |
1718 | } else { |
1719 | DAL->append(A); |
1720 | continue; |
1721 | } |
1722 | |
1723 | // Parse the argument to -Xopenmp-target. |
1724 | Prev = Index; |
1725 | std::unique_ptr<Arg> XOpenMPTargetArg(Opts.ParseOneArg(Args, Index)); |
1726 | if (!XOpenMPTargetArg || Index > Prev + 1) { |
1727 | if (!A->isClaimed()) { |
1728 | getDriver().Diag(diag::err_drv_invalid_Xopenmp_target_with_args) |
1729 | << A->getAsString(Args); |
1730 | } |
1731 | continue; |
1732 | } |
1733 | if (XOpenMPTargetNoTriple && XOpenMPTargetArg && |
1734 | Args.getAllArgValues(options::OPT_fopenmp_targets_EQ).size() != 1) { |
1735 | getDriver().Diag(diag::err_drv_Xopenmp_target_missing_triple); |
1736 | continue; |
1737 | } |
1738 | XOpenMPTargetArg->setBaseArg(A); |
1739 | A = XOpenMPTargetArg.release(); |
1740 | AllocatedArgs.push_back(Elt: A); |
1741 | DAL->append(A); |
1742 | Modified = true; |
1743 | } |
1744 | |
1745 | if (Modified) |
1746 | return DAL; |
1747 | |
1748 | delete DAL; |
1749 | return nullptr; |
1750 | } |
1751 | |
1752 | // TODO: Currently argument values separated by space e.g. |
1753 | // -Xclang -mframe-pointer=no cannot be passed by -Xarch_. This should be |
1754 | // fixed. |
1755 | void ToolChain::TranslateXarchArgs( |
1756 | const llvm::opt::DerivedArgList &Args, llvm::opt::Arg *&A, |
1757 | llvm::opt::DerivedArgList *DAL, |
1758 | SmallVectorImpl<llvm::opt::Arg *> *AllocatedArgs) const { |
1759 | const OptTable &Opts = getDriver().getOpts(); |
1760 | unsigned ValuePos = 1; |
1761 | if (A->getOption().matches(options::OPT_Xarch_device) || |
1762 | A->getOption().matches(options::OPT_Xarch_host)) |
1763 | ValuePos = 0; |
1764 | |
1765 | const InputArgList &BaseArgs = Args.getBaseArgs(); |
1766 | unsigned Index = BaseArgs.MakeIndex(String0: A->getValue(N: ValuePos)); |
1767 | unsigned Prev = Index; |
1768 | std::unique_ptr<llvm::opt::Arg> XarchArg(Opts.ParseOneArg( |
1769 | Args, Index, VisibilityMask: llvm::opt::Visibility(clang::driver::options::ClangOption))); |
1770 | |
1771 | // If the argument parsing failed or more than one argument was |
1772 | // consumed, the -Xarch_ argument's parameter tried to consume |
1773 | // extra arguments. Emit an error and ignore. |
1774 | // |
1775 | // We also want to disallow any options which would alter the |
1776 | // driver behavior; that isn't going to work in our model. We |
1777 | // use options::NoXarchOption to control this. |
1778 | if (!XarchArg || Index > Prev + 1) { |
1779 | getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args) |
1780 | << A->getAsString(Args); |
1781 | return; |
1782 | } else if (XarchArg->getOption().hasFlag(Val: options::NoXarchOption)) { |
1783 | auto &Diags = getDriver().getDiags(); |
1784 | unsigned DiagID = |
1785 | Diags.getCustomDiagID(L: DiagnosticsEngine::Error, |
1786 | FormatString: "invalid Xarch argument: '%0', not all driver " |
1787 | "options can be forwared via Xarch argument"); |
1788 | Diags.Report(DiagID) << A->getAsString(Args); |
1789 | return; |
1790 | } |
1791 | |
1792 | XarchArg->setBaseArg(A); |
1793 | A = XarchArg.release(); |
1794 | |
1795 | // Linker input arguments require custom handling. The problem is that we |
1796 | // have already constructed the phase actions, so we can not treat them as |
1797 | // "input arguments". |
1798 | if (A->getOption().hasFlag(Val: options::LinkerInput)) { |
1799 | // Convert the argument into individual Zlinker_input_args. Need to do this |
1800 | // manually to avoid memory leaks with the allocated arguments. |
1801 | for (const char *Value : A->getValues()) { |
1802 | auto Opt = Opts.getOption(options::OPT_Zlinker_input); |
1803 | unsigned Index = BaseArgs.MakeIndex(Opt.getName(), Value); |
1804 | auto NewArg = |
1805 | new Arg(Opt, BaseArgs.MakeArgString(Str: Opt.getPrefix() + Opt.getName()), |
1806 | Index, BaseArgs.getArgString(Index: Index + 1), A); |
1807 | |
1808 | DAL->append(A: NewArg); |
1809 | if (!AllocatedArgs) |
1810 | DAL->AddSynthesizedArg(A: NewArg); |
1811 | else |
1812 | AllocatedArgs->push_back(Elt: NewArg); |
1813 | } |
1814 | } |
1815 | |
1816 | if (!AllocatedArgs) |
1817 | DAL->AddSynthesizedArg(A); |
1818 | else |
1819 | AllocatedArgs->push_back(Elt: A); |
1820 | } |
1821 | |
1822 | llvm::opt::DerivedArgList *ToolChain::TranslateXarchArgs( |
1823 | const llvm::opt::DerivedArgList &Args, StringRef BoundArch, |
1824 | Action::OffloadKind OFK, |
1825 | SmallVectorImpl<llvm::opt::Arg *> *AllocatedArgs) const { |
1826 | DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs()); |
1827 | bool Modified = false; |
1828 | |
1829 | bool IsDevice = OFK != Action::OFK_None && OFK != Action::OFK_Host; |
1830 | for (Arg *A : Args) { |
1831 | bool NeedTrans = false; |
1832 | bool Skip = false; |
1833 | if (A->getOption().matches(options::OPT_Xarch_device)) { |
1834 | NeedTrans = IsDevice; |
1835 | Skip = !IsDevice; |
1836 | } else if (A->getOption().matches(options::OPT_Xarch_host)) { |
1837 | NeedTrans = !IsDevice; |
1838 | Skip = IsDevice; |
1839 | } else if (A->getOption().matches(options::OPT_Xarch__)) { |
1840 | NeedTrans = A->getValue() == getArchName() || |
1841 | (!BoundArch.empty() && A->getValue() == BoundArch); |
1842 | Skip = !NeedTrans; |
1843 | } |
1844 | if (NeedTrans || Skip) |
1845 | Modified = true; |
1846 | if (NeedTrans) { |
1847 | A->claim(); |
1848 | TranslateXarchArgs(Args, A, DAL, AllocatedArgs); |
1849 | } |
1850 | if (!Skip) |
1851 | DAL->append(A); |
1852 | } |
1853 | |
1854 | if (Modified) |
1855 | return DAL; |
1856 | |
1857 | delete DAL; |
1858 | return nullptr; |
1859 | } |
1860 |
Definitions
- GetRTTIArgument
- CalculateRTTIMode
- CalculateExceptionsMode
- ToolChain
- executeToolChainProgram
- setTripleEnvironment
- ~ToolChain
- getVFS
- useIntegratedAs
- useIntegratedBackend
- useRelaxRelocations
- defaultToIEEELongDouble
- processMultilibCustomFlags
- getAArch64MultilibFlags
- getARMMultilibFlags
- getRISCVMultilibFlags
- getMultilibFlags
- getSanitizerArgs
- getXRayArgs
- DriverSuffix
- FindDriverSuffix
- normalizeProgramName
- parseDriverSuffix
- getTargetAndModeFromProgramName
- getDefaultUniversalArchName
- getInputFilename
- getDefaultUnwindTableLevel
- getClang
- getFlang
- buildAssembler
- buildLinker
- buildStaticLibTool
- getAssemble
- getClangAs
- getLink
- getStaticLibTool
- getIfsMerge
- getOffloadBundler
- getOffloadPackager
- getLinkerWrapper
- getTool
- getArchNameForCompilerRTLib
- getOSLibName
- getCompilerRTPath
- getCompilerRTBasename
- buildCompilerRTBasename
- getCompilerRT
- getCompilerRTArgString
- addFortranRuntimeLibs
- addFortranRuntimeLibraryPath
- addFlangRTLibPath
- getFallbackAndroidTargetPath
- getTripleWithoutOSVersion
- getTargetSubDirPath
- getRuntimePath
- getStdlibPath
- getStdlibIncludePath
- getArchSpecificLibPaths
- needsProfileRT
- needsGCovInstrumentation
- SelectTool
- GetFilePath
- GetProgramPath
- GetLinkerPath
- GetStaticLibToolPath
- LookupTypeForExtension
- HasNativeLLVMSupport
- isCrossCompiling
- getDefaultObjCRuntime
- GetExceptionModel
- isThreadModelSupported
- ComputeLLVMTriple
- ComputeEffectiveClangTriple
- computeSysRoot
- AddClangSystemIncludeArgs
- addClangTargetOptions
- addClangCC1ASTargetOptions
- addClangWarningOptions
- addProfileRTLibs
- GetRuntimeLibType
- GetUnwindLibType
- GetCXXStdlibType
- addSystemFrameworkInclude
- addSystemInclude
- addExternCSystemInclude
- addExternCSystemIncludeIfExists
- addSystemFrameworkIncludes
- addSystemIncludes
- concat
- detectLibcxxVersion
- AddClangCXXStdlibIncludeArgs
- AddClangCXXStdlibIsystemArgs
- ShouldLinkCXXStdlib
- AddCXXStdlibLibArgs
- AddFilePathLibArgs
- AddCCKextLibArgs
- isFastMathRuntimeAvailable
- addFastMathRuntimeIfAvailable
- getSystemGPUArchs
- getSupportedSanitizers
- AddCudaIncludeArgs
- AddHIPIncludeArgs
- addSYCLIncludeArgs
- getDeviceLibs
- AddIAMCUIncludeArgs
- separateMSVCFullVersion
- computeMSVCVersion
- TranslateOpenMPTargetArgs
- TranslateXarchArgs
Update your C++ knowledge – Modern C++11/14/17 Training
Find out more