1 //===--- Driver.h - Clang GCC Compatible Driver -----------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #ifndef LLVM_CLANG_DRIVER_DRIVER_H
11 #define LLVM_CLANG_DRIVER_DRIVER_H
13 #include "clang/Basic/Diagnostic.h"
14 #include "clang/Basic/LLVM.h"
15 #include "clang/Driver/Action.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/ArgList.h"
23 #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 std::unique_ptr<llvm::opt::OptTable> Opts;
62 DiagnosticsEngine &Diags;
64 IntrusiveRefCntPtr<vfs::FileSystem> VFS;
79 enum BitcodeEmbedMode {
85 /// LTO mode selected via -f(no-)?lto(=.*)? options.
89 enum OpenMPRuntimeKind {
90 /// An unknown OpenMP runtime. We can't generate effective OpenMP code
91 /// without knowing what runtime to target.
94 /// The LLVM OpenMP runtime. When completed and integrated, this will become
95 /// the default for Clang.
98 /// The GNU OpenMP runtime. Clang doesn't support generating OpenMP code for
99 /// this runtime but can swallow the pragmas, and find and link against the
100 /// runtime library itself.
103 /// The legacy name for the LLVM OpenMP runtime from when it was the Intel
104 /// OpenMP runtime. We support this mode for users with existing
105 /// dependencies on this runtime library name.
109 // Diag - Forwarding function for diagnostics.
110 DiagnosticBuilder Diag(unsigned DiagID) const {
111 return Diags.Report(DiagID);
114 // FIXME: Privatize once interface is stable.
116 /// The name the driver was invoked as.
119 /// The path the driver executable was in, as invoked from the
123 /// The original path to the clang executable.
124 std::string ClangExecutable;
126 /// Target and driver mode components extracted from clang executable name.
127 ParsedClangName ClangNameParts;
129 /// The path to the installed clang directory, if any.
130 std::string InstalledDir;
132 /// The path to the compiler resource directory.
133 std::string ResourceDir;
135 /// System directory for config files.
136 std::string SystemConfigDir;
138 /// User directory for config files.
139 std::string UserConfigDir;
141 /// A prefix directory used to emulate a limited subset of GCC's '-Bprefix'
143 /// FIXME: This type of customization should be removed in favor of the
144 /// universal driver when it is ready.
145 typedef SmallVector<std::string, 4> prefix_list;
146 prefix_list PrefixDirs;
148 /// sysroot, if present
151 /// Dynamic loader prefix, if present
152 std::string DyldPrefix;
154 /// Driver title to use with help.
155 std::string DriverTitle;
157 /// Information about the host which can be overridden by the user.
158 std::string HostBits, HostMachine, HostSystem, HostRelease;
160 /// The file to log CC_PRINT_OPTIONS output to, if enabled.
161 const char *CCPrintOptionsFilename;
163 /// The file to log CC_PRINT_HEADERS output to, if enabled.
164 const char *CCPrintHeadersFilename;
166 /// The file to log CC_LOG_DIAGNOSTICS output to, if enabled.
167 const char *CCLogDiagnosticsFilename;
169 /// A list of inputs and their types for the given arguments.
170 typedef SmallVector<std::pair<types::ID, const llvm::opt::Arg *>, 16>
173 /// Whether the driver should follow g++ like behavior.
174 bool CCCIsCXX() const { return Mode == GXXMode; }
176 /// Whether the driver is just the preprocessor.
177 bool CCCIsCPP() const { return Mode == CPPMode; }
179 /// Whether the driver should follow gcc like behavior.
180 bool CCCIsCC() const { return Mode == GCCMode; }
182 /// Whether the driver should follow cl.exe like behavior.
183 bool IsCLMode() const { return Mode == CLMode; }
185 /// Only print tool bindings, don't build any jobs.
186 unsigned CCCPrintBindings : 1;
188 /// Set CC_PRINT_OPTIONS mode, which is like -v but logs the commands to
189 /// CCPrintOptionsFilename or to stderr.
190 unsigned CCPrintOptions : 1;
192 /// Set CC_PRINT_HEADERS mode, which causes the frontend to log header include
193 /// information to CCPrintHeadersFilename or to stderr.
194 unsigned CCPrintHeaders : 1;
196 /// Set CC_LOG_DIAGNOSTICS mode, which causes the frontend to log diagnostics
197 /// to CCLogDiagnosticsFilename or to stderr, in a stable machine readable
199 unsigned CCLogDiagnostics : 1;
201 /// Whether the driver is generating diagnostics for debugging purposes.
202 unsigned CCGenDiagnostics : 1;
205 /// Raw target triple.
206 std::string TargetTriple;
208 /// Name to use when invoking gcc/g++.
209 std::string CCCGenericGCCName;
211 /// Name of configuration file if used.
212 std::string ConfigFile;
214 /// Allocator for string saver.
215 llvm::BumpPtrAllocator Alloc;
217 /// Object that stores strings read from configuration file.
218 llvm::StringSaver Saver;
220 /// Arguments originated from configuration file.
221 std::unique_ptr<llvm::opt::InputArgList> CfgOptions;
223 /// Arguments originated from command line.
224 std::unique_ptr<llvm::opt::InputArgList> CLOptions;
226 /// Whether to check that input files exist when constructing compilation
228 unsigned CheckInputsExist : 1;
231 /// Use lazy precompiled headers for PCH support.
232 unsigned CCCUsePCH : 1;
234 /// Force clang to emit reproducer for driver invocation. This is enabled
235 /// indirectly by setting FORCE_CLANG_DIAGNOSTICS_CRASH environment variable
236 /// or when using the -gen-reproducer driver flag.
237 unsigned GenReproducer : 1;
240 /// Certain options suppress the 'no input files' warning.
241 unsigned SuppressMissingInputWarning : 1;
243 std::list<std::string> TempFiles;
244 std::list<std::string> ResultFiles;
246 /// Cache of all the ToolChains in use by the driver.
248 /// This maps from the string representation of a triple to a ToolChain
249 /// created targeting that triple. The driver owns all the ToolChain objects
250 /// stored in it, and will clean them up when torn down.
251 mutable llvm::StringMap<std::unique_ptr<ToolChain>> ToolChains;
254 /// TranslateInputArgs - Create a new derived argument list from the input
255 /// arguments, after applying the standard argument translations.
256 llvm::opt::DerivedArgList *
257 TranslateInputArgs(const llvm::opt::InputArgList &Args) const;
259 // getFinalPhase - Determine which compilation mode we are in and record
260 // which option we used to determine the final phase.
261 phases::ID getFinalPhase(const llvm::opt::DerivedArgList &DAL,
262 llvm::opt::Arg **FinalPhaseArg = nullptr) const;
264 // Before executing jobs, sets up response files for commands that need them.
265 void setUpResponseFiles(Compilation &C, Command &Cmd);
267 void generatePrefixedToolNames(StringRef Tool, const ToolChain &TC,
268 SmallVectorImpl<std::string> &Names) const;
270 /// Find the appropriate .crash diagonostic file for the child crash
271 /// under this driver and copy it out to a temporary destination with the
272 /// other reproducer related files (.sh, .cache, etc). If not found, suggest a
273 /// directory for the user to look at.
275 /// \param ReproCrashFilename The file path to copy the .crash to.
276 /// \param CrashDiagDir The suggested directory for the user to look at
277 /// in case the search or copy fails.
279 /// \returns If the .crash is found and successfully copied return true,
280 /// otherwise false and return the suggested directory in \p CrashDiagDir.
281 bool getCrashDiagnosticFile(StringRef ReproCrashFilename,
282 SmallString<128> &CrashDiagDir);
285 Driver(StringRef ClangExecutable, StringRef TargetTriple,
286 DiagnosticsEngine &Diags,
287 IntrusiveRefCntPtr<vfs::FileSystem> VFS = nullptr);
292 /// Name to use when invoking gcc/g++.
293 const std::string &getCCCGenericGCCName() const { return CCCGenericGCCName; }
295 const std::string &getConfigFile() const { return ConfigFile; }
297 const llvm::opt::OptTable &getOpts() const { return *Opts; }
299 const DiagnosticsEngine &getDiags() const { return Diags; }
301 vfs::FileSystem &getVFS() const { return *VFS; }
303 bool getCheckInputsExist() const { return CheckInputsExist; }
305 void setCheckInputsExist(bool Value) { CheckInputsExist = Value; }
307 void setTargetAndMode(const ParsedClangName &TM) { ClangNameParts = TM; }
309 const std::string &getTitle() { return DriverTitle; }
310 void setTitle(std::string Value) { DriverTitle = std::move(Value); }
312 std::string getTargetTriple() const { return TargetTriple; }
314 /// Get the path to the main clang executable.
315 const char *getClangProgramPath() const {
316 return ClangExecutable.c_str();
319 /// Get the path to where the clang executable was installed.
320 const char *getInstalledDir() const {
321 if (!InstalledDir.empty())
322 return InstalledDir.c_str();
325 void setInstalledDir(StringRef Value) {
326 InstalledDir = Value;
329 bool isSaveTempsEnabled() const { return SaveTemps != SaveTempsNone; }
330 bool isSaveTempsObj() const { return SaveTemps == SaveTempsObj; }
332 bool embedBitcodeEnabled() const { return BitcodeEmbed != EmbedNone; }
333 bool embedBitcodeInObject() const { return (BitcodeEmbed == EmbedBitcode); }
334 bool embedBitcodeMarkerOnly() const { return (BitcodeEmbed == EmbedMarker); }
336 /// Compute the desired OpenMP runtime from the flags provided.
337 OpenMPRuntimeKind getOpenMPRuntime(const llvm::opt::ArgList &Args) const;
340 /// @name Primary Functionality
343 /// CreateOffloadingDeviceToolChains - create all the toolchains required to
344 /// support offloading devices given the programming models specified in the
345 /// current compilation. Also, update the host tool chain kind accordingly.
346 void CreateOffloadingDeviceToolChains(Compilation &C, InputList &Inputs);
348 /// BuildCompilation - Construct a compilation object for a command
349 /// line argument vector.
351 /// \return A compilation, or 0 if none was built for the given
352 /// argument vector. A null return value does not necessarily
353 /// indicate an error condition, the diagnostics should be queried
354 /// to determine if an error occurred.
355 Compilation *BuildCompilation(ArrayRef<const char *> Args);
357 /// @name Driver Steps
360 /// ParseDriverMode - Look for and handle the driver mode option in Args.
361 void ParseDriverMode(StringRef ProgramName, ArrayRef<const char *> Args);
363 /// ParseArgStrings - Parse the given list of strings into an
365 llvm::opt::InputArgList ParseArgStrings(ArrayRef<const char *> Args,
366 bool &ContainsError);
368 /// BuildInputs - Construct the list of inputs and their types from
369 /// the given arguments.
371 /// \param TC - The default host tool chain.
372 /// \param Args - The input arguments.
373 /// \param Inputs - The list to store the resulting compilation
375 void BuildInputs(const ToolChain &TC, llvm::opt::DerivedArgList &Args,
376 InputList &Inputs) const;
378 /// BuildActions - Construct the list of actions to perform for the
379 /// given arguments, which are only done for a single architecture.
381 /// \param C - The compilation that is being built.
382 /// \param Args - The input arguments.
383 /// \param Actions - The list to store the resulting actions onto.
384 void BuildActions(Compilation &C, llvm::opt::DerivedArgList &Args,
385 const InputList &Inputs, ActionList &Actions) const;
387 /// BuildUniversalActions - Construct the list of actions to perform
388 /// for the given arguments, which may require a universal build.
390 /// \param C - The compilation that is being built.
391 /// \param TC - The default host tool chain.
392 void BuildUniversalActions(Compilation &C, const ToolChain &TC,
393 const InputList &BAInputs) const;
395 /// BuildJobs - Bind actions to concrete tools and translate
396 /// arguments to form the list of jobs to run.
398 /// \param C - The compilation that is being built.
399 void BuildJobs(Compilation &C) const;
401 /// ExecuteCompilation - Execute the compilation according to the command line
402 /// arguments and return an appropriate exit code.
404 /// This routine handles additional processing that must be done in addition
405 /// to just running the subprocesses, for example reporting errors, setting
406 /// up response files, removing temporary files, etc.
407 int ExecuteCompilation(Compilation &C,
408 SmallVectorImpl< std::pair<int, const Command *> > &FailingCommands);
410 /// Contains the files in the compilation diagnostic report generated by
411 /// generateCompilationDiagnostics.
412 struct CompilationDiagnosticReport {
413 llvm::SmallVector<std::string, 4> TemporaryFiles;
416 /// generateCompilationDiagnostics - Generate diagnostics information
417 /// including preprocessed source file(s).
419 void generateCompilationDiagnostics(
420 Compilation &C, const Command &FailingCommand,
421 StringRef AdditionalInformation = "",
422 CompilationDiagnosticReport *GeneratedReport = nullptr);
425 /// @name Helper Methods
428 /// PrintActions - Print the list of actions.
429 void PrintActions(const Compilation &C) const;
431 /// PrintHelp - Print the help text.
433 /// \param ShowHidden - Show hidden options.
434 void PrintHelp(bool ShowHidden) const;
436 /// PrintVersion - Print the driver version.
437 void PrintVersion(const Compilation &C, raw_ostream &OS) const;
439 /// GetFilePath - Lookup \p Name in the list of file search paths.
441 /// \param TC - The tool chain for additional information on
442 /// directories to search.
444 // FIXME: This should be in CompilationInfo.
445 std::string GetFilePath(StringRef Name, const ToolChain &TC) const;
447 /// GetProgramPath - Lookup \p Name in the list of program search paths.
449 /// \param TC - The provided tool chain for additional information on
450 /// directories to search.
452 // FIXME: This should be in CompilationInfo.
453 std::string GetProgramPath(StringRef Name, const ToolChain &TC) const;
455 /// HandleAutocompletions - Handle --autocomplete by searching and printing
456 /// possible flags, descriptions, and its arguments.
457 void HandleAutocompletions(StringRef PassedFlags) const;
459 /// HandleImmediateArgs - Handle any arguments which should be
460 /// treated before building actions or binding tools.
462 /// \return Whether any compilation should be built for this
464 bool HandleImmediateArgs(const Compilation &C);
466 /// ConstructAction - Construct the appropriate action to do for
467 /// \p Phase on the \p Input, taking in to account arguments
468 /// like -fsyntax-only or --analyze.
469 Action *ConstructPhaseAction(
470 Compilation &C, const llvm::opt::ArgList &Args, phases::ID Phase,
472 Action::OffloadKind TargetDeviceOffloadKind = Action::OFK_None) const;
474 /// BuildJobsForAction - Construct the jobs to perform for the action \p A and
475 /// return an InputInfo for the result of running \p A. Will only construct
476 /// jobs for a given (Action, ToolChain, BoundArch, DeviceKind) tuple once.
478 BuildJobsForAction(Compilation &C, const Action *A, const ToolChain *TC,
479 StringRef BoundArch, bool AtTopLevel, bool MultipleArchs,
480 const char *LinkingOutput,
481 std::map<std::pair<const Action *, std::string>, InputInfo>
483 Action::OffloadKind TargetDeviceOffloadKind) const;
485 /// Returns the default name for linked images (e.g., "a.out").
486 const char *getDefaultImageName() const;
488 /// GetNamedOutputPath - Return the name to use for the output of
489 /// the action \p JA. The result is appended to the compilation's
490 /// list of temporary or result files, as appropriate.
492 /// \param C - The compilation.
493 /// \param JA - The action of interest.
494 /// \param BaseInput - The original input file that this action was
496 /// \param BoundArch - The bound architecture.
497 /// \param AtTopLevel - Whether this is a "top-level" action.
498 /// \param MultipleArchs - Whether multiple -arch options were supplied.
499 /// \param NormalizedTriple - The normalized triple of the relevant target.
500 const char *GetNamedOutputPath(Compilation &C, const JobAction &JA,
501 const char *BaseInput, StringRef BoundArch,
502 bool AtTopLevel, bool MultipleArchs,
503 StringRef NormalizedTriple) const;
505 /// GetTemporaryPath - Return the pathname of a temporary file to use
506 /// as part of compilation; the file will have the given prefix and suffix.
508 /// GCC goes to extra lengths here to be a bit more robust.
509 std::string GetTemporaryPath(StringRef Prefix, StringRef Suffix) const;
511 /// Return the pathname of the pch file in clang-cl mode.
512 std::string GetClPchPath(Compilation &C, StringRef BaseName) const;
514 /// ShouldUseClangCompiler - Should the clang compiler be used to
515 /// handle this action.
516 bool ShouldUseClangCompiler(const JobAction &JA) const;
518 /// Returns true if we are performing any kind of LTO.
519 bool isUsingLTO() const { return LTOMode != LTOK_None; }
521 /// Get the specific kind of LTO being performed.
522 LTOKind getLTOMode() const { return LTOMode; }
526 /// Tries to load options from configuration file.
528 /// \returns true if error occurred.
529 bool loadConfigFile();
531 /// Read options from the specified file.
533 /// \param [in] FileName File to read.
534 /// \returns true, if error occurred while reading.
535 bool readConfigFile(StringRef FileName);
537 /// Set the driver mode (cl, gcc, etc) from an option string of the form
538 /// --driver-mode=<mode>.
539 void setDriverModeFromOption(StringRef Opt);
541 /// Parse the \p Args list for LTO options and record the type of LTO
542 /// compilation based on which -f(no-)?lto(=.*)? option occurs last.
543 void setLTOMode(const llvm::opt::ArgList &Args);
545 /// Retrieves a ToolChain for a particular \p Target triple.
547 /// Will cache ToolChains for the life of the driver object, and create them
549 const ToolChain &getToolChain(const llvm::opt::ArgList &Args,
550 const llvm::Triple &Target) const;
554 /// Get bitmasks for which option flags to include and exclude based on
556 std::pair<unsigned, unsigned> getIncludeExcludeOptionFlagMasks() const;
558 /// Helper used in BuildJobsForAction. Doesn't use the cache when building
559 /// jobs specifically for the given action, but will use the cache when
560 /// building jobs for the Action's inputs.
561 InputInfo BuildJobsForActionNoCache(
562 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
563 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
564 std::map<std::pair<const Action *, std::string>, InputInfo>
566 Action::OffloadKind TargetDeviceOffloadKind) const;
569 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and
570 /// return the grouped values as integers. Numbers which are not
571 /// provided are set to 0.
573 /// \return True if the entire string was parsed (9.2), or all
574 /// groups were parsed (10.3.5extrastuff). HadExtra is true if all
575 /// groups were parsed but extra characters remain at the end.
576 static bool GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
577 unsigned &Micro, bool &HadExtra);
579 /// Parse digits from a string \p Str and fulfill \p Digits with
580 /// the parsed numbers. This method assumes that the max number of
581 /// digits to look for is equal to Digits.size().
583 /// \return True if the entire string was parsed and there are
584 /// no extra characters remaining at the end.
585 static bool GetReleaseVersion(StringRef Str,
586 MutableArrayRef<unsigned> Digits);
587 /// Compute the default -fmodule-cache-path.
588 static void getDefaultModuleCachePath(SmallVectorImpl<char> &Result);
591 /// \return True if the last defined optimization level is -Ofast.
592 /// And False otherwise.
593 bool isOptimizationLevelFast(const llvm::opt::ArgList &Args);
595 } // end namespace driver
596 } // end namespace clang