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/Phases.h"
16 #include "clang/Driver/Types.h"
17 #include "clang/Driver/Util.h"
18 #include "llvm/ADT/StringMap.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/Support/Path.h" // FIXME: Kill when CompilationInfo lands.
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 llvm::opt::OptTable *Opts;
68 DiagnosticsEngine &Diags;
70 IntrusiveRefCntPtr<vfs::FileSystem> VFS;
85 /// LTO mode selected via -f(no-)?lto(=.*)? options.
89 // Diag - Forwarding function for diagnostics.
90 DiagnosticBuilder Diag(unsigned DiagID) const {
91 return Diags.Report(DiagID);
94 // FIXME: Privatize once interface is stable.
96 /// The name the driver was invoked as.
99 /// The path the driver executable was in, as invoked from the
103 /// The original path to the clang executable.
104 std::string ClangExecutable;
106 /// The path to the installed clang directory, if any.
107 std::string InstalledDir;
109 /// The path to the compiler resource directory.
110 std::string ResourceDir;
112 /// A prefix directory used to emulate a limited subset of GCC's '-Bprefix'
114 /// FIXME: This type of customization should be removed in favor of the
115 /// universal driver when it is ready.
116 typedef SmallVector<std::string, 4> prefix_list;
117 prefix_list PrefixDirs;
119 /// sysroot, if present
122 /// Dynamic loader prefix, if present
123 std::string DyldPrefix;
125 /// If the standard library is used
128 /// Default target triple.
129 std::string DefaultTargetTriple;
131 /// Driver title to use with help.
132 std::string DriverTitle;
134 /// Information about the host which can be overridden by the user.
135 std::string HostBits, HostMachine, HostSystem, HostRelease;
137 /// The file to log CC_PRINT_OPTIONS output to, if enabled.
138 const char *CCPrintOptionsFilename;
140 /// The file to log CC_PRINT_HEADERS output to, if enabled.
141 const char *CCPrintHeadersFilename;
143 /// The file to log CC_LOG_DIAGNOSTICS output to, if enabled.
144 const char *CCLogDiagnosticsFilename;
146 /// A list of inputs and their types for the given arguments.
147 typedef SmallVector<std::pair<types::ID, const llvm::opt::Arg *>, 16>
150 /// Whether the driver should follow g++ like behavior.
151 bool CCCIsCXX() const { return Mode == GXXMode; }
153 /// Whether the driver is just the preprocessor.
154 bool CCCIsCPP() const { return Mode == CPPMode; }
156 /// Whether the driver should follow cl.exe like behavior.
157 bool IsCLMode() const { return Mode == CLMode; }
159 /// Only print tool bindings, don't build any jobs.
160 unsigned CCCPrintBindings : 1;
162 /// Set CC_PRINT_OPTIONS mode, which is like -v but logs the commands to
163 /// CCPrintOptionsFilename or to stderr.
164 unsigned CCPrintOptions : 1;
166 /// Set CC_PRINT_HEADERS mode, which causes the frontend to log header include
167 /// information to CCPrintHeadersFilename or to stderr.
168 unsigned CCPrintHeaders : 1;
170 /// Set CC_LOG_DIAGNOSTICS mode, which causes the frontend to log diagnostics
171 /// to CCLogDiagnosticsFilename or to stderr, in a stable machine readable
173 unsigned CCLogDiagnostics : 1;
175 /// Whether the driver is generating diagnostics for debugging purposes.
176 unsigned CCGenDiagnostics : 1;
179 /// Name to use when invoking gcc/g++.
180 std::string CCCGenericGCCName;
182 /// Whether to check that input files exist when constructing compilation
184 unsigned CheckInputsExist : 1;
187 /// Use lazy precompiled headers for PCH support.
188 unsigned CCCUsePCH : 1;
191 /// Certain options suppress the 'no input files' warning.
192 bool SuppressMissingInputWarning : 1;
194 std::list<std::string> TempFiles;
195 std::list<std::string> ResultFiles;
197 /// \brief Cache of all the ToolChains in use by the driver.
199 /// This maps from the string representation of a triple to a ToolChain
200 /// created targeting that triple. The driver owns all the ToolChain objects
201 /// stored in it, and will clean them up when torn down.
202 mutable llvm::StringMap<ToolChain *> ToolChains;
205 /// TranslateInputArgs - Create a new derived argument list from the input
206 /// arguments, after applying the standard argument translations.
207 llvm::opt::DerivedArgList *
208 TranslateInputArgs(const llvm::opt::InputArgList &Args) const;
210 // getFinalPhase - Determine which compilation mode we are in and record
211 // which option we used to determine the final phase.
212 phases::ID getFinalPhase(const llvm::opt::DerivedArgList &DAL,
213 llvm::opt::Arg **FinalPhaseArg = nullptr) const;
215 // Before executing jobs, sets up response files for commands that need them.
216 void setUpResponseFiles(Compilation &C, Command &Cmd);
218 void generatePrefixedToolNames(const char *Tool, const ToolChain &TC,
219 SmallVectorImpl<std::string> &Names) const;
222 Driver(StringRef ClangExecutable, StringRef DefaultTargetTriple,
223 DiagnosticsEngine &Diags,
224 IntrusiveRefCntPtr<vfs::FileSystem> VFS = nullptr);
230 /// Name to use when invoking gcc/g++.
231 const std::string &getCCCGenericGCCName() const { return CCCGenericGCCName; }
233 const llvm::opt::OptTable &getOpts() const { return *Opts; }
235 const DiagnosticsEngine &getDiags() const { return Diags; }
237 vfs::FileSystem &getVFS() const { return *VFS; }
239 bool getCheckInputsExist() const { return CheckInputsExist; }
241 void setCheckInputsExist(bool Value) { CheckInputsExist = Value; }
243 const std::string &getTitle() { return DriverTitle; }
244 void setTitle(std::string Value) { DriverTitle = Value; }
246 /// \brief Get the path to the main clang executable.
247 const char *getClangProgramPath() const {
248 return ClangExecutable.c_str();
251 /// \brief Get the path to where the clang executable was installed.
252 const char *getInstalledDir() const {
253 if (!InstalledDir.empty())
254 return InstalledDir.c_str();
257 void setInstalledDir(StringRef Value) {
258 InstalledDir = Value;
261 bool isSaveTempsEnabled() const { return SaveTemps != SaveTempsNone; }
262 bool isSaveTempsObj() const { return SaveTemps == SaveTempsObj; }
265 /// @name Primary Functionality
268 /// BuildCompilation - Construct a compilation object for a command
269 /// line argument vector.
271 /// \return A compilation, or 0 if none was built for the given
272 /// argument vector. A null return value does not necessarily
273 /// indicate an error condition, the diagnostics should be queried
274 /// to determine if an error occurred.
275 Compilation *BuildCompilation(ArrayRef<const char *> Args);
277 /// @name Driver Steps
280 /// ParseDriverMode - Look for and handle the driver mode option in Args.
281 void ParseDriverMode(ArrayRef<const char *> Args);
283 /// ParseArgStrings - Parse the given list of strings into an
285 llvm::opt::InputArgList ParseArgStrings(ArrayRef<const char *> Args);
287 /// BuildInputs - Construct the list of inputs and their types from
288 /// the given arguments.
290 /// \param TC - The default host tool chain.
291 /// \param Args - The input arguments.
292 /// \param Inputs - The list to store the resulting compilation
294 void BuildInputs(const ToolChain &TC, llvm::opt::DerivedArgList &Args,
295 InputList &Inputs) const;
297 /// BuildActions - Construct the list of actions to perform for the
298 /// given arguments, which are only done for a single architecture.
300 /// \param C - The compilation that is being built.
301 /// \param TC - The default host tool chain.
302 /// \param Args - The input arguments.
303 /// \param Actions - The list to store the resulting actions onto.
304 void BuildActions(Compilation &C, const ToolChain &TC,
305 llvm::opt::DerivedArgList &Args, const InputList &Inputs,
306 ActionList &Actions) const;
308 /// BuildUniversalActions - Construct the list of actions to perform
309 /// for the given arguments, which may require a universal build.
311 /// \param C - The compilation that is being built.
312 /// \param TC - The default host tool chain.
313 void BuildUniversalActions(Compilation &C, const ToolChain &TC,
314 const InputList &BAInputs) const;
316 /// BuildJobs - Bind actions to concrete tools and translate
317 /// arguments to form the list of jobs to run.
319 /// \param C - The compilation that is being built.
320 void BuildJobs(Compilation &C) const;
322 /// ExecuteCompilation - Execute the compilation according to the command line
323 /// arguments and return an appropriate exit code.
325 /// This routine handles additional processing that must be done in addition
326 /// to just running the subprocesses, for example reporting errors, setting
327 /// up response files, removing temporary files, etc.
328 int ExecuteCompilation(Compilation &C,
329 SmallVectorImpl< std::pair<int, const Command *> > &FailingCommands);
331 /// generateCompilationDiagnostics - Generate diagnostics information
332 /// including preprocessed source file(s).
334 void generateCompilationDiagnostics(Compilation &C,
335 const Command &FailingCommand);
338 /// @name Helper Methods
341 /// PrintActions - Print the list of actions.
342 void PrintActions(const Compilation &C) const;
344 /// PrintHelp - Print the help text.
346 /// \param ShowHidden - Show hidden options.
347 void PrintHelp(bool ShowHidden) const;
349 /// PrintVersion - Print the driver version.
350 void PrintVersion(const Compilation &C, raw_ostream &OS) const;
352 /// GetFilePath - Lookup \p Name in the list of file search paths.
354 /// \param TC - The tool chain for additional information on
355 /// directories to search.
357 // FIXME: This should be in CompilationInfo.
358 std::string GetFilePath(const char *Name, const ToolChain &TC) const;
360 /// GetProgramPath - Lookup \p Name in the list of program search paths.
362 /// \param TC - The provided tool chain for additional information on
363 /// directories to search.
365 // FIXME: This should be in CompilationInfo.
366 std::string GetProgramPath(const char *Name, const ToolChain &TC) const;
368 /// HandleImmediateArgs - Handle any arguments which should be
369 /// treated before building actions or binding tools.
371 /// \return Whether any compilation should be built for this
373 bool HandleImmediateArgs(const Compilation &C);
375 /// ConstructAction - Construct the appropriate action to do for
376 /// \p Phase on the \p Input, taking in to account arguments
377 /// like -fsyntax-only or --analyze.
378 Action *ConstructPhaseAction(Compilation &C, const ToolChain &TC,
379 const llvm::opt::ArgList &Args, phases::ID Phase,
380 Action *Input) const;
382 /// BuildJobsForAction - Construct the jobs to perform for the
383 /// action \p A and return an InputInfo for the result of running \p A.
384 InputInfo BuildJobsForAction(Compilation &C, const Action *A,
385 const ToolChain *TC, const char *BoundArch,
386 bool AtTopLevel, bool MultipleArchs,
387 const char *LinkingOutput) const;
389 /// Returns the default name for linked images (e.g., "a.out").
390 const char *getDefaultImageName() const;
392 /// GetNamedOutputPath - Return the name to use for the output of
393 /// the action \p JA. The result is appended to the compilation's
394 /// list of temporary or result files, as appropriate.
396 /// \param C - The compilation.
397 /// \param JA - The action of interest.
398 /// \param BaseInput - The original input file that this action was
400 /// \param BoundArch - The bound architecture.
401 /// \param AtTopLevel - Whether this is a "top-level" action.
402 /// \param MultipleArchs - Whether multiple -arch options were supplied.
403 const char *GetNamedOutputPath(Compilation &C,
405 const char *BaseInput,
406 const char *BoundArch,
408 bool MultipleArchs) const;
410 /// GetTemporaryPath - Return the pathname of a temporary file to use
411 /// as part of compilation; the file will have the given prefix and suffix.
413 /// GCC goes to extra lengths here to be a bit more robust.
414 std::string GetTemporaryPath(StringRef Prefix, const char *Suffix) const;
416 /// ShouldUseClangCompiler - Should the clang compiler be used to
417 /// handle this action.
418 bool ShouldUseClangCompiler(const JobAction &JA) const;
420 /// Returns true if we are performing any kind of LTO.
421 bool isUsingLTO() const { return LTOMode != LTOK_None; }
423 /// Get the specific kind of LTO being performed.
424 LTOKind getLTOMode() const { return LTOMode; }
427 /// Parse the \p Args list for LTO options and record the type of LTO
428 /// compilation based on which -f(no-)?lto(=.*)? option occurs last.
429 void setLTOMode(const llvm::opt::ArgList &Args);
431 /// \brief Retrieves a ToolChain for a particular \p Target triple.
433 /// Will cache ToolChains for the life of the driver object, and create them
435 const ToolChain &getToolChain(const llvm::opt::ArgList &Args,
436 const llvm::Triple &Target) const;
440 /// \brief Get bitmasks for which option flags to include and exclude based on
442 std::pair<unsigned, unsigned> getIncludeExcludeOptionFlagMasks() const;
445 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and
446 /// return the grouped values as integers. Numbers which are not
447 /// provided are set to 0.
449 /// \return True if the entire string was parsed (9.2), or all
450 /// groups were parsed (10.3.5extrastuff). HadExtra is true if all
451 /// groups were parsed but extra characters remain at the end.
452 static bool GetReleaseVersion(const char *Str, unsigned &Major,
453 unsigned &Minor, unsigned &Micro,
457 /// \return True if the last defined optimization level is -Ofast.
458 /// And False otherwise.
459 bool isOptimizationLevelFast(const llvm::opt::ArgList &Args);
461 } // end namespace driver
462 } // end namespace clang