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 LLVM_CLANG_DRIVER_DRIVER_H 11 #define LLVM_CLANG_DRIVER_DRIVER_H 12 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" 24 25 #include <list> 26 #include <map> 27 #include <string> 28 29 namespace llvm { 30 class Triple; 31 namespace vfs { 32 class FileSystem; 33 } 34 } // namespace llvm 35 36 namespace clang { 37 38 namespace driver { 39 40 class Command; 41 class Compilation; 42 class InputInfo; 43 class JobList; 44 class JobAction; 45 class SanitizerArgs; 46 class ToolChain; 47 48 /// Describes the kind of LTO mode selected via -f(no-)?lto(=.*)? options. 49 enum LTOKind { 50 LTOK_None, 51 LTOK_Full, 52 LTOK_Thin, 53 LTOK_Unknown 54 }; 55 56 /// Driver - Encapsulate logic for constructing compilation processes 57 /// from a set of gcc-driver-like command line arguments. 58 class Driver { 59 std::unique_ptr<llvm::opt::OptTable> Opts; 60 61 DiagnosticsEngine &Diags; 62 63 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS; 64 65 enum DriverMode { 66 GCCMode, 67 GXXMode, 68 CPPMode, 69 CLMode 70 } Mode; 71 72 enum SaveTempsMode { 73 SaveTempsNone, 74 SaveTempsCwd, 75 SaveTempsObj 76 } SaveTemps; 77 78 enum BitcodeEmbedMode { 79 EmbedNone, 80 EmbedMarker, 81 EmbedBitcode 82 } BitcodeEmbed; 83 84 /// LTO mode selected via -f(no-)?lto(=.*)? options. 85 LTOKind LTOMode; 86 87 public: 88 enum OpenMPRuntimeKind { 89 /// An unknown OpenMP runtime. We can't generate effective OpenMP code 90 /// without knowing what runtime to target. 91 OMPRT_Unknown, 92 93 /// The LLVM OpenMP runtime. When completed and integrated, this will become 94 /// the default for Clang. 95 OMPRT_OMP, 96 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. 100 OMPRT_GOMP, 101 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. 105 OMPRT_IOMP5 106 }; 107 108 // Diag - Forwarding function for diagnostics. Diag(unsigned DiagID)109 DiagnosticBuilder Diag(unsigned DiagID) const { 110 return Diags.Report(DiagID); 111 } 112 113 // FIXME: Privatize once interface is stable. 114 public: 115 /// The name the driver was invoked as. 116 std::string Name; 117 118 /// The path the driver executable was in, as invoked from the 119 /// command line. 120 std::string Dir; 121 122 /// The original path to the clang executable. 123 std::string ClangExecutable; 124 125 /// Target and driver mode components extracted from clang executable name. 126 ParsedClangName ClangNameParts; 127 128 /// The path to the installed clang directory, if any. 129 std::string InstalledDir; 130 131 /// The path to the compiler resource directory. 132 std::string ResourceDir; 133 134 /// System directory for config files. 135 std::string SystemConfigDir; 136 137 /// User directory for config files. 138 std::string UserConfigDir; 139 140 /// A prefix directory used to emulate a limited subset of GCC's '-Bprefix' 141 /// functionality. 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; 146 147 /// sysroot, if present 148 std::string SysRoot; 149 150 /// Dynamic loader prefix, if present 151 std::string DyldPrefix; 152 153 /// Driver title to use with help. 154 std::string DriverTitle; 155 156 /// Information about the host which can be overridden by the user. 157 std::string HostBits, HostMachine, HostSystem, HostRelease; 158 159 /// The file to log CC_PRINT_OPTIONS output to, if enabled. 160 const char *CCPrintOptionsFilename; 161 162 /// The file to log CC_PRINT_HEADERS output to, if enabled. 163 const char *CCPrintHeadersFilename; 164 165 /// The file to log CC_LOG_DIAGNOSTICS output to, if enabled. 166 const char *CCLogDiagnosticsFilename; 167 168 /// A list of inputs and their types for the given arguments. 169 typedef SmallVector<std::pair<types::ID, const llvm::opt::Arg *>, 16> 170 InputList; 171 172 /// Whether the driver should follow g++ like behavior. CCCIsCXX()173 bool CCCIsCXX() const { return Mode == GXXMode; } 174 175 /// Whether the driver is just the preprocessor. CCCIsCPP()176 bool CCCIsCPP() const { return Mode == CPPMode; } 177 178 /// Whether the driver should follow gcc like behavior. CCCIsCC()179 bool CCCIsCC() const { return Mode == GCCMode; } 180 181 /// Whether the driver should follow cl.exe like behavior. IsCLMode()182 bool IsCLMode() const { return Mode == CLMode; } 183 184 /// Only print tool bindings, don't build any jobs. 185 unsigned CCCPrintBindings : 1; 186 187 /// Set CC_PRINT_OPTIONS mode, which is like -v but logs the commands to 188 /// CCPrintOptionsFilename or to stderr. 189 unsigned CCPrintOptions : 1; 190 191 /// Set CC_PRINT_HEADERS mode, which causes the frontend to log header include 192 /// information to CCPrintHeadersFilename or to stderr. 193 unsigned CCPrintHeaders : 1; 194 195 /// Set CC_LOG_DIAGNOSTICS mode, which causes the frontend to log diagnostics 196 /// to CCLogDiagnosticsFilename or to stderr, in a stable machine readable 197 /// format. 198 unsigned CCLogDiagnostics : 1; 199 200 /// Whether the driver is generating diagnostics for debugging purposes. 201 unsigned CCGenDiagnostics : 1; 202 203 private: 204 /// Raw target triple. 205 std::string TargetTriple; 206 207 /// Name to use when invoking gcc/g++. 208 std::string CCCGenericGCCName; 209 210 /// Name of configuration file if used. 211 std::string ConfigFile; 212 213 /// Allocator for string saver. 214 llvm::BumpPtrAllocator Alloc; 215 216 /// Object that stores strings read from configuration file. 217 llvm::StringSaver Saver; 218 219 /// Arguments originated from configuration file. 220 std::unique_ptr<llvm::opt::InputArgList> CfgOptions; 221 222 /// Arguments originated from command line. 223 std::unique_ptr<llvm::opt::InputArgList> CLOptions; 224 225 /// Whether to check that input files exist when constructing compilation 226 /// jobs. 227 unsigned CheckInputsExist : 1; 228 229 public: 230 /// Force clang to emit reproducer for driver invocation. This is enabled 231 /// indirectly by setting FORCE_CLANG_DIAGNOSTICS_CRASH environment variable 232 /// or when using the -gen-reproducer driver flag. 233 unsigned GenReproducer : 1; 234 235 private: 236 /// Certain options suppress the 'no input files' warning. 237 unsigned SuppressMissingInputWarning : 1; 238 239 std::list<std::string> TempFiles; 240 std::list<std::string> ResultFiles; 241 242 /// Cache of all the ToolChains in use by the driver. 243 /// 244 /// This maps from the string representation of a triple to a ToolChain 245 /// created targeting that triple. The driver owns all the ToolChain objects 246 /// stored in it, and will clean them up when torn down. 247 mutable llvm::StringMap<std::unique_ptr<ToolChain>> ToolChains; 248 249 private: 250 /// TranslateInputArgs - Create a new derived argument list from the input 251 /// arguments, after applying the standard argument translations. 252 llvm::opt::DerivedArgList * 253 TranslateInputArgs(const llvm::opt::InputArgList &Args) const; 254 255 // getFinalPhase - Determine which compilation mode we are in and record 256 // which option we used to determine the final phase. 257 phases::ID getFinalPhase(const llvm::opt::DerivedArgList &DAL, 258 llvm::opt::Arg **FinalPhaseArg = nullptr) const; 259 260 // Before executing jobs, sets up response files for commands that need them. 261 void setUpResponseFiles(Compilation &C, Command &Cmd); 262 263 void generatePrefixedToolNames(StringRef Tool, const ToolChain &TC, 264 SmallVectorImpl<std::string> &Names) const; 265 266 /// Find the appropriate .crash diagonostic file for the child crash 267 /// under this driver and copy it out to a temporary destination with the 268 /// other reproducer related files (.sh, .cache, etc). If not found, suggest a 269 /// directory for the user to look at. 270 /// 271 /// \param ReproCrashFilename The file path to copy the .crash to. 272 /// \param CrashDiagDir The suggested directory for the user to look at 273 /// in case the search or copy fails. 274 /// 275 /// \returns If the .crash is found and successfully copied return true, 276 /// otherwise false and return the suggested directory in \p CrashDiagDir. 277 bool getCrashDiagnosticFile(StringRef ReproCrashFilename, 278 SmallString<128> &CrashDiagDir); 279 280 public: 281 Driver(StringRef ClangExecutable, StringRef TargetTriple, 282 DiagnosticsEngine &Diags, 283 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS = nullptr); 284 285 /// @name Accessors 286 /// @{ 287 288 /// Name to use when invoking gcc/g++. getCCCGenericGCCName()289 const std::string &getCCCGenericGCCName() const { return CCCGenericGCCName; } 290 getConfigFile()291 const std::string &getConfigFile() const { return ConfigFile; } 292 getOpts()293 const llvm::opt::OptTable &getOpts() const { return *Opts; } 294 getDiags()295 const DiagnosticsEngine &getDiags() const { return Diags; } 296 getVFS()297 llvm::vfs::FileSystem &getVFS() const { return *VFS; } 298 getCheckInputsExist()299 bool getCheckInputsExist() const { return CheckInputsExist; } 300 setCheckInputsExist(bool Value)301 void setCheckInputsExist(bool Value) { CheckInputsExist = Value; } 302 setTargetAndMode(const ParsedClangName & TM)303 void setTargetAndMode(const ParsedClangName &TM) { ClangNameParts = TM; } 304 getTitle()305 const std::string &getTitle() { return DriverTitle; } setTitle(std::string Value)306 void setTitle(std::string Value) { DriverTitle = std::move(Value); } 307 getTargetTriple()308 std::string getTargetTriple() const { return TargetTriple; } 309 310 /// Get the path to the main clang executable. getClangProgramPath()311 const char *getClangProgramPath() const { 312 return ClangExecutable.c_str(); 313 } 314 315 /// Get the path to where the clang executable was installed. getInstalledDir()316 const char *getInstalledDir() const { 317 if (!InstalledDir.empty()) 318 return InstalledDir.c_str(); 319 return Dir.c_str(); 320 } setInstalledDir(StringRef Value)321 void setInstalledDir(StringRef Value) { 322 InstalledDir = Value; 323 } 324 isSaveTempsEnabled()325 bool isSaveTempsEnabled() const { return SaveTemps != SaveTempsNone; } isSaveTempsObj()326 bool isSaveTempsObj() const { return SaveTemps == SaveTempsObj; } 327 embedBitcodeEnabled()328 bool embedBitcodeEnabled() const { return BitcodeEmbed != EmbedNone; } embedBitcodeInObject()329 bool embedBitcodeInObject() const { return (BitcodeEmbed == EmbedBitcode); } embedBitcodeMarkerOnly()330 bool embedBitcodeMarkerOnly() const { return (BitcodeEmbed == EmbedMarker); } 331 332 /// Compute the desired OpenMP runtime from the flags provided. 333 OpenMPRuntimeKind getOpenMPRuntime(const llvm::opt::ArgList &Args) const; 334 335 /// @} 336 /// @name Primary Functionality 337 /// @{ 338 339 /// CreateOffloadingDeviceToolChains - create all the toolchains required to 340 /// support offloading devices given the programming models specified in the 341 /// current compilation. Also, update the host tool chain kind accordingly. 342 void CreateOffloadingDeviceToolChains(Compilation &C, InputList &Inputs); 343 344 /// BuildCompilation - Construct a compilation object for a command 345 /// line argument vector. 346 /// 347 /// \return A compilation, or 0 if none was built for the given 348 /// argument vector. A null return value does not necessarily 349 /// indicate an error condition, the diagnostics should be queried 350 /// to determine if an error occurred. 351 Compilation *BuildCompilation(ArrayRef<const char *> Args); 352 353 /// @name Driver Steps 354 /// @{ 355 356 /// ParseDriverMode - Look for and handle the driver mode option in Args. 357 void ParseDriverMode(StringRef ProgramName, ArrayRef<const char *> Args); 358 359 /// ParseArgStrings - Parse the given list of strings into an 360 /// ArgList. 361 llvm::opt::InputArgList ParseArgStrings(ArrayRef<const char *> Args, 362 bool IsClCompatMode, 363 bool &ContainsError); 364 365 /// BuildInputs - Construct the list of inputs and their types from 366 /// the given arguments. 367 /// 368 /// \param TC - The default host tool chain. 369 /// \param Args - The input arguments. 370 /// \param Inputs - The list to store the resulting compilation 371 /// inputs onto. 372 void BuildInputs(const ToolChain &TC, llvm::opt::DerivedArgList &Args, 373 InputList &Inputs) const; 374 375 /// BuildActions - Construct the list of actions to perform for the 376 /// given arguments, which are only done for a single architecture. 377 /// 378 /// \param C - The compilation that is being built. 379 /// \param Args - The input arguments. 380 /// \param Actions - The list to store the resulting actions onto. 381 void BuildActions(Compilation &C, llvm::opt::DerivedArgList &Args, 382 const InputList &Inputs, ActionList &Actions) const; 383 384 /// BuildUniversalActions - Construct the list of actions to perform 385 /// for the given arguments, which may require a universal build. 386 /// 387 /// \param C - The compilation that is being built. 388 /// \param TC - The default host tool chain. 389 void BuildUniversalActions(Compilation &C, const ToolChain &TC, 390 const InputList &BAInputs) const; 391 392 /// BuildJobs - Bind actions to concrete tools and translate 393 /// arguments to form the list of jobs to run. 394 /// 395 /// \param C - The compilation that is being built. 396 void BuildJobs(Compilation &C) const; 397 398 /// ExecuteCompilation - Execute the compilation according to the command line 399 /// arguments and return an appropriate exit code. 400 /// 401 /// This routine handles additional processing that must be done in addition 402 /// to just running the subprocesses, for example reporting errors, setting 403 /// up response files, removing temporary files, etc. 404 int ExecuteCompilation(Compilation &C, 405 SmallVectorImpl< std::pair<int, const Command *> > &FailingCommands); 406 407 /// Contains the files in the compilation diagnostic report generated by 408 /// generateCompilationDiagnostics. 409 struct CompilationDiagnosticReport { 410 llvm::SmallVector<std::string, 4> TemporaryFiles; 411 }; 412 413 /// generateCompilationDiagnostics - Generate diagnostics information 414 /// including preprocessed source file(s). 415 /// 416 void generateCompilationDiagnostics( 417 Compilation &C, const Command &FailingCommand, 418 StringRef AdditionalInformation = "", 419 CompilationDiagnosticReport *GeneratedReport = nullptr); 420 421 /// @} 422 /// @name Helper Methods 423 /// @{ 424 425 /// PrintActions - Print the list of actions. 426 void PrintActions(const Compilation &C) const; 427 428 /// PrintHelp - Print the help text. 429 /// 430 /// \param ShowHidden - Show hidden options. 431 void PrintHelp(bool ShowHidden) const; 432 433 /// PrintVersion - Print the driver version. 434 void PrintVersion(const Compilation &C, raw_ostream &OS) const; 435 436 /// GetFilePath - Lookup \p Name in the list of file search paths. 437 /// 438 /// \param TC - The tool chain for additional information on 439 /// directories to search. 440 // 441 // FIXME: This should be in CompilationInfo. 442 std::string GetFilePath(StringRef Name, const ToolChain &TC) const; 443 444 /// GetProgramPath - Lookup \p Name in the list of program search paths. 445 /// 446 /// \param TC - The provided tool chain for additional information on 447 /// directories to search. 448 // 449 // FIXME: This should be in CompilationInfo. 450 std::string GetProgramPath(StringRef Name, const ToolChain &TC) const; 451 452 /// HandleAutocompletions - Handle --autocomplete by searching and printing 453 /// possible flags, descriptions, and its arguments. 454 void HandleAutocompletions(StringRef PassedFlags) const; 455 456 /// HandleImmediateArgs - Handle any arguments which should be 457 /// treated before building actions or binding tools. 458 /// 459 /// \return Whether any compilation should be built for this 460 /// invocation. 461 bool HandleImmediateArgs(const Compilation &C); 462 463 /// ConstructAction - Construct the appropriate action to do for 464 /// \p Phase on the \p Input, taking in to account arguments 465 /// like -fsyntax-only or --analyze. 466 Action *ConstructPhaseAction( 467 Compilation &C, const llvm::opt::ArgList &Args, phases::ID Phase, 468 Action *Input, 469 Action::OffloadKind TargetDeviceOffloadKind = Action::OFK_None) const; 470 471 /// BuildJobsForAction - Construct the jobs to perform for the action \p A and 472 /// return an InputInfo for the result of running \p A. Will only construct 473 /// jobs for a given (Action, ToolChain, BoundArch, DeviceKind) tuple once. 474 InputInfo 475 BuildJobsForAction(Compilation &C, const Action *A, const ToolChain *TC, 476 StringRef BoundArch, bool AtTopLevel, bool MultipleArchs, 477 const char *LinkingOutput, 478 std::map<std::pair<const Action *, std::string>, InputInfo> 479 &CachedResults, 480 Action::OffloadKind TargetDeviceOffloadKind) const; 481 482 /// Returns the default name for linked images (e.g., "a.out"). 483 const char *getDefaultImageName() const; 484 485 /// GetNamedOutputPath - Return the name to use for the output of 486 /// the action \p JA. The result is appended to the compilation's 487 /// list of temporary or result files, as appropriate. 488 /// 489 /// \param C - The compilation. 490 /// \param JA - The action of interest. 491 /// \param BaseInput - The original input file that this action was 492 /// triggered by. 493 /// \param BoundArch - The bound architecture. 494 /// \param AtTopLevel - Whether this is a "top-level" action. 495 /// \param MultipleArchs - Whether multiple -arch options were supplied. 496 /// \param NormalizedTriple - The normalized triple of the relevant target. 497 const char *GetNamedOutputPath(Compilation &C, const JobAction &JA, 498 const char *BaseInput, StringRef BoundArch, 499 bool AtTopLevel, bool MultipleArchs, 500 StringRef NormalizedTriple) const; 501 502 /// GetTemporaryPath - Return the pathname of a temporary file to use 503 /// as part of compilation; the file will have the given prefix and suffix. 504 /// 505 /// GCC goes to extra lengths here to be a bit more robust. 506 std::string GetTemporaryPath(StringRef Prefix, StringRef Suffix) const; 507 508 /// GetTemporaryDirectory - Return the pathname of a temporary directory to 509 /// use as part of compilation; the directory will have the given prefix. 510 std::string GetTemporaryDirectory(StringRef Prefix) const; 511 512 /// Return the pathname of the pch file in clang-cl mode. 513 std::string GetClPchPath(Compilation &C, StringRef BaseName) const; 514 515 /// ShouldUseClangCompiler - Should the clang compiler be used to 516 /// handle this action. 517 bool ShouldUseClangCompiler(const JobAction &JA) const; 518 519 /// Returns true if we are performing any kind of LTO. isUsingLTO()520 bool isUsingLTO() const { return LTOMode != LTOK_None; } 521 522 /// Get the specific kind of LTO being performed. getLTOMode()523 LTOKind getLTOMode() const { return LTOMode; } 524 525 private: 526 527 /// Tries to load options from configuration file. 528 /// 529 /// \returns true if error occurred. 530 bool loadConfigFile(); 531 532 /// Read options from the specified file. 533 /// 534 /// \param [in] FileName File to read. 535 /// \returns true, if error occurred while reading. 536 bool readConfigFile(StringRef FileName); 537 538 /// Set the driver mode (cl, gcc, etc) from an option string of the form 539 /// --driver-mode=<mode>. 540 void setDriverModeFromOption(StringRef Opt); 541 542 /// Parse the \p Args list for LTO options and record the type of LTO 543 /// compilation based on which -f(no-)?lto(=.*)? option occurs last. 544 void setLTOMode(const llvm::opt::ArgList &Args); 545 546 /// Retrieves a ToolChain for a particular \p Target triple. 547 /// 548 /// Will cache ToolChains for the life of the driver object, and create them 549 /// on-demand. 550 const ToolChain &getToolChain(const llvm::opt::ArgList &Args, 551 const llvm::Triple &Target) const; 552 553 /// @} 554 555 /// Get bitmasks for which option flags to include and exclude based on 556 /// the driver mode. 557 std::pair<unsigned, unsigned> getIncludeExcludeOptionFlagMasks(bool IsClCompatMode) const; 558 559 /// Helper used in BuildJobsForAction. Doesn't use the cache when building 560 /// jobs specifically for the given action, but will use the cache when 561 /// building jobs for the Action's inputs. 562 InputInfo BuildJobsForActionNoCache( 563 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch, 564 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput, 565 std::map<std::pair<const Action *, std::string>, InputInfo> 566 &CachedResults, 567 Action::OffloadKind TargetDeviceOffloadKind) const; 568 569 public: 570 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and 571 /// return the grouped values as integers. Numbers which are not 572 /// provided are set to 0. 573 /// 574 /// \return True if the entire string was parsed (9.2), or all 575 /// groups were parsed (10.3.5extrastuff). HadExtra is true if all 576 /// groups were parsed but extra characters remain at the end. 577 static bool GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor, 578 unsigned &Micro, bool &HadExtra); 579 580 /// Parse digits from a string \p Str and fulfill \p Digits with 581 /// the parsed numbers. This method assumes that the max number of 582 /// digits to look for is equal to Digits.size(). 583 /// 584 /// \return True if the entire string was parsed and there are 585 /// no extra characters remaining at the end. 586 static bool GetReleaseVersion(StringRef Str, 587 MutableArrayRef<unsigned> Digits); 588 /// Compute the default -fmodule-cache-path. 589 static void getDefaultModuleCachePath(SmallVectorImpl<char> &Result); 590 }; 591 592 /// \return True if the last defined optimization level is -Ofast. 593 /// And False otherwise. 594 bool isOptimizationLevelFast(const llvm::opt::ArgList &Args); 595 596 } // end namespace driver 597 } // end namespace clang 598 599 #endif 600