1 //===- CompilerInvocation.cpp ---------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "clang/Frontend/CompilerInvocation.h" 10 #include "TestModuleFileExtension.h" 11 #include "clang/Basic/Builtins.h" 12 #include "clang/Basic/CharInfo.h" 13 #include "clang/Basic/CodeGenOptions.h" 14 #include "clang/Basic/CommentOptions.h" 15 #include "clang/Basic/DebugInfoOptions.h" 16 #include "clang/Basic/Diagnostic.h" 17 #include "clang/Basic/DiagnosticOptions.h" 18 #include "clang/Basic/FileSystemOptions.h" 19 #include "clang/Basic/LLVM.h" 20 #include "clang/Basic/LangOptions.h" 21 #include "clang/Basic/LangStandard.h" 22 #include "clang/Basic/ObjCRuntime.h" 23 #include "clang/Basic/Sanitizers.h" 24 #include "clang/Basic/SourceLocation.h" 25 #include "clang/Basic/TargetOptions.h" 26 #include "clang/Basic/Version.h" 27 #include "clang/Basic/Visibility.h" 28 #include "clang/Basic/XRayInstr.h" 29 #include "clang/Config/config.h" 30 #include "clang/Driver/Driver.h" 31 #include "clang/Driver/DriverDiagnostic.h" 32 #include "clang/Driver/Options.h" 33 #include "clang/Frontend/CommandLineSourceLoc.h" 34 #include "clang/Frontend/DependencyOutputOptions.h" 35 #include "clang/Frontend/FrontendDiagnostic.h" 36 #include "clang/Frontend/FrontendOptions.h" 37 #include "clang/Frontend/FrontendPluginRegistry.h" 38 #include "clang/Frontend/MigratorOptions.h" 39 #include "clang/Frontend/PreprocessorOutputOptions.h" 40 #include "clang/Frontend/Utils.h" 41 #include "clang/Lex/HeaderSearchOptions.h" 42 #include "clang/Lex/PreprocessorOptions.h" 43 #include "clang/Sema/CodeCompleteOptions.h" 44 #include "clang/Serialization/ModuleFileExtension.h" 45 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h" 46 #include "llvm/ADT/APInt.h" 47 #include "llvm/ADT/ArrayRef.h" 48 #include "llvm/ADT/CachedHashString.h" 49 #include "llvm/ADT/Hashing.h" 50 #include "llvm/ADT/None.h" 51 #include "llvm/ADT/Optional.h" 52 #include "llvm/ADT/SmallString.h" 53 #include "llvm/ADT/SmallVector.h" 54 #include "llvm/ADT/StringRef.h" 55 #include "llvm/ADT/StringSwitch.h" 56 #include "llvm/ADT/Triple.h" 57 #include "llvm/ADT/Twine.h" 58 #include "llvm/IR/DebugInfoMetadata.h" 59 #include "llvm/Linker/Linker.h" 60 #include "llvm/MC/MCTargetOptions.h" 61 #include "llvm/Option/Arg.h" 62 #include "llvm/Option/ArgList.h" 63 #include "llvm/Option/OptSpecifier.h" 64 #include "llvm/Option/OptTable.h" 65 #include "llvm/Option/Option.h" 66 #include "llvm/ProfileData/InstrProfReader.h" 67 #include "llvm/Support/CodeGen.h" 68 #include "llvm/Support/Compiler.h" 69 #include "llvm/Support/Error.h" 70 #include "llvm/Support/ErrorHandling.h" 71 #include "llvm/Support/ErrorOr.h" 72 #include "llvm/Support/FileSystem.h" 73 #include "llvm/Support/Host.h" 74 #include "llvm/Support/MathExtras.h" 75 #include "llvm/Support/MemoryBuffer.h" 76 #include "llvm/Support/Path.h" 77 #include "llvm/Support/Process.h" 78 #include "llvm/Support/Regex.h" 79 #include "llvm/Support/VersionTuple.h" 80 #include "llvm/Support/VirtualFileSystem.h" 81 #include "llvm/Support/raw_ostream.h" 82 #include "llvm/Target/TargetOptions.h" 83 #include <algorithm> 84 #include <atomic> 85 #include <cassert> 86 #include <cstddef> 87 #include <cstring> 88 #include <memory> 89 #include <string> 90 #include <tuple> 91 #include <utility> 92 #include <vector> 93 94 using namespace clang; 95 using namespace driver; 96 using namespace options; 97 using namespace llvm::opt; 98 99 //===----------------------------------------------------------------------===// 100 // Initialization. 101 //===----------------------------------------------------------------------===// 102 103 CompilerInvocationBase::CompilerInvocationBase() 104 : LangOpts(new LangOptions()), TargetOpts(new TargetOptions()), 105 DiagnosticOpts(new DiagnosticOptions()), 106 HeaderSearchOpts(new HeaderSearchOptions()), 107 PreprocessorOpts(new PreprocessorOptions()) {} 108 109 CompilerInvocationBase::CompilerInvocationBase(const CompilerInvocationBase &X) 110 : LangOpts(new LangOptions(*X.getLangOpts())), 111 TargetOpts(new TargetOptions(X.getTargetOpts())), 112 DiagnosticOpts(new DiagnosticOptions(X.getDiagnosticOpts())), 113 HeaderSearchOpts(new HeaderSearchOptions(X.getHeaderSearchOpts())), 114 PreprocessorOpts(new PreprocessorOptions(X.getPreprocessorOpts())) {} 115 116 CompilerInvocationBase::~CompilerInvocationBase() = default; 117 118 //===----------------------------------------------------------------------===// 119 // Deserialization (from args) 120 //===----------------------------------------------------------------------===// 121 122 static unsigned getOptimizationLevel(ArgList &Args, InputKind IK, 123 DiagnosticsEngine &Diags) { 124 unsigned DefaultOpt = llvm::CodeGenOpt::None; 125 if (IK.getLanguage() == Language::OpenCL && !Args.hasArg(OPT_cl_opt_disable)) 126 DefaultOpt = llvm::CodeGenOpt::Default; 127 128 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) { 129 if (A->getOption().matches(options::OPT_O0)) 130 return llvm::CodeGenOpt::None; 131 132 if (A->getOption().matches(options::OPT_Ofast)) 133 return llvm::CodeGenOpt::Aggressive; 134 135 assert(A->getOption().matches(options::OPT_O)); 136 137 StringRef S(A->getValue()); 138 if (S == "s" || S == "z" || S.empty()) 139 return llvm::CodeGenOpt::Default; 140 141 if (S == "g") 142 return llvm::CodeGenOpt::Less; 143 144 return getLastArgIntValue(Args, OPT_O, DefaultOpt, Diags); 145 } 146 147 return DefaultOpt; 148 } 149 150 static unsigned getOptimizationLevelSize(ArgList &Args) { 151 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) { 152 if (A->getOption().matches(options::OPT_O)) { 153 switch (A->getValue()[0]) { 154 default: 155 return 0; 156 case 's': 157 return 1; 158 case 'z': 159 return 2; 160 } 161 } 162 } 163 return 0; 164 } 165 166 static void addDiagnosticArgs(ArgList &Args, OptSpecifier Group, 167 OptSpecifier GroupWithValue, 168 std::vector<std::string> &Diagnostics) { 169 for (auto *A : Args.filtered(Group)) { 170 if (A->getOption().getKind() == Option::FlagClass) { 171 // The argument is a pure flag (such as OPT_Wall or OPT_Wdeprecated). Add 172 // its name (minus the "W" or "R" at the beginning) to the warning list. 173 Diagnostics.push_back(A->getOption().getName().drop_front(1)); 174 } else if (A->getOption().matches(GroupWithValue)) { 175 // This is -Wfoo= or -Rfoo=, where foo is the name of the diagnostic group. 176 Diagnostics.push_back(A->getOption().getName().drop_front(1).rtrim("=-")); 177 } else { 178 // Otherwise, add its value (for OPT_W_Joined and similar). 179 for (const auto *Arg : A->getValues()) 180 Diagnostics.emplace_back(Arg); 181 } 182 } 183 } 184 185 // Parse the Static Analyzer configuration. If \p Diags is set to nullptr, 186 // it won't verify the input. 187 static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts, 188 DiagnosticsEngine *Diags); 189 190 static void getAllNoBuiltinFuncValues(ArgList &Args, 191 std::vector<std::string> &Funcs) { 192 SmallVector<const char *, 8> Values; 193 for (const auto &Arg : Args) { 194 const Option &O = Arg->getOption(); 195 if (O.matches(options::OPT_fno_builtin_)) { 196 const char *FuncName = Arg->getValue(); 197 if (Builtin::Context::isBuiltinFunc(FuncName)) 198 Values.push_back(FuncName); 199 } 200 } 201 Funcs.insert(Funcs.end(), Values.begin(), Values.end()); 202 } 203 204 static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args, 205 DiagnosticsEngine &Diags) { 206 bool Success = true; 207 if (Arg *A = Args.getLastArg(OPT_analyzer_store)) { 208 StringRef Name = A->getValue(); 209 AnalysisStores Value = llvm::StringSwitch<AnalysisStores>(Name) 210 #define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN) \ 211 .Case(CMDFLAG, NAME##Model) 212 #include "clang/StaticAnalyzer/Core/Analyses.def" 213 .Default(NumStores); 214 if (Value == NumStores) { 215 Diags.Report(diag::err_drv_invalid_value) 216 << A->getAsString(Args) << Name; 217 Success = false; 218 } else { 219 Opts.AnalysisStoreOpt = Value; 220 } 221 } 222 223 if (Arg *A = Args.getLastArg(OPT_analyzer_constraints)) { 224 StringRef Name = A->getValue(); 225 AnalysisConstraints Value = llvm::StringSwitch<AnalysisConstraints>(Name) 226 #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \ 227 .Case(CMDFLAG, NAME##Model) 228 #include "clang/StaticAnalyzer/Core/Analyses.def" 229 .Default(NumConstraints); 230 if (Value == NumConstraints) { 231 Diags.Report(diag::err_drv_invalid_value) 232 << A->getAsString(Args) << Name; 233 Success = false; 234 } else { 235 Opts.AnalysisConstraintsOpt = Value; 236 } 237 } 238 239 if (Arg *A = Args.getLastArg(OPT_analyzer_output)) { 240 StringRef Name = A->getValue(); 241 AnalysisDiagClients Value = llvm::StringSwitch<AnalysisDiagClients>(Name) 242 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \ 243 .Case(CMDFLAG, PD_##NAME) 244 #include "clang/StaticAnalyzer/Core/Analyses.def" 245 .Default(NUM_ANALYSIS_DIAG_CLIENTS); 246 if (Value == NUM_ANALYSIS_DIAG_CLIENTS) { 247 Diags.Report(diag::err_drv_invalid_value) 248 << A->getAsString(Args) << Name; 249 Success = false; 250 } else { 251 Opts.AnalysisDiagOpt = Value; 252 } 253 } 254 255 if (Arg *A = Args.getLastArg(OPT_analyzer_purge)) { 256 StringRef Name = A->getValue(); 257 AnalysisPurgeMode Value = llvm::StringSwitch<AnalysisPurgeMode>(Name) 258 #define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \ 259 .Case(CMDFLAG, NAME) 260 #include "clang/StaticAnalyzer/Core/Analyses.def" 261 .Default(NumPurgeModes); 262 if (Value == NumPurgeModes) { 263 Diags.Report(diag::err_drv_invalid_value) 264 << A->getAsString(Args) << Name; 265 Success = false; 266 } else { 267 Opts.AnalysisPurgeOpt = Value; 268 } 269 } 270 271 if (Arg *A = Args.getLastArg(OPT_analyzer_inlining_mode)) { 272 StringRef Name = A->getValue(); 273 AnalysisInliningMode Value = llvm::StringSwitch<AnalysisInliningMode>(Name) 274 #define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \ 275 .Case(CMDFLAG, NAME) 276 #include "clang/StaticAnalyzer/Core/Analyses.def" 277 .Default(NumInliningModes); 278 if (Value == NumInliningModes) { 279 Diags.Report(diag::err_drv_invalid_value) 280 << A->getAsString(Args) << Name; 281 Success = false; 282 } else { 283 Opts.InliningMode = Value; 284 } 285 } 286 287 Opts.ShowCheckerHelp = Args.hasArg(OPT_analyzer_checker_help); 288 Opts.ShowCheckerHelpAlpha = Args.hasArg(OPT_analyzer_checker_help_alpha); 289 Opts.ShowCheckerHelpDeveloper = 290 Args.hasArg(OPT_analyzer_checker_help_developer); 291 292 Opts.ShowCheckerOptionList = Args.hasArg(OPT_analyzer_checker_option_help); 293 Opts.ShowCheckerOptionAlphaList = 294 Args.hasArg(OPT_analyzer_checker_option_help_alpha); 295 Opts.ShowCheckerOptionDeveloperList = 296 Args.hasArg(OPT_analyzer_checker_option_help_developer); 297 298 Opts.ShowConfigOptionsList = Args.hasArg(OPT_analyzer_config_help); 299 Opts.ShowEnabledCheckerList = Args.hasArg(OPT_analyzer_list_enabled_checkers); 300 Opts.ShouldEmitErrorsOnInvalidConfigValue = 301 /* negated */!llvm::StringSwitch<bool>( 302 Args.getLastArgValue(OPT_analyzer_config_compatibility_mode)) 303 .Case("true", true) 304 .Case("false", false) 305 .Default(false); 306 Opts.DisableAllCheckers = Args.hasArg(OPT_analyzer_disable_all_checks); 307 308 Opts.visualizeExplodedGraphWithGraphViz = 309 Args.hasArg(OPT_analyzer_viz_egraph_graphviz); 310 Opts.DumpExplodedGraphTo = Args.getLastArgValue(OPT_analyzer_dump_egraph); 311 Opts.NoRetryExhausted = Args.hasArg(OPT_analyzer_disable_retry_exhausted); 312 Opts.AnalyzerWerror = Args.hasArg(OPT_analyzer_werror); 313 Opts.AnalyzeAll = Args.hasArg(OPT_analyzer_opt_analyze_headers); 314 Opts.AnalyzerDisplayProgress = Args.hasArg(OPT_analyzer_display_progress); 315 Opts.AnalyzeNestedBlocks = 316 Args.hasArg(OPT_analyzer_opt_analyze_nested_blocks); 317 Opts.AnalyzeSpecificFunction = Args.getLastArgValue(OPT_analyze_function); 318 Opts.UnoptimizedCFG = Args.hasArg(OPT_analysis_UnoptimizedCFG); 319 Opts.TrimGraph = Args.hasArg(OPT_trim_egraph); 320 Opts.maxBlockVisitOnPath = 321 getLastArgIntValue(Args, OPT_analyzer_max_loop, 4, Diags); 322 Opts.PrintStats = Args.hasArg(OPT_analyzer_stats); 323 Opts.InlineMaxStackDepth = 324 getLastArgIntValue(Args, OPT_analyzer_inline_max_stack_depth, 325 Opts.InlineMaxStackDepth, Diags); 326 327 Opts.CheckersAndPackages.clear(); 328 for (const Arg *A : 329 Args.filtered(OPT_analyzer_checker, OPT_analyzer_disable_checker)) { 330 A->claim(); 331 bool IsEnabled = A->getOption().getID() == OPT_analyzer_checker; 332 // We can have a list of comma separated checker names, e.g: 333 // '-analyzer-checker=cocoa,unix' 334 StringRef CheckerAndPackageList = A->getValue(); 335 SmallVector<StringRef, 16> CheckersAndPackages; 336 CheckerAndPackageList.split(CheckersAndPackages, ","); 337 for (const StringRef &CheckerOrPackage : CheckersAndPackages) 338 Opts.CheckersAndPackages.emplace_back(CheckerOrPackage, IsEnabled); 339 } 340 341 // Go through the analyzer configuration options. 342 for (const auto *A : Args.filtered(OPT_analyzer_config)) { 343 344 // We can have a list of comma separated config names, e.g: 345 // '-analyzer-config key1=val1,key2=val2' 346 StringRef configList = A->getValue(); 347 SmallVector<StringRef, 4> configVals; 348 configList.split(configVals, ","); 349 for (const auto &configVal : configVals) { 350 StringRef key, val; 351 std::tie(key, val) = configVal.split("="); 352 if (val.empty()) { 353 Diags.Report(SourceLocation(), 354 diag::err_analyzer_config_no_value) << configVal; 355 Success = false; 356 break; 357 } 358 if (val.find('=') != StringRef::npos) { 359 Diags.Report(SourceLocation(), 360 diag::err_analyzer_config_multiple_values) 361 << configVal; 362 Success = false; 363 break; 364 } 365 366 // TODO: Check checker options too, possibly in CheckerRegistry. 367 // Leave unknown non-checker configs unclaimed. 368 if (!key.contains(":") && Opts.isUnknownAnalyzerConfig(key)) { 369 if (Opts.ShouldEmitErrorsOnInvalidConfigValue) 370 Diags.Report(diag::err_analyzer_config_unknown) << key; 371 continue; 372 } 373 374 A->claim(); 375 Opts.Config[key] = val; 376 } 377 } 378 379 if (Opts.ShouldEmitErrorsOnInvalidConfigValue) 380 parseAnalyzerConfigs(Opts, &Diags); 381 else 382 parseAnalyzerConfigs(Opts, nullptr); 383 384 llvm::raw_string_ostream os(Opts.FullCompilerInvocation); 385 for (unsigned i = 0; i < Args.getNumInputArgStrings(); ++i) { 386 if (i != 0) 387 os << " "; 388 os << Args.getArgString(i); 389 } 390 os.flush(); 391 392 return Success; 393 } 394 395 static StringRef getStringOption(AnalyzerOptions::ConfigTable &Config, 396 StringRef OptionName, StringRef DefaultVal) { 397 return Config.insert({OptionName, DefaultVal}).first->second; 398 } 399 400 static void initOption(AnalyzerOptions::ConfigTable &Config, 401 DiagnosticsEngine *Diags, 402 StringRef &OptionField, StringRef Name, 403 StringRef DefaultVal) { 404 // String options may be known to invalid (e.g. if the expected string is a 405 // file name, but the file does not exist), those will have to be checked in 406 // parseConfigs. 407 OptionField = getStringOption(Config, Name, DefaultVal); 408 } 409 410 static void initOption(AnalyzerOptions::ConfigTable &Config, 411 DiagnosticsEngine *Diags, 412 bool &OptionField, StringRef Name, bool DefaultVal) { 413 auto PossiblyInvalidVal = llvm::StringSwitch<Optional<bool>>( 414 getStringOption(Config, Name, (DefaultVal ? "true" : "false"))) 415 .Case("true", true) 416 .Case("false", false) 417 .Default(None); 418 419 if (!PossiblyInvalidVal) { 420 if (Diags) 421 Diags->Report(diag::err_analyzer_config_invalid_input) 422 << Name << "a boolean"; 423 else 424 OptionField = DefaultVal; 425 } else 426 OptionField = PossiblyInvalidVal.getValue(); 427 } 428 429 static void initOption(AnalyzerOptions::ConfigTable &Config, 430 DiagnosticsEngine *Diags, 431 unsigned &OptionField, StringRef Name, 432 unsigned DefaultVal) { 433 434 OptionField = DefaultVal; 435 bool HasFailed = getStringOption(Config, Name, std::to_string(DefaultVal)) 436 .getAsInteger(0, OptionField); 437 if (Diags && HasFailed) 438 Diags->Report(diag::err_analyzer_config_invalid_input) 439 << Name << "an unsigned"; 440 } 441 442 static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts, 443 DiagnosticsEngine *Diags) { 444 // TODO: There's no need to store the entire configtable, it'd be plenty 445 // enough tostore checker options. 446 447 #define ANALYZER_OPTION(TYPE, NAME, CMDFLAG, DESC, DEFAULT_VAL) \ 448 initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, DEFAULT_VAL); 449 450 #define ANALYZER_OPTION_DEPENDS_ON_USER_MODE(TYPE, NAME, CMDFLAG, DESC, \ 451 SHALLOW_VAL, DEEP_VAL) \ 452 switch (AnOpts.getUserMode()) { \ 453 case UMK_Shallow: \ 454 initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, SHALLOW_VAL); \ 455 break; \ 456 case UMK_Deep: \ 457 initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, DEEP_VAL); \ 458 break; \ 459 } \ 460 461 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.def" 462 #undef ANALYZER_OPTION 463 #undef ANALYZER_OPTION_DEPENDS_ON_USER_MODE 464 465 // At this point, AnalyzerOptions is configured. Let's validate some options. 466 467 // FIXME: Here we try to validate the silenced checkers or packages are valid. 468 // The current approach only validates the registered checkers which does not 469 // contain the runtime enabled checkers and optimally we would validate both. 470 if (!AnOpts.RawSilencedCheckersAndPackages.empty()) { 471 std::vector<StringRef> Checkers = 472 AnOpts.getRegisteredCheckers(/*IncludeExperimental=*/true); 473 std::vector<StringRef> Packages = 474 AnOpts.getRegisteredPackages(/*IncludeExperimental=*/true); 475 476 SmallVector<StringRef, 16> CheckersAndPackages; 477 AnOpts.RawSilencedCheckersAndPackages.split(CheckersAndPackages, ";"); 478 479 for (const StringRef &CheckerOrPackage : CheckersAndPackages) { 480 if (Diags) { 481 bool IsChecker = CheckerOrPackage.contains('.'); 482 bool IsValidName = 483 IsChecker 484 ? llvm::find(Checkers, CheckerOrPackage) != Checkers.end() 485 : llvm::find(Packages, CheckerOrPackage) != Packages.end(); 486 487 if (!IsValidName) 488 Diags->Report(diag::err_unknown_analyzer_checker_or_package) 489 << CheckerOrPackage; 490 } 491 492 AnOpts.SilencedCheckersAndPackages.emplace_back(CheckerOrPackage); 493 } 494 } 495 496 if (!Diags) 497 return; 498 499 if (AnOpts.ShouldTrackConditionsDebug && !AnOpts.ShouldTrackConditions) 500 Diags->Report(diag::err_analyzer_config_invalid_input) 501 << "track-conditions-debug" << "'track-conditions' to also be enabled"; 502 503 if (!AnOpts.CTUDir.empty() && !llvm::sys::fs::is_directory(AnOpts.CTUDir)) 504 Diags->Report(diag::err_analyzer_config_invalid_input) << "ctu-dir" 505 << "a filename"; 506 507 if (!AnOpts.ModelPath.empty() && 508 !llvm::sys::fs::is_directory(AnOpts.ModelPath)) 509 Diags->Report(diag::err_analyzer_config_invalid_input) << "model-path" 510 << "a filename"; 511 } 512 513 static bool ParseMigratorArgs(MigratorOptions &Opts, ArgList &Args) { 514 Opts.NoNSAllocReallocError = Args.hasArg(OPT_migrator_no_nsalloc_error); 515 Opts.NoFinalizeRemoval = Args.hasArg(OPT_migrator_no_finalize_removal); 516 return true; 517 } 518 519 static void ParseCommentArgs(CommentOptions &Opts, ArgList &Args) { 520 Opts.BlockCommandNames = Args.getAllArgValues(OPT_fcomment_block_commands); 521 Opts.ParseAllComments = Args.hasArg(OPT_fparse_all_comments); 522 } 523 524 static StringRef getCodeModel(ArgList &Args, DiagnosticsEngine &Diags) { 525 if (Arg *A = Args.getLastArg(OPT_mcode_model)) { 526 StringRef Value = A->getValue(); 527 if (Value == "small" || Value == "kernel" || Value == "medium" || 528 Value == "large" || Value == "tiny") 529 return Value; 530 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Value; 531 } 532 return "default"; 533 } 534 535 static llvm::Reloc::Model getRelocModel(ArgList &Args, 536 DiagnosticsEngine &Diags) { 537 if (Arg *A = Args.getLastArg(OPT_mrelocation_model)) { 538 StringRef Value = A->getValue(); 539 auto RM = llvm::StringSwitch<llvm::Optional<llvm::Reloc::Model>>(Value) 540 .Case("static", llvm::Reloc::Static) 541 .Case("pic", llvm::Reloc::PIC_) 542 .Case("ropi", llvm::Reloc::ROPI) 543 .Case("rwpi", llvm::Reloc::RWPI) 544 .Case("ropi-rwpi", llvm::Reloc::ROPI_RWPI) 545 .Case("dynamic-no-pic", llvm::Reloc::DynamicNoPIC) 546 .Default(None); 547 if (RM.hasValue()) 548 return *RM; 549 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Value; 550 } 551 return llvm::Reloc::PIC_; 552 } 553 554 /// Create a new Regex instance out of the string value in \p RpassArg. 555 /// It returns a pointer to the newly generated Regex instance. 556 static std::shared_ptr<llvm::Regex> 557 GenerateOptimizationRemarkRegex(DiagnosticsEngine &Diags, ArgList &Args, 558 Arg *RpassArg) { 559 StringRef Val = RpassArg->getValue(); 560 std::string RegexError; 561 std::shared_ptr<llvm::Regex> Pattern = std::make_shared<llvm::Regex>(Val); 562 if (!Pattern->isValid(RegexError)) { 563 Diags.Report(diag::err_drv_optimization_remark_pattern) 564 << RegexError << RpassArg->getAsString(Args); 565 Pattern.reset(); 566 } 567 return Pattern; 568 } 569 570 static bool parseDiagnosticLevelMask(StringRef FlagName, 571 const std::vector<std::string> &Levels, 572 DiagnosticsEngine *Diags, 573 DiagnosticLevelMask &M) { 574 bool Success = true; 575 for (const auto &Level : Levels) { 576 DiagnosticLevelMask const PM = 577 llvm::StringSwitch<DiagnosticLevelMask>(Level) 578 .Case("note", DiagnosticLevelMask::Note) 579 .Case("remark", DiagnosticLevelMask::Remark) 580 .Case("warning", DiagnosticLevelMask::Warning) 581 .Case("error", DiagnosticLevelMask::Error) 582 .Default(DiagnosticLevelMask::None); 583 if (PM == DiagnosticLevelMask::None) { 584 Success = false; 585 if (Diags) 586 Diags->Report(diag::err_drv_invalid_value) << FlagName << Level; 587 } 588 M = M | PM; 589 } 590 return Success; 591 } 592 593 static void parseSanitizerKinds(StringRef FlagName, 594 const std::vector<std::string> &Sanitizers, 595 DiagnosticsEngine &Diags, SanitizerSet &S) { 596 for (const auto &Sanitizer : Sanitizers) { 597 SanitizerMask K = parseSanitizerValue(Sanitizer, /*AllowGroups=*/false); 598 if (K == SanitizerMask()) 599 Diags.Report(diag::err_drv_invalid_value) << FlagName << Sanitizer; 600 else 601 S.set(K, true); 602 } 603 } 604 605 static void parseXRayInstrumentationBundle(StringRef FlagName, StringRef Bundle, 606 ArgList &Args, DiagnosticsEngine &D, 607 XRayInstrSet &S) { 608 llvm::SmallVector<StringRef, 2> BundleParts; 609 llvm::SplitString(Bundle, BundleParts, ","); 610 for (const auto &B : BundleParts) { 611 auto Mask = parseXRayInstrValue(B); 612 if (Mask == XRayInstrKind::None) 613 if (B != "none") 614 D.Report(diag::err_drv_invalid_value) << FlagName << Bundle; 615 else 616 S.Mask = Mask; 617 else if (Mask == XRayInstrKind::All) 618 S.Mask = Mask; 619 else 620 S.set(Mask, true); 621 } 622 } 623 624 // Set the profile kind for fprofile-instrument. 625 static void setPGOInstrumentor(CodeGenOptions &Opts, ArgList &Args, 626 DiagnosticsEngine &Diags) { 627 Arg *A = Args.getLastArg(OPT_fprofile_instrument_EQ); 628 if (A == nullptr) 629 return; 630 StringRef S = A->getValue(); 631 unsigned I = llvm::StringSwitch<unsigned>(S) 632 .Case("none", CodeGenOptions::ProfileNone) 633 .Case("clang", CodeGenOptions::ProfileClangInstr) 634 .Case("llvm", CodeGenOptions::ProfileIRInstr) 635 .Case("csllvm", CodeGenOptions::ProfileCSIRInstr) 636 .Default(~0U); 637 if (I == ~0U) { 638 Diags.Report(diag::err_drv_invalid_pgo_instrumentor) << A->getAsString(Args) 639 << S; 640 return; 641 } 642 auto Instrumentor = static_cast<CodeGenOptions::ProfileInstrKind>(I); 643 Opts.setProfileInstr(Instrumentor); 644 } 645 646 // Set the profile kind using fprofile-instrument-use-path. 647 static void setPGOUseInstrumentor(CodeGenOptions &Opts, 648 const Twine &ProfileName) { 649 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(ProfileName); 650 // In error, return silently and let Clang PGOUse report the error message. 651 if (auto E = ReaderOrErr.takeError()) { 652 llvm::consumeError(std::move(E)); 653 Opts.setProfileUse(CodeGenOptions::ProfileClangInstr); 654 return; 655 } 656 std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader = 657 std::move(ReaderOrErr.get()); 658 if (PGOReader->isIRLevelProfile()) { 659 if (PGOReader->hasCSIRLevelProfile()) 660 Opts.setProfileUse(CodeGenOptions::ProfileCSIRInstr); 661 else 662 Opts.setProfileUse(CodeGenOptions::ProfileIRInstr); 663 } else 664 Opts.setProfileUse(CodeGenOptions::ProfileClangInstr); 665 } 666 667 static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK, 668 DiagnosticsEngine &Diags, 669 const TargetOptions &TargetOpts, 670 const FrontendOptions &FrontendOpts) { 671 bool Success = true; 672 llvm::Triple Triple = llvm::Triple(TargetOpts.Triple); 673 674 unsigned OptimizationLevel = getOptimizationLevel(Args, IK, Diags); 675 // TODO: This could be done in Driver 676 unsigned MaxOptLevel = 3; 677 if (OptimizationLevel > MaxOptLevel) { 678 // If the optimization level is not supported, fall back on the default 679 // optimization 680 Diags.Report(diag::warn_drv_optimization_value) 681 << Args.getLastArg(OPT_O)->getAsString(Args) << "-O" << MaxOptLevel; 682 OptimizationLevel = MaxOptLevel; 683 } 684 Opts.OptimizationLevel = OptimizationLevel; 685 686 // At O0 we want to fully disable inlining outside of cases marked with 687 // 'alwaysinline' that are required for correctness. 688 Opts.setInlining((Opts.OptimizationLevel == 0) 689 ? CodeGenOptions::OnlyAlwaysInlining 690 : CodeGenOptions::NormalInlining); 691 // Explicit inlining flags can disable some or all inlining even at 692 // optimization levels above zero. 693 if (Arg *InlineArg = Args.getLastArg( 694 options::OPT_finline_functions, options::OPT_finline_hint_functions, 695 options::OPT_fno_inline_functions, options::OPT_fno_inline)) { 696 if (Opts.OptimizationLevel > 0) { 697 const Option &InlineOpt = InlineArg->getOption(); 698 if (InlineOpt.matches(options::OPT_finline_functions)) 699 Opts.setInlining(CodeGenOptions::NormalInlining); 700 else if (InlineOpt.matches(options::OPT_finline_hint_functions)) 701 Opts.setInlining(CodeGenOptions::OnlyHintInlining); 702 else 703 Opts.setInlining(CodeGenOptions::OnlyAlwaysInlining); 704 } 705 } 706 707 Opts.ExperimentalNewPassManager = Args.hasFlag( 708 OPT_fexperimental_new_pass_manager, OPT_fno_experimental_new_pass_manager, 709 /* Default */ ENABLE_EXPERIMENTAL_NEW_PASS_MANAGER); 710 711 Opts.DebugPassManager = 712 Args.hasFlag(OPT_fdebug_pass_manager, OPT_fno_debug_pass_manager, 713 /* Default */ false); 714 715 if (Arg *A = Args.getLastArg(OPT_fveclib)) { 716 StringRef Name = A->getValue(); 717 if (Name == "Accelerate") 718 Opts.setVecLib(CodeGenOptions::Accelerate); 719 else if (Name == "MASSV") 720 Opts.setVecLib(CodeGenOptions::MASSV); 721 else if (Name == "SVML") 722 Opts.setVecLib(CodeGenOptions::SVML); 723 else if (Name == "none") 724 Opts.setVecLib(CodeGenOptions::NoLibrary); 725 else 726 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name; 727 } 728 729 if (Arg *A = Args.getLastArg(OPT_debug_info_kind_EQ)) { 730 unsigned Val = 731 llvm::StringSwitch<unsigned>(A->getValue()) 732 .Case("line-tables-only", codegenoptions::DebugLineTablesOnly) 733 .Case("line-directives-only", codegenoptions::DebugDirectivesOnly) 734 .Case("constructor", codegenoptions::DebugInfoConstructor) 735 .Case("limited", codegenoptions::LimitedDebugInfo) 736 .Case("standalone", codegenoptions::FullDebugInfo) 737 .Default(~0U); 738 if (Val == ~0U) 739 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) 740 << A->getValue(); 741 else 742 Opts.setDebugInfo(static_cast<codegenoptions::DebugInfoKind>(Val)); 743 } 744 if (Arg *A = Args.getLastArg(OPT_debugger_tuning_EQ)) { 745 unsigned Val = llvm::StringSwitch<unsigned>(A->getValue()) 746 .Case("gdb", unsigned(llvm::DebuggerKind::GDB)) 747 .Case("lldb", unsigned(llvm::DebuggerKind::LLDB)) 748 .Case("sce", unsigned(llvm::DebuggerKind::SCE)) 749 .Default(~0U); 750 if (Val == ~0U) 751 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) 752 << A->getValue(); 753 else 754 Opts.setDebuggerTuning(static_cast<llvm::DebuggerKind>(Val)); 755 } 756 Opts.DwarfVersion = getLastArgIntValue(Args, OPT_dwarf_version_EQ, 0, Diags); 757 Opts.DebugColumnInfo = Args.hasArg(OPT_dwarf_column_info); 758 Opts.EmitCodeView = Args.hasArg(OPT_gcodeview); 759 Opts.CodeViewGHash = Args.hasArg(OPT_gcodeview_ghash); 760 Opts.MacroDebugInfo = Args.hasArg(OPT_debug_info_macro); 761 Opts.WholeProgramVTables = Args.hasArg(OPT_fwhole_program_vtables); 762 Opts.VirtualFunctionElimination = 763 Args.hasArg(OPT_fvirtual_function_elimination); 764 Opts.LTOVisibilityPublicStd = Args.hasArg(OPT_flto_visibility_public_std); 765 Opts.SplitDwarfFile = Args.getLastArgValue(OPT_split_dwarf_file); 766 Opts.SplitDwarfOutput = Args.getLastArgValue(OPT_split_dwarf_output); 767 Opts.SplitDwarfInlining = !Args.hasArg(OPT_fno_split_dwarf_inlining); 768 Opts.DebugTypeExtRefs = Args.hasArg(OPT_dwarf_ext_refs); 769 Opts.DebugExplicitImport = Args.hasArg(OPT_dwarf_explicit_import); 770 Opts.DebugFwdTemplateParams = Args.hasArg(OPT_debug_forward_template_params); 771 Opts.EmbedSource = Args.hasArg(OPT_gembed_source); 772 773 Opts.ForceDwarfFrameSection = 774 Args.hasFlag(OPT_fforce_dwarf_frame, OPT_fno_force_dwarf_frame, false); 775 776 for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ)) 777 Opts.DebugPrefixMap.insert(StringRef(Arg).split('=')); 778 779 if (const Arg *A = 780 Args.getLastArg(OPT_emit_llvm_uselists, OPT_no_emit_llvm_uselists)) 781 Opts.EmitLLVMUseLists = A->getOption().getID() == OPT_emit_llvm_uselists; 782 783 Opts.DisableLLVMPasses = Args.hasArg(OPT_disable_llvm_passes); 784 Opts.DisableLifetimeMarkers = Args.hasArg(OPT_disable_lifetimemarkers); 785 786 const llvm::Triple::ArchType DebugEntryValueArchs[] = { 787 llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::aarch64, 788 llvm::Triple::arm, llvm::Triple::armeb}; 789 790 llvm::Triple T(TargetOpts.Triple); 791 if (Opts.OptimizationLevel > 0 && Opts.hasReducedDebugInfo() && 792 llvm::is_contained(DebugEntryValueArchs, T.getArch())) 793 Opts.EnableDebugEntryValues = Args.hasArg(OPT_femit_debug_entry_values); 794 795 Opts.DisableO0ImplyOptNone = Args.hasArg(OPT_disable_O0_optnone); 796 Opts.DisableRedZone = Args.hasArg(OPT_disable_red_zone); 797 Opts.IndirectTlsSegRefs = Args.hasArg(OPT_mno_tls_direct_seg_refs); 798 Opts.ForbidGuardVariables = Args.hasArg(OPT_fforbid_guard_variables); 799 Opts.UseRegisterSizedBitfieldAccess = Args.hasArg( 800 OPT_fuse_register_sized_bitfield_access); 801 Opts.RelaxedAliasing = Args.hasArg(OPT_relaxed_aliasing); 802 Opts.StructPathTBAA = !Args.hasArg(OPT_no_struct_path_tbaa); 803 Opts.NewStructPathTBAA = !Args.hasArg(OPT_no_struct_path_tbaa) && 804 Args.hasArg(OPT_new_struct_path_tbaa); 805 Opts.FineGrainedBitfieldAccesses = 806 Args.hasFlag(OPT_ffine_grained_bitfield_accesses, 807 OPT_fno_fine_grained_bitfield_accesses, false); 808 Opts.DwarfDebugFlags = Args.getLastArgValue(OPT_dwarf_debug_flags); 809 Opts.RecordCommandLine = Args.getLastArgValue(OPT_record_command_line); 810 Opts.MergeAllConstants = Args.hasArg(OPT_fmerge_all_constants); 811 Opts.NoCommon = Args.hasArg(OPT_fno_common); 812 Opts.NoInlineLineTables = Args.hasArg(OPT_gno_inline_line_tables); 813 Opts.NoImplicitFloat = Args.hasArg(OPT_no_implicit_float); 814 Opts.OptimizeSize = getOptimizationLevelSize(Args); 815 Opts.SimplifyLibCalls = !(Args.hasArg(OPT_fno_builtin) || 816 Args.hasArg(OPT_ffreestanding)); 817 if (Opts.SimplifyLibCalls) 818 getAllNoBuiltinFuncValues(Args, Opts.NoBuiltinFuncs); 819 Opts.UnrollLoops = 820 Args.hasFlag(OPT_funroll_loops, OPT_fno_unroll_loops, 821 (Opts.OptimizationLevel > 1)); 822 Opts.RerollLoops = Args.hasArg(OPT_freroll_loops); 823 824 Opts.DisableIntegratedAS = Args.hasArg(OPT_fno_integrated_as); 825 Opts.Autolink = !Args.hasArg(OPT_fno_autolink); 826 Opts.SampleProfileFile = Args.getLastArgValue(OPT_fprofile_sample_use_EQ); 827 Opts.DebugInfoForProfiling = Args.hasFlag( 828 OPT_fdebug_info_for_profiling, OPT_fno_debug_info_for_profiling, false); 829 Opts.DebugNameTable = static_cast<unsigned>( 830 Args.hasArg(OPT_ggnu_pubnames) 831 ? llvm::DICompileUnit::DebugNameTableKind::GNU 832 : Args.hasArg(OPT_gpubnames) 833 ? llvm::DICompileUnit::DebugNameTableKind::Default 834 : llvm::DICompileUnit::DebugNameTableKind::None); 835 Opts.DebugRangesBaseAddress = Args.hasArg(OPT_fdebug_ranges_base_address); 836 837 setPGOInstrumentor(Opts, Args, Diags); 838 Opts.InstrProfileOutput = 839 Args.getLastArgValue(OPT_fprofile_instrument_path_EQ); 840 Opts.ProfileInstrumentUsePath = 841 Args.getLastArgValue(OPT_fprofile_instrument_use_path_EQ); 842 if (!Opts.ProfileInstrumentUsePath.empty()) 843 setPGOUseInstrumentor(Opts, Opts.ProfileInstrumentUsePath); 844 Opts.ProfileRemappingFile = 845 Args.getLastArgValue(OPT_fprofile_remapping_file_EQ); 846 if (!Opts.ProfileRemappingFile.empty() && !Opts.ExperimentalNewPassManager) { 847 Diags.Report(diag::err_drv_argument_only_allowed_with) 848 << Args.getLastArg(OPT_fprofile_remapping_file_EQ)->getAsString(Args) 849 << "-fexperimental-new-pass-manager"; 850 } 851 852 Opts.CoverageMapping = 853 Args.hasFlag(OPT_fcoverage_mapping, OPT_fno_coverage_mapping, false); 854 Opts.DumpCoverageMapping = Args.hasArg(OPT_dump_coverage_mapping); 855 Opts.AsmVerbose = Args.hasArg(OPT_masm_verbose); 856 Opts.PreserveAsmComments = !Args.hasArg(OPT_fno_preserve_as_comments); 857 Opts.AssumeSaneOperatorNew = !Args.hasArg(OPT_fno_assume_sane_operator_new); 858 Opts.ObjCAutoRefCountExceptions = Args.hasArg(OPT_fobjc_arc_exceptions); 859 Opts.CXAAtExit = !Args.hasArg(OPT_fno_use_cxa_atexit); 860 Opts.RegisterGlobalDtorsWithAtExit = 861 Args.hasArg(OPT_fregister_global_dtors_with_atexit); 862 Opts.CXXCtorDtorAliases = Args.hasArg(OPT_mconstructor_aliases); 863 Opts.CodeModel = TargetOpts.CodeModel; 864 Opts.DebugPass = Args.getLastArgValue(OPT_mdebug_pass); 865 866 // Handle -mframe-pointer option. 867 if (Arg *A = Args.getLastArg(OPT_mframe_pointer_EQ)) { 868 CodeGenOptions::FramePointerKind FP; 869 StringRef Name = A->getValue(); 870 bool ValidFP = true; 871 if (Name == "none") 872 FP = CodeGenOptions::FramePointerKind::None; 873 else if (Name == "non-leaf") 874 FP = CodeGenOptions::FramePointerKind::NonLeaf; 875 else if (Name == "all") 876 FP = CodeGenOptions::FramePointerKind::All; 877 else { 878 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name; 879 Success = false; 880 ValidFP = false; 881 } 882 if (ValidFP) 883 Opts.setFramePointer(FP); 884 } 885 886 // -pg may override -mframe-pointer 887 // TODO: This should be merged into getFramePointerKind in Clang.cpp. 888 if (Args.hasArg(OPT_pg)) 889 Opts.setFramePointer(CodeGenOptions::FramePointerKind::All); 890 891 Opts.DisableFree = Args.hasArg(OPT_disable_free); 892 Opts.DiscardValueNames = Args.hasArg(OPT_discard_value_names); 893 Opts.DisableTailCalls = Args.hasArg(OPT_mdisable_tail_calls); 894 Opts.NoEscapingBlockTailCalls = 895 Args.hasArg(OPT_fno_escaping_block_tail_calls); 896 Opts.FloatABI = Args.getLastArgValue(OPT_mfloat_abi); 897 Opts.LessPreciseFPMAD = Args.hasArg(OPT_cl_mad_enable) || 898 Args.hasArg(OPT_cl_unsafe_math_optimizations) || 899 Args.hasArg(OPT_cl_fast_relaxed_math); 900 Opts.LimitFloatPrecision = Args.getLastArgValue(OPT_mlimit_float_precision); 901 Opts.NoInfsFPMath = (Args.hasArg(OPT_menable_no_infinities) || 902 Args.hasArg(OPT_cl_finite_math_only) || 903 Args.hasArg(OPT_cl_fast_relaxed_math)); 904 Opts.NoNaNsFPMath = (Args.hasArg(OPT_menable_no_nans) || 905 Args.hasArg(OPT_cl_unsafe_math_optimizations) || 906 Args.hasArg(OPT_cl_finite_math_only) || 907 Args.hasArg(OPT_cl_fast_relaxed_math)); 908 Opts.NoSignedZeros = (Args.hasArg(OPT_fno_signed_zeros) || 909 Args.hasArg(OPT_cl_no_signed_zeros) || 910 Args.hasArg(OPT_cl_unsafe_math_optimizations) || 911 Args.hasArg(OPT_cl_fast_relaxed_math)); 912 Opts.Reassociate = Args.hasArg(OPT_mreassociate); 913 Opts.FlushDenorm = Args.hasArg(OPT_cl_denorms_are_zero) || 914 (Args.hasArg(OPT_fcuda_is_device) && 915 Args.hasArg(OPT_fcuda_flush_denormals_to_zero)); 916 Opts.CorrectlyRoundedDivSqrt = 917 Args.hasArg(OPT_cl_fp32_correctly_rounded_divide_sqrt); 918 Opts.UniformWGSize = 919 Args.hasArg(OPT_cl_uniform_work_group_size); 920 Opts.Reciprocals = Args.getAllArgValues(OPT_mrecip_EQ); 921 Opts.ReciprocalMath = Args.hasArg(OPT_freciprocal_math); 922 Opts.NoTrappingMath = Args.hasArg(OPT_fno_trapping_math); 923 Opts.StrictFloatCastOverflow = 924 !Args.hasArg(OPT_fno_strict_float_cast_overflow); 925 926 Opts.NoZeroInitializedInBSS = Args.hasArg(OPT_mno_zero_initialized_in_bss); 927 Opts.NumRegisterParameters = getLastArgIntValue(Args, OPT_mregparm, 0, Diags); 928 Opts.NoExecStack = Args.hasArg(OPT_mno_exec_stack); 929 Opts.FatalWarnings = Args.hasArg(OPT_massembler_fatal_warnings); 930 Opts.NoWarn = Args.hasArg(OPT_massembler_no_warn); 931 Opts.EnableSegmentedStacks = Args.hasArg(OPT_split_stacks); 932 Opts.RelaxAll = Args.hasArg(OPT_mrelax_all); 933 Opts.IncrementalLinkerCompatible = 934 Args.hasArg(OPT_mincremental_linker_compatible); 935 Opts.PIECopyRelocations = 936 Args.hasArg(OPT_mpie_copy_relocations); 937 Opts.NoPLT = Args.hasArg(OPT_fno_plt); 938 Opts.SaveTempLabels = Args.hasArg(OPT_msave_temp_labels); 939 Opts.NoDwarfDirectoryAsm = Args.hasArg(OPT_fno_dwarf_directory_asm); 940 Opts.SoftFloat = Args.hasArg(OPT_msoft_float); 941 Opts.StrictEnums = Args.hasArg(OPT_fstrict_enums); 942 Opts.StrictReturn = !Args.hasArg(OPT_fno_strict_return); 943 Opts.StrictVTablePointers = Args.hasArg(OPT_fstrict_vtable_pointers); 944 Opts.ForceEmitVTables = Args.hasArg(OPT_fforce_emit_vtables); 945 Opts.UnsafeFPMath = Args.hasArg(OPT_menable_unsafe_fp_math) || 946 Args.hasArg(OPT_cl_unsafe_math_optimizations) || 947 Args.hasArg(OPT_cl_fast_relaxed_math); 948 Opts.UnwindTables = Args.hasArg(OPT_munwind_tables); 949 Opts.RelocationModel = getRelocModel(Args, Diags); 950 Opts.ThreadModel = Args.getLastArgValue(OPT_mthread_model, "posix"); 951 if (Opts.ThreadModel != "posix" && Opts.ThreadModel != "single") 952 Diags.Report(diag::err_drv_invalid_value) 953 << Args.getLastArg(OPT_mthread_model)->getAsString(Args) 954 << Opts.ThreadModel; 955 Opts.TrapFuncName = Args.getLastArgValue(OPT_ftrap_function_EQ); 956 Opts.UseInitArray = !Args.hasArg(OPT_fno_use_init_array); 957 958 Opts.FunctionSections = Args.hasFlag(OPT_ffunction_sections, 959 OPT_fno_function_sections, false); 960 Opts.DataSections = Args.hasFlag(OPT_fdata_sections, 961 OPT_fno_data_sections, false); 962 Opts.StackSizeSection = 963 Args.hasFlag(OPT_fstack_size_section, OPT_fno_stack_size_section, false); 964 Opts.UniqueSectionNames = Args.hasFlag(OPT_funique_section_names, 965 OPT_fno_unique_section_names, true); 966 967 Opts.MergeFunctions = Args.hasArg(OPT_fmerge_functions); 968 969 Opts.NoUseJumpTables = Args.hasArg(OPT_fno_jump_tables); 970 971 Opts.NullPointerIsValid = Args.hasArg(OPT_fno_delete_null_pointer_checks); 972 973 Opts.ProfileSampleAccurate = Args.hasArg(OPT_fprofile_sample_accurate); 974 975 Opts.PrepareForLTO = Args.hasArg(OPT_flto, OPT_flto_EQ); 976 Opts.PrepareForThinLTO = false; 977 if (Arg *A = Args.getLastArg(OPT_flto_EQ)) { 978 StringRef S = A->getValue(); 979 if (S == "thin") 980 Opts.PrepareForThinLTO = true; 981 else if (S != "full") 982 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << S; 983 } 984 Opts.LTOUnit = Args.hasFlag(OPT_flto_unit, OPT_fno_lto_unit, false); 985 Opts.EnableSplitLTOUnit = Args.hasArg(OPT_fsplit_lto_unit); 986 if (Arg *A = Args.getLastArg(OPT_fthinlto_index_EQ)) { 987 if (IK.getLanguage() != Language::LLVM_IR) 988 Diags.Report(diag::err_drv_argument_only_allowed_with) 989 << A->getAsString(Args) << "-x ir"; 990 Opts.ThinLTOIndexFile = Args.getLastArgValue(OPT_fthinlto_index_EQ); 991 } 992 if (Arg *A = Args.getLastArg(OPT_save_temps_EQ)) 993 Opts.SaveTempsFilePrefix = 994 llvm::StringSwitch<std::string>(A->getValue()) 995 .Case("obj", FrontendOpts.OutputFile) 996 .Default(llvm::sys::path::filename(FrontendOpts.OutputFile).str()); 997 998 Opts.ThinLinkBitcodeFile = Args.getLastArgValue(OPT_fthin_link_bitcode_EQ); 999 1000 Opts.MSVolatile = Args.hasArg(OPT_fms_volatile); 1001 1002 Opts.VectorizeLoop = Args.hasArg(OPT_vectorize_loops); 1003 Opts.VectorizeSLP = Args.hasArg(OPT_vectorize_slp); 1004 1005 Opts.PreferVectorWidth = Args.getLastArgValue(OPT_mprefer_vector_width_EQ); 1006 1007 Opts.MainFileName = Args.getLastArgValue(OPT_main_file_name); 1008 Opts.VerifyModule = !Args.hasArg(OPT_disable_llvm_verifier); 1009 1010 Opts.ControlFlowGuardNoChecks = Args.hasArg(OPT_cfguard_no_checks); 1011 Opts.ControlFlowGuard = Args.hasArg(OPT_cfguard); 1012 1013 Opts.DisableGCov = Args.hasArg(OPT_test_coverage); 1014 Opts.EmitGcovArcs = Args.hasArg(OPT_femit_coverage_data); 1015 Opts.EmitGcovNotes = Args.hasArg(OPT_femit_coverage_notes); 1016 if (Opts.EmitGcovArcs || Opts.EmitGcovNotes) { 1017 Opts.CoverageDataFile = Args.getLastArgValue(OPT_coverage_data_file); 1018 Opts.CoverageNotesFile = Args.getLastArgValue(OPT_coverage_notes_file); 1019 Opts.CoverageExtraChecksum = Args.hasArg(OPT_coverage_cfg_checksum); 1020 Opts.CoverageNoFunctionNamesInData = 1021 Args.hasArg(OPT_coverage_no_function_names_in_data); 1022 Opts.ProfileFilterFiles = 1023 Args.getLastArgValue(OPT_fprofile_filter_files_EQ); 1024 Opts.ProfileExcludeFiles = 1025 Args.getLastArgValue(OPT_fprofile_exclude_files_EQ); 1026 Opts.CoverageExitBlockBeforeBody = 1027 Args.hasArg(OPT_coverage_exit_block_before_body); 1028 if (Args.hasArg(OPT_coverage_version_EQ)) { 1029 StringRef CoverageVersion = Args.getLastArgValue(OPT_coverage_version_EQ); 1030 if (CoverageVersion.size() != 4) { 1031 Diags.Report(diag::err_drv_invalid_value) 1032 << Args.getLastArg(OPT_coverage_version_EQ)->getAsString(Args) 1033 << CoverageVersion; 1034 } else { 1035 memcpy(Opts.CoverageVersion, CoverageVersion.data(), 4); 1036 } 1037 } 1038 } 1039 // Handle -fembed-bitcode option. 1040 if (Arg *A = Args.getLastArg(OPT_fembed_bitcode_EQ)) { 1041 StringRef Name = A->getValue(); 1042 unsigned Model = llvm::StringSwitch<unsigned>(Name) 1043 .Case("off", CodeGenOptions::Embed_Off) 1044 .Case("all", CodeGenOptions::Embed_All) 1045 .Case("bitcode", CodeGenOptions::Embed_Bitcode) 1046 .Case("marker", CodeGenOptions::Embed_Marker) 1047 .Default(~0U); 1048 if (Model == ~0U) { 1049 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name; 1050 Success = false; 1051 } else 1052 Opts.setEmbedBitcode( 1053 static_cast<CodeGenOptions::EmbedBitcodeKind>(Model)); 1054 } 1055 // FIXME: For backend options that are not yet recorded as function 1056 // attributes in the IR, keep track of them so we can embed them in a 1057 // separate data section and use them when building the bitcode. 1058 if (Opts.getEmbedBitcode() == CodeGenOptions::Embed_All) { 1059 for (const auto &A : Args) { 1060 // Do not encode output and input. 1061 if (A->getOption().getID() == options::OPT_o || 1062 A->getOption().getID() == options::OPT_INPUT || 1063 A->getOption().getID() == options::OPT_x || 1064 A->getOption().getID() == options::OPT_fembed_bitcode || 1065 (A->getOption().getGroup().isValid() && 1066 A->getOption().getGroup().getID() == options::OPT_W_Group)) 1067 continue; 1068 ArgStringList ASL; 1069 A->render(Args, ASL); 1070 for (const auto &arg : ASL) { 1071 StringRef ArgStr(arg); 1072 Opts.CmdArgs.insert(Opts.CmdArgs.end(), ArgStr.begin(), ArgStr.end()); 1073 // using \00 to separate each commandline options. 1074 Opts.CmdArgs.push_back('\0'); 1075 } 1076 } 1077 } 1078 1079 Opts.PreserveVec3Type = Args.hasArg(OPT_fpreserve_vec3_type); 1080 Opts.InstrumentFunctions = Args.hasArg(OPT_finstrument_functions); 1081 Opts.InstrumentFunctionsAfterInlining = 1082 Args.hasArg(OPT_finstrument_functions_after_inlining); 1083 Opts.InstrumentFunctionEntryBare = 1084 Args.hasArg(OPT_finstrument_function_entry_bare); 1085 1086 Opts.XRayInstrumentFunctions = 1087 Args.hasArg(OPT_fxray_instrument); 1088 Opts.XRayAlwaysEmitCustomEvents = 1089 Args.hasArg(OPT_fxray_always_emit_customevents); 1090 Opts.XRayAlwaysEmitTypedEvents = 1091 Args.hasArg(OPT_fxray_always_emit_typedevents); 1092 Opts.XRayInstructionThreshold = 1093 getLastArgIntValue(Args, OPT_fxray_instruction_threshold_EQ, 200, Diags); 1094 1095 auto XRayInstrBundles = 1096 Args.getAllArgValues(OPT_fxray_instrumentation_bundle); 1097 if (XRayInstrBundles.empty()) 1098 Opts.XRayInstrumentationBundle.Mask = XRayInstrKind::All; 1099 else 1100 for (const auto &A : XRayInstrBundles) 1101 parseXRayInstrumentationBundle("-fxray-instrumentation-bundle=", A, Args, 1102 Diags, Opts.XRayInstrumentationBundle); 1103 1104 Opts.PatchableFunctionEntryCount = 1105 getLastArgIntValue(Args, OPT_fpatchable_function_entry_EQ, 0, Diags); 1106 Opts.PatchableFunctionEntryOffset = getLastArgIntValue( 1107 Args, OPT_fpatchable_function_entry_offset_EQ, 0, Diags); 1108 Opts.InstrumentForProfiling = Args.hasArg(OPT_pg); 1109 Opts.CallFEntry = Args.hasArg(OPT_mfentry); 1110 Opts.MNopMCount = Args.hasArg(OPT_mnop_mcount); 1111 Opts.RecordMCount = Args.hasArg(OPT_mrecord_mcount); 1112 Opts.PackedStack = Args.hasArg(OPT_mpacked_stack); 1113 Opts.EmitOpenCLArgMetadata = Args.hasArg(OPT_cl_kernel_arg_info); 1114 1115 if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) { 1116 StringRef Name = A->getValue(); 1117 if (Name == "full") { 1118 Opts.CFProtectionReturn = 1; 1119 Opts.CFProtectionBranch = 1; 1120 } else if (Name == "return") 1121 Opts.CFProtectionReturn = 1; 1122 else if (Name == "branch") 1123 Opts.CFProtectionBranch = 1; 1124 else if (Name != "none") { 1125 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name; 1126 Success = false; 1127 } 1128 } 1129 1130 if (const Arg *A = Args.getLastArg(OPT_compress_debug_sections, 1131 OPT_compress_debug_sections_EQ)) { 1132 if (A->getOption().getID() == OPT_compress_debug_sections) { 1133 // TODO: be more clever about the compression type auto-detection 1134 Opts.setCompressDebugSections(llvm::DebugCompressionType::GNU); 1135 } else { 1136 auto DCT = llvm::StringSwitch<llvm::DebugCompressionType>(A->getValue()) 1137 .Case("none", llvm::DebugCompressionType::None) 1138 .Case("zlib", llvm::DebugCompressionType::Z) 1139 .Case("zlib-gnu", llvm::DebugCompressionType::GNU) 1140 .Default(llvm::DebugCompressionType::None); 1141 Opts.setCompressDebugSections(DCT); 1142 } 1143 } 1144 1145 Opts.RelaxELFRelocations = Args.hasArg(OPT_mrelax_relocations); 1146 Opts.DebugCompilationDir = Args.getLastArgValue(OPT_fdebug_compilation_dir); 1147 for (auto *A : 1148 Args.filtered(OPT_mlink_bitcode_file, OPT_mlink_builtin_bitcode)) { 1149 CodeGenOptions::BitcodeFileToLink F; 1150 F.Filename = A->getValue(); 1151 if (A->getOption().matches(OPT_mlink_builtin_bitcode)) { 1152 F.LinkFlags = llvm::Linker::Flags::LinkOnlyNeeded; 1153 // When linking CUDA bitcode, propagate function attributes so that 1154 // e.g. libdevice gets fast-math attrs if we're building with fast-math. 1155 F.PropagateAttrs = true; 1156 F.Internalize = true; 1157 } 1158 Opts.LinkBitcodeFiles.push_back(F); 1159 } 1160 Opts.SanitizeCoverageType = 1161 getLastArgIntValue(Args, OPT_fsanitize_coverage_type, 0, Diags); 1162 Opts.SanitizeCoverageIndirectCalls = 1163 Args.hasArg(OPT_fsanitize_coverage_indirect_calls); 1164 Opts.SanitizeCoverageTraceBB = Args.hasArg(OPT_fsanitize_coverage_trace_bb); 1165 Opts.SanitizeCoverageTraceCmp = Args.hasArg(OPT_fsanitize_coverage_trace_cmp); 1166 Opts.SanitizeCoverageTraceDiv = Args.hasArg(OPT_fsanitize_coverage_trace_div); 1167 Opts.SanitizeCoverageTraceGep = Args.hasArg(OPT_fsanitize_coverage_trace_gep); 1168 Opts.SanitizeCoverage8bitCounters = 1169 Args.hasArg(OPT_fsanitize_coverage_8bit_counters); 1170 Opts.SanitizeCoverageTracePC = Args.hasArg(OPT_fsanitize_coverage_trace_pc); 1171 Opts.SanitizeCoverageTracePCGuard = 1172 Args.hasArg(OPT_fsanitize_coverage_trace_pc_guard); 1173 Opts.SanitizeCoverageNoPrune = Args.hasArg(OPT_fsanitize_coverage_no_prune); 1174 Opts.SanitizeCoverageInline8bitCounters = 1175 Args.hasArg(OPT_fsanitize_coverage_inline_8bit_counters); 1176 Opts.SanitizeCoveragePCTable = Args.hasArg(OPT_fsanitize_coverage_pc_table); 1177 Opts.SanitizeCoverageStackDepth = 1178 Args.hasArg(OPT_fsanitize_coverage_stack_depth); 1179 Opts.SanitizeMemoryTrackOrigins = 1180 getLastArgIntValue(Args, OPT_fsanitize_memory_track_origins_EQ, 0, Diags); 1181 Opts.SanitizeMemoryUseAfterDtor = 1182 Args.hasFlag(OPT_fsanitize_memory_use_after_dtor, 1183 OPT_fno_sanitize_memory_use_after_dtor, 1184 false); 1185 Opts.SanitizeMinimalRuntime = Args.hasArg(OPT_fsanitize_minimal_runtime); 1186 Opts.SanitizeCfiCrossDso = Args.hasArg(OPT_fsanitize_cfi_cross_dso); 1187 Opts.SanitizeCfiICallGeneralizePointers = 1188 Args.hasArg(OPT_fsanitize_cfi_icall_generalize_pointers); 1189 Opts.SanitizeCfiCanonicalJumpTables = 1190 Args.hasArg(OPT_fsanitize_cfi_canonical_jump_tables); 1191 Opts.SanitizeStats = Args.hasArg(OPT_fsanitize_stats); 1192 if (Arg *A = Args.getLastArg( 1193 OPT_fsanitize_address_poison_custom_array_cookie, 1194 OPT_fno_sanitize_address_poison_custom_array_cookie)) { 1195 Opts.SanitizeAddressPoisonCustomArrayCookie = 1196 A->getOption().getID() == 1197 OPT_fsanitize_address_poison_custom_array_cookie; 1198 } 1199 if (Arg *A = Args.getLastArg(OPT_fsanitize_address_use_after_scope, 1200 OPT_fno_sanitize_address_use_after_scope)) { 1201 Opts.SanitizeAddressUseAfterScope = 1202 A->getOption().getID() == OPT_fsanitize_address_use_after_scope; 1203 } 1204 Opts.SanitizeAddressGlobalsDeadStripping = 1205 Args.hasArg(OPT_fsanitize_address_globals_dead_stripping); 1206 if (Arg *A = Args.getLastArg(OPT_fsanitize_address_use_odr_indicator, 1207 OPT_fno_sanitize_address_use_odr_indicator)) { 1208 Opts.SanitizeAddressUseOdrIndicator = 1209 A->getOption().getID() == OPT_fsanitize_address_use_odr_indicator; 1210 } 1211 Opts.SSPBufferSize = 1212 getLastArgIntValue(Args, OPT_stack_protector_buffer_size, 8, Diags); 1213 Opts.StackRealignment = Args.hasArg(OPT_mstackrealign); 1214 if (Arg *A = Args.getLastArg(OPT_mstack_alignment)) { 1215 StringRef Val = A->getValue(); 1216 unsigned StackAlignment = Opts.StackAlignment; 1217 Val.getAsInteger(10, StackAlignment); 1218 Opts.StackAlignment = StackAlignment; 1219 } 1220 1221 if (Arg *A = Args.getLastArg(OPT_mstack_probe_size)) { 1222 StringRef Val = A->getValue(); 1223 unsigned StackProbeSize = Opts.StackProbeSize; 1224 Val.getAsInteger(0, StackProbeSize); 1225 Opts.StackProbeSize = StackProbeSize; 1226 } 1227 1228 Opts.NoStackArgProbe = Args.hasArg(OPT_mno_stack_arg_probe); 1229 1230 if (Arg *A = Args.getLastArg(OPT_fobjc_dispatch_method_EQ)) { 1231 StringRef Name = A->getValue(); 1232 unsigned Method = llvm::StringSwitch<unsigned>(Name) 1233 .Case("legacy", CodeGenOptions::Legacy) 1234 .Case("non-legacy", CodeGenOptions::NonLegacy) 1235 .Case("mixed", CodeGenOptions::Mixed) 1236 .Default(~0U); 1237 if (Method == ~0U) { 1238 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name; 1239 Success = false; 1240 } else { 1241 Opts.setObjCDispatchMethod( 1242 static_cast<CodeGenOptions::ObjCDispatchMethodKind>(Method)); 1243 } 1244 } 1245 1246 1247 if (Args.hasArg(OPT_fno_objc_convert_messages_to_runtime_calls)) 1248 Opts.ObjCConvertMessagesToRuntimeCalls = 0; 1249 1250 if (Args.getLastArg(OPT_femulated_tls) || 1251 Args.getLastArg(OPT_fno_emulated_tls)) { 1252 Opts.ExplicitEmulatedTLS = true; 1253 Opts.EmulatedTLS = 1254 Args.hasFlag(OPT_femulated_tls, OPT_fno_emulated_tls, false); 1255 } 1256 1257 if (Arg *A = Args.getLastArg(OPT_ftlsmodel_EQ)) { 1258 StringRef Name = A->getValue(); 1259 unsigned Model = llvm::StringSwitch<unsigned>(Name) 1260 .Case("global-dynamic", CodeGenOptions::GeneralDynamicTLSModel) 1261 .Case("local-dynamic", CodeGenOptions::LocalDynamicTLSModel) 1262 .Case("initial-exec", CodeGenOptions::InitialExecTLSModel) 1263 .Case("local-exec", CodeGenOptions::LocalExecTLSModel) 1264 .Default(~0U); 1265 if (Model == ~0U) { 1266 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name; 1267 Success = false; 1268 } else { 1269 Opts.setDefaultTLSModel(static_cast<CodeGenOptions::TLSModel>(Model)); 1270 } 1271 } 1272 1273 Opts.TLSSize = getLastArgIntValue(Args, OPT_mtls_size_EQ, 0, Diags); 1274 1275 if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_EQ)) { 1276 StringRef Val = A->getValue(); 1277 Opts.FPDenormalMode = llvm::parseDenormalFPAttribute(Val); 1278 if (Opts.FPDenormalMode == llvm::DenormalMode::Invalid) 1279 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val; 1280 } 1281 1282 if (Arg *A = Args.getLastArg(OPT_fpcc_struct_return, OPT_freg_struct_return)) { 1283 if (A->getOption().matches(OPT_fpcc_struct_return)) { 1284 Opts.setStructReturnConvention(CodeGenOptions::SRCK_OnStack); 1285 } else { 1286 assert(A->getOption().matches(OPT_freg_struct_return)); 1287 Opts.setStructReturnConvention(CodeGenOptions::SRCK_InRegs); 1288 } 1289 } 1290 1291 Opts.DependentLibraries = Args.getAllArgValues(OPT_dependent_lib); 1292 Opts.LinkerOptions = Args.getAllArgValues(OPT_linker_option); 1293 bool NeedLocTracking = false; 1294 1295 Opts.OptRecordFile = Args.getLastArgValue(OPT_opt_record_file); 1296 if (!Opts.OptRecordFile.empty()) 1297 NeedLocTracking = true; 1298 1299 if (Arg *A = Args.getLastArg(OPT_opt_record_passes)) { 1300 Opts.OptRecordPasses = A->getValue(); 1301 NeedLocTracking = true; 1302 } 1303 1304 if (Arg *A = Args.getLastArg(OPT_opt_record_format)) { 1305 Opts.OptRecordFormat = A->getValue(); 1306 NeedLocTracking = true; 1307 } 1308 1309 if (Arg *A = Args.getLastArg(OPT_Rpass_EQ)) { 1310 Opts.OptimizationRemarkPattern = 1311 GenerateOptimizationRemarkRegex(Diags, Args, A); 1312 NeedLocTracking = true; 1313 } 1314 1315 if (Arg *A = Args.getLastArg(OPT_Rpass_missed_EQ)) { 1316 Opts.OptimizationRemarkMissedPattern = 1317 GenerateOptimizationRemarkRegex(Diags, Args, A); 1318 NeedLocTracking = true; 1319 } 1320 1321 if (Arg *A = Args.getLastArg(OPT_Rpass_analysis_EQ)) { 1322 Opts.OptimizationRemarkAnalysisPattern = 1323 GenerateOptimizationRemarkRegex(Diags, Args, A); 1324 NeedLocTracking = true; 1325 } 1326 1327 Opts.DiagnosticsWithHotness = 1328 Args.hasArg(options::OPT_fdiagnostics_show_hotness); 1329 bool UsingSampleProfile = !Opts.SampleProfileFile.empty(); 1330 bool UsingProfile = UsingSampleProfile || 1331 (Opts.getProfileUse() != CodeGenOptions::ProfileNone); 1332 1333 if (Opts.DiagnosticsWithHotness && !UsingProfile && 1334 // An IR file will contain PGO as metadata 1335 IK.getLanguage() != Language::LLVM_IR) 1336 Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo) 1337 << "-fdiagnostics-show-hotness"; 1338 1339 Opts.DiagnosticsHotnessThreshold = getLastArgUInt64Value( 1340 Args, options::OPT_fdiagnostics_hotness_threshold_EQ, 0); 1341 if (Opts.DiagnosticsHotnessThreshold > 0 && !UsingProfile) 1342 Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo) 1343 << "-fdiagnostics-hotness-threshold="; 1344 1345 // If the user requested to use a sample profile for PGO, then the 1346 // backend will need to track source location information so the profile 1347 // can be incorporated into the IR. 1348 if (UsingSampleProfile) 1349 NeedLocTracking = true; 1350 1351 // If the user requested a flag that requires source locations available in 1352 // the backend, make sure that the backend tracks source location information. 1353 if (NeedLocTracking && Opts.getDebugInfo() == codegenoptions::NoDebugInfo) 1354 Opts.setDebugInfo(codegenoptions::LocTrackingOnly); 1355 1356 Opts.RewriteMapFiles = Args.getAllArgValues(OPT_frewrite_map_file); 1357 1358 // Parse -fsanitize-recover= arguments. 1359 // FIXME: Report unrecoverable sanitizers incorrectly specified here. 1360 parseSanitizerKinds("-fsanitize-recover=", 1361 Args.getAllArgValues(OPT_fsanitize_recover_EQ), Diags, 1362 Opts.SanitizeRecover); 1363 parseSanitizerKinds("-fsanitize-trap=", 1364 Args.getAllArgValues(OPT_fsanitize_trap_EQ), Diags, 1365 Opts.SanitizeTrap); 1366 1367 Opts.CudaGpuBinaryFileName = 1368 Args.getLastArgValue(OPT_fcuda_include_gpubinary); 1369 1370 Opts.Backchain = Args.hasArg(OPT_mbackchain); 1371 1372 Opts.EmitCheckPathComponentsToStrip = getLastArgIntValue( 1373 Args, OPT_fsanitize_undefined_strip_path_components_EQ, 0, Diags); 1374 1375 Opts.EmitVersionIdentMetadata = Args.hasFlag(OPT_Qy, OPT_Qn, true); 1376 1377 Opts.Addrsig = Args.hasArg(OPT_faddrsig); 1378 1379 if (Arg *A = Args.getLastArg(OPT_msign_return_address_EQ)) { 1380 StringRef SignScope = A->getValue(); 1381 1382 if (SignScope.equals_lower("none")) 1383 Opts.setSignReturnAddress(CodeGenOptions::SignReturnAddressScope::None); 1384 else if (SignScope.equals_lower("all")) 1385 Opts.setSignReturnAddress(CodeGenOptions::SignReturnAddressScope::All); 1386 else if (SignScope.equals_lower("non-leaf")) 1387 Opts.setSignReturnAddress( 1388 CodeGenOptions::SignReturnAddressScope::NonLeaf); 1389 else 1390 Diags.Report(diag::err_drv_invalid_value) 1391 << A->getAsString(Args) << SignScope; 1392 1393 if (Arg *A = Args.getLastArg(OPT_msign_return_address_key_EQ)) { 1394 StringRef SignKey = A->getValue(); 1395 if (!SignScope.empty() && !SignKey.empty()) { 1396 if (SignKey.equals_lower("a_key")) 1397 Opts.setSignReturnAddressKey( 1398 CodeGenOptions::SignReturnAddressKeyValue::AKey); 1399 else if (SignKey.equals_lower("b_key")) 1400 Opts.setSignReturnAddressKey( 1401 CodeGenOptions::SignReturnAddressKeyValue::BKey); 1402 else 1403 Diags.Report(diag::err_drv_invalid_value) 1404 << A->getAsString(Args) << SignKey; 1405 } 1406 } 1407 } 1408 1409 Opts.BranchTargetEnforcement = Args.hasArg(OPT_mbranch_target_enforce); 1410 1411 Opts.KeepStaticConsts = Args.hasArg(OPT_fkeep_static_consts); 1412 1413 Opts.SpeculativeLoadHardening = Args.hasArg(OPT_mspeculative_load_hardening); 1414 1415 Opts.DefaultFunctionAttrs = Args.getAllArgValues(OPT_default_function_attr); 1416 1417 Opts.PassPlugins = Args.getAllArgValues(OPT_fpass_plugin_EQ); 1418 1419 Opts.SymbolPartition = Args.getLastArgValue(OPT_fsymbol_partition_EQ); 1420 1421 return Success; 1422 } 1423 1424 static void ParseDependencyOutputArgs(DependencyOutputOptions &Opts, 1425 ArgList &Args) { 1426 Opts.OutputFile = Args.getLastArgValue(OPT_dependency_file); 1427 Opts.Targets = Args.getAllArgValues(OPT_MT); 1428 Opts.IncludeSystemHeaders = Args.hasArg(OPT_sys_header_deps); 1429 Opts.IncludeModuleFiles = Args.hasArg(OPT_module_file_deps); 1430 Opts.UsePhonyTargets = Args.hasArg(OPT_MP); 1431 Opts.ShowHeaderIncludes = Args.hasArg(OPT_H); 1432 Opts.HeaderIncludeOutputFile = Args.getLastArgValue(OPT_header_include_file); 1433 Opts.AddMissingHeaderDeps = Args.hasArg(OPT_MG); 1434 if (Args.hasArg(OPT_show_includes)) { 1435 // Writing both /showIncludes and preprocessor output to stdout 1436 // would produce interleaved output, so use stderr for /showIncludes. 1437 // This behaves the same as cl.exe, when /E, /EP or /P are passed. 1438 if (Args.hasArg(options::OPT_E) || Args.hasArg(options::OPT_P)) 1439 Opts.ShowIncludesDest = ShowIncludesDestination::Stderr; 1440 else 1441 Opts.ShowIncludesDest = ShowIncludesDestination::Stdout; 1442 } else { 1443 Opts.ShowIncludesDest = ShowIncludesDestination::None; 1444 } 1445 Opts.DOTOutputFile = Args.getLastArgValue(OPT_dependency_dot); 1446 Opts.ModuleDependencyOutputDir = 1447 Args.getLastArgValue(OPT_module_dependency_dir); 1448 if (Args.hasArg(OPT_MV)) 1449 Opts.OutputFormat = DependencyOutputFormat::NMake; 1450 // Add sanitizer blacklists as extra dependencies. 1451 // They won't be discovered by the regular preprocessor, so 1452 // we let make / ninja to know about this implicit dependency. 1453 if (!Args.hasArg(OPT_fno_sanitize_blacklist)) { 1454 for (const auto *A : Args.filtered(OPT_fsanitize_blacklist)) { 1455 StringRef Val = A->getValue(); 1456 if (Val.find('=') == StringRef::npos) 1457 Opts.ExtraDeps.push_back(Val); 1458 } 1459 if (Opts.IncludeSystemHeaders) { 1460 for (const auto *A : Args.filtered(OPT_fsanitize_system_blacklist)) { 1461 StringRef Val = A->getValue(); 1462 if (Val.find('=') == StringRef::npos) 1463 Opts.ExtraDeps.push_back(Val); 1464 } 1465 } 1466 } 1467 1468 // Propagate the extra dependencies. 1469 for (const auto *A : Args.filtered(OPT_fdepfile_entry)) { 1470 Opts.ExtraDeps.push_back(A->getValue()); 1471 } 1472 1473 // Only the -fmodule-file=<file> form. 1474 for (const auto *A : Args.filtered(OPT_fmodule_file)) { 1475 StringRef Val = A->getValue(); 1476 if (Val.find('=') == StringRef::npos) 1477 Opts.ExtraDeps.push_back(Val); 1478 } 1479 } 1480 1481 static bool parseShowColorsArgs(const ArgList &Args, bool DefaultColor) { 1482 // Color diagnostics default to auto ("on" if terminal supports) in the driver 1483 // but default to off in cc1, needing an explicit OPT_fdiagnostics_color. 1484 // Support both clang's -f[no-]color-diagnostics and gcc's 1485 // -f[no-]diagnostics-colors[=never|always|auto]. 1486 enum { 1487 Colors_On, 1488 Colors_Off, 1489 Colors_Auto 1490 } ShowColors = DefaultColor ? Colors_Auto : Colors_Off; 1491 for (auto *A : Args) { 1492 const Option &O = A->getOption(); 1493 if (O.matches(options::OPT_fcolor_diagnostics) || 1494 O.matches(options::OPT_fdiagnostics_color)) { 1495 ShowColors = Colors_On; 1496 } else if (O.matches(options::OPT_fno_color_diagnostics) || 1497 O.matches(options::OPT_fno_diagnostics_color)) { 1498 ShowColors = Colors_Off; 1499 } else if (O.matches(options::OPT_fdiagnostics_color_EQ)) { 1500 StringRef Value(A->getValue()); 1501 if (Value == "always") 1502 ShowColors = Colors_On; 1503 else if (Value == "never") 1504 ShowColors = Colors_Off; 1505 else if (Value == "auto") 1506 ShowColors = Colors_Auto; 1507 } 1508 } 1509 return ShowColors == Colors_On || 1510 (ShowColors == Colors_Auto && 1511 llvm::sys::Process::StandardErrHasColors()); 1512 } 1513 1514 static bool checkVerifyPrefixes(const std::vector<std::string> &VerifyPrefixes, 1515 DiagnosticsEngine *Diags) { 1516 bool Success = true; 1517 for (const auto &Prefix : VerifyPrefixes) { 1518 // Every prefix must start with a letter and contain only alphanumeric 1519 // characters, hyphens, and underscores. 1520 auto BadChar = llvm::find_if(Prefix, [](char C) { 1521 return !isAlphanumeric(C) && C != '-' && C != '_'; 1522 }); 1523 if (BadChar != Prefix.end() || !isLetter(Prefix[0])) { 1524 Success = false; 1525 if (Diags) { 1526 Diags->Report(diag::err_drv_invalid_value) << "-verify=" << Prefix; 1527 Diags->Report(diag::note_drv_verify_prefix_spelling); 1528 } 1529 } 1530 } 1531 return Success; 1532 } 1533 1534 bool clang::ParseDiagnosticArgs(DiagnosticOptions &Opts, ArgList &Args, 1535 DiagnosticsEngine *Diags, 1536 bool DefaultDiagColor, bool DefaultShowOpt) { 1537 bool Success = true; 1538 1539 Opts.DiagnosticLogFile = Args.getLastArgValue(OPT_diagnostic_log_file); 1540 if (Arg *A = 1541 Args.getLastArg(OPT_diagnostic_serialized_file, OPT__serialize_diags)) 1542 Opts.DiagnosticSerializationFile = A->getValue(); 1543 Opts.IgnoreWarnings = Args.hasArg(OPT_w); 1544 Opts.NoRewriteMacros = Args.hasArg(OPT_Wno_rewrite_macros); 1545 Opts.Pedantic = Args.hasArg(OPT_pedantic); 1546 Opts.PedanticErrors = Args.hasArg(OPT_pedantic_errors); 1547 Opts.ShowCarets = !Args.hasArg(OPT_fno_caret_diagnostics); 1548 Opts.ShowColors = parseShowColorsArgs(Args, DefaultDiagColor); 1549 Opts.ShowColumn = Args.hasFlag(OPT_fshow_column, 1550 OPT_fno_show_column, 1551 /*Default=*/true); 1552 Opts.ShowFixits = !Args.hasArg(OPT_fno_diagnostics_fixit_info); 1553 Opts.ShowLocation = !Args.hasArg(OPT_fno_show_source_location); 1554 Opts.AbsolutePath = Args.hasArg(OPT_fdiagnostics_absolute_paths); 1555 Opts.ShowOptionNames = 1556 Args.hasFlag(OPT_fdiagnostics_show_option, 1557 OPT_fno_diagnostics_show_option, DefaultShowOpt); 1558 1559 llvm::sys::Process::UseANSIEscapeCodes(Args.hasArg(OPT_fansi_escape_codes)); 1560 1561 // Default behavior is to not to show note include stacks. 1562 Opts.ShowNoteIncludeStack = false; 1563 if (Arg *A = Args.getLastArg(OPT_fdiagnostics_show_note_include_stack, 1564 OPT_fno_diagnostics_show_note_include_stack)) 1565 if (A->getOption().matches(OPT_fdiagnostics_show_note_include_stack)) 1566 Opts.ShowNoteIncludeStack = true; 1567 1568 StringRef ShowOverloads = 1569 Args.getLastArgValue(OPT_fshow_overloads_EQ, "all"); 1570 if (ShowOverloads == "best") 1571 Opts.setShowOverloads(Ovl_Best); 1572 else if (ShowOverloads == "all") 1573 Opts.setShowOverloads(Ovl_All); 1574 else { 1575 Success = false; 1576 if (Diags) 1577 Diags->Report(diag::err_drv_invalid_value) 1578 << Args.getLastArg(OPT_fshow_overloads_EQ)->getAsString(Args) 1579 << ShowOverloads; 1580 } 1581 1582 StringRef ShowCategory = 1583 Args.getLastArgValue(OPT_fdiagnostics_show_category, "none"); 1584 if (ShowCategory == "none") 1585 Opts.ShowCategories = 0; 1586 else if (ShowCategory == "id") 1587 Opts.ShowCategories = 1; 1588 else if (ShowCategory == "name") 1589 Opts.ShowCategories = 2; 1590 else { 1591 Success = false; 1592 if (Diags) 1593 Diags->Report(diag::err_drv_invalid_value) 1594 << Args.getLastArg(OPT_fdiagnostics_show_category)->getAsString(Args) 1595 << ShowCategory; 1596 } 1597 1598 StringRef Format = 1599 Args.getLastArgValue(OPT_fdiagnostics_format, "clang"); 1600 if (Format == "clang") 1601 Opts.setFormat(DiagnosticOptions::Clang); 1602 else if (Format == "msvc") 1603 Opts.setFormat(DiagnosticOptions::MSVC); 1604 else if (Format == "msvc-fallback") { 1605 Opts.setFormat(DiagnosticOptions::MSVC); 1606 Opts.CLFallbackMode = true; 1607 } else if (Format == "vi") 1608 Opts.setFormat(DiagnosticOptions::Vi); 1609 else { 1610 Success = false; 1611 if (Diags) 1612 Diags->Report(diag::err_drv_invalid_value) 1613 << Args.getLastArg(OPT_fdiagnostics_format)->getAsString(Args) 1614 << Format; 1615 } 1616 1617 Opts.ShowSourceRanges = Args.hasArg(OPT_fdiagnostics_print_source_range_info); 1618 Opts.ShowParseableFixits = Args.hasArg(OPT_fdiagnostics_parseable_fixits); 1619 Opts.ShowPresumedLoc = !Args.hasArg(OPT_fno_diagnostics_use_presumed_location); 1620 Opts.VerifyDiagnostics = Args.hasArg(OPT_verify) || Args.hasArg(OPT_verify_EQ); 1621 Opts.VerifyPrefixes = Args.getAllArgValues(OPT_verify_EQ); 1622 if (Args.hasArg(OPT_verify)) 1623 Opts.VerifyPrefixes.push_back("expected"); 1624 // Keep VerifyPrefixes in its original order for the sake of diagnostics, and 1625 // then sort it to prepare for fast lookup using std::binary_search. 1626 if (!checkVerifyPrefixes(Opts.VerifyPrefixes, Diags)) { 1627 Opts.VerifyDiagnostics = false; 1628 Success = false; 1629 } 1630 else 1631 llvm::sort(Opts.VerifyPrefixes); 1632 DiagnosticLevelMask DiagMask = DiagnosticLevelMask::None; 1633 Success &= parseDiagnosticLevelMask("-verify-ignore-unexpected=", 1634 Args.getAllArgValues(OPT_verify_ignore_unexpected_EQ), 1635 Diags, DiagMask); 1636 if (Args.hasArg(OPT_verify_ignore_unexpected)) 1637 DiagMask = DiagnosticLevelMask::All; 1638 Opts.setVerifyIgnoreUnexpected(DiagMask); 1639 Opts.ElideType = !Args.hasArg(OPT_fno_elide_type); 1640 Opts.ShowTemplateTree = Args.hasArg(OPT_fdiagnostics_show_template_tree); 1641 Opts.ErrorLimit = getLastArgIntValue(Args, OPT_ferror_limit, 0, Diags); 1642 Opts.MacroBacktraceLimit = 1643 getLastArgIntValue(Args, OPT_fmacro_backtrace_limit, 1644 DiagnosticOptions::DefaultMacroBacktraceLimit, Diags); 1645 Opts.TemplateBacktraceLimit = getLastArgIntValue( 1646 Args, OPT_ftemplate_backtrace_limit, 1647 DiagnosticOptions::DefaultTemplateBacktraceLimit, Diags); 1648 Opts.ConstexprBacktraceLimit = getLastArgIntValue( 1649 Args, OPT_fconstexpr_backtrace_limit, 1650 DiagnosticOptions::DefaultConstexprBacktraceLimit, Diags); 1651 Opts.SpellCheckingLimit = getLastArgIntValue( 1652 Args, OPT_fspell_checking_limit, 1653 DiagnosticOptions::DefaultSpellCheckingLimit, Diags); 1654 Opts.SnippetLineLimit = getLastArgIntValue( 1655 Args, OPT_fcaret_diagnostics_max_lines, 1656 DiagnosticOptions::DefaultSnippetLineLimit, Diags); 1657 Opts.TabStop = getLastArgIntValue(Args, OPT_ftabstop, 1658 DiagnosticOptions::DefaultTabStop, Diags); 1659 if (Opts.TabStop == 0 || Opts.TabStop > DiagnosticOptions::MaxTabStop) { 1660 Opts.TabStop = DiagnosticOptions::DefaultTabStop; 1661 if (Diags) 1662 Diags->Report(diag::warn_ignoring_ftabstop_value) 1663 << Opts.TabStop << DiagnosticOptions::DefaultTabStop; 1664 } 1665 Opts.MessageLength = getLastArgIntValue(Args, OPT_fmessage_length, 0, Diags); 1666 addDiagnosticArgs(Args, OPT_W_Group, OPT_W_value_Group, Opts.Warnings); 1667 addDiagnosticArgs(Args, OPT_R_Group, OPT_R_value_Group, Opts.Remarks); 1668 1669 return Success; 1670 } 1671 1672 static void ParseFileSystemArgs(FileSystemOptions &Opts, ArgList &Args) { 1673 Opts.WorkingDir = Args.getLastArgValue(OPT_working_directory); 1674 } 1675 1676 /// Parse the argument to the -ftest-module-file-extension 1677 /// command-line argument. 1678 /// 1679 /// \returns true on error, false on success. 1680 static bool parseTestModuleFileExtensionArg(StringRef Arg, 1681 std::string &BlockName, 1682 unsigned &MajorVersion, 1683 unsigned &MinorVersion, 1684 bool &Hashed, 1685 std::string &UserInfo) { 1686 SmallVector<StringRef, 5> Args; 1687 Arg.split(Args, ':', 5); 1688 if (Args.size() < 5) 1689 return true; 1690 1691 BlockName = Args[0]; 1692 if (Args[1].getAsInteger(10, MajorVersion)) return true; 1693 if (Args[2].getAsInteger(10, MinorVersion)) return true; 1694 if (Args[3].getAsInteger(2, Hashed)) return true; 1695 if (Args.size() > 4) 1696 UserInfo = Args[4]; 1697 return false; 1698 } 1699 1700 static InputKind ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args, 1701 DiagnosticsEngine &Diags, 1702 bool &IsHeaderFile) { 1703 Opts.ProgramAction = frontend::ParseSyntaxOnly; 1704 if (const Arg *A = Args.getLastArg(OPT_Action_Group)) { 1705 switch (A->getOption().getID()) { 1706 default: 1707 llvm_unreachable("Invalid option in group!"); 1708 case OPT_ast_list: 1709 Opts.ProgramAction = frontend::ASTDeclList; break; 1710 case OPT_ast_dump_all_EQ: 1711 case OPT_ast_dump_EQ: { 1712 unsigned Val = llvm::StringSwitch<unsigned>(A->getValue()) 1713 .CaseLower("default", ADOF_Default) 1714 .CaseLower("json", ADOF_JSON) 1715 .Default(std::numeric_limits<unsigned>::max()); 1716 1717 if (Val != std::numeric_limits<unsigned>::max()) 1718 Opts.ASTDumpFormat = static_cast<ASTDumpOutputFormat>(Val); 1719 else { 1720 Diags.Report(diag::err_drv_invalid_value) 1721 << A->getAsString(Args) << A->getValue(); 1722 Opts.ASTDumpFormat = ADOF_Default; 1723 } 1724 LLVM_FALLTHROUGH; 1725 } 1726 case OPT_ast_dump: 1727 case OPT_ast_dump_all: 1728 case OPT_ast_dump_lookups: 1729 Opts.ProgramAction = frontend::ASTDump; break; 1730 case OPT_ast_print: 1731 Opts.ProgramAction = frontend::ASTPrint; break; 1732 case OPT_ast_view: 1733 Opts.ProgramAction = frontend::ASTView; break; 1734 case OPT_compiler_options_dump: 1735 Opts.ProgramAction = frontend::DumpCompilerOptions; break; 1736 case OPT_dump_raw_tokens: 1737 Opts.ProgramAction = frontend::DumpRawTokens; break; 1738 case OPT_dump_tokens: 1739 Opts.ProgramAction = frontend::DumpTokens; break; 1740 case OPT_S: 1741 Opts.ProgramAction = frontend::EmitAssembly; break; 1742 case OPT_emit_llvm_bc: 1743 Opts.ProgramAction = frontend::EmitBC; break; 1744 case OPT_emit_html: 1745 Opts.ProgramAction = frontend::EmitHTML; break; 1746 case OPT_emit_llvm: 1747 Opts.ProgramAction = frontend::EmitLLVM; break; 1748 case OPT_emit_llvm_only: 1749 Opts.ProgramAction = frontend::EmitLLVMOnly; break; 1750 case OPT_emit_codegen_only: 1751 Opts.ProgramAction = frontend::EmitCodeGenOnly; break; 1752 case OPT_emit_obj: 1753 Opts.ProgramAction = frontend::EmitObj; break; 1754 case OPT_fixit_EQ: 1755 Opts.FixItSuffix = A->getValue(); 1756 LLVM_FALLTHROUGH; 1757 case OPT_fixit: 1758 Opts.ProgramAction = frontend::FixIt; break; 1759 case OPT_emit_module: 1760 Opts.ProgramAction = frontend::GenerateModule; break; 1761 case OPT_emit_module_interface: 1762 Opts.ProgramAction = frontend::GenerateModuleInterface; break; 1763 case OPT_emit_header_module: 1764 Opts.ProgramAction = frontend::GenerateHeaderModule; break; 1765 case OPT_emit_pch: 1766 Opts.ProgramAction = frontend::GeneratePCH; break; 1767 case OPT_emit_interface_stubs: { 1768 StringRef ArgStr = 1769 Args.hasArg(OPT_interface_stub_version_EQ) 1770 ? Args.getLastArgValue(OPT_interface_stub_version_EQ) 1771 : "experimental-ifs-v1"; 1772 if (ArgStr == "experimental-yaml-elf-v1" || 1773 ArgStr == "experimental-tapi-elf-v1") { 1774 std::string ErrorMessage = 1775 "Invalid interface stub format: " + ArgStr.str() + 1776 " is deprecated."; 1777 Diags.Report(diag::err_drv_invalid_value) 1778 << "Must specify a valid interface stub format type, ie: " 1779 "-interface-stub-version=experimental-ifs-v1" 1780 << ErrorMessage; 1781 } else if (ArgStr != "experimental-ifs-v1") { 1782 std::string ErrorMessage = 1783 "Invalid interface stub format: " + ArgStr.str() + "."; 1784 Diags.Report(diag::err_drv_invalid_value) 1785 << "Must specify a valid interface stub format type, ie: " 1786 "-interface-stub-version=experimental-ifs-v1" 1787 << ErrorMessage; 1788 } else { 1789 Opts.ProgramAction = frontend::GenerateInterfaceIfsExpV1; 1790 } 1791 break; 1792 } 1793 case OPT_init_only: 1794 Opts.ProgramAction = frontend::InitOnly; break; 1795 case OPT_fsyntax_only: 1796 Opts.ProgramAction = frontend::ParseSyntaxOnly; break; 1797 case OPT_module_file_info: 1798 Opts.ProgramAction = frontend::ModuleFileInfo; break; 1799 case OPT_verify_pch: 1800 Opts.ProgramAction = frontend::VerifyPCH; break; 1801 case OPT_print_preamble: 1802 Opts.ProgramAction = frontend::PrintPreamble; break; 1803 case OPT_E: 1804 Opts.ProgramAction = frontend::PrintPreprocessedInput; break; 1805 case OPT_templight_dump: 1806 Opts.ProgramAction = frontend::TemplightDump; break; 1807 case OPT_rewrite_macros: 1808 Opts.ProgramAction = frontend::RewriteMacros; break; 1809 case OPT_rewrite_objc: 1810 Opts.ProgramAction = frontend::RewriteObjC; break; 1811 case OPT_rewrite_test: 1812 Opts.ProgramAction = frontend::RewriteTest; break; 1813 case OPT_analyze: 1814 Opts.ProgramAction = frontend::RunAnalysis; break; 1815 case OPT_migrate: 1816 Opts.ProgramAction = frontend::MigrateSource; break; 1817 case OPT_Eonly: 1818 Opts.ProgramAction = frontend::RunPreprocessorOnly; break; 1819 case OPT_print_dependency_directives_minimized_source: 1820 Opts.ProgramAction = 1821 frontend::PrintDependencyDirectivesSourceMinimizerOutput; 1822 break; 1823 } 1824 } 1825 1826 if (const Arg* A = Args.getLastArg(OPT_plugin)) { 1827 Opts.Plugins.emplace_back(A->getValue(0)); 1828 Opts.ProgramAction = frontend::PluginAction; 1829 Opts.ActionName = A->getValue(); 1830 } 1831 Opts.AddPluginActions = Args.getAllArgValues(OPT_add_plugin); 1832 for (const auto *AA : Args.filtered(OPT_plugin_arg)) 1833 Opts.PluginArgs[AA->getValue(0)].emplace_back(AA->getValue(1)); 1834 1835 for (const std::string &Arg : 1836 Args.getAllArgValues(OPT_ftest_module_file_extension_EQ)) { 1837 std::string BlockName; 1838 unsigned MajorVersion; 1839 unsigned MinorVersion; 1840 bool Hashed; 1841 std::string UserInfo; 1842 if (parseTestModuleFileExtensionArg(Arg, BlockName, MajorVersion, 1843 MinorVersion, Hashed, UserInfo)) { 1844 Diags.Report(diag::err_test_module_file_extension_format) << Arg; 1845 1846 continue; 1847 } 1848 1849 // Add the testing module file extension. 1850 Opts.ModuleFileExtensions.push_back( 1851 std::make_shared<TestModuleFileExtension>( 1852 BlockName, MajorVersion, MinorVersion, Hashed, UserInfo)); 1853 } 1854 1855 if (const Arg *A = Args.getLastArg(OPT_code_completion_at)) { 1856 Opts.CodeCompletionAt = 1857 ParsedSourceLocation::FromString(A->getValue()); 1858 if (Opts.CodeCompletionAt.FileName.empty()) 1859 Diags.Report(diag::err_drv_invalid_value) 1860 << A->getAsString(Args) << A->getValue(); 1861 } 1862 Opts.DisableFree = Args.hasArg(OPT_disable_free); 1863 1864 Opts.OutputFile = Args.getLastArgValue(OPT_o); 1865 Opts.Plugins = Args.getAllArgValues(OPT_load); 1866 Opts.RelocatablePCH = Args.hasArg(OPT_relocatable_pch); 1867 Opts.ShowHelp = Args.hasArg(OPT_help); 1868 Opts.ShowStats = Args.hasArg(OPT_print_stats); 1869 Opts.ShowTimers = Args.hasArg(OPT_ftime_report); 1870 Opts.PrintSupportedCPUs = Args.hasArg(OPT_print_supported_cpus); 1871 Opts.TimeTrace = Args.hasArg(OPT_ftime_trace); 1872 Opts.TimeTraceGranularity = getLastArgIntValue( 1873 Args, OPT_ftime_trace_granularity_EQ, Opts.TimeTraceGranularity, Diags); 1874 Opts.ShowVersion = Args.hasArg(OPT_version); 1875 Opts.ASTMergeFiles = Args.getAllArgValues(OPT_ast_merge); 1876 Opts.LLVMArgs = Args.getAllArgValues(OPT_mllvm); 1877 Opts.FixWhatYouCan = Args.hasArg(OPT_fix_what_you_can); 1878 Opts.FixOnlyWarnings = Args.hasArg(OPT_fix_only_warnings); 1879 Opts.FixAndRecompile = Args.hasArg(OPT_fixit_recompile); 1880 Opts.FixToTemporaries = Args.hasArg(OPT_fixit_to_temp); 1881 Opts.ASTDumpDecls = Args.hasArg(OPT_ast_dump, OPT_ast_dump_EQ); 1882 Opts.ASTDumpAll = Args.hasArg(OPT_ast_dump_all, OPT_ast_dump_all_EQ); 1883 Opts.ASTDumpFilter = Args.getLastArgValue(OPT_ast_dump_filter); 1884 Opts.ASTDumpLookups = Args.hasArg(OPT_ast_dump_lookups); 1885 Opts.UseGlobalModuleIndex = !Args.hasArg(OPT_fno_modules_global_index); 1886 Opts.GenerateGlobalModuleIndex = Opts.UseGlobalModuleIndex; 1887 Opts.ModuleMapFiles = Args.getAllArgValues(OPT_fmodule_map_file); 1888 // Only the -fmodule-file=<file> form. 1889 for (const auto *A : Args.filtered(OPT_fmodule_file)) { 1890 StringRef Val = A->getValue(); 1891 if (Val.find('=') == StringRef::npos) 1892 Opts.ModuleFiles.push_back(Val); 1893 } 1894 Opts.ModulesEmbedFiles = Args.getAllArgValues(OPT_fmodules_embed_file_EQ); 1895 Opts.ModulesEmbedAllFiles = Args.hasArg(OPT_fmodules_embed_all_files); 1896 Opts.IncludeTimestamps = !Args.hasArg(OPT_fno_pch_timestamp); 1897 Opts.UseTemporary = !Args.hasArg(OPT_fno_temp_file); 1898 1899 Opts.CodeCompleteOpts.IncludeMacros 1900 = Args.hasArg(OPT_code_completion_macros); 1901 Opts.CodeCompleteOpts.IncludeCodePatterns 1902 = Args.hasArg(OPT_code_completion_patterns); 1903 Opts.CodeCompleteOpts.IncludeGlobals 1904 = !Args.hasArg(OPT_no_code_completion_globals); 1905 Opts.CodeCompleteOpts.IncludeNamespaceLevelDecls 1906 = !Args.hasArg(OPT_no_code_completion_ns_level_decls); 1907 Opts.CodeCompleteOpts.IncludeBriefComments 1908 = Args.hasArg(OPT_code_completion_brief_comments); 1909 Opts.CodeCompleteOpts.IncludeFixIts 1910 = Args.hasArg(OPT_code_completion_with_fixits); 1911 1912 Opts.OverrideRecordLayoutsFile 1913 = Args.getLastArgValue(OPT_foverride_record_layout_EQ); 1914 Opts.AuxTriple = Args.getLastArgValue(OPT_aux_triple); 1915 Opts.StatsFile = Args.getLastArgValue(OPT_stats_file); 1916 1917 if (const Arg *A = Args.getLastArg(OPT_arcmt_check, 1918 OPT_arcmt_modify, 1919 OPT_arcmt_migrate)) { 1920 switch (A->getOption().getID()) { 1921 default: 1922 llvm_unreachable("missed a case"); 1923 case OPT_arcmt_check: 1924 Opts.ARCMTAction = FrontendOptions::ARCMT_Check; 1925 break; 1926 case OPT_arcmt_modify: 1927 Opts.ARCMTAction = FrontendOptions::ARCMT_Modify; 1928 break; 1929 case OPT_arcmt_migrate: 1930 Opts.ARCMTAction = FrontendOptions::ARCMT_Migrate; 1931 break; 1932 } 1933 } 1934 Opts.MTMigrateDir = Args.getLastArgValue(OPT_mt_migrate_directory); 1935 Opts.ARCMTMigrateReportOut 1936 = Args.getLastArgValue(OPT_arcmt_migrate_report_output); 1937 Opts.ARCMTMigrateEmitARCErrors 1938 = Args.hasArg(OPT_arcmt_migrate_emit_arc_errors); 1939 1940 if (Args.hasArg(OPT_objcmt_migrate_literals)) 1941 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Literals; 1942 if (Args.hasArg(OPT_objcmt_migrate_subscripting)) 1943 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Subscripting; 1944 if (Args.hasArg(OPT_objcmt_migrate_property_dot_syntax)) 1945 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_PropertyDotSyntax; 1946 if (Args.hasArg(OPT_objcmt_migrate_property)) 1947 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Property; 1948 if (Args.hasArg(OPT_objcmt_migrate_readonly_property)) 1949 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_ReadonlyProperty; 1950 if (Args.hasArg(OPT_objcmt_migrate_readwrite_property)) 1951 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_ReadwriteProperty; 1952 if (Args.hasArg(OPT_objcmt_migrate_annotation)) 1953 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Annotation; 1954 if (Args.hasArg(OPT_objcmt_returns_innerpointer_property)) 1955 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_ReturnsInnerPointerProperty; 1956 if (Args.hasArg(OPT_objcmt_migrate_instancetype)) 1957 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Instancetype; 1958 if (Args.hasArg(OPT_objcmt_migrate_nsmacros)) 1959 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_NsMacros; 1960 if (Args.hasArg(OPT_objcmt_migrate_protocol_conformance)) 1961 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_ProtocolConformance; 1962 if (Args.hasArg(OPT_objcmt_atomic_property)) 1963 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_AtomicProperty; 1964 if (Args.hasArg(OPT_objcmt_ns_nonatomic_iosonly)) 1965 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty; 1966 if (Args.hasArg(OPT_objcmt_migrate_designated_init)) 1967 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_DesignatedInitializer; 1968 if (Args.hasArg(OPT_objcmt_migrate_all)) 1969 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_MigrateDecls; 1970 1971 Opts.ObjCMTWhiteListPath = Args.getLastArgValue(OPT_objcmt_whitelist_dir_path); 1972 1973 if (Opts.ARCMTAction != FrontendOptions::ARCMT_None && 1974 Opts.ObjCMTAction != FrontendOptions::ObjCMT_None) { 1975 Diags.Report(diag::err_drv_argument_not_allowed_with) 1976 << "ARC migration" << "ObjC migration"; 1977 } 1978 1979 InputKind DashX(Language::Unknown); 1980 if (const Arg *A = Args.getLastArg(OPT_x)) { 1981 StringRef XValue = A->getValue(); 1982 1983 // Parse suffixes: '<lang>(-header|[-module-map][-cpp-output])'. 1984 // FIXME: Supporting '<lang>-header-cpp-output' would be useful. 1985 bool Preprocessed = XValue.consume_back("-cpp-output"); 1986 bool ModuleMap = XValue.consume_back("-module-map"); 1987 IsHeaderFile = 1988 !Preprocessed && !ModuleMap && XValue.consume_back("-header"); 1989 1990 // Principal languages. 1991 DashX = llvm::StringSwitch<InputKind>(XValue) 1992 .Case("c", Language::C) 1993 .Case("cl", Language::OpenCL) 1994 .Case("cuda", Language::CUDA) 1995 .Case("hip", Language::HIP) 1996 .Case("c++", Language::CXX) 1997 .Case("objective-c", Language::ObjC) 1998 .Case("objective-c++", Language::ObjCXX) 1999 .Case("renderscript", Language::RenderScript) 2000 .Default(Language::Unknown); 2001 2002 // "objc[++]-cpp-output" is an acceptable synonym for 2003 // "objective-c[++]-cpp-output". 2004 if (DashX.isUnknown() && Preprocessed && !IsHeaderFile && !ModuleMap) 2005 DashX = llvm::StringSwitch<InputKind>(XValue) 2006 .Case("objc", Language::ObjC) 2007 .Case("objc++", Language::ObjCXX) 2008 .Default(Language::Unknown); 2009 2010 // Some special cases cannot be combined with suffixes. 2011 if (DashX.isUnknown() && !Preprocessed && !ModuleMap && !IsHeaderFile) 2012 DashX = llvm::StringSwitch<InputKind>(XValue) 2013 .Case("cpp-output", InputKind(Language::C).getPreprocessed()) 2014 .Case("assembler-with-cpp", Language::Asm) 2015 .Cases("ast", "pcm", 2016 InputKind(Language::Unknown, InputKind::Precompiled)) 2017 .Case("ir", Language::LLVM_IR) 2018 .Default(Language::Unknown); 2019 2020 if (DashX.isUnknown()) 2021 Diags.Report(diag::err_drv_invalid_value) 2022 << A->getAsString(Args) << A->getValue(); 2023 2024 if (Preprocessed) 2025 DashX = DashX.getPreprocessed(); 2026 if (ModuleMap) 2027 DashX = DashX.withFormat(InputKind::ModuleMap); 2028 } 2029 2030 // '-' is the default input if none is given. 2031 std::vector<std::string> Inputs = Args.getAllArgValues(OPT_INPUT); 2032 Opts.Inputs.clear(); 2033 if (Inputs.empty()) 2034 Inputs.push_back("-"); 2035 for (unsigned i = 0, e = Inputs.size(); i != e; ++i) { 2036 InputKind IK = DashX; 2037 if (IK.isUnknown()) { 2038 IK = FrontendOptions::getInputKindForExtension( 2039 StringRef(Inputs[i]).rsplit('.').second); 2040 // FIXME: Warn on this? 2041 if (IK.isUnknown()) 2042 IK = Language::C; 2043 // FIXME: Remove this hack. 2044 if (i == 0) 2045 DashX = IK; 2046 } 2047 2048 // The -emit-module action implicitly takes a module map. 2049 if (Opts.ProgramAction == frontend::GenerateModule && 2050 IK.getFormat() == InputKind::Source) 2051 IK = IK.withFormat(InputKind::ModuleMap); 2052 2053 Opts.Inputs.emplace_back(std::move(Inputs[i]), IK); 2054 } 2055 2056 return DashX; 2057 } 2058 2059 std::string CompilerInvocation::GetResourcesPath(const char *Argv0, 2060 void *MainAddr) { 2061 std::string ClangExecutable = 2062 llvm::sys::fs::getMainExecutable(Argv0, MainAddr); 2063 return Driver::GetResourcesPath(ClangExecutable, CLANG_RESOURCE_DIR); 2064 } 2065 2066 static void ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args, 2067 const std::string &WorkingDir) { 2068 Opts.Sysroot = Args.getLastArgValue(OPT_isysroot, "/"); 2069 Opts.Verbose = Args.hasArg(OPT_v); 2070 Opts.UseBuiltinIncludes = !Args.hasArg(OPT_nobuiltininc); 2071 Opts.UseStandardSystemIncludes = !Args.hasArg(OPT_nostdsysteminc); 2072 Opts.UseStandardCXXIncludes = !Args.hasArg(OPT_nostdincxx); 2073 if (const Arg *A = Args.getLastArg(OPT_stdlib_EQ)) 2074 Opts.UseLibcxx = (strcmp(A->getValue(), "libc++") == 0); 2075 Opts.ResourceDir = Args.getLastArgValue(OPT_resource_dir); 2076 2077 // Canonicalize -fmodules-cache-path before storing it. 2078 SmallString<128> P(Args.getLastArgValue(OPT_fmodules_cache_path)); 2079 if (!(P.empty() || llvm::sys::path::is_absolute(P))) { 2080 if (WorkingDir.empty()) 2081 llvm::sys::fs::make_absolute(P); 2082 else 2083 llvm::sys::fs::make_absolute(WorkingDir, P); 2084 } 2085 llvm::sys::path::remove_dots(P); 2086 Opts.ModuleCachePath = P.str(); 2087 2088 Opts.ModuleUserBuildPath = Args.getLastArgValue(OPT_fmodules_user_build_path); 2089 // Only the -fmodule-file=<name>=<file> form. 2090 for (const auto *A : Args.filtered(OPT_fmodule_file)) { 2091 StringRef Val = A->getValue(); 2092 if (Val.find('=') != StringRef::npos) 2093 Opts.PrebuiltModuleFiles.insert(Val.split('=')); 2094 } 2095 for (const auto *A : Args.filtered(OPT_fprebuilt_module_path)) 2096 Opts.AddPrebuiltModulePath(A->getValue()); 2097 Opts.DisableModuleHash = Args.hasArg(OPT_fdisable_module_hash); 2098 Opts.ModulesHashContent = Args.hasArg(OPT_fmodules_hash_content); 2099 Opts.ModulesStrictContextHash = Args.hasArg(OPT_fmodules_strict_context_hash); 2100 Opts.ModulesValidateDiagnosticOptions = 2101 !Args.hasArg(OPT_fmodules_disable_diagnostic_validation); 2102 Opts.ImplicitModuleMaps = Args.hasArg(OPT_fimplicit_module_maps); 2103 Opts.ModuleMapFileHomeIsCwd = Args.hasArg(OPT_fmodule_map_file_home_is_cwd); 2104 Opts.ModuleCachePruneInterval = 2105 getLastArgIntValue(Args, OPT_fmodules_prune_interval, 7 * 24 * 60 * 60); 2106 Opts.ModuleCachePruneAfter = 2107 getLastArgIntValue(Args, OPT_fmodules_prune_after, 31 * 24 * 60 * 60); 2108 Opts.ModulesValidateOncePerBuildSession = 2109 Args.hasArg(OPT_fmodules_validate_once_per_build_session); 2110 Opts.BuildSessionTimestamp = 2111 getLastArgUInt64Value(Args, OPT_fbuild_session_timestamp, 0); 2112 Opts.ModulesValidateSystemHeaders = 2113 Args.hasArg(OPT_fmodules_validate_system_headers); 2114 Opts.ValidateASTInputFilesContent = 2115 Args.hasArg(OPT_fvalidate_ast_input_files_content); 2116 if (const Arg *A = Args.getLastArg(OPT_fmodule_format_EQ)) 2117 Opts.ModuleFormat = A->getValue(); 2118 2119 for (const auto *A : Args.filtered(OPT_fmodules_ignore_macro)) { 2120 StringRef MacroDef = A->getValue(); 2121 Opts.ModulesIgnoreMacros.insert( 2122 llvm::CachedHashString(MacroDef.split('=').first)); 2123 } 2124 2125 // Add -I..., -F..., and -index-header-map options in order. 2126 bool IsIndexHeaderMap = false; 2127 bool IsSysrootSpecified = 2128 Args.hasArg(OPT__sysroot_EQ) || Args.hasArg(OPT_isysroot); 2129 for (const auto *A : Args.filtered(OPT_I, OPT_F, OPT_index_header_map)) { 2130 if (A->getOption().matches(OPT_index_header_map)) { 2131 // -index-header-map applies to the next -I or -F. 2132 IsIndexHeaderMap = true; 2133 continue; 2134 } 2135 2136 frontend::IncludeDirGroup Group = 2137 IsIndexHeaderMap ? frontend::IndexHeaderMap : frontend::Angled; 2138 2139 bool IsFramework = A->getOption().matches(OPT_F); 2140 std::string Path = A->getValue(); 2141 2142 if (IsSysrootSpecified && !IsFramework && A->getValue()[0] == '=') { 2143 SmallString<32> Buffer; 2144 llvm::sys::path::append(Buffer, Opts.Sysroot, 2145 llvm::StringRef(A->getValue()).substr(1)); 2146 Path = Buffer.str(); 2147 } 2148 2149 Opts.AddPath(Path, Group, IsFramework, 2150 /*IgnoreSysroot*/ true); 2151 IsIndexHeaderMap = false; 2152 } 2153 2154 // Add -iprefix/-iwithprefix/-iwithprefixbefore options. 2155 StringRef Prefix = ""; // FIXME: This isn't the correct default prefix. 2156 for (const auto *A : 2157 Args.filtered(OPT_iprefix, OPT_iwithprefix, OPT_iwithprefixbefore)) { 2158 if (A->getOption().matches(OPT_iprefix)) 2159 Prefix = A->getValue(); 2160 else if (A->getOption().matches(OPT_iwithprefix)) 2161 Opts.AddPath(Prefix.str() + A->getValue(), frontend::After, false, true); 2162 else 2163 Opts.AddPath(Prefix.str() + A->getValue(), frontend::Angled, false, true); 2164 } 2165 2166 for (const auto *A : Args.filtered(OPT_idirafter)) 2167 Opts.AddPath(A->getValue(), frontend::After, false, true); 2168 for (const auto *A : Args.filtered(OPT_iquote)) 2169 Opts.AddPath(A->getValue(), frontend::Quoted, false, true); 2170 for (const auto *A : Args.filtered(OPT_isystem, OPT_iwithsysroot)) 2171 Opts.AddPath(A->getValue(), frontend::System, false, 2172 !A->getOption().matches(OPT_iwithsysroot)); 2173 for (const auto *A : Args.filtered(OPT_iframework)) 2174 Opts.AddPath(A->getValue(), frontend::System, true, true); 2175 for (const auto *A : Args.filtered(OPT_iframeworkwithsysroot)) 2176 Opts.AddPath(A->getValue(), frontend::System, /*IsFramework=*/true, 2177 /*IgnoreSysRoot=*/false); 2178 2179 // Add the paths for the various language specific isystem flags. 2180 for (const auto *A : Args.filtered(OPT_c_isystem)) 2181 Opts.AddPath(A->getValue(), frontend::CSystem, false, true); 2182 for (const auto *A : Args.filtered(OPT_cxx_isystem)) 2183 Opts.AddPath(A->getValue(), frontend::CXXSystem, false, true); 2184 for (const auto *A : Args.filtered(OPT_objc_isystem)) 2185 Opts.AddPath(A->getValue(), frontend::ObjCSystem, false,true); 2186 for (const auto *A : Args.filtered(OPT_objcxx_isystem)) 2187 Opts.AddPath(A->getValue(), frontend::ObjCXXSystem, false, true); 2188 2189 // Add the internal paths from a driver that detects standard include paths. 2190 for (const auto *A : 2191 Args.filtered(OPT_internal_isystem, OPT_internal_externc_isystem)) { 2192 frontend::IncludeDirGroup Group = frontend::System; 2193 if (A->getOption().matches(OPT_internal_externc_isystem)) 2194 Group = frontend::ExternCSystem; 2195 Opts.AddPath(A->getValue(), Group, false, true); 2196 } 2197 2198 // Add the path prefixes which are implicitly treated as being system headers. 2199 for (const auto *A : 2200 Args.filtered(OPT_system_header_prefix, OPT_no_system_header_prefix)) 2201 Opts.AddSystemHeaderPrefix( 2202 A->getValue(), A->getOption().matches(OPT_system_header_prefix)); 2203 2204 for (const auto *A : Args.filtered(OPT_ivfsoverlay)) 2205 Opts.AddVFSOverlayFile(A->getValue()); 2206 } 2207 2208 void CompilerInvocation::setLangDefaults(LangOptions &Opts, InputKind IK, 2209 const llvm::Triple &T, 2210 PreprocessorOptions &PPOpts, 2211 LangStandard::Kind LangStd) { 2212 // Set some properties which depend solely on the input kind; it would be nice 2213 // to move these to the language standard, and have the driver resolve the 2214 // input kind + language standard. 2215 // 2216 // FIXME: Perhaps a better model would be for a single source file to have 2217 // multiple language standards (C / C++ std, ObjC std, OpenCL std, OpenMP std) 2218 // simultaneously active? 2219 if (IK.getLanguage() == Language::Asm) { 2220 Opts.AsmPreprocessor = 1; 2221 } else if (IK.isObjectiveC()) { 2222 Opts.ObjC = 1; 2223 } 2224 2225 if (LangStd == LangStandard::lang_unspecified) { 2226 // Based on the base language, pick one. 2227 switch (IK.getLanguage()) { 2228 case Language::Unknown: 2229 case Language::LLVM_IR: 2230 llvm_unreachable("Invalid input kind!"); 2231 case Language::OpenCL: 2232 LangStd = LangStandard::lang_opencl10; 2233 break; 2234 case Language::CUDA: 2235 LangStd = LangStandard::lang_cuda; 2236 break; 2237 case Language::Asm: 2238 case Language::C: 2239 #if defined(CLANG_DEFAULT_STD_C) 2240 LangStd = CLANG_DEFAULT_STD_C; 2241 #else 2242 // The PS4 uses C99 as the default C standard. 2243 if (T.isPS4()) 2244 LangStd = LangStandard::lang_gnu99; 2245 else 2246 LangStd = LangStandard::lang_gnu11; 2247 #endif 2248 break; 2249 case Language::ObjC: 2250 #if defined(CLANG_DEFAULT_STD_C) 2251 LangStd = CLANG_DEFAULT_STD_C; 2252 #else 2253 LangStd = LangStandard::lang_gnu11; 2254 #endif 2255 break; 2256 case Language::CXX: 2257 case Language::ObjCXX: 2258 #if defined(CLANG_DEFAULT_STD_CXX) 2259 LangStd = CLANG_DEFAULT_STD_CXX; 2260 #else 2261 LangStd = LangStandard::lang_gnucxx14; 2262 #endif 2263 break; 2264 case Language::RenderScript: 2265 LangStd = LangStandard::lang_c99; 2266 break; 2267 case Language::HIP: 2268 LangStd = LangStandard::lang_hip; 2269 break; 2270 } 2271 } 2272 2273 const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd); 2274 Opts.LineComment = Std.hasLineComments(); 2275 Opts.C99 = Std.isC99(); 2276 Opts.C11 = Std.isC11(); 2277 Opts.C17 = Std.isC17(); 2278 Opts.C2x = Std.isC2x(); 2279 Opts.CPlusPlus = Std.isCPlusPlus(); 2280 Opts.CPlusPlus11 = Std.isCPlusPlus11(); 2281 Opts.CPlusPlus14 = Std.isCPlusPlus14(); 2282 Opts.CPlusPlus17 = Std.isCPlusPlus17(); 2283 Opts.CPlusPlus2a = Std.isCPlusPlus2a(); 2284 Opts.Digraphs = Std.hasDigraphs(); 2285 Opts.GNUMode = Std.isGNUMode(); 2286 Opts.GNUInline = !Opts.C99 && !Opts.CPlusPlus; 2287 Opts.GNUCVersion = 0; 2288 Opts.HexFloats = Std.hasHexFloats(); 2289 Opts.ImplicitInt = Std.hasImplicitInt(); 2290 2291 // Set OpenCL Version. 2292 Opts.OpenCL = Std.isOpenCL(); 2293 if (LangStd == LangStandard::lang_opencl10) 2294 Opts.OpenCLVersion = 100; 2295 else if (LangStd == LangStandard::lang_opencl11) 2296 Opts.OpenCLVersion = 110; 2297 else if (LangStd == LangStandard::lang_opencl12) 2298 Opts.OpenCLVersion = 120; 2299 else if (LangStd == LangStandard::lang_opencl20) 2300 Opts.OpenCLVersion = 200; 2301 else if (LangStd == LangStandard::lang_openclcpp) 2302 Opts.OpenCLCPlusPlusVersion = 100; 2303 2304 // OpenCL has some additional defaults. 2305 if (Opts.OpenCL) { 2306 Opts.AltiVec = 0; 2307 Opts.ZVector = 0; 2308 Opts.setLaxVectorConversions(LangOptions::LaxVectorConversionKind::None); 2309 Opts.setDefaultFPContractMode(LangOptions::FPC_On); 2310 Opts.NativeHalfType = 1; 2311 Opts.NativeHalfArgsAndReturns = 1; 2312 Opts.OpenCLCPlusPlus = Opts.CPlusPlus; 2313 2314 // Include default header file for OpenCL. 2315 if (Opts.IncludeDefaultHeader) { 2316 if (Opts.DeclareOpenCLBuiltins) { 2317 // Only include base header file for builtin types and constants. 2318 PPOpts.Includes.push_back("opencl-c-base.h"); 2319 } else { 2320 PPOpts.Includes.push_back("opencl-c.h"); 2321 } 2322 } 2323 } 2324 2325 Opts.HIP = IK.getLanguage() == Language::HIP; 2326 Opts.CUDA = IK.getLanguage() == Language::CUDA || Opts.HIP; 2327 if (Opts.CUDA) 2328 // Set default FP_CONTRACT to FAST. 2329 Opts.setDefaultFPContractMode(LangOptions::FPC_Fast); 2330 2331 Opts.RenderScript = IK.getLanguage() == Language::RenderScript; 2332 if (Opts.RenderScript) { 2333 Opts.NativeHalfType = 1; 2334 Opts.NativeHalfArgsAndReturns = 1; 2335 } 2336 2337 // OpenCL and C++ both have bool, true, false keywords. 2338 Opts.Bool = Opts.OpenCL || Opts.CPlusPlus; 2339 2340 // OpenCL has half keyword 2341 Opts.Half = Opts.OpenCL; 2342 2343 // C++ has wchar_t keyword. 2344 Opts.WChar = Opts.CPlusPlus; 2345 2346 Opts.GNUKeywords = Opts.GNUMode; 2347 Opts.CXXOperatorNames = Opts.CPlusPlus; 2348 2349 Opts.AlignedAllocation = Opts.CPlusPlus17; 2350 2351 Opts.DollarIdents = !Opts.AsmPreprocessor; 2352 2353 // Enable [[]] attributes in C++11 and C2x by default. 2354 Opts.DoubleSquareBracketAttributes = Opts.CPlusPlus11 || Opts.C2x; 2355 } 2356 2357 /// Attempt to parse a visibility value out of the given argument. 2358 static Visibility parseVisibility(Arg *arg, ArgList &args, 2359 DiagnosticsEngine &diags) { 2360 StringRef value = arg->getValue(); 2361 if (value == "default") { 2362 return DefaultVisibility; 2363 } else if (value == "hidden" || value == "internal") { 2364 return HiddenVisibility; 2365 } else if (value == "protected") { 2366 // FIXME: diagnose if target does not support protected visibility 2367 return ProtectedVisibility; 2368 } 2369 2370 diags.Report(diag::err_drv_invalid_value) 2371 << arg->getAsString(args) << value; 2372 return DefaultVisibility; 2373 } 2374 2375 /// Check if input file kind and language standard are compatible. 2376 static bool IsInputCompatibleWithStandard(InputKind IK, 2377 const LangStandard &S) { 2378 switch (IK.getLanguage()) { 2379 case Language::Unknown: 2380 case Language::LLVM_IR: 2381 llvm_unreachable("should not parse language flags for this input"); 2382 2383 case Language::C: 2384 case Language::ObjC: 2385 case Language::RenderScript: 2386 return S.getLanguage() == Language::C; 2387 2388 case Language::OpenCL: 2389 return S.getLanguage() == Language::OpenCL; 2390 2391 case Language::CXX: 2392 case Language::ObjCXX: 2393 return S.getLanguage() == Language::CXX; 2394 2395 case Language::CUDA: 2396 // FIXME: What -std= values should be permitted for CUDA compilations? 2397 return S.getLanguage() == Language::CUDA || 2398 S.getLanguage() == Language::CXX; 2399 2400 case Language::HIP: 2401 return S.getLanguage() == Language::CXX || S.getLanguage() == Language::HIP; 2402 2403 case Language::Asm: 2404 // Accept (and ignore) all -std= values. 2405 // FIXME: The -std= value is not ignored; it affects the tokenization 2406 // and preprocessing rules if we're preprocessing this asm input. 2407 return true; 2408 } 2409 2410 llvm_unreachable("unexpected input language"); 2411 } 2412 2413 /// Get language name for given input kind. 2414 static const StringRef GetInputKindName(InputKind IK) { 2415 switch (IK.getLanguage()) { 2416 case Language::C: 2417 return "C"; 2418 case Language::ObjC: 2419 return "Objective-C"; 2420 case Language::CXX: 2421 return "C++"; 2422 case Language::ObjCXX: 2423 return "Objective-C++"; 2424 case Language::OpenCL: 2425 return "OpenCL"; 2426 case Language::CUDA: 2427 return "CUDA"; 2428 case Language::RenderScript: 2429 return "RenderScript"; 2430 case Language::HIP: 2431 return "HIP"; 2432 2433 case Language::Asm: 2434 return "Asm"; 2435 case Language::LLVM_IR: 2436 return "LLVM IR"; 2437 2438 case Language::Unknown: 2439 break; 2440 } 2441 llvm_unreachable("unknown input language"); 2442 } 2443 2444 static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK, 2445 const TargetOptions &TargetOpts, 2446 PreprocessorOptions &PPOpts, 2447 DiagnosticsEngine &Diags) { 2448 // FIXME: Cleanup per-file based stuff. 2449 LangStandard::Kind LangStd = LangStandard::lang_unspecified; 2450 if (const Arg *A = Args.getLastArg(OPT_std_EQ)) { 2451 LangStd = LangStandard::getLangKind(A->getValue()); 2452 if (LangStd == LangStandard::lang_unspecified) { 2453 Diags.Report(diag::err_drv_invalid_value) 2454 << A->getAsString(Args) << A->getValue(); 2455 // Report supported standards with short description. 2456 for (unsigned KindValue = 0; 2457 KindValue != LangStandard::lang_unspecified; 2458 ++KindValue) { 2459 const LangStandard &Std = LangStandard::getLangStandardForKind( 2460 static_cast<LangStandard::Kind>(KindValue)); 2461 if (IsInputCompatibleWithStandard(IK, Std)) { 2462 auto Diag = Diags.Report(diag::note_drv_use_standard); 2463 Diag << Std.getName() << Std.getDescription(); 2464 unsigned NumAliases = 0; 2465 #define LANGSTANDARD(id, name, lang, desc, features) 2466 #define LANGSTANDARD_ALIAS(id, alias) \ 2467 if (KindValue == LangStandard::lang_##id) ++NumAliases; 2468 #define LANGSTANDARD_ALIAS_DEPR(id, alias) 2469 #include "clang/Basic/LangStandards.def" 2470 Diag << NumAliases; 2471 #define LANGSTANDARD(id, name, lang, desc, features) 2472 #define LANGSTANDARD_ALIAS(id, alias) \ 2473 if (KindValue == LangStandard::lang_##id) Diag << alias; 2474 #define LANGSTANDARD_ALIAS_DEPR(id, alias) 2475 #include "clang/Basic/LangStandards.def" 2476 } 2477 } 2478 } else { 2479 // Valid standard, check to make sure language and standard are 2480 // compatible. 2481 const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd); 2482 if (!IsInputCompatibleWithStandard(IK, Std)) { 2483 Diags.Report(diag::err_drv_argument_not_allowed_with) 2484 << A->getAsString(Args) << GetInputKindName(IK); 2485 } 2486 } 2487 } 2488 2489 if (Args.hasArg(OPT_fno_dllexport_inlines)) 2490 Opts.DllExportInlines = false; 2491 2492 if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) { 2493 StringRef Name = A->getValue(); 2494 if (Name == "full" || Name == "branch") { 2495 Opts.CFProtectionBranch = 1; 2496 } 2497 } 2498 // -cl-std only applies for OpenCL language standards. 2499 // Override the -std option in this case. 2500 if (const Arg *A = Args.getLastArg(OPT_cl_std_EQ)) { 2501 LangStandard::Kind OpenCLLangStd 2502 = llvm::StringSwitch<LangStandard::Kind>(A->getValue()) 2503 .Cases("cl", "CL", LangStandard::lang_opencl10) 2504 .Cases("cl1.1", "CL1.1", LangStandard::lang_opencl11) 2505 .Cases("cl1.2", "CL1.2", LangStandard::lang_opencl12) 2506 .Cases("cl2.0", "CL2.0", LangStandard::lang_opencl20) 2507 .Cases("clc++", "CLC++", LangStandard::lang_openclcpp) 2508 .Default(LangStandard::lang_unspecified); 2509 2510 if (OpenCLLangStd == LangStandard::lang_unspecified) { 2511 Diags.Report(diag::err_drv_invalid_value) 2512 << A->getAsString(Args) << A->getValue(); 2513 } 2514 else 2515 LangStd = OpenCLLangStd; 2516 } 2517 2518 Opts.IncludeDefaultHeader = Args.hasArg(OPT_finclude_default_header); 2519 Opts.DeclareOpenCLBuiltins = Args.hasArg(OPT_fdeclare_opencl_builtins); 2520 2521 llvm::Triple T(TargetOpts.Triple); 2522 CompilerInvocation::setLangDefaults(Opts, IK, T, PPOpts, LangStd); 2523 2524 // -cl-strict-aliasing needs to emit diagnostic in the case where CL > 1.0. 2525 // This option should be deprecated for CL > 1.0 because 2526 // this option was added for compatibility with OpenCL 1.0. 2527 if (Args.getLastArg(OPT_cl_strict_aliasing) 2528 && Opts.OpenCLVersion > 100) { 2529 Diags.Report(diag::warn_option_invalid_ocl_version) 2530 << Opts.getOpenCLVersionTuple().getAsString() 2531 << Args.getLastArg(OPT_cl_strict_aliasing)->getAsString(Args); 2532 } 2533 2534 // We abuse '-f[no-]gnu-keywords' to force overriding all GNU-extension 2535 // keywords. This behavior is provided by GCC's poorly named '-fasm' flag, 2536 // while a subset (the non-C++ GNU keywords) is provided by GCC's 2537 // '-fgnu-keywords'. Clang conflates the two for simplicity under the single 2538 // name, as it doesn't seem a useful distinction. 2539 Opts.GNUKeywords = Args.hasFlag(OPT_fgnu_keywords, OPT_fno_gnu_keywords, 2540 Opts.GNUKeywords); 2541 2542 Opts.Digraphs = Args.hasFlag(OPT_fdigraphs, OPT_fno_digraphs, Opts.Digraphs); 2543 2544 if (Args.hasArg(OPT_fno_operator_names)) 2545 Opts.CXXOperatorNames = 0; 2546 2547 if (Args.hasArg(OPT_fcuda_is_device)) 2548 Opts.CUDAIsDevice = 1; 2549 2550 if (Args.hasArg(OPT_fcuda_allow_variadic_functions)) 2551 Opts.CUDAAllowVariadicFunctions = 1; 2552 2553 if (Args.hasArg(OPT_fno_cuda_host_device_constexpr)) 2554 Opts.CUDAHostDeviceConstexpr = 0; 2555 2556 if (Opts.CUDAIsDevice && Args.hasArg(OPT_fcuda_approx_transcendentals)) 2557 Opts.CUDADeviceApproxTranscendentals = 1; 2558 2559 Opts.GPURelocatableDeviceCode = Args.hasArg(OPT_fgpu_rdc); 2560 if (Args.hasArg(OPT_fgpu_allow_device_init)) { 2561 if (Opts.HIP) 2562 Opts.GPUAllowDeviceInit = 1; 2563 else 2564 Diags.Report(diag::warn_ignored_hip_only_option) 2565 << Args.getLastArg(OPT_fgpu_allow_device_init)->getAsString(Args); 2566 } 2567 Opts.HIPUseNewLaunchAPI = Args.hasArg(OPT_fhip_new_launch_api); 2568 if (Opts.HIP) 2569 Opts.GPUMaxThreadsPerBlock = getLastArgIntValue( 2570 Args, OPT_gpu_max_threads_per_block_EQ, Opts.GPUMaxThreadsPerBlock); 2571 else if (Args.hasArg(OPT_gpu_max_threads_per_block_EQ)) 2572 Diags.Report(diag::warn_ignored_hip_only_option) 2573 << Args.getLastArg(OPT_gpu_max_threads_per_block_EQ)->getAsString(Args); 2574 2575 if (Opts.ObjC) { 2576 if (Arg *arg = Args.getLastArg(OPT_fobjc_runtime_EQ)) { 2577 StringRef value = arg->getValue(); 2578 if (Opts.ObjCRuntime.tryParse(value)) 2579 Diags.Report(diag::err_drv_unknown_objc_runtime) << value; 2580 } 2581 2582 if (Args.hasArg(OPT_fobjc_gc_only)) 2583 Opts.setGC(LangOptions::GCOnly); 2584 else if (Args.hasArg(OPT_fobjc_gc)) 2585 Opts.setGC(LangOptions::HybridGC); 2586 else if (Args.hasArg(OPT_fobjc_arc)) { 2587 Opts.ObjCAutoRefCount = 1; 2588 if (!Opts.ObjCRuntime.allowsARC()) 2589 Diags.Report(diag::err_arc_unsupported_on_runtime); 2590 } 2591 2592 // ObjCWeakRuntime tracks whether the runtime supports __weak, not 2593 // whether the feature is actually enabled. This is predominantly 2594 // determined by -fobjc-runtime, but we allow it to be overridden 2595 // from the command line for testing purposes. 2596 if (Args.hasArg(OPT_fobjc_runtime_has_weak)) 2597 Opts.ObjCWeakRuntime = 1; 2598 else 2599 Opts.ObjCWeakRuntime = Opts.ObjCRuntime.allowsWeak(); 2600 2601 // ObjCWeak determines whether __weak is actually enabled. 2602 // Note that we allow -fno-objc-weak to disable this even in ARC mode. 2603 if (auto weakArg = Args.getLastArg(OPT_fobjc_weak, OPT_fno_objc_weak)) { 2604 if (!weakArg->getOption().matches(OPT_fobjc_weak)) { 2605 assert(!Opts.ObjCWeak); 2606 } else if (Opts.getGC() != LangOptions::NonGC) { 2607 Diags.Report(diag::err_objc_weak_with_gc); 2608 } else if (!Opts.ObjCWeakRuntime) { 2609 Diags.Report(diag::err_objc_weak_unsupported); 2610 } else { 2611 Opts.ObjCWeak = 1; 2612 } 2613 } else if (Opts.ObjCAutoRefCount) { 2614 Opts.ObjCWeak = Opts.ObjCWeakRuntime; 2615 } 2616 2617 if (Args.hasArg(OPT_fno_objc_infer_related_result_type)) 2618 Opts.ObjCInferRelatedResultType = 0; 2619 2620 if (Args.hasArg(OPT_fobjc_subscripting_legacy_runtime)) 2621 Opts.ObjCSubscriptingLegacyRuntime = 2622 (Opts.ObjCRuntime.getKind() == ObjCRuntime::FragileMacOSX); 2623 } 2624 2625 if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) { 2626 // Check that the version has 1 to 3 components and the minor and patch 2627 // versions fit in two decimal digits. 2628 VersionTuple GNUCVer; 2629 bool Invalid = GNUCVer.tryParse(A->getValue()); 2630 unsigned Major = GNUCVer.getMajor(); 2631 unsigned Minor = GNUCVer.getMinor().getValueOr(0); 2632 unsigned Patch = GNUCVer.getSubminor().getValueOr(0); 2633 if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) { 2634 Diags.Report(diag::err_drv_invalid_value) 2635 << A->getAsString(Args) << A->getValue(); 2636 } 2637 Opts.GNUCVersion = Major * 100 * 100 + Minor * 100 + Patch; 2638 } 2639 2640 if (Args.hasArg(OPT_fgnu89_inline)) { 2641 if (Opts.CPlusPlus) 2642 Diags.Report(diag::err_drv_argument_not_allowed_with) 2643 << "-fgnu89-inline" << GetInputKindName(IK); 2644 else 2645 Opts.GNUInline = 1; 2646 } 2647 2648 if (Args.hasArg(OPT_fapple_kext)) { 2649 if (!Opts.CPlusPlus) 2650 Diags.Report(diag::warn_c_kext); 2651 else 2652 Opts.AppleKext = 1; 2653 } 2654 2655 if (Args.hasArg(OPT_print_ivar_layout)) 2656 Opts.ObjCGCBitmapPrint = 1; 2657 2658 if (Args.hasArg(OPT_fno_constant_cfstrings)) 2659 Opts.NoConstantCFStrings = 1; 2660 if (const auto *A = Args.getLastArg(OPT_fcf_runtime_abi_EQ)) 2661 Opts.CFRuntime = 2662 llvm::StringSwitch<LangOptions::CoreFoundationABI>(A->getValue()) 2663 .Cases("unspecified", "standalone", "objc", 2664 LangOptions::CoreFoundationABI::ObjectiveC) 2665 .Cases("swift", "swift-5.0", 2666 LangOptions::CoreFoundationABI::Swift5_0) 2667 .Case("swift-4.2", LangOptions::CoreFoundationABI::Swift4_2) 2668 .Case("swift-4.1", LangOptions::CoreFoundationABI::Swift4_1) 2669 .Default(LangOptions::CoreFoundationABI::ObjectiveC); 2670 2671 if (Args.hasArg(OPT_fzvector)) 2672 Opts.ZVector = 1; 2673 2674 if (Args.hasArg(OPT_pthread)) 2675 Opts.POSIXThreads = 1; 2676 2677 // The value-visibility mode defaults to "default". 2678 if (Arg *visOpt = Args.getLastArg(OPT_fvisibility)) { 2679 Opts.setValueVisibilityMode(parseVisibility(visOpt, Args, Diags)); 2680 } else { 2681 Opts.setValueVisibilityMode(DefaultVisibility); 2682 } 2683 2684 // The type-visibility mode defaults to the value-visibility mode. 2685 if (Arg *typeVisOpt = Args.getLastArg(OPT_ftype_visibility)) { 2686 Opts.setTypeVisibilityMode(parseVisibility(typeVisOpt, Args, Diags)); 2687 } else { 2688 Opts.setTypeVisibilityMode(Opts.getValueVisibilityMode()); 2689 } 2690 2691 if (Args.hasArg(OPT_fvisibility_inlines_hidden)) 2692 Opts.InlineVisibilityHidden = 1; 2693 2694 if (Args.hasArg(OPT_fvisibility_global_new_delete_hidden)) 2695 Opts.GlobalAllocationFunctionVisibilityHidden = 1; 2696 2697 if (Args.hasArg(OPT_fapply_global_visibility_to_externs)) 2698 Opts.SetVisibilityForExternDecls = 1; 2699 2700 if (Args.hasArg(OPT_ftrapv)) { 2701 Opts.setSignedOverflowBehavior(LangOptions::SOB_Trapping); 2702 // Set the handler, if one is specified. 2703 Opts.OverflowHandler = 2704 Args.getLastArgValue(OPT_ftrapv_handler); 2705 } 2706 else if (Args.hasArg(OPT_fwrapv)) 2707 Opts.setSignedOverflowBehavior(LangOptions::SOB_Defined); 2708 2709 Opts.MSVCCompat = Args.hasArg(OPT_fms_compatibility); 2710 Opts.MicrosoftExt = Opts.MSVCCompat || Args.hasArg(OPT_fms_extensions); 2711 Opts.AsmBlocks = Args.hasArg(OPT_fasm_blocks) || Opts.MicrosoftExt; 2712 Opts.MSCompatibilityVersion = 0; 2713 if (const Arg *A = Args.getLastArg(OPT_fms_compatibility_version)) { 2714 VersionTuple VT; 2715 if (VT.tryParse(A->getValue())) 2716 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) 2717 << A->getValue(); 2718 Opts.MSCompatibilityVersion = VT.getMajor() * 10000000 + 2719 VT.getMinor().getValueOr(0) * 100000 + 2720 VT.getSubminor().getValueOr(0); 2721 } 2722 2723 // Mimicking gcc's behavior, trigraphs are only enabled if -trigraphs 2724 // is specified, or -std is set to a conforming mode. 2725 // Trigraphs are disabled by default in c++1z onwards. 2726 Opts.Trigraphs = !Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus17; 2727 Opts.Trigraphs = 2728 Args.hasFlag(OPT_ftrigraphs, OPT_fno_trigraphs, Opts.Trigraphs); 2729 2730 Opts.DollarIdents = Args.hasFlag(OPT_fdollars_in_identifiers, 2731 OPT_fno_dollars_in_identifiers, 2732 Opts.DollarIdents); 2733 Opts.PascalStrings = Args.hasArg(OPT_fpascal_strings); 2734 Opts.setVtorDispMode( 2735 MSVtorDispMode(getLastArgIntValue(Args, OPT_vtordisp_mode_EQ, 1, Diags))); 2736 Opts.Borland = Args.hasArg(OPT_fborland_extensions); 2737 Opts.WritableStrings = Args.hasArg(OPT_fwritable_strings); 2738 Opts.ConstStrings = Args.hasFlag(OPT_fconst_strings, OPT_fno_const_strings, 2739 Opts.ConstStrings); 2740 if (Arg *A = Args.getLastArg(OPT_flax_vector_conversions_EQ)) { 2741 using LaxKind = LangOptions::LaxVectorConversionKind; 2742 if (auto Kind = llvm::StringSwitch<Optional<LaxKind>>(A->getValue()) 2743 .Case("none", LaxKind::None) 2744 .Case("integer", LaxKind::Integer) 2745 .Case("all", LaxKind::All) 2746 .Default(llvm::None)) 2747 Opts.setLaxVectorConversions(*Kind); 2748 else 2749 Diags.Report(diag::err_drv_invalid_value) 2750 << A->getAsString(Args) << A->getValue(); 2751 } 2752 if (Args.hasArg(OPT_fno_threadsafe_statics)) 2753 Opts.ThreadsafeStatics = 0; 2754 Opts.Exceptions = Args.hasArg(OPT_fexceptions); 2755 Opts.ObjCExceptions = Args.hasArg(OPT_fobjc_exceptions); 2756 Opts.CXXExceptions = Args.hasArg(OPT_fcxx_exceptions); 2757 2758 // -ffixed-point 2759 Opts.FixedPoint = 2760 Args.hasFlag(OPT_ffixed_point, OPT_fno_fixed_point, /*Default=*/false) && 2761 !Opts.CPlusPlus; 2762 Opts.PaddingOnUnsignedFixedPoint = 2763 Args.hasFlag(OPT_fpadding_on_unsigned_fixed_point, 2764 OPT_fno_padding_on_unsigned_fixed_point, 2765 /*Default=*/false) && 2766 Opts.FixedPoint; 2767 2768 // Handle exception personalities 2769 Arg *A = Args.getLastArg( 2770 options::OPT_fsjlj_exceptions, options::OPT_fseh_exceptions, 2771 options::OPT_fdwarf_exceptions, options::OPT_fwasm_exceptions); 2772 if (A) { 2773 const Option &Opt = A->getOption(); 2774 llvm::Triple T(TargetOpts.Triple); 2775 if (T.isWindowsMSVCEnvironment()) 2776 Diags.Report(diag::err_fe_invalid_exception_model) 2777 << Opt.getName() << T.str(); 2778 2779 Opts.SjLjExceptions = Opt.matches(options::OPT_fsjlj_exceptions); 2780 Opts.SEHExceptions = Opt.matches(options::OPT_fseh_exceptions); 2781 Opts.DWARFExceptions = Opt.matches(options::OPT_fdwarf_exceptions); 2782 Opts.WasmExceptions = Opt.matches(options::OPT_fwasm_exceptions); 2783 } 2784 2785 Opts.ExternCNoUnwind = Args.hasArg(OPT_fexternc_nounwind); 2786 Opts.TraditionalCPP = Args.hasArg(OPT_traditional_cpp); 2787 2788 Opts.RTTI = Opts.CPlusPlus && !Args.hasArg(OPT_fno_rtti); 2789 Opts.RTTIData = Opts.RTTI && !Args.hasArg(OPT_fno_rtti_data); 2790 Opts.Blocks = Args.hasArg(OPT_fblocks) || (Opts.OpenCL 2791 && Opts.OpenCLVersion == 200); 2792 Opts.BlocksRuntimeOptional = Args.hasArg(OPT_fblocks_runtime_optional); 2793 Opts.Coroutines = Opts.CPlusPlus2a || Args.hasArg(OPT_fcoroutines_ts); 2794 2795 Opts.ConvergentFunctions = Opts.OpenCL || (Opts.CUDA && Opts.CUDAIsDevice) || 2796 Args.hasArg(OPT_fconvergent_functions); 2797 2798 Opts.DoubleSquareBracketAttributes = 2799 Args.hasFlag(OPT_fdouble_square_bracket_attributes, 2800 OPT_fno_double_square_bracket_attributes, 2801 Opts.DoubleSquareBracketAttributes); 2802 2803 Opts.CPlusPlusModules = Opts.CPlusPlus2a; 2804 Opts.ModulesTS = Args.hasArg(OPT_fmodules_ts); 2805 Opts.Modules = 2806 Args.hasArg(OPT_fmodules) || Opts.ModulesTS || Opts.CPlusPlusModules; 2807 Opts.ModulesStrictDeclUse = Args.hasArg(OPT_fmodules_strict_decluse); 2808 Opts.ModulesDeclUse = 2809 Args.hasArg(OPT_fmodules_decluse) || Opts.ModulesStrictDeclUse; 2810 // FIXME: We only need this in C++ modules / Modules TS if we might textually 2811 // enter a different module (eg, when building a header unit). 2812 Opts.ModulesLocalVisibility = 2813 Args.hasArg(OPT_fmodules_local_submodule_visibility) || Opts.ModulesTS || 2814 Opts.CPlusPlusModules; 2815 Opts.ModulesCodegen = Args.hasArg(OPT_fmodules_codegen); 2816 Opts.ModulesDebugInfo = Args.hasArg(OPT_fmodules_debuginfo); 2817 Opts.ModulesSearchAll = Opts.Modules && 2818 !Args.hasArg(OPT_fno_modules_search_all) && 2819 Args.hasArg(OPT_fmodules_search_all); 2820 Opts.ModulesErrorRecovery = !Args.hasArg(OPT_fno_modules_error_recovery); 2821 Opts.ImplicitModules = !Args.hasArg(OPT_fno_implicit_modules); 2822 Opts.CharIsSigned = Opts.OpenCL || !Args.hasArg(OPT_fno_signed_char); 2823 Opts.WChar = Opts.CPlusPlus && !Args.hasArg(OPT_fno_wchar); 2824 Opts.Char8 = Args.hasFlag(OPT_fchar8__t, OPT_fno_char8__t, Opts.CPlusPlus2a); 2825 if (const Arg *A = Args.getLastArg(OPT_fwchar_type_EQ)) { 2826 Opts.WCharSize = llvm::StringSwitch<unsigned>(A->getValue()) 2827 .Case("char", 1) 2828 .Case("short", 2) 2829 .Case("int", 4) 2830 .Default(0); 2831 if (Opts.WCharSize == 0) 2832 Diags.Report(diag::err_fe_invalid_wchar_type) << A->getValue(); 2833 } 2834 Opts.WCharIsSigned = Args.hasFlag(OPT_fsigned_wchar, OPT_fno_signed_wchar, true); 2835 Opts.ShortEnums = Args.hasArg(OPT_fshort_enums); 2836 Opts.Freestanding = Args.hasArg(OPT_ffreestanding); 2837 Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding; 2838 if (!Opts.NoBuiltin) 2839 getAllNoBuiltinFuncValues(Args, Opts.NoBuiltinFuncs); 2840 Opts.NoMathBuiltin = Args.hasArg(OPT_fno_math_builtin); 2841 Opts.RelaxedTemplateTemplateArgs = 2842 Args.hasArg(OPT_frelaxed_template_template_args); 2843 Opts.SizedDeallocation = Args.hasArg(OPT_fsized_deallocation); 2844 Opts.AlignedAllocation = 2845 Args.hasFlag(OPT_faligned_allocation, OPT_fno_aligned_allocation, 2846 Opts.AlignedAllocation); 2847 Opts.AlignedAllocationUnavailable = 2848 Opts.AlignedAllocation && Args.hasArg(OPT_aligned_alloc_unavailable); 2849 Opts.NewAlignOverride = 2850 getLastArgIntValue(Args, OPT_fnew_alignment_EQ, 0, Diags); 2851 if (Opts.NewAlignOverride && !llvm::isPowerOf2_32(Opts.NewAlignOverride)) { 2852 Arg *A = Args.getLastArg(OPT_fnew_alignment_EQ); 2853 Diags.Report(diag::err_fe_invalid_alignment) << A->getAsString(Args) 2854 << A->getValue(); 2855 Opts.NewAlignOverride = 0; 2856 } 2857 Opts.ConceptSatisfactionCaching = 2858 !Args.hasArg(OPT_fno_concept_satisfaction_caching); 2859 if (Args.hasArg(OPT_fconcepts_ts)) 2860 Diags.Report(diag::warn_fe_concepts_ts_flag); 2861 Opts.HeinousExtensions = Args.hasArg(OPT_fheinous_gnu_extensions); 2862 Opts.AccessControl = !Args.hasArg(OPT_fno_access_control); 2863 Opts.ElideConstructors = !Args.hasArg(OPT_fno_elide_constructors); 2864 Opts.MathErrno = !Opts.OpenCL && Args.hasArg(OPT_fmath_errno); 2865 Opts.InstantiationDepth = 2866 getLastArgIntValue(Args, OPT_ftemplate_depth, 1024, Diags); 2867 Opts.ArrowDepth = 2868 getLastArgIntValue(Args, OPT_foperator_arrow_depth, 256, Diags); 2869 Opts.ConstexprCallDepth = 2870 getLastArgIntValue(Args, OPT_fconstexpr_depth, 512, Diags); 2871 Opts.ConstexprStepLimit = 2872 getLastArgIntValue(Args, OPT_fconstexpr_steps, 1048576, Diags); 2873 Opts.EnableNewConstInterp = 2874 Args.hasArg(OPT_fexperimental_new_constant_interpreter); 2875 Opts.BracketDepth = getLastArgIntValue(Args, OPT_fbracket_depth, 256, Diags); 2876 Opts.DelayedTemplateParsing = Args.hasArg(OPT_fdelayed_template_parsing); 2877 Opts.NumLargeByValueCopy = 2878 getLastArgIntValue(Args, OPT_Wlarge_by_value_copy_EQ, 0, Diags); 2879 Opts.MSBitfields = Args.hasArg(OPT_mms_bitfields); 2880 Opts.ObjCConstantStringClass = 2881 Args.getLastArgValue(OPT_fconstant_string_class); 2882 Opts.ObjCDefaultSynthProperties = 2883 !Args.hasArg(OPT_disable_objc_default_synthesize_properties); 2884 Opts.EncodeExtendedBlockSig = 2885 Args.hasArg(OPT_fencode_extended_block_signature); 2886 Opts.EmitAllDecls = Args.hasArg(OPT_femit_all_decls); 2887 Opts.PackStruct = getLastArgIntValue(Args, OPT_fpack_struct_EQ, 0, Diags); 2888 Opts.MaxTypeAlign = getLastArgIntValue(Args, OPT_fmax_type_align_EQ, 0, Diags); 2889 Opts.AlignDouble = Args.hasArg(OPT_malign_double); 2890 Opts.LongDoubleSize = Args.hasArg(OPT_mlong_double_128) 2891 ? 128 2892 : Args.hasArg(OPT_mlong_double_64) ? 64 : 0; 2893 Opts.PPCIEEELongDouble = Args.hasArg(OPT_mabi_EQ_ieeelongdouble); 2894 Opts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags); 2895 Opts.ROPI = Args.hasArg(OPT_fropi); 2896 Opts.RWPI = Args.hasArg(OPT_frwpi); 2897 Opts.PIE = Args.hasArg(OPT_pic_is_pie); 2898 Opts.Static = Args.hasArg(OPT_static_define); 2899 Opts.DumpRecordLayoutsSimple = Args.hasArg(OPT_fdump_record_layouts_simple); 2900 Opts.DumpRecordLayouts = Opts.DumpRecordLayoutsSimple 2901 || Args.hasArg(OPT_fdump_record_layouts); 2902 Opts.DumpVTableLayouts = Args.hasArg(OPT_fdump_vtable_layouts); 2903 Opts.SpellChecking = !Args.hasArg(OPT_fno_spell_checking); 2904 Opts.NoBitFieldTypeAlign = Args.hasArg(OPT_fno_bitfield_type_align); 2905 Opts.SinglePrecisionConstants = Args.hasArg(OPT_cl_single_precision_constant); 2906 Opts.FastRelaxedMath = Args.hasArg(OPT_cl_fast_relaxed_math); 2907 Opts.HexagonQdsp6Compat = Args.hasArg(OPT_mqdsp6_compat); 2908 Opts.FakeAddressSpaceMap = Args.hasArg(OPT_ffake_address_space_map); 2909 Opts.ParseUnknownAnytype = Args.hasArg(OPT_funknown_anytype); 2910 Opts.DebuggerSupport = Args.hasArg(OPT_fdebugger_support); 2911 Opts.DebuggerCastResultToId = Args.hasArg(OPT_fdebugger_cast_result_to_id); 2912 Opts.DebuggerObjCLiteral = Args.hasArg(OPT_fdebugger_objc_literal); 2913 Opts.ApplePragmaPack = Args.hasArg(OPT_fapple_pragma_pack); 2914 Opts.ModuleName = Args.getLastArgValue(OPT_fmodule_name_EQ); 2915 Opts.CurrentModule = Opts.ModuleName; 2916 Opts.AppExt = Args.hasArg(OPT_fapplication_extension); 2917 Opts.ModuleFeatures = Args.getAllArgValues(OPT_fmodule_feature); 2918 llvm::sort(Opts.ModuleFeatures); 2919 Opts.NativeHalfType |= Args.hasArg(OPT_fnative_half_type); 2920 Opts.NativeHalfArgsAndReturns |= Args.hasArg(OPT_fnative_half_arguments_and_returns); 2921 // Enable HalfArgsAndReturns if present in Args or if NativeHalfArgsAndReturns 2922 // is enabled. 2923 Opts.HalfArgsAndReturns = Args.hasArg(OPT_fallow_half_arguments_and_returns) 2924 | Opts.NativeHalfArgsAndReturns; 2925 Opts.GNUAsm = !Args.hasArg(OPT_fno_gnu_inline_asm); 2926 Opts.Cmse = Args.hasArg(OPT_mcmse); // Armv8-M Security Extensions 2927 2928 // __declspec is enabled by default for the PS4 by the driver, and also 2929 // enabled for Microsoft Extensions or Borland Extensions, here. 2930 // 2931 // FIXME: __declspec is also currently enabled for CUDA, but isn't really a 2932 // CUDA extension. However, it is required for supporting 2933 // __clang_cuda_builtin_vars.h, which uses __declspec(property). Once that has 2934 // been rewritten in terms of something more generic, remove the Opts.CUDA 2935 // term here. 2936 Opts.DeclSpecKeyword = 2937 Args.hasFlag(OPT_fdeclspec, OPT_fno_declspec, 2938 (Opts.MicrosoftExt || Opts.Borland || Opts.CUDA)); 2939 2940 if (Arg *A = Args.getLastArg(OPT_faddress_space_map_mangling_EQ)) { 2941 switch (llvm::StringSwitch<unsigned>(A->getValue()) 2942 .Case("target", LangOptions::ASMM_Target) 2943 .Case("no", LangOptions::ASMM_Off) 2944 .Case("yes", LangOptions::ASMM_On) 2945 .Default(255)) { 2946 default: 2947 Diags.Report(diag::err_drv_invalid_value) 2948 << "-faddress-space-map-mangling=" << A->getValue(); 2949 break; 2950 case LangOptions::ASMM_Target: 2951 Opts.setAddressSpaceMapMangling(LangOptions::ASMM_Target); 2952 break; 2953 case LangOptions::ASMM_On: 2954 Opts.setAddressSpaceMapMangling(LangOptions::ASMM_On); 2955 break; 2956 case LangOptions::ASMM_Off: 2957 Opts.setAddressSpaceMapMangling(LangOptions::ASMM_Off); 2958 break; 2959 } 2960 } 2961 2962 if (Arg *A = Args.getLastArg(OPT_fms_memptr_rep_EQ)) { 2963 LangOptions::PragmaMSPointersToMembersKind InheritanceModel = 2964 llvm::StringSwitch<LangOptions::PragmaMSPointersToMembersKind>( 2965 A->getValue()) 2966 .Case("single", 2967 LangOptions::PPTMK_FullGeneralitySingleInheritance) 2968 .Case("multiple", 2969 LangOptions::PPTMK_FullGeneralityMultipleInheritance) 2970 .Case("virtual", 2971 LangOptions::PPTMK_FullGeneralityVirtualInheritance) 2972 .Default(LangOptions::PPTMK_BestCase); 2973 if (InheritanceModel == LangOptions::PPTMK_BestCase) 2974 Diags.Report(diag::err_drv_invalid_value) 2975 << "-fms-memptr-rep=" << A->getValue(); 2976 2977 Opts.setMSPointerToMemberRepresentationMethod(InheritanceModel); 2978 } 2979 2980 // Check for MS default calling conventions being specified. 2981 if (Arg *A = Args.getLastArg(OPT_fdefault_calling_conv_EQ)) { 2982 LangOptions::DefaultCallingConvention DefaultCC = 2983 llvm::StringSwitch<LangOptions::DefaultCallingConvention>(A->getValue()) 2984 .Case("cdecl", LangOptions::DCC_CDecl) 2985 .Case("fastcall", LangOptions::DCC_FastCall) 2986 .Case("stdcall", LangOptions::DCC_StdCall) 2987 .Case("vectorcall", LangOptions::DCC_VectorCall) 2988 .Case("regcall", LangOptions::DCC_RegCall) 2989 .Default(LangOptions::DCC_None); 2990 if (DefaultCC == LangOptions::DCC_None) 2991 Diags.Report(diag::err_drv_invalid_value) 2992 << "-fdefault-calling-conv=" << A->getValue(); 2993 2994 llvm::Triple T(TargetOpts.Triple); 2995 llvm::Triple::ArchType Arch = T.getArch(); 2996 bool emitError = (DefaultCC == LangOptions::DCC_FastCall || 2997 DefaultCC == LangOptions::DCC_StdCall) && 2998 Arch != llvm::Triple::x86; 2999 emitError |= (DefaultCC == LangOptions::DCC_VectorCall || 3000 DefaultCC == LangOptions::DCC_RegCall) && 3001 !T.isX86(); 3002 if (emitError) 3003 Diags.Report(diag::err_drv_argument_not_allowed_with) 3004 << A->getSpelling() << T.getTriple(); 3005 else 3006 Opts.setDefaultCallingConv(DefaultCC); 3007 } 3008 3009 // -mrtd option 3010 if (Arg *A = Args.getLastArg(OPT_mrtd)) { 3011 if (Opts.getDefaultCallingConv() != LangOptions::DCC_None) 3012 Diags.Report(diag::err_drv_argument_not_allowed_with) 3013 << A->getSpelling() << "-fdefault-calling-conv"; 3014 else { 3015 llvm::Triple T(TargetOpts.Triple); 3016 if (T.getArch() != llvm::Triple::x86) 3017 Diags.Report(diag::err_drv_argument_not_allowed_with) 3018 << A->getSpelling() << T.getTriple(); 3019 else 3020 Opts.setDefaultCallingConv(LangOptions::DCC_StdCall); 3021 } 3022 } 3023 3024 // Check if -fopenmp is specified and set default version to 4.5. 3025 Opts.OpenMP = Args.hasArg(options::OPT_fopenmp) ? 45 : 0; 3026 // Check if -fopenmp-simd is specified. 3027 bool IsSimdSpecified = 3028 Args.hasFlag(options::OPT_fopenmp_simd, options::OPT_fno_openmp_simd, 3029 /*Default=*/false); 3030 Opts.OpenMPSimd = !Opts.OpenMP && IsSimdSpecified; 3031 Opts.OpenMPUseTLS = 3032 Opts.OpenMP && !Args.hasArg(options::OPT_fnoopenmp_use_tls); 3033 Opts.OpenMPIsDevice = 3034 Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_is_device); 3035 Opts.OpenMPIRBuilder = 3036 Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_enable_irbuilder); 3037 bool IsTargetSpecified = 3038 Opts.OpenMPIsDevice || Args.hasArg(options::OPT_fopenmp_targets_EQ); 3039 3040 if (Opts.OpenMP || Opts.OpenMPSimd) { 3041 if (int Version = getLastArgIntValue( 3042 Args, OPT_fopenmp_version_EQ, 3043 (IsSimdSpecified || IsTargetSpecified) ? 45 : Opts.OpenMP, Diags)) 3044 Opts.OpenMP = Version; 3045 else if (IsSimdSpecified || IsTargetSpecified) 3046 Opts.OpenMP = 45; 3047 // Provide diagnostic when a given target is not expected to be an OpenMP 3048 // device or host. 3049 if (!Opts.OpenMPIsDevice) { 3050 switch (T.getArch()) { 3051 default: 3052 break; 3053 // Add unsupported host targets here: 3054 case llvm::Triple::nvptx: 3055 case llvm::Triple::nvptx64: 3056 Diags.Report(diag::err_drv_omp_host_target_not_supported) 3057 << TargetOpts.Triple; 3058 break; 3059 } 3060 } 3061 } 3062 3063 // Set the flag to prevent the implementation from emitting device exception 3064 // handling code for those requiring so. 3065 if ((Opts.OpenMPIsDevice && T.isNVPTX()) || Opts.OpenCLCPlusPlus) { 3066 Opts.Exceptions = 0; 3067 Opts.CXXExceptions = 0; 3068 } 3069 if (Opts.OpenMPIsDevice && T.isNVPTX()) { 3070 Opts.OpenMPCUDANumSMs = 3071 getLastArgIntValue(Args, options::OPT_fopenmp_cuda_number_of_sm_EQ, 3072 Opts.OpenMPCUDANumSMs, Diags); 3073 Opts.OpenMPCUDABlocksPerSM = 3074 getLastArgIntValue(Args, options::OPT_fopenmp_cuda_blocks_per_sm_EQ, 3075 Opts.OpenMPCUDABlocksPerSM, Diags); 3076 Opts.OpenMPCUDAReductionBufNum = getLastArgIntValue( 3077 Args, options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ, 3078 Opts.OpenMPCUDAReductionBufNum, Diags); 3079 } 3080 3081 // Prevent auto-widening the representation of loop counters during an 3082 // OpenMP collapse clause. 3083 Opts.OpenMPOptimisticCollapse = 3084 Args.hasArg(options::OPT_fopenmp_optimistic_collapse) ? 1 : 0; 3085 3086 // Get the OpenMP target triples if any. 3087 if (Arg *A = Args.getLastArg(options::OPT_fopenmp_targets_EQ)) { 3088 3089 for (unsigned i = 0; i < A->getNumValues(); ++i) { 3090 llvm::Triple TT(A->getValue(i)); 3091 3092 if (TT.getArch() == llvm::Triple::UnknownArch || 3093 !(TT.getArch() == llvm::Triple::aarch64 || 3094 TT.getArch() == llvm::Triple::ppc || 3095 TT.getArch() == llvm::Triple::ppc64 || 3096 TT.getArch() == llvm::Triple::ppc64le || 3097 TT.getArch() == llvm::Triple::nvptx || 3098 TT.getArch() == llvm::Triple::nvptx64 || 3099 TT.getArch() == llvm::Triple::x86 || 3100 TT.getArch() == llvm::Triple::x86_64)) 3101 Diags.Report(diag::err_drv_invalid_omp_target) << A->getValue(i); 3102 else 3103 Opts.OMPTargetTriples.push_back(TT); 3104 } 3105 } 3106 3107 // Get OpenMP host file path if any and report if a non existent file is 3108 // found 3109 if (Arg *A = Args.getLastArg(options::OPT_fopenmp_host_ir_file_path)) { 3110 Opts.OMPHostIRFile = A->getValue(); 3111 if (!llvm::sys::fs::exists(Opts.OMPHostIRFile)) 3112 Diags.Report(diag::err_drv_omp_host_ir_file_not_found) 3113 << Opts.OMPHostIRFile; 3114 } 3115 3116 Opts.SYCLIsDevice = Args.hasArg(options::OPT_fsycl_is_device); 3117 3118 // Set CUDA mode for OpenMP target NVPTX if specified in options 3119 Opts.OpenMPCUDAMode = Opts.OpenMPIsDevice && T.isNVPTX() && 3120 Args.hasArg(options::OPT_fopenmp_cuda_mode); 3121 3122 // Set CUDA mode for OpenMP target NVPTX if specified in options 3123 Opts.OpenMPCUDAForceFullRuntime = 3124 Opts.OpenMPIsDevice && T.isNVPTX() && 3125 Args.hasArg(options::OPT_fopenmp_cuda_force_full_runtime); 3126 3127 // Record whether the __DEPRECATED define was requested. 3128 Opts.Deprecated = Args.hasFlag(OPT_fdeprecated_macro, 3129 OPT_fno_deprecated_macro, 3130 Opts.Deprecated); 3131 3132 // FIXME: Eliminate this dependency. 3133 unsigned Opt = getOptimizationLevel(Args, IK, Diags), 3134 OptSize = getOptimizationLevelSize(Args); 3135 Opts.Optimize = Opt != 0; 3136 Opts.OptimizeSize = OptSize != 0; 3137 3138 // This is the __NO_INLINE__ define, which just depends on things like the 3139 // optimization level and -fno-inline, not actually whether the backend has 3140 // inlining enabled. 3141 Opts.NoInlineDefine = !Opts.Optimize; 3142 if (Arg *InlineArg = Args.getLastArg( 3143 options::OPT_finline_functions, options::OPT_finline_hint_functions, 3144 options::OPT_fno_inline_functions, options::OPT_fno_inline)) 3145 if (InlineArg->getOption().matches(options::OPT_fno_inline)) 3146 Opts.NoInlineDefine = true; 3147 3148 Opts.FastMath = Args.hasArg(OPT_ffast_math) || 3149 Args.hasArg(OPT_cl_fast_relaxed_math); 3150 Opts.FiniteMathOnly = Args.hasArg(OPT_ffinite_math_only) || 3151 Args.hasArg(OPT_cl_finite_math_only) || 3152 Args.hasArg(OPT_cl_fast_relaxed_math); 3153 Opts.UnsafeFPMath = Args.hasArg(OPT_menable_unsafe_fp_math) || 3154 Args.hasArg(OPT_cl_unsafe_math_optimizations) || 3155 Args.hasArg(OPT_cl_fast_relaxed_math); 3156 3157 if (Arg *A = Args.getLastArg(OPT_ffp_contract)) { 3158 StringRef Val = A->getValue(); 3159 if (Val == "fast") 3160 Opts.setDefaultFPContractMode(LangOptions::FPC_Fast); 3161 else if (Val == "on") 3162 Opts.setDefaultFPContractMode(LangOptions::FPC_On); 3163 else if (Val == "off") 3164 Opts.setDefaultFPContractMode(LangOptions::FPC_Off); 3165 else 3166 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val; 3167 } 3168 3169 LangOptions::FPRoundingModeKind FPRM = LangOptions::FPR_ToNearest; 3170 if (Args.hasArg(OPT_frounding_math)) { 3171 FPRM = LangOptions::FPR_Dynamic; 3172 } 3173 Opts.setFPRoundingMode(FPRM); 3174 3175 if (Args.hasArg(OPT_ftrapping_math)) { 3176 Opts.setFPExceptionMode(LangOptions::FPE_Strict); 3177 } 3178 3179 if (Args.hasArg(OPT_fno_trapping_math)) { 3180 Opts.setFPExceptionMode(LangOptions::FPE_Ignore); 3181 } 3182 3183 LangOptions::FPExceptionModeKind FPEB = LangOptions::FPE_Ignore; 3184 if (Arg *A = Args.getLastArg(OPT_ffp_exception_behavior_EQ)) { 3185 StringRef Val = A->getValue(); 3186 if (Val.equals("ignore")) 3187 FPEB = LangOptions::FPE_Ignore; 3188 else if (Val.equals("maytrap")) 3189 FPEB = LangOptions::FPE_MayTrap; 3190 else if (Val.equals("strict")) 3191 FPEB = LangOptions::FPE_Strict; 3192 else 3193 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val; 3194 } 3195 Opts.setFPExceptionMode(FPEB); 3196 3197 Opts.RetainCommentsFromSystemHeaders = 3198 Args.hasArg(OPT_fretain_comments_from_system_headers); 3199 3200 unsigned SSP = getLastArgIntValue(Args, OPT_stack_protector, 0, Diags); 3201 switch (SSP) { 3202 default: 3203 Diags.Report(diag::err_drv_invalid_value) 3204 << Args.getLastArg(OPT_stack_protector)->getAsString(Args) << SSP; 3205 break; 3206 case 0: Opts.setStackProtector(LangOptions::SSPOff); break; 3207 case 1: Opts.setStackProtector(LangOptions::SSPOn); break; 3208 case 2: Opts.setStackProtector(LangOptions::SSPStrong); break; 3209 case 3: Opts.setStackProtector(LangOptions::SSPReq); break; 3210 } 3211 3212 if (Arg *A = Args.getLastArg(OPT_ftrivial_auto_var_init)) { 3213 StringRef Val = A->getValue(); 3214 if (Val == "uninitialized") 3215 Opts.setTrivialAutoVarInit( 3216 LangOptions::TrivialAutoVarInitKind::Uninitialized); 3217 else if (Val == "zero") 3218 Opts.setTrivialAutoVarInit(LangOptions::TrivialAutoVarInitKind::Zero); 3219 else if (Val == "pattern") 3220 Opts.setTrivialAutoVarInit(LangOptions::TrivialAutoVarInitKind::Pattern); 3221 else 3222 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val; 3223 } 3224 3225 // Parse -fsanitize= arguments. 3226 parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ), 3227 Diags, Opts.Sanitize); 3228 // -fsanitize-address-field-padding=N has to be a LangOpt, parse it here. 3229 Opts.SanitizeAddressFieldPadding = 3230 getLastArgIntValue(Args, OPT_fsanitize_address_field_padding, 0, Diags); 3231 Opts.SanitizerBlacklistFiles = Args.getAllArgValues(OPT_fsanitize_blacklist); 3232 std::vector<std::string> systemBlacklists = 3233 Args.getAllArgValues(OPT_fsanitize_system_blacklist); 3234 Opts.SanitizerBlacklistFiles.insert(Opts.SanitizerBlacklistFiles.end(), 3235 systemBlacklists.begin(), 3236 systemBlacklists.end()); 3237 3238 // -fxray-instrument 3239 Opts.XRayInstrument = 3240 Args.hasFlag(OPT_fxray_instrument, OPT_fnoxray_instrument, false); 3241 3242 // -fxray-always-emit-customevents 3243 Opts.XRayAlwaysEmitCustomEvents = 3244 Args.hasFlag(OPT_fxray_always_emit_customevents, 3245 OPT_fnoxray_always_emit_customevents, false); 3246 3247 // -fxray-always-emit-typedevents 3248 Opts.XRayAlwaysEmitTypedEvents = 3249 Args.hasFlag(OPT_fxray_always_emit_typedevents, 3250 OPT_fnoxray_always_emit_customevents, false); 3251 3252 // -fxray-{always,never}-instrument= filenames. 3253 Opts.XRayAlwaysInstrumentFiles = 3254 Args.getAllArgValues(OPT_fxray_always_instrument); 3255 Opts.XRayNeverInstrumentFiles = 3256 Args.getAllArgValues(OPT_fxray_never_instrument); 3257 Opts.XRayAttrListFiles = Args.getAllArgValues(OPT_fxray_attr_list); 3258 3259 // -fforce-emit-vtables 3260 Opts.ForceEmitVTables = Args.hasArg(OPT_fforce_emit_vtables); 3261 3262 // -fallow-editor-placeholders 3263 Opts.AllowEditorPlaceholders = Args.hasArg(OPT_fallow_editor_placeholders); 3264 3265 Opts.RegisterStaticDestructors = !Args.hasArg(OPT_fno_cxx_static_destructors); 3266 3267 if (Arg *A = Args.getLastArg(OPT_fclang_abi_compat_EQ)) { 3268 Opts.setClangABICompat(LangOptions::ClangABI::Latest); 3269 3270 StringRef Ver = A->getValue(); 3271 std::pair<StringRef, StringRef> VerParts = Ver.split('.'); 3272 unsigned Major, Minor = 0; 3273 3274 // Check the version number is valid: either 3.x (0 <= x <= 9) or 3275 // y or y.0 (4 <= y <= current version). 3276 if (!VerParts.first.startswith("0") && 3277 !VerParts.first.getAsInteger(10, Major) && 3278 3 <= Major && Major <= CLANG_VERSION_MAJOR && 3279 (Major == 3 ? VerParts.second.size() == 1 && 3280 !VerParts.second.getAsInteger(10, Minor) 3281 : VerParts.first.size() == Ver.size() || 3282 VerParts.second == "0")) { 3283 // Got a valid version number. 3284 if (Major == 3 && Minor <= 8) 3285 Opts.setClangABICompat(LangOptions::ClangABI::Ver3_8); 3286 else if (Major <= 4) 3287 Opts.setClangABICompat(LangOptions::ClangABI::Ver4); 3288 else if (Major <= 6) 3289 Opts.setClangABICompat(LangOptions::ClangABI::Ver6); 3290 else if (Major <= 7) 3291 Opts.setClangABICompat(LangOptions::ClangABI::Ver7); 3292 else if (Major <= 9) 3293 Opts.setClangABICompat(LangOptions::ClangABI::Ver9); 3294 } else if (Ver != "latest") { 3295 Diags.Report(diag::err_drv_invalid_value) 3296 << A->getAsString(Args) << A->getValue(); 3297 } 3298 } 3299 3300 Opts.CompleteMemberPointers = Args.hasArg(OPT_fcomplete_member_pointers); 3301 Opts.BuildingPCHWithObjectFile = Args.hasArg(OPT_building_pch_with_obj); 3302 } 3303 3304 static bool isStrictlyPreprocessorAction(frontend::ActionKind Action) { 3305 switch (Action) { 3306 case frontend::ASTDeclList: 3307 case frontend::ASTDump: 3308 case frontend::ASTPrint: 3309 case frontend::ASTView: 3310 case frontend::EmitAssembly: 3311 case frontend::EmitBC: 3312 case frontend::EmitHTML: 3313 case frontend::EmitLLVM: 3314 case frontend::EmitLLVMOnly: 3315 case frontend::EmitCodeGenOnly: 3316 case frontend::EmitObj: 3317 case frontend::FixIt: 3318 case frontend::GenerateModule: 3319 case frontend::GenerateModuleInterface: 3320 case frontend::GenerateHeaderModule: 3321 case frontend::GeneratePCH: 3322 case frontend::GenerateInterfaceIfsExpV1: 3323 case frontend::ParseSyntaxOnly: 3324 case frontend::ModuleFileInfo: 3325 case frontend::VerifyPCH: 3326 case frontend::PluginAction: 3327 case frontend::RewriteObjC: 3328 case frontend::RewriteTest: 3329 case frontend::RunAnalysis: 3330 case frontend::TemplightDump: 3331 case frontend::MigrateSource: 3332 return false; 3333 3334 case frontend::DumpCompilerOptions: 3335 case frontend::DumpRawTokens: 3336 case frontend::DumpTokens: 3337 case frontend::InitOnly: 3338 case frontend::PrintPreamble: 3339 case frontend::PrintPreprocessedInput: 3340 case frontend::RewriteMacros: 3341 case frontend::RunPreprocessorOnly: 3342 case frontend::PrintDependencyDirectivesSourceMinimizerOutput: 3343 return true; 3344 } 3345 llvm_unreachable("invalid frontend action"); 3346 } 3347 3348 static void ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args, 3349 DiagnosticsEngine &Diags, 3350 frontend::ActionKind Action) { 3351 Opts.ImplicitPCHInclude = Args.getLastArgValue(OPT_include_pch); 3352 Opts.PCHWithHdrStop = Args.hasArg(OPT_pch_through_hdrstop_create) || 3353 Args.hasArg(OPT_pch_through_hdrstop_use); 3354 Opts.PCHWithHdrStopCreate = Args.hasArg(OPT_pch_through_hdrstop_create); 3355 Opts.PCHThroughHeader = Args.getLastArgValue(OPT_pch_through_header_EQ); 3356 Opts.UsePredefines = !Args.hasArg(OPT_undef); 3357 Opts.DetailedRecord = Args.hasArg(OPT_detailed_preprocessing_record); 3358 Opts.DisablePCHValidation = Args.hasArg(OPT_fno_validate_pch); 3359 Opts.AllowPCHWithCompilerErrors = Args.hasArg(OPT_fallow_pch_with_errors); 3360 3361 Opts.DumpDeserializedPCHDecls = Args.hasArg(OPT_dump_deserialized_pch_decls); 3362 for (const auto *A : Args.filtered(OPT_error_on_deserialized_pch_decl)) 3363 Opts.DeserializedPCHDeclsToErrorOn.insert(A->getValue()); 3364 3365 for (const auto &A : Args.getAllArgValues(OPT_fmacro_prefix_map_EQ)) 3366 Opts.MacroPrefixMap.insert(StringRef(A).split('=')); 3367 3368 if (const Arg *A = Args.getLastArg(OPT_preamble_bytes_EQ)) { 3369 StringRef Value(A->getValue()); 3370 size_t Comma = Value.find(','); 3371 unsigned Bytes = 0; 3372 unsigned EndOfLine = 0; 3373 3374 if (Comma == StringRef::npos || 3375 Value.substr(0, Comma).getAsInteger(10, Bytes) || 3376 Value.substr(Comma + 1).getAsInteger(10, EndOfLine)) 3377 Diags.Report(diag::err_drv_preamble_format); 3378 else { 3379 Opts.PrecompiledPreambleBytes.first = Bytes; 3380 Opts.PrecompiledPreambleBytes.second = (EndOfLine != 0); 3381 } 3382 } 3383 3384 // Add the __CET__ macro if a CFProtection option is set. 3385 if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) { 3386 StringRef Name = A->getValue(); 3387 if (Name == "branch") 3388 Opts.addMacroDef("__CET__=1"); 3389 else if (Name == "return") 3390 Opts.addMacroDef("__CET__=2"); 3391 else if (Name == "full") 3392 Opts.addMacroDef("__CET__=3"); 3393 } 3394 3395 // Add macros from the command line. 3396 for (const auto *A : Args.filtered(OPT_D, OPT_U)) { 3397 if (A->getOption().matches(OPT_D)) 3398 Opts.addMacroDef(A->getValue()); 3399 else 3400 Opts.addMacroUndef(A->getValue()); 3401 } 3402 3403 Opts.MacroIncludes = Args.getAllArgValues(OPT_imacros); 3404 3405 // Add the ordered list of -includes. 3406 for (const auto *A : Args.filtered(OPT_include)) 3407 Opts.Includes.emplace_back(A->getValue()); 3408 3409 for (const auto *A : Args.filtered(OPT_chain_include)) 3410 Opts.ChainedIncludes.emplace_back(A->getValue()); 3411 3412 for (const auto *A : Args.filtered(OPT_remap_file)) { 3413 std::pair<StringRef, StringRef> Split = StringRef(A->getValue()).split(';'); 3414 3415 if (Split.second.empty()) { 3416 Diags.Report(diag::err_drv_invalid_remap_file) << A->getAsString(Args); 3417 continue; 3418 } 3419 3420 Opts.addRemappedFile(Split.first, Split.second); 3421 } 3422 3423 if (Arg *A = Args.getLastArg(OPT_fobjc_arc_cxxlib_EQ)) { 3424 StringRef Name = A->getValue(); 3425 unsigned Library = llvm::StringSwitch<unsigned>(Name) 3426 .Case("libc++", ARCXX_libcxx) 3427 .Case("libstdc++", ARCXX_libstdcxx) 3428 .Case("none", ARCXX_nolib) 3429 .Default(~0U); 3430 if (Library == ~0U) 3431 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name; 3432 else 3433 Opts.ObjCXXARCStandardLibrary = (ObjCXXARCStandardLibraryKind)Library; 3434 } 3435 3436 // Always avoid lexing editor placeholders when we're just running the 3437 // preprocessor as we never want to emit the 3438 // "editor placeholder in source file" error in PP only mode. 3439 if (isStrictlyPreprocessorAction(Action)) 3440 Opts.LexEditorPlaceholders = false; 3441 3442 Opts.SetUpStaticAnalyzer = Args.hasArg(OPT_setup_static_analyzer); 3443 Opts.DisablePragmaDebugCrash = Args.hasArg(OPT_disable_pragma_debug_crash); 3444 } 3445 3446 static void ParsePreprocessorOutputArgs(PreprocessorOutputOptions &Opts, 3447 ArgList &Args, 3448 frontend::ActionKind Action) { 3449 if (isStrictlyPreprocessorAction(Action)) 3450 Opts.ShowCPP = !Args.hasArg(OPT_dM); 3451 else 3452 Opts.ShowCPP = 0; 3453 3454 Opts.ShowComments = Args.hasArg(OPT_C); 3455 Opts.ShowLineMarkers = !Args.hasArg(OPT_P); 3456 Opts.ShowMacroComments = Args.hasArg(OPT_CC); 3457 Opts.ShowMacros = Args.hasArg(OPT_dM) || Args.hasArg(OPT_dD); 3458 Opts.ShowIncludeDirectives = Args.hasArg(OPT_dI); 3459 Opts.RewriteIncludes = Args.hasArg(OPT_frewrite_includes); 3460 Opts.RewriteImports = Args.hasArg(OPT_frewrite_imports); 3461 Opts.UseLineDirectives = Args.hasArg(OPT_fuse_line_directives); 3462 } 3463 3464 static void ParseTargetArgs(TargetOptions &Opts, ArgList &Args, 3465 DiagnosticsEngine &Diags) { 3466 Opts.CodeModel = getCodeModel(Args, Diags); 3467 Opts.ABI = Args.getLastArgValue(OPT_target_abi); 3468 if (Arg *A = Args.getLastArg(OPT_meabi)) { 3469 StringRef Value = A->getValue(); 3470 llvm::EABI EABIVersion = llvm::StringSwitch<llvm::EABI>(Value) 3471 .Case("default", llvm::EABI::Default) 3472 .Case("4", llvm::EABI::EABI4) 3473 .Case("5", llvm::EABI::EABI5) 3474 .Case("gnu", llvm::EABI::GNU) 3475 .Default(llvm::EABI::Unknown); 3476 if (EABIVersion == llvm::EABI::Unknown) 3477 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) 3478 << Value; 3479 else 3480 Opts.EABIVersion = EABIVersion; 3481 } 3482 Opts.CPU = Args.getLastArgValue(OPT_target_cpu); 3483 Opts.FPMath = Args.getLastArgValue(OPT_mfpmath); 3484 Opts.FeaturesAsWritten = Args.getAllArgValues(OPT_target_feature); 3485 Opts.LinkerVersion = Args.getLastArgValue(OPT_target_linker_version); 3486 Opts.Triple = Args.getLastArgValue(OPT_triple); 3487 // Use the default target triple if unspecified. 3488 if (Opts.Triple.empty()) 3489 Opts.Triple = llvm::sys::getDefaultTargetTriple(); 3490 Opts.Triple = llvm::Triple::normalize(Opts.Triple); 3491 Opts.OpenCLExtensionsAsWritten = Args.getAllArgValues(OPT_cl_ext_EQ); 3492 Opts.ForceEnableInt128 = Args.hasArg(OPT_fforce_enable_int128); 3493 Opts.NVPTXUseShortPointers = Args.hasFlag( 3494 options::OPT_fcuda_short_ptr, options::OPT_fno_cuda_short_ptr, false); 3495 if (Arg *A = Args.getLastArg(options::OPT_target_sdk_version_EQ)) { 3496 llvm::VersionTuple Version; 3497 if (Version.tryParse(A->getValue())) 3498 Diags.Report(diag::err_drv_invalid_value) 3499 << A->getAsString(Args) << A->getValue(); 3500 else 3501 Opts.SDKVersion = Version; 3502 } 3503 } 3504 3505 bool CompilerInvocation::CreateFromArgs(CompilerInvocation &Res, 3506 ArrayRef<const char *> CommandLineArgs, 3507 DiagnosticsEngine &Diags) { 3508 bool Success = true; 3509 3510 // Parse the arguments. 3511 const OptTable &Opts = getDriverOptTable(); 3512 const unsigned IncludedFlagsBitmask = options::CC1Option; 3513 unsigned MissingArgIndex, MissingArgCount; 3514 InputArgList Args = Opts.ParseArgs(CommandLineArgs, MissingArgIndex, 3515 MissingArgCount, IncludedFlagsBitmask); 3516 LangOptions &LangOpts = *Res.getLangOpts(); 3517 3518 // Check for missing argument error. 3519 if (MissingArgCount) { 3520 Diags.Report(diag::err_drv_missing_argument) 3521 << Args.getArgString(MissingArgIndex) << MissingArgCount; 3522 Success = false; 3523 } 3524 3525 // Issue errors on unknown arguments. 3526 for (const auto *A : Args.filtered(OPT_UNKNOWN)) { 3527 auto ArgString = A->getAsString(Args); 3528 std::string Nearest; 3529 if (Opts.findNearest(ArgString, Nearest, IncludedFlagsBitmask) > 1) 3530 Diags.Report(diag::err_drv_unknown_argument) << ArgString; 3531 else 3532 Diags.Report(diag::err_drv_unknown_argument_with_suggestion) 3533 << ArgString << Nearest; 3534 Success = false; 3535 } 3536 3537 Success &= ParseAnalyzerArgs(*Res.getAnalyzerOpts(), Args, Diags); 3538 Success &= ParseMigratorArgs(Res.getMigratorOpts(), Args); 3539 ParseDependencyOutputArgs(Res.getDependencyOutputOpts(), Args); 3540 if (!Res.getDependencyOutputOpts().OutputFile.empty() && 3541 Res.getDependencyOutputOpts().Targets.empty()) { 3542 Diags.Report(diag::err_fe_dependency_file_requires_MT); 3543 Success = false; 3544 } 3545 Success &= 3546 ParseDiagnosticArgs(Res.getDiagnosticOpts(), Args, &Diags, 3547 false /*DefaultDiagColor*/, false /*DefaultShowOpt*/); 3548 ParseCommentArgs(LangOpts.CommentOpts, Args); 3549 ParseFileSystemArgs(Res.getFileSystemOpts(), Args); 3550 // FIXME: We shouldn't have to pass the DashX option around here 3551 InputKind DashX = ParseFrontendArgs(Res.getFrontendOpts(), Args, Diags, 3552 LangOpts.IsHeaderFile); 3553 ParseTargetArgs(Res.getTargetOpts(), Args, Diags); 3554 Success &= ParseCodeGenArgs(Res.getCodeGenOpts(), Args, DashX, Diags, 3555 Res.getTargetOpts(), Res.getFrontendOpts()); 3556 ParseHeaderSearchArgs(Res.getHeaderSearchOpts(), Args, 3557 Res.getFileSystemOpts().WorkingDir); 3558 llvm::Triple T(Res.getTargetOpts().Triple); 3559 if (DashX.getFormat() == InputKind::Precompiled || 3560 DashX.getLanguage() == Language::LLVM_IR) { 3561 // ObjCAAutoRefCount and Sanitize LangOpts are used to setup the 3562 // PassManager in BackendUtil.cpp. They need to be initializd no matter 3563 // what the input type is. 3564 if (Args.hasArg(OPT_fobjc_arc)) 3565 LangOpts.ObjCAutoRefCount = 1; 3566 // PIClevel and PIELevel are needed during code generation and this should be 3567 // set regardless of the input type. 3568 LangOpts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags); 3569 LangOpts.PIE = Args.hasArg(OPT_pic_is_pie); 3570 parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ), 3571 Diags, LangOpts.Sanitize); 3572 } else { 3573 // Other LangOpts are only initialized when the input is not AST or LLVM IR. 3574 // FIXME: Should we really be calling this for an Language::Asm input? 3575 ParseLangArgs(LangOpts, Args, DashX, Res.getTargetOpts(), 3576 Res.getPreprocessorOpts(), Diags); 3577 if (Res.getFrontendOpts().ProgramAction == frontend::RewriteObjC) 3578 LangOpts.ObjCExceptions = 1; 3579 if (T.isOSDarwin() && DashX.isPreprocessed()) { 3580 // Supress the darwin-specific 'stdlibcxx-not-found' diagnostic for 3581 // preprocessed input as we don't expect it to be used with -std=libc++ 3582 // anyway. 3583 Res.getDiagnosticOpts().Warnings.push_back("no-stdlibcxx-not-found"); 3584 } 3585 } 3586 3587 if (Diags.isIgnored(diag::warn_profile_data_misexpect, SourceLocation())) 3588 Res.FrontendOpts.LLVMArgs.push_back("-pgo-warn-misexpect"); 3589 3590 LangOpts.FunctionAlignment = 3591 getLastArgIntValue(Args, OPT_function_alignment, 0, Diags); 3592 3593 if (LangOpts.CUDA) { 3594 // During CUDA device-side compilation, the aux triple is the 3595 // triple used for host compilation. 3596 if (LangOpts.CUDAIsDevice) 3597 Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple; 3598 } 3599 3600 // Set the triple of the host for OpenMP device compile. 3601 if (LangOpts.OpenMPIsDevice) 3602 Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple; 3603 3604 // FIXME: Override value name discarding when asan or msan is used because the 3605 // backend passes depend on the name of the alloca in order to print out 3606 // names. 3607 Res.getCodeGenOpts().DiscardValueNames &= 3608 !LangOpts.Sanitize.has(SanitizerKind::Address) && 3609 !LangOpts.Sanitize.has(SanitizerKind::KernelAddress) && 3610 !LangOpts.Sanitize.has(SanitizerKind::Memory) && 3611 !LangOpts.Sanitize.has(SanitizerKind::KernelMemory); 3612 3613 ParsePreprocessorArgs(Res.getPreprocessorOpts(), Args, Diags, 3614 Res.getFrontendOpts().ProgramAction); 3615 ParsePreprocessorOutputArgs(Res.getPreprocessorOutputOpts(), Args, 3616 Res.getFrontendOpts().ProgramAction); 3617 3618 // Turn on -Wspir-compat for SPIR target. 3619 if (T.isSPIR()) 3620 Res.getDiagnosticOpts().Warnings.push_back("spir-compat"); 3621 3622 // If sanitizer is enabled, disable OPT_ffine_grained_bitfield_accesses. 3623 if (Res.getCodeGenOpts().FineGrainedBitfieldAccesses && 3624 !Res.getLangOpts()->Sanitize.empty()) { 3625 Res.getCodeGenOpts().FineGrainedBitfieldAccesses = false; 3626 Diags.Report(diag::warn_drv_fine_grained_bitfield_accesses_ignored); 3627 } 3628 return Success; 3629 } 3630 3631 std::string CompilerInvocation::getModuleHash() const { 3632 // Note: For QoI reasons, the things we use as a hash here should all be 3633 // dumped via the -module-info flag. 3634 using llvm::hash_code; 3635 using llvm::hash_value; 3636 using llvm::hash_combine; 3637 using llvm::hash_combine_range; 3638 3639 // Start the signature with the compiler version. 3640 // FIXME: We'd rather use something more cryptographically sound than 3641 // CityHash, but this will do for now. 3642 hash_code code = hash_value(getClangFullRepositoryVersion()); 3643 3644 // Extend the signature with the language options 3645 #define LANGOPT(Name, Bits, Default, Description) \ 3646 code = hash_combine(code, LangOpts->Name); 3647 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \ 3648 code = hash_combine(code, static_cast<unsigned>(LangOpts->get##Name())); 3649 #define BENIGN_LANGOPT(Name, Bits, Default, Description) 3650 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description) 3651 #include "clang/Basic/LangOptions.def" 3652 3653 for (StringRef Feature : LangOpts->ModuleFeatures) 3654 code = hash_combine(code, Feature); 3655 3656 // Extend the signature with the target options. 3657 code = hash_combine(code, TargetOpts->Triple, TargetOpts->CPU, 3658 TargetOpts->ABI); 3659 for (const auto &FeatureAsWritten : TargetOpts->FeaturesAsWritten) 3660 code = hash_combine(code, FeatureAsWritten); 3661 3662 // Extend the signature with preprocessor options. 3663 const PreprocessorOptions &ppOpts = getPreprocessorOpts(); 3664 const HeaderSearchOptions &hsOpts = getHeaderSearchOpts(); 3665 code = hash_combine(code, ppOpts.UsePredefines, ppOpts.DetailedRecord); 3666 3667 for (const auto &I : getPreprocessorOpts().Macros) { 3668 // If we're supposed to ignore this macro for the purposes of modules, 3669 // don't put it into the hash. 3670 if (!hsOpts.ModulesIgnoreMacros.empty()) { 3671 // Check whether we're ignoring this macro. 3672 StringRef MacroDef = I.first; 3673 if (hsOpts.ModulesIgnoreMacros.count( 3674 llvm::CachedHashString(MacroDef.split('=').first))) 3675 continue; 3676 } 3677 3678 code = hash_combine(code, I.first, I.second); 3679 } 3680 3681 // Extend the signature with the sysroot and other header search options. 3682 code = hash_combine(code, hsOpts.Sysroot, 3683 hsOpts.ModuleFormat, 3684 hsOpts.UseDebugInfo, 3685 hsOpts.UseBuiltinIncludes, 3686 hsOpts.UseStandardSystemIncludes, 3687 hsOpts.UseStandardCXXIncludes, 3688 hsOpts.UseLibcxx, 3689 hsOpts.ModulesValidateDiagnosticOptions); 3690 code = hash_combine(code, hsOpts.ResourceDir); 3691 3692 if (hsOpts.ModulesStrictContextHash) { 3693 hash_code SHPC = hash_combine_range(hsOpts.SystemHeaderPrefixes.begin(), 3694 hsOpts.SystemHeaderPrefixes.end()); 3695 hash_code UEC = hash_combine_range(hsOpts.UserEntries.begin(), 3696 hsOpts.UserEntries.end()); 3697 code = hash_combine(code, hsOpts.SystemHeaderPrefixes.size(), SHPC, 3698 hsOpts.UserEntries.size(), UEC); 3699 3700 const DiagnosticOptions &diagOpts = getDiagnosticOpts(); 3701 #define DIAGOPT(Name, Bits, Default) \ 3702 code = hash_combine(code, diagOpts.Name); 3703 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \ 3704 code = hash_combine(code, diagOpts.get##Name()); 3705 #include "clang/Basic/DiagnosticOptions.def" 3706 #undef DIAGOPT 3707 #undef ENUM_DIAGOPT 3708 } 3709 3710 // Extend the signature with the user build path. 3711 code = hash_combine(code, hsOpts.ModuleUserBuildPath); 3712 3713 // Extend the signature with the module file extensions. 3714 const FrontendOptions &frontendOpts = getFrontendOpts(); 3715 for (const auto &ext : frontendOpts.ModuleFileExtensions) { 3716 code = ext->hashExtension(code); 3717 } 3718 3719 // When compiling with -gmodules, also hash -fdebug-prefix-map as it 3720 // affects the debug info in the PCM. 3721 if (getCodeGenOpts().DebugTypeExtRefs) 3722 for (const auto &KeyValue : getCodeGenOpts().DebugPrefixMap) 3723 code = hash_combine(code, KeyValue.first, KeyValue.second); 3724 3725 // Extend the signature with the enabled sanitizers, if at least one is 3726 // enabled. Sanitizers which cannot affect AST generation aren't hashed. 3727 SanitizerSet SanHash = LangOpts->Sanitize; 3728 SanHash.clear(getPPTransparentSanitizers()); 3729 if (!SanHash.empty()) 3730 code = hash_combine(code, SanHash.Mask); 3731 3732 return llvm::APInt(64, code).toString(36, /*Signed=*/false); 3733 } 3734 3735 namespace clang { 3736 3737 IntrusiveRefCntPtr<llvm::vfs::FileSystem> 3738 createVFSFromCompilerInvocation(const CompilerInvocation &CI, 3739 DiagnosticsEngine &Diags) { 3740 return createVFSFromCompilerInvocation(CI, Diags, 3741 llvm::vfs::getRealFileSystem()); 3742 } 3743 3744 IntrusiveRefCntPtr<llvm::vfs::FileSystem> createVFSFromCompilerInvocation( 3745 const CompilerInvocation &CI, DiagnosticsEngine &Diags, 3746 IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS) { 3747 if (CI.getHeaderSearchOpts().VFSOverlayFiles.empty()) 3748 return BaseFS; 3749 3750 IntrusiveRefCntPtr<llvm::vfs::FileSystem> Result = BaseFS; 3751 // earlier vfs files are on the bottom 3752 for (const auto &File : CI.getHeaderSearchOpts().VFSOverlayFiles) { 3753 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer = 3754 Result->getBufferForFile(File); 3755 if (!Buffer) { 3756 Diags.Report(diag::err_missing_vfs_overlay_file) << File; 3757 continue; 3758 } 3759 3760 IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS = llvm::vfs::getVFSFromYAML( 3761 std::move(Buffer.get()), /*DiagHandler*/ nullptr, File, 3762 /*DiagContext*/ nullptr, Result); 3763 if (!FS) { 3764 Diags.Report(diag::err_invalid_vfs_overlay) << File; 3765 continue; 3766 } 3767 3768 Result = FS; 3769 } 3770 return Result; 3771 } 3772 3773 } // namespace clang 3774