1 //===--- Driver.h - Clang GCC Compatible Driver -----------------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #ifndef CLANG_DRIVER_DRIVER_H_ 11 #define CLANG_DRIVER_DRIVER_H_ 12 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 22 // lands. 23 #include <list> 24 #include <set> 25 #include <string> 26 27 namespace clang { 28 namespace driver { 29 class Action; 30 class Arg; 31 class ArgList; 32 class Command; 33 class Compilation; 34 class DerivedArgList; 35 class InputArgList; 36 class InputInfo; 37 class JobAction; 38 class OptTable; 39 class ToolChain; 40 41 /// Driver - Encapsulate logic for constructing compilation processes 42 /// from a set of gcc-driver-like command line arguments. 43 class Driver { 44 OptTable *Opts; 45 46 DiagnosticsEngine &Diags; 47 48 public: 49 // Diag - Forwarding function for diagnostics. Diag(unsigned DiagID)50 DiagnosticBuilder Diag(unsigned DiagID) const { 51 return Diags.Report(DiagID); 52 } 53 54 // FIXME: Privatize once interface is stable. 55 public: 56 /// The name the driver was invoked as. 57 std::string Name; 58 59 /// The path the driver executable was in, as invoked from the 60 /// command line. 61 std::string Dir; 62 63 /// The original path to the clang executable. 64 std::string ClangExecutable; 65 66 /// The path to the installed clang directory, if any. 67 std::string InstalledDir; 68 69 /// The path to the compiler resource directory. 70 std::string ResourceDir; 71 72 /// A prefix directory used to emulated a limited subset of GCC's '-Bprefix' 73 /// functionality. 74 /// FIXME: This type of customization should be removed in favor of the 75 /// universal driver when it is ready. 76 typedef SmallVector<std::string, 4> prefix_list; 77 prefix_list PrefixDirs; 78 79 /// sysroot, if present 80 std::string SysRoot; 81 82 /// If the standard library is used 83 bool UseStdLib; 84 85 /// Default target triple. 86 std::string DefaultTargetTriple; 87 88 /// Default name for linked images (e.g., "a.out"). 89 std::string DefaultImageName; 90 91 /// Driver title to use with help. 92 std::string DriverTitle; 93 94 /// Information about the host which can be overridden by the user. 95 std::string HostBits, HostMachine, HostSystem, HostRelease; 96 97 /// The file to log CC_PRINT_OPTIONS output to, if enabled. 98 const char *CCPrintOptionsFilename; 99 100 /// The file to log CC_PRINT_HEADERS output to, if enabled. 101 const char *CCPrintHeadersFilename; 102 103 /// The file to log CC_LOG_DIAGNOSTICS output to, if enabled. 104 const char *CCLogDiagnosticsFilename; 105 106 /// A list of inputs and their types for the given arguments. 107 typedef SmallVector<std::pair<types::ID, const Arg*>, 16> InputList; 108 109 /// Whether the driver should follow g++ like behavior. 110 unsigned CCCIsCXX : 1; 111 112 /// Whether the driver is just the preprocessor. 113 unsigned CCCIsCPP : 1; 114 115 /// Echo commands while executing (in -v style). 116 unsigned CCCEcho : 1; 117 118 /// Only print tool bindings, don't build any jobs. 119 unsigned CCCPrintBindings : 1; 120 121 /// Set CC_PRINT_OPTIONS mode, which is like -v but logs the commands to 122 /// CCPrintOptionsFilename or to stderr. 123 unsigned CCPrintOptions : 1; 124 125 /// Set CC_PRINT_HEADERS mode, which causes the frontend to log header include 126 /// information to CCPrintHeadersFilename or to stderr. 127 unsigned CCPrintHeaders : 1; 128 129 /// Set CC_LOG_DIAGNOSTICS mode, which causes the frontend to log diagnostics 130 /// to CCLogDiagnosticsFilename or to stderr, in a stable machine readable 131 /// format. 132 unsigned CCLogDiagnostics : 1; 133 134 /// Whether the driver is generating diagnostics for debugging purposes. 135 unsigned CCGenDiagnostics : 1; 136 137 private: 138 /// Name to use when invoking gcc/g++. 139 std::string CCCGenericGCCName; 140 141 /// Whether to check that input files exist when constructing compilation 142 /// jobs. 143 unsigned CheckInputsExist : 1; 144 145 public: 146 /// Use lazy precompiled headers for PCH support. 147 unsigned CCCUsePCH : 1; 148 149 private: 150 /// Certain options suppress the 'no input files' warning. 151 bool SuppressMissingInputWarning : 1; 152 153 std::list<std::string> TempFiles; 154 std::list<std::string> ResultFiles; 155 156 /// \brief Cache of all the ToolChains in use by the driver. 157 /// 158 /// This maps from the string representation of a triple to a ToolChain 159 /// created targeting that triple. The driver owns all the ToolChain objects 160 /// stored in it, and will clean them up when torn down. 161 mutable llvm::StringMap<ToolChain *> ToolChains; 162 163 private: 164 /// TranslateInputArgs - Create a new derived argument list from the input 165 /// arguments, after applying the standard argument translations. 166 DerivedArgList *TranslateInputArgs(const InputArgList &Args) const; 167 168 // getFinalPhase - Determine which compilation mode we are in and record 169 // which option we used to determine the final phase. 170 phases::ID getFinalPhase(const DerivedArgList &DAL, Arg **FinalPhaseArg = 0) 171 const; 172 173 public: 174 Driver(StringRef _ClangExecutable, 175 StringRef _DefaultTargetTriple, 176 StringRef _DefaultImageName, 177 DiagnosticsEngine &_Diags); 178 ~Driver(); 179 180 /// @name Accessors 181 /// @{ 182 183 /// Name to use when invoking gcc/g++. getCCCGenericGCCName()184 const std::string &getCCCGenericGCCName() const { return CCCGenericGCCName; } 185 186 getOpts()187 const OptTable &getOpts() const { return *Opts; } 188 getDiags()189 const DiagnosticsEngine &getDiags() const { return Diags; } 190 getCheckInputsExist()191 bool getCheckInputsExist() const { return CheckInputsExist; } 192 setCheckInputsExist(bool Value)193 void setCheckInputsExist(bool Value) { CheckInputsExist = Value; } 194 getTitle()195 const std::string &getTitle() { return DriverTitle; } setTitle(std::string Value)196 void setTitle(std::string Value) { DriverTitle = Value; } 197 198 /// \brief Get the path to the main clang executable. getClangProgramPath()199 const char *getClangProgramPath() const { 200 return ClangExecutable.c_str(); 201 } 202 203 /// \brief Get the path to where the clang executable was installed. getInstalledDir()204 const char *getInstalledDir() const { 205 if (!InstalledDir.empty()) 206 return InstalledDir.c_str(); 207 return Dir.c_str(); 208 } setInstalledDir(StringRef Value)209 void setInstalledDir(StringRef Value) { 210 InstalledDir = Value; 211 } 212 213 /// @} 214 /// @name Primary Functionality 215 /// @{ 216 217 /// BuildCompilation - Construct a compilation object for a command 218 /// line argument vector. 219 /// 220 /// \return A compilation, or 0 if none was built for the given 221 /// argument vector. A null return value does not necessarily 222 /// indicate an error condition, the diagnostics should be queried 223 /// to determine if an error occurred. 224 Compilation *BuildCompilation(ArrayRef<const char *> Args); 225 226 /// @name Driver Steps 227 /// @{ 228 229 /// ParseArgStrings - Parse the given list of strings into an 230 /// ArgList. 231 InputArgList *ParseArgStrings(ArrayRef<const char *> Args); 232 233 /// BuildInputs - Construct the list of inputs and their types from 234 /// the given arguments. 235 /// 236 /// \param TC - The default host tool chain. 237 /// \param Args - The input arguments. 238 /// \param Inputs - The list to store the resulting compilation 239 /// inputs onto. 240 void BuildInputs(const ToolChain &TC, const DerivedArgList &Args, 241 InputList &Inputs) const; 242 243 /// BuildActions - Construct the list of actions to perform for the 244 /// given arguments, which are only done for a single architecture. 245 /// 246 /// \param TC - The default host tool chain. 247 /// \param Args - The input arguments. 248 /// \param Actions - The list to store the resulting actions onto. 249 void BuildActions(const ToolChain &TC, const DerivedArgList &Args, 250 const InputList &Inputs, ActionList &Actions) const; 251 252 /// BuildUniversalActions - Construct the list of actions to perform 253 /// for the given arguments, which may require a universal build. 254 /// 255 /// \param TC - The default host tool chain. 256 /// \param Args - The input arguments. 257 /// \param Actions - The list to store the resulting actions onto. 258 void BuildUniversalActions(const ToolChain &TC, const DerivedArgList &Args, 259 const InputList &BAInputs, 260 ActionList &Actions) const; 261 262 /// BuildJobs - Bind actions to concrete tools and translate 263 /// arguments to form the list of jobs to run. 264 /// 265 /// \param C - The compilation that is being built. 266 void BuildJobs(Compilation &C) const; 267 268 /// ExecuteCompilation - Execute the compilation according to the command line 269 /// arguments and return an appropriate exit code. 270 /// 271 /// This routine handles additional processing that must be done in addition 272 /// to just running the subprocesses, for example reporting errors, removing 273 /// temporary files, etc. 274 int ExecuteCompilation(const Compilation &C, 275 SmallVectorImpl< std::pair<int, const Command *> > &FailingCommands) const; 276 277 /// generateCompilationDiagnostics - Generate diagnostics information 278 /// including preprocessed source file(s). 279 /// 280 void generateCompilationDiagnostics(Compilation &C, 281 const Command *FailingCommand); 282 283 /// @} 284 /// @name Helper Methods 285 /// @{ 286 287 /// PrintActions - Print the list of actions. 288 void PrintActions(const Compilation &C) const; 289 290 /// PrintHelp - Print the help text. 291 /// 292 /// \param ShowHidden - Show hidden options. 293 void PrintHelp(bool ShowHidden) const; 294 295 /// PrintOptions - Print the list of arguments. 296 void PrintOptions(const ArgList &Args) const; 297 298 /// PrintVersion - Print the driver version. 299 void PrintVersion(const Compilation &C, raw_ostream &OS) const; 300 301 /// GetFilePath - Lookup \p Name in the list of file search paths. 302 /// 303 /// \param TC - The tool chain for additional information on 304 /// directories to search. 305 // 306 // FIXME: This should be in CompilationInfo. 307 std::string GetFilePath(const char *Name, const ToolChain &TC) const; 308 309 /// GetProgramPath - Lookup \p Name in the list of program search paths. 310 /// 311 /// \param TC - The provided tool chain for additional information on 312 /// directories to search. 313 // 314 // FIXME: This should be in CompilationInfo. 315 std::string GetProgramPath(const char *Name, const ToolChain &TC) const; 316 317 /// HandleImmediateArgs - Handle any arguments which should be 318 /// treated before building actions or binding tools. 319 /// 320 /// \return Whether any compilation should be built for this 321 /// invocation. 322 bool HandleImmediateArgs(const Compilation &C); 323 324 /// ConstructAction - Construct the appropriate action to do for 325 /// \p Phase on the \p Input, taking in to account arguments 326 /// like -fsyntax-only or --analyze. 327 Action *ConstructPhaseAction(const ArgList &Args, phases::ID Phase, 328 Action *Input) const; 329 330 331 /// BuildJobsForAction - Construct the jobs to perform for the 332 /// action \p A. 333 void BuildJobsForAction(Compilation &C, 334 const Action *A, 335 const ToolChain *TC, 336 const char *BoundArch, 337 bool AtTopLevel, 338 const char *LinkingOutput, 339 InputInfo &Result) const; 340 341 /// GetNamedOutputPath - Return the name to use for the output of 342 /// the action \p JA. The result is appended to the compilation's 343 /// list of temporary or result files, as appropriate. 344 /// 345 /// \param C - The compilation. 346 /// \param JA - The action of interest. 347 /// \param BaseInput - The original input file that this action was 348 /// triggered by. 349 /// \param AtTopLevel - Whether this is a "top-level" action. 350 const char *GetNamedOutputPath(Compilation &C, 351 const JobAction &JA, 352 const char *BaseInput, 353 bool AtTopLevel) const; 354 355 /// GetTemporaryPath - Return the pathname of a temporary file to use 356 /// as part of compilation; the file will have the given prefix and suffix. 357 /// 358 /// GCC goes to extra lengths here to be a bit more robust. 359 std::string GetTemporaryPath(StringRef Prefix, const char *Suffix) const; 360 361 /// ShouldUseClangCompiler - Should the clang compiler be used to 362 /// handle this action. 363 bool ShouldUseClangCompiler(const JobAction &JA) const; 364 365 bool IsUsingLTO(const ArgList &Args) const; 366 367 private: 368 /// \brief Retrieves a ToolChain for a particular target triple. 369 /// 370 /// Will cache ToolChains for the life of the driver object, and create them 371 /// on-demand. 372 const ToolChain &getToolChain(const ArgList &Args, 373 StringRef DarwinArchName = "") const; 374 375 /// @} 376 377 public: 378 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and 379 /// return the grouped values as integers. Numbers which are not 380 /// provided are set to 0. 381 /// 382 /// \return True if the entire string was parsed (9.2), or all 383 /// groups were parsed (10.3.5extrastuff). HadExtra is true if all 384 /// groups were parsed but extra characters remain at the end. 385 static bool GetReleaseVersion(const char *Str, unsigned &Major, 386 unsigned &Minor, unsigned &Micro, 387 bool &HadExtra); 388 }; 389 390 } // end namespace driver 391 } // end namespace clang 392 393 #endif 394