1//===--- Driver.cpp - Clang GCC Compatible Driver -------------------------===//
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/Driver.h"
10#include "ToolChains/AIX.h"
11#include "ToolChains/AMDGPU.h"
12#include "ToolChains/AVR.h"
13#include "ToolChains/Arch/RISCV.h"
14#include "ToolChains/BareMetal.h"
15#include "ToolChains/CSKYToolChain.h"
16#include "ToolChains/Clang.h"
17#include "ToolChains/CrossWindows.h"
18#include "ToolChains/Cuda.h"
19#include "ToolChains/Cygwin.h"
20#include "ToolChains/Darwin.h"
21#include "ToolChains/DragonFly.h"
22#include "ToolChains/FreeBSD.h"
23#include "ToolChains/Fuchsia.h"
24#include "ToolChains/Gnu.h"
25#include "ToolChains/HIPAMD.h"
26#include "ToolChains/HIPSPV.h"
27#include "ToolChains/HLSL.h"
28#include "ToolChains/Haiku.h"
29#include "ToolChains/Hexagon.h"
30#include "ToolChains/Hurd.h"
31#include "ToolChains/LFILinux.h"
32#include "ToolChains/Lanai.h"
33#include "ToolChains/Linux.h"
34#include "ToolChains/MSP430.h"
35#include "ToolChains/MSVC.h"
36#include "ToolChains/Managarm.h"
37#include "ToolChains/MinGW.h"
38#include "ToolChains/MipsLinux.h"
39#include "ToolChains/NetBSD.h"
40#include "ToolChains/OHOS.h"
41#include "ToolChains/OpenBSD.h"
42#include "ToolChains/PPCFreeBSD.h"
43#include "ToolChains/PPCLinux.h"
44#include "ToolChains/PS4CPU.h"
45#include "ToolChains/SPIRV.h"
46#include "ToolChains/SPIRVOpenMP.h"
47#include "ToolChains/SYCL.h"
48#include "ToolChains/Serenity.h"
49#include "ToolChains/Solaris.h"
50#include "ToolChains/TCE.h"
51#include "ToolChains/UEFI.h"
52#include "ToolChains/VEToolchain.h"
53#include "ToolChains/WebAssembly.h"
54#include "ToolChains/XCore.h"
55#include "ToolChains/ZOS.h"
56#include "clang/Basic/DiagnosticDriver.h"
57#include "clang/Basic/TargetID.h"
58#include "clang/Basic/Version.h"
59#include "clang/Config/config.h"
60#include "clang/Driver/Action.h"
61#include "clang/Driver/CommonArgs.h"
62#include "clang/Driver/Compilation.h"
63#include "clang/Driver/InputInfo.h"
64#include "clang/Driver/Job.h"
65#include "clang/Driver/ModulesDriver.h"
66#include "clang/Driver/Phases.h"
67#include "clang/Driver/SanitizerArgs.h"
68#include "clang/Driver/Tool.h"
69#include "clang/Driver/ToolChain.h"
70#include "clang/Driver/Types.h"
71#include "clang/Options/OptionUtils.h"
72#include "clang/Options/Options.h"
73#include "clang/ScalableStaticAnalysis/Core/Serialization/SerializationFormatRegistry.h"
74#include "clang/ScalableStaticAnalysis/Core/TUSummary/ExtractorRegistry.h"
75#include "clang/ScalableStaticAnalysis/SSAFForceLinker.h" // IWYU pragma: keep
76#include "llvm/ADT/ArrayRef.h"
77#include "llvm/ADT/STLExtras.h"
78#include "llvm/ADT/ScopeExit.h"
79#include "llvm/ADT/SmallSet.h"
80#include "llvm/ADT/SmallVector.h"
81#include "llvm/ADT/StringExtras.h"
82#include "llvm/ADT/StringRef.h"
83#include "llvm/ADT/StringSet.h"
84#include "llvm/ADT/StringSwitch.h"
85#include "llvm/Config/llvm-config.h"
86#include "llvm/MC/TargetRegistry.h"
87#include "llvm/Option/Arg.h"
88#include "llvm/Option/ArgList.h"
89#include "llvm/Option/OptSpecifier.h"
90#include "llvm/Option/OptTable.h"
91#include "llvm/Option/Option.h"
92#include "llvm/Support/CommandLine.h"
93#include "llvm/Support/ErrorHandling.h"
94#include "llvm/Support/ExitCodes.h"
95#include "llvm/Support/FileSystem.h"
96#include "llvm/Support/FileUtilities.h"
97#include "llvm/Support/FormatVariadic.h"
98#include "llvm/Support/IOSandbox.h"
99#include "llvm/Support/JSON.h"
100#include "llvm/Support/MD5.h"
101#include "llvm/Support/MemoryBuffer.h"
102#include "llvm/Support/Path.h"
103#include "llvm/Support/PrettyStackTrace.h"
104#include "llvm/Support/Process.h"
105#include "llvm/Support/Program.h"
106#include "llvm/Support/Regex.h"
107#include "llvm/Support/StringSaver.h"
108#include "llvm/Support/TarWriter.h"
109#include "llvm/Support/VirtualFileSystem.h"
110#include "llvm/Support/raw_ostream.h"
111#include "llvm/TargetParser/Host.h"
112#include "llvm/TargetParser/RISCVISAInfo.h"
113#include <cstdlib> // ::getenv
114#include <map>
115#include <memory>
116#include <optional>
117#include <set>
118#include <string>
119#include <utility>
120#if LLVM_ON_UNIX
121#include <unistd.h> // getpid
122#endif
123
124using namespace clang::driver;
125using namespace clang;
126using namespace llvm::opt;
127
128template <typename F> static bool usesInput(const ArgList &Args, F &&Fn) {
129 return llvm::any_of(Args, [&](Arg *A) {
130 return (A->getOption().matches(ID: options::OPT_x) &&
131 Fn(types::lookupTypeForTypeSpecifier(Name: A->getValue()))) ||
132 (A->getOption().getKind() == Option::InputClass &&
133 StringRef(A->getValue()).rfind(C: '.') != StringRef::npos &&
134 Fn(types::lookupTypeForExtension(
135 Ext: &A->getValue()[StringRef(A->getValue()).rfind(C: '.') + 1])));
136 });
137}
138
139CUIDOptions::CUIDOptions(llvm::opt::DerivedArgList &Args, const Driver &D)
140 : UseCUID(Kind::Hash) {
141 if (Arg *A = Args.getLastArg(Ids: options::OPT_fuse_cuid_EQ)) {
142 StringRef UseCUIDStr = A->getValue();
143 UseCUID = llvm::StringSwitch<Kind>(UseCUIDStr)
144 .Case(S: "hash", Value: Kind::Hash)
145 .Case(S: "random", Value: Kind::Random)
146 .Case(S: "none", Value: Kind::None)
147 .Default(Value: Kind::Invalid);
148 if (UseCUID == Kind::Invalid)
149 D.Diag(DiagID: clang::diag::err_drv_invalid_value)
150 << A->getAsString(Args) << UseCUIDStr;
151 }
152
153 FixedCUID = Args.getLastArgValue(Id: options::OPT_cuid_EQ);
154 if (!FixedCUID.empty())
155 UseCUID = Kind::Fixed;
156}
157
158std::string CUIDOptions::getCUID(StringRef InputFile,
159 llvm::opt::DerivedArgList &Args) const {
160 std::string CUID = FixedCUID.str();
161 if (CUID.empty()) {
162 if (UseCUID == Kind::Random)
163 CUID = llvm::utohexstr(X: llvm::sys::Process::GetRandomNumber(),
164 /*LowerCase=*/true);
165 else if (UseCUID == Kind::Hash) {
166 llvm::MD5 Hasher;
167 llvm::MD5::MD5Result Hash;
168 Hasher.update(Str: InputFile);
169 for (auto *A : Args) {
170 if (A->getOption().matches(ID: options::OPT_INPUT))
171 continue;
172 Hasher.update(Str: A->getAsString(Args));
173 }
174 Hasher.final(Result&: Hash);
175 CUID = llvm::utohexstr(X: Hash.low(), /*LowerCase=*/true);
176 }
177 }
178 return CUID;
179}
180Driver::Driver(StringRef DriverExecutable, StringRef TargetTriple,
181 DiagnosticsEngine &Diags, std::string Title,
182 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)
183 : Diags(Diags), VFS(std::move(VFS)), Mode(GCCMode),
184 SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
185 Offload(OffloadHostDevice), CXX20HeaderType(HeaderMode_None),
186 ModulesModeCXX20(false), DriverExecutable(DriverExecutable),
187 SysRoot(DEFAULT_SYSROOT), DriverTitle(Title), CCCPrintBindings(false),
188 CCPrintOptions(false), CCLogDiagnostics(false), CCGenDiagnostics(false),
189 CCPrintProcessStats(false), CCPrintInternalStats(false),
190 TargetTriple(TargetTriple), Saver(Alloc), PrependArg(nullptr),
191 PreferredLinker(CLANG_DEFAULT_LINKER), CheckInputsExist(true),
192 ProbePrecompiled(true), SuppressMissingInputWarning(false) {
193 // Provide a sane fallback if no VFS is specified.
194 if (!this->VFS)
195 this->VFS = llvm::vfs::getRealFileSystem();
196
197 Name = std::string(llvm::sys::path::filename(path: DriverExecutable));
198 Dir = std::string(llvm::sys::path::parent_path(path: DriverExecutable));
199
200 if ((!SysRoot.empty()) && llvm::sys::path::is_relative(path: SysRoot)) {
201 // Prepend InstalledDir if SysRoot is relative
202 SmallString<128> P(Dir);
203 llvm::sys::path::append(path&: P, a: SysRoot);
204 SysRoot = std::string(P);
205 }
206
207#if defined(CLANG_CONFIG_FILE_SYSTEM_DIR)
208 if (llvm::sys::path::is_absolute(CLANG_CONFIG_FILE_SYSTEM_DIR)) {
209 SystemConfigDir = CLANG_CONFIG_FILE_SYSTEM_DIR;
210 } else {
211 SmallString<128> configFileDir(Dir);
212 llvm::sys::path::append(configFileDir, CLANG_CONFIG_FILE_SYSTEM_DIR);
213 llvm::sys::path::remove_dots(configFileDir, true);
214 SystemConfigDir = static_cast<std::string>(configFileDir);
215 }
216#endif
217#if defined(CLANG_CONFIG_FILE_USER_DIR)
218 {
219 SmallString<128> P;
220 llvm::sys::fs::expand_tilde(CLANG_CONFIG_FILE_USER_DIR, P);
221 UserConfigDir = static_cast<std::string>(P);
222 }
223#endif
224
225 // Compute the path to the resource directory.
226 ResourceDir = GetResourcesPath(BinaryPath: DriverExecutable);
227}
228
229void Driver::setDriverMode(StringRef Value) {
230 static StringRef OptName =
231 getOpts().getOption(Opt: options::OPT_driver_mode).getPrefixedName();
232 if (auto M = llvm::StringSwitch<std::optional<DriverMode>>(Value)
233 .Case(S: "gcc", Value: GCCMode)
234 .Case(S: "g++", Value: GXXMode)
235 .Case(S: "cpp", Value: CPPMode)
236 .Case(S: "cl", Value: CLMode)
237 .Case(S: "flang", Value: FlangMode)
238 .Case(S: "dxc", Value: DXCMode)
239 .Default(Value: std::nullopt))
240 Mode = *M;
241 else
242 Diag(DiagID: diag::err_drv_unsupported_option_argument) << OptName << Value;
243}
244
245InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings,
246 bool UseDriverMode,
247 bool &ContainsError) const {
248 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
249 ContainsError = false;
250
251 llvm::opt::Visibility VisibilityMask = getOptionVisibilityMask(UseDriverMode);
252 unsigned MissingArgIndex, MissingArgCount;
253 InputArgList Args = getOpts().ParseArgs(Args: ArgStrings, MissingArgIndex,
254 MissingArgCount, VisibilityMask);
255
256 // Check for missing argument error.
257 if (MissingArgCount) {
258 Diag(DiagID: diag::err_drv_missing_argument)
259 << Args.getArgString(Index: MissingArgIndex) << MissingArgCount;
260 ContainsError |=
261 Diags.getDiagnosticLevel(DiagID: diag::err_drv_missing_argument,
262 Loc: SourceLocation()) > DiagnosticsEngine::Warning;
263 }
264
265 // Check for unsupported options.
266 for (const Arg *A : Args) {
267 if (A->getOption().hasFlag(Val: options::Unsupported)) {
268 Diag(DiagID: diag::err_drv_unsupported_opt) << A->getAsString(Args);
269 ContainsError |= Diags.getDiagnosticLevel(DiagID: diag::err_drv_unsupported_opt,
270 Loc: SourceLocation()) >
271 DiagnosticsEngine::Warning;
272 continue;
273 }
274
275 // Warn about -mcpu= without an argument.
276 if (A->getOption().matches(ID: options::OPT_mcpu_EQ) && A->containsValue(Value: "")) {
277 Diag(DiagID: diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
278 ContainsError |= Diags.getDiagnosticLevel(
279 DiagID: diag::warn_drv_empty_joined_argument,
280 Loc: SourceLocation()) > DiagnosticsEngine::Warning;
281 }
282 }
283
284 for (const Arg *A : Args.filtered(Ids: options::OPT_UNKNOWN)) {
285 unsigned DiagID;
286 auto ArgString = A->getAsString(Args);
287 std::string Nearest;
288 if (getOpts().findNearest(Option: ArgString, NearestString&: Nearest, VisibilityMask) > 1) {
289 if (IsFlangMode()) {
290 if (getOpts().findExact(Option: ArgString, ExactString&: Nearest,
291 VisibilityMask: llvm::opt::Visibility(options::FC1Option))) {
292 DiagID = diag::err_drv_unknown_argument_with_suggestion;
293 Diags.Report(DiagID) << ArgString << "-Xflang " + Nearest;
294 } else {
295 DiagID = diag::err_drv_unknown_argument;
296 Diags.Report(DiagID) << ArgString;
297 }
298 } else if (!IsCLMode() && getOpts().findExact(Option: ArgString, ExactString&: Nearest,
299 VisibilityMask: llvm::opt::Visibility(
300 options::CC1Option))) {
301 DiagID = diag::err_drv_unknown_argument_with_suggestion;
302 Diags.Report(DiagID) << ArgString << "-Xclang " + Nearest;
303 } else {
304 DiagID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl
305 : diag::err_drv_unknown_argument;
306 Diags.Report(DiagID) << ArgString;
307 }
308 } else {
309 DiagID = IsCLMode()
310 ? diag::warn_drv_unknown_argument_clang_cl_with_suggestion
311 : diag::err_drv_unknown_argument_with_suggestion;
312 Diags.Report(DiagID) << ArgString << Nearest;
313 }
314 ContainsError |= Diags.getDiagnosticLevel(DiagID, Loc: SourceLocation()) >
315 DiagnosticsEngine::Warning;
316 }
317
318 for (const Arg *A : Args.filtered(Ids: options::OPT_o)) {
319 if (ArgStrings[A->getIndex()] == A->getSpelling())
320 continue;
321
322 // Warn on joined arguments that are similar to a long argument.
323 std::string ArgString = ArgStrings[A->getIndex()];
324 std::string Nearest;
325 if (getOpts().findExact(Option: "-" + ArgString, ExactString&: Nearest, VisibilityMask))
326 Diags.Report(DiagID: diag::warn_drv_potentially_misspelled_joined_argument)
327 << A->getAsString(Args) << Nearest;
328 }
329
330 return Args;
331}
332
333// Determine which compilation mode we are in. We look for options which
334// affect the phase, starting with the earliest phases, and record which
335// option we used to determine the final phase.
336phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
337 Arg **FinalPhaseArg) const {
338 Arg *PhaseArg = nullptr;
339 phases::ID FinalPhase;
340
341 // -{E,EP,P,M,MM} only run the preprocessor.
342 if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(Ids: options::OPT_E)) ||
343 (PhaseArg = DAL.getLastArg(Ids: options::OPT__SLASH_EP)) ||
344 (PhaseArg = DAL.getLastArg(Ids: options::OPT_M, Ids: options::OPT_MM)) ||
345 (PhaseArg = DAL.getLastArg(Ids: options::OPT__SLASH_P)) ||
346 CCGenDiagnostics) {
347 FinalPhase = phases::Preprocess;
348
349 // --precompile only runs up to precompilation.
350 // Options that cause the output of C++20 compiled module interfaces or
351 // header units have the same effect.
352 } else if ((PhaseArg = DAL.getLastArg(Ids: options::OPT__precompile)) ||
353 (PhaseArg =
354 DAL.getLastArg(Ids: options::OPT__precompile_reduced_bmi)) ||
355 (PhaseArg = DAL.getLastArg(Ids: options::OPT_extract_api)) ||
356 (PhaseArg = DAL.getLastArg(Ids: options::OPT_fmodule_header,
357 Ids: options::OPT_fmodule_header_EQ))) {
358 FinalPhase = phases::Precompile;
359 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
360 } else if ((PhaseArg = DAL.getLastArg(Ids: options::OPT_fsyntax_only)) ||
361 (PhaseArg = DAL.getLastArg(Ids: options::OPT_print_supported_cpus)) ||
362 (PhaseArg =
363 DAL.getLastArg(Ids: options::OPT_print_enabled_extensions)) ||
364 (PhaseArg = DAL.getLastArg(Ids: options::OPT_module_file_info)) ||
365 (PhaseArg = DAL.getLastArg(Ids: options::OPT_verify_pch)) ||
366 (PhaseArg = DAL.getLastArg(Ids: options::OPT_rewrite_objc)) ||
367 (PhaseArg = DAL.getLastArg(Ids: options::OPT_rewrite_legacy_objc)) ||
368 (PhaseArg = DAL.getLastArg(Ids: options::OPT__analyze)) ||
369 (PhaseArg = DAL.getLastArg(Ids: options::OPT_emit_cir)) ||
370 (PhaseArg = DAL.getLastArg(Ids: options::OPT_emit_ast))) {
371 FinalPhase = phases::Compile;
372
373 // -S only runs up to the backend.
374 } else if ((PhaseArg = DAL.getLastArg(Ids: options::OPT_S))) {
375 FinalPhase = phases::Backend;
376
377 // -c compilation only runs up to the assembler.
378 } else if ((PhaseArg = DAL.getLastArg(Ids: options::OPT_c))) {
379 FinalPhase = phases::Assemble;
380
381 } else if ((PhaseArg = DAL.getLastArg(Ids: options::OPT_emit_interface_stubs))) {
382 FinalPhase = phases::IfsMerge;
383
384 // Otherwise do everything.
385 } else
386 FinalPhase = phases::Link;
387
388 if (FinalPhaseArg)
389 *FinalPhaseArg = PhaseArg;
390
391 return FinalPhase;
392}
393
394llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>>
395Driver::executeProgram(llvm::ArrayRef<llvm::StringRef> Args) const {
396 llvm::SmallString<64> OutputFile;
397 llvm::sys::fs::createTemporaryFile(Prefix: "driver-program", Suffix: "txt", ResultPath&: OutputFile,
398 Flags: llvm::sys::fs::OF_Text);
399 llvm::FileRemover OutputRemover(OutputFile.c_str());
400 std::optional<llvm::StringRef> Redirects[] = {
401 {""},
402 OutputFile.str(),
403 {""},
404 };
405
406 std::string ErrorMessage;
407 int SecondsToWait = 60;
408 if (std::optional<std::string> Str =
409 llvm::sys::Process::GetEnv(name: "CLANG_TOOLCHAIN_PROGRAM_TIMEOUT")) {
410 if (!llvm::to_integer(S: *Str, Num&: SecondsToWait))
411 return llvm::createStringError(EC: std::error_code(),
412 S: "CLANG_TOOLCHAIN_PROGRAM_TIMEOUT expected "
413 "an integer, got '" +
414 *Str + "'");
415 SecondsToWait = std::max(a: SecondsToWait, b: 0); // infinite
416 }
417 StringRef Executable = Args[0];
418 if (llvm::sys::ExecuteAndWait(Program: Executable, Args, Env: {}, Redirects, SecondsToWait,
419 /*MemoryLimit=*/0, ErrMsg: &ErrorMessage))
420 return llvm::createStringError(EC: std::error_code(),
421 S: Executable + ": " + ErrorMessage);
422
423 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> OutputBuf =
424 llvm::MemoryBuffer::getFile(Filename: OutputFile.c_str());
425 if (!OutputBuf)
426 return llvm::createStringError(EC: OutputBuf.getError(),
427 S: "Failed to read stdout of " + Executable +
428 ": " + OutputBuf.getError().message());
429 return std::move(*OutputBuf);
430}
431
432Arg *clang::driver::makeInputArg(DerivedArgList &Args, const OptTable &Opts,
433 StringRef Value, bool Claim) {
434 Arg *A = new Arg(Opts.getOption(Opt: options::OPT_INPUT), Value,
435 Args.getBaseArgs().MakeIndex(String0: Value), Value.data());
436 Args.AddSynthesizedArg(A);
437 if (Claim)
438 A->claim();
439 return A;
440}
441
442DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
443 const llvm::opt::OptTable &Opts = getOpts();
444 DerivedArgList *DAL = new DerivedArgList(Args);
445
446 bool HasNostdlib = Args.hasArg(Ids: options::OPT_nostdlib);
447 bool HasNostdlibxx = Args.hasArg(Ids: options::OPT_nostdlibxx);
448 bool HasNodefaultlib = Args.hasArg(Ids: options::OPT_nodefaultlibs);
449 bool IgnoreUnused = false;
450 for (Arg *A : Args) {
451 if (IgnoreUnused)
452 A->claim();
453
454 if (A->getOption().matches(ID: options::OPT_start_no_unused_arguments)) {
455 IgnoreUnused = true;
456 continue;
457 }
458 if (A->getOption().matches(ID: options::OPT_end_no_unused_arguments)) {
459 IgnoreUnused = false;
460 continue;
461 }
462
463 // Unfortunately, we have to parse some forwarding options (-Xassembler,
464 // -Xlinker, -Xpreprocessor) because we either integrate their functionality
465 // (assembler and preprocessor), or bypass a previous driver ('collect2').
466
467 // Rewrite linker options, to replace --no-demangle with a custom internal
468 // option.
469 if ((A->getOption().matches(ID: options::OPT_Wl_COMMA) ||
470 A->getOption().matches(ID: options::OPT_Xlinker)) &&
471 A->containsValue(Value: "--no-demangle")) {
472 // Add the rewritten no-demangle argument.
473 DAL->AddFlagArg(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_Z_Xlinker__no_demangle));
474
475 // Add the remaining values as Xlinker arguments.
476 for (StringRef Val : A->getValues())
477 if (Val != "--no-demangle")
478 DAL->AddSeparateArg(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_Xlinker), Value: Val);
479
480 continue;
481 }
482
483 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
484 // some build systems. We don't try to be complete here because we don't
485 // care to encourage this usage model.
486 if (A->getOption().matches(ID: options::OPT_Wp_COMMA) &&
487 A->getNumValues() > 0 &&
488 (A->getValue(N: 0) == StringRef("-MD") ||
489 A->getValue(N: 0) == StringRef("-MMD"))) {
490 // Rewrite to -MD/-MMD along with -MF.
491 if (A->getValue(N: 0) == StringRef("-MD"))
492 DAL->AddFlagArg(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_MD));
493 else
494 DAL->AddFlagArg(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_MMD));
495 if (A->getNumValues() == 2)
496 DAL->AddSeparateArg(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_MF), Value: A->getValue(N: 1));
497 continue;
498 }
499
500 // Rewrite reserved library names.
501 if (A->getOption().matches(ID: options::OPT_l)) {
502 StringRef Value = A->getValue();
503
504 // Rewrite unless -nostdlib is present.
505 if (!HasNostdlib && !HasNodefaultlib && !HasNostdlibxx &&
506 Value == "stdc++") {
507 DAL->AddFlagArg(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_Z_reserved_lib_stdcxx));
508 continue;
509 }
510
511 // Rewrite unconditionally.
512 if (Value == "cc_kext") {
513 DAL->AddFlagArg(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_Z_reserved_lib_cckext));
514 continue;
515 }
516 }
517
518 // Pick up inputs via the -- option.
519 if (A->getOption().matches(ID: options::OPT__DASH_DASH)) {
520 A->claim();
521 for (StringRef Val : A->getValues())
522 DAL->append(A: makeInputArg(Args&: *DAL, Opts, Value: Val, Claim: false));
523 continue;
524 }
525
526 DAL->append(A);
527 }
528
529 // DXC mode quits before assembly if an output object file isn't specified.
530 if (IsDXCMode() && !Args.hasArg(Ids: options::OPT_dxc_Fo))
531 DAL->AddFlagArg(BaseArg: nullptr, Opt: Opts.getOption(Opt: options::OPT_S));
532
533 // Enforce -static if -miamcu is present.
534 if (Args.hasFlag(Pos: options::OPT_miamcu, Neg: options::OPT_mno_iamcu, Default: false))
535 DAL->AddFlagArg(BaseArg: nullptr, Opt: Opts.getOption(Opt: options::OPT_static));
536
537// Add a default value of -mlinker-version=, if one was given and the user
538// didn't specify one.
539#if defined(HOST_LINK_VERSION)
540 if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
541 strlen(HOST_LINK_VERSION) > 0) {
542 DAL->AddJoinedArg(0, Opts.getOption(options::OPT_mlinker_version_EQ),
543 HOST_LINK_VERSION);
544 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
545 }
546#endif
547
548 return DAL;
549}
550
551static void setZosTargetVersion(const Driver &D, llvm::Triple &Target,
552 StringRef ArgTarget) {
553
554 static bool BeSilent = false;
555 auto IsTooOldToBeSupported = [](int v, int r) -> bool { return v < 3; };
556
557 /* expect CURRENT, zOSVnRn, or 0xnnnnnnnn */
558 if (ArgTarget.equals_insensitive(RHS: "CURRENT")) {
559 /* If the user gives CURRENT, then we rely on the LE to set */
560 /* __TARGET_LIB__. There's nothing more we need to do. */
561 } else {
562 unsigned int Version = 0;
563 unsigned int Release = 0;
564 unsigned int Modification = 0;
565 bool IsOk = true;
566 llvm::Regex ZOsvRegex("[zZ][oO][sS][vV]([0-9])[rR]([0-9])");
567 llvm::Regex HexRegex(
568 "0x4" /* product */
569 "([0-9a-fA-F])" /* version */
570 "([0-9a-fA-F][0-9a-fA-F])" /* release */
571 "([0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F])" /* modification */);
572 SmallVector<StringRef> Matches;
573
574 if (ZOsvRegex.match(String: ArgTarget, Matches: &Matches)) {
575 Matches[1].getAsInteger(Radix: 10, Result&: Version);
576 Matches[2].getAsInteger(Radix: 10, Result&: Release);
577 Modification = 0;
578 if (IsTooOldToBeSupported(Version, Release)) {
579 if (!BeSilent)
580 D.Diag(DiagID: diag::err_zos_target_release_discontinued) << ArgTarget;
581 IsOk = false;
582 }
583 } else if (HexRegex.match(String: ArgTarget, Matches: &Matches)) {
584 Matches[1].getAsInteger(Radix: 16, Result&: Version);
585 Matches[2].getAsInteger(Radix: 16, Result&: Release);
586 Matches[3].getAsInteger(Radix: 16, Result&: Modification);
587 if (IsTooOldToBeSupported(Version, Release)) {
588 if (!BeSilent)
589 D.Diag(DiagID: diag::err_zos_target_release_discontinued) << ArgTarget;
590 IsOk = false;
591 }
592 } else {
593 /* something else: need to report an error */
594 if (!BeSilent)
595 D.Diag(DiagID: diag::err_zos_target_unrecognized_release) << ArgTarget;
596 IsOk = false;
597 }
598
599 if (IsOk) {
600 llvm::VersionTuple V(Version, Release, Modification);
601 llvm::VersionTuple TV = Target.getOSVersion();
602 // The goal is to pick the minimally supported version of
603 // the OS. Pick the lesser as the target.
604 if (TV.empty() || V < TV) {
605 SmallString<16> Str;
606 Str = llvm::Triple::getOSTypeName(Kind: Target.getOS());
607 Str += V.getAsString();
608 Target.setOSName(Str);
609 }
610 }
611 }
612 BeSilent = true;
613}
614
615/// Compute target triple from args.
616///
617/// This routine provides the logic to compute a target triple from various
618/// args passed to the driver and the default triple string.
619static llvm::Triple computeTargetTriple(const Driver &D, StringRef TargetTriple,
620 const ArgList &Args,
621 StringRef ArchName = "") {
622 // FIXME: Already done in Compilation *Driver::BuildCompilation
623 if (const Arg *A = Args.getLastArg(Ids: options::OPT_target))
624 TargetTriple = A->getValue();
625
626 llvm::Triple Target(llvm::Triple::normalize(Str: TargetTriple));
627
628 // GNU/Hurd's triples should have been -hurd-gnu*, but were historically made
629 // -gnu* only, and we can not change this, so we have to detect that case as
630 // being the Hurd OS.
631 if (TargetTriple.contains(Other: "-unknown-gnu") || TargetTriple.contains(Other: "-pc-gnu"))
632 Target.setOSName("hurd");
633
634 // Handle Apple-specific options available here.
635 if (Target.isOSBinFormatMachO()) {
636 // If an explicit Darwin arch name is given, that trumps all.
637 if (!ArchName.empty()) {
638 tools::darwin::setTripleTypeForMachOArchName(T&: Target, Str: ArchName, Args);
639 return llvm::Triple(Target.normalize());
640 }
641
642 // Handle the Darwin '-arch' flag.
643 if (Arg *A = Args.getLastArg(Ids: options::OPT_arch)) {
644 StringRef ArchName = A->getValue();
645 tools::darwin::setTripleTypeForMachOArchName(T&: Target, Str: ArchName, Args);
646 }
647 } else if (!ArchName.empty()) {
648 Target.setArchName(ArchName);
649 return Target;
650 }
651
652 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
653 // '-mbig-endian'/'-EB'.
654 if (Arg *A = Args.getLastArgNoClaim(Ids: options::OPT_mlittle_endian,
655 Ids: options::OPT_mbig_endian)) {
656 llvm::Triple T = A->getOption().matches(ID: options::OPT_mlittle_endian)
657 ? Target.getLittleEndianArchVariant()
658 : Target.getBigEndianArchVariant();
659 if (T.getArch() != llvm::Triple::UnknownArch) {
660 Target = llvm::Triple(T.normalize());
661 Args.claimAllArgs(Ids: options::OPT_mlittle_endian, Ids: options::OPT_mbig_endian);
662 }
663 }
664
665 // Skip further flag support on OSes which don't support '-m32' or '-m64'.
666 if (Target.getArch() == llvm::Triple::tce)
667 return Target;
668
669 // On AIX, the env OBJECT_MODE may affect the resulting arch variant.
670 // However, if --target was explicitly specified, it takes precedence.
671#ifdef _AIX
672 if (!Args.hasArg(options::OPT_target)) {
673 if (std::optional<std::string> ObjectModeValue =
674 llvm::sys::Process::GetEnv("OBJECT_MODE")) {
675 StringRef ObjectMode = *ObjectModeValue;
676 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
677
678 // Silently accept '32_64' and 'any'
679 const bool OtherAllowedMode =
680 ObjectMode == "32_64" || ObjectMode == "any";
681 if (ObjectMode == "64") {
682 AT = Target.get64BitArchVariant().getArch();
683 } else if (ObjectMode == "32") {
684 AT = Target.get32BitArchVariant().getArch();
685 } else if (!OtherAllowedMode) {
686 D.Diag(diag::err_drv_invalid_object_mode) << ObjectMode;
687 }
688
689 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch()) {
690 Target.setArch(AT);
691 Target = llvm::Triple(Target.normalize());
692 }
693 }
694 }
695#endif
696
697 // Currently the only architecture supported by *-uefi triples are x86_64.
698 if (Target.isUEFI() && Target.getArch() != llvm::Triple::x86_64)
699 D.Diag(DiagID: diag::err_target_unknown_triple) << Target.str();
700
701 // The `-maix[32|64]` flags are only valid for AIX targets.
702 if (Arg *A = Args.getLastArgNoClaim(Ids: options::OPT_maix32, Ids: options::OPT_maix64);
703 A && !Target.isOSAIX())
704 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
705 << A->getAsString(Args) << Target.str();
706
707 // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
708 Arg *A = Args.getLastArg(Ids: options::OPT_m64, Ids: options::OPT_mx32,
709 Ids: options::OPT_m32, Ids: options::OPT_m16,
710 Ids: options::OPT_maix32, Ids: options::OPT_maix64);
711 if (A) {
712 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
713
714 if (A->getOption().matches(ID: options::OPT_m64) ||
715 A->getOption().matches(ID: options::OPT_maix64)) {
716 AT = Target.get64BitArchVariant().getArch();
717 if (Target.getEnvironment() == llvm::Triple::GNUX32 ||
718 Target.getEnvironment() == llvm::Triple::GNUT64)
719 Target.setEnvironment(llvm::Triple::GNU);
720 else if (Target.getEnvironment() == llvm::Triple::MuslX32)
721 Target.setEnvironment(llvm::Triple::Musl);
722 } else if (A->getOption().matches(ID: options::OPT_mx32) &&
723 Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
724 AT = llvm::Triple::x86_64;
725 if (Target.getEnvironment() == llvm::Triple::Musl)
726 Target.setEnvironment(llvm::Triple::MuslX32);
727 else
728 Target.setEnvironment(llvm::Triple::GNUX32);
729 } else if (A->getOption().matches(ID: options::OPT_m32) ||
730 A->getOption().matches(ID: options::OPT_maix32)) {
731 if (D.IsFlangMode() && !Target.isOSAIX()) {
732 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
733 << A->getAsString(Args) << Target.str();
734 } else {
735 AT = Target.get32BitArchVariant().getArch();
736 if (Target.getEnvironment() == llvm::Triple::GNUX32)
737 Target.setEnvironment(llvm::Triple::GNU);
738 else if (Target.getEnvironment() == llvm::Triple::MuslX32)
739 Target.setEnvironment(llvm::Triple::Musl);
740 }
741 } else if (A->getOption().matches(ID: options::OPT_m16) &&
742 Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
743 AT = llvm::Triple::x86;
744 Target.setEnvironment(llvm::Triple::CODE16);
745 }
746
747 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch()) {
748 Target.setArch(Kind: AT);
749 if (Target.isWindowsGNUEnvironment())
750 toolchains::MinGW::fixTripleArch(D, Triple&: Target, Args);
751 }
752
753 Target = llvm::Triple(Target.normalize());
754 }
755
756 if (Target.isOSzOS()) {
757 if ((A = Args.getLastArg(Ids: options::OPT_mzos_target_EQ))) {
758 setZosTargetVersion(D, Target, ArgTarget: A->getValue());
759 }
760 }
761
762 // Handle -miamcu flag.
763 if (Args.hasFlag(Pos: options::OPT_miamcu, Neg: options::OPT_mno_iamcu, Default: false)) {
764 if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
765 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target) << "-miamcu"
766 << Target.str();
767
768 if (A && !A->getOption().matches(ID: options::OPT_m32))
769 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
770 << "-miamcu" << A->getBaseArg().getAsString(Args);
771
772 Target.setArch(Kind: llvm::Triple::x86);
773 Target.setArchName("i586");
774 Target.setEnvironmentName("");
775 Target.setOS(llvm::Triple::ELFIAMCU);
776 Target.setVendor(llvm::Triple::Intel);
777 }
778
779 // If target is MIPS adjust the target triple
780 // accordingly to provided ABI name.
781 if (Target.isMIPS()) {
782 if ((A = Args.getLastArg(Ids: options::OPT_mabi_EQ))) {
783 StringRef ABIName = A->getValue();
784 if (ABIName == "32") {
785 Target = Target.get32BitArchVariant();
786 if (Target.getEnvironment() == llvm::Triple::GNUABI64 ||
787 Target.getEnvironment() == llvm::Triple::GNUABIN32)
788 Target.setEnvironment(llvm::Triple::GNU);
789 } else if (ABIName == "n32") {
790 Target = Target.get64BitArchVariant();
791 if (Target.getEnvironment() == llvm::Triple::GNU ||
792 Target.getEnvironment() == llvm::Triple::GNUT64 ||
793 Target.getEnvironment() == llvm::Triple::GNUABI64)
794 Target.setEnvironment(llvm::Triple::GNUABIN32);
795 else if (Target.getEnvironment() == llvm::Triple::Musl ||
796 Target.getEnvironment() == llvm::Triple::MuslABI64)
797 Target.setEnvironment(llvm::Triple::MuslABIN32);
798 } else if (ABIName == "64") {
799 Target = Target.get64BitArchVariant();
800 if (Target.getEnvironment() == llvm::Triple::GNU ||
801 Target.getEnvironment() == llvm::Triple::GNUT64 ||
802 Target.getEnvironment() == llvm::Triple::GNUABIN32)
803 Target.setEnvironment(llvm::Triple::GNUABI64);
804 else if (Target.getEnvironment() == llvm::Triple::Musl ||
805 Target.getEnvironment() == llvm::Triple::MuslABIN32)
806 Target.setEnvironment(llvm::Triple::MuslABI64);
807 }
808
809 Target = llvm::Triple(Target.normalize());
810 }
811 }
812
813 // If target is RISC-V adjust the target triple according to
814 // provided architecture name
815 if (Target.isRISCV()) {
816 if (Args.hasArg(Ids: options::OPT_march_EQ) ||
817 Args.hasArg(Ids: options::OPT_mcpu_EQ)) {
818 std::string ArchName = tools::riscv::getRISCVArch(Args, Triple: Target);
819 auto ISAInfo = llvm::RISCVISAInfo::parseArchString(
820 Arch: ArchName, /*EnableExperimentalExtensions=*/EnableExperimentalExtension: true);
821 if (!llvm::errorToBool(Err: ISAInfo.takeError())) {
822 unsigned XLen = (*ISAInfo)->getXLen();
823 if (XLen == 32) {
824 if (Target.isLittleEndian())
825 Target.setArch(Kind: llvm::Triple::riscv32);
826 else
827 Target.setArch(Kind: llvm::Triple::riscv32be);
828 Target = llvm::Triple(Target.normalize());
829 } else if (XLen == 64) {
830 if (Target.isLittleEndian())
831 Target.setArch(Kind: llvm::Triple::riscv64);
832 else
833 Target.setArch(Kind: llvm::Triple::riscv64be);
834 Target = llvm::Triple(Target.normalize());
835 }
836 }
837 }
838 }
839
840 if (Target.getArch() == llvm::Triple::riscv32be ||
841 Target.getArch() == llvm::Triple::riscv64be) {
842 static bool WarnedRISCVBE = false;
843 if (!WarnedRISCVBE) {
844 D.Diag(DiagID: diag::warn_drv_riscv_be_experimental);
845 WarnedRISCVBE = true;
846 }
847 }
848
849 return Target;
850}
851
852/// Compute the desired OpenMP runtime from the flags provided.
853Driver::OpenMPRuntimeKind Driver::getOpenMPRuntime(const ArgList &Args) const {
854 StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
855
856 const Arg *A = Args.getLastArg(Ids: options::OPT_fopenmp_EQ);
857 if (A)
858 RuntimeName = A->getValue();
859
860 auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
861 .Case(S: "libomp", Value: OMPRT_OMP)
862 .Case(S: "libgomp", Value: OMPRT_GOMP)
863 .Case(S: "libiomp5", Value: OMPRT_IOMP5)
864 .Default(Value: OMPRT_Unknown);
865
866 if (RT == OMPRT_Unknown) {
867 if (A)
868 Diag(DiagID: diag::err_drv_unsupported_option_argument)
869 << A->getSpelling() << A->getValue();
870 else
871 // FIXME: We could use a nicer diagnostic here.
872 Diag(DiagID: diag::err_drv_unsupported_opt) << "-fopenmp";
873 }
874
875 return RT;
876}
877
878// Handles `native` offload architectures by using the 'offload-arch' utility.
879static llvm::SmallVector<std::string>
880getSystemOffloadArchs(Compilation &C, Action::OffloadKind Kind) {
881 StringRef Program = C.getArgs().getLastArgValue(
882 Id: options::OPT_offload_arch_tool_EQ, Default: "offload-arch");
883
884 SmallVector<std::string> GPUArchs;
885 if (llvm::ErrorOr<std::string> Executable =
886 llvm::sys::findProgramByName(Name: Program, Paths: {C.getDriver().Dir})) {
887 llvm::SmallVector<StringRef> Args{*Executable};
888 if (Kind == Action::OFK_HIP)
889 Args.push_back(Elt: "--only=amdgpu");
890 else if (Kind == Action::OFK_Cuda)
891 Args.push_back(Elt: "--only=nvptx");
892 auto StdoutOrErr = C.getDriver().executeProgram(Args);
893
894 if (!StdoutOrErr) {
895 C.getDriver().Diag(DiagID: diag::err_drv_undetermined_gpu_arch)
896 << Action::GetOffloadKindName(Kind) << StdoutOrErr.takeError()
897 << "--offload-arch";
898 return GPUArchs;
899 }
900 if ((*StdoutOrErr)->getBuffer().empty()) {
901 C.getDriver().Diag(DiagID: diag::err_drv_undetermined_gpu_arch)
902 << Action::GetOffloadKindName(Kind) << "No GPU detected in the system"
903 << "--offload-arch";
904 return GPUArchs;
905 }
906
907 for (StringRef Arch : llvm::split(Str: (*StdoutOrErr)->getBuffer(), Separator: "\n"))
908 if (!Arch.empty())
909 GPUArchs.push_back(Elt: Arch.str());
910 } else {
911 C.getDriver().Diag(DiagID: diag::err_drv_command_failure) << "offload-arch";
912 }
913 return GPUArchs;
914}
915
916using TripleSet = std::multiset<llvm::Triple>;
917
918// Attempts to infer the correct offloading toolchain triple by looking at the
919// requested offloading kind and architectures.
920static TripleSet inferOffloadToolchains(Compilation &C,
921 Action::OffloadKind Kind) {
922 std::set<std::string> Archs;
923 for (Arg *A : C.getInputArgs()) {
924 for (StringRef Arch : A->getValues()) {
925 if (A->getOption().matches(ID: options::OPT_offload_arch_EQ)) {
926 if (Arch == "native") {
927 for (StringRef Str : getSystemOffloadArchs(C, Kind))
928 Archs.insert(x: Str.str());
929 } else {
930 Archs.insert(x: Arch.str());
931 }
932 } else if (A->getOption().matches(ID: options::OPT_no_offload_arch_EQ)) {
933 if (Arch == "all")
934 Archs.clear();
935 else
936 Archs.erase(x: Arch.str());
937 }
938 }
939 }
940
941 TripleSet Triples;
942 for (llvm::StringRef Arch : Archs) {
943 OffloadArch ID = StringToOffloadArch(S: Arch);
944 if (ID == OffloadArch::Unknown)
945 ID = StringToOffloadArch(
946 S: getProcessorFromTargetID(T: llvm::Triple("amdgcn-amd-amdhsa"), OffloadArch: Arch));
947
948 if (Kind == Action::OFK_HIP && !IsAMDOffloadArch(A: ID)) {
949 C.getDriver().Diag(DiagID: clang::diag::err_drv_offload_bad_gpu_arch)
950 << "HIP" << Arch;
951 return {};
952 }
953 if (Kind == Action::OFK_Cuda && !IsNVIDIAOffloadArch(A: ID)) {
954 C.getDriver().Diag(DiagID: clang::diag::err_drv_offload_bad_gpu_arch)
955 << "CUDA" << Arch;
956 return {};
957 }
958 if (Kind == Action::OFK_OpenMP &&
959 (ID == OffloadArch::Unknown || ID == OffloadArch::Unused)) {
960 C.getDriver().Diag(DiagID: clang::diag::err_drv_failed_to_deduce_target_from_arch)
961 << Arch;
962 return {};
963 }
964 if (ID == OffloadArch::Unknown || ID == OffloadArch::Unused) {
965 C.getDriver().Diag(DiagID: clang::diag::err_drv_offload_bad_gpu_arch)
966 << "offload" << Arch;
967 return {};
968 }
969
970 llvm::Triple Triple =
971 OffloadArchToTriple(DefaultToolchainTriple: C.getDefaultToolChain().getTriple(), ID);
972
973 // Make a new argument that dispatches this argument to the appropriate
974 // toolchain. This is required when we infer it and create potentially
975 // incompatible toolchains from the global option.
976 Option Opt = C.getDriver().getOpts().getOption(Opt: options::OPT_Xarch__);
977 unsigned Index = C.getArgs().getBaseArgs().MakeIndex(String0: "-Xarch_");
978 Arg *A = new Arg(Opt, C.getArgs().getArgString(Index), Index,
979 C.getArgs().MakeArgString(Str: Triple.getArchName()),
980 C.getArgs().MakeArgString(Str: "--offload-arch=" + Arch));
981 A->claim();
982 C.getArgs().append(A);
983 C.getArgs().AddSynthesizedArg(A);
984
985 auto It = Triples.lower_bound(x: Triple);
986 if (It == Triples.end() || *It != Triple)
987 Triples.insert(position: It, x: Triple);
988 }
989
990 // Infer the default target triple if no specific architectures are given.
991 if (Archs.empty() && Kind == Action::OFK_HIP)
992 Triples.insert(x: llvm::Triple("amdgcn-amd-amdhsa"));
993 else if (Archs.empty() && Kind == Action::OFK_Cuda) {
994 llvm::Triple::ArchType Arch =
995 C.getDefaultToolChain().getTriple().isArch64Bit()
996 ? llvm::Triple::nvptx64
997 : llvm::Triple::nvptx;
998 Triples.insert(x: llvm::Triple(Arch, llvm::Triple::NoSubArch,
999 llvm::Triple::NVIDIA, llvm::Triple::CUDA));
1000 } else if (Archs.empty() && Kind == Action::OFK_SYCL)
1001 Triples.insert(
1002 x: llvm::Triple(C.getDefaultToolChain().getTriple().isArch64Bit()
1003 ? llvm::Triple::spirv64
1004 : llvm::Triple::spirv32));
1005
1006 // We need to dispatch these to the appropriate toolchain now.
1007 C.getArgs().eraseArg(Id: options::OPT_offload_arch_EQ);
1008 C.getArgs().eraseArg(Id: options::OPT_no_offload_arch_EQ);
1009
1010 return Triples;
1011}
1012
1013void Driver::CreateOffloadingDeviceToolChains(Compilation &C,
1014 InputList &Inputs) {
1015 bool UseLLVMOffload = C.getInputArgs().hasArg(
1016 Ids: options::OPT_foffload_via_llvm, Ids: options::OPT_fno_offload_via_llvm, Ids: false);
1017 bool IsCuda =
1018 llvm::any_of(Range&: Inputs,
1019 P: [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
1020 return types::isCuda(Id: I.first);
1021 }) &&
1022 !UseLLVMOffload;
1023 bool IsHIP =
1024 (llvm::any_of(Range&: Inputs,
1025 P: [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
1026 return types::isHIP(Id: I.first);
1027 }) ||
1028 C.getInputArgs().hasArg(Ids: options::OPT_hip_link) ||
1029 C.getInputArgs().hasArg(Ids: options::OPT_hipstdpar)) &&
1030 !UseLLVMOffload;
1031 bool IsSYCL = C.getInputArgs().hasFlag(Pos: options::OPT_fsycl,
1032 Neg: options::OPT_fno_sycl, Default: false);
1033 bool IsOpenMPOffloading =
1034 UseLLVMOffload ||
1035 (C.getInputArgs().hasFlag(Pos: options::OPT_fopenmp, PosAlias: options::OPT_fopenmp_EQ,
1036 Neg: options::OPT_fno_openmp, Default: false) &&
1037 (C.getInputArgs().hasArg(Ids: options::OPT_offload_targets_EQ) ||
1038 (C.getInputArgs().hasArg(Ids: options::OPT_offload_arch_EQ) &&
1039 !(IsCuda || IsHIP))));
1040
1041 llvm::SmallSet<Action::OffloadKind, 4> Kinds;
1042 const std::pair<bool, Action::OffloadKind> ActiveKinds[] = {
1043 {IsCuda, Action::OFK_Cuda},
1044 {IsHIP, Action::OFK_HIP},
1045 {IsOpenMPOffloading, Action::OFK_OpenMP},
1046 {IsSYCL, Action::OFK_SYCL}};
1047 for (const auto &[Active, Kind] : ActiveKinds)
1048 if (Active)
1049 Kinds.insert(V: Kind);
1050
1051 // We currently don't support any kind of mixed offloading.
1052 if (Kinds.size() > 1) {
1053 Diag(DiagID: clang::diag::err_drv_mix_offload)
1054 << Action::GetOffloadKindName(Kind: *Kinds.begin()).upper()
1055 << Action::GetOffloadKindName(Kind: *(++Kinds.begin())).upper();
1056 return;
1057 }
1058
1059 // Initialize the compilation identifier used for unique CUDA / HIP names.
1060 if (IsCuda || IsHIP)
1061 CUIDOpts = CUIDOptions(C.getArgs(), *this);
1062
1063 // Get the list of requested offloading toolchains. If they were not
1064 // explicitly specified we will infer them based on the offloading language
1065 // and requested architectures.
1066 TripleSet Triples;
1067 if (C.getInputArgs().hasArg(Ids: options::OPT_offload_targets_EQ)) {
1068 std::vector<std::string> ArgValues =
1069 C.getInputArgs().getAllArgValues(Id: options::OPT_offload_targets_EQ);
1070 for (llvm::StringRef Target : ArgValues) {
1071 Triples.insert(x: ToolChain::normalizeOffloadTriple(OrigTT: Target));
1072 }
1073
1074 if (ArgValues.empty())
1075 Diag(DiagID: clang::diag::warn_drv_empty_joined_argument)
1076 << C.getInputArgs()
1077 .getLastArg(Ids: options::OPT_offload_targets_EQ)
1078 ->getAsString(Args: C.getInputArgs());
1079 } else {
1080 for (Action::OffloadKind Kind : Kinds)
1081 Triples = inferOffloadToolchains(C, Kind);
1082 }
1083
1084 // Build an offloading toolchain for every requested target and kind.
1085 llvm::StringMap<StringRef> FoundNormalizedTriples;
1086 for (const llvm::Triple &Target : Triples) {
1087 // OpenMP offloading requires a compatible libomp.
1088 if (Kinds.contains(V: Action::OFK_OpenMP)) {
1089 OpenMPRuntimeKind RuntimeKind = getOpenMPRuntime(Args: C.getInputArgs());
1090 if (RuntimeKind != OMPRT_OMP && RuntimeKind != OMPRT_IOMP5) {
1091 Diag(DiagID: clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
1092 return;
1093 }
1094 }
1095
1096 // Certain options are not allowed when combined with SYCL compilation.
1097 if (Kinds.contains(V: Action::OFK_SYCL)) {
1098 for (auto ID :
1099 {options::OPT_static_libstdcxx, options::OPT_ffreestanding})
1100 if (Arg *IncompatArg = C.getInputArgs().getLastArg(Ids: ID))
1101 Diag(DiagID: clang::diag::err_drv_argument_not_allowed_with)
1102 << IncompatArg->getSpelling() << "-fsycl";
1103 }
1104
1105 // Create a device toolchain for every specified kind and triple.
1106 for (Action::OffloadKind Kind : Kinds) {
1107 if (Target.getArch() == llvm::Triple::ArchType::UnknownArch) {
1108 Diag(DiagID: diag::err_drv_invalid_or_unsupported_offload_target)
1109 << Target.str();
1110 continue;
1111 }
1112
1113 std::string NormalizedName = Target.normalize();
1114 auto [TripleIt, Inserted] =
1115 FoundNormalizedTriples.try_emplace(Key: NormalizedName, Args: Target.str());
1116 if (!Inserted) {
1117 Diag(DiagID: clang::diag::warn_drv_omp_offload_target_duplicate)
1118 << Target.str() << TripleIt->second;
1119 continue;
1120 }
1121
1122 auto &TC = getOffloadToolChain(Args: C.getInputArgs(), Kind, Target,
1123 AuxTarget: C.getDefaultToolChain().getTriple());
1124
1125 // Emit a warning if the detected CUDA version is too new.
1126 if (Kind == Action::OFK_Cuda) {
1127 auto &CudaInstallation =
1128 static_cast<const toolchains::CudaToolChain &>(TC).CudaInstallation;
1129 if (CudaInstallation.isValid())
1130 CudaInstallation.WarnIfUnsupportedVersion();
1131 }
1132
1133 C.addOffloadDeviceToolChain(DeviceToolChain: &TC, OffloadKind: Kind);
1134 }
1135 }
1136}
1137
1138bool Driver::loadZOSCustomizationFile(llvm::cl::ExpansionContext &ExpCtx) {
1139 if (IsCLMode() || IsDXCMode() || IsFlangMode())
1140 return false;
1141
1142 SmallString<128> CustomizationFile;
1143 StringRef PathLIBEnv = StringRef(getenv(name: "CLANG_CONFIG_PATH")).trim();
1144 // If the env var is a directory then append "/clang.cfg" and treat
1145 // that as the config file. Otherwise treat the env var as the
1146 // config file.
1147 if (!PathLIBEnv.empty()) {
1148 llvm::sys::path::append(path&: CustomizationFile, a: PathLIBEnv);
1149 if (llvm::sys::fs::is_directory(Path: PathLIBEnv))
1150 llvm::sys::path::append(path&: CustomizationFile, a: "/clang.cfg");
1151 if (llvm::sys::fs::is_regular_file(Path: CustomizationFile))
1152 return readConfigFile(FileName: CustomizationFile, ExpCtx);
1153 Diag(DiagID: diag::err_drv_config_file_not_found) << CustomizationFile;
1154 return true;
1155 }
1156
1157 SmallString<128> BaseDir(llvm::sys::path::parent_path(path: Dir));
1158 llvm::sys::path::append(path&: CustomizationFile, a: BaseDir + "/etc/clang.cfg");
1159 if (llvm::sys::fs::is_regular_file(Path: CustomizationFile))
1160 return readConfigFile(FileName: CustomizationFile, ExpCtx);
1161
1162 // If no customization file, just return
1163 return false;
1164}
1165
1166static void appendOneArg(InputArgList &Args, const Arg *Opt) {
1167 // The args for config files or /clang: flags belong to different InputArgList
1168 // objects than Args. This copies an Arg from one of those other InputArgLists
1169 // to the ownership of Args.
1170 unsigned Index = Args.MakeIndex(String0: Opt->getSpelling());
1171 Arg *Copy = new Arg(Opt->getOption(), Args.getArgString(Index), Index);
1172 Copy->getValues() = Opt->getValues();
1173 if (Opt->isClaimed())
1174 Copy->claim();
1175 Copy->setOwnsValues(Opt->getOwnsValues());
1176 Opt->setOwnsValues(false);
1177 Args.append(A: Copy);
1178 if (Opt->getAlias()) {
1179 const Arg *Alias = Opt->getAlias();
1180 unsigned Index = Args.MakeIndex(String0: Alias->getSpelling());
1181 auto AliasCopy = std::make_unique<Arg>(args: Alias->getOption(),
1182 args: Args.getArgString(Index), args&: Index);
1183 AliasCopy->getValues() = Alias->getValues();
1184 AliasCopy->setOwnsValues(false);
1185 if (Alias->isClaimed())
1186 AliasCopy->claim();
1187 Copy->setAlias(std::move(AliasCopy));
1188 }
1189}
1190
1191bool Driver::readConfigFile(StringRef FileName,
1192 llvm::cl::ExpansionContext &ExpCtx) {
1193 // Try opening the given file.
1194 auto Status = getVFS().status(Path: FileName);
1195 if (!Status) {
1196 Diag(DiagID: diag::err_drv_cannot_open_config_file)
1197 << FileName << Status.getError().message();
1198 return true;
1199 }
1200 if (Status->getType() != llvm::sys::fs::file_type::regular_file) {
1201 Diag(DiagID: diag::err_drv_cannot_open_config_file)
1202 << FileName << "not a regular file";
1203 return true;
1204 }
1205
1206 // Try reading the given file.
1207 SmallVector<const char *, 32> NewCfgFileArgs;
1208 if (llvm::Error Err = ExpCtx.readConfigFile(CfgFile: FileName, Argv&: NewCfgFileArgs)) {
1209 Diag(DiagID: diag::err_drv_cannot_read_config_file)
1210 << FileName << toString(E: std::move(Err));
1211 return true;
1212 }
1213
1214 // Populate head and tail lists. The tail list is used only when linking.
1215 SmallVector<const char *, 32> NewCfgHeadArgs, NewCfgTailArgs;
1216 for (const char *Opt : NewCfgFileArgs) {
1217 // An $-prefixed option should go to the tail list.
1218 if (Opt[0] == '$' && Opt[1])
1219 NewCfgTailArgs.push_back(Elt: Opt + 1);
1220 else
1221 NewCfgHeadArgs.push_back(Elt: Opt);
1222 }
1223
1224 // Read options from config file.
1225 llvm::SmallString<128> CfgFileName(FileName);
1226 llvm::sys::path::native(path&: CfgFileName);
1227 bool ContainErrors = false;
1228 auto NewHeadOptions = std::make_unique<InputArgList>(
1229 args: ParseArgStrings(ArgStrings: NewCfgHeadArgs, /*UseDriverMode=*/true, ContainsError&: ContainErrors));
1230 if (ContainErrors)
1231 return true;
1232 auto NewTailOptions = std::make_unique<InputArgList>(
1233 args: ParseArgStrings(ArgStrings: NewCfgTailArgs, /*UseDriverMode=*/true, ContainsError&: ContainErrors));
1234 if (ContainErrors)
1235 return true;
1236
1237 // Claim all arguments that come from a configuration file so that the driver
1238 // does not warn on any that is unused.
1239 for (Arg *A : *NewHeadOptions)
1240 A->claim();
1241 for (Arg *A : *NewTailOptions)
1242 A->claim();
1243
1244 if (!CfgOptionsHead)
1245 CfgOptionsHead = std::move(NewHeadOptions);
1246 else {
1247 // If this is a subsequent config file, append options to the previous one.
1248 for (auto *Opt : *NewHeadOptions)
1249 appendOneArg(Args&: *CfgOptionsHead, Opt);
1250 }
1251
1252 if (!CfgOptionsTail)
1253 CfgOptionsTail = std::move(NewTailOptions);
1254 else {
1255 // If this is a subsequent config file, append options to the previous one.
1256 for (auto *Opt : *NewTailOptions)
1257 appendOneArg(Args&: *CfgOptionsTail, Opt);
1258 }
1259
1260 ConfigFiles.push_back(x: std::string(CfgFileName));
1261 return false;
1262}
1263
1264bool Driver::loadConfigFiles() {
1265 llvm::cl::ExpansionContext ExpCtx(Saver.getAllocator(),
1266 llvm::cl::tokenizeConfigFile, &getVFS());
1267
1268 // Process options that change search path for config files.
1269 if (CLOptions) {
1270 if (CLOptions->hasArg(Ids: options::OPT_config_system_dir_EQ)) {
1271 SmallString<128> CfgDir;
1272 CfgDir.append(
1273 RHS: CLOptions->getLastArgValue(Id: options::OPT_config_system_dir_EQ));
1274 if (CfgDir.empty() || getVFS().makeAbsolute(Path&: CfgDir))
1275 SystemConfigDir.clear();
1276 else
1277 SystemConfigDir = static_cast<std::string>(CfgDir);
1278 }
1279 if (CLOptions->hasArg(Ids: options::OPT_config_user_dir_EQ)) {
1280 SmallString<128> CfgDir;
1281 llvm::sys::fs::expand_tilde(
1282 path: CLOptions->getLastArgValue(Id: options::OPT_config_user_dir_EQ), output&: CfgDir);
1283 if (CfgDir.empty() || getVFS().makeAbsolute(Path&: CfgDir))
1284 UserConfigDir.clear();
1285 else
1286 UserConfigDir = static_cast<std::string>(CfgDir);
1287 }
1288 }
1289
1290 // Prepare list of directories where config file is searched for.
1291 StringRef CfgFileSearchDirs[] = {UserConfigDir, SystemConfigDir, Dir};
1292 ExpCtx.setSearchDirs(CfgFileSearchDirs);
1293
1294 // First try to load configuration from the default files, return on error.
1295 if (loadDefaultConfigFiles(ExpCtx))
1296 return true;
1297
1298 // Then load configuration files specified explicitly.
1299 SmallString<128> CfgFilePath;
1300 if (CLOptions) {
1301 for (auto CfgFileName : CLOptions->getAllArgValues(Id: options::OPT_config)) {
1302 // If argument contains directory separator, treat it as a path to
1303 // configuration file.
1304 if (llvm::sys::path::has_parent_path(path: CfgFileName)) {
1305 CfgFilePath.assign(RHS: CfgFileName);
1306 if (llvm::sys::path::is_relative(path: CfgFilePath)) {
1307 if (getVFS().makeAbsolute(Path&: CfgFilePath)) {
1308 Diag(DiagID: diag::err_drv_cannot_open_config_file)
1309 << CfgFilePath << "cannot get absolute path";
1310 return true;
1311 }
1312 }
1313 } else if (!ExpCtx.findConfigFile(FileName: CfgFileName, FilePath&: CfgFilePath)) {
1314 // Report an error that the config file could not be found.
1315 Diag(DiagID: diag::err_drv_config_file_not_found) << CfgFileName;
1316 for (const StringRef &SearchDir : CfgFileSearchDirs)
1317 if (!SearchDir.empty())
1318 Diag(DiagID: diag::note_drv_config_file_searched_in) << SearchDir;
1319 return true;
1320 }
1321
1322 // Try to read the config file, return on error.
1323 if (readConfigFile(FileName: CfgFilePath, ExpCtx))
1324 return true;
1325 }
1326 }
1327
1328 // No error occurred.
1329 return false;
1330}
1331
1332static bool findTripleConfigFile(llvm::cl::ExpansionContext &ExpCtx,
1333 SmallString<128> &ConfigFilePath,
1334 llvm::Triple Triple, std::string Suffix) {
1335 // First, try the full unmodified triple.
1336 if (ExpCtx.findConfigFile(FileName: Triple.str() + Suffix, FilePath&: ConfigFilePath))
1337 return true;
1338
1339 // Don't continue if we didn't find a parsable version in the triple.
1340 VersionTuple OSVersion = Triple.getOSVersion();
1341 if (!OSVersion.getMinor().has_value())
1342 return false;
1343
1344 std::string BaseOSName = Triple.getOSTypeName(Kind: Triple.getOS()).str();
1345
1346 // Next try strip the version to only include the major component.
1347 // e.g. arm64-apple-darwin23.6.0 -> arm64-apple-darwin23
1348 if (OSVersion.getMajor() != 0) {
1349 Triple.setOSName(BaseOSName + llvm::utostr(X: OSVersion.getMajor()));
1350 if (ExpCtx.findConfigFile(FileName: Triple.str() + Suffix, FilePath&: ConfigFilePath))
1351 return true;
1352 }
1353
1354 // Finally, try without any version suffix at all.
1355 // e.g. arm64-apple-darwin23.6.0 -> arm64-apple-darwin
1356 Triple.setOSName(BaseOSName);
1357 return ExpCtx.findConfigFile(FileName: Triple.str() + Suffix, FilePath&: ConfigFilePath);
1358}
1359
1360bool Driver::loadDefaultConfigFiles(llvm::cl::ExpansionContext &ExpCtx) {
1361 // Disable default config if CLANG_NO_DEFAULT_CONFIG is set to a non-empty
1362 // value.
1363 if (const char *NoConfigEnv = ::getenv(name: "CLANG_NO_DEFAULT_CONFIG")) {
1364 if (*NoConfigEnv)
1365 return false;
1366 }
1367 if (CLOptions && CLOptions->hasArg(Ids: options::OPT_no_default_config))
1368 return false;
1369
1370 std::string RealMode = getExecutableForDriverMode(Mode);
1371 llvm::Triple Triple;
1372
1373 // If name prefix is present, no --target= override was passed via CLOptions
1374 // and the name prefix is not a valid triple, force it for backwards
1375 // compatibility.
1376 if (!ClangNameParts.TargetPrefix.empty() &&
1377 computeTargetTriple(D: *this, TargetTriple: "/invalid/", Args: *CLOptions).str() ==
1378 "/invalid/") {
1379 llvm::Triple PrefixTriple{ClangNameParts.TargetPrefix};
1380 if (PrefixTriple.getArch() == llvm::Triple::UnknownArch ||
1381 PrefixTriple.isOSUnknown())
1382 Triple = std::move(PrefixTriple);
1383 }
1384
1385 // Otherwise, use the real triple as used by the driver.
1386 llvm::Triple RealTriple =
1387 computeTargetTriple(D: *this, TargetTriple, Args: *CLOptions);
1388 if (Triple.str().empty()) {
1389 Triple = RealTriple;
1390 assert(!Triple.str().empty());
1391 }
1392
1393 // On z/OS, start by loading the customization file before loading
1394 // the usual default config file(s).
1395 if (RealTriple.isOSzOS() && loadZOSCustomizationFile(ExpCtx))
1396 return true;
1397
1398 // Search for config files in the following order:
1399 // 1. <triple>-<mode>.cfg using real driver mode
1400 // (e.g. i386-pc-linux-gnu-clang++.cfg).
1401 // 2. <triple>-<mode>.cfg using executable suffix
1402 // (e.g. i386-pc-linux-gnu-clang-g++.cfg for *clang-g++).
1403 // 3. <triple>.cfg + <mode>.cfg using real driver mode
1404 // (e.g. i386-pc-linux-gnu.cfg + clang++.cfg).
1405 // 4. <triple>.cfg + <mode>.cfg using executable suffix
1406 // (e.g. i386-pc-linux-gnu.cfg + clang-g++.cfg for *clang-g++).
1407
1408 // Try loading <triple>-<mode>.cfg, and return if we find a match.
1409 SmallString<128> CfgFilePath;
1410 if (findTripleConfigFile(ExpCtx, ConfigFilePath&: CfgFilePath, Triple,
1411 Suffix: "-" + RealMode + ".cfg"))
1412 return readConfigFile(FileName: CfgFilePath, ExpCtx);
1413
1414 bool TryModeSuffix = !ClangNameParts.ModeSuffix.empty() &&
1415 ClangNameParts.ModeSuffix != RealMode;
1416 if (TryModeSuffix) {
1417 if (findTripleConfigFile(ExpCtx, ConfigFilePath&: CfgFilePath, Triple,
1418 Suffix: "-" + ClangNameParts.ModeSuffix + ".cfg"))
1419 return readConfigFile(FileName: CfgFilePath, ExpCtx);
1420 }
1421
1422 // Try loading <mode>.cfg, and return if loading failed. If a matching file
1423 // was not found, still proceed on to try <triple>.cfg.
1424 std::string CfgFileName = RealMode + ".cfg";
1425 if (ExpCtx.findConfigFile(FileName: CfgFileName, FilePath&: CfgFilePath)) {
1426 if (readConfigFile(FileName: CfgFilePath, ExpCtx))
1427 return true;
1428 } else if (TryModeSuffix) {
1429 CfgFileName = ClangNameParts.ModeSuffix + ".cfg";
1430 if (ExpCtx.findConfigFile(FileName: CfgFileName, FilePath&: CfgFilePath) &&
1431 readConfigFile(FileName: CfgFilePath, ExpCtx))
1432 return true;
1433 }
1434
1435 // Try loading <triple>.cfg and return if we find a match.
1436 if (findTripleConfigFile(ExpCtx, ConfigFilePath&: CfgFilePath, Triple, Suffix: ".cfg"))
1437 return readConfigFile(FileName: CfgFilePath, ExpCtx);
1438
1439 // If we were unable to find a config file deduced from executable name,
1440 // that is not an error.
1441 return false;
1442}
1443
1444Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
1445 llvm::PrettyStackTraceString CrashInfo("Compilation construction");
1446
1447 // FIXME: Handle environment options which affect driver behavior, somewhere
1448 // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
1449
1450 // We look for the driver mode option early, because the mode can affect
1451 // how other options are parsed.
1452
1453 auto DriverMode = getDriverMode(ProgName: DriverExecutable, Args: ArgList.slice(N: 1));
1454 if (!DriverMode.empty())
1455 setDriverMode(DriverMode);
1456
1457 // FIXME: What are we going to do with -V and -b?
1458
1459 // Arguments specified in command line.
1460 bool ContainsError;
1461 CLOptions = std::make_unique<InputArgList>(
1462 args: ParseArgStrings(ArgStrings: ArgList.slice(N: 1), /*UseDriverMode=*/true, ContainsError));
1463
1464 // Try parsing configuration file.
1465 if (!ContainsError)
1466 ContainsError = loadConfigFiles();
1467 bool HasConfigFileHead = !ContainsError && CfgOptionsHead;
1468 bool HasConfigFileTail = !ContainsError && CfgOptionsTail;
1469
1470 // All arguments, from both config file and command line.
1471 InputArgList Args =
1472 HasConfigFileHead ? std::move(*CfgOptionsHead) : std::move(*CLOptions);
1473
1474 if (HasConfigFileHead)
1475 for (auto *Opt : *CLOptions)
1476 if (!Opt->getOption().matches(ID: options::OPT_config))
1477 appendOneArg(Args, Opt);
1478
1479 // In CL mode, look for any pass-through arguments
1480 if (IsCLMode() && !ContainsError) {
1481 SmallVector<const char *, 16> CLModePassThroughArgList;
1482 for (const auto *A : Args.filtered(Ids: options::OPT__SLASH_clang)) {
1483 A->claim();
1484 CLModePassThroughArgList.push_back(Elt: A->getValue());
1485 }
1486
1487 if (!CLModePassThroughArgList.empty()) {
1488 // Parse any pass through args using default clang processing rather
1489 // than clang-cl processing.
1490 auto CLModePassThroughOptions = std::make_unique<InputArgList>(
1491 args: ParseArgStrings(ArgStrings: CLModePassThroughArgList, /*UseDriverMode=*/false,
1492 ContainsError));
1493
1494 if (!ContainsError)
1495 for (auto *Opt : *CLModePassThroughOptions)
1496 appendOneArg(Args, Opt);
1497 }
1498 }
1499
1500 // Check for working directory option before accessing any files
1501 if (Arg *WD = Args.getLastArg(Ids: options::OPT_working_directory))
1502 if (VFS->setCurrentWorkingDirectory(WD->getValue()))
1503 Diag(DiagID: diag::err_drv_unable_to_set_working_directory) << WD->getValue();
1504
1505 // Check for missing include directories.
1506 if (!Diags.isIgnored(DiagID: diag::warn_missing_include_dirs, Loc: SourceLocation())) {
1507 for (auto IncludeDir : Args.getAllArgValues(Id: options::OPT_I_Group)) {
1508 if (!VFS->exists(Path: IncludeDir))
1509 Diag(DiagID: diag::warn_missing_include_dirs) << IncludeDir;
1510 }
1511 }
1512
1513 // FIXME: This stuff needs to go into the Compilation, not the driver.
1514 bool CCCPrintPhases;
1515
1516 // -canonical-prefixes, -no-canonical-prefixes are used very early in main.
1517 Args.ClaimAllArgs(Id0: options::OPT_canonical_prefixes);
1518 Args.ClaimAllArgs(Id0: options::OPT_no_canonical_prefixes);
1519
1520 // f(no-)integated-cc1 is also used very early in main.
1521 Args.ClaimAllArgs(Id0: options::OPT_fintegrated_cc1);
1522 Args.ClaimAllArgs(Id0: options::OPT_fno_integrated_cc1);
1523
1524 // Ignore -pipe.
1525 Args.ClaimAllArgs(Id0: options::OPT_pipe);
1526
1527 // Extract -ccc args.
1528 //
1529 // FIXME: We need to figure out where this behavior should live. Most of it
1530 // should be outside in the client; the parts that aren't should have proper
1531 // options, either by introducing new ones or by overloading gcc ones like -V
1532 // or -b.
1533 CCCPrintPhases = Args.hasArg(Ids: options::OPT_ccc_print_phases);
1534 CCCPrintBindings = Args.hasArg(Ids: options::OPT_ccc_print_bindings);
1535 if (const Arg *A = Args.getLastArg(Ids: options::OPT_ccc_gcc_name))
1536 CCCGenericGCCName = A->getValue();
1537
1538 // Process -fproc-stat-report options.
1539 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fproc_stat_report_EQ)) {
1540 CCPrintProcessStats = true;
1541 CCPrintStatReportFilename = A->getValue();
1542 }
1543 if (Args.hasArg(Ids: options::OPT_fproc_stat_report))
1544 CCPrintProcessStats = true;
1545
1546 // FIXME: TargetTriple is used by the target-prefixed calls to as/ld
1547 // and getToolChain is const.
1548 if (IsCLMode()) {
1549 // clang-cl targets MSVC-style Win32.
1550 llvm::Triple T(TargetTriple);
1551 T.setOS(llvm::Triple::Win32);
1552 T.setVendor(llvm::Triple::PC);
1553 T.setEnvironment(llvm::Triple::MSVC);
1554 T.setObjectFormat(llvm::Triple::COFF);
1555 if (Args.hasArg(Ids: options::OPT__SLASH_arm64EC))
1556 T.setArch(Kind: llvm::Triple::aarch64, SubArch: llvm::Triple::AArch64SubArch_arm64ec);
1557 TargetTriple = T.str();
1558 } else if (IsDXCMode()) {
1559 // Build TargetTriple from target_profile option for clang-dxc.
1560 if (const Arg *A = Args.getLastArg(Ids: options::OPT_target_profile)) {
1561 StringRef TargetProfile = A->getValue();
1562 if (auto Triple =
1563 toolchains::HLSLToolChain::parseTargetProfile(TargetProfile))
1564 TargetTriple = *Triple;
1565 else
1566 Diag(DiagID: diag::err_drv_invalid_directx_shader_module) << TargetProfile;
1567
1568 A->claim();
1569
1570 if (Args.hasArg(Ids: options::OPT_spirv)) {
1571 const llvm::StringMap<llvm::Triple::SubArchType> ValidTargets = {
1572 {"vulkan1.2", llvm::Triple::SPIRVSubArch_v15},
1573 {"vulkan1.3", llvm::Triple::SPIRVSubArch_v16}};
1574 llvm::Triple T(TargetTriple);
1575
1576 // Set specific Vulkan version. Default to vulkan1.3.
1577 auto TargetInfo = ValidTargets.find(Key: "vulkan1.3");
1578 assert(TargetInfo != ValidTargets.end());
1579 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fspv_target_env_EQ)) {
1580 TargetInfo = ValidTargets.find(Key: A->getValue());
1581 if (TargetInfo == ValidTargets.end()) {
1582 Diag(DiagID: diag::err_drv_invalid_value)
1583 << A->getAsString(Args) << A->getValue();
1584 }
1585 A->claim();
1586 }
1587 if (TargetInfo != ValidTargets.end()) {
1588 T.setOSName(TargetInfo->getKey());
1589 T.setArch(Kind: llvm::Triple::spirv, SubArch: TargetInfo->getValue());
1590 TargetTriple = T.str();
1591 }
1592 }
1593 } else {
1594 Diag(DiagID: diag::err_drv_dxc_missing_target_profile);
1595 }
1596 }
1597
1598 if (const Arg *A = Args.getLastArg(Ids: options::OPT_target))
1599 TargetTriple = A->getValue();
1600 if (const Arg *A = Args.getLastArg(Ids: options::OPT_ccc_install_dir))
1601 Dir = A->getValue();
1602 for (const Arg *A : Args.filtered(Ids: options::OPT_B)) {
1603 A->claim();
1604 PrefixDirs.push_back(Elt: A->getValue(N: 0));
1605 }
1606 if (std::optional<std::string> CompilerPathValue =
1607 llvm::sys::Process::GetEnv(name: "COMPILER_PATH")) {
1608 StringRef CompilerPath = *CompilerPathValue;
1609 while (!CompilerPath.empty()) {
1610 std::pair<StringRef, StringRef> Split =
1611 CompilerPath.split(Separator: llvm::sys::EnvPathSeparator);
1612 PrefixDirs.push_back(Elt: std::string(Split.first));
1613 CompilerPath = Split.second;
1614 }
1615 }
1616 if (const Arg *A = Args.getLastArg(Ids: options::OPT__sysroot_EQ))
1617 SysRoot = A->getValue();
1618 if (const Arg *A = Args.getLastArg(Ids: options::OPT__dyld_prefix_EQ))
1619 DyldPrefix = A->getValue();
1620
1621 if (const Arg *A = Args.getLastArg(Ids: options::OPT_resource_dir))
1622 ResourceDir = A->getValue();
1623
1624 if (const Arg *A = Args.getLastArg(Ids: options::OPT_save_temps_EQ)) {
1625 SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
1626 .Case(S: "cwd", Value: SaveTempsCwd)
1627 .Case(S: "obj", Value: SaveTempsObj)
1628 .Default(Value: SaveTempsCwd);
1629 }
1630
1631 if (const Arg *A = Args.getLastArg(Ids: options::OPT_offload_host_only,
1632 Ids: options::OPT_offload_device_only,
1633 Ids: options::OPT_offload_host_device)) {
1634 if (A->getOption().matches(ID: options::OPT_offload_host_only))
1635 Offload = OffloadHost;
1636 else if (A->getOption().matches(ID: options::OPT_offload_device_only))
1637 Offload = OffloadDevice;
1638 else
1639 Offload = OffloadHostDevice;
1640 }
1641
1642 // Process -fembed-bitcode= flags.
1643 if (Arg *A = Args.getLastArg(Ids: options::OPT_fembed_bitcode_EQ)) {
1644 StringRef Name = A->getValue();
1645 unsigned Model = llvm::StringSwitch<unsigned>(Name)
1646 .Case(S: "off", Value: EmbedNone)
1647 .Case(S: "all", Value: EmbedBitcode)
1648 .Case(S: "bitcode", Value: EmbedBitcode)
1649 .Case(S: "marker", Value: EmbedMarker)
1650 .Default(Value: ~0U);
1651 if (Model == ~0U) {
1652 Diags.Report(DiagID: diag::err_drv_invalid_value) << A->getAsString(Args)
1653 << Name;
1654 } else
1655 BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
1656 }
1657
1658 // Remove existing compilation database so that each job can append to it.
1659 if (Arg *A = Args.getLastArg(Ids: options::OPT_MJ))
1660 llvm::sys::fs::remove(path: A->getValue());
1661
1662 // Setting up the jobs for some precompile cases depends on whether we are
1663 // treating them as PCH, implicit modules or C++20 ones.
1664 // TODO: inferring the mode like this seems fragile (it meets the objective
1665 // of not requiring anything new for operation, however).
1666 const Arg *Std = Args.getLastArg(Ids: options::OPT_std_EQ);
1667 ModulesModeCXX20 =
1668 !Args.hasArg(Ids: options::OPT_fmodules) && Std &&
1669 (Std->containsValue(Value: "c++20") || Std->containsValue(Value: "c++2a") ||
1670 Std->containsValue(Value: "c++23") || Std->containsValue(Value: "c++2b") ||
1671 Std->containsValue(Value: "c++26") || Std->containsValue(Value: "c++2c") ||
1672 Std->containsValue(Value: "c++2d") || Std->containsValue(Value: "c++latest"));
1673
1674 // Process -fmodule-header{=} flags.
1675 if (Arg *A = Args.getLastArg(Ids: options::OPT_fmodule_header_EQ,
1676 Ids: options::OPT_fmodule_header)) {
1677 // These flags force C++20 handling of headers.
1678 ModulesModeCXX20 = true;
1679 if (A->getOption().matches(ID: options::OPT_fmodule_header))
1680 CXX20HeaderType = HeaderMode_Default;
1681 else {
1682 StringRef ArgName = A->getValue();
1683 unsigned Kind = llvm::StringSwitch<unsigned>(ArgName)
1684 .Case(S: "user", Value: HeaderMode_User)
1685 .Case(S: "system", Value: HeaderMode_System)
1686 .Default(Value: ~0U);
1687 if (Kind == ~0U) {
1688 Diags.Report(DiagID: diag::err_drv_invalid_value)
1689 << A->getAsString(Args) << ArgName;
1690 } else
1691 CXX20HeaderType = static_cast<ModuleHeaderMode>(Kind);
1692 }
1693 }
1694
1695 std::unique_ptr<llvm::opt::InputArgList> UArgs =
1696 std::make_unique<InputArgList>(args: std::move(Args));
1697
1698 // Owned by the host.
1699 const ToolChain &TC =
1700 getToolChain(Args: *UArgs, Target: computeTargetTriple(D: *this, TargetTriple, Args: *UArgs));
1701
1702 {
1703 SmallVector<std::string> MultilibMacroDefinesStr =
1704 TC.getMultilibMacroDefinesStr(Args&: *UArgs);
1705 SmallVector<const char *> MLMacroDefinesChar(
1706 llvm::map_range(C&: MultilibMacroDefinesStr, F: [&UArgs](const auto &S) {
1707 return UArgs->MakeArgString(Str: Twine("-D") + Twine(S));
1708 }));
1709 bool MLContainsError;
1710 auto MultilibMacroDefineList =
1711 std::make_unique<InputArgList>(args: ParseArgStrings(
1712 ArgStrings: MLMacroDefinesChar, /*UseDriverMode=*/false, ContainsError&: MLContainsError));
1713 if (!MLContainsError) {
1714 for (auto *Opt : *MultilibMacroDefineList) {
1715 appendOneArg(Args&: *UArgs, Opt);
1716 }
1717 }
1718 }
1719
1720 // Perform the default argument translations.
1721 DerivedArgList *TranslatedArgs = TranslateInputArgs(Args: *UArgs);
1722
1723 // Check if the environment version is valid except wasm case.
1724 llvm::Triple Triple = TC.getTriple();
1725 if (!Triple.isWasm()) {
1726 StringRef TripleVersionName = Triple.getEnvironmentVersionString();
1727 StringRef TripleObjectFormat =
1728 Triple.getObjectFormatTypeName(ObjectFormat: Triple.getObjectFormat());
1729 if (Triple.getEnvironmentVersion().empty() && TripleVersionName != "" &&
1730 TripleVersionName != TripleObjectFormat) {
1731 Diags.Report(DiagID: diag::err_drv_triple_version_invalid)
1732 << TripleVersionName << TC.getTripleString();
1733 ContainsError = true;
1734 }
1735 }
1736
1737 // Report warning when arm64EC option is overridden by specified target
1738 if ((TC.getTriple().getArch() != llvm::Triple::aarch64 ||
1739 TC.getTriple().getSubArch() != llvm::Triple::AArch64SubArch_arm64ec) &&
1740 UArgs->hasArg(Ids: options::OPT__SLASH_arm64EC)) {
1741 getDiags().Report(DiagID: clang::diag::warn_target_override_arm64ec)
1742 << TC.getTripleString();
1743 }
1744
1745 // A common user mistake is specifying a target of aarch64-none-eabi or
1746 // arm-none-elf whereas the correct names are aarch64-none-elf &
1747 // arm-none-eabi. Detect these cases and issue a warning.
1748 if (TC.getTriple().getOS() == llvm::Triple::UnknownOS &&
1749 TC.getTriple().getVendor() == llvm::Triple::UnknownVendor) {
1750 switch (TC.getTriple().getArch()) {
1751 case llvm::Triple::arm:
1752 case llvm::Triple::armeb:
1753 case llvm::Triple::thumb:
1754 case llvm::Triple::thumbeb:
1755 if (TC.getTriple().getEnvironmentName() == "elf") {
1756 Diag(DiagID: diag::warn_target_unrecognized_env)
1757 << TargetTriple
1758 << (TC.getTriple().getArchName().str() + "-none-eabi");
1759 }
1760 break;
1761 case llvm::Triple::aarch64:
1762 case llvm::Triple::aarch64_be:
1763 case llvm::Triple::aarch64_32:
1764 if (TC.getTriple().getEnvironmentName().starts_with(Prefix: "eabi")) {
1765 Diag(DiagID: diag::warn_target_unrecognized_env)
1766 << TargetTriple
1767 << (TC.getTriple().getArchName().str() + "-none-elf");
1768 }
1769 break;
1770 default:
1771 break;
1772 }
1773 }
1774
1775 // The compilation takes ownership of Args.
1776 Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs,
1777 ContainsError);
1778
1779 if (!HandleImmediateArgs(C&: *C))
1780 return C;
1781
1782 // Construct the list of inputs.
1783 InputList Inputs;
1784 BuildInputs(TC: C->getDefaultToolChain(), Args&: *TranslatedArgs, Inputs);
1785 if (HasConfigFileTail && Inputs.size()) {
1786 Arg *FinalPhaseArg;
1787 if (getFinalPhase(DAL: *TranslatedArgs, FinalPhaseArg: &FinalPhaseArg) == phases::Link) {
1788 DerivedArgList TranslatedLinkerIns(*CfgOptionsTail);
1789 for (Arg *A : *CfgOptionsTail)
1790 TranslatedLinkerIns.append(A);
1791 BuildInputs(TC: C->getDefaultToolChain(), Args&: TranslatedLinkerIns, Inputs);
1792 }
1793 }
1794
1795 // Populate the tool chains for the offloading devices, if any.
1796 CreateOffloadingDeviceToolChains(C&: *C, Inputs);
1797
1798 bool UseModulesDriver = C->getArgs().hasFlag(
1799 Pos: options::OPT_fmodules_driver, Neg: options::OPT_fno_modules_driver, Default: false);
1800 modules::StdModuleManifest ModulesManifest;
1801 if (UseModulesDriver) {
1802 Diags.Report(DiagID: diag::remark_performing_driver_managed_module_build);
1803
1804 modules::diagnoseModulesDriverArgs(DAL&: C->getArgs(), Diags);
1805
1806 // Read the Standard library module manifest and, if available, add all
1807 // discovered modules to this Compilation. Jobs for modules specified in
1808 // the manifest that are not required by any command-line input are pruned
1809 // later.
1810 const auto StdModuleManifestPath =
1811 GetStdModuleManifestPath(C: *C, TC: C->getDefaultToolChain());
1812
1813 if (!llvm::sys::fs::exists(Path: StdModuleManifestPath))
1814 Diags.Report(DiagID: diag::remark_modules_manifest_not_found);
1815 else {
1816 Diags.Report(DiagID: diag::remark_using_modules_manifest)
1817 << StdModuleManifestPath;
1818 if (auto ManifestOrErr =
1819 modules::readStdModuleManifest(ManifestPath: StdModuleManifestPath, VFS&: getVFS())) {
1820 ModulesManifest = std::move(*ManifestOrErr);
1821 // Only allow on-demand imports of standard library modules for now.
1822 llvm::erase_if(C&: ModulesManifest.Modules, P: [](const auto &ModuleEntry) {
1823 return !ModuleEntry.IsStdlib;
1824 });
1825 modules::buildStdModuleManifestInputs(ManifestEntries: ModulesManifest.Modules, C&: *C,
1826 Inputs);
1827 } else {
1828 llvm::handleAllErrors(
1829 E: ManifestOrErr.takeError(),
1830 Handlers: [&](llvm::json::ParseError &Err) {
1831 Diags.Report(DiagID: diag::err_modules_manifest_failed_parse)
1832 << Err.message();
1833 },
1834 Handlers: [&](llvm::FileError &Err) {
1835 Diags.Report(DiagID: diag::err_cannot_open_file)
1836 << Err.getFileName() << Err.messageWithoutFileInfo();
1837 });
1838 }
1839 }
1840 }
1841
1842 // Construct the list of abstract actions to perform for this compilation. On
1843 // MachO targets this uses the driver-driver and universal actions.
1844 if (TC.getTriple().isOSBinFormatMachO())
1845 BuildUniversalActions(C&: *C, TC: C->getDefaultToolChain(), BAInputs: Inputs);
1846 else
1847 BuildActions(C&: *C, Args&: C->getArgs(), Inputs, Actions&: C->getActions());
1848
1849 if (CCCPrintPhases) {
1850 PrintActions(C: *C);
1851 return C;
1852 }
1853
1854 BuildJobs(C&: *C);
1855
1856 if (UseModulesDriver)
1857 modules::runModulesDriver(C&: *C, ManifestEntries: ModulesManifest.Modules);
1858
1859 return C;
1860}
1861
1862static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
1863 llvm::opt::ArgStringList ASL;
1864 for (const auto *A : Args) {
1865 // Use user's original spelling of flags. For example, use
1866 // `/source-charset:utf-8` instead of `-finput-charset=utf-8` if the user
1867 // wrote the former.
1868 while (A->getAlias())
1869 A = A->getAlias();
1870 A->render(Args, Output&: ASL);
1871 }
1872
1873 for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
1874 if (I != ASL.begin())
1875 OS << ' ';
1876 llvm::sys::printArg(OS, Arg: *I, Quote: true);
1877 }
1878 OS << '\n';
1879}
1880
1881bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename,
1882 SmallString<128> &CrashDiagDir) {
1883 using namespace llvm::sys;
1884 assert(llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin() &&
1885 "Only knows about .crash files on Darwin");
1886 // This is not a formal output of the compiler, let's bypass the sandbox.
1887 auto BypassSandbox = sandbox::scopedDisable();
1888
1889 // The .crash file can be found on at ~/Library/Logs/DiagnosticReports/
1890 // (or /Library/Logs/DiagnosticReports for root) and has the filename pattern
1891 // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash.
1892 path::home_directory(result&: CrashDiagDir);
1893 if (CrashDiagDir.starts_with(Prefix: "/var/root"))
1894 CrashDiagDir = "/";
1895 path::append(path&: CrashDiagDir, a: "Library/Logs/DiagnosticReports");
1896 int PID =
1897#if LLVM_ON_UNIX
1898 getpid();
1899#else
1900 0;
1901#endif
1902 std::error_code EC;
1903 fs::file_status FileStatus;
1904 TimePoint<> LastAccessTime;
1905 SmallString<128> CrashFilePath;
1906 // Lookup the .crash files and get the one generated by a subprocess spawned
1907 // by this driver invocation.
1908 for (fs::directory_iterator File(CrashDiagDir, EC), FileEnd;
1909 File != FileEnd && !EC; File.increment(ec&: EC)) {
1910 StringRef FileName = path::filename(path: File->path());
1911 if (!FileName.starts_with(Prefix: Name))
1912 continue;
1913 if (fs::status(path: File->path(), result&: FileStatus))
1914 continue;
1915 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CrashFile =
1916 llvm::MemoryBuffer::getFile(Filename: File->path());
1917 if (!CrashFile)
1918 continue;
1919 // The first line should start with "Process:", otherwise this isn't a real
1920 // .crash file.
1921 StringRef Data = CrashFile.get()->getBuffer();
1922 if (!Data.starts_with(Prefix: "Process:"))
1923 continue;
1924 // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]"
1925 size_t ParentProcPos = Data.find(Str: "Parent Process:");
1926 if (ParentProcPos == StringRef::npos)
1927 continue;
1928 size_t LineEnd = Data.find_first_of(Chars: "\n", From: ParentProcPos);
1929 if (LineEnd == StringRef::npos)
1930 continue;
1931 StringRef ParentProcess = Data.slice(Start: ParentProcPos+15, End: LineEnd).trim();
1932 int OpenBracket = -1, CloseBracket = -1;
1933 for (size_t i = 0, e = ParentProcess.size(); i < e; ++i) {
1934 if (ParentProcess[i] == '[')
1935 OpenBracket = i;
1936 if (ParentProcess[i] == ']')
1937 CloseBracket = i;
1938 }
1939 // Extract the parent process PID from the .crash file and check whether
1940 // it matches this driver invocation pid.
1941 int CrashPID;
1942 if (OpenBracket < 0 || CloseBracket < 0 ||
1943 ParentProcess.slice(Start: OpenBracket + 1, End: CloseBracket)
1944 .getAsInteger(Radix: 10, Result&: CrashPID) || CrashPID != PID) {
1945 continue;
1946 }
1947
1948 // Found a .crash file matching the driver pid. To avoid getting an older
1949 // and misleading crash file, continue looking for the most recent.
1950 // FIXME: the driver can dispatch multiple cc1 invocations, leading to
1951 // multiple crashes poiting to the same parent process. Since the driver
1952 // does not collect pid information for the dispatched invocation there's
1953 // currently no way to distinguish among them.
1954 const auto FileAccessTime = FileStatus.getLastModificationTime();
1955 if (FileAccessTime > LastAccessTime) {
1956 CrashFilePath.assign(RHS: File->path());
1957 LastAccessTime = FileAccessTime;
1958 }
1959 }
1960
1961 // If found, copy it over to the location of other reproducer files.
1962 if (!CrashFilePath.empty()) {
1963 EC = fs::copy_file(From: CrashFilePath, To: ReproCrashFilename);
1964 if (EC)
1965 return false;
1966 return true;
1967 }
1968
1969 return false;
1970}
1971
1972static const char BugReportMsg[] =
1973 "\n********************\n\n"
1974 "PLEASE ATTACH THE FOLLOWING CRASH REPRODUCER FILES TO THE BUG REPORT:";
1975
1976// When clang crashes, produce diagnostic information including the fully
1977// preprocessed source file(s). Request that the developer attach the
1978// diagnostic information to a bug report.
1979void Driver::generateCompilationDiagnostics(
1980 Compilation &C, const Command &FailingCommand,
1981 StringRef AdditionalInformation, CompilationDiagnosticReport *Report) {
1982 if (C.getArgs().hasArg(Ids: options::OPT_fno_crash_diagnostics))
1983 return;
1984
1985 bool HasCrashTar = C.getArgs().hasArg(Ids: options::OPT_fcrash_diagnostics_tar);
1986
1987 unsigned Level = 1;
1988 if (Arg *A = C.getArgs().getLastArg(Ids: options::OPT_fcrash_diagnostics_EQ)) {
1989 Level = llvm::StringSwitch<unsigned>(A->getValue())
1990 .Case(S: "off", Value: 0)
1991 .Case(S: "compiler", Value: 1)
1992 .Case(S: "all", Value: 2)
1993 .Default(Value: 1);
1994 }
1995 if (!Level)
1996 return;
1997
1998 // Don't try to generate diagnostics for dsymutil jobs.
1999 if (FailingCommand.getCreator().isDsymutilJob())
2000 return;
2001
2002 bool IsLLD = false;
2003 ArgStringList SavedTemps;
2004 if (FailingCommand.getCreator().isLinkJob()) {
2005 C.getDefaultToolChain().GetLinkerPath(LinkerIsLLD: &IsLLD);
2006 if (!IsLLD || Level < 2)
2007 return;
2008
2009 // If lld crashed, we will re-run the same command with the input it used
2010 // to have. In that case we should not remove temp files in
2011 // initCompilationForDiagnostics yet. They will be added back and removed
2012 // later.
2013 SavedTemps = std::move(C.getTempFiles());
2014 assert(!C.getTempFiles().size());
2015 }
2016
2017 // Print the version of the compiler.
2018 PrintVersion(C, OS&: llvm::errs());
2019
2020 // Suppress driver output and emit preprocessor output to temp file.
2021 CCGenDiagnostics = true;
2022
2023 // Save the original job command(s).
2024 Command Cmd = FailingCommand;
2025
2026 // Keep track of whether we produce any errors while trying to produce
2027 // preprocessed sources.
2028 DiagnosticErrorTrap Trap(Diags);
2029
2030 // Suppress tool output.
2031 C.initCompilationForDiagnostics();
2032
2033 // If lld failed, rerun it again with --reproduce.
2034 if (IsLLD) {
2035 const char *TmpName = CreateTempFile(C, Prefix: "linker-crash", Suffix: "tar");
2036 Command NewLLDInvocation = Cmd;
2037 llvm::opt::ArgStringList ArgList = NewLLDInvocation.getArguments();
2038 StringRef ReproduceOption =
2039 C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment()
2040 ? "/reproduce:"
2041 : "--reproduce=";
2042 ArgList.push_back(Elt: Saver.save(S: Twine(ReproduceOption) + TmpName).data());
2043 NewLLDInvocation.replaceArguments(List: std::move(ArgList));
2044
2045 // Redirect stdout/stderr to /dev/null.
2046 NewLLDInvocation.Execute(Redirects: {std::nullopt, {""}, {""}}, ErrMsg: nullptr, ExecutionFailed: nullptr);
2047 Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) << BugReportMsg;
2048 Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) << TmpName;
2049 Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg)
2050 << "\n\n********************";
2051 if (Report)
2052 Report->TemporaryFiles.push_back(Elt: TmpName);
2053 return;
2054 }
2055
2056 // Construct the list of inputs.
2057 InputList Inputs;
2058 BuildInputs(TC: C.getDefaultToolChain(), Args&: C.getArgs(), Inputs);
2059
2060 ArgStringList IRInputs;
2061 for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
2062 bool IgnoreInput = false;
2063
2064 // Save IR inputs separately, ignore input from stdin or any other inputs
2065 // that cannot be preprocessed. Check type first as not all linker inputs
2066 // have a value.
2067 if (types::isLLVMIR(Id: it->first)) {
2068 IRInputs.push_back(Elt: it->second->getValue());
2069 IgnoreInput = true;
2070 } else if (types::getPreprocessedType(Id: it->first) == types::TY_INVALID) {
2071 IgnoreInput = true;
2072 } else if (!strcmp(s1: it->second->getValue(), s2: "-")) {
2073 Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg)
2074 << "Error generating preprocessed source(s) - "
2075 "ignoring input from stdin.";
2076 IgnoreInput = true;
2077 }
2078
2079 if (IgnoreInput) {
2080 it = Inputs.erase(CI: it);
2081 ie = Inputs.end();
2082 } else {
2083 ++it;
2084 }
2085 }
2086
2087 if (Inputs.empty() && IRInputs.empty()) {
2088 Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg)
2089 << "Error generating preprocessed source(s) - "
2090 "no preprocessable inputs.";
2091 return;
2092 }
2093
2094 // If there are multiple -arch options, build a reproducer only for the bound
2095 // arch that crashed.
2096 llvm::StringSet<> ArchNames;
2097 for (const Arg *A : C.getArgs()) {
2098 if (A->getOption().matches(ID: options::OPT_arch)) {
2099 StringRef ArchName = A->getValue();
2100 ArchNames.insert(key: ArchName);
2101 }
2102 }
2103 if (ArchNames.size() > 1) {
2104 // Build a reproducer only for the bound arch that crashed.
2105 StringRef FailingArch = Cmd.getBoundArch().ArchName;
2106 if (FailingArch.empty()) {
2107 Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg)
2108 << "Error generating preprocessed source(s) - cannot generate "
2109 "preprocessed source with multiple -arch options.";
2110 return;
2111 }
2112 C.getArgs().eraseArg(Id: options::OPT_arch);
2113 C.getArgs().AddJoinedArg(BaseArg: nullptr, Opt: getOpts().getOption(Opt: options::OPT_arch),
2114 Value: FailingArch);
2115 }
2116
2117 // If we only have IR inputs there's no need for preprocessing.
2118 if (!Inputs.empty()) {
2119 // Construct the list of abstract actions to perform for this compilation.
2120 // On Darwin OSes this uses the driver-driver and builds universal actions.
2121 const ToolChain &TC = C.getDefaultToolChain();
2122 if (TC.getTriple().isOSBinFormatMachO())
2123 BuildUniversalActions(C, TC, BAInputs: Inputs);
2124 else
2125 BuildActions(C, Args&: C.getArgs(), Inputs, Actions&: C.getActions());
2126
2127 BuildJobs(C);
2128
2129 // If there were errors building the compilation, quit now.
2130 if (Trap.hasErrorOccurred()) {
2131 Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg)
2132 << "Error generating preprocessed source(s).";
2133 return;
2134 }
2135 // Generate preprocessed output.
2136 SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
2137 C.ExecuteJobs(Jobs: C.getJobs(), FailingCommands);
2138
2139 // If any of the preprocessing commands failed, clean up and exit.
2140 if (!FailingCommands.empty()) {
2141 Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg)
2142 << "Error generating preprocessed source(s).";
2143 return;
2144 }
2145
2146 const ArgStringList &TempFiles = C.getTempFiles();
2147 if (TempFiles.empty()) {
2148 Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg)
2149 << "Error generating preprocessed source(s).";
2150 return;
2151 }
2152 }
2153
2154 // Copying filenames due to ownership.
2155 const ArgStringList &Files = C.getTempFiles();
2156 SmallVector<std::string> TempFiles(Files.begin(), Files.end());
2157
2158 // We'd like to copy the IR input file into our own temp file
2159 // because the build system might try to clean-up after itself.
2160 for (auto const *Input : IRInputs) {
2161 int FD;
2162 llvm::SmallVector<char, 64> Path;
2163
2164 StringRef extension = llvm::sys::path::extension(path: Input);
2165 if (!extension.empty())
2166 extension = extension.drop_front();
2167
2168 std::error_code EC = llvm::sys::fs::createTemporaryFile(
2169 Prefix: llvm::sys::path::stem(path: Input), Suffix: extension, ResultFD&: FD, ResultPath&: Path);
2170 if (EC) {
2171 Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg)
2172 << "Error generating run script: " << "Failed copying IR input files"
2173 << " " << EC.message();
2174 return;
2175 }
2176
2177 EC = llvm::sys::fs::copy_file(From: Input, ToFD: FD);
2178 if (EC) {
2179 Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg)
2180 << "Error generating run script: " << "Failed copying IR input files"
2181 << " " << EC.message();
2182 return;
2183 }
2184
2185 TempFiles.push_back(Elt: std::string(Path.begin(), Path.end()));
2186 }
2187
2188 Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) << BugReportMsg;
2189
2190 SmallString<128> VFS;
2191 SmallString<128> ReproCrashFilename;
2192 for (std::string &TempFile : TempFiles) {
2193 if (!HasCrashTar)
2194 Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) << TempFile;
2195 if (Report)
2196 Report->TemporaryFiles.push_back(Elt: TempFile);
2197 if (ReproCrashFilename.empty()) {
2198 ReproCrashFilename = TempFile;
2199 llvm::sys::path::replace_extension(path&: ReproCrashFilename, extension: ".crash");
2200 }
2201 if (StringRef(TempFile).ends_with(Suffix: ".cache")) {
2202 // In some cases (modules) we'll dump extra data to help with reproducing
2203 // the crash into a directory next to the output.
2204 VFS = llvm::sys::path::filename(path: TempFile);
2205 llvm::sys::path::append(path&: VFS, a: "vfs", b: "vfs.yaml");
2206 }
2207 }
2208
2209 for (const char *TempFile : SavedTemps)
2210 TempFiles.push_back(Elt: TempFile);
2211
2212 // Assume associated files are based off of the first temporary file.
2213 CrashReportInfo CrashInfo(TempFiles[0], VFS);
2214
2215 llvm::SmallString<128> Script(CrashInfo.Filename);
2216 llvm::sys::path::replace_extension(path&: Script, extension: "sh");
2217 std::error_code EC;
2218 llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::CD_CreateNew,
2219 llvm::sys::fs::FA_Write,
2220 llvm::sys::fs::OF_Text);
2221 if (EC) {
2222 Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg)
2223 << "Error generating run script: " << Script << " " << EC.message();
2224 } else {
2225 ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
2226 << "# Driver args: ";
2227 printArgList(OS&: ScriptOS, Args: C.getInputArgs());
2228 ScriptOS << "# Original command: ";
2229 Cmd.Print(OS&: ScriptOS, Terminator: "\n", /*Quote=*/true);
2230 Cmd.Print(OS&: ScriptOS, Terminator: "\n", /*Quote=*/true, CrashInfo: &CrashInfo);
2231 if (!AdditionalInformation.empty())
2232 ScriptOS << "\n# Additional information: " << AdditionalInformation
2233 << "\n";
2234 if (Report)
2235 Report->TemporaryFiles.push_back(Elt: std::string(Script));
2236 TempFiles.push_back(Elt: std::string(Script));
2237 ScriptOS.close();
2238 if (!HasCrashTar)
2239 Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg) << Script;
2240 }
2241
2242 if (Arg *A = C.getArgs().getLastArg(Ids: options::OPT_fcrash_diagnostics_tar)) {
2243 StringRef CrashDiagnosticsTar = A->getValue();
2244 Expected<std::unique_ptr<llvm::TarWriter>> TarOrErr =
2245 llvm::TarWriter::create(OutputPath: CrashDiagnosticsTar,
2246 BaseDir: llvm::sys::path::stem(path: CrashDiagnosticsTar));
2247 if (!TarOrErr) {
2248 Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg)
2249 << (std::string("Error creating reproducer tarball: ") +
2250 llvm::toString(E: TarOrErr.takeError()));
2251 } else {
2252 std::unique_ptr<llvm::TarWriter> &Tar = *TarOrErr;
2253 for (const std::string &TempFile : TempFiles) {
2254 if (llvm::sys::fs::is_directory(Path: TempFile)) {
2255 std::error_code EC;
2256 for (llvm::sys::fs::recursive_directory_iterator I(TempFile, EC), E;
2257 I != E && !EC; I.increment(ec&: EC)) {
2258 if (llvm::sys::fs::is_regular_file(Path: I->path())) {
2259 auto BufferOrErr = llvm::MemoryBuffer::getFile(Filename: I->path());
2260 if (BufferOrErr) {
2261 // Construct path of file relative to TempFile.
2262 llvm::SmallString<128> PathInTar =
2263 llvm::sys::path::filename(path: TempFile);
2264 StringRef SubPath = I->path();
2265 if (SubPath.consume_front(Prefix: TempFile)) {
2266 if (!SubPath.empty() &&
2267 llvm::sys::path::is_separator(value: SubPath.front())) {
2268 SubPath = SubPath.drop_front();
2269 }
2270 llvm::sys::path::append(path&: PathInTar, a: SubPath);
2271 Tar->append(Path: PathInTar, Data: (*BufferOrErr)->getBuffer());
2272 }
2273 } else {
2274 Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg)
2275 << (std::string("Error reading file for tarball: ") +
2276 I->path());
2277 }
2278 }
2279 }
2280 if (EC) {
2281 Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg)
2282 << (std::string("Error iterating directory for tarball: ") +
2283 TempFile + " " + EC.message());
2284 }
2285 } else {
2286 auto BufferOrErr = llvm::MemoryBuffer::getFile(Filename: TempFile);
2287 if (BufferOrErr) {
2288 Tar->append(Path: llvm::sys::path::filename(path: TempFile),
2289 Data: (*BufferOrErr)->getBuffer());
2290 } else {
2291 Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg)
2292 << (std::string("Error reading file for tarball: ") + TempFile);
2293 }
2294 }
2295 }
2296 Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg)
2297 << CrashDiagnosticsTar;
2298 }
2299 }
2300
2301 // On darwin, provide information about the .crash diagnostic report.
2302 if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) {
2303 SmallString<128> CrashDiagDir;
2304 if (getCrashDiagnosticFile(ReproCrashFilename, CrashDiagDir)) {
2305 Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg)
2306 << ReproCrashFilename.str();
2307 } else { // Suggest a directory for the user to look for .crash files.
2308 llvm::sys::path::append(path&: CrashDiagDir, a: Name);
2309 CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash";
2310 Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg)
2311 << "Crash backtrace is located in";
2312 Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg)
2313 << CrashDiagDir.str();
2314 Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg)
2315 << "(choose the .crash file that corresponds to your crash)";
2316 }
2317 }
2318
2319 Diag(DiagID: clang::diag::note_drv_command_failed_diag_msg)
2320 << "\n\n********************";
2321}
2322
2323void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
2324 // Since commandLineFitsWithinSystemLimits() may underestimate system's
2325 // capacity if the tool does not support response files, there is a chance/
2326 // that things will just work without a response file, so we silently just
2327 // skip it.
2328 if (Cmd.getResponseFileSupport().ResponseKind ==
2329 ResponseFileSupport::RF_None ||
2330 llvm::sys::commandLineFitsWithinSystemLimits(Program: Cmd.getExecutable(),
2331 Args: Cmd.getArguments()))
2332 return;
2333
2334 std::string TmpName = GetTemporaryPath(Prefix: "response", Suffix: "txt");
2335 Cmd.setResponseFile(C.addTempFile(Name: C.getArgs().MakeArgString(Str: TmpName)));
2336}
2337
2338int Driver::ExecuteCompilation(
2339 Compilation &C,
2340 SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
2341 if (C.getArgs().hasArg(Ids: options::OPT_fdriver_only)) {
2342 if (C.getArgs().hasArg(Ids: options::OPT_v))
2343 C.getJobs().Print(OS&: llvm::errs(), Terminator: "\n", Quote: true);
2344
2345 C.ExecuteJobs(Jobs: C.getJobs(), FailingCommands, /*LogOnly=*/true);
2346
2347 // If there were errors building the compilation, quit now.
2348 if (!FailingCommands.empty() || Diags.hasErrorOccurred())
2349 return 1;
2350
2351 return 0;
2352 }
2353
2354 // Just print if -### was present.
2355 if (C.getArgs().hasArg(Ids: options::OPT__HASH_HASH_HASH)) {
2356 C.getJobs().Print(OS&: llvm::errs(), Terminator: "\n", Quote: true);
2357 return Diags.hasErrorOccurred() ? 1 : 0;
2358 }
2359
2360 // If there were errors building the compilation, quit now.
2361 if (Diags.hasErrorOccurred())
2362 return 1;
2363
2364 // Set up response file names for each command, if necessary.
2365 for (auto &Job : C.getJobs())
2366 setUpResponseFiles(C, Cmd&: Job);
2367
2368 C.ExecuteJobs(Jobs: C.getJobs(), FailingCommands);
2369
2370 // If the command succeeded, we are done.
2371 if (FailingCommands.empty())
2372 return 0;
2373
2374 // Otherwise, remove result files and print extra information about abnormal
2375 // failures.
2376 int Res = 0;
2377 for (const auto &CmdPair : FailingCommands) {
2378 int CommandRes = CmdPair.first;
2379 const Command *FailingCommand = CmdPair.second;
2380
2381 // Remove result files if we're not saving temps.
2382 if (!isSaveTempsEnabled()) {
2383 const JobAction *JA = cast<JobAction>(Val: &FailingCommand->getSource());
2384 C.CleanupFileMap(Files: C.getResultFiles(), JA, IssueErrors: true);
2385
2386 // Failure result files are valid unless we crashed.
2387 if (CommandRes < 0)
2388 C.CleanupFileMap(Files: C.getFailureResultFiles(), JA, IssueErrors: true);
2389 }
2390
2391 // llvm/lib/Support/*/Signals.inc will exit with a special return code
2392 // for SIGPIPE. Do not print diagnostics for this case.
2393 if (CommandRes == EX_IOERR) {
2394 Res = CommandRes;
2395 continue;
2396 }
2397
2398 // Print extra information about abnormal failures, if possible.
2399 //
2400 // This is ad-hoc, but we don't want to be excessively noisy. If the result
2401 // status was 1, assume the command failed normally. In particular, if it
2402 // was the compiler then assume it gave a reasonable error code. Failures
2403 // in other tools are less common, and they generally have worse
2404 // diagnostics, so always print the diagnostic there.
2405 const Tool &FailingTool = FailingCommand->getCreator();
2406
2407 if (!FailingCommand->getCreator().hasGoodDiagnostics() || CommandRes != 1) {
2408 // FIXME: See FIXME above regarding result code interpretation.
2409#if LLVM_ON_UNIX
2410 // On Unix, signals are represented by return codes of 128 plus the
2411 // signal number. Return code 255 is excluded because some tools,
2412 // such as llvm-ifs, exit with code 255 (-1) on failure.
2413 if (CommandRes > 128 && CommandRes != 255)
2414#else
2415 if (CommandRes < 0)
2416#endif
2417 Diag(DiagID: clang::diag::err_drv_command_signalled)
2418 << FailingTool.getShortName();
2419 else
2420 Diag(DiagID: clang::diag::err_drv_command_failed)
2421 << FailingTool.getShortName() << CommandRes;
2422 }
2423 }
2424 return Res;
2425}
2426
2427void Driver::PrintHelp(bool ShowHidden) const {
2428 llvm::opt::Visibility VisibilityMask = getOptionVisibilityMask();
2429
2430 std::string Usage = llvm::formatv(Fmt: "{0} [options] file...", Vals: Name).str();
2431 getOpts().printHelp(OS&: llvm::outs(), Usage: Usage.c_str(), Title: DriverTitle.c_str(),
2432 ShowHidden, /*ShowAllAliases=*/false,
2433 VisibilityMask);
2434}
2435
2436void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
2437 if (IsFlangMode()) {
2438 OS << getClangToolFullVersion(ToolName: "flang") << '\n';
2439 } else {
2440 // FIXME: The following handlers should use a callback mechanism, we don't
2441 // know what the client would like to do.
2442 OS << getClangFullVersion() << '\n';
2443 }
2444 const ToolChain &TC = C.getDefaultToolChain();
2445 OS << "Target: " << TC.getTripleString() << '\n';
2446
2447 // Print the threading model.
2448 if (Arg *A = C.getArgs().getLastArg(Ids: options::OPT_mthread_model)) {
2449 // Don't print if the ToolChain would have barfed on it already
2450 if (TC.isThreadModelSupported(Model: A->getValue()))
2451 OS << "Thread model: " << A->getValue();
2452 } else
2453 OS << "Thread model: " << TC.getThreadModel();
2454 OS << '\n';
2455
2456 // Print out the install directory.
2457 OS << "InstalledDir: " << Dir << '\n';
2458
2459 // Print the build config if it's non-default.
2460 // Intended to help LLVM developers understand the configs of compilers
2461 // they're investigating.
2462 if (!llvm::cl::getCompilerBuildConfig().empty())
2463 llvm::cl::printBuildConfig(OS);
2464
2465 // If configuration files were used, print their paths.
2466 for (auto ConfigFile : ConfigFiles)
2467 OS << "Configuration file: " << ConfigFile << '\n';
2468}
2469
2470/// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
2471/// option.
2472static void PrintDiagnosticCategories(raw_ostream &OS) {
2473 // Skip the empty category.
2474 for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
2475 ++i)
2476 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(CategoryID: i) << '\n';
2477}
2478
2479void Driver::HandleAutocompletions(StringRef PassedFlags) const {
2480 if (PassedFlags == "")
2481 return;
2482 // Print out all options that start with a given argument. This is used for
2483 // shell autocompletion.
2484 std::vector<std::string> SuggestedCompletions;
2485 std::vector<std::string> Flags;
2486
2487 llvm::opt::Visibility VisibilityMask(options::ClangOption);
2488
2489 // Make sure that Flang-only options don't pollute the Clang output
2490 // TODO: Make sure that Clang-only options don't pollute Flang output
2491 if (IsFlangMode())
2492 VisibilityMask = llvm::opt::Visibility(options::FlangOption);
2493
2494 // Distinguish "--autocomplete=-someflag" and "--autocomplete=-someflag,"
2495 // because the latter indicates that the user put space before pushing tab
2496 // which should end up in a file completion.
2497 const bool HasSpace = PassedFlags.ends_with(Suffix: ",");
2498
2499 // Parse PassedFlags by "," as all the command-line flags are passed to this
2500 // function separated by ","
2501 StringRef TargetFlags = PassedFlags;
2502 while (TargetFlags != "") {
2503 StringRef CurFlag;
2504 std::tie(args&: CurFlag, args&: TargetFlags) = TargetFlags.split(Separator: ",");
2505 Flags.push_back(x: std::string(CurFlag));
2506 }
2507
2508 // We want to show cc1-only options only when clang is invoked with -cc1 or
2509 // -Xclang.
2510 if (llvm::is_contained(Range&: Flags, Element: "-Xclang") || llvm::is_contained(Range&: Flags, Element: "-cc1"))
2511 VisibilityMask = llvm::opt::Visibility(options::CC1Option);
2512
2513 const llvm::opt::OptTable &Opts = getOpts();
2514 StringRef Cur;
2515 Cur = Flags.at(n: Flags.size() - 1);
2516 StringRef Prev;
2517 if (Flags.size() >= 2) {
2518 Prev = Flags.at(n: Flags.size() - 2);
2519 SuggestedCompletions = Opts.suggestValueCompletions(Option: Prev, Arg: Cur);
2520 }
2521
2522 if (SuggestedCompletions.empty())
2523 SuggestedCompletions = Opts.suggestValueCompletions(Option: Cur, Arg: "");
2524
2525 // If Flags were empty, it means the user typed `clang [tab]` where we should
2526 // list all possible flags. If there was no value completion and the user
2527 // pressed tab after a space, we should fall back to a file completion.
2528 // We're printing a newline to be consistent with what we print at the end of
2529 // this function.
2530 if (SuggestedCompletions.empty() && HasSpace && !Flags.empty()) {
2531 llvm::outs() << '\n';
2532 return;
2533 }
2534
2535 // When flag ends with '=' and there was no value completion, return empty
2536 // string and fall back to the file autocompletion.
2537 if (SuggestedCompletions.empty() && !Cur.ends_with(Suffix: "=")) {
2538 // If the flag is in the form of "--autocomplete=-foo",
2539 // we were requested to print out all option names that start with "-foo".
2540 // For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only".
2541 SuggestedCompletions = Opts.findByPrefix(
2542 Cur, VisibilityMask,
2543 /*DisableFlags=*/options::Unsupported | options::Ignored);
2544
2545 // We have to query the -W flags manually as they're not in the OptTable.
2546 // TODO: Find a good way to add them to OptTable instead and them remove
2547 // this code.
2548 for (StringRef S : DiagnosticIDs::getDiagnosticFlags())
2549 if (S.starts_with(Prefix: Cur))
2550 SuggestedCompletions.push_back(x: std::string(S));
2551 }
2552
2553 // Sort the autocomplete candidates so that shells print them out in a
2554 // deterministic order. We could sort in any way, but we chose
2555 // case-insensitive sorting for consistency with the -help option
2556 // which prints out options in the case-insensitive alphabetical order.
2557 llvm::sort(C&: SuggestedCompletions, Comp: [](StringRef A, StringRef B) {
2558 if (int X = A.compare_insensitive(RHS: B))
2559 return X < 0;
2560 return A.compare(RHS: B) > 0;
2561 });
2562
2563 llvm::outs() << llvm::join(R&: SuggestedCompletions, Separator: "\n") << '\n';
2564}
2565
2566bool Driver::HandleImmediateArgs(Compilation &C) {
2567 // The order these options are handled in gcc is all over the place, but we
2568 // don't expect inconsistencies w.r.t. that to matter in practice.
2569
2570 if (C.getArgs().hasArg(Ids: options::OPT_dumpmachine)) {
2571 llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
2572 return false;
2573 }
2574
2575 if (C.getArgs().hasArg(Ids: options::OPT_dumpversion)) {
2576 // Since -dumpversion is only implemented for pedantic GCC compatibility, we
2577 // return an answer which matches our definition of __VERSION__.
2578 llvm::outs() << CLANG_VERSION_STRING << "\n";
2579 return false;
2580 }
2581
2582 if (C.getArgs().hasArg(Ids: options::OPT__print_diagnostic_categories)) {
2583 PrintDiagnosticCategories(OS&: llvm::outs());
2584 return false;
2585 }
2586
2587 if (C.getArgs().hasArg(Ids: options::OPT_help) ||
2588 C.getArgs().hasArg(Ids: options::OPT__help_hidden)) {
2589 PrintHelp(ShowHidden: C.getArgs().hasArg(Ids: options::OPT__help_hidden));
2590 return false;
2591 }
2592
2593 if (C.getArgs().hasArg(Ids: options::OPT__version)) {
2594 // Follow gcc behavior and use stdout for --version and stderr for -v.
2595 PrintVersion(C, OS&: llvm::outs());
2596 return false;
2597 }
2598
2599 // Honor --ssaf-list-extractors, --ssaf-list-formats and their combinations.
2600 bool ListExtractors = C.getArgs().hasArg(Ids: options::OPT__ssaf_list_extractors);
2601 bool ListFormats = C.getArgs().hasArg(Ids: options::OPT__ssaf_list_formats);
2602 if (ListExtractors || ListFormats) {
2603 if (ListExtractors)
2604 ssaf::printAvailableTUSummaryExtractors(OS&: llvm::outs());
2605 if (ListFormats)
2606 ssaf::printAvailableFormats(OS&: llvm::outs());
2607 return false;
2608 }
2609
2610 if (C.getArgs().hasArg(Ids: options::OPT__ssaf_list_formats)) {
2611 ssaf::printAvailableFormats(OS&: llvm::outs());
2612 return false;
2613 }
2614
2615 if (C.getArgs().hasArg(Ids: options::OPT_v) ||
2616 C.getArgs().hasArg(Ids: options::OPT__HASH_HASH_HASH) ||
2617 C.getArgs().hasArg(Ids: options::OPT_print_supported_cpus) ||
2618 C.getArgs().hasArg(Ids: options::OPT_print_supported_extensions) ||
2619 C.getArgs().hasArg(Ids: options::OPT_print_enabled_extensions)) {
2620 PrintVersion(C, OS&: llvm::errs());
2621 SuppressMissingInputWarning = true;
2622 }
2623
2624 if (C.getArgs().hasArg(Ids: options::OPT_v)) {
2625 if (!SystemConfigDir.empty())
2626 llvm::errs() << "System configuration file directory: "
2627 << SystemConfigDir << "\n";
2628 if (!UserConfigDir.empty())
2629 llvm::errs() << "User configuration file directory: "
2630 << UserConfigDir << "\n";
2631 }
2632
2633 const ToolChain &TC = C.getDefaultToolChain();
2634
2635 if (C.getArgs().hasArg(Ids: options::OPT_v))
2636 TC.printVerboseInfo(OS&: llvm::errs());
2637
2638 if (C.getArgs().hasArg(Ids: options::OPT_print_resource_dir)) {
2639 llvm::outs() << ResourceDir << '\n';
2640 return false;
2641 }
2642
2643 if (C.getArgs().hasArg(Ids: options::OPT_print_search_dirs)) {
2644 llvm::outs() << "programs: =";
2645 bool separator = false;
2646 // Print -B and COMPILER_PATH.
2647 for (const std::string &Path : PrefixDirs) {
2648 if (separator)
2649 llvm::outs() << llvm::sys::EnvPathSeparator;
2650 llvm::outs() << Path;
2651 separator = true;
2652 }
2653 for (const std::string &Path : TC.getProgramPaths()) {
2654 if (separator)
2655 llvm::outs() << llvm::sys::EnvPathSeparator;
2656 llvm::outs() << Path;
2657 separator = true;
2658 }
2659 llvm::outs() << "\n";
2660 llvm::outs() << "libraries: =" << ResourceDir;
2661
2662 StringRef sysroot = C.getSysRoot();
2663
2664 for (const std::string &Path : TC.getFilePaths()) {
2665 // Always print a separator. ResourceDir was the first item shown.
2666 llvm::outs() << llvm::sys::EnvPathSeparator;
2667 // Interpretation of leading '=' is needed only for NetBSD.
2668 if (Path[0] == '=')
2669 llvm::outs() << sysroot << Path.substr(pos: 1);
2670 else
2671 llvm::outs() << Path;
2672 }
2673 llvm::outs() << "\n";
2674 return false;
2675 }
2676
2677 if (C.getArgs().hasArg(Ids: options::OPT_print_std_module_manifest_path)) {
2678 llvm::outs() << GetStdModuleManifestPath(C, TC: C.getDefaultToolChain())
2679 << '\n';
2680 return false;
2681 }
2682
2683 if (C.getArgs().hasArg(Ids: options::OPT_print_runtime_dir)) {
2684 for (auto RuntimePath :
2685 {TC.getRuntimePath(), std::make_optional(t: TC.getCompilerRTPath())}) {
2686 if (RuntimePath && getVFS().exists(Path: *RuntimePath)) {
2687 llvm::outs() << *RuntimePath << '\n';
2688 return false;
2689 }
2690 }
2691 llvm::outs() << "(runtime dir is not present)" << '\n';
2692 return false;
2693 }
2694
2695 if (C.getArgs().hasArg(Ids: options::OPT_print_diagnostic_options)) {
2696 std::vector<std::string> Flags = DiagnosticIDs::getDiagnosticFlags();
2697 for (std::size_t I = 0; I != Flags.size(); I += 2)
2698 llvm::outs() << " " << Flags[I] << "\n " << Flags[I + 1] << "\n\n";
2699 return false;
2700 }
2701
2702 // FIXME: The following handlers should use a callback mechanism, we don't
2703 // know what the client would like to do.
2704 if (Arg *A = C.getArgs().getLastArg(Ids: options::OPT_print_file_name_EQ)) {
2705 llvm::outs() << GetFilePath(Name: A->getValue(), TC) << "\n";
2706 return false;
2707 }
2708
2709 if (Arg *A = C.getArgs().getLastArg(Ids: options::OPT_print_prog_name_EQ)) {
2710 StringRef ProgName = A->getValue();
2711
2712 // Null program name cannot have a path.
2713 if (! ProgName.empty())
2714 llvm::outs() << GetProgramPath(Name: ProgName, TC);
2715
2716 llvm::outs() << "\n";
2717 return false;
2718 }
2719
2720 if (Arg *A = C.getArgs().getLastArg(Ids: options::OPT_autocomplete)) {
2721 StringRef PassedFlags = A->getValue();
2722 HandleAutocompletions(PassedFlags);
2723 return false;
2724 }
2725
2726 if (C.getArgs().hasArg(Ids: options::OPT_print_libgcc_file_name)) {
2727 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args: C.getArgs());
2728 const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(Args: C.getArgs()));
2729 // The 'Darwin' toolchain is initialized only when its arguments are
2730 // computed. Get the default arguments for OFK_None to ensure that
2731 // initialization is performed before trying to access properties of
2732 // the toolchain in the functions below.
2733 // FIXME: Remove when darwin's toolchain is initialized during construction.
2734 // FIXME: For some more esoteric targets the default toolchain is not the
2735 // correct one.
2736 C.getArgsForToolChain(TC: &TC, BA: BoundArch(Triple.getArchName()),
2737 DeviceOffloadKind: Action::OFK_Host);
2738 RegisterEffectiveTriple TripleRAII(TC, Triple);
2739 switch (RLT) {
2740 case ToolChain::RLT_CompilerRT:
2741 llvm::outs() << TC.getCompilerRT(Args: C.getArgs(), Component: "builtins") << "\n";
2742 break;
2743 case ToolChain::RLT_Libgcc:
2744 llvm::outs() << GetFilePath(Name: "libgcc.a", TC) << "\n";
2745 break;
2746 }
2747 return false;
2748 }
2749
2750 if (C.getArgs().hasArg(Ids: options::OPT_print_multi_lib)) {
2751 for (const Multilib &Multilib : TC.getMultilibs())
2752 if (!Multilib.isError())
2753 llvm::outs() << Multilib << "\n";
2754 return false;
2755 }
2756
2757 if (C.getArgs().hasArg(Ids: options::OPT_print_multi_flags)) {
2758 Multilib::flags_list ArgFlags = TC.getMultilibFlags(C.getArgs());
2759 llvm::StringSet<> ExpandedFlags = TC.getMultilibs().expandFlags(ArgFlags);
2760 std::set<llvm::StringRef> SortedFlags;
2761 for (const auto &FlagEntry : ExpandedFlags)
2762 SortedFlags.insert(x: FlagEntry.getKey());
2763 for (auto Flag : SortedFlags)
2764 llvm::outs() << Flag << '\n';
2765 return false;
2766 }
2767
2768 if (C.getArgs().hasArg(Ids: options::OPT_print_multi_directory)) {
2769 for (const Multilib &Multilib : TC.getSelectedMultilibs()) {
2770 if (Multilib.gccSuffix().empty())
2771 llvm::outs() << ".\n";
2772 else {
2773 StringRef Suffix(Multilib.gccSuffix());
2774 assert(Suffix.front() == '/');
2775 llvm::outs() << Suffix.substr(Start: 1) << "\n";
2776 }
2777 }
2778 return false;
2779 }
2780
2781 if (C.getArgs().hasArg(Ids: options::OPT_print_target_triple)) {
2782 llvm::outs() << TC.getTripleString() << "\n";
2783 return false;
2784 }
2785
2786 if (C.getArgs().hasArg(Ids: options::OPT_print_effective_triple)) {
2787 const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(Args: C.getArgs()));
2788 llvm::outs() << Triple.getTriple() << "\n";
2789 return false;
2790 }
2791
2792 if (C.getArgs().hasArg(Ids: options::OPT_print_targets)) {
2793 llvm::TargetRegistry::printRegisteredTargetsForVersion(OS&: llvm::outs());
2794 return false;
2795 }
2796
2797 return true;
2798}
2799
2800enum {
2801 TopLevelAction = 0,
2802 HeadSibAction = 1,
2803 OtherSibAction = 2,
2804};
2805
2806// Display an action graph human-readably. Action A is the "sink" node
2807// and latest-occuring action. Traversal is in pre-order, visiting the
2808// inputs to each action before printing the action itself.
2809static unsigned PrintActions1(const Compilation &C, Action *A,
2810 std::map<Action *, unsigned> &Ids,
2811 Twine Indent = {}, int Kind = TopLevelAction) {
2812 if (auto It = Ids.find(x: A); It != Ids.end()) // A was already visited.
2813 return It->second;
2814
2815 std::string str;
2816 llvm::raw_string_ostream os(str);
2817
2818 auto getSibIndent = [](int K) -> Twine {
2819 return (K == HeadSibAction) ? " " : (K == OtherSibAction) ? "| " : "";
2820 };
2821
2822 Twine SibIndent = Indent + getSibIndent(Kind);
2823 int SibKind = HeadSibAction;
2824 os << Action::getClassName(AC: A->getKind()) << ", ";
2825 if (InputAction *IA = dyn_cast<InputAction>(Val: A)) {
2826 os << "\"" << IA->getInputArg().getValue() << "\"";
2827 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(Val: A)) {
2828 os << '"' << BIA->getArch().ArchName << '"' << ", {"
2829 << PrintActions1(C, A: *BIA->input_begin(), Ids, Indent: SibIndent, Kind: SibKind) << "}";
2830 } else if (OffloadAction *OA = dyn_cast<OffloadAction>(Val: A)) {
2831 bool IsFirst = true;
2832 OA->doOnEachDependence(Work: [&](Action *A, const ToolChain *TC, BoundArch BA) {
2833 assert(TC && "Unknown host toolchain");
2834 // E.g. for two CUDA device dependences whose bound arch is sm_20 and
2835 // sm_35 this will generate:
2836 // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
2837 // (nvptx64-nvidia-cuda:sm_35) {#ID}
2838 if (!IsFirst)
2839 os << ", ";
2840 os << '"';
2841 os << A->getOffloadingKindPrefix();
2842 os << " (";
2843 os << TC->getTripleString();
2844 if (!BA.empty())
2845 os << ":" << BA.ArchName;
2846 os << ")";
2847 os << '"';
2848 os << " {" << PrintActions1(C, A, Ids, Indent: SibIndent, Kind: SibKind) << "}";
2849 IsFirst = false;
2850 SibKind = OtherSibAction;
2851 });
2852 } else {
2853 const ActionList *AL = &A->getInputs();
2854
2855 if (AL->size()) {
2856 const char *Prefix = "{";
2857 for (Action *PreRequisite : *AL) {
2858 os << Prefix << PrintActions1(C, A: PreRequisite, Ids, Indent: SibIndent, Kind: SibKind);
2859 Prefix = ", ";
2860 SibKind = OtherSibAction;
2861 }
2862 os << "}";
2863 } else
2864 os << "{}";
2865 }
2866
2867 // Append offload info for all options other than the offloading action
2868 // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
2869 std::string offload_str;
2870 llvm::raw_string_ostream offload_os(offload_str);
2871 if (!isa<OffloadAction>(Val: A)) {
2872 auto S = A->getOffloadingKindPrefix();
2873 if (!S.empty()) {
2874 offload_os << ", (" << S;
2875 if (!A->getOffloadingArch().empty())
2876 offload_os << ", " << A->getOffloadingArch().ArchName;
2877 offload_os << ")";
2878 }
2879 }
2880
2881 auto getSelfIndent = [](int K) -> Twine {
2882 return (K == HeadSibAction) ? "+- " : (K == OtherSibAction) ? "|- " : "";
2883 };
2884
2885 unsigned Id = Ids.size();
2886 Ids[A] = Id;
2887 llvm::errs() << Indent + getSelfIndent(Kind) << Id << ": " << os.str() << ", "
2888 << types::getTypeName(Id: A->getType()) << offload_os.str() << "\n";
2889
2890 return Id;
2891}
2892
2893// Print the action graphs in a compilation C.
2894// For example "clang -c file1.c file2.c" is composed of two subgraphs.
2895void Driver::PrintActions(const Compilation &C) const {
2896 std::map<Action *, unsigned> Ids;
2897 for (Action *A : C.getActions())
2898 PrintActions1(C, A, Ids);
2899}
2900
2901/// Check whether the given input tree contains any compilation or
2902/// assembly actions.
2903static bool ContainsCompileOrAssembleAction(const Action *A) {
2904 if (isa<CompileJobAction>(Val: A) || isa<BackendJobAction>(Val: A) ||
2905 isa<AssembleJobAction>(Val: A))
2906 return true;
2907
2908 return llvm::any_of(Range: A->inputs(), P: ContainsCompileOrAssembleAction);
2909}
2910
2911void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
2912 const InputList &BAInputs) const {
2913 DerivedArgList &Args = C.getArgs();
2914 ActionList &Actions = C.getActions();
2915 llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
2916 // Collect the list of architectures. Duplicates are allowed, but should only
2917 // be handled once (in the order seen).
2918 llvm::StringSet<> ArchNames;
2919 SmallVector<const char *, 4> Archs;
2920 for (Arg *A : Args) {
2921 if (A->getOption().matches(ID: options::OPT_arch)) {
2922 // Validate the option here; we don't save the type here because its
2923 // particular spelling may participate in other driver choices.
2924 llvm::Triple::ArchType Arch =
2925 tools::darwin::getArchTypeForMachOArchName(Str: A->getValue());
2926 if (Arch == llvm::Triple::UnknownArch) {
2927 Diag(DiagID: clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
2928 continue;
2929 }
2930
2931 A->claim();
2932 if (ArchNames.insert(key: A->getValue()).second)
2933 Archs.push_back(Elt: A->getValue());
2934 }
2935 }
2936
2937 // When there is no explicit arch for this platform, make sure we still bind
2938 // the architecture (to the default) so that -Xarch_ is handled correctly.
2939 if (!Archs.size())
2940 Archs.push_back(Elt: Args.MakeArgString(Str: TC.getDefaultUniversalArchName()));
2941
2942 ActionList SingleActions;
2943 BuildActions(C, Args, Inputs: BAInputs, Actions&: SingleActions);
2944
2945 // Add in arch bindings for every top level action, as well as lipo and
2946 // dsymutil steps if needed.
2947 for (Action* Act : SingleActions) {
2948 // Make sure we can lipo this kind of output. If not (and it is an actual
2949 // output) then we disallow, since we can't create an output file with the
2950 // right name without overwriting it. We could remove this oddity by just
2951 // changing the output names to include the arch, which would also fix
2952 // -save-temps. Compatibility wins for now.
2953
2954 if (Archs.size() > 1 && !types::canLipoType(Id: Act->getType()))
2955 Diag(DiagID: clang::diag::err_drv_invalid_output_with_multiple_archs)
2956 << types::getTypeName(Id: Act->getType());
2957
2958 ActionList Inputs;
2959 for (unsigned i = 0, e = Archs.size(); i != e; ++i)
2960 Inputs.push_back(Elt: C.MakeAction<BindArchAction>(Arg&: Act, Arg: BoundArch(Archs[i])));
2961
2962 // Lipo if necessary, we do it this way because we need to set the arch flag
2963 // so that -Xarch_ gets overwritten.
2964 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
2965 Actions.append(in_start: Inputs.begin(), in_end: Inputs.end());
2966 else
2967 Actions.push_back(Elt: C.MakeAction<LipoJobAction>(Arg&: Inputs, Arg: Act->getType()));
2968
2969 // Handle debug info queries.
2970 Arg *A = Args.getLastArg(Ids: options::OPT_g_Group);
2971 bool enablesDebugInfo = A && !A->getOption().matches(ID: options::OPT_g0) &&
2972 !A->getOption().matches(ID: options::OPT_gstabs);
2973 bool enablesPseudoProbe =
2974 Args.hasFlag(Pos: options::OPT_fpseudo_probe_for_profiling,
2975 Neg: options::OPT_fno_pseudo_probe_for_profiling, Default: false);
2976 bool enablesDebugInfoForProfiling =
2977 Args.hasFlag(Pos: options::OPT_fdebug_info_for_profiling,
2978 Neg: options::OPT_fno_debug_info_for_profiling, Default: false);
2979 if ((enablesDebugInfo || willEmitRemarks(Args) || enablesPseudoProbe ||
2980 enablesDebugInfoForProfiling) &&
2981 ContainsCompileOrAssembleAction(A: Actions.back())) {
2982
2983 // Add a 'dsymutil' step if necessary, when debug info, remarks, or
2984 // pseudo probes are enabled and we have a compile input. We need to run
2985 // 'dsymutil' ourselves in such cases because the debug info will refer
2986 // to a temporary object file which will be removed at the end of the
2987 // compilation process.
2988 if (Act->getType() == types::TY_Image) {
2989 ActionList Inputs;
2990 Inputs.push_back(Elt: Actions.back());
2991 Actions.pop_back();
2992 Actions.push_back(
2993 Elt: C.MakeAction<DsymutilJobAction>(Arg&: Inputs, Arg: types::TY_dSYM));
2994 }
2995
2996 // Verify the debug info output.
2997 if (Args.hasArg(Ids: options::OPT_verify_debug_info)) {
2998 Action *LastAction = Actions.pop_back_val();
2999 Actions.push_back(Elt: C.MakeAction<VerifyDebugInfoJobAction>(
3000 Arg&: LastAction, Arg: types::TY_Nothing));
3001 }
3002 }
3003 }
3004}
3005
3006bool Driver::DiagnoseInputExistence(StringRef Value, types::ID Ty,
3007 bool TypoCorrect) const {
3008 if (!getCheckInputsExist())
3009 return true;
3010
3011 // stdin always exists.
3012 if (Value == "-")
3013 return true;
3014
3015 // If it's a header to be found in the system or user search path, then defer
3016 // complaints about its absence until those searches can be done. When we
3017 // are definitely processing headers for C++20 header units, extend this to
3018 // allow the user to put "-fmodule-header -xc++-header vector" for example.
3019 if (Ty == types::TY_CXXSHeader || Ty == types::TY_CXXUHeader ||
3020 (ModulesModeCXX20 && Ty == types::TY_CXXHeader))
3021 return true;
3022
3023 if (getVFS().exists(Path: Value))
3024 return true;
3025
3026 if (TypoCorrect) {
3027 // Check if the filename is a typo for an option flag. OptTable thinks
3028 // that all args that are not known options and that start with / are
3029 // filenames, but e.g. `/diagnostic:caret` is more likely a typo for
3030 // the option `/diagnostics:caret` than a reference to a file in the root
3031 // directory.
3032 std::string Nearest;
3033 if (getOpts().findNearest(Option: Value, NearestString&: Nearest, VisibilityMask: getOptionVisibilityMask()) <= 1) {
3034 Diag(DiagID: clang::diag::err_drv_no_such_file_with_suggestion)
3035 << Value << Nearest;
3036 return false;
3037 }
3038 }
3039
3040 // In CL mode, don't error on apparently non-existent linker inputs, because
3041 // they can be influenced by linker flags the clang driver might not
3042 // understand.
3043 // Examples:
3044 // - `clang-cl main.cc ole32.lib` in a non-MSVC shell will make the driver
3045 // module look for an MSVC installation in the registry. (We could ask
3046 // the MSVCToolChain object if it can find `ole32.lib`, but the logic to
3047 // look in the registry might move into lld-link in the future so that
3048 // lld-link invocations in non-MSVC shells just work too.)
3049 // - `clang-cl ... /link ...` can pass arbitrary flags to the linker,
3050 // including /libpath:, which is used to find .lib and .obj files.
3051 // So do not diagnose this on the driver level. Rely on the linker diagnosing
3052 // it. (If we don't end up invoking the linker, this means we'll emit a
3053 // "'linker' input unused [-Wunused-command-line-argument]" warning instead
3054 // of an error.)
3055 //
3056 // Only do this skip after the typo correction step above. `/Brepo` is treated
3057 // as TY_Object, but it's clearly a typo for `/Brepro`. It seems fine to emit
3058 // an error if we have a flag that's within an edit distance of 1 from a
3059 // flag. (Users can use `-Wl,` or `/linker` to launder the flag past the
3060 // driver in the unlikely case they run into this.)
3061 //
3062 // Don't do this for inputs that start with a '/', else we'd pass options
3063 // like /libpath: through to the linker silently.
3064 //
3065 // Emitting an error for linker inputs can also cause incorrect diagnostics
3066 // with the gcc driver. The command
3067 // clang -fuse-ld=lld -Wl,--chroot,some/dir /file.o
3068 // will make lld look for some/dir/file.o, while we will diagnose here that
3069 // `/file.o` does not exist. However, configure scripts check if
3070 // `clang /GR-` compiles without error to see if the compiler is cl.exe,
3071 // so we can't downgrade diagnostics for `/GR-` from an error to a warning
3072 // in cc mode. (We can in cl mode because cl.exe itself only warns on
3073 // unknown flags.)
3074 if (IsCLMode() && Ty == types::TY_Object && !Value.starts_with(Prefix: "/"))
3075 return true;
3076
3077 Diag(DiagID: clang::diag::err_drv_no_such_file) << Value;
3078 return false;
3079}
3080
3081// Get the C++20 Header Unit type corresponding to the input type.
3082static types::ID CXXHeaderUnitType(ModuleHeaderMode HM) {
3083 switch (HM) {
3084 case HeaderMode_User:
3085 return types::TY_CXXUHeader;
3086 case HeaderMode_System:
3087 return types::TY_CXXSHeader;
3088 case HeaderMode_Default:
3089 break;
3090 case HeaderMode_None:
3091 llvm_unreachable("should not be called in this case");
3092 }
3093 return types::TY_CXXHUHeader;
3094}
3095
3096// Construct a the list of inputs and their types.
3097void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
3098 InputList &Inputs) const {
3099 const llvm::opt::OptTable &Opts = getOpts();
3100 // Track the current user specified (-x) input. We also explicitly track the
3101 // argument used to set the type; we only want to claim the type when we
3102 // actually use it, so we warn about unused -x arguments.
3103 types::ID InputType = types::TY_Nothing;
3104 Arg *InputTypeArg = nullptr;
3105
3106 // The last /TC or /TP option sets the input type to C or C++ globally.
3107 if (Arg *TCTP = Args.getLastArgNoClaim(Ids: options::OPT__SLASH_TC,
3108 Ids: options::OPT__SLASH_TP)) {
3109 InputTypeArg = TCTP;
3110 InputType = TCTP->getOption().matches(ID: options::OPT__SLASH_TC)
3111 ? types::TY_C
3112 : types::TY_CXX;
3113
3114 Arg *Previous = nullptr;
3115 bool ShowNote = false;
3116 for (Arg *A :
3117 Args.filtered(Ids: options::OPT__SLASH_TC, Ids: options::OPT__SLASH_TP)) {
3118 if (Previous) {
3119 Diag(DiagID: clang::diag::warn_drv_overriding_option)
3120 << Previous->getSpelling() << A->getSpelling();
3121 ShowNote = true;
3122 }
3123 Previous = A;
3124 }
3125 if (ShowNote)
3126 Diag(DiagID: clang::diag::note_drv_t_option_is_global);
3127 }
3128
3129 // Warn -x after last input file has no effect
3130 {
3131 Arg *LastXArg = Args.getLastArgNoClaim(Ids: options::OPT_x);
3132 Arg *LastInputArg = Args.getLastArgNoClaim(Ids: options::OPT_INPUT);
3133 if (LastXArg && LastInputArg &&
3134 LastInputArg->getIndex() < LastXArg->getIndex())
3135 Diag(DiagID: clang::diag::warn_drv_unused_x) << LastXArg->getValue();
3136 }
3137
3138 bool IsSYCL = Args.hasFlag(Pos: options::OPT_fsycl, Neg: options::OPT_fno_sycl, Default: false);
3139
3140 for (Arg *A : Args) {
3141 if (A->getOption().getKind() == Option::InputClass) {
3142 const char *Value = A->getValue();
3143 types::ID Ty = types::TY_INVALID;
3144
3145 // Infer the input type if necessary.
3146 if (InputType == types::TY_Nothing) {
3147 // If there was an explicit arg for this, claim it.
3148 if (InputTypeArg)
3149 InputTypeArg->claim();
3150
3151 // stdin must be handled specially.
3152 if (strcmp(s1: Value, s2: "-") == 0) {
3153 if (IsFlangMode()) {
3154 Ty = types::TY_Fortran;
3155 } else if (IsDXCMode()) {
3156 Ty = types::TY_HLSL;
3157 } else if (IsSYCL) {
3158 Ty = types::TY_CXX;
3159 } else {
3160 // If running with -E, treat as a C input (this changes the
3161 // builtin macros, for example). This may be overridden by -ObjC
3162 // below.
3163 //
3164 // Otherwise emit an error but still use a valid type to avoid
3165 // spurious errors (e.g., no inputs).
3166 assert(!CCGenDiagnostics && "stdin produces no crash reproducer");
3167 if (!Args.hasArgNoClaim(Ids: options::OPT_E) && !CCCIsCPP())
3168 Diag(DiagID: IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
3169 : clang::diag::err_drv_unknown_stdin_type);
3170 Ty = types::TY_C;
3171 }
3172 } else {
3173 // Otherwise lookup by extension.
3174 // Fallback is C if invoked as C preprocessor, C++ if invoked with
3175 // clang-cl /E, or Object otherwise.
3176 // We use a host hook here because Darwin at least has its own
3177 // idea of what .s is.
3178 if (const char *Ext = strrchr(s: Value, c: '.'))
3179 Ty = TC.LookupTypeForExtension(Ext: Ext + 1);
3180
3181 if (Ty == types::TY_INVALID) {
3182 if (IsCLMode() && (Args.hasArgNoClaim(Ids: options::OPT_E) || CCGenDiagnostics))
3183 Ty = types::TY_CXX;
3184 else if (CCCIsCPP() || CCGenDiagnostics)
3185 Ty = types::TY_C;
3186 else if (IsDXCMode())
3187 Ty = types::TY_HLSL;
3188 else
3189 Ty = types::TY_Object;
3190 }
3191
3192 // If the driver is invoked as C++ compiler (like clang++ or c++) it
3193 // should autodetect some input files as C++ for g++ compatibility.
3194 if (CCCIsCXX()) {
3195 types::ID OldTy = Ty;
3196 Ty = types::lookupCXXTypeForCType(Id: Ty);
3197
3198 // Do not complain about foo.h, when we are known to be processing
3199 // it as a C++20 header unit.
3200 if (Ty != OldTy && !(OldTy == types::TY_CHeader && hasHeaderMode()))
3201 Diag(DiagID: clang::diag::warn_drv_treating_input_as_cxx)
3202 << getTypeName(Id: OldTy) << getTypeName(Id: Ty);
3203 }
3204
3205 // If running with -fthinlto-index=, extensions that normally identify
3206 // native object files actually identify LLVM bitcode files.
3207 if (Args.hasArgNoClaim(Ids: options::OPT_fthinlto_index_EQ) &&
3208 Ty == types::TY_Object)
3209 Ty = types::TY_LLVM_BC;
3210 }
3211
3212 // -ObjC and -ObjC++ override the default language, but only for "source
3213 // files". We just treat everything that isn't a linker input as a
3214 // source file.
3215 //
3216 // FIXME: Clean this up if we move the phase sequence into the type.
3217 if (Ty != types::TY_Object) {
3218 if (Args.hasArg(Ids: options::OPT_ObjC))
3219 Ty = types::TY_ObjC;
3220 else if (Args.hasArg(Ids: options::OPT_ObjCXX))
3221 Ty = types::TY_ObjCXX;
3222 }
3223
3224 // Disambiguate headers that are meant to be header units from those
3225 // intended to be PCH. Avoid missing '.h' cases that are counted as
3226 // C headers by default - we know we are in C++ mode and we do not
3227 // want to issue a complaint about compiling things in the wrong mode.
3228 if ((Ty == types::TY_CXXHeader || Ty == types::TY_CHeader) &&
3229 hasHeaderMode())
3230 Ty = CXXHeaderUnitType(HM: CXX20HeaderType);
3231 } else {
3232 assert(InputTypeArg && "InputType set w/o InputTypeArg");
3233 if (!InputTypeArg->getOption().matches(ID: options::OPT_x)) {
3234 // If emulating cl.exe, make sure that /TC and /TP don't affect input
3235 // object files.
3236 const char *Ext = strrchr(s: Value, c: '.');
3237 if (Ext && TC.LookupTypeForExtension(Ext: Ext + 1) == types::TY_Object)
3238 Ty = types::TY_Object;
3239 }
3240 if (Ty == types::TY_INVALID) {
3241 Ty = InputType;
3242 InputTypeArg->claim();
3243 }
3244 }
3245
3246 if ((Ty == types::TY_C || Ty == types::TY_CXX) &&
3247 Args.hasArgNoClaim(Ids: options::OPT_hipstdpar))
3248 Ty = types::TY_HIP;
3249
3250 if (DiagnoseInputExistence(Value, Ty, /*TypoCorrect=*/true))
3251 Inputs.push_back(Elt: std::make_pair(x&: Ty, y&: A));
3252
3253 } else if (A->getOption().matches(ID: options::OPT__SLASH_Tc)) {
3254 StringRef Value = A->getValue();
3255 if (DiagnoseInputExistence(Value, Ty: types::TY_C,
3256 /*TypoCorrect=*/false)) {
3257 Arg *InputArg = makeInputArg(Args, Opts, Value: A->getValue());
3258 Inputs.push_back(Elt: std::make_pair(x: types::TY_C, y&: InputArg));
3259 }
3260 A->claim();
3261 } else if (A->getOption().matches(ID: options::OPT__SLASH_Tp)) {
3262 StringRef Value = A->getValue();
3263 if (DiagnoseInputExistence(Value, Ty: types::TY_CXX,
3264 /*TypoCorrect=*/false)) {
3265 Arg *InputArg = makeInputArg(Args, Opts, Value: A->getValue());
3266 Inputs.push_back(Elt: std::make_pair(x: types::TY_CXX, y&: InputArg));
3267 }
3268 A->claim();
3269 } else if (A->getOption().hasFlag(Val: options::LinkerInput)) {
3270 // Just treat as object type, we could make a special type for this if
3271 // necessary.
3272 Inputs.push_back(Elt: std::make_pair(x: types::TY_Object, y&: A));
3273
3274 } else if (A->getOption().matches(ID: options::OPT_x)) {
3275 InputTypeArg = A;
3276 InputType = types::lookupTypeForTypeSpecifier(Name: A->getValue());
3277 A->claim();
3278
3279 // Follow gcc behavior and treat as linker input for invalid -x
3280 // options. Its not clear why we shouldn't just revert to unknown; but
3281 // this isn't very important, we might as well be bug compatible.
3282 if (!InputType) {
3283 Diag(DiagID: clang::diag::err_drv_unknown_language) << A->getValue();
3284 InputType = types::TY_Object;
3285 }
3286
3287 // If the user has put -fmodule-header{,=} then we treat C++ headers as
3288 // header unit inputs. So we 'promote' -xc++-header appropriately.
3289 if (InputType == types::TY_CXXHeader && hasHeaderMode())
3290 InputType = CXXHeaderUnitType(HM: CXX20HeaderType);
3291 } else if (A->getOption().getID() == options::OPT_U) {
3292 assert(A->getNumValues() == 1 && "The /U option has one value.");
3293 StringRef Val = A->getValue(N: 0);
3294 if (Val.find_first_of(Chars: "/\\") != StringRef::npos) {
3295 // Warn about e.g. "/Users/me/myfile.c".
3296 Diag(DiagID: diag::warn_slash_u_filename) << Val;
3297 Diag(DiagID: diag::note_use_dashdash);
3298 }
3299 }
3300 }
3301 if (CCCIsCPP() && Inputs.empty()) {
3302 // If called as standalone preprocessor, stdin is processed
3303 // if no other input is present.
3304 Arg *A = makeInputArg(Args, Opts, Value: "-");
3305 Inputs.push_back(Elt: std::make_pair(x: types::TY_C, y&: A));
3306 }
3307}
3308
3309namespace {
3310/// Provides a convenient interface for different programming models to generate
3311/// the required device actions.
3312class OffloadingActionBuilder final {
3313 /// Flag used to trace errors in the builder.
3314 bool IsValid = false;
3315
3316 /// The compilation that is using this builder.
3317 Compilation &C;
3318
3319 /// Map between an input argument and the offload kinds used to process it.
3320 std::map<const Arg *, unsigned> InputArgToOffloadKindMap;
3321
3322 /// Map between a host action and its originating input argument.
3323 std::map<Action *, const Arg *> HostActionToInputArgMap;
3324
3325 /// Builder interface. It doesn't build anything or keep any state.
3326 class DeviceActionBuilder {
3327 public:
3328 typedef const llvm::SmallVectorImpl<phases::ID> PhasesTy;
3329
3330 enum ActionBuilderReturnCode {
3331 // The builder acted successfully on the current action.
3332 ABRT_Success,
3333 // The builder didn't have to act on the current action.
3334 ABRT_Inactive,
3335 // The builder was successful and requested the host action to not be
3336 // generated.
3337 ABRT_Ignore_Host,
3338 };
3339
3340 protected:
3341 /// Compilation associated with this builder.
3342 Compilation &C;
3343
3344 /// Tool chains associated with this builder. The same programming
3345 /// model may have associated one or more tool chains.
3346 /// There should be one entry for each TargetID.
3347 SmallVector<const ToolChain *, 2> ToolChains;
3348 const ToolChain *FatBinaryToolChain = nullptr;
3349
3350 /// The derived arguments associated with this builder.
3351 DerivedArgList &Args;
3352
3353 /// The inputs associated with this builder.
3354 const InputList &Inputs;
3355
3356 /// The associated offload kind.
3357 Action::OffloadKind AssociatedOffloadKind = Action::OFK_None;
3358
3359 public:
3360 DeviceActionBuilder(Compilation &C, DerivedArgList &Args,
3361 const InputList &Inputs,
3362 Action::OffloadKind AssociatedOffloadKind)
3363 : C(C), Args(Args), Inputs(Inputs),
3364 AssociatedOffloadKind(AssociatedOffloadKind) {}
3365 virtual ~DeviceActionBuilder() {}
3366
3367 /// Fill up the array \a DA with all the device dependences that should be
3368 /// added to the provided host action \a HostAction. By default it is
3369 /// inactive.
3370 virtual ActionBuilderReturnCode
3371 getDeviceDependences(OffloadAction::DeviceDependences &DA,
3372 phases::ID CurPhase, phases::ID FinalPhase,
3373 PhasesTy &Phases) {
3374 return ABRT_Inactive;
3375 }
3376
3377 /// Update the state to include the provided host action \a HostAction as a
3378 /// dependency of the current device action. By default it is inactive.
3379 virtual ActionBuilderReturnCode addDeviceDependences(Action *HostAction) {
3380 return ABRT_Inactive;
3381 }
3382
3383 /// Append top level actions generated by the builder.
3384 virtual void appendTopLevelActions(ActionList &AL) {}
3385
3386 /// Append linker device actions generated by the builder.
3387 virtual void appendLinkDeviceActions(ActionList &AL) {}
3388
3389 /// Append linker host action generated by the builder.
3390 virtual Action* appendLinkHostActions(ActionList &AL) { return nullptr; }
3391
3392 /// Append linker actions generated by the builder.
3393 virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {}
3394
3395 /// Initialize the builder. Return true if any initialization errors are
3396 /// found.
3397 virtual bool initialize() { return false; }
3398
3399 /// Return true if the builder can use bundling/unbundling.
3400 virtual bool canUseBundlerUnbundler() const { return false; }
3401
3402 /// Return true if this builder is valid. We have a valid builder if we have
3403 /// associated device tool chains.
3404 bool isValid() { return !ToolChains.empty(); }
3405
3406 /// Return the associated offload kind.
3407 Action::OffloadKind getAssociatedOffloadKind() {
3408 return AssociatedOffloadKind;
3409 }
3410 };
3411
3412 /// Base class for CUDA/HIP action builder. It injects device code in
3413 /// the host backend action.
3414 class CudaActionBuilderBase : public DeviceActionBuilder {
3415 protected:
3416 /// Flags to signal if the user requested host-only or device-only
3417 /// compilation.
3418 bool CompileHostOnly = false;
3419 bool CompileDeviceOnly = false;
3420 bool EmitLLVM = false;
3421 bool EmitAsm = false;
3422
3423 /// List of GPU architectures to use in this compilation.
3424 SmallVector<BoundArch, 4> GpuArchList;
3425
3426 /// The CUDA actions for the current input.
3427 ActionList CudaDeviceActions;
3428
3429 /// The CUDA fat binary if it was generated for the current input.
3430 Action *CudaFatBinary = nullptr;
3431
3432 /// Flag that is set to true if this builder acted on the current input.
3433 bool IsActive = false;
3434
3435 /// Flag for -fgpu-rdc.
3436 bool Relocatable = false;
3437
3438 /// Default GPU architecture if there's no one specified.
3439 OffloadArch DefaultOffloadArch = OffloadArch::Unknown;
3440
3441 /// Compilation unit ID specified by option '-fuse-cuid=' or'-cuid='.
3442 const CUIDOptions &CUIDOpts;
3443
3444 public:
3445 CudaActionBuilderBase(Compilation &C, DerivedArgList &Args,
3446 const InputList &Inputs, Action::OffloadKind OFKind)
3447 : DeviceActionBuilder(C, Args, Inputs, OFKind),
3448 CUIDOpts(C.getDriver().getCUIDOpts()) {
3449
3450 CompileDeviceOnly = C.getDriver().offloadDeviceOnly();
3451 Relocatable = Args.hasFlag(Pos: options::OPT_fgpu_rdc,
3452 Neg: options::OPT_fno_gpu_rdc, /*Default=*/false);
3453 }
3454
3455 ActionBuilderReturnCode addDeviceDependences(Action *HostAction) override {
3456 // While generating code for CUDA, we only depend on the host input action
3457 // to trigger the creation of all the CUDA device actions.
3458
3459 // If we are dealing with an input action, replicate it for each GPU
3460 // architecture. If we are in host-only mode we return 'success' so that
3461 // the host uses the CUDA offload kind.
3462 if (auto *IA = dyn_cast<InputAction>(Val: HostAction)) {
3463 // If the host input is not CUDA or HIP, we don't need to bother about
3464 // this input.
3465 if (!(IA->getType() == types::TY_CUDA ||
3466 IA->getType() == types::TY_HIP ||
3467 IA->getType() == types::TY_PP_HIP)) {
3468 // The builder will ignore this input.
3469 IsActive = false;
3470 return ABRT_Inactive;
3471 }
3472
3473 // Set the flag to true, so that the builder acts on the current input.
3474 IsActive = true;
3475
3476 if (CUIDOpts.isEnabled())
3477 IA->setId(CUIDOpts.getCUID(InputFile: IA->getInputArg().getValue(), Args));
3478
3479 if (CompileHostOnly)
3480 return ABRT_Success;
3481
3482 // Replicate inputs for each GPU architecture.
3483 auto Ty = IA->getType() == types::TY_HIP ? types::TY_HIP_DEVICE
3484 : types::TY_CUDA_DEVICE;
3485 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
3486 CudaDeviceActions.push_back(
3487 Elt: C.MakeAction<InputAction>(Arg: IA->getInputArg(), Arg&: Ty, Arg: IA->getId()));
3488 }
3489
3490 return ABRT_Success;
3491 }
3492
3493 // If this is an unbundling action use it as is for each CUDA toolchain.
3494 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(Val: HostAction)) {
3495
3496 // If -fgpu-rdc is disabled, should not unbundle since there is no
3497 // device code to link.
3498 if (UA->getType() == types::TY_Object && !Relocatable)
3499 return ABRT_Inactive;
3500
3501 CudaDeviceActions.clear();
3502 auto *IA = cast<InputAction>(Val: UA->getInputs().back());
3503 std::string FileName = IA->getInputArg().getAsString(Args);
3504 // Check if the type of the file is the same as the action. Do not
3505 // unbundle it if it is not. Do not unbundle .so files, for example,
3506 // which are not object files. Files with extension ".lib" is classified
3507 // as TY_Object but they are actually archives, therefore should not be
3508 // unbundled here as objects. They will be handled at other places.
3509 const StringRef LibFileExt = ".lib";
3510 if (IA->getType() == types::TY_Object &&
3511 (!llvm::sys::path::has_extension(path: FileName) ||
3512 types::lookupTypeForExtension(
3513 Ext: llvm::sys::path::extension(path: FileName).drop_front()) !=
3514 types::TY_Object ||
3515 llvm::sys::path::extension(path: FileName) == LibFileExt))
3516 return ABRT_Inactive;
3517
3518 for (auto [Arch, ToolChain] : llvm::zip(t&: GpuArchList, u&: ToolChains)) {
3519 CudaDeviceActions.push_back(Elt: UA);
3520 UA->registerDependentActionInfo(TC: ToolChain, BA: Arch,
3521 Kind: AssociatedOffloadKind);
3522 }
3523 IsActive = true;
3524 return ABRT_Success;
3525 }
3526
3527 return IsActive ? ABRT_Success : ABRT_Inactive;
3528 }
3529
3530 void appendTopLevelActions(ActionList &AL) override {
3531 // Utility to append actions to the top level list.
3532 auto AddTopLevel = [&](Action *A, BoundArch BA, const ToolChain *TC) {
3533 OffloadAction::DeviceDependences Dep;
3534 Dep.add(A&: *A, TC: *TC, BA, OKind: AssociatedOffloadKind);
3535 AL.push_back(Elt: C.MakeAction<OffloadAction>(Arg&: Dep, Arg: A->getType()));
3536 };
3537
3538 // If we have a fat binary, add it to the list.
3539 if (CudaFatBinary) {
3540 AddTopLevel(CudaFatBinary, {}, FatBinaryToolChain);
3541 CudaDeviceActions.clear();
3542 CudaFatBinary = nullptr;
3543 return;
3544 }
3545
3546 if (CudaDeviceActions.empty())
3547 return;
3548
3549 // If we have CUDA actions at this point, that's because we have a have
3550 // partial compilation, so we should have an action for each GPU
3551 // architecture.
3552 assert(CudaDeviceActions.size() == GpuArchList.size() &&
3553 "Expecting one action per GPU architecture.");
3554 assert(ToolChains.size() == GpuArchList.size() &&
3555 "Expecting to have a toolchain per GPU architecture");
3556 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
3557 AddTopLevel(CudaDeviceActions[I], GpuArchList[I], ToolChains[I]);
3558
3559 CudaDeviceActions.clear();
3560 }
3561
3562 bool initialize() override {
3563 assert(AssociatedOffloadKind == Action::OFK_Cuda ||
3564 AssociatedOffloadKind == Action::OFK_HIP);
3565
3566 // We don't need to support CUDA.
3567 if (AssociatedOffloadKind == Action::OFK_Cuda &&
3568 !C.hasOffloadToolChain<Action::OFK_Cuda>())
3569 return false;
3570
3571 // We don't need to support HIP.
3572 if (AssociatedOffloadKind == Action::OFK_HIP &&
3573 !C.hasOffloadToolChain<Action::OFK_HIP>())
3574 return false;
3575
3576 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
3577 assert(HostTC && "No toolchain for host compilation.");
3578 if (HostTC->getTriple().isNVPTX() || HostTC->getTriple().isAMDGCN()) {
3579 // We do not support targeting NVPTX/AMDGCN for host compilation. Throw
3580 // an error and abort pipeline construction early so we don't trip
3581 // asserts that assume device-side compilation.
3582 C.getDriver().Diag(DiagID: diag::err_drv_cuda_host_arch)
3583 << HostTC->getTriple().getArchName();
3584 return true;
3585 }
3586
3587 std::set<std::pair<BoundArch, const ToolChain *>> GpuArchs;
3588 for (Action::OffloadKind Kind : {Action::OFK_Cuda, Action::OFK_HIP}) {
3589 for (auto &I : llvm::make_range(p: C.getOffloadToolChains(Kind))) {
3590 for (auto Arch :
3591 C.getDriver().getOffloadArchs(C, Args: C.getArgs(), Kind, TC: *I.second))
3592 GpuArchs.insert(x: {Arch, I.second});
3593 }
3594 }
3595
3596 for (auto [Arch, TC] : GpuArchs) {
3597 GpuArchList.push_back(Elt: Arch);
3598 ToolChains.push_back(Elt: TC);
3599 }
3600
3601 FatBinaryToolChain = ToolChains.front();
3602 CompileHostOnly = C.getDriver().offloadHostOnly();
3603 EmitLLVM = Args.getLastArg(Ids: options::OPT_emit_llvm);
3604 EmitAsm = Args.getLastArg(Ids: options::OPT_S);
3605
3606 return false;
3607 }
3608 };
3609
3610 /// \brief CUDA action builder. It injects device code in the host backend
3611 /// action.
3612 class CudaActionBuilder final : public CudaActionBuilderBase {
3613 public:
3614 CudaActionBuilder(Compilation &C, DerivedArgList &Args,
3615 const InputList &Inputs)
3616 : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_Cuda) {
3617 DefaultOffloadArch = OffloadArch::CudaDefault;
3618 }
3619
3620 ActionBuilderReturnCode
3621 getDeviceDependences(OffloadAction::DeviceDependences &DA,
3622 phases::ID CurPhase, phases::ID FinalPhase,
3623 PhasesTy &Phases) override {
3624 if (!IsActive)
3625 return ABRT_Inactive;
3626
3627 // If we don't have more CUDA actions, we don't have any dependences to
3628 // create for the host.
3629 if (CudaDeviceActions.empty())
3630 return ABRT_Success;
3631
3632 assert(CudaDeviceActions.size() == GpuArchList.size() &&
3633 "Expecting one action per GPU architecture.");
3634 assert(!CompileHostOnly &&
3635 "Not expecting CUDA actions in host-only compilation.");
3636
3637 // If we are generating code for the device or we are in a backend phase,
3638 // we attempt to generate the fat binary. We compile each arch to ptx and
3639 // assemble to cubin, then feed the cubin *and* the ptx into a device
3640 // "link" action, which uses fatbinary to combine these cubins into one
3641 // fatbin. The fatbin is then an input to the host action if not in
3642 // device-only mode.
3643 if (CompileDeviceOnly || CurPhase == phases::Backend) {
3644 ActionList DeviceActions;
3645 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
3646 // Produce the device action from the current phase up to the assemble
3647 // phase.
3648 for (auto Ph : Phases) {
3649 // Skip the phases that were already dealt with.
3650 if (Ph < CurPhase)
3651 continue;
3652 // We have to be consistent with the host final phase.
3653 if (Ph > FinalPhase)
3654 break;
3655
3656 CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction(
3657 C, Args, Phase: Ph, Input: CudaDeviceActions[I], TargetDeviceOffloadKind: Action::OFK_Cuda,
3658 TargetLTOMode: ToolChains[I]->getLTOMode(Args, Kind: Action::OFK_Cuda));
3659
3660 if (Ph == phases::Assemble)
3661 break;
3662 }
3663
3664 // If we didn't reach the assemble phase, we can't generate the fat
3665 // binary. We don't need to generate the fat binary if we are not in
3666 // device-only mode.
3667 if (!isa<AssembleJobAction>(Val: CudaDeviceActions[I]) ||
3668 CompileDeviceOnly)
3669 continue;
3670
3671 Action *AssembleAction = CudaDeviceActions[I];
3672 assert(AssembleAction->getType() == types::TY_Object);
3673 assert(AssembleAction->getInputs().size() == 1);
3674
3675 Action *BackendAction = AssembleAction->getInputs()[0];
3676 assert(BackendAction->getType() == types::TY_PP_Asm);
3677
3678 for (auto &A : {AssembleAction, BackendAction}) {
3679 OffloadAction::DeviceDependences DDep;
3680 DDep.add(A&: *A, TC: *ToolChains[I], BA: GpuArchList[I], OKind: Action::OFK_Cuda);
3681 DeviceActions.push_back(
3682 Elt: C.MakeAction<OffloadAction>(Arg&: DDep, Arg: A->getType()));
3683 }
3684 }
3685
3686 // We generate the fat binary if we have device input actions.
3687 if (!DeviceActions.empty()) {
3688 CudaFatBinary =
3689 C.MakeAction<LinkJobAction>(Arg&: DeviceActions, Arg: types::TY_CUDA_FATBIN);
3690
3691 if (!CompileDeviceOnly) {
3692 DA.add(A&: *CudaFatBinary, TC: *FatBinaryToolChain, /*BA=*/{},
3693 OKind: Action::OFK_Cuda);
3694 // Clear the fat binary, it is already a dependence to an host
3695 // action.
3696 CudaFatBinary = nullptr;
3697 }
3698
3699 // Remove the CUDA actions as they are already connected to an host
3700 // action or fat binary.
3701 CudaDeviceActions.clear();
3702 }
3703
3704 // We avoid creating host action in device-only mode.
3705 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
3706 } else if (CurPhase > phases::Backend) {
3707 // If we are past the backend phase and still have a device action, we
3708 // don't have to do anything as this action is already a device
3709 // top-level action.
3710 return ABRT_Success;
3711 }
3712
3713 assert(CurPhase < phases::Backend && "Generating single CUDA "
3714 "instructions should only occur "
3715 "before the backend phase!");
3716
3717 // By default, we produce an action for each device arch.
3718 for (Action *&A : CudaDeviceActions)
3719 A = C.getDriver().ConstructPhaseAction(C, Args, Phase: CurPhase, Input: A);
3720
3721 return ABRT_Success;
3722 }
3723 };
3724 /// \brief HIP action builder. It injects device code in the host backend
3725 /// action.
3726 class HIPActionBuilder final : public CudaActionBuilderBase {
3727 /// The linker inputs obtained for each device arch.
3728 SmallVector<ActionList, 8> DeviceLinkerInputs;
3729 // The default bundling behavior depends on the type of output, therefore
3730 // BundleOutput needs to be tri-value: None, true, or false.
3731 // Bundle code objects except --no-gpu-output is specified for device
3732 // only compilation. Bundle other type of output files only if
3733 // --gpu-bundle-output is specified for device only compilation.
3734 std::optional<bool> BundleOutput;
3735 std::optional<bool> EmitReloc;
3736
3737 public:
3738 HIPActionBuilder(Compilation &C, DerivedArgList &Args,
3739 const InputList &Inputs)
3740 : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_HIP) {
3741
3742 DefaultOffloadArch = OffloadArch::HIPDefault;
3743
3744 if (Args.hasArg(Ids: options::OPT_fhip_emit_relocatable,
3745 Ids: options::OPT_fno_hip_emit_relocatable)) {
3746 EmitReloc = Args.hasFlag(Pos: options::OPT_fhip_emit_relocatable,
3747 Neg: options::OPT_fno_hip_emit_relocatable, Default: false);
3748
3749 if (*EmitReloc) {
3750 if (Relocatable) {
3751 C.getDriver().Diag(DiagID: diag::err_opt_not_valid_with_opt)
3752 << "-fhip-emit-relocatable"
3753 << "-fgpu-rdc";
3754 }
3755
3756 if (!CompileDeviceOnly) {
3757 C.getDriver().Diag(DiagID: diag::err_opt_not_valid_without_opt)
3758 << "-fhip-emit-relocatable"
3759 << "--offload-device-only";
3760 }
3761 }
3762 }
3763
3764 if (Args.hasArg(Ids: options::OPT_gpu_bundle_output,
3765 Ids: options::OPT_no_gpu_bundle_output))
3766 BundleOutput = Args.hasFlag(Pos: options::OPT_gpu_bundle_output,
3767 Neg: options::OPT_no_gpu_bundle_output, Default: true) &&
3768 (!EmitReloc || !*EmitReloc);
3769 }
3770
3771 bool canUseBundlerUnbundler() const override { return true; }
3772
3773 ActionBuilderReturnCode
3774 getDeviceDependences(OffloadAction::DeviceDependences &DA,
3775 phases::ID CurPhase, phases::ID FinalPhase,
3776 PhasesTy &Phases) override {
3777 if (!IsActive)
3778 return ABRT_Inactive;
3779
3780 // amdgcn does not support linking of object files, therefore we skip
3781 // backend and assemble phases to output LLVM IR. Except for generating
3782 // non-relocatable device code, where we generate fat binary for device
3783 // code and pass to host in Backend phase.
3784 if (CudaDeviceActions.empty())
3785 return ABRT_Success;
3786
3787 assert(((CurPhase == phases::Link && Relocatable) ||
3788 CudaDeviceActions.size() == GpuArchList.size()) &&
3789 "Expecting one action per GPU architecture.");
3790 assert(!CompileHostOnly &&
3791 "Not expecting HIP actions in host-only compilation.");
3792
3793 bool ShouldLink = !EmitReloc || !*EmitReloc;
3794
3795 if (!Relocatable && CurPhase == phases::Backend && !EmitLLVM &&
3796 !EmitAsm && ShouldLink) {
3797 // If we are in backend phase, we attempt to generate the fat binary.
3798 // We compile each arch to IR and use a link action to generate code
3799 // object containing ISA. Then we use a special "link" action to create
3800 // a fat binary containing all the code objects for different GPU's.
3801 // The fat binary is then an input to the host action.
3802 bool ExplicitOffloadLTO = Args.hasArg(Ids: options::OPT_foffload_lto,
3803 Ids: options::OPT_foffload_lto_EQ);
3804 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
3805 if (ExplicitOffloadLTO &&
3806 ToolChains[I]->isUsingLTO(Args, Kind: AssociatedOffloadKind)) {
3807 // When LTO is enabled, skip the backend and assemble phases and
3808 // use lld to link the bitcode.
3809 ActionList AL;
3810 AL.push_back(Elt: CudaDeviceActions[I]);
3811 // Create a link action to link device IR with device library
3812 // and generate ISA.
3813 CudaDeviceActions[I] =
3814 C.MakeAction<LinkJobAction>(Arg&: AL, Arg: types::TY_Image);
3815 } else {
3816 // When LTO is not enabled, we follow the conventional
3817 // compiler phases, including backend and assemble phases.
3818 ActionList AL;
3819 Action *BackendAction = nullptr;
3820 if (ToolChains[I]->getTriple().isSPIRV() ||
3821 (ToolChains[I]->getTriple().isAMDGCN() &&
3822 GpuArchList[I].ArchName == StringRef("amdgcnspirv"))) {
3823 // Emit LLVM bitcode for SPIR-V targets. SPIR-V device tool chain
3824 // (HIPSPVToolChain or HIPAMDToolChain) runs post-link LLVM IR
3825 // passes.
3826 types::ID Output = Args.hasArg(Ids: options::OPT_S)
3827 ? types::TY_LLVM_IR
3828 : types::TY_LLVM_BC;
3829 BackendAction =
3830 C.MakeAction<BackendJobAction>(Arg&: CudaDeviceActions[I], Arg&: Output);
3831 } else {
3832 BackendAction = C.getDriver().ConstructPhaseAction(
3833 C, Args, Phase: phases::Backend, Input: CudaDeviceActions[I],
3834 TargetDeviceOffloadKind: AssociatedOffloadKind, TargetLTOMode: LTOK_None);
3835 }
3836 auto AssembleAction = C.getDriver().ConstructPhaseAction(
3837 C, Args, Phase: phases::Assemble, Input: BackendAction,
3838 TargetDeviceOffloadKind: AssociatedOffloadKind);
3839 AL.push_back(Elt: AssembleAction);
3840 // Create a link action to link device IR with device library
3841 // and generate ISA.
3842 CudaDeviceActions[I] =
3843 C.MakeAction<LinkJobAction>(Arg&: AL, Arg: types::TY_Image);
3844 }
3845
3846 // OffloadingActionBuilder propagates device arch until an offload
3847 // action. Since the next action for creating fatbin does
3848 // not have device arch, whereas the above link action and its input
3849 // have device arch, an offload action is needed to stop the null
3850 // device arch of the next action being propagated to the above link
3851 // action.
3852 OffloadAction::DeviceDependences DDep;
3853 DDep.add(A&: *CudaDeviceActions[I], TC: *ToolChains[I], BA: GpuArchList[I],
3854 OKind: AssociatedOffloadKind);
3855 CudaDeviceActions[I] = C.MakeAction<OffloadAction>(
3856 Arg&: DDep, Arg: CudaDeviceActions[I]->getType());
3857 }
3858
3859 if (!CompileDeviceOnly || !BundleOutput || *BundleOutput) {
3860 // Create HIP fat binary with a special "link" action.
3861 CudaFatBinary = C.MakeAction<LinkJobAction>(Arg&: CudaDeviceActions,
3862 Arg: types::TY_HIP_FATBIN);
3863
3864 if (!CompileDeviceOnly) {
3865 DA.add(A&: *CudaFatBinary, TC: *FatBinaryToolChain, /*BA=*/{},
3866 OKind: AssociatedOffloadKind);
3867 // Clear the fat binary, it is already a dependence to an host
3868 // action.
3869 CudaFatBinary = nullptr;
3870 }
3871
3872 // Remove the CUDA actions as they are already connected to an host
3873 // action or fat binary.
3874 CudaDeviceActions.clear();
3875 }
3876
3877 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
3878 } else if (CurPhase == phases::Link) {
3879 if (!ShouldLink)
3880 return ABRT_Success;
3881 // Save CudaDeviceActions to DeviceLinkerInputs for each GPU subarch.
3882 // This happens to each device action originated from each input file.
3883 // Later on, device actions in DeviceLinkerInputs are used to create
3884 // device link actions in appendLinkDependences and the created device
3885 // link actions are passed to the offload action as device dependence.
3886 DeviceLinkerInputs.resize(N: CudaDeviceActions.size());
3887 auto LI = DeviceLinkerInputs.begin();
3888 for (auto *A : CudaDeviceActions) {
3889 LI->push_back(Elt: A);
3890 ++LI;
3891 }
3892
3893 // We will pass the device action as a host dependence, so we don't
3894 // need to do anything else with them.
3895 CudaDeviceActions.clear();
3896 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
3897 }
3898
3899 // By default, we produce an action for each device arch.
3900 for (unsigned I = 0, E = CudaDeviceActions.size(); I != E; ++I)
3901 CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction(
3902 C, Args, Phase: CurPhase, Input: CudaDeviceActions[I], TargetDeviceOffloadKind: AssociatedOffloadKind,
3903 TargetLTOMode: ToolChains[I]->getLTOMode(Args, Kind: AssociatedOffloadKind));
3904
3905 if (CompileDeviceOnly && CurPhase == FinalPhase && BundleOutput &&
3906 *BundleOutput) {
3907 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
3908 OffloadAction::DeviceDependences DDep;
3909 DDep.add(A&: *CudaDeviceActions[I], TC: *ToolChains[I], BA: GpuArchList[I],
3910 OKind: AssociatedOffloadKind);
3911 CudaDeviceActions[I] = C.MakeAction<OffloadAction>(
3912 Arg&: DDep, Arg: CudaDeviceActions[I]->getType());
3913 }
3914 CudaFatBinary =
3915 C.MakeAction<OffloadBundlingJobAction>(Arg&: CudaDeviceActions);
3916 CudaDeviceActions.clear();
3917 }
3918
3919 return (CompileDeviceOnly &&
3920 (CurPhase == FinalPhase ||
3921 (!ShouldLink && CurPhase == phases::Assemble)))
3922 ? ABRT_Ignore_Host
3923 : ABRT_Success;
3924 }
3925
3926 void appendLinkDeviceActions(ActionList &AL) override {
3927 if (DeviceLinkerInputs.size() == 0)
3928 return;
3929
3930 assert(DeviceLinkerInputs.size() == GpuArchList.size() &&
3931 "Linker inputs and GPU arch list sizes do not match.");
3932
3933 ActionList Actions;
3934 unsigned I = 0;
3935 // Append a new link action for each device.
3936 // Each entry in DeviceLinkerInputs corresponds to a GPU arch.
3937 for (auto &LI : DeviceLinkerInputs) {
3938
3939 types::ID Output = Args.hasArg(Ids: options::OPT_emit_llvm)
3940 ? types::TY_LLVM_BC
3941 : types::TY_Image;
3942
3943 auto *DeviceLinkAction = C.MakeAction<LinkJobAction>(Arg&: LI, Arg&: Output);
3944 // Linking all inputs for the current GPU arch.
3945 // LI contains all the inputs for the linker.
3946 OffloadAction::DeviceDependences DeviceLinkDeps;
3947 DeviceLinkDeps.add(A&: *DeviceLinkAction, TC: *ToolChains[I], BA: GpuArchList[I],
3948 OKind: AssociatedOffloadKind);
3949 Actions.push_back(Elt: C.MakeAction<OffloadAction>(
3950 Arg&: DeviceLinkDeps, Arg: DeviceLinkAction->getType()));
3951 ++I;
3952 }
3953 DeviceLinkerInputs.clear();
3954
3955 // If emitting LLVM, do not generate final host/device compilation action
3956 if (Args.hasArg(Ids: options::OPT_emit_llvm)) {
3957 AL.append(RHS: Actions);
3958 return;
3959 }
3960
3961 // Create a host object from all the device images by embedding them
3962 // in a fat binary for mixed host-device compilation. For device-only
3963 // compilation, creates a fat binary.
3964 OffloadAction::DeviceDependences DDeps;
3965 if (!CompileDeviceOnly || !BundleOutput || *BundleOutput) {
3966 auto *TopDeviceLinkAction = C.MakeAction<LinkJobAction>(
3967 Arg&: Actions,
3968 Arg: CompileDeviceOnly ? types::TY_HIP_FATBIN : types::TY_Object);
3969 DDeps.add(A&: *TopDeviceLinkAction, TC: *FatBinaryToolChain, /*BA=*/{},
3970 OKind: AssociatedOffloadKind);
3971 // Offload the host object to the host linker.
3972 AL.push_back(
3973 Elt: C.MakeAction<OffloadAction>(Arg&: DDeps, Arg: TopDeviceLinkAction->getType()));
3974 } else {
3975 AL.append(RHS: Actions);
3976 }
3977 }
3978
3979 Action* appendLinkHostActions(ActionList &AL) override { return AL.back(); }
3980
3981 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {}
3982 };
3983
3984 ///
3985 /// TODO: Add the implementation for other specialized builders here.
3986 ///
3987
3988 /// Specialized builders being used by this offloading action builder.
3989 SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders;
3990
3991 /// Flag set to true if all valid builders allow file bundling/unbundling.
3992 bool CanUseBundler;
3993
3994 /// Flag set to false if an argument turns off bundling.
3995 bool ShouldUseBundler;
3996
3997public:
3998 OffloadingActionBuilder(Compilation &C, DerivedArgList &Args,
3999 const InputList &Inputs)
4000 : C(C) {
4001 // Create a specialized builder for each device toolchain.
4002
4003 IsValid = true;
4004
4005 // Create a specialized builder for CUDA.
4006 SpecializedBuilders.push_back(Elt: new CudaActionBuilder(C, Args, Inputs));
4007
4008 // Create a specialized builder for HIP.
4009 SpecializedBuilders.push_back(Elt: new HIPActionBuilder(C, Args, Inputs));
4010
4011 //
4012 // TODO: Build other specialized builders here.
4013 //
4014
4015 // Initialize all the builders, keeping track of errors. If all valid
4016 // builders agree that we can use bundling, set the flag to true.
4017 unsigned ValidBuilders = 0u;
4018 unsigned ValidBuildersSupportingBundling = 0u;
4019 for (auto *SB : SpecializedBuilders) {
4020 IsValid = IsValid && !SB->initialize();
4021
4022 // Update the counters if the builder is valid.
4023 if (SB->isValid()) {
4024 ++ValidBuilders;
4025 if (SB->canUseBundlerUnbundler())
4026 ++ValidBuildersSupportingBundling;
4027 }
4028 }
4029 CanUseBundler =
4030 ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling;
4031
4032 ShouldUseBundler = Args.hasFlag(Pos: options::OPT_gpu_bundle_output,
4033 Neg: options::OPT_no_gpu_bundle_output, Default: true);
4034 }
4035
4036 ~OffloadingActionBuilder() {
4037 for (auto *SB : SpecializedBuilders)
4038 delete SB;
4039 }
4040
4041 /// Record a host action and its originating input argument.
4042 void recordHostAction(Action *HostAction, const Arg *InputArg) {
4043 assert(HostAction && "Invalid host action");
4044 assert(InputArg && "Invalid input argument");
4045 auto Loc = HostActionToInputArgMap.try_emplace(k: HostAction, args&: InputArg).first;
4046 assert(Loc->second == InputArg &&
4047 "host action mapped to multiple input arguments");
4048 (void)Loc;
4049 }
4050
4051 /// Generate an action that adds device dependences (if any) to a host action.
4052 /// If no device dependence actions exist, just return the host action \a
4053 /// HostAction. If an error is found or if no builder requires the host action
4054 /// to be generated, return nullptr.
4055 Action *
4056 addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg,
4057 phases::ID CurPhase, phases::ID FinalPhase,
4058 DeviceActionBuilder::PhasesTy &Phases) {
4059 if (!IsValid)
4060 return nullptr;
4061
4062 if (SpecializedBuilders.empty())
4063 return HostAction;
4064
4065 assert(HostAction && "Invalid host action!");
4066 recordHostAction(HostAction, InputArg);
4067
4068 OffloadAction::DeviceDependences DDeps;
4069 // Check if all the programming models agree we should not emit the host
4070 // action. Also, keep track of the offloading kinds employed.
4071 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
4072 unsigned InactiveBuilders = 0u;
4073 unsigned IgnoringBuilders = 0u;
4074 for (auto *SB : SpecializedBuilders) {
4075 if (!SB->isValid()) {
4076 ++InactiveBuilders;
4077 continue;
4078 }
4079 auto RetCode =
4080 SB->getDeviceDependences(DA&: DDeps, CurPhase, FinalPhase, Phases);
4081
4082 // If the builder explicitly says the host action should be ignored,
4083 // we need to increment the variable that tracks the builders that request
4084 // the host object to be ignored.
4085 if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host)
4086 ++IgnoringBuilders;
4087
4088 // Unless the builder was inactive for this action, we have to record the
4089 // offload kind because the host will have to use it.
4090 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
4091 OffloadKind |= SB->getAssociatedOffloadKind();
4092 }
4093
4094 // If all builders agree that the host object should be ignored, just return
4095 // nullptr.
4096 if (IgnoringBuilders &&
4097 SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders))
4098 return nullptr;
4099
4100 if (DDeps.getActions().empty())
4101 return HostAction;
4102
4103 // We have dependences we need to bundle together. We use an offload action
4104 // for that.
4105 OffloadAction::HostDependence HDep(
4106 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
4107 /*BA=*/{}, DDeps);
4108 return C.MakeAction<OffloadAction>(Arg&: HDep, Arg&: DDeps);
4109 }
4110
4111 /// Generate an action that adds a host dependence to a device action. The
4112 /// results will be kept in this action builder. Return true if an error was
4113 /// found.
4114 bool addHostDependenceToDeviceActions(Action *&HostAction,
4115 const Arg *InputArg) {
4116 if (!IsValid)
4117 return true;
4118
4119 recordHostAction(HostAction, InputArg);
4120
4121 // If we are supporting bundling/unbundling and the current action is an
4122 // input action of non-source file, we replace the host action by the
4123 // unbundling action. The bundler tool has the logic to detect if an input
4124 // is a bundle or not and if the input is not a bundle it assumes it is a
4125 // host file. Therefore it is safe to create an unbundling action even if
4126 // the input is not a bundle.
4127 if (CanUseBundler && isa<InputAction>(Val: HostAction) &&
4128 InputArg->getOption().getKind() == llvm::opt::Option::InputClass &&
4129 (!types::isSrcFile(Id: HostAction->getType()) ||
4130 HostAction->getType() == types::TY_PP_HIP)) {
4131 auto UnbundlingHostAction =
4132 C.MakeAction<OffloadUnbundlingJobAction>(Arg&: HostAction);
4133 UnbundlingHostAction->registerDependentActionInfo(
4134 TC: C.getSingleOffloadToolChain<Action::OFK_Host>(),
4135 /*BA=*/{}, Kind: Action::OFK_Host);
4136 HostAction = UnbundlingHostAction;
4137 recordHostAction(HostAction, InputArg);
4138 }
4139
4140 assert(HostAction && "Invalid host action!");
4141
4142 // Register the offload kinds that are used.
4143 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
4144 for (auto *SB : SpecializedBuilders) {
4145 if (!SB->isValid())
4146 continue;
4147
4148 auto RetCode = SB->addDeviceDependences(HostAction);
4149
4150 // Host dependences for device actions are not compatible with that same
4151 // action being ignored.
4152 assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host &&
4153 "Host dependence not expected to be ignored.!");
4154
4155 // Unless the builder was inactive for this action, we have to record the
4156 // offload kind because the host will have to use it.
4157 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
4158 OffloadKind |= SB->getAssociatedOffloadKind();
4159 }
4160
4161 // Do not use unbundler if the Host does not depend on device action.
4162 if (OffloadKind == Action::OFK_None && CanUseBundler)
4163 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(Val: HostAction))
4164 HostAction = UA->getInputs().back();
4165
4166 return false;
4167 }
4168
4169 /// Add the offloading top level actions to the provided action list. This
4170 /// function can replace the host action by a bundling action if the
4171 /// programming models allow it.
4172 bool appendTopLevelActions(ActionList &AL, Action *HostAction,
4173 const Arg *InputArg) {
4174 if (HostAction)
4175 recordHostAction(HostAction, InputArg);
4176
4177 // Get the device actions to be appended.
4178 ActionList OffloadAL;
4179 for (auto *SB : SpecializedBuilders) {
4180 if (!SB->isValid())
4181 continue;
4182 SB->appendTopLevelActions(AL&: OffloadAL);
4183 }
4184
4185 // If we can and should use the bundler, replace the host action by the
4186 // bundling one in the resulting list. Otherwise, just append the device
4187 // actions. For device only compilation, HostAction is a null pointer,
4188 // therefore only do this when HostAction is not a null pointer.
4189 if (CanUseBundler && ShouldUseBundler && HostAction &&
4190 HostAction->getType() != types::TY_Nothing && !OffloadAL.empty()) {
4191 // Add the host action to the list in order to create the bundling action.
4192 OffloadAL.push_back(Elt: HostAction);
4193
4194 // We expect that the host action was just appended to the action list
4195 // before this method was called.
4196 assert(HostAction == AL.back() && "Host action not in the list??");
4197 HostAction = C.MakeAction<OffloadBundlingJobAction>(Arg&: OffloadAL);
4198 recordHostAction(HostAction, InputArg);
4199 AL.back() = HostAction;
4200 } else
4201 AL.append(in_start: OffloadAL.begin(), in_end: OffloadAL.end());
4202
4203 // Propagate to the current host action (if any) the offload information
4204 // associated with the current input.
4205 if (HostAction)
4206 HostAction->propagateHostOffloadInfo(OKinds: InputArgToOffloadKindMap[InputArg],
4207 /*BA=*/OArch: {});
4208 return false;
4209 }
4210
4211 void appendDeviceLinkActions(ActionList &AL) {
4212 for (DeviceActionBuilder *SB : SpecializedBuilders) {
4213 if (!SB->isValid())
4214 continue;
4215 SB->appendLinkDeviceActions(AL);
4216 }
4217 }
4218
4219 Action *makeHostLinkAction() {
4220 // Build a list of device linking actions.
4221 ActionList DeviceAL;
4222 appendDeviceLinkActions(AL&: DeviceAL);
4223 if (DeviceAL.empty())
4224 return nullptr;
4225
4226 // Let builders add host linking actions.
4227 Action* HA = nullptr;
4228 for (DeviceActionBuilder *SB : SpecializedBuilders) {
4229 if (!SB->isValid())
4230 continue;
4231 HA = SB->appendLinkHostActions(AL&: DeviceAL);
4232 // This created host action has no originating input argument, therefore
4233 // needs to set its offloading kind directly.
4234 if (HA)
4235 HA->propagateHostOffloadInfo(OKinds: SB->getAssociatedOffloadKind(),
4236 /*BA=*/OArch: {});
4237 }
4238 return HA;
4239 }
4240
4241 /// Processes the host linker action. This currently consists of replacing it
4242 /// with an offload action if there are device link objects and propagate to
4243 /// the host action all the offload kinds used in the current compilation. The
4244 /// resulting action is returned.
4245 Action *processHostLinkAction(Action *HostAction) {
4246 // Add all the dependences from the device linking actions.
4247 OffloadAction::DeviceDependences DDeps;
4248 for (auto *SB : SpecializedBuilders) {
4249 if (!SB->isValid())
4250 continue;
4251
4252 SB->appendLinkDependences(DA&: DDeps);
4253 }
4254
4255 // Calculate all the offload kinds used in the current compilation.
4256 unsigned ActiveOffloadKinds = 0u;
4257 for (auto &I : InputArgToOffloadKindMap)
4258 ActiveOffloadKinds |= I.second;
4259
4260 // If we don't have device dependencies, we don't have to create an offload
4261 // action.
4262 if (DDeps.getActions().empty()) {
4263 // Set all the active offloading kinds to the link action. Given that it
4264 // is a link action it is assumed to depend on all actions generated so
4265 // far.
4266 HostAction->setHostOffloadInfo(OKinds: ActiveOffloadKinds,
4267 /*BA=*/OArch: {});
4268 // Propagate active offloading kinds for each input to the link action.
4269 // Each input may have different active offloading kind.
4270 for (auto *A : HostAction->inputs()) {
4271 auto ArgLoc = HostActionToInputArgMap.find(x: A);
4272 if (ArgLoc == HostActionToInputArgMap.end())
4273 continue;
4274 auto OFKLoc = InputArgToOffloadKindMap.find(x: ArgLoc->second);
4275 if (OFKLoc == InputArgToOffloadKindMap.end())
4276 continue;
4277 A->propagateHostOffloadInfo(OKinds: OFKLoc->second, /*BA=*/OArch: {});
4278 }
4279 return HostAction;
4280 }
4281
4282 // Create the offload action with all dependences. When an offload action
4283 // is created the kinds are propagated to the host action, so we don't have
4284 // to do that explicitly here.
4285 OffloadAction::HostDependence HDep(
4286 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
4287 /*BA=*/{}, ActiveOffloadKinds);
4288 return C.MakeAction<OffloadAction>(Arg&: HDep, Arg&: DDeps);
4289 }
4290};
4291} // anonymous namespace.
4292
4293void Driver::handleArguments(Compilation &C, DerivedArgList &Args,
4294 const InputList &Inputs,
4295 ActionList &Actions) const {
4296
4297 // Diagnose misuse of /Fo.
4298 if (Arg *A = Args.getLastArg(Ids: options::OPT__SLASH_Fo)) {
4299 StringRef V = A->getValue();
4300 if (Inputs.size() > 1 && !V.empty() &&
4301 !llvm::sys::path::is_separator(value: V.back())) {
4302 // Check whether /Fo tries to name an output file for multiple inputs.
4303 Diag(DiagID: clang::diag::err_drv_out_file_argument_with_multiple_sources)
4304 << A->getSpelling() << V;
4305 Args.eraseArg(Id: options::OPT__SLASH_Fo);
4306 }
4307 }
4308
4309 // Diagnose misuse of /Fa.
4310 if (Arg *A = Args.getLastArg(Ids: options::OPT__SLASH_Fa)) {
4311 StringRef V = A->getValue();
4312 if (Inputs.size() > 1 && !V.empty() &&
4313 !llvm::sys::path::is_separator(value: V.back())) {
4314 // Check whether /Fa tries to name an asm file for multiple inputs.
4315 Diag(DiagID: clang::diag::err_drv_out_file_argument_with_multiple_sources)
4316 << A->getSpelling() << V;
4317 Args.eraseArg(Id: options::OPT__SLASH_Fa);
4318 }
4319 }
4320
4321 // Diagnose misuse of /o.
4322 if (Arg *A = Args.getLastArg(Ids: options::OPT__SLASH_o)) {
4323 if (A->getValue()[0] == '\0') {
4324 // It has to have a value.
4325 Diag(DiagID: clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
4326 Args.eraseArg(Id: options::OPT__SLASH_o);
4327 }
4328 }
4329
4330 // Ignore /Yc/Yu if both /Yc and /Yu passed but with different filenames.
4331 Arg *YcArg = Args.getLastArg(Ids: options::OPT__SLASH_Yc);
4332 Arg *YuArg = Args.getLastArg(Ids: options::OPT__SLASH_Yu);
4333 if (YcArg && YuArg && strcmp(s1: YcArg->getValue(), s2: YuArg->getValue()) != 0) {
4334 Diag(DiagID: clang::diag::warn_drv_ycyu_different_arg_clang_cl);
4335 Args.eraseArg(Id: options::OPT__SLASH_Yc);
4336 Args.eraseArg(Id: options::OPT__SLASH_Yu);
4337 YcArg = YuArg = nullptr;
4338 }
4339 if (YcArg && Inputs.size() > 1) {
4340 Diag(DiagID: clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
4341 Args.eraseArg(Id: options::OPT__SLASH_Yc);
4342 YcArg = nullptr;
4343 }
4344
4345 Arg *FinalPhaseArg;
4346 phases::ID FinalPhase = getFinalPhase(DAL: Args, FinalPhaseArg: &FinalPhaseArg);
4347
4348 if (FinalPhase == phases::Link) {
4349 if (Args.hasArgNoClaim(Ids: options::OPT_hipstdpar)) {
4350 Args.AddFlagArg(BaseArg: nullptr, Opt: getOpts().getOption(Opt: options::OPT_hip_link));
4351 Args.AddFlagArg(BaseArg: nullptr,
4352 Opt: getOpts().getOption(Opt: options::OPT_frtlib_add_rpath));
4353 }
4354 // Emitting LLVM while linking disabled except in the HIPAMD or SPIR-V
4355 // Toolchains
4356 if (Args.hasArg(Ids: options::OPT_emit_llvm) &&
4357 !Args.hasArg(Ids: options::OPT_hip_link) &&
4358 !C.getDefaultToolChain().getTriple().isSPIRV())
4359 Diag(DiagID: clang::diag::err_drv_emit_llvm_link);
4360 if (C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment() &&
4361 C.getDefaultToolChain().isUsingLTO(Args) &&
4362 !Args.getLastArgValue(Id: options::OPT_fuse_ld_EQ)
4363 .starts_with_insensitive(Prefix: "lld"))
4364 Diag(DiagID: clang::diag::err_drv_lto_without_lld);
4365
4366 // If -dumpdir is not specified, give a default prefix derived from the link
4367 // output filename. For example, `clang -g -gsplit-dwarf a.c -o x` passes
4368 // `-dumpdir x-` to cc1. If -o is unspecified, use
4369 // stem(getDefaultImageName()) (usually stem("a.out") = "a").
4370 if (!Args.hasArg(Ids: options::OPT_dumpdir)) {
4371 Arg *FinalOutput = Args.getLastArg(Ids: options::OPT_o, Ids: options::OPT__SLASH_o);
4372 Arg *Arg = Args.MakeSeparateArg(
4373 BaseArg: nullptr, Opt: getOpts().getOption(Opt: options::OPT_dumpdir),
4374 Value: Args.MakeArgString(
4375 Str: (FinalOutput ? FinalOutput->getValue()
4376 : llvm::sys::path::stem(path: getDefaultImageName())) +
4377 "-"));
4378 Arg->claim();
4379 Args.append(A: Arg);
4380 }
4381 }
4382
4383 if (FinalPhase == phases::Preprocess || Args.hasArg(Ids: options::OPT__SLASH_Y_)) {
4384 // If only preprocessing or /Y- is used, all pch handling is disabled.
4385 // Rather than check for it everywhere, just remove clang-cl pch-related
4386 // flags here.
4387 Args.eraseArg(Id: options::OPT__SLASH_Fp);
4388 Args.eraseArg(Id: options::OPT__SLASH_Yc);
4389 Args.eraseArg(Id: options::OPT__SLASH_Yu);
4390 YcArg = YuArg = nullptr;
4391 }
4392
4393 if (Args.hasArg(Ids: options::OPT_include_pch) &&
4394 Args.hasArg(Ids: options::OPT_ignore_pch)) {
4395 // If -ignore-pch is used, -include-pch is disabled. Since -emit-pch is
4396 // CC1option, it will not be added to command argments if -ignore-pch is
4397 // used.
4398 Args.eraseArg(Id: options::OPT_include_pch);
4399 }
4400
4401 bool LinkOnly = phases::Link == FinalPhase && Inputs.size() > 0;
4402 for (auto &I : Inputs) {
4403 types::ID InputType = I.first;
4404 const Arg *InputArg = I.second;
4405
4406 auto PL = types::getCompilationPhases(Id: InputType);
4407
4408 phases::ID InitialPhase = PL[0];
4409 LinkOnly = LinkOnly && phases::Link == InitialPhase && PL.size() == 1;
4410
4411 // If the first step comes after the final phase we are doing as part of
4412 // this compilation, warn the user about it.
4413 if (InitialPhase > FinalPhase) {
4414 if (InputArg->isClaimed())
4415 continue;
4416
4417 // Claim here to avoid the more general unused warning.
4418 InputArg->claim();
4419
4420 // Suppress all unused style warnings with -Qunused-arguments
4421 if (Args.hasArg(Ids: options::OPT_Qunused_arguments))
4422 continue;
4423
4424 // Special case when final phase determined by binary name, rather than
4425 // by a command-line argument with a corresponding Arg.
4426 if (CCCIsCPP())
4427 Diag(DiagID: clang::diag::warn_drv_input_file_unused_by_cpp)
4428 << InputArg->getAsString(Args) << getPhaseName(Id: InitialPhase);
4429 // Special case '-E' warning on a previously preprocessed file to make
4430 // more sense.
4431 else if (InitialPhase == phases::Compile &&
4432 (Args.getLastArg(Ids: options::OPT__SLASH_EP,
4433 Ids: options::OPT__SLASH_P) ||
4434 Args.getLastArg(Ids: options::OPT_E) ||
4435 Args.getLastArg(Ids: options::OPT_M, Ids: options::OPT_MM)) &&
4436 getPreprocessedType(Id: InputType) == types::TY_INVALID)
4437 Diag(DiagID: clang::diag::warn_drv_preprocessed_input_file_unused)
4438 << InputArg->getAsString(Args) << !!FinalPhaseArg
4439 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
4440 else
4441 Diag(DiagID: clang::diag::warn_drv_input_file_unused)
4442 << InputArg->getAsString(Args) << getPhaseName(Id: InitialPhase)
4443 << !!FinalPhaseArg
4444 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
4445 continue;
4446 }
4447
4448 if (YcArg) {
4449 // Add a separate precompile phase for the compile phase.
4450 if (FinalPhase >= phases::Compile) {
4451 const types::ID HeaderType = lookupHeaderTypeForSourceType(Id: InputType);
4452 // Build the pipeline for the pch file.
4453 Action *ClangClPch = C.MakeAction<InputAction>(Arg: *InputArg, Arg: HeaderType);
4454 auto HostLTO = C.getDefaultToolChain().getLTOMode(Args);
4455 for (phases::ID Phase : types::getCompilationPhases(Id: HeaderType))
4456 ClangClPch = ConstructPhaseAction(C, Args, Phase, Input: ClangClPch,
4457 TargetDeviceOffloadKind: Action::OFK_None, TargetLTOMode: HostLTO);
4458 assert(ClangClPch);
4459 Actions.push_back(Elt: ClangClPch);
4460 // The driver currently exits after the first failed command. This
4461 // relies on that behavior, to make sure if the pch generation fails,
4462 // the main compilation won't run.
4463 // FIXME: If the main compilation fails, the PCH generation should
4464 // probably not be considered successful either.
4465 }
4466 }
4467 }
4468
4469 // Claim any options which are obviously only used for compilation.
4470 if (LinkOnly) {
4471 Args.ClaimAllArgs(Id0: options::OPT_CompileOnly_Group);
4472 Args.ClaimAllArgs(Id0: options::OPT_cl_compile_Group);
4473 }
4474}
4475
4476/// HIP non-RDC \c -S for AMDGCN: emit host and device assembly separately and
4477/// bundle with \c clang-offload-bundler (new offload driver), instead of
4478/// \c llvm-offload-binary / \c clang-linker-wrapper fatbin embedding.
4479static bool
4480shouldBundleHIPAsmWithNewDriver(const Compilation &C,
4481 const llvm::opt::DerivedArgList &Args,
4482 const Driver &D) {
4483 if (!C.isOffloadingHostKind(Kind: Action::OFK_HIP) ||
4484 !Args.hasArg(Ids: options::OPT_S) || Args.hasArg(Ids: options::OPT_emit_llvm) ||
4485 D.offloadDeviceOnly() ||
4486 Args.hasFlag(Pos: options::OPT_fgpu_rdc, Neg: options::OPT_fno_gpu_rdc, Default: false))
4487 return false;
4488
4489 bool HasAMDGCNHIPDevice = false;
4490 auto HIPTCs = C.getOffloadToolChains(Kind: Action::OFK_HIP);
4491 for (auto It = HIPTCs.first; It != HIPTCs.second; ++It) {
4492 const ToolChain *TC = It->second;
4493 const llvm::Triple &Tr = TC->getTriple();
4494 if (!Tr.isAMDGPU())
4495 return false;
4496 HasAMDGCNHIPDevice = true;
4497 }
4498 return HasAMDGCNHIPDevice;
4499}
4500
4501void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
4502 const InputList &Inputs, ActionList &Actions) const {
4503 llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
4504
4505 if (!SuppressMissingInputWarning && Inputs.empty()) {
4506 Diag(DiagID: clang::diag::err_drv_no_input_files);
4507 return;
4508 }
4509
4510 handleArguments(C, Args, Inputs, Actions);
4511
4512 bool UseNewOffloadingDriver = Args.hasFlag(
4513 Pos: options::OPT_offload_new_driver, Neg: options::OPT_no_offload_new_driver,
4514 Default: C.getActiveOffloadKinds() != Action::OFK_None);
4515
4516 // Builder to be used to build offloading actions.
4517 std::unique_ptr<OffloadingActionBuilder> OffloadBuilder =
4518 !UseNewOffloadingDriver
4519 ? std::make_unique<OffloadingActionBuilder>(args&: C, args&: Args, args: Inputs)
4520 : nullptr;
4521
4522 // Construct the actions to perform.
4523 ExtractAPIJobAction *ExtractAPIAction = nullptr;
4524 ActionList LinkerInputs;
4525 ActionList MergerInputs;
4526
4527 for (auto &I : Inputs) {
4528 types::ID InputType = I.first;
4529 const Arg *InputArg = I.second;
4530
4531 auto PL = types::getCompilationPhases(Driver: *this, DAL&: Args, Id: InputType);
4532 if (PL.empty())
4533 continue;
4534
4535 auto FullPL = types::getCompilationPhases(Id: InputType);
4536
4537 // Build the pipeline for this file.
4538 Action *Current = C.MakeAction<InputAction>(Arg: *InputArg, Arg&: InputType);
4539
4540 std::string CUID;
4541 if (CUIDOpts.isEnabled() && types::isSrcFile(Id: InputType)) {
4542 CUID = CUIDOpts.getCUID(InputFile: InputArg->getValue(), Args);
4543 cast<InputAction>(Val: Current)->setId(CUID);
4544 }
4545
4546 ActionList HIPAsmDeviceActions;
4547
4548 // Use the current host action in any of the offloading actions, if
4549 // required.
4550 if (!UseNewOffloadingDriver)
4551 if (OffloadBuilder->addHostDependenceToDeviceActions(HostAction&: Current, InputArg))
4552 break;
4553
4554 for (phases::ID Phase : PL) {
4555
4556 // Add any offload action the host action depends on.
4557 if (!UseNewOffloadingDriver)
4558 Current = OffloadBuilder->addDeviceDependencesToHostAction(
4559 HostAction: Current, InputArg, CurPhase: Phase, FinalPhase: PL.back(), Phases: FullPL);
4560 if (!Current)
4561 break;
4562
4563 // Queue linker inputs.
4564 if (Phase == phases::Link) {
4565 assert(Phase == PL.back() && "linking must be final compilation step.");
4566 // We don't need to generate additional link commands if emitting AMD
4567 // bitcode or compiling only for the offload device
4568 if (!(C.getInputArgs().hasArg(Ids: options::OPT_hip_link) &&
4569 (C.getInputArgs().hasArg(Ids: options::OPT_emit_llvm))) &&
4570 !offloadDeviceOnly())
4571 LinkerInputs.push_back(Elt: Current);
4572 Current = nullptr;
4573 break;
4574 }
4575
4576 // TODO: Consider removing this because the merged may not end up being
4577 // the final Phase in the pipeline. Perhaps the merged could just merge
4578 // and then pass an artifact of some sort to the Link Phase.
4579 // Queue merger inputs.
4580 if (Phase == phases::IfsMerge) {
4581 assert(Phase == PL.back() && "merging must be final compilation step.");
4582 MergerInputs.push_back(Elt: Current);
4583 Current = nullptr;
4584 break;
4585 }
4586
4587 if (Phase == phases::Precompile && ExtractAPIAction) {
4588 ExtractAPIAction->addHeaderInput(Input: Current);
4589 Current = nullptr;
4590 break;
4591 }
4592
4593 // FIXME: Should we include any prior module file outputs as inputs of
4594 // later actions in the same command line?
4595
4596 // Otherwise construct the appropriate action.
4597 Action *NewCurrent =
4598 ConstructPhaseAction(C, Args, Phase, Input: Current, TargetDeviceOffloadKind: Action::OFK_None,
4599 TargetLTOMode: C.getDefaultToolChain().getLTOMode(Args));
4600
4601 // We didn't create a new action, so we will just move to the next phase.
4602 if (NewCurrent == Current)
4603 continue;
4604
4605 if (auto *EAA = dyn_cast<ExtractAPIJobAction>(Val: NewCurrent))
4606 ExtractAPIAction = EAA;
4607
4608 Current = NewCurrent;
4609
4610 // Try to build the offloading actions and add the result as a dependency
4611 // to the host.
4612 if (UseNewOffloadingDriver)
4613 Current = BuildOffloadingActions(C, Args, Input: I, CUID, HostAction: Current,
4614 HIPAsmBundleDeviceOut: &HIPAsmDeviceActions);
4615 // Use the current host action in any of the offloading actions, if
4616 // required.
4617 else if (OffloadBuilder->addHostDependenceToDeviceActions(HostAction&: Current,
4618 InputArg))
4619 break;
4620
4621 if (Current->getType() == types::TY_Nothing)
4622 break;
4623 }
4624
4625 // HIP non-RDC -S (AMDGCN): bundle host and device assembly like the
4626 // classic driver instead of embedding a fat binary in host asm.
4627 if (Current && !HIPAsmDeviceActions.empty()) {
4628 assert(UseNewOffloadingDriver && "unexpected HIP asm bundle list");
4629 ActionList BundleInputs;
4630 BundleInputs.append(RHS: HIPAsmDeviceActions);
4631 BundleInputs.push_back(Elt: Current);
4632 Current = C.MakeAction<OffloadBundlingJobAction>(Arg&: BundleInputs);
4633 }
4634
4635 // If we ended with something, add to the output list.
4636 if (Current)
4637 Actions.push_back(Elt: Current);
4638
4639 // Add any top level actions generated for offloading.
4640 if (!UseNewOffloadingDriver)
4641 OffloadBuilder->appendTopLevelActions(AL&: Actions, HostAction: Current, InputArg);
4642 else if (Current)
4643 Current->propagateHostOffloadInfo(OKinds: C.getActiveOffloadKinds(),
4644 /*BA=*/OArch: {});
4645 }
4646
4647 // Add a link action if necessary.
4648
4649 if (LinkerInputs.empty()) {
4650 Arg *FinalPhaseArg;
4651 if (getFinalPhase(DAL: Args, FinalPhaseArg: &FinalPhaseArg) == phases::Link)
4652 if (!UseNewOffloadingDriver)
4653 OffloadBuilder->appendDeviceLinkActions(AL&: Actions);
4654 }
4655
4656 if (!LinkerInputs.empty()) {
4657 if (!UseNewOffloadingDriver)
4658 if (Action *Wrapper = OffloadBuilder->makeHostLinkAction())
4659 LinkerInputs.push_back(Elt: Wrapper);
4660 Action *LA;
4661 // Check if this Linker Job should emit a static library.
4662 if (ShouldEmitStaticLibrary(Args)) {
4663 LA = C.MakeAction<StaticLibJobAction>(Arg&: LinkerInputs, Arg: types::TY_Image);
4664 } else if (UseNewOffloadingDriver ||
4665 Args.hasArg(Ids: options::OPT_offload_link)) {
4666 LA = C.MakeAction<LinkerWrapperJobAction>(Arg&: LinkerInputs, Arg: types::TY_Image);
4667 LA->propagateHostOffloadInfo(OKinds: C.getActiveOffloadKinds(),
4668 /*BA=*/OArch: {});
4669 } else {
4670 // If we are linking but were passed -emit-llvm, we will be calling
4671 // llvm-link, so set the output type accordingly. This is only allowed in
4672 // rare cases, so make sure we aren't going to error about it.
4673 bool LinkingIR = Args.hasArg(Ids: options::OPT_emit_llvm) &&
4674 C.getDefaultToolChain().getTriple().isSPIRV();
4675 types::ID LT = LinkingIR && !Diags.hasErrorOccurred() ? types::TY_LLVM_BC
4676 : types::TY_Image;
4677 LA = C.MakeAction<LinkJobAction>(Arg&: LinkerInputs, Arg&: LT);
4678 }
4679 if (!UseNewOffloadingDriver)
4680 LA = OffloadBuilder->processHostLinkAction(HostAction: LA);
4681 Actions.push_back(Elt: LA);
4682 }
4683
4684 // Add an interface stubs merge action if necessary.
4685 if (!MergerInputs.empty())
4686 Actions.push_back(
4687 Elt: C.MakeAction<IfsMergeJobAction>(Arg&: MergerInputs, Arg: types::TY_Image));
4688
4689 if (Args.hasArg(Ids: options::OPT_emit_interface_stubs)) {
4690 auto PhaseList = types::getCompilationPhases(
4691 Id: types::TY_IFS_CPP,
4692 LastPhase: Args.hasArg(Ids: options::OPT_c) ? phases::Compile : phases::IfsMerge);
4693
4694 ActionList MergerInputs;
4695
4696 for (auto &I : Inputs) {
4697 types::ID InputType = I.first;
4698 const Arg *InputArg = I.second;
4699
4700 // Currently clang and the llvm assembler do not support generating symbol
4701 // stubs from assembly, so we skip the input on asm files. For ifs files
4702 // we rely on the normal pipeline setup in the pipeline setup code above.
4703 if (InputType == types::TY_IFS || InputType == types::TY_PP_Asm ||
4704 InputType == types::TY_Asm)
4705 continue;
4706
4707 Action *Current = C.MakeAction<InputAction>(Arg: *InputArg, Arg&: InputType);
4708
4709 for (auto Phase : PhaseList) {
4710 switch (Phase) {
4711 default:
4712 llvm_unreachable(
4713 "IFS Pipeline can only consist of Compile followed by IfsMerge.");
4714 case phases::Compile: {
4715 // Only IfsMerge (llvm-ifs) can handle .o files by looking for ifs
4716 // files where the .o file is located. The compile action can not
4717 // handle this.
4718 if (InputType == types::TY_Object)
4719 break;
4720
4721 Current = C.MakeAction<CompileJobAction>(Arg&: Current, Arg: types::TY_IFS_CPP);
4722 break;
4723 }
4724 case phases::IfsMerge: {
4725 assert(Phase == PhaseList.back() &&
4726 "merging must be final compilation step.");
4727 MergerInputs.push_back(Elt: Current);
4728 Current = nullptr;
4729 break;
4730 }
4731 }
4732 }
4733
4734 // If we ended with something, add to the output list.
4735 if (Current)
4736 Actions.push_back(Elt: Current);
4737 }
4738
4739 // Add an interface stubs merge action if necessary.
4740 if (!MergerInputs.empty())
4741 Actions.push_back(
4742 Elt: C.MakeAction<IfsMergeJobAction>(Arg&: MergerInputs, Arg: types::TY_Image));
4743 }
4744
4745 for (auto Opt : {options::OPT_print_supported_cpus,
4746 options::OPT_print_supported_extensions,
4747 options::OPT_print_enabled_extensions}) {
4748 // If --print-supported-cpus, -mcpu=? or -mtune=? is specified, build a
4749 // custom Compile phase that prints out supported cpu models and quits.
4750 //
4751 // If either --print-supported-extensions or --print-enabled-extensions is
4752 // specified, call the corresponding helper function that prints out the
4753 // supported/enabled extensions and quits.
4754 if (Arg *A = Args.getLastArg(Ids: Opt)) {
4755 if (Opt == options::OPT_print_supported_extensions &&
4756 !C.getDefaultToolChain().getTriple().isRISCV() &&
4757 !C.getDefaultToolChain().getTriple().isAArch64() &&
4758 !C.getDefaultToolChain().getTriple().isARM()) {
4759 C.getDriver().Diag(DiagID: diag::err_opt_not_valid_on_target)
4760 << "--print-supported-extensions";
4761 return;
4762 }
4763 if (Opt == options::OPT_print_enabled_extensions &&
4764 !C.getDefaultToolChain().getTriple().isRISCV() &&
4765 !C.getDefaultToolChain().getTriple().isAArch64()) {
4766 C.getDriver().Diag(DiagID: diag::err_opt_not_valid_on_target)
4767 << "--print-enabled-extensions";
4768 return;
4769 }
4770
4771 // Use the -mcpu=? flag as the dummy input to cc1.
4772 Actions.clear();
4773 Action *InputAc = C.MakeAction<InputAction>(
4774 Arg&: *A, Arg: IsFlangMode() ? types::TY_Fortran : types::TY_C);
4775 Actions.push_back(
4776 Elt: C.MakeAction<PrecompileJobAction>(Arg&: InputAc, Arg: types::TY_Nothing));
4777 for (auto &I : Inputs)
4778 I.second->claim();
4779 }
4780 }
4781
4782 llvm::Triple TargetTriple(C.getDriver().getTargetTriple());
4783 if (TargetTriple.getOS() == llvm::Triple::Vulkan ||
4784 TargetTriple.getOS() == llvm::Triple::ShaderModel) {
4785 const auto &TC =
4786 static_cast<const toolchains::HLSLToolChain &>(C.getDefaultToolChain());
4787
4788 // Call objcopy for manipulation of the unvalidated DXContainer when an
4789 // option in Args requires it.
4790 if (TC.requiresObjcopy(Args)) {
4791 Action *LastAction = Actions.back();
4792 // llvm-objcopy expects an unvalidated DXIL container (TY_OBJECT).
4793 if (LastAction->getType() == types::TY_Object) {
4794 ActionList ObjcopyActions({LastAction});
4795 Actions.push_back(
4796 Elt: C.MakeAction<ObjcopyJobAction>(Arg&: ObjcopyActions, Arg: types::TY_Object));
4797 }
4798 }
4799
4800 // Call validator when -Vd not in Args.
4801 auto ValInfo = TC.getValidationInfo(Args);
4802 if (ValInfo.NeedsValidation) {
4803 Action *LastAction = Actions.back();
4804 if (LastAction->getType() == types::TY_Object) {
4805 types::ID OutType =
4806 ValInfo.ProducesOutput ? types::TY_DX_CONTAINER : types::TY_Object;
4807 Actions.push_back(
4808 Elt: C.MakeAction<BinaryAnalyzeJobAction>(Arg&: LastAction, Arg&: OutType));
4809 }
4810 }
4811
4812 // Call metal-shaderconverter when targeting metal.
4813 if (TC.requiresBinaryTranslation(Args)) {
4814 Action *LastAction = Actions.back();
4815 // Metal shader converter runs on DXIL containers, which can either be
4816 // validated (in which case they are TY_DX_CONTAINER), or unvalidated
4817 // (TY_OBJECT).
4818 if (LastAction->getType() == types::TY_DX_CONTAINER ||
4819 LastAction->getType() == types::TY_Object)
4820 Actions.push_back(Elt: C.MakeAction<BinaryTranslatorJobAction>(
4821 Arg&: LastAction, Arg: types::TY_DX_CONTAINER));
4822 }
4823 }
4824
4825 // Claim ignored clang-cl options.
4826 Args.ClaimAllArgs(Id0: options::OPT_cl_ignored_Group);
4827}
4828
4829/// Returns the canonical name for the offloading architecture when using a HIP
4830/// or CUDA architecture.
4831static StringRef getCanonicalArchString(Compilation &C,
4832 const llvm::opt::DerivedArgList &Args,
4833 StringRef ArchStr,
4834 const llvm::Triple &Triple) {
4835 // Lookup the CUDA / HIP architecture string. Only report an error if we were
4836 // expecting the triple to be only NVPTX / AMDGPU.
4837 OffloadArch Arch =
4838 StringToOffloadArch(S: getProcessorFromTargetID(T: Triple, OffloadArch: ArchStr));
4839 if (Triple.isNVPTX() &&
4840 (Arch == OffloadArch::Unknown || !IsNVIDIAOffloadArch(A: Arch))) {
4841 C.getDriver().Diag(DiagID: clang::diag::err_drv_offload_bad_gpu_arch)
4842 << "CUDA" << ArchStr;
4843 return StringRef();
4844 } else if (Triple.isAMDGPU() &&
4845 (Arch == OffloadArch::Unknown || !IsAMDOffloadArch(A: Arch))) {
4846 C.getDriver().Diag(DiagID: clang::diag::err_drv_offload_bad_gpu_arch)
4847 << "HIP" << ArchStr;
4848 return StringRef();
4849 }
4850
4851 if (IsNVIDIAOffloadArch(A: Arch))
4852 return Args.MakeArgStringRef(Str: OffloadArchToString(A: Arch));
4853
4854 if (IsAMDOffloadArch(A: Arch)) {
4855 llvm::StringMap<bool> Features;
4856 std::optional<StringRef> Arch = parseTargetID(T: Triple, OffloadArch: ArchStr, FeatureMap: &Features);
4857 if (!Arch) {
4858 C.getDriver().Diag(DiagID: clang::diag::err_drv_bad_target_id) << ArchStr;
4859 return StringRef();
4860 }
4861 return Args.MakeArgStringRef(Str: getCanonicalTargetID(Processor: *Arch, Features));
4862 }
4863
4864 // If the input isn't CUDA or HIP just return the architecture.
4865 return ArchStr;
4866}
4867
4868/// Checks if the set offloading architectures does not conflict. Returns the
4869/// incompatible pair if a conflict occurs.
4870static std::optional<std::pair<llvm::StringRef, llvm::StringRef>>
4871getConflictOffloadArchCombination(const llvm::DenseSet<StringRef> &Archs,
4872 llvm::Triple Triple) {
4873 if (!Triple.isAMDGPU())
4874 return std::nullopt;
4875
4876 std::set<StringRef> ArchSet;
4877 llvm::copy(Range: Archs, Out: std::inserter(x&: ArchSet, i: ArchSet.begin()));
4878 return getConflictTargetIDCombination(TargetIDs: ArchSet);
4879}
4880
4881llvm::SmallVector<BoundArch>
4882Driver::getOffloadArchs(Compilation &C, const llvm::opt::DerivedArgList &Args,
4883 Action::OffloadKind Kind, const ToolChain &TC) const {
4884 // --offload and --offload-arch options are mutually exclusive.
4885 if (Args.hasArgNoClaim(Ids: options::OPT_offload_EQ) &&
4886 Args.hasArgNoClaim(Ids: options::OPT_offload_arch_EQ,
4887 Ids: options::OPT_no_offload_arch_EQ)) {
4888 C.getDriver().Diag(DiagID: diag::err_opt_not_valid_with_opt)
4889 << "--offload"
4890 << (Args.hasArgNoClaim(Ids: options::OPT_offload_arch_EQ)
4891 ? "--offload-arch"
4892 : "--no-offload-arch");
4893 }
4894
4895 llvm::DenseSet<StringRef> Archs;
4896 for (auto *Arg : C.getArgsForToolChain(TC: &TC, /*BA=*/{}, DeviceOffloadKind: Kind)) {
4897 // Add or remove the seen architectures in order of appearance. If an
4898 // invalid architecture is given we simply exit.
4899 if (Arg->getOption().matches(ID: options::OPT_offload_arch_EQ)) {
4900 for (StringRef Arch : Arg->getValues()) {
4901 if (Arch == "native" || Arch.empty()) {
4902 auto GPUsOrErr = TC.getSystemGPUArchs(Args);
4903 if (!GPUsOrErr) {
4904 TC.getDriver().Diag(DiagID: diag::err_drv_undetermined_gpu_arch)
4905 << TC.getTriple().getArchName()
4906 << llvm::toString(E: GPUsOrErr.takeError()) << "--offload-arch";
4907 continue;
4908 }
4909
4910 for (auto ArchStr : *GPUsOrErr) {
4911 StringRef CanonicalStr = getCanonicalArchString(
4912 C, Args, ArchStr: Args.MakeArgString(Str: ArchStr), Triple: TC.getTriple());
4913 if (!CanonicalStr.empty())
4914 Archs.insert(V: CanonicalStr);
4915 else
4916 return {};
4917 }
4918 } else {
4919 StringRef CanonicalStr =
4920 getCanonicalArchString(C, Args, ArchStr: Arch, Triple: TC.getTriple());
4921 if (!CanonicalStr.empty())
4922 Archs.insert(V: CanonicalStr);
4923 else
4924 return {};
4925 }
4926 }
4927 } else if (Arg->getOption().matches(ID: options::OPT_no_offload_arch_EQ)) {
4928 for (StringRef Arch : Arg->getValues()) {
4929 if (Arch == "all") {
4930 Archs.clear();
4931 } else {
4932 StringRef ArchStr =
4933 getCanonicalArchString(C, Args, ArchStr: Arch, Triple: TC.getTriple());
4934 Archs.erase(V: ArchStr);
4935 }
4936 }
4937 }
4938 }
4939
4940 if (auto ConflictingArchs =
4941 getConflictOffloadArchCombination(Archs, Triple: TC.getTriple()))
4942 C.getDriver().Diag(DiagID: clang::diag::err_drv_bad_offload_arch_combo)
4943 << ConflictingArchs->first << ConflictingArchs->second;
4944
4945 // Fill in the default architectures if not provided explicitly.
4946 if (Archs.empty()) {
4947 if (Kind == Action::OFK_Cuda) {
4948 Archs.insert(V: OffloadArchToString(A: TC.getTriple().isSPIRV()
4949 ? OffloadArch::Unused
4950 : OffloadArch::CudaDefault));
4951 } else if (Kind == Action::OFK_HIP) {
4952 Archs.insert(V: OffloadArchToString(A: TC.getTriple().isSPIRV()
4953 ? OffloadArch::Generic
4954 : OffloadArch::HIPDefault));
4955 } else if (Kind == Action::OFK_SYCL) {
4956 Archs.insert(V: StringRef());
4957 } else if (Kind == Action::OFK_OpenMP) {
4958 // Accept legacy `-march` device arguments for OpenMP.
4959 if (auto *Arg = C.getArgsForToolChain(TC: &TC, /*BA=*/{}, DeviceOffloadKind: Kind)
4960 .getLastArg(Ids: options::OPT_march_EQ)) {
4961 Archs.insert(V: Arg->getValue());
4962 } else {
4963 auto ArchsOrErr = TC.getSystemGPUArchs(Args);
4964 if (!ArchsOrErr) {
4965 TC.getDriver().Diag(DiagID: diag::err_drv_undetermined_gpu_arch)
4966 << TC.getArchName() << llvm::toString(E: ArchsOrErr.takeError())
4967 << "--offload-arch";
4968 } else if (!ArchsOrErr->empty()) {
4969 for (auto Arch : *ArchsOrErr)
4970 Archs.insert(V: Args.MakeArgStringRef(Str: Arch));
4971 } else {
4972 Archs.insert(V: StringRef());
4973 }
4974 }
4975 }
4976 }
4977 Args.ClaimAllArgs(Id0: options::OPT_offload_arch_EQ);
4978 Args.ClaimAllArgs(Id0: options::OPT_no_offload_arch_EQ);
4979
4980 SmallVector<StringRef> Sorted(Archs.begin(), Archs.end());
4981 llvm::sort(C&: Sorted);
4982
4983 // Convert to BoundArch, parsing each architecture string once
4984 SmallVector<BoundArch> Result;
4985 Result.reserve(N: Sorted.size());
4986 for (StringRef Arch : Sorted)
4987 Result.push_back(Elt: BoundArch(Arch));
4988 return Result;
4989}
4990
4991Action *
4992Driver::BuildOffloadingActions(Compilation &C, llvm::opt::DerivedArgList &Args,
4993 const InputTy &Input, StringRef CUID,
4994 Action *HostAction,
4995 ActionList *HIPAsmBundleDeviceOut) const {
4996 // Don't build offloading actions if explicitly disabled or we do not have a
4997 // valid source input.
4998 if (offloadHostOnly() || !types::isSrcFile(Id: Input.first))
4999 return HostAction;
5000
5001 bool HIPNoRDC =
5002 C.isOffloadingHostKind(Kind: Action::OFK_HIP) &&
5003 !Args.hasFlag(Pos: options::OPT_fgpu_rdc, Neg: options::OPT_fno_gpu_rdc, Default: false);
5004
5005 bool HIPRelocatableObj =
5006 C.isOffloadingHostKind(Kind: Action::OFK_HIP) &&
5007 Args.hasFlag(Pos: options::OPT_fhip_emit_relocatable,
5008 Neg: options::OPT_fno_hip_emit_relocatable, Default: false);
5009
5010 if (!HIPNoRDC && HIPRelocatableObj)
5011 C.getDriver().Diag(DiagID: diag::err_opt_not_valid_with_opt)
5012 << "-fhip-emit-relocatable"
5013 << "-fgpu-rdc";
5014
5015 if (!offloadDeviceOnly() && HIPRelocatableObj)
5016 C.getDriver().Diag(DiagID: diag::err_opt_not_valid_without_opt)
5017 << "-fhip-emit-relocatable"
5018 << "--offload-device-only";
5019
5020 // Don't build offloading actions if we do not have a compile action. If
5021 // preprocessing only ignore embedding.
5022 if (!(isa<CompileJobAction>(Val: HostAction) ||
5023 getFinalPhase(DAL: Args) == phases::Preprocess))
5024 return HostAction;
5025
5026 ActionList OffloadActions;
5027 OffloadAction::DeviceDependences DDeps;
5028
5029 const Action::OffloadKind OffloadKinds[] = {
5030 Action::OFK_OpenMP, Action::OFK_Cuda, Action::OFK_HIP, Action::OFK_SYCL};
5031
5032 for (Action::OffloadKind Kind : OffloadKinds) {
5033 SmallVector<const ToolChain *, 2> ToolChains;
5034 ActionList DeviceActions;
5035
5036 auto TCRange = C.getOffloadToolChains(Kind);
5037 for (auto TI = TCRange.first, TE = TCRange.second; TI != TE; ++TI)
5038 ToolChains.push_back(Elt: TI->second);
5039
5040 if (ToolChains.empty())
5041 continue;
5042
5043 types::ID InputType = Input.first;
5044 const Arg *InputArg = Input.second;
5045
5046 // The toolchain can be active for unsupported file types.
5047 if ((Kind == Action::OFK_Cuda && !types::isCuda(Id: InputType)) ||
5048 (Kind == Action::OFK_HIP && !types::isHIP(Id: InputType)))
5049 continue;
5050
5051 // Get the product of all bound architectures and toolchains.
5052 SmallVector<std::pair<const ToolChain *, BoundArch>> TCAndArchs;
5053 for (const ToolChain *TC : ToolChains) {
5054 for (BoundArch Arch : getOffloadArchs(C, Args: C.getArgs(), Kind, TC: *TC)) {
5055 TCAndArchs.push_back(Elt: std::make_pair(x&: TC, y&: Arch));
5056 DeviceActions.push_back(
5057 Elt: C.MakeAction<InputAction>(Arg: *InputArg, Arg&: InputType, Arg&: CUID));
5058 }
5059 }
5060
5061 if (DeviceActions.empty())
5062 return HostAction;
5063
5064 // FIXME: Do not collapse the host side for Darwin targets with SYCL offload
5065 // compilations. The toolchain is not properly initialized for the target.
5066 if (isa<CompileJobAction>(Val: HostAction) && Kind == Action::OFK_SYCL &&
5067 HostAction->getType() != types::TY_Nothing &&
5068 C.getSingleOffloadToolChain<Action::OFK_Host>()
5069 ->getTriple()
5070 .isOSDarwin())
5071 HostAction->setCannotBeCollapsedWithNextDependentAction();
5072
5073 auto PL = types::getCompilationPhases(Driver: *this, DAL&: Args, Id: InputType);
5074
5075 for (phases::ID Phase : PL) {
5076 if (Phase == phases::Link) {
5077 assert(Phase == PL.back() && "linking must be final compilation step.");
5078 break;
5079 }
5080
5081 // Assemble actions are not used for the SYCL device side. Both compile
5082 // and backend actions are used to generate IR and textual IR if needed.
5083 if (Kind == Action::OFK_SYCL && Phase == phases::Assemble)
5084 continue;
5085
5086 auto *TCAndArch = TCAndArchs.begin();
5087 for (Action *&A : DeviceActions) {
5088 if (A->getType() == types::TY_Nothing)
5089 continue;
5090
5091 // Propagate the ToolChain so we can use it in ConstructPhaseAction.
5092 A->propagateDeviceOffloadInfo(OKind: Kind, OArch: TCAndArch->second,
5093 OToolChain: TCAndArch->first);
5094 A = ConstructPhaseAction(C, Args, Phase, Input: A, TargetDeviceOffloadKind: Kind,
5095 TargetLTOMode: TCAndArch->first->getLTOMode(Args, Kind));
5096
5097 if (isa<CompileJobAction>(Val: A) && isa<CompileJobAction>(Val: HostAction) &&
5098 Kind == Action::OFK_OpenMP &&
5099 HostAction->getType() != types::TY_Nothing) {
5100 // OpenMP offloading has a dependency on the host compile action to
5101 // identify which declarations need to be emitted. This shouldn't be
5102 // collapsed with any other actions so we can use it in the device.
5103 HostAction->setCannotBeCollapsedWithNextDependentAction();
5104 OffloadAction::HostDependence HDep(
5105 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
5106 TCAndArch->second, Kind);
5107 OffloadAction::DeviceDependences DDep;
5108 DDep.add(A&: *A, TC: *TCAndArch->first, BA: TCAndArch->second, OKind: Kind);
5109 A = C.MakeAction<OffloadAction>(Arg&: HDep, Arg&: DDep);
5110 }
5111
5112 ++TCAndArch;
5113 }
5114 }
5115
5116 // Compiling HIP in device-only non-RDC mode requires linking each action
5117 // individually.
5118 for (Action *&A : DeviceActions) {
5119 auto *OffloadTriple = A->getOffloadingToolChain()
5120 ? &A->getOffloadingToolChain()->getTriple()
5121 : nullptr;
5122 bool IsHIPSPV =
5123 OffloadTriple && OffloadTriple->isSPIRV() &&
5124 (OffloadTriple->getOS() == llvm::Triple::OSType::AMDHSA ||
5125 OffloadTriple->getOS() == llvm::Triple::OSType::ChipStar);
5126
5127 if ((A->getType() != types::TY_Object && !IsHIPSPV &&
5128 A->getType() != types::TY_LTO_BC) ||
5129 HIPRelocatableObj || !HIPNoRDC || !offloadDeviceOnly())
5130 continue;
5131 ActionList LinkerInput = {A};
5132 A = C.MakeAction<LinkJobAction>(Arg&: LinkerInput, Arg: types::TY_Image);
5133 }
5134
5135 auto *TCAndArch = TCAndArchs.begin();
5136 for (Action *A : DeviceActions) {
5137 DDeps.add(A&: *A, TC: *TCAndArch->first, BA: TCAndArch->second, OKind: Kind);
5138 OffloadAction::DeviceDependences DDep;
5139 DDep.add(A&: *A, TC: *TCAndArch->first, BA: TCAndArch->second, OKind: Kind);
5140
5141 // Compiling CUDA in non-RDC mode uses the PTX output if available.
5142 for (Action *Input : A->getInputs())
5143 if (Kind == Action::OFK_Cuda && A->getType() == types::TY_Object &&
5144 !Args.hasFlag(Pos: options::OPT_fgpu_rdc, Neg: options::OPT_fno_gpu_rdc,
5145 Default: false))
5146 DDep.add(A&: *Input, TC: *TCAndArch->first, BA: TCAndArch->second, OKind: Kind);
5147 OffloadActions.push_back(Elt: C.MakeAction<OffloadAction>(Arg&: DDep, Arg: A->getType()));
5148
5149 ++TCAndArch;
5150 }
5151 }
5152
5153 // HIP code in device-only non-RDC mode will bundle the output if it invoked
5154 // the linker or if the user explicitly requested it.
5155 bool ShouldBundleHIP =
5156 Args.hasFlag(Pos: options::OPT_gpu_bundle_output,
5157 Neg: options::OPT_no_gpu_bundle_output, Default: false) ||
5158 (!Args.getLastArg(Ids: options::OPT_no_gpu_bundle_output) && HIPNoRDC &&
5159 offloadDeviceOnly() && llvm::none_of(Range&: OffloadActions, P: [](Action *A) {
5160 return A->getType() != types::TY_Image;
5161 }));
5162
5163 // All kinds exit now in device-only mode except for non-RDC mode HIP.
5164 if (offloadDeviceOnly() && !ShouldBundleHIP)
5165 return C.MakeAction<OffloadAction>(Arg&: DDeps, Arg: types::TY_Nothing);
5166
5167 if (OffloadActions.empty())
5168 return HostAction;
5169
5170 OffloadAction::DeviceDependences DDep;
5171 if (C.isOffloadingHostKind(Kind: Action::OFK_Cuda) &&
5172 !Args.hasFlag(Pos: options::OPT_fgpu_rdc, Neg: options::OPT_fno_gpu_rdc, Default: false)) {
5173 // If we are not in RDC-mode we just emit the final CUDA fatbinary for
5174 // each translation unit without requiring any linking.
5175 Action *FatbinAction =
5176 C.MakeAction<LinkJobAction>(Arg&: OffloadActions, Arg: types::TY_CUDA_FATBIN);
5177 DDep.add(A&: *FatbinAction, TC: *C.getSingleOffloadToolChain<Action::OFK_Cuda>(),
5178 /*BA=*/{}, OKind: Action::OFK_Cuda);
5179 } else if (HIPNoRDC && offloadDeviceOnly()) {
5180 // If we are in device-only non-RDC-mode we just emit the final HIP
5181 // fatbinary for each translation unit, linking each input individually.
5182 Action *FatbinAction =
5183 C.MakeAction<LinkJobAction>(Arg&: OffloadActions, Arg: types::TY_HIP_FATBIN);
5184 DDep.add(A&: *FatbinAction,
5185 TC: *C.getOffloadToolChains<Action::OFK_HIP>().first->second,
5186 /*BA=*/{}, OKind: Action::OFK_HIP);
5187 } else if (HIPNoRDC) {
5188 // Host + device assembly: defer to clang-offload-bundler (see
5189 // BuildActions).
5190 if (HIPAsmBundleDeviceOut &&
5191 shouldBundleHIPAsmWithNewDriver(C, Args, D: C.getDriver())) {
5192 for (Action *OA : OffloadActions)
5193 HIPAsmBundleDeviceOut->push_back(Elt: OA);
5194 return HostAction;
5195 }
5196 // Package all the offloading actions into a single output that can be
5197 // embedded in the host and linked.
5198 Action *PackagerAction =
5199 C.MakeAction<OffloadPackagerJobAction>(Arg&: OffloadActions, Arg: types::TY_Image);
5200
5201 // For HIP non-RDC compilation, wrap the device binary with linker wrapper
5202 // before bundling with host code. Do not bind a specific GPU arch here,
5203 // as the packaged image may contain entries for multiple GPUs.
5204 ActionList AL{PackagerAction};
5205 PackagerAction =
5206 C.MakeAction<LinkerWrapperJobAction>(Arg&: AL, Arg: types::TY_HIP_FATBIN);
5207 DDep.add(A&: *PackagerAction,
5208 TC: *C.getOffloadToolChains<Action::OFK_HIP>().first->second,
5209 /*BA=*/{}, OKind: Action::OFK_HIP);
5210 } else {
5211 // Package all the offloading actions into a single output that can be
5212 // embedded in the host and linked.
5213 Action *PackagerAction =
5214 C.MakeAction<OffloadPackagerJobAction>(Arg&: OffloadActions, Arg: types::TY_Image);
5215 DDep.add(A&: *PackagerAction, TC: *C.getSingleOffloadToolChain<Action::OFK_Host>(),
5216 /*BA=*/{}, OffloadKindMask: C.getActiveOffloadKinds());
5217 }
5218
5219 // HIP wants '--offload-device-only' to create a fatbinary by default.
5220 if (offloadDeviceOnly())
5221 return C.MakeAction<OffloadAction>(Arg&: DDep, Arg: types::TY_Nothing);
5222
5223 // If we are unable to embed a single device output into the host, we need to
5224 // add each device output as a host dependency to ensure they are still built.
5225 bool SingleDeviceOutput = !llvm::any_of(Range&: OffloadActions, P: [](Action *A) {
5226 return A->getType() == types::TY_Nothing;
5227 }) && isa<CompileJobAction>(Val: HostAction);
5228 OffloadAction::HostDependence HDep(
5229 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
5230 /*BA=*/{}, SingleDeviceOutput ? DDep : DDeps);
5231 return C.MakeAction<OffloadAction>(Arg&: HDep, Arg&: SingleDeviceOutput ? DDep : DDeps);
5232}
5233
5234Action *Driver::ConstructPhaseAction(
5235 Compilation &C, const ArgList &Args, phases::ID Phase, Action *Input,
5236 Action::OffloadKind TargetDeviceOffloadKind, LTOKind TargetLTOMode) const {
5237 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
5238
5239 // Some types skip the assembler phase (e.g., llvm-bc), but we can't
5240 // encode this in the steps because the intermediate type depends on
5241 // arguments. Just special case here.
5242 if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm)
5243 return Input;
5244
5245 // Use of --sycl-link will only allow for the link phase to occur. This is
5246 // for all input files.
5247 if (Args.hasArg(Ids: options::OPT_sycl_link) && Phase != phases::Link)
5248 return Input;
5249
5250 // Build the appropriate action.
5251 switch (Phase) {
5252 case phases::Link:
5253 llvm_unreachable("link action invalid here.");
5254 case phases::IfsMerge:
5255 llvm_unreachable("ifsmerge action invalid here.");
5256 case phases::Preprocess: {
5257 types::ID OutputTy;
5258 // -M and -MM specify the dependency file name by altering the output type,
5259 // -if -MD and -MMD are not specified.
5260 if (Args.hasArg(Ids: options::OPT_M, Ids: options::OPT_MM) &&
5261 !Args.hasArg(Ids: options::OPT_MD, Ids: options::OPT_MMD)) {
5262 OutputTy = types::TY_Dependencies;
5263 } else {
5264 OutputTy = Input->getType();
5265 // For these cases, the preprocessor is only translating forms, the Output
5266 // still needs preprocessing.
5267 if (!Args.hasFlag(Pos: options::OPT_frewrite_includes,
5268 Neg: options::OPT_fno_rewrite_includes, Default: false) &&
5269 !Args.hasFlag(Pos: options::OPT_frewrite_imports,
5270 Neg: options::OPT_fno_rewrite_imports, Default: false) &&
5271 !Args.hasFlag(Pos: options::OPT_fdirectives_only,
5272 Neg: options::OPT_fno_directives_only, Default: false) &&
5273 !CCGenDiagnostics)
5274 OutputTy = types::getPreprocessedType(Id: OutputTy);
5275 assert(OutputTy != types::TY_INVALID &&
5276 "Cannot preprocess this input type!");
5277 }
5278 return C.MakeAction<PreprocessJobAction>(Arg&: Input, Arg&: OutputTy);
5279 }
5280 case phases::Precompile: {
5281 // API extraction should not generate an actual precompilation action.
5282 if (Args.hasArg(Ids: options::OPT_extract_api))
5283 return C.MakeAction<ExtractAPIJobAction>(Arg&: Input, Arg: types::TY_API_INFO);
5284
5285 // Standard library modules always precompile in -fmodules-driver mode,
5286 // even when -fsyntax-only is specified.
5287 if (Input->getType() == types::TY_CXXStdModule ||
5288 Input->getType() == types::TY_PP_CXXStdModule)
5289 return C.MakeAction<PrecompileJobAction>(
5290 Arg&: Input, Arg: getPrecompiledType(Id: Input->getType()));
5291
5292 // With 'fmodules-reduced-bmi', we don't want to run the
5293 // precompile phase unless the user specified '--precompile' or
5294 // '--precompile-reduced-bmi'. If '--precompile' is specified, we will try
5295 // to emit the reduced BMI as a by product in
5296 // GenerateModuleInterfaceAction. If '--precompile-reduced-bmi' is
5297 // specified, we will generate the reduced BMI directly.
5298 if (!Args.hasArg(Ids: options::OPT_fno_modules_reduced_bmi) &&
5299 (Input->getType() == driver::types::TY_CXXModule ||
5300 Input->getType() == driver::types::TY_PP_CXXModule) &&
5301 !Args.getLastArg(Ids: options::OPT__precompile) &&
5302 !Args.getLastArg(Ids: options::OPT__precompile_reduced_bmi))
5303 return Input;
5304
5305 types::ID OutputTy = getPrecompiledType(Id: Input->getType());
5306 assert(OutputTy != types::TY_INVALID &&
5307 "Cannot precompile this input type!");
5308
5309 // If we're given a module name, precompile header file inputs as a
5310 // module, not as a precompiled header.
5311 const char *ModName = nullptr;
5312 if (OutputTy == types::TY_PCH) {
5313 if (Arg *A = Args.getLastArg(Ids: options::OPT_fmodule_name_EQ))
5314 ModName = A->getValue();
5315 if (ModName)
5316 OutputTy = types::TY_ModuleFile;
5317 }
5318
5319 if (Args.hasArg(Ids: options::OPT_fsyntax_only)) {
5320 // Syntax checks should not emit a PCH file
5321 OutputTy = types::TY_Nothing;
5322 }
5323
5324 return C.MakeAction<PrecompileJobAction>(Arg&: Input, Arg&: OutputTy);
5325 }
5326 case phases::Compile: {
5327 if (Args.hasArg(Ids: options::OPT_fsyntax_only))
5328 return C.MakeAction<CompileJobAction>(Arg&: Input, Arg: types::TY_Nothing);
5329 if (Args.hasArg(Ids: options::OPT_rewrite_objc))
5330 return C.MakeAction<CompileJobAction>(Arg&: Input, Arg: types::TY_RewrittenObjC);
5331 if (Args.hasArg(Ids: options::OPT_rewrite_legacy_objc))
5332 return C.MakeAction<CompileJobAction>(Arg&: Input,
5333 Arg: types::TY_RewrittenLegacyObjC);
5334 if (Args.hasArg(Ids: options::OPT__analyze))
5335 return C.MakeAction<AnalyzeJobAction>(Arg&: Input, Arg: types::TY_Plist);
5336 if (Args.hasArg(Ids: options::OPT_emit_ast))
5337 return C.MakeAction<CompileJobAction>(Arg&: Input, Arg: types::TY_AST);
5338 if (Args.hasArg(Ids: options::OPT_emit_cir))
5339 return C.MakeAction<CompileJobAction>(Arg&: Input, Arg: types::TY_CIR);
5340 if (Args.hasArg(Ids: options::OPT_module_file_info))
5341 return C.MakeAction<CompileJobAction>(Arg&: Input, Arg: types::TY_ModuleFile);
5342 if (Args.hasArg(Ids: options::OPT_verify_pch))
5343 return C.MakeAction<VerifyPCHJobAction>(Arg&: Input, Arg: types::TY_Nothing);
5344 if (Args.hasArg(Ids: options::OPT_extract_api))
5345 return C.MakeAction<ExtractAPIJobAction>(Arg&: Input, Arg: types::TY_API_INFO);
5346 return C.MakeAction<CompileJobAction>(Arg&: Input, Arg: types::TY_LLVM_BC);
5347 }
5348 case phases::Backend: {
5349 if (TargetLTOMode != LTOK_None) {
5350 bool IsDeviceOffload = TargetDeviceOffloadKind != Action::OFK_None;
5351 if (!IsDeviceOffload) {
5352 types::ID Output;
5353 if (Args.hasArg(Ids: options::OPT_ffat_lto_objects) &&
5354 !Args.hasArg(Ids: options::OPT_emit_llvm))
5355 Output = types::TY_PP_Asm;
5356 else if (Args.hasArg(Ids: options::OPT_S))
5357 Output = types::TY_LTO_IR;
5358 else
5359 Output = types::TY_LTO_BC;
5360 return C.MakeAction<BackendJobAction>(Arg&: Input, Arg&: Output);
5361 }
5362 types::ID Output;
5363 if (Args.hasArg(Ids: options::OPT_emit_llvm)) {
5364 Output =
5365 Args.hasArg(Ids: options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
5366 } else if (Args.hasArg(Ids: options::OPT_S) && offloadDeviceOnly() &&
5367 !Args.hasFlag(Pos: options::OPT_fgpu_rdc, Neg: options::OPT_fno_gpu_rdc,
5368 Default: false)) {
5369 // For non-RDC device-only compilations with -S, produce real assembly
5370 // since the user explicitly requested assembly output.
5371 Output = types::TY_PP_Asm;
5372 } else if (Args.hasArg(Ids: options::OPT_S)) {
5373 Output = types::TY_LTO_IR;
5374 } else {
5375 Output = types::TY_LTO_BC;
5376 }
5377 return C.MakeAction<BackendJobAction>(Arg&: Input, Arg&: Output);
5378 }
5379 if (Args.hasArg(Ids: options::OPT_emit_llvm) ||
5380 TargetDeviceOffloadKind == Action::OFK_SYCL) {
5381 types::ID Output =
5382 Args.hasArg(Ids: options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
5383 return C.MakeAction<BackendJobAction>(Arg&: Input, Arg&: Output);
5384 }
5385
5386 return C.MakeAction<BackendJobAction>(Arg&: Input, Arg: types::TY_PP_Asm);
5387 }
5388 case phases::Assemble:
5389 // When -marm64x is used, construct jobs for the EC and native targets and
5390 // merge them into an archive with llvm-objcopy.
5391 const llvm::Triple Target(llvm::Triple::normalize(Str: TargetTriple));
5392 if (Target.isOSWindows() && Args.hasArg(Ids: options::OPT_marm64x)) {
5393 Action *Act =
5394 C.MakeAction<AssembleJobAction>(Arg: std::move(Input), Arg: types::TY_Object);
5395 ActionList Inputs;
5396 Inputs.push_back(Elt: C.MakeAction<BindArchAction>(Arg&: Act, Arg: BoundArch("aarch64")));
5397 Inputs.push_back(Elt: C.MakeAction<BindArchAction>(Arg&: Act, Arg: BoundArch("arm64ec")));
5398 return C.MakeAction<ObjcopyJobAction>(Arg&: Inputs, Arg: types::TY_Object);
5399 }
5400 return C.MakeAction<AssembleJobAction>(Arg: std::move(Input), Arg: types::TY_Object);
5401 }
5402
5403 llvm_unreachable("invalid phase in ConstructPhaseAction");
5404}
5405
5406static bool isOffloadDeviceCC1JobCandidate(Command &Job) {
5407 const Action &Source = Job.getSource();
5408 if (!isa<CompileJobAction>(Val: Source) && !isa<BackendJobAction>(Val: Source))
5409 return false;
5410
5411 if (Job.getBoundArch().empty() && !Source.getOffloadingArch().empty())
5412 Job.setBoundArch(Source.getOffloadingArch());
5413
5414 if (Job.getBoundArch().empty())
5415 return false;
5416
5417 if (StringRef(Job.getCreator().getName()) != "clang")
5418 return false;
5419
5420 Action::OffloadKind OKind = Source.getOffloadingDeviceKind();
5421 if (OKind != Action::OFK_None && OKind != Action::OFK_Host)
5422 return true;
5423
5424 const llvm::Triple &Triple = Job.getCreator().getToolChain().getTriple();
5425 return Triple.isAMDGPU() || Triple.isNVPTX() || Triple.isSPIROrSPIRV();
5426}
5427
5428static std::string getOffloadDeviceCC1ParallelJobGroup(const Command &Job) {
5429 const Action &Source = Job.getSource();
5430 // This key groups device cc1 jobs that can run in parallel. Jobs may differ
5431 // by offload arch, but must have the same offload kind, target triple,
5432 // action kind, and output type. For example, HIP compile jobs for gfx900 and
5433 // gfx906 can share a group, but HIP and OpenMP jobs cannot.
5434 return (Twine(Action::GetOffloadKindName(Kind: Source.getOffloadingDeviceKind())) +
5435 ":" + Job.getCreator().getToolChain().getTripleString() + ":" +
5436 Source.getClassName() + ":" + types::getTypeName(Id: Source.getType()))
5437 .str();
5438}
5439
5440static void claimAndDiagnoseOffloadJobs(const Driver &D, const ArgList &Args) {
5441 auto OffloadJobs = tools::parseOffloadJobs(Args);
5442 if (!OffloadJobs.A)
5443 return;
5444
5445 if (!OffloadJobs.isValid())
5446 D.Diag(DiagID: diag::err_drv_invalid_int_value)
5447 << OffloadJobs.A->getAsString(Args) << OffloadJobs.Value;
5448
5449 OffloadJobs.A->claim();
5450}
5451
5452static void markOffloadDeviceCC1JobsForParallelExecution(Compilation &C) {
5453 bool FoundCandidate = false;
5454 for (auto &Job : C.getJobs()) {
5455 if (!isOffloadDeviceCC1JobCandidate(Job))
5456 continue;
5457
5458 Job.setOffloadDeviceParallelJobGroup(
5459 getOffloadDeviceCC1ParallelJobGroup(Job));
5460 FoundCandidate = true;
5461 }
5462
5463 if (FoundCandidate)
5464 claimAndDiagnoseOffloadJobs(D: C.getDriver(), Args: C.getArgs());
5465}
5466
5467void Driver::BuildJobs(Compilation &C) const {
5468 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
5469
5470 Arg *FinalOutput = C.getArgs().getLastArg(Ids: options::OPT_o);
5471
5472 // It is an error to provide a -o option if we are making multiple output
5473 // files. There are exceptions:
5474 //
5475 // IfsMergeJob: when generating interface stubs enabled we want to be able to
5476 // generate the stub file at the same time that we generate the real
5477 // library/a.out. So when a .o, .so, etc are the output, with clang interface
5478 // stubs there will also be a .ifs and .ifso at the same location.
5479 //
5480 // CompileJob of type TY_IFS_CPP: when generating interface stubs is enabled
5481 // and -c is passed, we still want to be able to generate a .ifs file while
5482 // we are also generating .o files. So we allow more than one output file in
5483 // this case as well.
5484 //
5485 // OffloadClass of type TY_Nothing: device-only output will place many outputs
5486 // into a single offloading action. We should count all inputs to the action
5487 // as outputs. Also ignore device-only outputs if we're compiling with
5488 // -fsyntax-only.
5489 if (FinalOutput) {
5490 unsigned NumOutputs = 0;
5491 unsigned NumIfsOutputs = 0;
5492 for (const Action *A : C.getActions()) {
5493 // The actions below do not increase the number of outputs.
5494 if (A->getKind() == clang::driver::Action::BinaryAnalyzeJobClass ||
5495 A->getKind() == clang::driver::Action::BinaryTranslatorJobClass)
5496 continue;
5497
5498 // With -fmodules-driver, Standard library modules should not count toward
5499 // the number of outputs, since they are implicitly added to the input
5500 // list.
5501 if (isa<PrecompileJobAction>(Val: A) && !A->getInputs().empty() &&
5502 (A->getInputs().front()->getType() == types::TY_CXXStdModule ||
5503 A->getInputs().front()->getType() == types::TY_PP_CXXStdModule))
5504 continue;
5505
5506 if (A->getType() != types::TY_Nothing &&
5507 !(A->getKind() == Action::IfsMergeJobClass ||
5508 (A->getType() == clang::driver::types::TY_IFS_CPP &&
5509 A->getKind() == clang::driver::Action::CompileJobClass &&
5510 0 == NumIfsOutputs++) ||
5511 (A->getKind() == Action::BindArchClass && A->getInputs().size() &&
5512 A->getInputs().front()->getKind() == Action::IfsMergeJobClass)))
5513 ++NumOutputs;
5514 else if (A->getKind() == Action::OffloadClass &&
5515 A->getType() == types::TY_Nothing &&
5516 !C.getArgs().hasArg(Ids: options::OPT_fsyntax_only))
5517 NumOutputs += A->size();
5518 }
5519
5520 if (NumOutputs > 1) {
5521 Diag(DiagID: clang::diag::err_drv_output_argument_with_multiple_files);
5522 FinalOutput = nullptr;
5523 }
5524 }
5525
5526 const llvm::Triple &RawTriple = C.getDefaultToolChain().getTriple();
5527
5528 // Collect the list of architectures.
5529 llvm::StringSet<> ArchNames;
5530 if (RawTriple.isOSBinFormatMachO())
5531 for (const Arg *A : C.getArgs())
5532 if (A->getOption().matches(ID: options::OPT_arch))
5533 ArchNames.insert(key: A->getValue());
5534
5535 // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
5536 std::map<std::pair<const Action *, std::string>, InputInfoList> CachedResults;
5537 for (Action *A : C.getActions()) {
5538 // If we are linking an image for multiple archs then the linker wants
5539 // -arch_multiple and -final_output <final image name>. Unfortunately, this
5540 // doesn't fit in cleanly because we have to pass this information down.
5541 //
5542 // FIXME: This is a hack; find a cleaner way to integrate this into the
5543 // process.
5544 const char *LinkingOutput = nullptr;
5545 if (isa<LipoJobAction>(Val: A)) {
5546 if (FinalOutput)
5547 LinkingOutput = FinalOutput->getValue();
5548 else
5549 LinkingOutput = getDefaultImageName();
5550 }
5551
5552 BuildJobsForAction(C, A, TC: &C.getDefaultToolChain(),
5553 /*BA=*/{},
5554 /*AtTopLevel*/ true,
5555 /*MultipleArchs*/ ArchNames.size() > 1 ||
5556 C.getArgs().hasArgNoClaim(Ids: options::OPT_marm64x),
5557 /*LinkingOutput*/ LinkingOutput, CachedResults,
5558 /*TargetDeviceOffloadKind*/ Action::OFK_None);
5559 }
5560
5561 // If we have more than one job, then disable integrated-cc1 for now. Do this
5562 // also when we need to report process execution statistics.
5563 if (C.getJobs().size() > 1 || CCPrintProcessStats)
5564 for (auto &J : C.getJobs())
5565 J.InProcess = false;
5566
5567 markOffloadDeviceCC1JobsForParallelExecution(C);
5568
5569 if (CCPrintProcessStats) {
5570 C.setPostCallback([=](const Command &Cmd, int Res) {
5571 std::optional<llvm::sys::ProcessStatistics> ProcStat =
5572 Cmd.getProcessStatistics();
5573 if (!ProcStat)
5574 return;
5575
5576 const char *LinkingOutput = nullptr;
5577 if (FinalOutput)
5578 LinkingOutput = FinalOutput->getValue();
5579 else if (!Cmd.getOutputFilenames().empty())
5580 LinkingOutput = Cmd.getOutputFilenames().front().c_str();
5581 else
5582 LinkingOutput = getDefaultImageName();
5583
5584 if (CCPrintStatReportFilename.empty()) {
5585 using namespace llvm;
5586 // Human readable output.
5587 outs() << sys::path::filename(path: Cmd.getExecutable()) << ": "
5588 << "output=" << LinkingOutput;
5589 outs() << ", total="
5590 << format(Fmt: "%.3f", Vals: ProcStat->TotalTime.count() / 1000.) << " ms"
5591 << ", user="
5592 << format(Fmt: "%.3f", Vals: ProcStat->UserTime.count() / 1000.) << " ms"
5593 << ", mem=" << ProcStat->PeakMemory << " Kb\n";
5594 } else {
5595 // CSV format.
5596 std::string Buffer;
5597 llvm::raw_string_ostream Out(Buffer);
5598 llvm::sys::printArg(OS&: Out, Arg: llvm::sys::path::filename(path: Cmd.getExecutable()),
5599 /*Quote*/ true);
5600 Out << ',';
5601 llvm::sys::printArg(OS&: Out, Arg: LinkingOutput, Quote: true);
5602 Out << ',' << ProcStat->TotalTime.count() << ','
5603 << ProcStat->UserTime.count() << ',' << ProcStat->PeakMemory
5604 << '\n';
5605 Out.flush();
5606 std::error_code EC;
5607 llvm::raw_fd_ostream OS(CCPrintStatReportFilename, EC,
5608 llvm::sys::fs::OF_Append |
5609 llvm::sys::fs::OF_Text);
5610 if (EC)
5611 return;
5612 auto L = OS.lock();
5613 if (!L) {
5614 llvm::errs() << "ERROR: Cannot lock file "
5615 << CCPrintStatReportFilename << ": "
5616 << toString(E: L.takeError()) << "\n";
5617 return;
5618 }
5619 OS << Buffer;
5620 OS.flush();
5621 }
5622 });
5623 }
5624
5625 // If the user passed -Qunused-arguments or there were errors, don't
5626 // warn about any unused arguments.
5627 bool ReportUnusedArguments =
5628 !Diags.hasErrorOccurred() &&
5629 !C.getArgs().hasArg(Ids: options::OPT_Qunused_arguments);
5630
5631 // Claim -fdriver-only here.
5632 (void)C.getArgs().hasArg(Ids: options::OPT_fdriver_only);
5633 // Claim -### here.
5634 (void)C.getArgs().hasArg(Ids: options::OPT__HASH_HASH_HASH);
5635
5636 // Claim --driver-mode, --rsp-quoting, it was handled earlier.
5637 (void)C.getArgs().hasArg(Ids: options::OPT_driver_mode);
5638 (void)C.getArgs().hasArg(Ids: options::OPT_rsp_quoting);
5639
5640 bool HasAssembleJob = llvm::any_of(Range&: C.getJobs(), P: [](auto &J) {
5641 // Match ClangAs and other derived assemblers of Tool. ClangAs uses a
5642 // longer ShortName "clang integrated assembler" while other assemblers just
5643 // use "assembler".
5644 return strstr(J.getCreator().getShortName(), "assembler");
5645 });
5646 for (Arg *A : C.getArgs()) {
5647 // FIXME: It would be nice to be able to send the argument to the
5648 // DiagnosticsEngine, so that extra values, position, and so on could be
5649 // printed.
5650 if (!A->isClaimed()) {
5651 if (A->getOption().hasFlag(Val: options::NoArgumentUnused))
5652 continue;
5653
5654 // Suppress the warning automatically if this is just a flag, and it is an
5655 // instance of an argument we already claimed.
5656 const Option &Opt = A->getOption();
5657 if (Opt.getKind() == Option::FlagClass) {
5658 bool DuplicateClaimed = false;
5659
5660 for (const Arg *AA : C.getArgs().filtered(Ids: &Opt)) {
5661 if (AA->isClaimed()) {
5662 DuplicateClaimed = true;
5663 break;
5664 }
5665 }
5666
5667 if (DuplicateClaimed)
5668 continue;
5669 }
5670
5671 // In clang-cl, don't mention unknown arguments here since they have
5672 // already been warned about.
5673 if (!IsCLMode() || !A->getOption().matches(ID: options::OPT_UNKNOWN)) {
5674 if (A->getOption().hasFlag(Val: options::TargetSpecific) &&
5675 !A->isIgnoredTargetSpecific() && !HasAssembleJob &&
5676 // When for example -### or -v is used
5677 // without a file, target specific options are not
5678 // consumed/validated.
5679 // Instead emitting an error emit a warning instead.
5680 !C.getActions().empty()) {
5681 Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5682 << A->getSpelling() << getTargetTriple();
5683 } else if (ReportUnusedArguments) {
5684 Diag(DiagID: clang::diag::warn_drv_unused_argument)
5685 << A->getAsString(Args: C.getArgs());
5686 }
5687 }
5688 }
5689 }
5690}
5691
5692namespace {
5693/// Utility class to control the collapse of dependent actions and select the
5694/// tools accordingly.
5695class ToolSelector final {
5696 /// The tool chain this selector refers to.
5697 const ToolChain &TC;
5698
5699 /// The compilation this selector refers to.
5700 const Compilation &C;
5701
5702 /// The base action this selector refers to.
5703 const JobAction *BaseAction;
5704
5705 /// Set to true if the current toolchain refers to host actions.
5706 bool IsHostSelector;
5707
5708 /// Set to true if save-temps and embed-bitcode functionalities are active.
5709 bool SaveTemps;
5710 bool EmbedBitcode;
5711
5712 /// Get previous dependent action or null if that does not exist. If
5713 /// \a CanBeCollapsed is false, that action must be legal to collapse or
5714 /// null will be returned.
5715 const JobAction *getPrevDependentAction(const ActionList &Inputs,
5716 ActionList &SavedOffloadAction,
5717 bool CanBeCollapsed = true) {
5718 // An option can be collapsed only if it has a single input.
5719 if (Inputs.size() != 1)
5720 return nullptr;
5721
5722 Action *CurAction = *Inputs.begin();
5723 if (CanBeCollapsed &&
5724 !CurAction->isCollapsingWithNextDependentActionLegal())
5725 return nullptr;
5726
5727 // If the input action is an offload action. Look through it and save any
5728 // offload action that can be dropped in the event of a collapse.
5729 if (auto *OA = dyn_cast<OffloadAction>(Val: CurAction)) {
5730 // If the dependent action is a device action, we will attempt to collapse
5731 // only with other device actions. Otherwise, we would do the same but
5732 // with host actions only.
5733 if (!IsHostSelector) {
5734 if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) {
5735 CurAction =
5736 OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
5737 if (CanBeCollapsed &&
5738 !CurAction->isCollapsingWithNextDependentActionLegal())
5739 return nullptr;
5740 SavedOffloadAction.push_back(Elt: OA);
5741 return dyn_cast<JobAction>(Val: CurAction);
5742 }
5743 } else if (OA->hasHostDependence()) {
5744 CurAction = OA->getHostDependence();
5745 if (CanBeCollapsed &&
5746 !CurAction->isCollapsingWithNextDependentActionLegal())
5747 return nullptr;
5748 SavedOffloadAction.push_back(Elt: OA);
5749 return dyn_cast<JobAction>(Val: CurAction);
5750 }
5751 return nullptr;
5752 }
5753
5754 return dyn_cast<JobAction>(Val: CurAction);
5755 }
5756
5757 /// Return true if an assemble action can be collapsed.
5758 bool canCollapseAssembleAction() const {
5759 return TC.useIntegratedAs() && !SaveTemps &&
5760 !C.getArgs().hasArg(Ids: options::OPT_via_file_asm) &&
5761 !C.getArgs().hasArg(Ids: options::OPT__SLASH_FA) &&
5762 !C.getArgs().hasArg(Ids: options::OPT__SLASH_Fa) &&
5763 !C.getArgs().hasArg(Ids: options::OPT_dxc_Fc);
5764 }
5765
5766 /// Return true if a preprocessor action can be collapsed.
5767 bool canCollapsePreprocessorAction() const {
5768 return !C.getArgs().hasArg(Ids: options::OPT_no_integrated_cpp) &&
5769 !C.getArgs().hasArg(Ids: options::OPT_traditional_cpp) && !SaveTemps &&
5770 !C.getArgs().hasArg(Ids: options::OPT_rewrite_objc);
5771 }
5772
5773 /// Struct that relates an action with the offload actions that would be
5774 /// collapsed with it.
5775 struct JobActionInfo final {
5776 /// The action this info refers to.
5777 const JobAction *JA = nullptr;
5778 /// The offload actions we need to take care off if this action is
5779 /// collapsed.
5780 ActionList SavedOffloadAction;
5781 };
5782
5783 /// Append collapsed offload actions from the give number of elements in the
5784 /// action info array.
5785 static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction,
5786 ArrayRef<JobActionInfo> &ActionInfo,
5787 unsigned ElementNum) {
5788 assert(ElementNum <= ActionInfo.size() && "Invalid number of elements.");
5789 for (unsigned I = 0; I < ElementNum; ++I)
5790 CollapsedOffloadAction.append(in_start: ActionInfo[I].SavedOffloadAction.begin(),
5791 in_end: ActionInfo[I].SavedOffloadAction.end());
5792 }
5793
5794 /// Functions that attempt to perform the combining. They detect if that is
5795 /// legal, and if so they update the inputs \a Inputs and the offload action
5796 /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with
5797 /// the combined action is returned. If the combining is not legal or if the
5798 /// tool does not exist, null is returned.
5799 /// Currently three kinds of collapsing are supported:
5800 /// - Assemble + Backend + Compile;
5801 /// - Assemble + Backend ;
5802 /// - Backend + Compile.
5803 const Tool *
5804 combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
5805 ActionList &Inputs,
5806 ActionList &CollapsedOffloadAction) {
5807 if (ActionInfo.size() < 3 || !canCollapseAssembleAction())
5808 return nullptr;
5809 auto *AJ = dyn_cast<AssembleJobAction>(Val: ActionInfo[0].JA);
5810 auto *BJ = dyn_cast<BackendJobAction>(Val: ActionInfo[1].JA);
5811 auto *CJ = dyn_cast<CompileJobAction>(Val: ActionInfo[2].JA);
5812 if (!AJ || !BJ || !CJ)
5813 return nullptr;
5814
5815 // Get compiler tool.
5816 const Tool *T = TC.SelectTool(JA: *CJ);
5817 if (!T)
5818 return nullptr;
5819
5820 // Can't collapse if we don't have codegen support unless we are
5821 // emitting LLVM IR.
5822 bool OutputIsLLVM = types::isLLVMIR(Id: ActionInfo[0].JA->getType());
5823 if (!T->hasIntegratedBackend() && !(OutputIsLLVM && T->canEmitIR()))
5824 return nullptr;
5825
5826 // When using -fembed-bitcode, it is required to have the same tool (clang)
5827 // for both CompilerJA and BackendJA. Otherwise, combine two stages.
5828 if (EmbedBitcode) {
5829 const Tool *BT = TC.SelectTool(JA: *BJ);
5830 if (BT == T)
5831 return nullptr;
5832 }
5833
5834 if (!T->hasIntegratedAssembler())
5835 return nullptr;
5836
5837 Inputs = CJ->getInputs();
5838 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
5839 /*NumElements=*/ElementNum: 3);
5840 return T;
5841 }
5842 const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo,
5843 ActionList &Inputs,
5844 ActionList &CollapsedOffloadAction) {
5845 if (ActionInfo.size() < 2 || !canCollapseAssembleAction())
5846 return nullptr;
5847 auto *AJ = dyn_cast<AssembleJobAction>(Val: ActionInfo[0].JA);
5848 auto *BJ = dyn_cast<BackendJobAction>(Val: ActionInfo[1].JA);
5849 if (!AJ || !BJ)
5850 return nullptr;
5851
5852 // Get backend tool.
5853 const Tool *T = TC.SelectTool(JA: *BJ);
5854 if (!T)
5855 return nullptr;
5856
5857 if (!T->hasIntegratedAssembler())
5858 return nullptr;
5859
5860 Inputs = BJ->getInputs();
5861 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
5862 /*NumElements=*/ElementNum: 2);
5863 return T;
5864 }
5865 const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
5866 ActionList &Inputs,
5867 ActionList &CollapsedOffloadAction) {
5868 if (ActionInfo.size() < 2)
5869 return nullptr;
5870 auto *BJ = dyn_cast<BackendJobAction>(Val: ActionInfo[0].JA);
5871 auto *CJ = dyn_cast<CompileJobAction>(Val: ActionInfo[1].JA);
5872 if (!BJ || !CJ)
5873 return nullptr;
5874
5875 auto HasBitcodeInput = [](const JobActionInfo &AI) {
5876 for (auto &Input : AI.JA->getInputs())
5877 if (!types::isLLVMIR(Id: Input->getType()))
5878 return false;
5879 return true;
5880 };
5881
5882 // Check if the initial input (to the compile job or its predessor if one
5883 // exists) is LLVM bitcode. In that case, no preprocessor step is required
5884 // and we can still collapse the compile and backend jobs when we have
5885 // -save-temps. I.e. there is no need for a separate compile job just to
5886 // emit unoptimized bitcode.
5887 bool InputIsBitcode = all_of(Range&: ActionInfo, P: HasBitcodeInput);
5888 if (SaveTemps && !InputIsBitcode)
5889 return nullptr;
5890
5891 // Get compiler tool.
5892 const Tool *T = TC.SelectTool(JA: *CJ);
5893 if (!T)
5894 return nullptr;
5895
5896 // Can't collapse if we don't have codegen support unless we are
5897 // emitting LLVM IR.
5898 bool OutputIsLLVM = types::isLLVMIR(Id: ActionInfo[0].JA->getType());
5899 if (!T->hasIntegratedBackend() && !(OutputIsLLVM && T->canEmitIR()))
5900 return nullptr;
5901
5902 if (T->canEmitIR() && EmbedBitcode)
5903 return nullptr;
5904
5905 Inputs = CJ->getInputs();
5906 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
5907 /*NumElements=*/ElementNum: 2);
5908 return T;
5909 }
5910
5911 /// Updates the inputs if the obtained tool supports combining with
5912 /// preprocessor action, and the current input is indeed a preprocessor
5913 /// action. If combining results in the collapse of offloading actions, those
5914 /// are appended to \a CollapsedOffloadAction.
5915 void combineWithPreprocessor(const Tool *T, ActionList &Inputs,
5916 ActionList &CollapsedOffloadAction) {
5917 if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP())
5918 return;
5919
5920 // Attempt to get a preprocessor action dependence.
5921 ActionList PreprocessJobOffloadActions;
5922 ActionList NewInputs;
5923 for (Action *A : Inputs) {
5924 auto *PJ = getPrevDependentAction(Inputs: {A}, SavedOffloadAction&: PreprocessJobOffloadActions);
5925 if (!PJ || !isa<PreprocessJobAction>(Val: PJ)) {
5926 NewInputs.push_back(Elt: A);
5927 continue;
5928 }
5929
5930 // This is legal to combine. Append any offload action we found and add the
5931 // current input to preprocessor inputs.
5932 CollapsedOffloadAction.append(in_start: PreprocessJobOffloadActions.begin(),
5933 in_end: PreprocessJobOffloadActions.end());
5934 NewInputs.append(in_start: PJ->input_begin(), in_end: PJ->input_end());
5935 }
5936 Inputs = NewInputs;
5937 }
5938
5939public:
5940 ToolSelector(const JobAction *BaseAction, const ToolChain &TC,
5941 const Compilation &C, bool SaveTemps, bool EmbedBitcode)
5942 : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps),
5943 EmbedBitcode(EmbedBitcode) {
5944 assert(BaseAction && "Invalid base action.");
5945 IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None;
5946 }
5947
5948 /// Check if a chain of actions can be combined and return the tool that can
5949 /// handle the combination of actions. The pointer to the current inputs \a
5950 /// Inputs and the list of offload actions \a CollapsedOffloadActions
5951 /// connected to collapsed actions are updated accordingly. The latter enables
5952 /// the caller of the selector to process them afterwards instead of just
5953 /// dropping them. If no suitable tool is found, null will be returned.
5954 const Tool *getTool(ActionList &Inputs,
5955 ActionList &CollapsedOffloadAction) {
5956 //
5957 // Get the largest chain of actions that we could combine.
5958 //
5959
5960 SmallVector<JobActionInfo, 5> ActionChain(1);
5961 ActionChain.back().JA = BaseAction;
5962 while (ActionChain.back().JA) {
5963 const Action *CurAction = ActionChain.back().JA;
5964
5965 // Grow the chain by one element.
5966 ActionChain.resize(N: ActionChain.size() + 1);
5967 JobActionInfo &AI = ActionChain.back();
5968
5969 // Attempt to fill it with the
5970 AI.JA =
5971 getPrevDependentAction(Inputs: CurAction->getInputs(), SavedOffloadAction&: AI.SavedOffloadAction);
5972 }
5973
5974 // Pop the last action info as it could not be filled.
5975 ActionChain.pop_back();
5976
5977 //
5978 // Attempt to combine actions. If all combining attempts failed, just return
5979 // the tool of the provided action. At the end we attempt to combine the
5980 // action with any preprocessor action it may depend on.
5981 //
5982
5983 const Tool *T = combineAssembleBackendCompile(ActionInfo: ActionChain, Inputs,
5984 CollapsedOffloadAction);
5985 if (!T)
5986 T = combineAssembleBackend(ActionInfo: ActionChain, Inputs, CollapsedOffloadAction);
5987 if (!T)
5988 T = combineBackendCompile(ActionInfo: ActionChain, Inputs, CollapsedOffloadAction);
5989 if (!T) {
5990 Inputs = BaseAction->getInputs();
5991 T = TC.SelectTool(JA: *BaseAction);
5992 }
5993
5994 combineWithPreprocessor(T, Inputs, CollapsedOffloadAction);
5995 return T;
5996 }
5997};
5998}
5999
6000/// Return a string that uniquely identifies the result of a job. The bound arch
6001/// is not necessarily represented in the toolchain's triple -- for example,
6002/// armv7 and armv7s both map to the same triple -- so we need both in our map.
6003/// Also, we need to add the offloading device kind, as the same tool chain can
6004/// be used for host and device for some programming models, e.g. OpenMP.
6005static std::string GetTriplePlusArchString(const ToolChain *TC, BoundArch BA,
6006 Action::OffloadKind OffloadKind) {
6007 std::string TriplePlusArch = TC->getTriple().normalize();
6008 if (!BA.empty()) {
6009 TriplePlusArch += "-";
6010 TriplePlusArch += BA.ArchName;
6011 }
6012 TriplePlusArch += "-";
6013 TriplePlusArch += Action::GetOffloadKindName(Kind: OffloadKind);
6014 return TriplePlusArch;
6015}
6016
6017InputInfoList Driver::BuildJobsForAction(
6018 Compilation &C, const Action *A, const ToolChain *TC, BoundArch BA,
6019 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
6020 std::map<std::pair<const Action *, std::string>, InputInfoList>
6021 &CachedResults,
6022 Action::OffloadKind TargetDeviceOffloadKind) const {
6023 std::pair<const Action *, std::string> ActionTC = {
6024 A, GetTriplePlusArchString(TC, BA, OffloadKind: TargetDeviceOffloadKind)};
6025 auto CachedResult = CachedResults.find(x: ActionTC);
6026 if (CachedResult != CachedResults.end()) {
6027 return CachedResult->second;
6028 }
6029 InputInfoList Result = BuildJobsForActionNoCache(
6030 C, A, TC, BA, AtTopLevel, MultipleArchs, LinkingOutput, CachedResults,
6031 TargetDeviceOffloadKind);
6032 CachedResults[ActionTC] = Result;
6033 return Result;
6034}
6035
6036static void handleTimeTrace(Compilation &C, const ArgList &Args,
6037 const JobAction *JA, const char *BaseInput,
6038 const InputInfo &Result) {
6039 Arg *A =
6040 Args.getLastArg(Ids: options::OPT_ftime_trace, Ids: options::OPT_ftime_trace_EQ);
6041 if (!A)
6042 return;
6043
6044 SmallString<64> OffloadingPrefix;
6045 if (JA->getOffloadingDeviceKind() != Action::OFK_None) {
6046 const ToolChain *TC = JA->getOffloadingToolChain();
6047 OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
6048 Kind: JA->getOffloadingDeviceKind(), NormalizedTriple: TC ? TC->getEffectiveTriple().str() : "",
6049 /*CreatePrefixForHost=*/false);
6050 BoundArch Arch = JA->getOffloadingArch();
6051 if (!Arch.empty()) {
6052 OffloadingPrefix += "-";
6053 OffloadingPrefix += Arch.ArchName;
6054 }
6055 } else if (JA->getOffloadingHostActiveKinds() != Action::OFK_None &&
6056 C.getDriver().isSaveTempsEnabled()) {
6057 OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
6058 Kind: Action::OFK_None, NormalizedTriple: C.getDefaultToolChain().getTripleString(),
6059 /*CreatePrefixForHost=*/true);
6060 }
6061
6062 SmallString<128> Path;
6063 if (A->getOption().matches(ID: options::OPT_ftime_trace_EQ)) {
6064 Path = A->getValue();
6065 if (llvm::sys::fs::is_directory(Path)) {
6066 SmallString<128> Tmp(OffloadingPrefix.empty()
6067 ? llvm::sys::path::stem(path: Result.getFilename())
6068 : llvm::sys::path::stem(path: BaseInput));
6069 Tmp += OffloadingPrefix;
6070 Tmp += ".json";
6071 llvm::sys::path::append(path&: Path, a: Tmp);
6072 }
6073 } else {
6074 if (Arg *DumpDir = Args.getLastArgNoClaim(Ids: options::OPT_dumpdir)) {
6075 // The trace file is ${dumpdir}${basename}${offloadprefix}.json. Note
6076 // that dumpdir may not end with a path separator.
6077 Path = DumpDir->getValue();
6078 Path += llvm::sys::path::stem(path: BaseInput);
6079 Path += OffloadingPrefix;
6080 Path += ".json";
6081 } else if (!OffloadingPrefix.empty()) {
6082 // For offloading, derive path from -o output directory combined with
6083 // the input filename and offload prefix.
6084 SmallString<128> TraceName(llvm::sys::path::stem(path: BaseInput));
6085 TraceName += OffloadingPrefix;
6086 if (Arg *FinalOutput = Args.getLastArg(Ids: options::OPT_o))
6087 Path = llvm::sys::path::parent_path(path: FinalOutput->getValue());
6088 llvm::sys::path::append(path&: Path, a: TraceName);
6089 Path += ".json";
6090 } else {
6091 Path = Result.getFilename();
6092 llvm::sys::path::replace_extension(path&: Path, extension: "json");
6093 }
6094 }
6095 const char *ResultFile = C.getArgs().MakeArgString(Str: Path);
6096 C.addTimeTraceFile(Name: ResultFile, JA);
6097 C.addResultFile(Name: ResultFile, JA);
6098}
6099
6100InputInfoList Driver::BuildJobsForActionNoCache(
6101 Compilation &C, const Action *A, const ToolChain *TC, BoundArch BA,
6102 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
6103 std::map<std::pair<const Action *, std::string>, InputInfoList>
6104 &CachedResults,
6105 Action::OffloadKind TargetDeviceOffloadKind) const {
6106 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
6107
6108 // Track the bound arch for commands constructed in this scope so
6109 // generateCompilationDiagnostics can identify the crashing arch.
6110 BoundArch SavedBoundArch = C.getCurrentBoundArch();
6111 C.setCurrentBoundArch(BA);
6112 auto RestoreBoundArch =
6113 llvm::scope_exit([&] { C.setCurrentBoundArch(SavedBoundArch); });
6114
6115 InputInfoList OffloadDependencesInputInfo;
6116 bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None;
6117 if (const OffloadAction *OA = dyn_cast<OffloadAction>(Val: A)) {
6118 // The 'Darwin' toolchain is initialized only when its arguments are
6119 // computed. Get the default arguments for OFK_None to ensure that
6120 // initialization is performed before processing the offload action.
6121 // FIXME: Remove when darwin's toolchain is initialized during construction.
6122 C.getArgsForToolChain(TC, BA, DeviceOffloadKind: Action::OFK_Host);
6123
6124 // The offload action is expected to be used in four different situations.
6125 //
6126 // a) Set a toolchain/architecture/kind for a host action:
6127 // Host Action 1 -> OffloadAction -> Host Action 2
6128 //
6129 // b) Set a toolchain/architecture/kind for a device action;
6130 // Device Action 1 -> OffloadAction -> Device Action 2
6131 //
6132 // c) Specify a device dependence to a host action;
6133 // Device Action 1 _
6134 // \
6135 // Host Action 1 ---> OffloadAction -> Host Action 2
6136 //
6137 // d) Specify a host dependence to a device action.
6138 // Host Action 1 _
6139 // \
6140 // Device Action 1 ---> OffloadAction -> Device Action 2
6141 //
6142 // For a) and b), we just return the job generated for the dependences. For
6143 // c) and d) we override the current action with the host/device dependence
6144 // if the current toolchain is host/device and set the offload dependences
6145 // info with the jobs obtained from the device/host dependence(s).
6146
6147 // If there is a single device option or has no host action, just generate
6148 // the job for it.
6149 if (OA->hasSingleDeviceDependence() || !OA->hasHostDependence()) {
6150 InputInfoList DevA;
6151 OA->doOnEachDeviceDependence(Work: [&](Action *DepA, const ToolChain *DepTC,
6152 BoundArch DepBoundArch) {
6153 DevA.append(RHS: BuildJobsForAction(C, A: DepA, TC: DepTC, BA: DepBoundArch, AtTopLevel,
6154 /*MultipleArchs=*/!DepBoundArch.empty(),
6155 LinkingOutput, CachedResults,
6156 TargetDeviceOffloadKind: DepA->getOffloadingDeviceKind()));
6157 });
6158 return DevA;
6159 }
6160
6161 // If 'Action 2' is host, we generate jobs for the device dependences and
6162 // override the current action with the host dependence. Otherwise, we
6163 // generate the host dependences and override the action with the device
6164 // dependence. The dependences can't therefore be a top-level action.
6165 OA->doOnEachDependence(
6166 /*IsHostDependence=*/BuildingForOffloadDevice,
6167 Work: [&](Action *DepA, const ToolChain *DepTC, BoundArch DepBoundArch) {
6168 OffloadDependencesInputInfo.append(RHS: BuildJobsForAction(
6169 C, A: DepA, TC: DepTC, BA: DepBoundArch, /*AtTopLevel=*/false,
6170 /*MultipleArchs=*/!DepBoundArch.empty(), LinkingOutput,
6171 CachedResults, TargetDeviceOffloadKind: DepA->getOffloadingDeviceKind()));
6172 });
6173
6174 A = BuildingForOffloadDevice
6175 ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
6176 : OA->getHostDependence();
6177
6178 // We may have already built this action as a part of the offloading
6179 // toolchain, return the cached input if so.
6180 std::pair<const Action *, std::string> ActionTC = {
6181 OA->getHostDependence(),
6182 GetTriplePlusArchString(TC, BA, OffloadKind: TargetDeviceOffloadKind)};
6183 auto It = CachedResults.find(x: ActionTC);
6184 if (It != CachedResults.end()) {
6185 InputInfoList Inputs = It->second;
6186 Inputs.append(RHS: OffloadDependencesInputInfo);
6187 return Inputs;
6188 }
6189 }
6190
6191 if (const InputAction *IA = dyn_cast<InputAction>(Val: A)) {
6192 // FIXME: It would be nice to not claim this here; maybe the old scheme of
6193 // just using Args was better?
6194 const Arg &Input = IA->getInputArg();
6195 Input.claim();
6196 if (Input.getOption().matches(ID: options::OPT_INPUT)) {
6197 const char *Name = Input.getValue();
6198 return {InputInfo(A, Name, /* _BaseInput = */ Name)};
6199 }
6200 return {InputInfo(A, &Input, /* _BaseInput = */ "")};
6201 }
6202
6203 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(Val: A)) {
6204 const ToolChain *TC;
6205 BoundArch ArchName = BAA->getArch();
6206
6207 if (!ArchName.empty())
6208 TC = &getToolChain(Args: C.getArgs(),
6209 Target: computeTargetTriple(D: *this, TargetTriple, Args: C.getArgs(),
6210 ArchName: ArchName.ArchName));
6211 else
6212 TC = &C.getDefaultToolChain();
6213
6214 return BuildJobsForAction(C, A: *BAA->input_begin(), TC, BA: ArchName, AtTopLevel,
6215 MultipleArchs, LinkingOutput, CachedResults,
6216 TargetDeviceOffloadKind);
6217 }
6218
6219
6220 ActionList Inputs = A->getInputs();
6221
6222 const JobAction *JA = cast<JobAction>(Val: A);
6223 ActionList CollapsedOffloadActions;
6224
6225 ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(),
6226 embedBitcodeInObject() && !TC->isUsingLTO(Args: C.getArgs()));
6227 const Tool *T = TS.getTool(Inputs, CollapsedOffloadAction&: CollapsedOffloadActions);
6228
6229 if (!T)
6230 return {InputInfo()};
6231
6232 // If we've collapsed action list that contained OffloadAction we
6233 // need to build jobs for host/device-side inputs it may have held.
6234 for (const auto *OA : CollapsedOffloadActions)
6235 cast<OffloadAction>(Val: OA)->doOnEachDependence(
6236 /*IsHostDependence=*/BuildingForOffloadDevice,
6237 Work: [&](Action *DepA, const ToolChain *DepTC, BoundArch DepBoundArch) {
6238 OffloadDependencesInputInfo.append(RHS: BuildJobsForAction(
6239 C, A: DepA, TC: DepTC, BA: DepBoundArch, /*AtTopLevel=*/false,
6240 /*MultipleArchs=*/!DepBoundArch.empty(), LinkingOutput,
6241 CachedResults, TargetDeviceOffloadKind: DepA->getOffloadingDeviceKind()));
6242 });
6243
6244 // Only use pipes when there is exactly one input.
6245 InputInfoList InputInfos;
6246 for (const Action *Input : Inputs) {
6247 // Treat dsymutil and verify sub-jobs as being at the top-level too, they
6248 // shouldn't get temporary output names.
6249 // FIXME: Clean this up.
6250 bool SubJobAtTopLevel =
6251 AtTopLevel && (isa<DsymutilJobAction>(Val: A) || isa<VerifyJobAction>(Val: A));
6252 InputInfos.append(RHS: BuildJobsForAction(
6253 C, A: Input, TC, BA, AtTopLevel: SubJobAtTopLevel, MultipleArchs, LinkingOutput,
6254 CachedResults, TargetDeviceOffloadKind: A->getOffloadingDeviceKind()));
6255 }
6256
6257 // Always use the first file input as the base input.
6258 const char *BaseInput = InputInfos[0].getBaseInput();
6259 for (auto &Info : InputInfos) {
6260 if (Info.isFilename()) {
6261 BaseInput = Info.getBaseInput();
6262 break;
6263 }
6264 }
6265
6266 // ... except dsymutil actions, which use their actual input as the base
6267 // input.
6268 if (JA->getType() == types::TY_dSYM)
6269 BaseInput = InputInfos[0].getFilename();
6270
6271 // Append outputs of offload device jobs to the input list
6272 if (!OffloadDependencesInputInfo.empty())
6273 InputInfos.append(in_start: OffloadDependencesInputInfo.begin(),
6274 in_end: OffloadDependencesInputInfo.end());
6275
6276 // Set the effective triple of the toolchain for the duration of this job.
6277 llvm::Triple EffectiveTriple;
6278 const ToolChain &ToolTC = T->getToolChain();
6279 const ArgList &Args =
6280 C.getArgsForToolChain(TC, BA, DeviceOffloadKind: A->getOffloadingDeviceKind());
6281 if (InputInfos.size() != 1) {
6282 EffectiveTriple =
6283 llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args, BA));
6284 } else {
6285 // Pass along the input type if it can be unambiguously determined.
6286 EffectiveTriple = llvm::Triple(
6287 ToolTC.ComputeEffectiveClangTriple(Args, BA, InputType: InputInfos[0].getType()));
6288 }
6289 RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple);
6290
6291 // Determine the place to write output to, if any.
6292 InputInfo Result;
6293 InputInfoList UnbundlingResults;
6294 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(Val: JA)) {
6295 // If we have an unbundling job, we need to create results for all the
6296 // outputs. We also update the results cache so that other actions using
6297 // this unbundling action can get the right results.
6298 for (auto &UI : UA->getDependentActionsInfo()) {
6299 assert(UI.DependentOffloadKind != Action::OFK_None &&
6300 "Unbundling with no offloading??");
6301
6302 // Unbundling actions are never at the top level. When we generate the
6303 // offloading prefix, we also do that for the host file because the
6304 // unbundling action does not change the type of the output which can
6305 // cause a overwrite.
6306 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
6307 Kind: UI.DependentOffloadKind, NormalizedTriple: UI.DependentToolChain->getTripleString(),
6308 /*CreatePrefixForHost=*/true);
6309 auto CurI = InputInfo(
6310 UA,
6311 GetNamedOutputPath(C, JA: *UA, BaseInput, BA: UI.DependentBoundArch,
6312 /*AtTopLevel=*/false,
6313 MultipleArchs: MultipleArchs ||
6314 UI.DependentOffloadKind == Action::OFK_HIP,
6315 NormalizedTriple: OffloadingPrefix),
6316 BaseInput);
6317 // Save the unbundling result.
6318 UnbundlingResults.push_back(Elt: CurI);
6319
6320 // Get the unique string identifier for this dependence and cache the
6321 // result.
6322 BoundArch Arch;
6323 if (TargetDeviceOffloadKind == Action::OFK_HIP) {
6324 if (UI.DependentOffloadKind == Action::OFK_Host)
6325 Arch = BoundArch();
6326 else
6327 Arch = BoundArch(UI.DependentBoundArch);
6328 } else
6329 Arch = BA;
6330
6331 CachedResults[{A, GetTriplePlusArchString(TC: UI.DependentToolChain, BA: Arch,
6332 OffloadKind: UI.DependentOffloadKind)}] = {
6333 CurI};
6334 }
6335
6336 // Now that we have all the results generated, select the one that should be
6337 // returned for the current depending action.
6338 std::pair<const Action *, std::string> ActionTC = {
6339 A, GetTriplePlusArchString(TC, BA, OffloadKind: TargetDeviceOffloadKind)};
6340 assert(CachedResults.find(ActionTC) != CachedResults.end() &&
6341 "Result does not exist??");
6342 Result = CachedResults[ActionTC].front();
6343 } else if (JA->getType() == types::TY_Nothing)
6344 Result = {InputInfo(A, BaseInput)};
6345 else {
6346 // We only have to generate a prefix for the host if this is not a top-level
6347 // action.
6348 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
6349 Kind: A->getOffloadingDeviceKind(), NormalizedTriple: EffectiveTriple.str(),
6350 /*CreatePrefixForHost=*/isa<OffloadPackagerJobAction>(Val: A) ||
6351 !(A->getOffloadingHostActiveKinds() == Action::OFK_None ||
6352 AtTopLevel));
6353 Result = InputInfo(A,
6354 GetNamedOutputPath(C, JA: *JA, BaseInput, BA, AtTopLevel,
6355 MultipleArchs, NormalizedTriple: OffloadingPrefix),
6356 BaseInput);
6357 if (T->canEmitIR())
6358 handleTimeTrace(C, Args, JA, BaseInput, Result);
6359 }
6360
6361 if (CCCPrintBindings && !CCGenDiagnostics) {
6362 llvm::errs() << "# \"" << T->getToolChain().getEffectiveTriple().str()
6363 << '"' << " - \"" << T->getName() << "\", inputs: [";
6364 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
6365 llvm::errs() << InputInfos[i].getAsString();
6366 if (i + 1 != e)
6367 llvm::errs() << ", ";
6368 }
6369 if (UnbundlingResults.empty())
6370 llvm::errs() << "], output: " << Result.getAsString() << "\n";
6371 else {
6372 llvm::errs() << "], outputs: [";
6373 for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) {
6374 llvm::errs() << UnbundlingResults[i].getAsString();
6375 if (i + 1 != e)
6376 llvm::errs() << ", ";
6377 }
6378 llvm::errs() << "] \n";
6379 }
6380 } else {
6381 if (UnbundlingResults.empty())
6382 T->ConstructJob(C, JA: *JA, Output: Result, Inputs: InputInfos, TCArgs: Args, LinkingOutput);
6383 else
6384 T->ConstructJobMultipleOutputs(C, JA: *JA, Outputs: UnbundlingResults, Inputs: InputInfos,
6385 TCArgs: Args, LinkingOutput);
6386 }
6387 return {Result};
6388}
6389
6390const char *Driver::getDefaultImageName() const {
6391 llvm::Triple Target(llvm::Triple::normalize(Str: TargetTriple));
6392 return Target.isOSWindows() ? "a.exe" : "a.out";
6393}
6394
6395/// Create output filename based on ArgValue, which could either be a
6396/// full filename, filename without extension, or a directory. If ArgValue
6397/// does not provide a filename, then use BaseName, and use the extension
6398/// suitable for FileType.
6399static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
6400 StringRef BaseName,
6401 types::ID FileType) {
6402 SmallString<128> Filename = ArgValue;
6403
6404 if (ArgValue.empty()) {
6405 // If the argument is empty, output to BaseName in the current dir.
6406 Filename = BaseName;
6407 } else if (llvm::sys::path::is_separator(value: Filename.back())) {
6408 // If the argument is a directory, output to BaseName in that dir.
6409 llvm::sys::path::append(path&: Filename, a: BaseName);
6410 }
6411
6412 if (!llvm::sys::path::has_extension(path: ArgValue)) {
6413 // If the argument didn't provide an extension, then set it.
6414 const char *Extension = types::getTypeTempSuffix(Id: FileType, CLStyle: true);
6415
6416 if (FileType == types::TY_Image &&
6417 Args.hasArg(Ids: options::OPT__SLASH_LD, Ids: options::OPT__SLASH_LDd)) {
6418 // The output file is a dll.
6419 Extension = "dll";
6420 }
6421
6422 llvm::sys::path::replace_extension(path&: Filename, extension: Extension);
6423 }
6424
6425 return Args.MakeArgString(Str: Filename.c_str());
6426}
6427
6428static bool HasPreprocessOutput(const Action &JA) {
6429 if (isa<PreprocessJobAction>(Val: JA))
6430 return true;
6431 if (isa<OffloadAction>(Val: JA) && isa<PreprocessJobAction>(Val: JA.getInputs()[0]))
6432 return true;
6433 if (isa<OffloadBundlingJobAction>(Val: JA) &&
6434 HasPreprocessOutput(JA: *(JA.getInputs()[0])))
6435 return true;
6436 return false;
6437}
6438
6439const char *Driver::CreateTempFile(Compilation &C, StringRef Prefix,
6440 StringRef Suffix, bool MultipleArchs,
6441 StringRef BoundArchStr,
6442 bool NeedUniqueDirectory) const {
6443 SmallString<128> TmpName;
6444 Arg *A = C.getArgs().getLastArg(Ids: options::OPT_fcrash_diagnostics_dir);
6445 std::optional<std::string> CrashDirectory =
6446 CCGenDiagnostics && A
6447 ? std::string(A->getValue())
6448 : llvm::sys::Process::GetEnv(name: "CLANG_CRASH_DIAGNOSTICS_DIR");
6449 if (CrashDirectory) {
6450 if (!getVFS().exists(Path: *CrashDirectory))
6451 llvm::sys::fs::create_directories(path: *CrashDirectory);
6452 SmallString<128> Path(*CrashDirectory);
6453 llvm::sys::path::append(path&: Path, a: Prefix);
6454 const char *Middle = !Suffix.empty() ? "-%%%%%%." : "-%%%%%%";
6455 if (std::error_code EC =
6456 llvm::sys::fs::createUniqueFile(Model: Path + Middle + Suffix, ResultPath&: TmpName)) {
6457 Diag(DiagID: clang::diag::err_unable_to_make_temp) << EC.message();
6458 return "";
6459 }
6460 } else {
6461 if (MultipleArchs && !BoundArchStr.empty()) {
6462 if (NeedUniqueDirectory) {
6463 TmpName = GetTemporaryDirectory(Prefix);
6464 llvm::sys::path::append(path&: TmpName, a: Twine(Prefix) + "-" + BoundArchStr +
6465 "." + Suffix);
6466 } else {
6467 TmpName = GetTemporaryPath(Prefix: (Twine(Prefix) + "-" + BoundArchStr).str(),
6468 Suffix);
6469 }
6470
6471 } else {
6472 TmpName = GetTemporaryPath(Prefix, Suffix);
6473 }
6474 }
6475 return C.addTempFile(Name: C.getArgs().MakeArgString(Str: TmpName));
6476}
6477
6478// Calculate the output path of the module file when compiling a module unit
6479// with the `-fmodule-output` option or `-fmodule-output=` option specified.
6480// The behavior is:
6481// - If `-fmodule-output=` is specfied, then the module file is
6482// writing to the value.
6483// - Otherwise if the output object file of the module unit is specified, the
6484// output path
6485// of the module file should be the same with the output object file except
6486// the corresponding suffix. This requires both `-o` and `-c` are specified.
6487// - Otherwise, the output path of the module file will be the same with the
6488// input with the corresponding suffix.
6489static const char *GetModuleOutputPath(Compilation &C, const JobAction &JA,
6490 const char *BaseInput) {
6491 assert(isa<PrecompileJobAction>(JA) && JA.getType() == types::TY_ModuleFile &&
6492 (C.getArgs().hasArg(options::OPT_fmodule_output) ||
6493 C.getArgs().hasArg(options::OPT_fmodule_output_EQ)));
6494
6495 SmallString<256> OutputPath =
6496 tools::getCXX20NamedModuleOutputPath(Args: C.getArgs(), BaseInput);
6497
6498 return C.addResultFile(Name: C.getArgs().MakeArgString(Str: OutputPath.c_str()), JA: &JA);
6499}
6500
6501const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
6502 const char *BaseInput, BoundArch BA,
6503 bool AtTopLevel, bool MultipleArchs,
6504 StringRef OffloadingPrefix) const {
6505 std::string BoundArchStr = sanitizeTargetIDInFileName(TargetID: BA.ArchName);
6506
6507 llvm::PrettyStackTraceString CrashInfo("Computing output path");
6508
6509 auto CreateTempOutputPath = [&](StringRef Prefix) {
6510 const char *Suffix =
6511 types::getTypeTempSuffix(Id: JA.getType(), CLStyle: IsCLMode() || IsDXCMode());
6512 // The non-offloading toolchain on Darwin requires deterministic input
6513 // file name for binaries to be deterministic, therefore it needs unique
6514 // directory.
6515 const llvm::Triple Triple(C.getDriver().getTargetTriple());
6516 const bool NeedUniqueDirectory =
6517 (JA.getOffloadingDeviceKind() == Action::OFK_None ||
6518 JA.getOffloadingDeviceKind() == Action::OFK_Host) &&
6519 Triple.isOSDarwin();
6520 return CreateTempFile(C, Prefix, Suffix, MultipleArchs, BoundArchStr,
6521 NeedUniqueDirectory);
6522 };
6523
6524 // Standard library output in -fmodules-driver?
6525 if (isa<PrecompileJobAction>(Val: JA) && !JA.getInputs().empty() &&
6526 (JA.getInputs().front()->getType() == types::TY_CXXStdModule ||
6527 JA.getInputs().front()->getType() == types::TY_PP_CXXStdModule)) {
6528 StringRef Filename = llvm::sys::path::filename(path: BaseInput);
6529 StringRef Stem = llvm::sys::path::stem(path: Filename);
6530 return CreateTempOutputPath(Stem);
6531 }
6532
6533 // Output to a user requested destination?
6534 if (AtTopLevel && !isa<DsymutilJobAction>(Val: JA) && !isa<VerifyJobAction>(Val: JA)) {
6535 if (Arg *FinalOutput = C.getArgs().getLastArg(Ids: options::OPT_o))
6536 return C.addResultFile(Name: FinalOutput->getValue(), JA: &JA);
6537 }
6538
6539 // For /P, preprocess to file named after BaseInput.
6540 if (C.getArgs().hasArg(Ids: options::OPT__SLASH_P)) {
6541 assert(AtTopLevel && isa<PreprocessJobAction>(JA));
6542 StringRef BaseName = llvm::sys::path::filename(path: BaseInput);
6543 StringRef NameArg;
6544 if (Arg *A = C.getArgs().getLastArg(Ids: options::OPT__SLASH_Fi))
6545 NameArg = A->getValue();
6546 return C.addResultFile(
6547 Name: MakeCLOutputFilename(Args: C.getArgs(), ArgValue: NameArg, BaseName, FileType: types::TY_PP_C),
6548 JA: &JA);
6549 }
6550
6551 // Default to writing to stdout?
6552 if (AtTopLevel && !CCGenDiagnostics && HasPreprocessOutput(JA)) {
6553 return "-";
6554 }
6555
6556 if (JA.getType() == types::TY_ModuleFile &&
6557 C.getArgs().getLastArg(Ids: options::OPT_module_file_info)) {
6558 return "-";
6559 }
6560
6561 if (JA.getType() == types::TY_PP_Asm &&
6562 C.getArgs().hasArg(Ids: options::OPT_dxc_Fc)) {
6563 StringRef FcValue = C.getArgs().getLastArgValue(Id: options::OPT_dxc_Fc);
6564 // TODO: Should we use `MakeCLOutputFilename` here? If so, we can probably
6565 // handle this as part of the SLASH_Fa handling below.
6566 return C.addResultFile(Name: C.getArgs().MakeArgString(Str: FcValue), JA: &JA);
6567 }
6568
6569 if ((JA.getType() == types::TY_Object &&
6570 C.getArgs().hasArg(Ids: options::OPT_dxc_Fo)) ||
6571 JA.getType() == types::TY_DX_CONTAINER) {
6572 StringRef FoValue = C.getArgs().getLastArgValue(Id: options::OPT_dxc_Fo);
6573 assert((C.getDefaultToolChain().getTriple().isDXIL() ||
6574 C.getDefaultToolChain().getTriple().isSPIRV()) &&
6575 "expected DXIL or SPIR-V triple for HLSL output path");
6576 const auto &TC =
6577 static_cast<const toolchains::HLSLToolChain &>(C.getDefaultToolChain());
6578 // Fo can be empty here if the validator is running for a compiler flow
6579 // that is using Fc or just printing disassembly.
6580 if (TC.isLastOutputProducingJob(Args&: C.getArgs(), AC: JA.getKind()) &&
6581 !FoValue.empty())
6582 return C.addResultFile(Name: C.getArgs().MakeArgString(Str: FoValue), JA: &JA);
6583 StringRef Name = llvm::sys::path::filename(path: BaseInput);
6584 std::pair<StringRef, StringRef> Split = Name.split(Separator: '.');
6585 const char *Suffix = types::getTypeTempSuffix(Id: JA.getType(), CLStyle: true);
6586 return CreateTempFile(C, Prefix: Split.first, Suffix, MultipleArchs: false);
6587 }
6588
6589 // Is this the assembly listing for /FA?
6590 if (JA.getType() == types::TY_PP_Asm &&
6591 (C.getArgs().hasArg(Ids: options::OPT__SLASH_FA) ||
6592 C.getArgs().hasArg(Ids: options::OPT__SLASH_Fa))) {
6593 // Use /Fa and the input filename to determine the asm file name.
6594 StringRef BaseName = llvm::sys::path::filename(path: BaseInput);
6595 StringRef FaValue = C.getArgs().getLastArgValue(Id: options::OPT__SLASH_Fa);
6596 return C.addResultFile(
6597 Name: MakeCLOutputFilename(Args: C.getArgs(), ArgValue: FaValue, BaseName, FileType: JA.getType()),
6598 JA: &JA);
6599 }
6600
6601 if (JA.getType() == types::TY_API_INFO &&
6602 C.getArgs().hasArg(Ids: options::OPT_emit_extension_symbol_graphs) &&
6603 C.getArgs().hasArg(Ids: options::OPT_o))
6604 Diag(DiagID: clang::diag::err_drv_unexpected_symbol_graph_output)
6605 << C.getArgs().getLastArgValue(Id: options::OPT_o);
6606
6607 // DXC defaults to standard out when generating assembly. We check this after
6608 // any DXC flags that might specify a file.
6609 if (AtTopLevel && JA.getType() == types::TY_PP_Asm && IsDXCMode())
6610 return "-";
6611
6612 bool SpecifiedModuleOutput =
6613 C.getArgs().hasArg(Ids: options::OPT_fmodule_output) ||
6614 C.getArgs().hasArg(Ids: options::OPT_fmodule_output_EQ);
6615 if (MultipleArchs && SpecifiedModuleOutput)
6616 Diag(DiagID: clang::diag::err_drv_module_output_with_multiple_arch);
6617
6618 // If we're emitting a module output with the specified option
6619 // `-fmodule-output`.
6620 if (!AtTopLevel && isa<PrecompileJobAction>(Val: JA) &&
6621 JA.getType() == types::TY_ModuleFile && SpecifiedModuleOutput) {
6622 assert(C.getArgs().hasArg(options::OPT_fno_modules_reduced_bmi));
6623 return GetModuleOutputPath(C, JA, BaseInput);
6624 }
6625
6626 // Output to a temporary file?
6627 if ((!AtTopLevel && !isSaveTempsEnabled() &&
6628 !C.getArgs().hasArg(Ids: options::OPT__SLASH_Fo)) ||
6629 CCGenDiagnostics) {
6630 StringRef Name = llvm::sys::path::filename(path: BaseInput);
6631 return CreateTempOutputPath(Name.split(Separator: '.').first);
6632 }
6633
6634 SmallString<128> BasePath(BaseInput);
6635 SmallString<128> ExternalPath("");
6636 StringRef BaseName;
6637
6638 // Dsymutil actions should use the full path.
6639 if (isa<DsymutilJobAction>(Val: JA) && C.getArgs().hasArg(Ids: options::OPT_dsym_dir)) {
6640 ExternalPath += C.getArgs().getLastArg(Ids: options::OPT_dsym_dir)->getValue();
6641 // We use posix style here because the tests (specifically
6642 // darwin-dsymutil.c) demonstrate that posix style paths are acceptable
6643 // even on Windows and if we don't then the similar test covering this
6644 // fails.
6645 llvm::sys::path::append(path&: ExternalPath, style: llvm::sys::path::Style::posix,
6646 a: llvm::sys::path::filename(path: BasePath));
6647 BaseName = ExternalPath;
6648 } else if (isa<DsymutilJobAction>(Val: JA) || isa<VerifyJobAction>(Val: JA))
6649 BaseName = BasePath;
6650 else
6651 BaseName = llvm::sys::path::filename(path: BasePath);
6652
6653 // Determine what the derived output name should be.
6654 const char *NamedOutput;
6655
6656 if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC ||
6657 JA.getType() == types::TY_LLVM_BC ||
6658 JA.getType() == types::TY_LLVM_IR) &&
6659 C.getArgs().hasArg(Ids: options::OPT__SLASH_Fo, Ids: options::OPT__SLASH_o)) {
6660 // The /Fo or /o flag decides the object filename.
6661 StringRef Val =
6662 C.getArgs()
6663 .getLastArg(Ids: options::OPT__SLASH_Fo, Ids: options::OPT__SLASH_o)
6664 ->getValue();
6665 NamedOutput =
6666 MakeCLOutputFilename(Args: C.getArgs(), ArgValue: Val, BaseName, FileType: JA.getType());
6667 } else if (JA.getType() == types::TY_Image &&
6668 C.getArgs().hasArg(Ids: options::OPT__SLASH_Fe,
6669 Ids: options::OPT__SLASH_o)) {
6670 // The /Fe or /o flag names the linked file.
6671 StringRef Val =
6672 C.getArgs()
6673 .getLastArg(Ids: options::OPT__SLASH_Fe, Ids: options::OPT__SLASH_o)
6674 ->getValue();
6675 NamedOutput =
6676 MakeCLOutputFilename(Args: C.getArgs(), ArgValue: Val, BaseName, FileType: types::TY_Image);
6677 } else if (JA.getType() == types::TY_Image) {
6678 if (IsCLMode()) {
6679 // clang-cl uses BaseName for the executable name.
6680 NamedOutput =
6681 MakeCLOutputFilename(Args: C.getArgs(), ArgValue: "", BaseName, FileType: types::TY_Image);
6682 } else {
6683 SmallString<128> Output(getDefaultImageName());
6684 // HIP image for device compilation with -fno-gpu-rdc is per compilation
6685 // unit.
6686 bool IsHIPNoRDC = JA.getOffloadingDeviceKind() == Action::OFK_HIP &&
6687 !C.getArgs().hasFlag(Pos: options::OPT_fgpu_rdc,
6688 Neg: options::OPT_fno_gpu_rdc, Default: false);
6689 bool UseOutExtension = IsHIPNoRDC || isa<OffloadPackagerJobAction>(Val: JA);
6690 if (UseOutExtension) {
6691 Output = BaseName;
6692 llvm::sys::path::replace_extension(path&: Output, extension: "");
6693 }
6694 Output += OffloadingPrefix;
6695 if (MultipleArchs && !BoundArchStr.empty()) {
6696 Output += "-";
6697 Output.append(RHS: BoundArchStr);
6698 }
6699 if (UseOutExtension)
6700 Output += ".out";
6701 NamedOutput = C.getArgs().MakeArgString(Str: Output.c_str());
6702 }
6703 } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
6704 NamedOutput = C.getArgs().MakeArgString(Str: GetClPchPath(C, BaseName));
6705 } else if ((JA.getType() == types::TY_Plist || JA.getType() == types::TY_AST) &&
6706 C.getArgs().hasArg(Ids: options::OPT__SLASH_o)) {
6707 StringRef Val =
6708 C.getArgs()
6709 .getLastArg(Ids: options::OPT__SLASH_o)
6710 ->getValue();
6711 NamedOutput =
6712 MakeCLOutputFilename(Args: C.getArgs(), ArgValue: Val, BaseName, FileType: types::TY_Object);
6713 } else {
6714 const char *Suffix =
6715 types::getTypeTempSuffix(Id: JA.getType(), CLStyle: IsCLMode() || IsDXCMode());
6716 assert(Suffix && "All types used for output should have a suffix.");
6717
6718 std::string::size_type End = std::string::npos;
6719 if (!types::appendSuffixForType(Id: JA.getType()))
6720 End = BaseName.rfind(C: '.');
6721 SmallString<128> Suffixed(BaseName.substr(Start: 0, N: End));
6722 Suffixed += OffloadingPrefix;
6723 if (MultipleArchs && !BoundArchStr.empty()) {
6724 Suffixed += "-";
6725 Suffixed.append(RHS: BoundArchStr);
6726 }
6727 // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
6728 // the unoptimized bitcode so that it does not get overwritten by the ".bc"
6729 // optimized bitcode output.
6730 auto IsAMDRDCInCompilePhase = [](const JobAction &JA,
6731 const llvm::opt::DerivedArgList &Args) {
6732 // The relocatable compilation in HIP and OpenMP implies -emit-llvm.
6733 // Similarly, use a ".tmp.bc" suffix for the unoptimized bitcode
6734 // (generated in the compile phase.)
6735 const ToolChain *TC = JA.getOffloadingToolChain();
6736 return isa<CompileJobAction>(Val: JA) &&
6737 ((JA.getOffloadingDeviceKind() == Action::OFK_HIP &&
6738 (Args.hasFlag(Pos: options::OPT_fgpu_rdc, Neg: options::OPT_fno_gpu_rdc,
6739 Default: false) ||
6740 Args.hasFlag(Pos: options::OPT_offload_new_driver,
6741 Neg: options::OPT_no_offload_new_driver, Default: true))) ||
6742 (JA.getOffloadingDeviceKind() == Action::OFK_OpenMP && TC &&
6743 TC->getTriple().isAMDGPU()));
6744 };
6745
6746 // The linker wrapper may not support the input and output files to be the
6747 // same one, and without it -save-temps can fail.
6748 bool IsLinkerWrapper =
6749 JA.getType() == types::TY_Object && isa<LinkerWrapperJobAction>(Val: JA);
6750 bool IsEmitBitcode = JA.getType() == types::TY_LLVM_BC &&
6751 (C.getArgs().hasArg(Ids: options::OPT_emit_llvm) ||
6752 IsAMDRDCInCompilePhase(JA, C.getArgs()));
6753
6754 if (!AtTopLevel && (IsLinkerWrapper || IsEmitBitcode))
6755 Suffixed += ".tmp";
6756 Suffixed += '.';
6757 Suffixed += Suffix;
6758 NamedOutput = C.getArgs().MakeArgString(Str: Suffixed.c_str());
6759 }
6760
6761 // Prepend object file path if -save-temps=obj
6762 if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(Ids: options::OPT_o) &&
6763 JA.getType() != types::TY_PCH) {
6764 Arg *FinalOutput = C.getArgs().getLastArg(Ids: options::OPT_o);
6765 SmallString<128> TempPath(FinalOutput->getValue());
6766 llvm::sys::path::remove_filename(path&: TempPath);
6767 StringRef OutputFileName = llvm::sys::path::filename(path: NamedOutput);
6768 llvm::sys::path::append(path&: TempPath, a: OutputFileName);
6769 NamedOutput = C.getArgs().MakeArgString(Str: TempPath.c_str());
6770 }
6771
6772 // If we're saving temps and the temp file conflicts with the input file,
6773 // then avoid overwriting input file.
6774 if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
6775 bool SameFile = false;
6776 SmallString<256> Result;
6777 llvm::sys::fs::current_path(result&: Result);
6778 llvm::sys::path::append(path&: Result, a: BaseName);
6779 llvm::sys::fs::equivalent(A: BaseInput, B: Result.c_str(), result&: SameFile);
6780 // Must share the same path to conflict.
6781 if (SameFile) {
6782 StringRef Name = llvm::sys::path::filename(path: BaseInput);
6783 std::pair<StringRef, StringRef> Split = Name.split(Separator: '.');
6784 std::string TmpName = GetTemporaryPath(
6785 Prefix: Split.first,
6786 Suffix: types::getTypeTempSuffix(Id: JA.getType(), CLStyle: IsCLMode() || IsDXCMode()));
6787 return C.addTempFile(Name: C.getArgs().MakeArgString(Str: TmpName));
6788 }
6789 }
6790
6791 // As an annoying special case, PCH generation doesn't strip the pathname.
6792 if (JA.getType() == types::TY_PCH && !IsCLMode()) {
6793 llvm::sys::path::remove_filename(path&: BasePath);
6794 if (BasePath.empty())
6795 BasePath = NamedOutput;
6796 else
6797 llvm::sys::path::append(path&: BasePath, a: NamedOutput);
6798 return C.addResultFile(Name: C.getArgs().MakeArgString(Str: BasePath.c_str()), JA: &JA);
6799 }
6800
6801 return C.addResultFile(Name: NamedOutput, JA: &JA);
6802}
6803
6804std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const {
6805 // Search for Name in a list of paths.
6806 auto SearchPaths = [&](const llvm::SmallVectorImpl<std::string> &P)
6807 -> std::optional<std::string> {
6808 // Respect a limited subset of the '-Bprefix' functionality in GCC by
6809 // attempting to use this prefix when looking for file paths.
6810 for (const auto &Dir : P) {
6811 if (Dir.empty())
6812 continue;
6813 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(pos: 1) : Dir);
6814 llvm::sys::path::append(path&: P, a: Name);
6815 if (llvm::sys::fs::exists(Path: Twine(P)))
6816 return std::string(P);
6817 }
6818 return std::nullopt;
6819 };
6820
6821 if (auto P = SearchPaths(PrefixDirs))
6822 return *P;
6823
6824 SmallString<128> R(ResourceDir);
6825 llvm::sys::path::append(path&: R, a: Name);
6826 if (llvm::sys::fs::exists(Path: Twine(R)))
6827 return std::string(R);
6828
6829 SmallString<128> P(TC.getCompilerRTPath());
6830 llvm::sys::path::append(path&: P, a: Name);
6831 if (llvm::sys::fs::exists(Path: Twine(P)))
6832 return std::string(P);
6833
6834 // With Flang, also look for intrinsic modules
6835 if (IsFlangMode()) {
6836 if (std::optional<std::string> IntrPath =
6837 TC.getDefaultIntrinsicModuleDir()) {
6838 SmallString<128> P(*IntrPath);
6839 llvm::sys::path::append(path&: P, a: Name);
6840 if (llvm::sys::fs::exists(Path: P))
6841 return std::string(P);
6842 }
6843 }
6844
6845 SmallString<128> D(Dir);
6846 llvm::sys::path::append(path&: D, a: "..", b: Name);
6847 if (llvm::sys::fs::exists(Path: Twine(D)))
6848 return std::string(D);
6849
6850 if (auto P = SearchPaths(TC.getLibraryPaths()))
6851 return *P;
6852
6853 if (auto P = SearchPaths(TC.getFilePaths()))
6854 return *P;
6855
6856 SmallString<128> R2(ResourceDir);
6857 llvm::sys::path::append(path&: R2, a: "..", b: "..", c: Name);
6858 if (llvm::sys::fs::exists(Path: Twine(R2)))
6859 return std::string(R2);
6860
6861 return std::string(Name);
6862}
6863
6864void Driver::generatePrefixedToolNames(
6865 StringRef Tool, const ToolChain &TC,
6866 SmallVectorImpl<std::string> &Names) const {
6867 // FIXME: Needs a better variable than TargetTriple
6868 Names.emplace_back(Args: (TargetTriple + "-" + Tool).str());
6869 Names.emplace_back(Args&: Tool);
6870}
6871
6872static bool ScanDirForExecutable(SmallString<128> &Dir, StringRef Name) {
6873 llvm::sys::path::append(path&: Dir, a: Name);
6874 if (llvm::sys::fs::can_execute(Path: Twine(Dir)))
6875 return true;
6876 llvm::sys::path::remove_filename(path&: Dir);
6877 return false;
6878}
6879
6880std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const {
6881 SmallVector<std::string, 2> TargetSpecificExecutables;
6882 generatePrefixedToolNames(Tool: Name, TC, Names&: TargetSpecificExecutables);
6883
6884 // Respect a limited subset of the '-Bprefix' functionality in GCC by
6885 // attempting to use this prefix when looking for program paths.
6886 for (const auto &PrefixDir : PrefixDirs) {
6887 if (llvm::sys::fs::is_directory(Path: PrefixDir)) {
6888 SmallString<128> P(PrefixDir);
6889 if (ScanDirForExecutable(Dir&: P, Name))
6890 return std::string(P);
6891 } else {
6892 SmallString<128> P((PrefixDir + Name).str());
6893 if (llvm::sys::fs::can_execute(Path: Twine(P)))
6894 return std::string(P);
6895 }
6896 }
6897
6898 const ToolChain::path_list &List = TC.getProgramPaths();
6899 for (const auto &TargetSpecificExecutable : TargetSpecificExecutables) {
6900 // For each possible name of the tool look for it in
6901 // program paths first, then the path.
6902 // Higher priority names will be first, meaning that
6903 // a higher priority name in the path will be found
6904 // instead of a lower priority name in the program path.
6905 // E.g. <triple>-gcc on the path will be found instead
6906 // of gcc in the program path
6907 for (const auto &Path : List) {
6908 SmallString<128> P(Path);
6909 if (ScanDirForExecutable(Dir&: P, Name: TargetSpecificExecutable))
6910 return std::string(P);
6911 }
6912
6913 // Fall back to the path
6914 if (llvm::ErrorOr<std::string> P =
6915 llvm::sys::findProgramByName(Name: TargetSpecificExecutable))
6916 return *P;
6917 }
6918
6919 return std::string(Name);
6920}
6921
6922std::string Driver::GetStdModuleManifestPath(const Compilation &C,
6923 const ToolChain &TC) const {
6924 std::string error = "<NOT PRESENT>";
6925
6926 if (C.getArgs().hasArg(Ids: options::OPT_nostdlib))
6927 return error;
6928
6929 switch (TC.GetCXXStdlibType(Args: C.getArgs())) {
6930 case ToolChain::CST_Libcxx: {
6931 auto evaluate = [&](const char *library) -> std::optional<std::string> {
6932 std::string lib = GetFilePath(Name: library, TC);
6933
6934 // Note when there are multiple flavours of libc++ the module json needs
6935 // to look at the command-line arguments for the proper json. These
6936 // flavours do not exist at the moment, but there are plans to provide a
6937 // variant that is built with sanitizer instrumentation enabled.
6938
6939 // For example
6940 // StringRef modules = [&] {
6941 // const SanitizerArgs &Sanitize = TC.getSanitizerArgs(C.getArgs());
6942 // if (Sanitize.needsAsanRt())
6943 // return "libc++.modules-asan.json";
6944 // return "libc++.modules.json";
6945 // }();
6946
6947 SmallString<128> path(lib.begin(), lib.end());
6948 llvm::sys::path::remove_filename(path);
6949 llvm::sys::path::append(path, a: "libc++.modules.json");
6950 if (TC.getVFS().exists(Path: path))
6951 return static_cast<std::string>(path);
6952
6953 return {};
6954 };
6955
6956 if (std::optional<std::string> result = evaluate("libc++.so"); result)
6957 return *result;
6958
6959 return evaluate("libc++.a").value_or(u&: error);
6960 }
6961
6962 case ToolChain::CST_Libstdcxx: {
6963 auto evaluate = [&](const char *library) -> std::optional<std::string> {
6964 std::string lib = GetFilePath(Name: library, TC);
6965
6966 SmallString<128> path(lib.begin(), lib.end());
6967 llvm::sys::path::remove_filename(path);
6968 llvm::sys::path::append(path, a: "libstdc++.modules.json");
6969 if (TC.getVFS().exists(Path: path))
6970 return static_cast<std::string>(path);
6971
6972 return {};
6973 };
6974
6975 if (std::optional<std::string> result = evaluate("libstdc++.so"); result)
6976 return *result;
6977
6978 return evaluate("libstdc++.a").value_or(u&: error);
6979 }
6980 }
6981
6982 return error;
6983}
6984
6985std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const {
6986 SmallString<128> Path;
6987 std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, ResultPath&: Path);
6988 if (EC) {
6989 Diag(DiagID: clang::diag::err_unable_to_make_temp) << EC.message();
6990 return "";
6991 }
6992
6993 return std::string(Path);
6994}
6995
6996std::string Driver::GetTemporaryDirectory(StringRef Prefix) const {
6997 SmallString<128> Path;
6998 std::error_code EC = llvm::sys::fs::createUniqueDirectory(Prefix, ResultPath&: Path);
6999 if (EC) {
7000 Diag(DiagID: clang::diag::err_unable_to_make_temp) << EC.message();
7001 return "";
7002 }
7003
7004 return std::string(Path);
7005}
7006
7007std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
7008 SmallString<128> Output;
7009 if (Arg *FpArg = C.getArgs().getLastArg(Ids: options::OPT__SLASH_Fp)) {
7010 // FIXME: If anybody needs it, implement this obscure rule:
7011 // "If you specify a directory without a file name, the default file name
7012 // is VCx0.pch., where x is the major version of Visual C++ in use."
7013 Output = FpArg->getValue();
7014
7015 // "If you do not specify an extension as part of the path name, an
7016 // extension of .pch is assumed. "
7017 if (!llvm::sys::path::has_extension(path: Output))
7018 Output += ".pch";
7019 } else {
7020 if (Arg *YcArg = C.getArgs().getLastArg(Ids: options::OPT__SLASH_Yc))
7021 Output = YcArg->getValue();
7022 if (Output.empty())
7023 Output = BaseName;
7024 llvm::sys::path::replace_extension(path&: Output, extension: ".pch");
7025 }
7026 return std::string(Output);
7027}
7028
7029const ToolChain &Driver::getOffloadToolChain(
7030 const llvm::opt::ArgList &Args, const Action::OffloadKind Kind,
7031 const llvm::Triple &Target, const llvm::Triple &AuxTarget) const {
7032 std::unique_ptr<ToolChain> &TC =
7033 ToolChains[Target.str() + "/" + AuxTarget.str()];
7034 std::unique_ptr<ToolChain> &HostTC = ToolChains[AuxTarget.str()];
7035
7036 assert(HostTC && "Host toolchain for offloading doesn't exit?");
7037 if (!TC) {
7038 // Detect the toolchain based off of the target operating system.
7039 switch (Target.getOS()) {
7040 case llvm::Triple::CUDA:
7041 TC = std::make_unique<toolchains::CudaToolChain>(args: *this, args: Target, args&: *HostTC,
7042 args: Args);
7043 break;
7044 case llvm::Triple::AMDHSA:
7045 // For AMDHSA offloading (HIP, OpenMP), use the unified AMDGPUToolChain
7046 // This handles both amdgpu-amd-amdhsa and spirv64-amd-amdhsa
7047 // FIXME: This should not key off language or OS.
7048 if (Kind == Action::OFK_HIP || Kind == Action::OFK_OpenMP)
7049 TC = std::make_unique<toolchains::AMDGPUToolChain>(args: *this, args: Target, args: Args,
7050 args: HostTC.get(), args: Kind);
7051 break;
7052 default:
7053 break;
7054 }
7055 }
7056 if (!TC) {
7057 // Detect the toolchain based off of the target architecture if that failed.
7058 switch (Target.getArch()) {
7059 case llvm::Triple::amdgpu:
7060 case llvm::Triple::r600:
7061 TC = std::make_unique<toolchains::AMDGPUToolChain>(args: *this, args: Target, args: Args,
7062 args: HostTC.get(), args: Kind);
7063 break;
7064 case llvm::Triple::spir:
7065 case llvm::Triple::spir64:
7066 case llvm::Triple::spirv:
7067 case llvm::Triple::spirv32:
7068 case llvm::Triple::spirv64:
7069 switch (Kind) {
7070 case Action::OFK_SYCL:
7071 TC = std::make_unique<toolchains::SYCLToolChain>(args: *this, args: Target, args&: *HostTC,
7072 args: Args);
7073 break;
7074 case Action::OFK_HIP:
7075 TC = std::make_unique<toolchains::HIPSPVToolChain>(args: *this, args: Target,
7076 args&: *HostTC, args: Args);
7077 break;
7078 case Action::OFK_OpenMP:
7079 TC = std::make_unique<toolchains::SPIRVOpenMPToolChain>(args: *this, args: Target,
7080 args&: *HostTC, args: Args);
7081 break;
7082 case Action::OFK_Cuda:
7083 TC = std::make_unique<toolchains::CudaToolChain>(args: *this, args: Target, args&: *HostTC,
7084 args: Args);
7085 break;
7086 default:
7087 break;
7088 }
7089 break;
7090 default:
7091 break;
7092 }
7093 }
7094
7095 // If all else fails, just look up the normal toolchain for the target.
7096 if (!TC)
7097 return getToolChain(Args, Target);
7098 return *TC;
7099}
7100
7101const ToolChain &Driver::getToolChain(const ArgList &Args,
7102 const llvm::Triple &Target) const {
7103
7104 auto &TC = ToolChains[Target.str()];
7105 if (!TC) {
7106 switch (Target.getOS()) {
7107 case llvm::Triple::AIX:
7108 TC = std::make_unique<toolchains::AIX>(args: *this, args: Target, args: Args);
7109 break;
7110 case llvm::Triple::Haiku:
7111 TC = std::make_unique<toolchains::Haiku>(args: *this, args: Target, args: Args);
7112 break;
7113 case llvm::Triple::Darwin:
7114 case llvm::Triple::MacOSX:
7115 case llvm::Triple::IOS:
7116 case llvm::Triple::TvOS:
7117 case llvm::Triple::WatchOS:
7118 case llvm::Triple::XROS:
7119 case llvm::Triple::DriverKit:
7120 TC = std::make_unique<toolchains::DarwinClang>(args: *this, args: Target, args: Args);
7121 break;
7122 case llvm::Triple::DragonFly:
7123 TC = std::make_unique<toolchains::DragonFly>(args: *this, args: Target, args: Args);
7124 break;
7125 case llvm::Triple::OpenBSD:
7126 TC = std::make_unique<toolchains::OpenBSD>(args: *this, args: Target, args: Args);
7127 break;
7128 case llvm::Triple::NetBSD:
7129 TC = std::make_unique<toolchains::NetBSD>(args: *this, args: Target, args: Args);
7130 break;
7131 case llvm::Triple::FreeBSD:
7132 if (Target.isPPC())
7133 TC = std::make_unique<toolchains::PPCFreeBSDToolChain>(args: *this, args: Target,
7134 args: Args);
7135 else
7136 TC = std::make_unique<toolchains::FreeBSD>(args: *this, args: Target, args: Args);
7137 break;
7138 case llvm::Triple::Linux:
7139 case llvm::Triple::ELFIAMCU:
7140 if (Target.getArch() == llvm::Triple::hexagon)
7141 TC = std::make_unique<toolchains::HexagonToolChain>(args: *this, args: Target,
7142 args: Args);
7143 else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
7144 !Target.hasEnvironment())
7145 TC = std::make_unique<toolchains::MipsLLVMToolChain>(args: *this, args: Target,
7146 args: Args);
7147 else if (Target.isPPC())
7148 TC = std::make_unique<toolchains::PPCLinuxToolChain>(args: *this, args: Target,
7149 args: Args);
7150 else if (Target.getArch() == llvm::Triple::ve)
7151 TC = std::make_unique<toolchains::VEToolChain>(args: *this, args: Target, args: Args);
7152 else if (Target.isOHOSFamily())
7153 TC = std::make_unique<toolchains::OHOS>(args: *this, args: Target, args: Args);
7154 else if (Target.isWALI())
7155 TC = std::make_unique<toolchains::WebAssembly>(args: *this, args: Target, args: Args);
7156 else if (Target.isLFI())
7157 TC = std::make_unique<toolchains::LFILinux>(args: *this, args: Target, args: Args);
7158 else
7159 TC = std::make_unique<toolchains::Linux>(args: *this, args: Target, args: Args);
7160 break;
7161 case llvm::Triple::Fuchsia:
7162 TC = std::make_unique<toolchains::Fuchsia>(args: *this, args: Target, args: Args);
7163 break;
7164 case llvm::Triple::Managarm:
7165 TC = std::make_unique<toolchains::Managarm>(args: *this, args: Target, args: Args);
7166 break;
7167 case llvm::Triple::Serenity:
7168 TC = std::make_unique<toolchains::Serenity>(args: *this, args: Target, args: Args);
7169 break;
7170 case llvm::Triple::Solaris:
7171 TC = std::make_unique<toolchains::Solaris>(args: *this, args: Target, args: Args);
7172 break;
7173 case llvm::Triple::CUDA:
7174 TC = std::make_unique<toolchains::NVPTXToolChain>(args: *this, args: Target, args: Args);
7175 break;
7176 case llvm::Triple::AMDHSA: {
7177 if (Target.getArch() == llvm::Triple::spirv64) {
7178 TC = std::make_unique<toolchains::SPIRVAMDToolChain>(args: *this, args: Target,
7179 args: Args);
7180 } else {
7181 // Only link device libraries for OpenCL and LLVM IR inputs
7182 bool ShouldLinkDeviceLibs = usesInput(Args, Fn&: types::isOpenCL) ||
7183 usesInput(Args, Fn&: types::isLLVMIR);
7184 TC = std::make_unique<toolchains::AMDGPUToolChain>(
7185 args: *this, args: Target, args: Args, args: nullptr, args: Action::OFK_None,
7186 args&: ShouldLinkDeviceLibs);
7187 }
7188 break;
7189 }
7190 case llvm::Triple::AMDPAL:
7191 case llvm::Triple::Mesa3D:
7192 TC = std::make_unique<toolchains::AMDGPUToolChain>(args: *this, args: Target, args: Args);
7193 break;
7194 case llvm::Triple::UEFI:
7195 TC = std::make_unique<toolchains::UEFI>(args: *this, args: Target, args: Args);
7196 break;
7197 case llvm::Triple::Win32:
7198 switch (Target.getEnvironment()) {
7199 default:
7200 if (Target.isOSBinFormatELF())
7201 TC = std::make_unique<toolchains::Generic_ELF>(args: *this, args: Target, args: Args);
7202 else if (Target.isOSBinFormatMachO())
7203 TC = std::make_unique<toolchains::MachO>(args: *this, args: Target, args: Args);
7204 else
7205 TC = std::make_unique<toolchains::Generic_GCC>(args: *this, args: Target, args: Args);
7206 break;
7207 case llvm::Triple::GNU:
7208 TC = std::make_unique<toolchains::MinGW>(args: *this, args: Target, args: Args);
7209 break;
7210 case llvm::Triple::Cygnus:
7211 TC = std::make_unique<toolchains::Cygwin>(args: *this, args: Target, args: Args);
7212 break;
7213 case llvm::Triple::Itanium:
7214 TC = std::make_unique<toolchains::CrossWindowsToolChain>(args: *this, args: Target,
7215 args: Args);
7216 break;
7217 case llvm::Triple::MSVC:
7218 case llvm::Triple::UnknownEnvironment:
7219 if (Args.getLastArgValue(Id: options::OPT_fuse_ld_EQ)
7220 .starts_with_insensitive(Prefix: "bfd"))
7221 TC = std::make_unique<toolchains::CrossWindowsToolChain>(
7222 args: *this, args: Target, args: Args);
7223 else
7224 TC =
7225 std::make_unique<toolchains::MSVCToolChain>(args: *this, args: Target, args: Args);
7226 break;
7227 }
7228 break;
7229 case llvm::Triple::PS4:
7230 TC = std::make_unique<toolchains::PS4CPU>(args: *this, args: Target, args: Args);
7231 break;
7232 case llvm::Triple::PS5:
7233 TC = std::make_unique<toolchains::PS5CPU>(args: *this, args: Target, args: Args);
7234 break;
7235 case llvm::Triple::Hurd:
7236 TC = std::make_unique<toolchains::Hurd>(args: *this, args: Target, args: Args);
7237 break;
7238 case llvm::Triple::LiteOS:
7239 TC = std::make_unique<toolchains::OHOS>(args: *this, args: Target, args: Args);
7240 break;
7241 case llvm::Triple::ZOS:
7242 TC = std::make_unique<toolchains::ZOS>(args: *this, args: Target, args: Args);
7243 break;
7244 case llvm::Triple::Vulkan:
7245 case llvm::Triple::ShaderModel:
7246 if ((Target.getArch() == llvm::Triple::spirv32 ||
7247 Target.getArch() == llvm::Triple::spirv64) &&
7248 !usesInput(Args, Fn&: types::isHLSL))
7249 TC = std::make_unique<toolchains::SPIRVToolChain>(args: *this, args: Target, args: Args);
7250 else
7251 TC = std::make_unique<toolchains::HLSLToolChain>(args: *this, args: Target, args: Args);
7252 break;
7253 case llvm::Triple::ChipStar:
7254 TC = std::make_unique<toolchains::HIPSPVToolChain>(args: *this, args: Target, args: Args);
7255 break;
7256 default:
7257 // Of these targets, Hexagon is the only one that might have
7258 // an OS of Linux, in which case it got handled above already.
7259 switch (Target.getArch()) {
7260 case llvm::Triple::tce:
7261 TC = std::make_unique<toolchains::TCEToolChain>(args: *this, args: Target, args: Args);
7262 break;
7263 case llvm::Triple::tcele:
7264 TC = std::make_unique<toolchains::TCELEToolChain>(args: *this, args: Target, args: Args);
7265 break;
7266 case llvm::Triple::tcele64:
7267 TC =
7268 std::make_unique<toolchains::TCELE64ToolChain>(args: *this, args: Target, args: Args);
7269 break;
7270 case llvm::Triple::hexagon:
7271 TC = std::make_unique<toolchains::HexagonToolChain>(args: *this, args: Target,
7272 args: Args);
7273 break;
7274 case llvm::Triple::lanai:
7275 TC = std::make_unique<toolchains::LanaiToolChain>(args: *this, args: Target, args: Args);
7276 break;
7277 case llvm::Triple::xcore:
7278 TC = std::make_unique<toolchains::XCoreToolChain>(args: *this, args: Target, args: Args);
7279 break;
7280 case llvm::Triple::wasm32:
7281 case llvm::Triple::wasm64:
7282 TC = std::make_unique<toolchains::WebAssembly>(args: *this, args: Target, args: Args);
7283 break;
7284 case llvm::Triple::avr:
7285 TC = std::make_unique<toolchains::AVRToolChain>(args: *this, args: Target, args: Args);
7286 break;
7287 case llvm::Triple::msp430:
7288 TC = std::make_unique<toolchains::MSP430ToolChain>(args: *this, args: Target, args: Args);
7289 break;
7290 case llvm::Triple::riscv32:
7291 case llvm::Triple::riscv64:
7292 case llvm::Triple::riscv32be:
7293 case llvm::Triple::riscv64be:
7294 TC = std::make_unique<toolchains::BareMetal>(args: *this, args: Target, args: Args);
7295 break;
7296 case llvm::Triple::ve:
7297 TC = std::make_unique<toolchains::VEToolChain>(args: *this, args: Target, args: Args);
7298 break;
7299 case llvm::Triple::spirv32:
7300 case llvm::Triple::spirv64:
7301 TC = std::make_unique<toolchains::SPIRVToolChain>(args: *this, args: Target, args: Args);
7302 break;
7303 case llvm::Triple::csky:
7304 TC = std::make_unique<toolchains::CSKYToolChain>(args: *this, args: Target, args: Args);
7305 break;
7306 case llvm::Triple::amdgpu:
7307 case llvm::Triple::r600:
7308 TC = std::make_unique<toolchains::AMDGPUToolChain>(args: *this, args: Target, args: Args);
7309 break;
7310 default:
7311 if (toolchains::BareMetal::handlesTarget(Triple: Target))
7312 TC = std::make_unique<toolchains::BareMetal>(args: *this, args: Target, args: Args);
7313 else if (Target.isOSBinFormatELF())
7314 TC = std::make_unique<toolchains::Generic_ELF>(args: *this, args: Target, args: Args);
7315 else if (Target.isAppleFirmware())
7316 TC = std::make_unique<toolchains::DarwinClang>(args: *this, args: Target, args: Args);
7317 else if (Target.isAppleMachO())
7318 TC = std::make_unique<toolchains::AppleMachO>(args: *this, args: Target, args: Args);
7319 else if (Target.isOSBinFormatMachO())
7320 TC = std::make_unique<toolchains::MachO>(args: *this, args: Target, args: Args);
7321 else
7322 TC = std::make_unique<toolchains::Generic_GCC>(args: *this, args: Target, args: Args);
7323 }
7324 }
7325 }
7326
7327 return *TC;
7328}
7329
7330bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
7331 // Say "no" if there is not exactly one input of a type clang understands.
7332 if (JA.size() != 1 ||
7333 !types::isAcceptedByClang(Id: (*JA.input_begin())->getType()))
7334 return false;
7335
7336 // And say "no" if this is not a kind of action clang understands.
7337 if (!isa<PreprocessJobAction>(Val: JA) && !isa<PrecompileJobAction>(Val: JA) &&
7338 !isa<CompileJobAction>(Val: JA) && !isa<BackendJobAction>(Val: JA) &&
7339 !isa<ExtractAPIJobAction>(Val: JA))
7340 return false;
7341
7342 return true;
7343}
7344
7345bool Driver::ShouldUseFlangCompiler(const JobAction &JA) const {
7346 // Say "no" if there is not exactly one input of a type flang understands.
7347 if (JA.size() != 1 ||
7348 !types::isAcceptedByFlang(Id: (*JA.input_begin())->getType()))
7349 return false;
7350
7351 // And say "no" if this is not a kind of action flang understands.
7352 if (!isa<PreprocessJobAction>(Val: JA) && !isa<PrecompileJobAction>(Val: JA) &&
7353 !isa<CompileJobAction>(Val: JA) && !isa<BackendJobAction>(Val: JA))
7354 return false;
7355
7356 return true;
7357}
7358
7359bool Driver::ShouldEmitStaticLibrary(const ArgList &Args) const {
7360 // Only emit static library if the flag is set explicitly.
7361 if (Args.hasArg(Ids: options::OPT_emit_static_lib))
7362 return true;
7363 return false;
7364}
7365
7366/// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
7367/// grouped values as integers. Numbers which are not provided are set to 0.
7368///
7369/// \return True if the entire string was parsed (9.2), or all groups were
7370/// parsed (10.3.5extrastuff).
7371bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
7372 unsigned &Micro, bool &HadExtra) {
7373 HadExtra = false;
7374
7375 Major = Minor = Micro = 0;
7376 if (Str.empty())
7377 return false;
7378
7379 if (Str.consumeInteger(Radix: 10, Result&: Major))
7380 return false;
7381 if (Str.empty())
7382 return true;
7383 if (!Str.consume_front(Prefix: "."))
7384 return false;
7385
7386 if (Str.consumeInteger(Radix: 10, Result&: Minor))
7387 return false;
7388 if (Str.empty())
7389 return true;
7390 if (!Str.consume_front(Prefix: "."))
7391 return false;
7392
7393 if (Str.consumeInteger(Radix: 10, Result&: Micro))
7394 return false;
7395 if (!Str.empty())
7396 HadExtra = true;
7397 return true;
7398}
7399
7400/// Parse digits from a string \p Str and fulfill \p Digits with
7401/// the parsed numbers. This method assumes that the max number of
7402/// digits to look for is equal to Digits.size().
7403///
7404/// \return True if the entire string was parsed and there are
7405/// no extra characters remaining at the end.
7406bool Driver::GetReleaseVersion(StringRef Str,
7407 MutableArrayRef<unsigned> Digits) {
7408 if (Str.empty())
7409 return false;
7410
7411 unsigned CurDigit = 0;
7412 while (CurDigit < Digits.size()) {
7413 unsigned Digit;
7414 if (Str.consumeInteger(Radix: 10, Result&: Digit))
7415 return false;
7416 Digits[CurDigit] = Digit;
7417 if (Str.empty())
7418 return true;
7419 if (!Str.consume_front(Prefix: "."))
7420 return false;
7421 CurDigit++;
7422 }
7423
7424 // More digits than requested, bail out...
7425 return false;
7426}
7427
7428llvm::opt::Visibility
7429Driver::getOptionVisibilityMask(bool UseDriverMode) const {
7430 if (!UseDriverMode)
7431 return llvm::opt::Visibility(options::ClangOption);
7432 if (IsCLMode())
7433 return llvm::opt::Visibility(options::CLOption);
7434 if (IsDXCMode())
7435 return llvm::opt::Visibility(options::DXCOption);
7436 if (IsFlangMode())
7437 return llvm::opt::Visibility(options::FlangOption);
7438 return llvm::opt::Visibility(options::ClangOption);
7439}
7440
7441const char *Driver::getExecutableForDriverMode(DriverMode Mode) {
7442 switch (Mode) {
7443 case GCCMode:
7444 return "clang";
7445 case GXXMode:
7446 return "clang++";
7447 case CPPMode:
7448 return "clang-cpp";
7449 case CLMode:
7450 return "clang-cl";
7451 case FlangMode:
7452 return "flang";
7453 case DXCMode:
7454 return "clang-dxc";
7455 }
7456
7457 llvm_unreachable("Unhandled Mode");
7458}
7459
7460bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
7461 return Args.hasFlag(Pos: options::OPT_Ofast, Neg: options::OPT_O_Group, Default: false);
7462}
7463
7464bool clang::driver::willEmitRemarks(const ArgList &Args) {
7465 // -fsave-optimization-record enables it.
7466 if (Args.hasFlag(Pos: options::OPT_fsave_optimization_record,
7467 Neg: options::OPT_fno_save_optimization_record, Default: false))
7468 return true;
7469
7470 // -fsave-optimization-record=<format> enables it as well.
7471 if (Args.hasFlag(Pos: options::OPT_fsave_optimization_record_EQ,
7472 Neg: options::OPT_fno_save_optimization_record, Default: false))
7473 return true;
7474
7475 // -foptimization-record-file alone enables it too.
7476 if (Args.hasFlag(Pos: options::OPT_foptimization_record_file_EQ,
7477 Neg: options::OPT_fno_save_optimization_record, Default: false))
7478 return true;
7479
7480 // -foptimization-record-passes alone enables it too.
7481 if (Args.hasFlag(Pos: options::OPT_foptimization_record_passes_EQ,
7482 Neg: options::OPT_fno_save_optimization_record, Default: false))
7483 return true;
7484 return false;
7485}
7486
7487llvm::StringRef clang::driver::getDriverMode(StringRef ProgName,
7488 ArrayRef<const char *> Args) {
7489 static StringRef OptName =
7490 getDriverOptTable().getOption(Opt: options::OPT_driver_mode).getPrefixedName();
7491 llvm::StringRef Opt;
7492 for (StringRef Arg : Args) {
7493 if (!Arg.starts_with(Prefix: OptName))
7494 continue;
7495 Opt = Arg;
7496 }
7497 if (Opt.empty())
7498 Opt = ToolChain::getTargetAndModeFromProgramName(ProgName).DriverMode;
7499 return Opt.consume_front(Prefix: OptName) ? Opt : "";
7500}
7501
7502bool driver::IsClangCL(StringRef DriverMode) { return DriverMode == "cl"; }
7503
7504llvm::Error driver::expandResponseFiles(SmallVectorImpl<const char *> &Args,
7505 bool ClangCLMode,
7506 llvm::BumpPtrAllocator &Alloc,
7507 llvm::vfs::FileSystem *FS) {
7508 // Parse response files using the GNU syntax, unless we're in CL mode. There
7509 // are two ways to put clang in CL compatibility mode: ProgName is either
7510 // clang-cl or cl, or --driver-mode=cl is on the command line. The normal
7511 // command line parsing can't happen until after response file parsing, so we
7512 // have to manually search for a --driver-mode=cl argument the hard way.
7513 // Finally, our -cc1 tools don't care which tokenization mode we use because
7514 // response files written by clang will tokenize the same way in either mode.
7515 enum { Default, POSIX, Windows } RSPQuoting = Default;
7516 for (const char *F : Args) {
7517 if (strcmp(s1: F, s2: "--rsp-quoting=posix") == 0)
7518 RSPQuoting = POSIX;
7519 else if (strcmp(s1: F, s2: "--rsp-quoting=windows") == 0)
7520 RSPQuoting = Windows;
7521 }
7522
7523 // Determines whether we want nullptr markers in Args to indicate response
7524 // files end-of-lines. We only use this for the /LINK driver argument with
7525 // clang-cl.exe on Windows.
7526 bool MarkEOLs = ClangCLMode;
7527
7528 llvm::cl::TokenizerCallback Tokenizer;
7529 if (RSPQuoting == Windows || (RSPQuoting == Default && ClangCLMode))
7530 Tokenizer = &llvm::cl::TokenizeWindowsCommandLine;
7531 else
7532 Tokenizer = &llvm::cl::TokenizeGNUCommandLine;
7533
7534 if (MarkEOLs && Args.size() > 1 && StringRef(Args[1]).starts_with(Prefix: "-cc1"))
7535 MarkEOLs = false;
7536
7537 llvm::cl::ExpansionContext ECtx(Alloc, Tokenizer);
7538 ECtx.setMarkEOLs(MarkEOLs);
7539 if (FS)
7540 ECtx.setVFS(FS);
7541
7542 if (llvm::Error Err = ECtx.expandResponseFiles(Argv&: Args))
7543 return Err;
7544
7545 // If -cc1 came from a response file, remove the EOL sentinels.
7546 auto FirstArg = llvm::find_if(Range: llvm::drop_begin(RangeOrContainer&: Args),
7547 P: [](const char *A) { return A != nullptr; });
7548 if (FirstArg != Args.end() && StringRef(*FirstArg).starts_with(Prefix: "-cc1")) {
7549 // If -cc1 came from a response file, remove the EOL sentinels.
7550 if (MarkEOLs) {
7551 auto newEnd = std::remove(first: Args.begin(), last: Args.end(), value: nullptr);
7552 Args.resize(N: newEnd - Args.begin());
7553 }
7554 }
7555
7556 return llvm::Error::success();
7557}
7558
7559static const char *GetStableCStr(llvm::StringSet<> &SavedStrings, StringRef S) {
7560 return SavedStrings.insert(key: S).first->getKeyData();
7561}
7562
7563/// Apply a list of edits to the input argument lists.
7564///
7565/// The input string is a space separated list of edits to perform,
7566/// they are applied in order to the input argument lists. Edits
7567/// should be one of the following forms:
7568///
7569/// '#': Silence information about the changes to the command line arguments.
7570///
7571/// '^FOO': Add FOO as a new argument at the beginning of the command line
7572/// right after the name of the compiler executable.
7573///
7574/// '+FOO': Add FOO as a new argument at the end of the command line.
7575///
7576/// 's/XXX/YYY/': Substitute the regular expression XXX with YYY in the command
7577/// line.
7578///
7579/// 'xOPTION': Removes all instances of the literal argument OPTION.
7580///
7581/// 'XOPTION': Removes all instances of the literal argument OPTION,
7582/// and the following argument.
7583///
7584/// 'Ox': Removes all flags matching 'O' or 'O[sz0-9]' and adds 'Ox'
7585/// at the end of the command line.
7586///
7587/// \param OS - The stream to write edit information to.
7588/// \param Args - The vector of command line arguments.
7589/// \param Edit - The override command to perform.
7590/// \param SavedStrings - Set to use for storing string representations.
7591static void applyOneOverrideOption(raw_ostream &OS,
7592 SmallVectorImpl<const char *> &Args,
7593 StringRef Edit,
7594 llvm::StringSet<> &SavedStrings) {
7595 // This does not need to be efficient.
7596
7597 if (Edit[0] == '^') {
7598 const char *Str = GetStableCStr(SavedStrings, S: Edit.substr(Start: 1));
7599 OS << "### Adding argument " << Str << " at beginning\n";
7600 Args.insert(I: Args.begin() + 1, Elt: Str);
7601 } else if (Edit[0] == '+') {
7602 const char *Str = GetStableCStr(SavedStrings, S: Edit.substr(Start: 1));
7603 OS << "### Adding argument " << Str << " at end\n";
7604 Args.push_back(Elt: Str);
7605 } else if (Edit[0] == 's' && Edit[1] == '/' && Edit.ends_with(Suffix: "/") &&
7606 Edit.slice(Start: 2, End: Edit.size() - 1).contains(C: '/')) {
7607 StringRef MatchPattern = Edit.substr(Start: 2).split(Separator: '/').first;
7608 StringRef ReplPattern = Edit.substr(Start: 2).split(Separator: '/').second;
7609 ReplPattern = ReplPattern.slice(Start: 0, End: ReplPattern.size() - 1);
7610
7611 for (unsigned i = 1, e = Args.size(); i != e; ++i) {
7612 // Ignore end-of-line response file markers
7613 if (Args[i] == nullptr)
7614 continue;
7615 std::string Repl = llvm::Regex(MatchPattern).sub(Repl: ReplPattern, String: Args[i]);
7616
7617 if (Repl != Args[i]) {
7618 OS << "### Replacing '" << Args[i] << "' with '" << Repl << "'\n";
7619 Args[i] = GetStableCStr(SavedStrings, S: Repl);
7620 }
7621 }
7622 } else if (Edit[0] == 'x' || Edit[0] == 'X') {
7623 auto Option = Edit.substr(Start: 1);
7624 for (unsigned i = 1; i < Args.size();) {
7625 if (Option == Args[i]) {
7626 OS << "### Deleting argument " << Args[i] << '\n';
7627 Args.erase(CI: Args.begin() + i);
7628 if (Edit[0] == 'X') {
7629 if (i < Args.size()) {
7630 OS << "### Deleting argument " << Args[i] << '\n';
7631 Args.erase(CI: Args.begin() + i);
7632 } else
7633 OS << "### Invalid X edit, end of command line!\n";
7634 }
7635 } else
7636 ++i;
7637 }
7638 } else if (Edit[0] == 'O') {
7639 for (unsigned i = 1; i < Args.size();) {
7640 const char *A = Args[i];
7641 // Ignore end-of-line response file markers
7642 if (A == nullptr)
7643 continue;
7644 if (A[0] == '-' && A[1] == 'O' &&
7645 (A[2] == '\0' || (A[3] == '\0' && (A[2] == 's' || A[2] == 'z' ||
7646 ('0' <= A[2] && A[2] <= '9'))))) {
7647 OS << "### Deleting argument " << Args[i] << '\n';
7648 Args.erase(CI: Args.begin() + i);
7649 } else
7650 ++i;
7651 }
7652 OS << "### Adding argument " << Edit << " at end\n";
7653 Args.push_back(Elt: GetStableCStr(SavedStrings, S: '-' + Edit.str()));
7654 } else {
7655 OS << "### Unrecognized edit: " << Edit << "\n";
7656 }
7657}
7658
7659void driver::applyOverrideOptions(SmallVectorImpl<const char *> &Args,
7660 const char *OverrideStr,
7661 llvm::StringSet<> &SavedStrings,
7662 StringRef EnvVar, raw_ostream *OS) {
7663 if (!OS)
7664 OS = &llvm::nulls();
7665
7666 if (OverrideStr[0] == '#') {
7667 ++OverrideStr;
7668 OS = &llvm::nulls();
7669 }
7670
7671 *OS << "### " << EnvVar << ": " << OverrideStr << "\n";
7672
7673 // This does not need to be efficient.
7674
7675 const char *S = OverrideStr;
7676 while (*S) {
7677 const char *End = ::strchr(s: S, c: ' ');
7678 if (!End)
7679 End = S + strlen(s: S);
7680 if (End != S)
7681 applyOneOverrideOption(OS&: *OS, Args, Edit: std::string(S, End), SavedStrings);
7682 S = End;
7683 if (*S != '\0')
7684 ++S;
7685 }
7686}
7687