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"
55 /// Describes the kind of LTO mode selected via -f(no-)?lto(=.*)? options.
63 /// Driver - Encapsulate logic for constructing compilation processes
64 /// from a set of gcc-driver-like command line arguments.
66 std::unique_ptr<llvm::opt::OptTable> Opts;
68 DiagnosticsEngine &Diags;
70 IntrusiveRefCntPtr<vfs::FileSystem> VFS;
85 enum BitcodeEmbedMode {
91 /// LTO mode selected via -f(no-)?lto(=.*)? options.
95 enum OpenMPRuntimeKind {
96 /// An unknown OpenMP runtime. We can't generate effective OpenMP code
97 /// without knowing what runtime to target.
100 /// The LLVM OpenMP runtime. When completed and integrated, this will become
101 /// the default for Clang.
104 /// The GNU OpenMP runtime. Clang doesn't support generating OpenMP code for
105 /// this runtime but can swallow the pragmas, and find and link against the
106 /// runtime library itself.
109 /// The legacy name for the LLVM OpenMP runtime from when it was the Intel
110 /// OpenMP runtime. We support this mode for users with existing
111 /// dependencies on this runtime library name.
115 // Diag - Forwarding function for diagnostics.
116 DiagnosticBuilder Diag(unsigned DiagID) const {
117 return Diags.Report(DiagID);
120 // FIXME: Privatize once interface is stable.
122 /// The name the driver was invoked as.
125 /// The path the driver executable was in, as invoked from the
129 /// The original path to the clang executable.
130 std::string ClangExecutable;
132 /// The path to the installed clang directory, if any.
133 std::string InstalledDir;
135 /// The path to the compiler resource directory.
136 std::string ResourceDir;
138 /// A prefix directory used to emulate a limited subset of GCC's '-Bprefix'
140 /// FIXME: This type of customization should be removed in favor of the
141 /// universal driver when it is ready.
142 typedef SmallVector<std::string, 4> prefix_list;
143 prefix_list PrefixDirs;
145 /// sysroot, if present
148 /// Dynamic loader prefix, if present
149 std::string DyldPrefix;
151 /// If the standard library is used
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 /// Default target triple.
206 std::string DefaultTargetTriple;
208 /// Name to use when invoking gcc/g++.
209 std::string CCCGenericGCCName;
211 /// Whether to check that input files exist when constructing compilation
213 unsigned CheckInputsExist : 1;
216 /// Use lazy precompiled headers for PCH support.
217 unsigned CCCUsePCH : 1;
219 /// Force clang to emit reproducer for driver invocation. This is enabled
220 /// indirectly by setting FORCE_CLANG_DIAGNOSTICS_CRASH environment variable
221 /// or when using the -gen-reproducer driver flag.
222 unsigned GenReproducer : 1;
225 /// Certain options suppress the 'no input files' warning.
226 unsigned SuppressMissingInputWarning : 1;
228 std::list<std::string> TempFiles;
229 std::list<std::string> ResultFiles;
231 /// \brief Cache of all the ToolChains in use by the driver.
233 /// This maps from the string representation of a triple to a ToolChain
234 /// created targeting that triple. The driver owns all the ToolChain objects
235 /// stored in it, and will clean them up when torn down.
236 mutable llvm::StringMap<std::unique_ptr<ToolChain>> ToolChains;
239 /// TranslateInputArgs - Create a new derived argument list from the input
240 /// arguments, after applying the standard argument translations.
241 llvm::opt::DerivedArgList *
242 TranslateInputArgs(const llvm::opt::InputArgList &Args) const;
244 // getFinalPhase - Determine which compilation mode we are in and record
245 // which option we used to determine the final phase.
246 phases::ID getFinalPhase(const llvm::opt::DerivedArgList &DAL,
247 llvm::opt::Arg **FinalPhaseArg = nullptr) const;
249 // Before executing jobs, sets up response files for commands that need them.
250 void setUpResponseFiles(Compilation &C, Command &Cmd);
252 void generatePrefixedToolNames(StringRef Tool, const ToolChain &TC,
253 SmallVectorImpl<std::string> &Names) const;
255 /// \brief Find the appropriate .crash diagonostic file for the child crash
256 /// under this driver and copy it out to a temporary destination with the
257 /// other reproducer related files (.sh, .cache, etc). If not found, suggest a
258 /// directory for the user to look at.
260 /// \param ReproCrashFilename The file path to copy the .crash to.
261 /// \param CrashDiagDir The suggested directory for the user to look at
262 /// in case the search or copy fails.
264 /// \returns If the .crash is found and successfully copied return true,
265 /// otherwise false and return the suggested directory in \p CrashDiagDir.
266 bool getCrashDiagnosticFile(StringRef ReproCrashFilename,
267 SmallString<128> &CrashDiagDir);
270 Driver(StringRef ClangExecutable, StringRef DefaultTargetTriple,
271 DiagnosticsEngine &Diags,
272 IntrusiveRefCntPtr<vfs::FileSystem> VFS = nullptr);
277 /// Name to use when invoking gcc/g++.
278 const std::string &getCCCGenericGCCName() const { return CCCGenericGCCName; }
280 const llvm::opt::OptTable &getOpts() const { return *Opts; }
282 const DiagnosticsEngine &getDiags() const { return Diags; }
284 vfs::FileSystem &getVFS() const { return *VFS; }
286 bool getCheckInputsExist() const { return CheckInputsExist; }
288 void setCheckInputsExist(bool Value) { CheckInputsExist = Value; }
290 const std::string &getTitle() { return DriverTitle; }
291 void setTitle(std::string Value) { DriverTitle = std::move(Value); }
293 /// \brief Get the path to the main clang executable.
294 const char *getClangProgramPath() const {
295 return ClangExecutable.c_str();
298 /// \brief Get the path to where the clang executable was installed.
299 const char *getInstalledDir() const {
300 if (!InstalledDir.empty())
301 return InstalledDir.c_str();
304 void setInstalledDir(StringRef Value) {
305 InstalledDir = Value;
308 bool isSaveTempsEnabled() const { return SaveTemps != SaveTempsNone; }
309 bool isSaveTempsObj() const { return SaveTemps == SaveTempsObj; }
311 bool embedBitcodeEnabled() const { return BitcodeEmbed != EmbedNone; }
312 bool embedBitcodeInObject() const { return (BitcodeEmbed == EmbedBitcode); }
313 bool embedBitcodeMarkerOnly() const { return (BitcodeEmbed == EmbedMarker); }
315 /// Compute the desired OpenMP runtime from the flags provided.
316 OpenMPRuntimeKind getOpenMPRuntime(const llvm::opt::ArgList &Args) const;
319 /// @name Primary Functionality
322 /// CreateOffloadingDeviceToolChains - create all the toolchains required to
323 /// support offloading devices given the programming models specified in the
324 /// current compilation. Also, update the host tool chain kind accordingly.
325 void CreateOffloadingDeviceToolChains(Compilation &C, InputList &Inputs);
327 /// BuildCompilation - Construct a compilation object for a command
328 /// line argument vector.
330 /// \return A compilation, or 0 if none was built for the given
331 /// argument vector. A null return value does not necessarily
332 /// indicate an error condition, the diagnostics should be queried
333 /// to determine if an error occurred.
334 Compilation *BuildCompilation(ArrayRef<const char *> Args);
336 /// @name Driver Steps
339 /// ParseDriverMode - Look for and handle the driver mode option in Args.
340 void ParseDriverMode(StringRef ProgramName, ArrayRef<const char *> Args);
342 /// ParseArgStrings - Parse the given list of strings into an
344 llvm::opt::InputArgList ParseArgStrings(ArrayRef<const char *> Args,
345 bool &ContainsError);
347 /// BuildInputs - Construct the list of inputs and their types from
348 /// the given arguments.
350 /// \param TC - The default host tool chain.
351 /// \param Args - The input arguments.
352 /// \param Inputs - The list to store the resulting compilation
354 void BuildInputs(const ToolChain &TC, llvm::opt::DerivedArgList &Args,
355 InputList &Inputs) const;
357 /// BuildActions - Construct the list of actions to perform for the
358 /// given arguments, which are only done for a single architecture.
360 /// \param C - The compilation that is being built.
361 /// \param Args - The input arguments.
362 /// \param Actions - The list to store the resulting actions onto.
363 void BuildActions(Compilation &C, llvm::opt::DerivedArgList &Args,
364 const InputList &Inputs, ActionList &Actions) const;
366 /// BuildUniversalActions - Construct the list of actions to perform
367 /// for the given arguments, which may require a universal build.
369 /// \param C - The compilation that is being built.
370 /// \param TC - The default host tool chain.
371 void BuildUniversalActions(Compilation &C, const ToolChain &TC,
372 const InputList &BAInputs) const;
374 /// BuildJobs - Bind actions to concrete tools and translate
375 /// arguments to form the list of jobs to run.
377 /// \param C - The compilation that is being built.
378 void BuildJobs(Compilation &C) const;
380 /// ExecuteCompilation - Execute the compilation according to the command line
381 /// arguments and return an appropriate exit code.
383 /// This routine handles additional processing that must be done in addition
384 /// to just running the subprocesses, for example reporting errors, setting
385 /// up response files, removing temporary files, etc.
386 int ExecuteCompilation(Compilation &C,
387 SmallVectorImpl< std::pair<int, const Command *> > &FailingCommands);
389 /// generateCompilationDiagnostics - Generate diagnostics information
390 /// including preprocessed source file(s).
392 void generateCompilationDiagnostics(Compilation &C,
393 const Command &FailingCommand);
396 /// @name Helper Methods
399 /// PrintActions - Print the list of actions.
400 void PrintActions(const Compilation &C) const;
402 /// PrintHelp - Print the help text.
404 /// \param ShowHidden - Show hidden options.
405 void PrintHelp(bool ShowHidden) const;
407 /// PrintVersion - Print the driver version.
408 void PrintVersion(const Compilation &C, raw_ostream &OS) const;
410 /// GetFilePath - Lookup \p Name in the list of file search paths.
412 /// \param TC - The tool chain for additional information on
413 /// directories to search.
415 // FIXME: This should be in CompilationInfo.
416 std::string GetFilePath(StringRef Name, const ToolChain &TC) const;
418 /// GetProgramPath - Lookup \p Name in the list of program search paths.
420 /// \param TC - The provided tool chain for additional information on
421 /// directories to search.
423 // FIXME: This should be in CompilationInfo.
424 std::string GetProgramPath(StringRef Name, const ToolChain &TC) const;
426 /// HandleImmediateArgs - Handle any arguments which should be
427 /// treated before building actions or binding tools.
429 /// \return Whether any compilation should be built for this
431 bool HandleImmediateArgs(const Compilation &C);
433 /// ConstructAction - Construct the appropriate action to do for
434 /// \p Phase on the \p Input, taking in to account arguments
435 /// like -fsyntax-only or --analyze.
436 Action *ConstructPhaseAction(Compilation &C, const llvm::opt::ArgList &Args,
437 phases::ID Phase, Action *Input) const;
439 /// BuildJobsForAction - Construct the jobs to perform for the action \p A and
440 /// return an InputInfo for the result of running \p A. Will only construct
441 /// jobs for a given (Action, ToolChain, BoundArch, DeviceKind) tuple once.
443 BuildJobsForAction(Compilation &C, const Action *A, const ToolChain *TC,
444 StringRef BoundArch, bool AtTopLevel, bool MultipleArchs,
445 const char *LinkingOutput,
446 std::map<std::pair<const Action *, std::string>, InputInfo>
448 Action::OffloadKind TargetDeviceOffloadKind) const;
450 /// Returns the default name for linked images (e.g., "a.out").
451 const char *getDefaultImageName() const;
453 /// GetNamedOutputPath - Return the name to use for the output of
454 /// the action \p JA. The result is appended to the compilation's
455 /// list of temporary or result files, as appropriate.
457 /// \param C - The compilation.
458 /// \param JA - The action of interest.
459 /// \param BaseInput - The original input file that this action was
461 /// \param BoundArch - The bound architecture.
462 /// \param AtTopLevel - Whether this is a "top-level" action.
463 /// \param MultipleArchs - Whether multiple -arch options were supplied.
464 /// \param NormalizedTriple - The normalized triple of the relevant target.
465 const char *GetNamedOutputPath(Compilation &C, const JobAction &JA,
466 const char *BaseInput, StringRef BoundArch,
467 bool AtTopLevel, bool MultipleArchs,
468 StringRef NormalizedTriple) const;
470 /// GetTemporaryPath - Return the pathname of a temporary file to use
471 /// as part of compilation; the file will have the given prefix and suffix.
473 /// GCC goes to extra lengths here to be a bit more robust.
474 std::string GetTemporaryPath(StringRef Prefix, StringRef Suffix) const;
476 /// Return the pathname of the pch file in clang-cl mode.
477 std::string GetClPchPath(Compilation &C, StringRef BaseName) const;
479 /// ShouldUseClangCompiler - Should the clang compiler be used to
480 /// handle this action.
481 bool ShouldUseClangCompiler(const JobAction &JA) const;
483 /// Returns true if we are performing any kind of LTO.
484 bool isUsingLTO() const { return LTOMode != LTOK_None; }
486 /// Get the specific kind of LTO being performed.
487 LTOKind getLTOMode() const { return LTOMode; }
490 /// Set the driver mode (cl, gcc, etc) from an option string of the form
491 /// --driver-mode=<mode>.
492 void setDriverModeFromOption(StringRef Opt);
494 /// Parse the \p Args list for LTO options and record the type of LTO
495 /// compilation based on which -f(no-)?lto(=.*)? option occurs last.
496 void setLTOMode(const llvm::opt::ArgList &Args);
498 /// \brief Retrieves a ToolChain for a particular \p Target triple.
500 /// Will cache ToolChains for the life of the driver object, and create them
502 const ToolChain &getToolChain(const llvm::opt::ArgList &Args,
503 const llvm::Triple &Target) const;
507 /// \brief Get bitmasks for which option flags to include and exclude based on
509 std::pair<unsigned, unsigned> getIncludeExcludeOptionFlagMasks() const;
511 /// Helper used in BuildJobsForAction. Doesn't use the cache when building
512 /// jobs specifically for the given action, but will use the cache when
513 /// building jobs for the Action's inputs.
514 InputInfo BuildJobsForActionNoCache(
515 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
516 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
517 std::map<std::pair<const Action *, std::string>, InputInfo>
519 Action::OffloadKind TargetDeviceOffloadKind) const;
522 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and
523 /// return the grouped values as integers. Numbers which are not
524 /// provided are set to 0.
526 /// \return True if the entire string was parsed (9.2), or all
527 /// groups were parsed (10.3.5extrastuff). HadExtra is true if all
528 /// groups were parsed but extra characters remain at the end.
529 static bool GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
530 unsigned &Micro, bool &HadExtra);
532 /// Parse digits from a string \p Str and fulfill \p Digits with
533 /// the parsed numbers. This method assumes that the max number of
534 /// digits to look for is equal to Digits.size().
536 /// \return True if the entire string was parsed and there are
537 /// no extra characters remaining at the end.
538 static bool GetReleaseVersion(StringRef Str,
539 MutableArrayRef<unsigned> Digits);
542 /// \return True if the last defined optimization level is -Ofast.
543 /// And False otherwise.
544 bool isOptimizationLevelFast(const llvm::opt::ArgList &Args);
546 } // end namespace driver
547 } // end namespace clang