1 //===--- Driver.h - Clang GCC Compatible Driver -----------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 #ifndef LLVM_CLANG_DRIVER_DRIVER_H
10 #define LLVM_CLANG_DRIVER_DRIVER_H
12 #include "clang/Basic/Diagnostic.h"
13 #include "clang/Basic/LLVM.h"
14 #include "clang/Driver/Action.h"
15 #include "clang/Driver/Options.h"
16 #include "clang/Driver/Phases.h"
17 #include "clang/Driver/ToolChain.h"
18 #include "clang/Driver/Types.h"
19 #include "clang/Driver/Util.h"
20 #include "llvm/ADT/StringMap.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/Option/Arg.h"
23 #include "llvm/Option/ArgList.h"
24 #include "llvm/Support/StringSaver.h"
49 /// Describes the kind of LTO mode selected via -f(no-)?lto(=.*)? options.
57 /// Driver - Encapsulate logic for constructing compilation processes
58 /// from a set of gcc-driver-like command line arguments.
60 DiagnosticsEngine &Diags;
62 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS;
78 enum BitcodeEmbedMode {
84 /// LTO mode selected via -f(no-)?lto(=.*)? options.
88 enum OpenMPRuntimeKind {
89 /// An unknown OpenMP runtime. We can't generate effective OpenMP code
90 /// without knowing what runtime to target.
93 /// The LLVM OpenMP runtime. When completed and integrated, this will become
94 /// the default for Clang.
97 /// The GNU OpenMP runtime. Clang doesn't support generating OpenMP code for
98 /// this runtime but can swallow the pragmas, and find and link against the
99 /// runtime library itself.
102 /// The legacy name for the LLVM OpenMP runtime from when it was the Intel
103 /// OpenMP runtime. We support this mode for users with existing
104 /// dependencies on this runtime library name.
108 // Diag - Forwarding function for diagnostics.
109 DiagnosticBuilder Diag(unsigned DiagID) const {
110 return Diags.Report(DiagID);
113 // FIXME: Privatize once interface is stable.
115 /// The name the driver was invoked as.
118 /// The path the driver executable was in, as invoked from the
122 /// The original path to the clang executable.
123 std::string ClangExecutable;
125 /// Target and driver mode components extracted from clang executable name.
126 ParsedClangName ClangNameParts;
128 /// The path to the installed clang directory, if any.
129 std::string InstalledDir;
131 /// The path to the compiler resource directory.
132 std::string ResourceDir;
134 /// System directory for config files.
135 std::string SystemConfigDir;
137 /// User directory for config files.
138 std::string UserConfigDir;
140 /// A prefix directory used to emulate a limited subset of GCC's '-Bprefix'
142 /// FIXME: This type of customization should be removed in favor of the
143 /// universal driver when it is ready.
144 typedef SmallVector<std::string, 4> prefix_list;
145 prefix_list PrefixDirs;
147 /// sysroot, if present
150 /// Dynamic loader prefix, if present
151 std::string DyldPrefix;
153 /// Driver title to use with help.
154 std::string DriverTitle;
156 /// Information about the host which can be overridden by the user.
157 std::string HostBits, HostMachine, HostSystem, HostRelease;
159 /// The file to log CC_PRINT_OPTIONS output to, if enabled.
160 const char *CCPrintOptionsFilename;
162 /// The file to log CC_PRINT_HEADERS output to, if enabled.
163 const char *CCPrintHeadersFilename;
165 /// The file to log CC_LOG_DIAGNOSTICS output to, if enabled.
166 const char *CCLogDiagnosticsFilename;
168 /// A list of inputs and their types for the given arguments.
169 typedef SmallVector<std::pair<types::ID, const llvm::opt::Arg *>, 16>
172 /// Whether the driver should follow g++ like behavior.
173 bool CCCIsCXX() const { return Mode == GXXMode; }
175 /// Whether the driver is just the preprocessor.
176 bool CCCIsCPP() const { return Mode == CPPMode; }
178 /// Whether the driver should follow gcc like behavior.
179 bool CCCIsCC() const { return Mode == GCCMode; }
181 /// Whether the driver should follow cl.exe like behavior.
182 bool IsCLMode() const { return Mode == CLMode; }
184 /// Whether the driver should invoke flang for fortran inputs.
185 /// Other modes fall back to calling gcc which in turn calls gfortran.
186 bool IsFlangMode() const { return Mode == FlangMode; }
188 /// Only print tool bindings, don't build any jobs.
189 unsigned CCCPrintBindings : 1;
191 /// Set CC_PRINT_OPTIONS mode, which is like -v but logs the commands to
192 /// CCPrintOptionsFilename or to stderr.
193 unsigned CCPrintOptions : 1;
195 /// Set CC_PRINT_HEADERS mode, which causes the frontend to log header include
196 /// information to CCPrintHeadersFilename or to stderr.
197 unsigned CCPrintHeaders : 1;
199 /// Set CC_LOG_DIAGNOSTICS mode, which causes the frontend to log diagnostics
200 /// to CCLogDiagnosticsFilename or to stderr, in a stable machine readable
202 unsigned CCLogDiagnostics : 1;
204 /// Whether the driver is generating diagnostics for debugging purposes.
205 unsigned CCGenDiagnostics : 1;
207 /// Pointer to the ExecuteCC1Tool function, if available.
208 /// When the clangDriver lib is used through clang.exe, this provides a
209 /// shortcut for executing the -cc1 command-line directly, in the same
211 typedef int (*CC1ToolFunc)(SmallVectorImpl<const char *> &ArgV);
212 CC1ToolFunc CC1Main = nullptr;
215 /// Raw target triple.
216 std::string TargetTriple;
218 /// Name to use when invoking gcc/g++.
219 std::string CCCGenericGCCName;
221 /// Name of configuration file if used.
222 std::string ConfigFile;
224 /// Allocator for string saver.
225 llvm::BumpPtrAllocator Alloc;
227 /// Object that stores strings read from configuration file.
228 llvm::StringSaver Saver;
230 /// Arguments originated from configuration file.
231 std::unique_ptr<llvm::opt::InputArgList> CfgOptions;
233 /// Arguments originated from command line.
234 std::unique_ptr<llvm::opt::InputArgList> CLOptions;
236 /// Whether to check that input files exist when constructing compilation
238 unsigned CheckInputsExist : 1;
241 /// Force clang to emit reproducer for driver invocation. This is enabled
242 /// indirectly by setting FORCE_CLANG_DIAGNOSTICS_CRASH environment variable
243 /// or when using the -gen-reproducer driver flag.
244 unsigned GenReproducer : 1;
247 /// Certain options suppress the 'no input files' warning.
248 unsigned SuppressMissingInputWarning : 1;
250 /// Cache of all the ToolChains in use by the driver.
252 /// This maps from the string representation of a triple to a ToolChain
253 /// created targeting that triple. The driver owns all the ToolChain objects
254 /// stored in it, and will clean them up when torn down.
255 mutable llvm::StringMap<std::unique_ptr<ToolChain>> ToolChains;
258 /// TranslateInputArgs - Create a new derived argument list from the input
259 /// arguments, after applying the standard argument translations.
260 llvm::opt::DerivedArgList *
261 TranslateInputArgs(const llvm::opt::InputArgList &Args) const;
263 // getFinalPhase - Determine which compilation mode we are in and record
264 // which option we used to determine the final phase.
265 // TODO: Much of what getFinalPhase returns are not actually true compiler
266 // modes. Fold this functionality into Types::getCompilationPhases and
268 phases::ID getFinalPhase(const llvm::opt::DerivedArgList &DAL,
269 llvm::opt::Arg **FinalPhaseArg = nullptr) const;
271 // handleArguments - All code related to claiming and printing diagnostics
272 // related to arguments to the driver are done here.
273 void handleArguments(Compilation &C, llvm::opt::DerivedArgList &Args,
274 const InputList &Inputs, ActionList &Actions) const;
276 // Before executing jobs, sets up response files for commands that need them.
277 void setUpResponseFiles(Compilation &C, Command &Cmd);
279 void generatePrefixedToolNames(StringRef Tool, const ToolChain &TC,
280 SmallVectorImpl<std::string> &Names) const;
282 /// Find the appropriate .crash diagonostic file for the child crash
283 /// under this driver and copy it out to a temporary destination with the
284 /// other reproducer related files (.sh, .cache, etc). If not found, suggest a
285 /// directory for the user to look at.
287 /// \param ReproCrashFilename The file path to copy the .crash to.
288 /// \param CrashDiagDir The suggested directory for the user to look at
289 /// in case the search or copy fails.
291 /// \returns If the .crash is found and successfully copied return true,
292 /// otherwise false and return the suggested directory in \p CrashDiagDir.
293 bool getCrashDiagnosticFile(StringRef ReproCrashFilename,
294 SmallString<128> &CrashDiagDir);
298 /// Takes the path to a binary that's either in bin/ or lib/ and returns
299 /// the path to clang's resource directory.
300 static std::string GetResourcesPath(StringRef BinaryPath,
301 StringRef CustomResourceDir = "");
303 Driver(StringRef ClangExecutable, StringRef TargetTriple,
304 DiagnosticsEngine &Diags,
305 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS = nullptr);
310 /// Name to use when invoking gcc/g++.
311 const std::string &getCCCGenericGCCName() const { return CCCGenericGCCName; }
313 const std::string &getConfigFile() const { return ConfigFile; }
315 const llvm::opt::OptTable &getOpts() const { return getDriverOptTable(); }
317 const DiagnosticsEngine &getDiags() const { return Diags; }
319 llvm::vfs::FileSystem &getVFS() const { return *VFS; }
321 bool getCheckInputsExist() const { return CheckInputsExist; }
323 void setCheckInputsExist(bool Value) { CheckInputsExist = Value; }
325 void setTargetAndMode(const ParsedClangName &TM) { ClangNameParts = TM; }
327 const std::string &getTitle() { return DriverTitle; }
328 void setTitle(std::string Value) { DriverTitle = std::move(Value); }
330 std::string getTargetTriple() const { return TargetTriple; }
332 /// Get the path to the main clang executable.
333 const char *getClangProgramPath() const {
334 return ClangExecutable.c_str();
337 /// Get the path to where the clang executable was installed.
338 const char *getInstalledDir() const {
339 if (!InstalledDir.empty())
340 return InstalledDir.c_str();
343 void setInstalledDir(StringRef Value) { InstalledDir = std::string(Value); }
345 bool isSaveTempsEnabled() const { return SaveTemps != SaveTempsNone; }
346 bool isSaveTempsObj() const { return SaveTemps == SaveTempsObj; }
348 bool embedBitcodeEnabled() const { return BitcodeEmbed != EmbedNone; }
349 bool embedBitcodeInObject() const { return (BitcodeEmbed == EmbedBitcode); }
350 bool embedBitcodeMarkerOnly() const { return (BitcodeEmbed == EmbedMarker); }
352 /// Compute the desired OpenMP runtime from the flags provided.
353 OpenMPRuntimeKind getOpenMPRuntime(const llvm::opt::ArgList &Args) const;
356 /// @name Primary Functionality
359 /// CreateOffloadingDeviceToolChains - create all the toolchains required to
360 /// support offloading devices given the programming models specified in the
361 /// current compilation. Also, update the host tool chain kind accordingly.
362 void CreateOffloadingDeviceToolChains(Compilation &C, InputList &Inputs);
364 /// BuildCompilation - Construct a compilation object for a command
365 /// line argument vector.
367 /// \return A compilation, or 0 if none was built for the given
368 /// argument vector. A null return value does not necessarily
369 /// indicate an error condition, the diagnostics should be queried
370 /// to determine if an error occurred.
371 Compilation *BuildCompilation(ArrayRef<const char *> Args);
373 /// @name Driver Steps
376 /// ParseDriverMode - Look for and handle the driver mode option in Args.
377 void ParseDriverMode(StringRef ProgramName, ArrayRef<const char *> Args);
379 /// ParseArgStrings - Parse the given list of strings into an
381 llvm::opt::InputArgList ParseArgStrings(ArrayRef<const char *> Args,
383 bool &ContainsError);
385 /// BuildInputs - Construct the list of inputs and their types from
386 /// the given arguments.
388 /// \param TC - The default host tool chain.
389 /// \param Args - The input arguments.
390 /// \param Inputs - The list to store the resulting compilation
392 void BuildInputs(const ToolChain &TC, llvm::opt::DerivedArgList &Args,
393 InputList &Inputs) const;
395 /// BuildActions - Construct the list of actions to perform for the
396 /// given arguments, which are only done for a single architecture.
398 /// \param C - The compilation that is being built.
399 /// \param Args - The input arguments.
400 /// \param Actions - The list to store the resulting actions onto.
401 void BuildActions(Compilation &C, llvm::opt::DerivedArgList &Args,
402 const InputList &Inputs, ActionList &Actions) const;
404 /// BuildUniversalActions - Construct the list of actions to perform
405 /// for the given arguments, which may require a universal build.
407 /// \param C - The compilation that is being built.
408 /// \param TC - The default host tool chain.
409 void BuildUniversalActions(Compilation &C, const ToolChain &TC,
410 const InputList &BAInputs) const;
412 /// Check that the file referenced by Value exists. If it doesn't,
413 /// issue a diagnostic and return false.
414 /// If TypoCorrect is true and the file does not exist, see if it looks
415 /// like a likely typo for a flag and if so print a "did you mean" blurb.
416 bool DiagnoseInputExistence(const llvm::opt::DerivedArgList &Args,
417 StringRef Value, types::ID Ty,
418 bool TypoCorrect) const;
420 /// BuildJobs - Bind actions to concrete tools and translate
421 /// arguments to form the list of jobs to run.
423 /// \param C - The compilation that is being built.
424 void BuildJobs(Compilation &C) const;
426 /// ExecuteCompilation - Execute the compilation according to the command line
427 /// arguments and return an appropriate exit code.
429 /// This routine handles additional processing that must be done in addition
430 /// to just running the subprocesses, for example reporting errors, setting
431 /// up response files, removing temporary files, etc.
432 int ExecuteCompilation(Compilation &C,
433 SmallVectorImpl< std::pair<int, const Command *> > &FailingCommands);
435 /// Contains the files in the compilation diagnostic report generated by
436 /// generateCompilationDiagnostics.
437 struct CompilationDiagnosticReport {
438 llvm::SmallVector<std::string, 4> TemporaryFiles;
441 /// generateCompilationDiagnostics - Generate diagnostics information
442 /// including preprocessed source file(s).
444 void generateCompilationDiagnostics(
445 Compilation &C, const Command &FailingCommand,
446 StringRef AdditionalInformation = "",
447 CompilationDiagnosticReport *GeneratedReport = nullptr);
450 /// @name Helper Methods
453 /// PrintActions - Print the list of actions.
454 void PrintActions(const Compilation &C) const;
456 /// PrintHelp - Print the help text.
458 /// \param ShowHidden - Show hidden options.
459 void PrintHelp(bool ShowHidden) const;
461 /// PrintVersion - Print the driver version.
462 void PrintVersion(const Compilation &C, raw_ostream &OS) const;
464 /// GetFilePath - Lookup \p Name in the list of file search paths.
466 /// \param TC - The tool chain for additional information on
467 /// directories to search.
469 // FIXME: This should be in CompilationInfo.
470 std::string GetFilePath(StringRef Name, const ToolChain &TC) const;
472 /// GetProgramPath - Lookup \p Name in the list of program search paths.
474 /// \param TC - The provided tool chain for additional information on
475 /// directories to search.
477 // FIXME: This should be in CompilationInfo.
478 std::string GetProgramPath(StringRef Name, const ToolChain &TC) const;
480 /// HandleAutocompletions - Handle --autocomplete by searching and printing
481 /// possible flags, descriptions, and its arguments.
482 void HandleAutocompletions(StringRef PassedFlags) const;
484 /// HandleImmediateArgs - Handle any arguments which should be
485 /// treated before building actions or binding tools.
487 /// \return Whether any compilation should be built for this
489 bool HandleImmediateArgs(const Compilation &C);
491 /// ConstructAction - Construct the appropriate action to do for
492 /// \p Phase on the \p Input, taking in to account arguments
493 /// like -fsyntax-only or --analyze.
494 Action *ConstructPhaseAction(
495 Compilation &C, const llvm::opt::ArgList &Args, phases::ID Phase,
497 Action::OffloadKind TargetDeviceOffloadKind = Action::OFK_None) const;
499 /// BuildJobsForAction - Construct the jobs to perform for the action \p A and
500 /// return an InputInfo for the result of running \p A. Will only construct
501 /// jobs for a given (Action, ToolChain, BoundArch, DeviceKind) tuple once.
503 BuildJobsForAction(Compilation &C, const Action *A, const ToolChain *TC,
504 StringRef BoundArch, bool AtTopLevel, bool MultipleArchs,
505 const char *LinkingOutput,
506 std::map<std::pair<const Action *, std::string>, InputInfo>
508 Action::OffloadKind TargetDeviceOffloadKind) const;
510 /// Returns the default name for linked images (e.g., "a.out").
511 const char *getDefaultImageName() const;
513 /// GetNamedOutputPath - Return the name to use for the output of
514 /// the action \p JA. The result is appended to the compilation's
515 /// list of temporary or result files, as appropriate.
517 /// \param C - The compilation.
518 /// \param JA - The action of interest.
519 /// \param BaseInput - The original input file that this action was
521 /// \param BoundArch - The bound architecture.
522 /// \param AtTopLevel - Whether this is a "top-level" action.
523 /// \param MultipleArchs - Whether multiple -arch options were supplied.
524 /// \param NormalizedTriple - The normalized triple of the relevant target.
525 const char *GetNamedOutputPath(Compilation &C, const JobAction &JA,
526 const char *BaseInput, StringRef BoundArch,
527 bool AtTopLevel, bool MultipleArchs,
528 StringRef NormalizedTriple) const;
530 /// GetTemporaryPath - Return the pathname of a temporary file to use
531 /// as part of compilation; the file will have the given prefix and suffix.
533 /// GCC goes to extra lengths here to be a bit more robust.
534 std::string GetTemporaryPath(StringRef Prefix, StringRef Suffix) const;
536 /// GetTemporaryDirectory - Return the pathname of a temporary directory to
537 /// use as part of compilation; the directory will have the given prefix.
538 std::string GetTemporaryDirectory(StringRef Prefix) const;
540 /// Return the pathname of the pch file in clang-cl mode.
541 std::string GetClPchPath(Compilation &C, StringRef BaseName) const;
543 /// ShouldUseClangCompiler - Should the clang compiler be used to
544 /// handle this action.
545 bool ShouldUseClangCompiler(const JobAction &JA) const;
547 /// ShouldUseFlangCompiler - Should the flang compiler be used to
548 /// handle this action.
549 bool ShouldUseFlangCompiler(const JobAction &JA) const;
551 /// ShouldEmitStaticLibrary - Should the linker emit a static library.
552 bool ShouldEmitStaticLibrary(const llvm::opt::ArgList &Args) const;
554 /// Returns true if we are performing any kind of LTO.
555 bool isUsingLTO() const { return LTOMode != LTOK_None; }
557 /// Get the specific kind of LTO being performed.
558 LTOKind getLTOMode() const { return LTOMode; }
562 /// Tries to load options from configuration file.
564 /// \returns true if error occurred.
565 bool loadConfigFile();
567 /// Read options from the specified file.
569 /// \param [in] FileName File to read.
570 /// \returns true, if error occurred while reading.
571 bool readConfigFile(StringRef FileName);
573 /// Set the driver mode (cl, gcc, etc) from an option string of the form
574 /// --driver-mode=<mode>.
575 void setDriverModeFromOption(StringRef Opt);
577 /// Parse the \p Args list for LTO options and record the type of LTO
578 /// compilation based on which -f(no-)?lto(=.*)? option occurs last.
579 void setLTOMode(const llvm::opt::ArgList &Args);
581 /// Retrieves a ToolChain for a particular \p Target triple.
583 /// Will cache ToolChains for the life of the driver object, and create them
585 const ToolChain &getToolChain(const llvm::opt::ArgList &Args,
586 const llvm::Triple &Target) const;
590 /// Get bitmasks for which option flags to include and exclude based on
592 std::pair<unsigned, unsigned> getIncludeExcludeOptionFlagMasks(bool IsClCompatMode) const;
594 /// Helper used in BuildJobsForAction. Doesn't use the cache when building
595 /// jobs specifically for the given action, but will use the cache when
596 /// building jobs for the Action's inputs.
597 InputInfo BuildJobsForActionNoCache(
598 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
599 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
600 std::map<std::pair<const Action *, std::string>, InputInfo>
602 Action::OffloadKind TargetDeviceOffloadKind) const;
605 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and
606 /// return the grouped values as integers. Numbers which are not
607 /// provided are set to 0.
609 /// \return True if the entire string was parsed (9.2), or all
610 /// groups were parsed (10.3.5extrastuff). HadExtra is true if all
611 /// groups were parsed but extra characters remain at the end.
612 static bool GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
613 unsigned &Micro, bool &HadExtra);
615 /// Parse digits from a string \p Str and fulfill \p Digits with
616 /// the parsed numbers. This method assumes that the max number of
617 /// digits to look for is equal to Digits.size().
619 /// \return True if the entire string was parsed and there are
620 /// no extra characters remaining at the end.
621 static bool GetReleaseVersion(StringRef Str,
622 MutableArrayRef<unsigned> Digits);
623 /// Compute the default -fmodule-cache-path.
624 /// \return True if the system provides a default cache directory.
625 static bool getDefaultModuleCachePath(SmallVectorImpl<char> &Result);
628 /// \return True if the last defined optimization level is -Ofast.
629 /// And False otherwise.
630 bool isOptimizationLevelFast(const llvm::opt::ArgList &Args);
632 /// \return True if the argument combination will end up generating remarks.
633 bool willEmitRemarks(const llvm::opt::ArgList &Args);
635 } // end namespace driver
636 } // end namespace clang