1//===--- Driver.h - Clang GCC Compatible Driver -----------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#ifndef LLVM_CLANG_DRIVER_DRIVER_H
10#define LLVM_CLANG_DRIVER_DRIVER_H
11
12#include "clang/Basic/Diagnostic.h"
13#include "clang/Basic/HeaderInclude.h"
14#include "clang/Basic/LLVM.h"
15#include "clang/Driver/Action.h"
16#include "clang/Driver/DriverDiagnostic.h"
17#include "clang/Driver/InputInfo.h"
18#include "clang/Driver/Options.h"
19#include "clang/Driver/Phases.h"
20#include "clang/Driver/ToolChain.h"
21#include "clang/Driver/Types.h"
22#include "clang/Driver/Util.h"
23#include "llvm/ADT/ArrayRef.h"
24#include "llvm/ADT/STLFunctionalExtras.h"
25#include "llvm/ADT/StringMap.h"
26#include "llvm/ADT/StringRef.h"
27#include "llvm/Option/Arg.h"
28#include "llvm/Option/ArgList.h"
29#include "llvm/Support/StringSaver.h"
30
31#include <list>
32#include <map>
33#include <string>
34#include <vector>
35
36namespace llvm {
37class Triple;
38namespace vfs {
39class FileSystem;
40}
41namespace cl {
42class ExpansionContext;
43}
44} // namespace llvm
45
46namespace clang {
47
48namespace driver {
49
50typedef SmallVector<InputInfo, 4> InputInfoList;
51
52class Command;
53class Compilation;
54class JobAction;
55class ToolChain;
56
57/// Describes the kind of LTO mode selected via -f(no-)?lto(=.*)? options.
58enum LTOKind {
59 LTOK_None,
60 LTOK_Full,
61 LTOK_Thin,
62 LTOK_Unknown
63};
64
65/// Whether headers used to construct C++20 module units should be looked
66/// up by the path supplied on the command line, or in the user or system
67/// search paths.
68enum ModuleHeaderMode {
69 HeaderMode_None,
70 HeaderMode_Default,
71 HeaderMode_User,
72 HeaderMode_System
73};
74
75/// Driver - Encapsulate logic for constructing compilation processes
76/// from a set of gcc-driver-like command line arguments.
77class Driver {
78 DiagnosticsEngine &Diags;
79
80 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS;
81
82 enum DriverMode {
83 GCCMode,
84 GXXMode,
85 CPPMode,
86 CLMode,
87 FlangMode,
88 DXCMode
89 } Mode;
90
91 enum SaveTempsMode {
92 SaveTempsNone,
93 SaveTempsCwd,
94 SaveTempsObj
95 } SaveTemps;
96
97 enum BitcodeEmbedMode {
98 EmbedNone,
99 EmbedMarker,
100 EmbedBitcode
101 } BitcodeEmbed;
102
103 enum OffloadMode {
104 OffloadHostDevice,
105 OffloadHost,
106 OffloadDevice,
107 } Offload;
108
109 /// Header unit mode set by -fmodule-header={user,system}.
110 ModuleHeaderMode CXX20HeaderType;
111
112 /// Set if we should process inputs and jobs with C++20 module
113 /// interpretation.
114 bool ModulesModeCXX20;
115
116 /// LTO mode selected via -f(no-)?lto(=.*)? options.
117 LTOKind LTOMode;
118
119 /// LTO mode selected via -f(no-offload-)?lto(=.*)? options.
120 LTOKind OffloadLTOMode;
121
122public:
123 enum OpenMPRuntimeKind {
124 /// An unknown OpenMP runtime. We can't generate effective OpenMP code
125 /// without knowing what runtime to target.
126 OMPRT_Unknown,
127
128 /// The LLVM OpenMP runtime. When completed and integrated, this will become
129 /// the default for Clang.
130 OMPRT_OMP,
131
132 /// The GNU OpenMP runtime. Clang doesn't support generating OpenMP code for
133 /// this runtime but can swallow the pragmas, and find and link against the
134 /// runtime library itself.
135 OMPRT_GOMP,
136
137 /// The legacy name for the LLVM OpenMP runtime from when it was the Intel
138 /// OpenMP runtime. We support this mode for users with existing
139 /// dependencies on this runtime library name.
140 OMPRT_IOMP5
141 };
142
143 // Diag - Forwarding function for diagnostics.
144 DiagnosticBuilder Diag(unsigned DiagID) const {
145 return Diags.Report(DiagID);
146 }
147
148 // FIXME: Privatize once interface is stable.
149public:
150 /// The name the driver was invoked as.
151 std::string Name;
152
153 /// The path the driver executable was in, as invoked from the
154 /// command line.
155 std::string Dir;
156
157 /// The original path to the clang executable.
158 std::string ClangExecutable;
159
160 /// Target and driver mode components extracted from clang executable name.
161 ParsedClangName ClangNameParts;
162
163 /// The path to the installed clang directory, if any.
164 std::string InstalledDir;
165
166 /// The path to the compiler resource directory.
167 std::string ResourceDir;
168
169 /// System directory for config files.
170 std::string SystemConfigDir;
171
172 /// User directory for config files.
173 std::string UserConfigDir;
174
175 /// A prefix directory used to emulate a limited subset of GCC's '-Bprefix'
176 /// functionality.
177 /// FIXME: This type of customization should be removed in favor of the
178 /// universal driver when it is ready.
179 typedef SmallVector<std::string, 4> prefix_list;
180 prefix_list PrefixDirs;
181
182 /// sysroot, if present
183 std::string SysRoot;
184
185 /// Dynamic loader prefix, if present
186 std::string DyldPrefix;
187
188 /// Driver title to use with help.
189 std::string DriverTitle;
190
191 /// Information about the host which can be overridden by the user.
192 std::string HostBits, HostMachine, HostSystem, HostRelease;
193
194 /// The file to log CC_PRINT_PROC_STAT_FILE output to, if enabled.
195 std::string CCPrintStatReportFilename;
196
197 /// The file to log CC_PRINT_INTERNAL_STAT_FILE output to, if enabled.
198 std::string CCPrintInternalStatReportFilename;
199
200 /// The file to log CC_PRINT_OPTIONS output to, if enabled.
201 std::string CCPrintOptionsFilename;
202
203 /// The file to log CC_PRINT_HEADERS output to, if enabled.
204 std::string CCPrintHeadersFilename;
205
206 /// The file to log CC_LOG_DIAGNOSTICS output to, if enabled.
207 std::string CCLogDiagnosticsFilename;
208
209 /// An input type and its arguments.
210 using InputTy = std::pair<types::ID, const llvm::opt::Arg *>;
211
212 /// A list of inputs and their types for the given arguments.
213 using InputList = SmallVector<InputTy, 16>;
214
215 /// Whether the driver should follow g++ like behavior.
216 bool CCCIsCXX() const { return Mode == GXXMode; }
217
218 /// Whether the driver is just the preprocessor.
219 bool CCCIsCPP() const { return Mode == CPPMode; }
220
221 /// Whether the driver should follow gcc like behavior.
222 bool CCCIsCC() const { return Mode == GCCMode; }
223
224 /// Whether the driver should follow cl.exe like behavior.
225 bool IsCLMode() const { return Mode == CLMode; }
226
227 /// Whether the driver should invoke flang for fortran inputs.
228 /// Other modes fall back to calling gcc which in turn calls gfortran.
229 bool IsFlangMode() const { return Mode == FlangMode; }
230
231 /// Whether the driver should follow dxc.exe like behavior.
232 bool IsDXCMode() const { return Mode == DXCMode; }
233
234 /// Only print tool bindings, don't build any jobs.
235 LLVM_PREFERRED_TYPE(bool)
236 unsigned CCCPrintBindings : 1;
237
238 /// Set CC_PRINT_OPTIONS mode, which is like -v but logs the commands to
239 /// CCPrintOptionsFilename or to stderr.
240 LLVM_PREFERRED_TYPE(bool)
241 unsigned CCPrintOptions : 1;
242
243 /// The format of the header information that is emitted. If CC_PRINT_HEADERS
244 /// is set, the format is textual. Otherwise, the format is determined by the
245 /// enviroment variable CC_PRINT_HEADERS_FORMAT.
246 HeaderIncludeFormatKind CCPrintHeadersFormat = HIFMT_None;
247
248 /// This flag determines whether clang should filter the header information
249 /// that is emitted. If enviroment variable CC_PRINT_HEADERS_FILTERING is set
250 /// to "only-direct-system", only system headers that are directly included
251 /// from non-system headers are emitted.
252 HeaderIncludeFilteringKind CCPrintHeadersFiltering = HIFIL_None;
253
254 /// Set CC_LOG_DIAGNOSTICS mode, which causes the frontend to log diagnostics
255 /// to CCLogDiagnosticsFilename or to stderr, in a stable machine readable
256 /// format.
257 LLVM_PREFERRED_TYPE(bool)
258 unsigned CCLogDiagnostics : 1;
259
260 /// Whether the driver is generating diagnostics for debugging purposes.
261 LLVM_PREFERRED_TYPE(bool)
262 unsigned CCGenDiagnostics : 1;
263
264 /// Set CC_PRINT_PROC_STAT mode, which causes the driver to dump
265 /// performance report to CC_PRINT_PROC_STAT_FILE or to stdout.
266 LLVM_PREFERRED_TYPE(bool)
267 unsigned CCPrintProcessStats : 1;
268
269 /// Set CC_PRINT_INTERNAL_STAT mode, which causes the driver to dump internal
270 /// performance report to CC_PRINT_INTERNAL_STAT_FILE or to stdout.
271 LLVM_PREFERRED_TYPE(bool)
272 unsigned CCPrintInternalStats : 1;
273
274 /// Pointer to the ExecuteCC1Tool function, if available.
275 /// When the clangDriver lib is used through clang.exe, this provides a
276 /// shortcut for executing the -cc1 command-line directly, in the same
277 /// process.
278 using CC1ToolFunc =
279 llvm::function_ref<int(SmallVectorImpl<const char *> &ArgV)>;
280 CC1ToolFunc CC1Main = nullptr;
281
282private:
283 /// Raw target triple.
284 std::string TargetTriple;
285
286 /// Name to use when invoking gcc/g++.
287 std::string CCCGenericGCCName;
288
289 /// Paths to configuration files used.
290 std::vector<std::string> ConfigFiles;
291
292 /// Allocator for string saver.
293 llvm::BumpPtrAllocator Alloc;
294
295 /// Object that stores strings read from configuration file.
296 llvm::StringSaver Saver;
297
298 /// Arguments originated from configuration file.
299 std::unique_ptr<llvm::opt::InputArgList> CfgOptions;
300
301 /// Arguments originated from command line.
302 std::unique_ptr<llvm::opt::InputArgList> CLOptions;
303
304 /// If this is non-null, the driver will prepend this argument before
305 /// reinvoking clang. This is useful for the llvm-driver where clang's
306 /// realpath will be to the llvm binary and not clang, so it must pass
307 /// "clang" as it's first argument.
308 const char *PrependArg;
309
310 /// Whether to check that input files exist when constructing compilation
311 /// jobs.
312 LLVM_PREFERRED_TYPE(bool)
313 unsigned CheckInputsExist : 1;
314 /// Whether to probe for PCH files on disk, in order to upgrade
315 /// -include foo.h to -include-pch foo.h.pch.
316 LLVM_PREFERRED_TYPE(bool)
317 unsigned ProbePrecompiled : 1;
318
319public:
320 // getFinalPhase - Determine which compilation mode we are in and record
321 // which option we used to determine the final phase.
322 // TODO: Much of what getFinalPhase returns are not actually true compiler
323 // modes. Fold this functionality into Types::getCompilationPhases and
324 // handleArguments.
325 phases::ID getFinalPhase(const llvm::opt::DerivedArgList &DAL,
326 llvm::opt::Arg **FinalPhaseArg = nullptr) const;
327
328private:
329 /// Certain options suppress the 'no input files' warning.
330 LLVM_PREFERRED_TYPE(bool)
331 unsigned SuppressMissingInputWarning : 1;
332
333 /// Cache of all the ToolChains in use by the driver.
334 ///
335 /// This maps from the string representation of a triple to a ToolChain
336 /// created targeting that triple. The driver owns all the ToolChain objects
337 /// stored in it, and will clean them up when torn down.
338 mutable llvm::StringMap<std::unique_ptr<ToolChain>> ToolChains;
339
340 /// Cache of known offloading architectures for the ToolChain already derived.
341 /// This should only be modified when we first initialize the offloading
342 /// toolchains.
343 llvm::DenseMap<const ToolChain *, llvm::DenseSet<llvm::StringRef>> KnownArchs;
344
345private:
346 /// TranslateInputArgs - Create a new derived argument list from the input
347 /// arguments, after applying the standard argument translations.
348 llvm::opt::DerivedArgList *
349 TranslateInputArgs(const llvm::opt::InputArgList &Args) const;
350
351 // handleArguments - All code related to claiming and printing diagnostics
352 // related to arguments to the driver are done here.
353 void handleArguments(Compilation &C, llvm::opt::DerivedArgList &Args,
354 const InputList &Inputs, ActionList &Actions) const;
355
356 // Before executing jobs, sets up response files for commands that need them.
357 void setUpResponseFiles(Compilation &C, Command &Cmd);
358
359 void generatePrefixedToolNames(StringRef Tool, const ToolChain &TC,
360 SmallVectorImpl<std::string> &Names) const;
361
362 /// Find the appropriate .crash diagonostic file for the child crash
363 /// under this driver and copy it out to a temporary destination with the
364 /// other reproducer related files (.sh, .cache, etc). If not found, suggest a
365 /// directory for the user to look at.
366 ///
367 /// \param ReproCrashFilename The file path to copy the .crash to.
368 /// \param CrashDiagDir The suggested directory for the user to look at
369 /// in case the search or copy fails.
370 ///
371 /// \returns If the .crash is found and successfully copied return true,
372 /// otherwise false and return the suggested directory in \p CrashDiagDir.
373 bool getCrashDiagnosticFile(StringRef ReproCrashFilename,
374 SmallString<128> &CrashDiagDir);
375
376public:
377
378 /// Takes the path to a binary that's either in bin/ or lib/ and returns
379 /// the path to clang's resource directory.
380 static std::string GetResourcesPath(StringRef BinaryPath,
381 StringRef CustomResourceDir = "");
382
383 Driver(StringRef ClangExecutable, StringRef TargetTriple,
384 DiagnosticsEngine &Diags, std::string Title = "clang LLVM compiler",
385 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS = nullptr);
386
387 /// @name Accessors
388 /// @{
389
390 /// Name to use when invoking gcc/g++.
391 const std::string &getCCCGenericGCCName() const { return CCCGenericGCCName; }
392
393 llvm::ArrayRef<std::string> getConfigFiles() const {
394 return ConfigFiles;
395 }
396
397 const llvm::opt::OptTable &getOpts() const { return getDriverOptTable(); }
398
399 DiagnosticsEngine &getDiags() const { return Diags; }
400
401 llvm::vfs::FileSystem &getVFS() const { return *VFS; }
402
403 bool getCheckInputsExist() const { return CheckInputsExist; }
404
405 void setCheckInputsExist(bool Value) { CheckInputsExist = Value; }
406
407 bool getProbePrecompiled() const { return ProbePrecompiled; }
408 void setProbePrecompiled(bool Value) { ProbePrecompiled = Value; }
409
410 const char *getPrependArg() const { return PrependArg; }
411 void setPrependArg(const char *Value) { PrependArg = Value; }
412
413 void setTargetAndMode(const ParsedClangName &TM) { ClangNameParts = TM; }
414
415 const std::string &getTitle() { return DriverTitle; }
416 void setTitle(std::string Value) { DriverTitle = std::move(Value); }
417
418 std::string getTargetTriple() const { return TargetTriple; }
419
420 /// Get the path to the main clang executable.
421 const char *getClangProgramPath() const {
422 return ClangExecutable.c_str();
423 }
424
425 /// Get the path to where the clang executable was installed.
426 const char *getInstalledDir() const {
427 if (!InstalledDir.empty())
428 return InstalledDir.c_str();
429 return Dir.c_str();
430 }
431 void setInstalledDir(StringRef Value) { InstalledDir = std::string(Value); }
432
433 bool isSaveTempsEnabled() const { return SaveTemps != SaveTempsNone; }
434 bool isSaveTempsObj() const { return SaveTemps == SaveTempsObj; }
435
436 bool embedBitcodeEnabled() const { return BitcodeEmbed != EmbedNone; }
437 bool embedBitcodeInObject() const { return (BitcodeEmbed == EmbedBitcode); }
438 bool embedBitcodeMarkerOnly() const { return (BitcodeEmbed == EmbedMarker); }
439
440 bool offloadHostOnly() const { return Offload == OffloadHost; }
441 bool offloadDeviceOnly() const { return Offload == OffloadDevice; }
442
443 /// Compute the desired OpenMP runtime from the flags provided.
444 OpenMPRuntimeKind getOpenMPRuntime(const llvm::opt::ArgList &Args) const;
445
446 /// @}
447 /// @name Primary Functionality
448 /// @{
449
450 /// CreateOffloadingDeviceToolChains - create all the toolchains required to
451 /// support offloading devices given the programming models specified in the
452 /// current compilation. Also, update the host tool chain kind accordingly.
453 void CreateOffloadingDeviceToolChains(Compilation &C, InputList &Inputs);
454
455 /// BuildCompilation - Construct a compilation object for a command
456 /// line argument vector.
457 ///
458 /// \return A compilation, or 0 if none was built for the given
459 /// argument vector. A null return value does not necessarily
460 /// indicate an error condition, the diagnostics should be queried
461 /// to determine if an error occurred.
462 Compilation *BuildCompilation(ArrayRef<const char *> Args);
463
464 /// ParseArgStrings - Parse the given list of strings into an
465 /// ArgList.
466 llvm::opt::InputArgList ParseArgStrings(ArrayRef<const char *> Args,
467 bool UseDriverMode,
468 bool &ContainsError);
469
470 /// BuildInputs - Construct the list of inputs and their types from
471 /// the given arguments.
472 ///
473 /// \param TC - The default host tool chain.
474 /// \param Args - The input arguments.
475 /// \param Inputs - The list to store the resulting compilation
476 /// inputs onto.
477 void BuildInputs(const ToolChain &TC, llvm::opt::DerivedArgList &Args,
478 InputList &Inputs) const;
479
480 /// BuildActions - Construct the list of actions to perform for the
481 /// given arguments, which are only done for a single architecture.
482 ///
483 /// \param C - The compilation that is being built.
484 /// \param Args - The input arguments.
485 /// \param Actions - The list to store the resulting actions onto.
486 void BuildActions(Compilation &C, llvm::opt::DerivedArgList &Args,
487 const InputList &Inputs, ActionList &Actions) const;
488
489 /// BuildUniversalActions - Construct the list of actions to perform
490 /// for the given arguments, which may require a universal build.
491 ///
492 /// \param C - The compilation that is being built.
493 /// \param TC - The default host tool chain.
494 void BuildUniversalActions(Compilation &C, const ToolChain &TC,
495 const InputList &BAInputs) const;
496
497 /// BuildOffloadingActions - Construct the list of actions to perform for the
498 /// offloading toolchain that will be embedded in the host.
499 ///
500 /// \param C - The compilation that is being built.
501 /// \param Args - The input arguments.
502 /// \param Input - The input type and arguments
503 /// \param HostAction - The host action used in the offloading toolchain.
504 Action *BuildOffloadingActions(Compilation &C,
505 llvm::opt::DerivedArgList &Args,
506 const InputTy &Input,
507 Action *HostAction) const;
508
509 /// Returns the set of bound architectures active for this offload kind.
510 /// If there are no bound architctures we return a set containing only the
511 /// empty string. The \p SuppressError option is used to suppress errors.
512 llvm::DenseSet<StringRef>
513 getOffloadArchs(Compilation &C, const llvm::opt::DerivedArgList &Args,
514 Action::OffloadKind Kind, const ToolChain *TC,
515 bool SuppressError = false) const;
516
517 /// Check that the file referenced by Value exists. If it doesn't,
518 /// issue a diagnostic and return false.
519 /// If TypoCorrect is true and the file does not exist, see if it looks
520 /// like a likely typo for a flag and if so print a "did you mean" blurb.
521 bool DiagnoseInputExistence(const llvm::opt::DerivedArgList &Args,
522 StringRef Value, types::ID Ty,
523 bool TypoCorrect) const;
524
525 /// BuildJobs - Bind actions to concrete tools and translate
526 /// arguments to form the list of jobs to run.
527 ///
528 /// \param C - The compilation that is being built.
529 void BuildJobs(Compilation &C) const;
530
531 /// ExecuteCompilation - Execute the compilation according to the command line
532 /// arguments and return an appropriate exit code.
533 ///
534 /// This routine handles additional processing that must be done in addition
535 /// to just running the subprocesses, for example reporting errors, setting
536 /// up response files, removing temporary files, etc.
537 int ExecuteCompilation(Compilation &C,
538 SmallVectorImpl< std::pair<int, const Command *> > &FailingCommands);
539
540 /// Contains the files in the compilation diagnostic report generated by
541 /// generateCompilationDiagnostics.
542 struct CompilationDiagnosticReport {
543 llvm::SmallVector<std::string, 4> TemporaryFiles;
544 };
545
546 /// generateCompilationDiagnostics - Generate diagnostics information
547 /// including preprocessed source file(s).
548 ///
549 void generateCompilationDiagnostics(
550 Compilation &C, const Command &FailingCommand,
551 StringRef AdditionalInformation = "",
552 CompilationDiagnosticReport *GeneratedReport = nullptr);
553
554 enum class CommandStatus {
555 Crash = 1,
556 Error,
557 Ok,
558 };
559
560 enum class ReproLevel {
561 Off = 0,
562 OnCrash = static_cast<int>(CommandStatus::Crash),
563 OnError = static_cast<int>(CommandStatus::Error),
564 Always = static_cast<int>(CommandStatus::Ok),
565 };
566
567 bool maybeGenerateCompilationDiagnostics(
568 CommandStatus CS, ReproLevel Level, Compilation &C,
569 const Command &FailingCommand, StringRef AdditionalInformation = "",
570 CompilationDiagnosticReport *GeneratedReport = nullptr) {
571 if (static_cast<int>(CS) > static_cast<int>(Level))
572 return false;
573 if (CS != CommandStatus::Crash)
574 Diags.Report(diag::err_drv_force_crash)
575 << !::getenv(name: "FORCE_CLANG_DIAGNOSTICS_CRASH");
576 // Hack to ensure that diagnostic notes get emitted.
577 Diags.setLastDiagnosticIgnored(false);
578 generateCompilationDiagnostics(C, FailingCommand, AdditionalInformation,
579 GeneratedReport);
580 return true;
581 }
582
583 /// @}
584 /// @name Helper Methods
585 /// @{
586
587 /// PrintActions - Print the list of actions.
588 void PrintActions(const Compilation &C) const;
589
590 /// PrintHelp - Print the help text.
591 ///
592 /// \param ShowHidden - Show hidden options.
593 void PrintHelp(bool ShowHidden) const;
594
595 /// PrintVersion - Print the driver version.
596 void PrintVersion(const Compilation &C, raw_ostream &OS) const;
597
598 /// GetFilePath - Lookup \p Name in the list of file search paths.
599 ///
600 /// \param TC - The tool chain for additional information on
601 /// directories to search.
602 //
603 // FIXME: This should be in CompilationInfo.
604 std::string GetFilePath(StringRef Name, const ToolChain &TC) const;
605
606 /// GetProgramPath - Lookup \p Name in the list of program search paths.
607 ///
608 /// \param TC - The provided tool chain for additional information on
609 /// directories to search.
610 //
611 // FIXME: This should be in CompilationInfo.
612 std::string GetProgramPath(StringRef Name, const ToolChain &TC) const;
613
614 /// HandleAutocompletions - Handle --autocomplete by searching and printing
615 /// possible flags, descriptions, and its arguments.
616 void HandleAutocompletions(StringRef PassedFlags) const;
617
618 /// HandleImmediateArgs - Handle any arguments which should be
619 /// treated before building actions or binding tools.
620 ///
621 /// \return Whether any compilation should be built for this
622 /// invocation.
623 bool HandleImmediateArgs(const Compilation &C);
624
625 /// ConstructAction - Construct the appropriate action to do for
626 /// \p Phase on the \p Input, taking in to account arguments
627 /// like -fsyntax-only or --analyze.
628 Action *ConstructPhaseAction(
629 Compilation &C, const llvm::opt::ArgList &Args, phases::ID Phase,
630 Action *Input,
631 Action::OffloadKind TargetDeviceOffloadKind = Action::OFK_None) const;
632
633 /// BuildJobsForAction - Construct the jobs to perform for the action \p A and
634 /// return an InputInfo for the result of running \p A. Will only construct
635 /// jobs for a given (Action, ToolChain, BoundArch, DeviceKind) tuple once.
636 InputInfoList BuildJobsForAction(
637 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
638 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
639 std::map<std::pair<const Action *, std::string>, InputInfoList>
640 &CachedResults,
641 Action::OffloadKind TargetDeviceOffloadKind) const;
642
643 /// Returns the default name for linked images (e.g., "a.out").
644 const char *getDefaultImageName() const;
645
646 /// Creates a temp file.
647 /// 1. If \p MultipleArch is false or \p BoundArch is empty, the temp file is
648 /// in the temporary directory with name $Prefix-%%%%%%.$Suffix.
649 /// 2. If \p MultipleArch is true and \p BoundArch is not empty,
650 /// 2a. If \p NeedUniqueDirectory is false, the temp file is in the
651 /// temporary directory with name $Prefix-$BoundArch-%%%%%.$Suffix.
652 /// 2b. If \p NeedUniqueDirectory is true, the temp file is in a unique
653 /// subdiretory with random name under the temporary directory, and
654 /// the temp file itself has name $Prefix-$BoundArch.$Suffix.
655 const char *CreateTempFile(Compilation &C, StringRef Prefix, StringRef Suffix,
656 bool MultipleArchs = false,
657 StringRef BoundArch = {},
658 bool NeedUniqueDirectory = false) const;
659
660 /// GetNamedOutputPath - Return the name to use for the output of
661 /// the action \p JA. The result is appended to the compilation's
662 /// list of temporary or result files, as appropriate.
663 ///
664 /// \param C - The compilation.
665 /// \param JA - The action of interest.
666 /// \param BaseInput - The original input file that this action was
667 /// triggered by.
668 /// \param BoundArch - The bound architecture.
669 /// \param AtTopLevel - Whether this is a "top-level" action.
670 /// \param MultipleArchs - Whether multiple -arch options were supplied.
671 /// \param NormalizedTriple - The normalized triple of the relevant target.
672 const char *GetNamedOutputPath(Compilation &C, const JobAction &JA,
673 const char *BaseInput, StringRef BoundArch,
674 bool AtTopLevel, bool MultipleArchs,
675 StringRef NormalizedTriple) const;
676
677 /// GetTemporaryPath - Return the pathname of a temporary file to use
678 /// as part of compilation; the file will have the given prefix and suffix.
679 ///
680 /// GCC goes to extra lengths here to be a bit more robust.
681 std::string GetTemporaryPath(StringRef Prefix, StringRef Suffix) const;
682
683 /// GetTemporaryDirectory - Return the pathname of a temporary directory to
684 /// use as part of compilation; the directory will have the given prefix.
685 std::string GetTemporaryDirectory(StringRef Prefix) const;
686
687 /// Return the pathname of the pch file in clang-cl mode.
688 std::string GetClPchPath(Compilation &C, StringRef BaseName) const;
689
690 /// ShouldUseClangCompiler - Should the clang compiler be used to
691 /// handle this action.
692 bool ShouldUseClangCompiler(const JobAction &JA) const;
693
694 /// ShouldUseFlangCompiler - Should the flang compiler be used to
695 /// handle this action.
696 bool ShouldUseFlangCompiler(const JobAction &JA) const;
697
698 /// ShouldEmitStaticLibrary - Should the linker emit a static library.
699 bool ShouldEmitStaticLibrary(const llvm::opt::ArgList &Args) const;
700
701 /// Returns true if the user has indicated a C++20 header unit mode.
702 bool hasHeaderMode() const { return CXX20HeaderType != HeaderMode_None; }
703
704 /// Get the mode for handling headers as set by fmodule-header{=}.
705 ModuleHeaderMode getModuleHeaderMode() const { return CXX20HeaderType; }
706
707 /// Returns true if we are performing any kind of LTO.
708 bool isUsingLTO(bool IsOffload = false) const {
709 return getLTOMode(IsOffload) != LTOK_None;
710 }
711
712 /// Get the specific kind of LTO being performed.
713 LTOKind getLTOMode(bool IsOffload = false) const {
714 return IsOffload ? OffloadLTOMode : LTOMode;
715 }
716
717private:
718
719 /// Tries to load options from configuration files.
720 ///
721 /// \returns true if error occurred.
722 bool loadConfigFiles();
723
724 /// Tries to load options from default configuration files (deduced from
725 /// executable filename).
726 ///
727 /// \returns true if error occurred.
728 bool loadDefaultConfigFiles(llvm::cl::ExpansionContext &ExpCtx);
729
730 /// Read options from the specified file.
731 ///
732 /// \param [in] FileName File to read.
733 /// \param [in] Search and expansion options.
734 /// \returns true, if error occurred while reading.
735 bool readConfigFile(StringRef FileName, llvm::cl::ExpansionContext &ExpCtx);
736
737 /// Set the driver mode (cl, gcc, etc) from the value of the `--driver-mode`
738 /// option.
739 void setDriverMode(StringRef DriverModeValue);
740
741 /// Parse the \p Args list for LTO options and record the type of LTO
742 /// compilation based on which -f(no-)?lto(=.*)? option occurs last.
743 void setLTOMode(const llvm::opt::ArgList &Args);
744
745 /// Retrieves a ToolChain for a particular \p Target triple.
746 ///
747 /// Will cache ToolChains for the life of the driver object, and create them
748 /// on-demand.
749 const ToolChain &getToolChain(const llvm::opt::ArgList &Args,
750 const llvm::Triple &Target) const;
751
752 /// @}
753
754 /// Retrieves a ToolChain for a particular device \p Target triple
755 ///
756 /// \param[in] HostTC is the host ToolChain paired with the device
757 ///
758 /// \param[in] TargetDeviceOffloadKind (e.g. OFK_Cuda/OFK_OpenMP/OFK_SYCL) is
759 /// an Offloading action that is optionally passed to a ToolChain (used by
760 /// CUDA, to specify if it's used in conjunction with OpenMP)
761 ///
762 /// Will cache ToolChains for the life of the driver object, and create them
763 /// on-demand.
764 const ToolChain &getOffloadingDeviceToolChain(
765 const llvm::opt::ArgList &Args, const llvm::Triple &Target,
766 const ToolChain &HostTC,
767 const Action::OffloadKind &TargetDeviceOffloadKind) const;
768
769 /// Get bitmasks for which option flags to include and exclude based on
770 /// the driver mode.
771 llvm::opt::Visibility
772 getOptionVisibilityMask(bool UseDriverMode = true) const;
773
774 /// Helper used in BuildJobsForAction. Doesn't use the cache when building
775 /// jobs specifically for the given action, but will use the cache when
776 /// building jobs for the Action's inputs.
777 InputInfoList BuildJobsForActionNoCache(
778 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
779 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
780 std::map<std::pair<const Action *, std::string>, InputInfoList>
781 &CachedResults,
782 Action::OffloadKind TargetDeviceOffloadKind) const;
783
784 /// Return the typical executable name for the specified driver \p Mode.
785 static const char *getExecutableForDriverMode(DriverMode Mode);
786
787public:
788 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and
789 /// return the grouped values as integers. Numbers which are not
790 /// provided are set to 0.
791 ///
792 /// \return True if the entire string was parsed (9.2), or all
793 /// groups were parsed (10.3.5extrastuff). HadExtra is true if all
794 /// groups were parsed but extra characters remain at the end.
795 static bool GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
796 unsigned &Micro, bool &HadExtra);
797
798 /// Parse digits from a string \p Str and fulfill \p Digits with
799 /// the parsed numbers. This method assumes that the max number of
800 /// digits to look for is equal to Digits.size().
801 ///
802 /// \return True if the entire string was parsed and there are
803 /// no extra characters remaining at the end.
804 static bool GetReleaseVersion(StringRef Str,
805 MutableArrayRef<unsigned> Digits);
806 /// Compute the default -fmodule-cache-path.
807 /// \return True if the system provides a default cache directory.
808 static bool getDefaultModuleCachePath(SmallVectorImpl<char> &Result);
809};
810
811/// \return True if the last defined optimization level is -Ofast.
812/// And False otherwise.
813bool isOptimizationLevelFast(const llvm::opt::ArgList &Args);
814
815/// \return True if the argument combination will end up generating remarks.
816bool willEmitRemarks(const llvm::opt::ArgList &Args);
817
818/// Returns the driver mode option's value, i.e. `X` in `--driver-mode=X`. If \p
819/// Args doesn't mention one explicitly, tries to deduce from `ProgName`.
820/// Returns empty on failure.
821/// Common values are "gcc", "g++", "cpp", "cl" and "flang". Returned value need
822/// not be one of these.
823llvm::StringRef getDriverMode(StringRef ProgName, ArrayRef<const char *> Args);
824
825/// Checks whether the value produced by getDriverMode is for CL mode.
826bool IsClangCL(StringRef DriverMode);
827
828/// Expand response files from a clang driver or cc1 invocation.
829///
830/// \param Args The arguments that will be expanded.
831/// \param ClangCLMode Whether clang is in CL mode.
832/// \param Alloc Allocator for new arguments.
833/// \param FS Filesystem to use when expanding files.
834llvm::Error expandResponseFiles(SmallVectorImpl<const char *> &Args,
835 bool ClangCLMode, llvm::BumpPtrAllocator &Alloc,
836 llvm::vfs::FileSystem *FS = nullptr);
837
838} // end namespace driver
839} // end namespace clang
840
841#endif
842

source code of clang/include/clang/Driver/Driver.h