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 // X86_32 has -fppc-struct-return and -freg-struct-return. 1283 // PPC32 has -maix-struct-return and -msvr4-struct-return. 1284 if (Arg *A = 1285 Args.getLastArg(OPT_fpcc_struct_return, OPT_freg_struct_return, 1286 OPT_maix_struct_return, OPT_msvr4_struct_return)) { 1287 const Option &O = A->getOption(); 1288 if (O.matches(OPT_fpcc_struct_return) || 1289 O.matches(OPT_maix_struct_return)) { 1290 Opts.setStructReturnConvention(CodeGenOptions::SRCK_OnStack); 1291 } else { 1292 assert(O.matches(OPT_freg_struct_return) || 1293 O.matches(OPT_msvr4_struct_return)); 1294 Opts.setStructReturnConvention(CodeGenOptions::SRCK_InRegs); 1295 } 1296 } 1297 1298 Opts.DependentLibraries = Args.getAllArgValues(OPT_dependent_lib); 1299 Opts.LinkerOptions = Args.getAllArgValues(OPT_linker_option); 1300 bool NeedLocTracking = false; 1301 1302 Opts.OptRecordFile = Args.getLastArgValue(OPT_opt_record_file); 1303 if (!Opts.OptRecordFile.empty()) 1304 NeedLocTracking = true; 1305 1306 if (Arg *A = Args.getLastArg(OPT_opt_record_passes)) { 1307 Opts.OptRecordPasses = A->getValue(); 1308 NeedLocTracking = true; 1309 } 1310 1311 if (Arg *A = Args.getLastArg(OPT_opt_record_format)) { 1312 Opts.OptRecordFormat = A->getValue(); 1313 NeedLocTracking = true; 1314 } 1315 1316 if (Arg *A = Args.getLastArg(OPT_Rpass_EQ)) { 1317 Opts.OptimizationRemarkPattern = 1318 GenerateOptimizationRemarkRegex(Diags, Args, A); 1319 NeedLocTracking = true; 1320 } 1321 1322 if (Arg *A = Args.getLastArg(OPT_Rpass_missed_EQ)) { 1323 Opts.OptimizationRemarkMissedPattern = 1324 GenerateOptimizationRemarkRegex(Diags, Args, A); 1325 NeedLocTracking = true; 1326 } 1327 1328 if (Arg *A = Args.getLastArg(OPT_Rpass_analysis_EQ)) { 1329 Opts.OptimizationRemarkAnalysisPattern = 1330 GenerateOptimizationRemarkRegex(Diags, Args, A); 1331 NeedLocTracking = true; 1332 } 1333 1334 Opts.DiagnosticsWithHotness = 1335 Args.hasArg(options::OPT_fdiagnostics_show_hotness); 1336 bool UsingSampleProfile = !Opts.SampleProfileFile.empty(); 1337 bool UsingProfile = UsingSampleProfile || 1338 (Opts.getProfileUse() != CodeGenOptions::ProfileNone); 1339 1340 if (Opts.DiagnosticsWithHotness && !UsingProfile && 1341 // An IR file will contain PGO as metadata 1342 IK.getLanguage() != Language::LLVM_IR) 1343 Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo) 1344 << "-fdiagnostics-show-hotness"; 1345 1346 Opts.DiagnosticsHotnessThreshold = getLastArgUInt64Value( 1347 Args, options::OPT_fdiagnostics_hotness_threshold_EQ, 0); 1348 if (Opts.DiagnosticsHotnessThreshold > 0 && !UsingProfile) 1349 Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo) 1350 << "-fdiagnostics-hotness-threshold="; 1351 1352 // If the user requested to use a sample profile for PGO, then the 1353 // backend will need to track source location information so the profile 1354 // can be incorporated into the IR. 1355 if (UsingSampleProfile) 1356 NeedLocTracking = true; 1357 1358 // If the user requested a flag that requires source locations available in 1359 // the backend, make sure that the backend tracks source location information. 1360 if (NeedLocTracking && Opts.getDebugInfo() == codegenoptions::NoDebugInfo) 1361 Opts.setDebugInfo(codegenoptions::LocTrackingOnly); 1362 1363 Opts.RewriteMapFiles = Args.getAllArgValues(OPT_frewrite_map_file); 1364 1365 // Parse -fsanitize-recover= arguments. 1366 // FIXME: Report unrecoverable sanitizers incorrectly specified here. 1367 parseSanitizerKinds("-fsanitize-recover=", 1368 Args.getAllArgValues(OPT_fsanitize_recover_EQ), Diags, 1369 Opts.SanitizeRecover); 1370 parseSanitizerKinds("-fsanitize-trap=", 1371 Args.getAllArgValues(OPT_fsanitize_trap_EQ), Diags, 1372 Opts.SanitizeTrap); 1373 1374 Opts.CudaGpuBinaryFileName = 1375 Args.getLastArgValue(OPT_fcuda_include_gpubinary); 1376 1377 Opts.Backchain = Args.hasArg(OPT_mbackchain); 1378 1379 Opts.EmitCheckPathComponentsToStrip = getLastArgIntValue( 1380 Args, OPT_fsanitize_undefined_strip_path_components_EQ, 0, Diags); 1381 1382 Opts.EmitVersionIdentMetadata = Args.hasFlag(OPT_Qy, OPT_Qn, true); 1383 1384 Opts.Addrsig = Args.hasArg(OPT_faddrsig); 1385 1386 if (Arg *A = Args.getLastArg(OPT_msign_return_address_EQ)) { 1387 StringRef SignScope = A->getValue(); 1388 1389 if (SignScope.equals_lower("none")) 1390 Opts.setSignReturnAddress(CodeGenOptions::SignReturnAddressScope::None); 1391 else if (SignScope.equals_lower("all")) 1392 Opts.setSignReturnAddress(CodeGenOptions::SignReturnAddressScope::All); 1393 else if (SignScope.equals_lower("non-leaf")) 1394 Opts.setSignReturnAddress( 1395 CodeGenOptions::SignReturnAddressScope::NonLeaf); 1396 else 1397 Diags.Report(diag::err_drv_invalid_value) 1398 << A->getAsString(Args) << SignScope; 1399 1400 if (Arg *A = Args.getLastArg(OPT_msign_return_address_key_EQ)) { 1401 StringRef SignKey = A->getValue(); 1402 if (!SignScope.empty() && !SignKey.empty()) { 1403 if (SignKey.equals_lower("a_key")) 1404 Opts.setSignReturnAddressKey( 1405 CodeGenOptions::SignReturnAddressKeyValue::AKey); 1406 else if (SignKey.equals_lower("b_key")) 1407 Opts.setSignReturnAddressKey( 1408 CodeGenOptions::SignReturnAddressKeyValue::BKey); 1409 else 1410 Diags.Report(diag::err_drv_invalid_value) 1411 << A->getAsString(Args) << SignKey; 1412 } 1413 } 1414 } 1415 1416 Opts.BranchTargetEnforcement = Args.hasArg(OPT_mbranch_target_enforce); 1417 1418 Opts.KeepStaticConsts = Args.hasArg(OPT_fkeep_static_consts); 1419 1420 Opts.SpeculativeLoadHardening = Args.hasArg(OPT_mspeculative_load_hardening); 1421 1422 Opts.DefaultFunctionAttrs = Args.getAllArgValues(OPT_default_function_attr); 1423 1424 Opts.PassPlugins = Args.getAllArgValues(OPT_fpass_plugin_EQ); 1425 1426 Opts.SymbolPartition = Args.getLastArgValue(OPT_fsymbol_partition_EQ); 1427 1428 return Success; 1429 } 1430 1431 static void ParseDependencyOutputArgs(DependencyOutputOptions &Opts, 1432 ArgList &Args) { 1433 Opts.OutputFile = Args.getLastArgValue(OPT_dependency_file); 1434 Opts.Targets = Args.getAllArgValues(OPT_MT); 1435 Opts.IncludeSystemHeaders = Args.hasArg(OPT_sys_header_deps); 1436 Opts.IncludeModuleFiles = Args.hasArg(OPT_module_file_deps); 1437 Opts.UsePhonyTargets = Args.hasArg(OPT_MP); 1438 Opts.ShowHeaderIncludes = Args.hasArg(OPT_H); 1439 Opts.HeaderIncludeOutputFile = Args.getLastArgValue(OPT_header_include_file); 1440 Opts.AddMissingHeaderDeps = Args.hasArg(OPT_MG); 1441 if (Args.hasArg(OPT_show_includes)) { 1442 // Writing both /showIncludes and preprocessor output to stdout 1443 // would produce interleaved output, so use stderr for /showIncludes. 1444 // This behaves the same as cl.exe, when /E, /EP or /P are passed. 1445 if (Args.hasArg(options::OPT_E) || Args.hasArg(options::OPT_P)) 1446 Opts.ShowIncludesDest = ShowIncludesDestination::Stderr; 1447 else 1448 Opts.ShowIncludesDest = ShowIncludesDestination::Stdout; 1449 } else { 1450 Opts.ShowIncludesDest = ShowIncludesDestination::None; 1451 } 1452 Opts.DOTOutputFile = Args.getLastArgValue(OPT_dependency_dot); 1453 Opts.ModuleDependencyOutputDir = 1454 Args.getLastArgValue(OPT_module_dependency_dir); 1455 if (Args.hasArg(OPT_MV)) 1456 Opts.OutputFormat = DependencyOutputFormat::NMake; 1457 // Add sanitizer blacklists as extra dependencies. 1458 // They won't be discovered by the regular preprocessor, so 1459 // we let make / ninja to know about this implicit dependency. 1460 if (!Args.hasArg(OPT_fno_sanitize_blacklist)) { 1461 for (const auto *A : Args.filtered(OPT_fsanitize_blacklist)) { 1462 StringRef Val = A->getValue(); 1463 if (Val.find('=') == StringRef::npos) 1464 Opts.ExtraDeps.push_back(Val); 1465 } 1466 if (Opts.IncludeSystemHeaders) { 1467 for (const auto *A : Args.filtered(OPT_fsanitize_system_blacklist)) { 1468 StringRef Val = A->getValue(); 1469 if (Val.find('=') == StringRef::npos) 1470 Opts.ExtraDeps.push_back(Val); 1471 } 1472 } 1473 } 1474 1475 // Propagate the extra dependencies. 1476 for (const auto *A : Args.filtered(OPT_fdepfile_entry)) { 1477 Opts.ExtraDeps.push_back(A->getValue()); 1478 } 1479 1480 // Only the -fmodule-file=<file> form. 1481 for (const auto *A : Args.filtered(OPT_fmodule_file)) { 1482 StringRef Val = A->getValue(); 1483 if (Val.find('=') == StringRef::npos) 1484 Opts.ExtraDeps.push_back(Val); 1485 } 1486 } 1487 1488 static bool parseShowColorsArgs(const ArgList &Args, bool DefaultColor) { 1489 // Color diagnostics default to auto ("on" if terminal supports) in the driver 1490 // but default to off in cc1, needing an explicit OPT_fdiagnostics_color. 1491 // Support both clang's -f[no-]color-diagnostics and gcc's 1492 // -f[no-]diagnostics-colors[=never|always|auto]. 1493 enum { 1494 Colors_On, 1495 Colors_Off, 1496 Colors_Auto 1497 } ShowColors = DefaultColor ? Colors_Auto : Colors_Off; 1498 for (auto *A : Args) { 1499 const Option &O = A->getOption(); 1500 if (O.matches(options::OPT_fcolor_diagnostics) || 1501 O.matches(options::OPT_fdiagnostics_color)) { 1502 ShowColors = Colors_On; 1503 } else if (O.matches(options::OPT_fno_color_diagnostics) || 1504 O.matches(options::OPT_fno_diagnostics_color)) { 1505 ShowColors = Colors_Off; 1506 } else if (O.matches(options::OPT_fdiagnostics_color_EQ)) { 1507 StringRef Value(A->getValue()); 1508 if (Value == "always") 1509 ShowColors = Colors_On; 1510 else if (Value == "never") 1511 ShowColors = Colors_Off; 1512 else if (Value == "auto") 1513 ShowColors = Colors_Auto; 1514 } 1515 } 1516 return ShowColors == Colors_On || 1517 (ShowColors == Colors_Auto && 1518 llvm::sys::Process::StandardErrHasColors()); 1519 } 1520 1521 static bool checkVerifyPrefixes(const std::vector<std::string> &VerifyPrefixes, 1522 DiagnosticsEngine *Diags) { 1523 bool Success = true; 1524 for (const auto &Prefix : VerifyPrefixes) { 1525 // Every prefix must start with a letter and contain only alphanumeric 1526 // characters, hyphens, and underscores. 1527 auto BadChar = llvm::find_if(Prefix, [](char C) { 1528 return !isAlphanumeric(C) && C != '-' && C != '_'; 1529 }); 1530 if (BadChar != Prefix.end() || !isLetter(Prefix[0])) { 1531 Success = false; 1532 if (Diags) { 1533 Diags->Report(diag::err_drv_invalid_value) << "-verify=" << Prefix; 1534 Diags->Report(diag::note_drv_verify_prefix_spelling); 1535 } 1536 } 1537 } 1538 return Success; 1539 } 1540 1541 bool clang::ParseDiagnosticArgs(DiagnosticOptions &Opts, ArgList &Args, 1542 DiagnosticsEngine *Diags, 1543 bool DefaultDiagColor, bool DefaultShowOpt) { 1544 bool Success = true; 1545 1546 Opts.DiagnosticLogFile = Args.getLastArgValue(OPT_diagnostic_log_file); 1547 if (Arg *A = 1548 Args.getLastArg(OPT_diagnostic_serialized_file, OPT__serialize_diags)) 1549 Opts.DiagnosticSerializationFile = A->getValue(); 1550 Opts.IgnoreWarnings = Args.hasArg(OPT_w); 1551 Opts.NoRewriteMacros = Args.hasArg(OPT_Wno_rewrite_macros); 1552 Opts.Pedantic = Args.hasArg(OPT_pedantic); 1553 Opts.PedanticErrors = Args.hasArg(OPT_pedantic_errors); 1554 Opts.ShowCarets = !Args.hasArg(OPT_fno_caret_diagnostics); 1555 Opts.ShowColors = parseShowColorsArgs(Args, DefaultDiagColor); 1556 Opts.ShowColumn = Args.hasFlag(OPT_fshow_column, 1557 OPT_fno_show_column, 1558 /*Default=*/true); 1559 Opts.ShowFixits = !Args.hasArg(OPT_fno_diagnostics_fixit_info); 1560 Opts.ShowLocation = !Args.hasArg(OPT_fno_show_source_location); 1561 Opts.AbsolutePath = Args.hasArg(OPT_fdiagnostics_absolute_paths); 1562 Opts.ShowOptionNames = 1563 Args.hasFlag(OPT_fdiagnostics_show_option, 1564 OPT_fno_diagnostics_show_option, DefaultShowOpt); 1565 1566 llvm::sys::Process::UseANSIEscapeCodes(Args.hasArg(OPT_fansi_escape_codes)); 1567 1568 // Default behavior is to not to show note include stacks. 1569 Opts.ShowNoteIncludeStack = false; 1570 if (Arg *A = Args.getLastArg(OPT_fdiagnostics_show_note_include_stack, 1571 OPT_fno_diagnostics_show_note_include_stack)) 1572 if (A->getOption().matches(OPT_fdiagnostics_show_note_include_stack)) 1573 Opts.ShowNoteIncludeStack = true; 1574 1575 StringRef ShowOverloads = 1576 Args.getLastArgValue(OPT_fshow_overloads_EQ, "all"); 1577 if (ShowOverloads == "best") 1578 Opts.setShowOverloads(Ovl_Best); 1579 else if (ShowOverloads == "all") 1580 Opts.setShowOverloads(Ovl_All); 1581 else { 1582 Success = false; 1583 if (Diags) 1584 Diags->Report(diag::err_drv_invalid_value) 1585 << Args.getLastArg(OPT_fshow_overloads_EQ)->getAsString(Args) 1586 << ShowOverloads; 1587 } 1588 1589 StringRef ShowCategory = 1590 Args.getLastArgValue(OPT_fdiagnostics_show_category, "none"); 1591 if (ShowCategory == "none") 1592 Opts.ShowCategories = 0; 1593 else if (ShowCategory == "id") 1594 Opts.ShowCategories = 1; 1595 else if (ShowCategory == "name") 1596 Opts.ShowCategories = 2; 1597 else { 1598 Success = false; 1599 if (Diags) 1600 Diags->Report(diag::err_drv_invalid_value) 1601 << Args.getLastArg(OPT_fdiagnostics_show_category)->getAsString(Args) 1602 << ShowCategory; 1603 } 1604 1605 StringRef Format = 1606 Args.getLastArgValue(OPT_fdiagnostics_format, "clang"); 1607 if (Format == "clang") 1608 Opts.setFormat(DiagnosticOptions::Clang); 1609 else if (Format == "msvc") 1610 Opts.setFormat(DiagnosticOptions::MSVC); 1611 else if (Format == "msvc-fallback") { 1612 Opts.setFormat(DiagnosticOptions::MSVC); 1613 Opts.CLFallbackMode = true; 1614 } else if (Format == "vi") 1615 Opts.setFormat(DiagnosticOptions::Vi); 1616 else { 1617 Success = false; 1618 if (Diags) 1619 Diags->Report(diag::err_drv_invalid_value) 1620 << Args.getLastArg(OPT_fdiagnostics_format)->getAsString(Args) 1621 << Format; 1622 } 1623 1624 Opts.ShowSourceRanges = Args.hasArg(OPT_fdiagnostics_print_source_range_info); 1625 Opts.ShowParseableFixits = Args.hasArg(OPT_fdiagnostics_parseable_fixits); 1626 Opts.ShowPresumedLoc = !Args.hasArg(OPT_fno_diagnostics_use_presumed_location); 1627 Opts.VerifyDiagnostics = Args.hasArg(OPT_verify) || Args.hasArg(OPT_verify_EQ); 1628 Opts.VerifyPrefixes = Args.getAllArgValues(OPT_verify_EQ); 1629 if (Args.hasArg(OPT_verify)) 1630 Opts.VerifyPrefixes.push_back("expected"); 1631 // Keep VerifyPrefixes in its original order for the sake of diagnostics, and 1632 // then sort it to prepare for fast lookup using std::binary_search. 1633 if (!checkVerifyPrefixes(Opts.VerifyPrefixes, Diags)) { 1634 Opts.VerifyDiagnostics = false; 1635 Success = false; 1636 } 1637 else 1638 llvm::sort(Opts.VerifyPrefixes); 1639 DiagnosticLevelMask DiagMask = DiagnosticLevelMask::None; 1640 Success &= parseDiagnosticLevelMask("-verify-ignore-unexpected=", 1641 Args.getAllArgValues(OPT_verify_ignore_unexpected_EQ), 1642 Diags, DiagMask); 1643 if (Args.hasArg(OPT_verify_ignore_unexpected)) 1644 DiagMask = DiagnosticLevelMask::All; 1645 Opts.setVerifyIgnoreUnexpected(DiagMask); 1646 Opts.ElideType = !Args.hasArg(OPT_fno_elide_type); 1647 Opts.ShowTemplateTree = Args.hasArg(OPT_fdiagnostics_show_template_tree); 1648 Opts.ErrorLimit = getLastArgIntValue(Args, OPT_ferror_limit, 0, Diags); 1649 Opts.MacroBacktraceLimit = 1650 getLastArgIntValue(Args, OPT_fmacro_backtrace_limit, 1651 DiagnosticOptions::DefaultMacroBacktraceLimit, Diags); 1652 Opts.TemplateBacktraceLimit = getLastArgIntValue( 1653 Args, OPT_ftemplate_backtrace_limit, 1654 DiagnosticOptions::DefaultTemplateBacktraceLimit, Diags); 1655 Opts.ConstexprBacktraceLimit = getLastArgIntValue( 1656 Args, OPT_fconstexpr_backtrace_limit, 1657 DiagnosticOptions::DefaultConstexprBacktraceLimit, Diags); 1658 Opts.SpellCheckingLimit = getLastArgIntValue( 1659 Args, OPT_fspell_checking_limit, 1660 DiagnosticOptions::DefaultSpellCheckingLimit, Diags); 1661 Opts.SnippetLineLimit = getLastArgIntValue( 1662 Args, OPT_fcaret_diagnostics_max_lines, 1663 DiagnosticOptions::DefaultSnippetLineLimit, Diags); 1664 Opts.TabStop = getLastArgIntValue(Args, OPT_ftabstop, 1665 DiagnosticOptions::DefaultTabStop, Diags); 1666 if (Opts.TabStop == 0 || Opts.TabStop > DiagnosticOptions::MaxTabStop) { 1667 Opts.TabStop = DiagnosticOptions::DefaultTabStop; 1668 if (Diags) 1669 Diags->Report(diag::warn_ignoring_ftabstop_value) 1670 << Opts.TabStop << DiagnosticOptions::DefaultTabStop; 1671 } 1672 Opts.MessageLength = getLastArgIntValue(Args, OPT_fmessage_length, 0, Diags); 1673 addDiagnosticArgs(Args, OPT_W_Group, OPT_W_value_Group, Opts.Warnings); 1674 addDiagnosticArgs(Args, OPT_R_Group, OPT_R_value_Group, Opts.Remarks); 1675 1676 return Success; 1677 } 1678 1679 static void ParseFileSystemArgs(FileSystemOptions &Opts, ArgList &Args) { 1680 Opts.WorkingDir = Args.getLastArgValue(OPT_working_directory); 1681 } 1682 1683 /// Parse the argument to the -ftest-module-file-extension 1684 /// command-line argument. 1685 /// 1686 /// \returns true on error, false on success. 1687 static bool parseTestModuleFileExtensionArg(StringRef Arg, 1688 std::string &BlockName, 1689 unsigned &MajorVersion, 1690 unsigned &MinorVersion, 1691 bool &Hashed, 1692 std::string &UserInfo) { 1693 SmallVector<StringRef, 5> Args; 1694 Arg.split(Args, ':', 5); 1695 if (Args.size() < 5) 1696 return true; 1697 1698 BlockName = Args[0]; 1699 if (Args[1].getAsInteger(10, MajorVersion)) return true; 1700 if (Args[2].getAsInteger(10, MinorVersion)) return true; 1701 if (Args[3].getAsInteger(2, Hashed)) return true; 1702 if (Args.size() > 4) 1703 UserInfo = Args[4]; 1704 return false; 1705 } 1706 1707 static InputKind ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args, 1708 DiagnosticsEngine &Diags, 1709 bool &IsHeaderFile) { 1710 Opts.ProgramAction = frontend::ParseSyntaxOnly; 1711 if (const Arg *A = Args.getLastArg(OPT_Action_Group)) { 1712 switch (A->getOption().getID()) { 1713 default: 1714 llvm_unreachable("Invalid option in group!"); 1715 case OPT_ast_list: 1716 Opts.ProgramAction = frontend::ASTDeclList; break; 1717 case OPT_ast_dump_all_EQ: 1718 case OPT_ast_dump_EQ: { 1719 unsigned Val = llvm::StringSwitch<unsigned>(A->getValue()) 1720 .CaseLower("default", ADOF_Default) 1721 .CaseLower("json", ADOF_JSON) 1722 .Default(std::numeric_limits<unsigned>::max()); 1723 1724 if (Val != std::numeric_limits<unsigned>::max()) 1725 Opts.ASTDumpFormat = static_cast<ASTDumpOutputFormat>(Val); 1726 else { 1727 Diags.Report(diag::err_drv_invalid_value) 1728 << A->getAsString(Args) << A->getValue(); 1729 Opts.ASTDumpFormat = ADOF_Default; 1730 } 1731 LLVM_FALLTHROUGH; 1732 } 1733 case OPT_ast_dump: 1734 case OPT_ast_dump_all: 1735 case OPT_ast_dump_lookups: 1736 Opts.ProgramAction = frontend::ASTDump; break; 1737 case OPT_ast_print: 1738 Opts.ProgramAction = frontend::ASTPrint; break; 1739 case OPT_ast_view: 1740 Opts.ProgramAction = frontend::ASTView; break; 1741 case OPT_compiler_options_dump: 1742 Opts.ProgramAction = frontend::DumpCompilerOptions; break; 1743 case OPT_dump_raw_tokens: 1744 Opts.ProgramAction = frontend::DumpRawTokens; break; 1745 case OPT_dump_tokens: 1746 Opts.ProgramAction = frontend::DumpTokens; break; 1747 case OPT_S: 1748 Opts.ProgramAction = frontend::EmitAssembly; break; 1749 case OPT_emit_llvm_bc: 1750 Opts.ProgramAction = frontend::EmitBC; break; 1751 case OPT_emit_html: 1752 Opts.ProgramAction = frontend::EmitHTML; break; 1753 case OPT_emit_llvm: 1754 Opts.ProgramAction = frontend::EmitLLVM; break; 1755 case OPT_emit_llvm_only: 1756 Opts.ProgramAction = frontend::EmitLLVMOnly; break; 1757 case OPT_emit_codegen_only: 1758 Opts.ProgramAction = frontend::EmitCodeGenOnly; break; 1759 case OPT_emit_obj: 1760 Opts.ProgramAction = frontend::EmitObj; break; 1761 case OPT_fixit_EQ: 1762 Opts.FixItSuffix = A->getValue(); 1763 LLVM_FALLTHROUGH; 1764 case OPT_fixit: 1765 Opts.ProgramAction = frontend::FixIt; break; 1766 case OPT_emit_module: 1767 Opts.ProgramAction = frontend::GenerateModule; break; 1768 case OPT_emit_module_interface: 1769 Opts.ProgramAction = frontend::GenerateModuleInterface; break; 1770 case OPT_emit_header_module: 1771 Opts.ProgramAction = frontend::GenerateHeaderModule; break; 1772 case OPT_emit_pch: 1773 Opts.ProgramAction = frontend::GeneratePCH; break; 1774 case OPT_emit_interface_stubs: { 1775 StringRef ArgStr = 1776 Args.hasArg(OPT_interface_stub_version_EQ) 1777 ? Args.getLastArgValue(OPT_interface_stub_version_EQ) 1778 : "experimental-ifs-v1"; 1779 if (ArgStr == "experimental-yaml-elf-v1" || 1780 ArgStr == "experimental-tapi-elf-v1") { 1781 std::string ErrorMessage = 1782 "Invalid interface stub format: " + ArgStr.str() + 1783 " is deprecated."; 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 if (ArgStr != "experimental-ifs-v1") { 1789 std::string ErrorMessage = 1790 "Invalid interface stub format: " + ArgStr.str() + "."; 1791 Diags.Report(diag::err_drv_invalid_value) 1792 << "Must specify a valid interface stub format type, ie: " 1793 "-interface-stub-version=experimental-ifs-v1" 1794 << ErrorMessage; 1795 } else { 1796 Opts.ProgramAction = frontend::GenerateInterfaceIfsExpV1; 1797 } 1798 break; 1799 } 1800 case OPT_init_only: 1801 Opts.ProgramAction = frontend::InitOnly; break; 1802 case OPT_fsyntax_only: 1803 Opts.ProgramAction = frontend::ParseSyntaxOnly; break; 1804 case OPT_module_file_info: 1805 Opts.ProgramAction = frontend::ModuleFileInfo; break; 1806 case OPT_verify_pch: 1807 Opts.ProgramAction = frontend::VerifyPCH; break; 1808 case OPT_print_preamble: 1809 Opts.ProgramAction = frontend::PrintPreamble; break; 1810 case OPT_E: 1811 Opts.ProgramAction = frontend::PrintPreprocessedInput; break; 1812 case OPT_templight_dump: 1813 Opts.ProgramAction = frontend::TemplightDump; break; 1814 case OPT_rewrite_macros: 1815 Opts.ProgramAction = frontend::RewriteMacros; break; 1816 case OPT_rewrite_objc: 1817 Opts.ProgramAction = frontend::RewriteObjC; break; 1818 case OPT_rewrite_test: 1819 Opts.ProgramAction = frontend::RewriteTest; break; 1820 case OPT_analyze: 1821 Opts.ProgramAction = frontend::RunAnalysis; break; 1822 case OPT_migrate: 1823 Opts.ProgramAction = frontend::MigrateSource; break; 1824 case OPT_Eonly: 1825 Opts.ProgramAction = frontend::RunPreprocessorOnly; break; 1826 case OPT_print_dependency_directives_minimized_source: 1827 Opts.ProgramAction = 1828 frontend::PrintDependencyDirectivesSourceMinimizerOutput; 1829 break; 1830 } 1831 } 1832 1833 if (const Arg* A = Args.getLastArg(OPT_plugin)) { 1834 Opts.Plugins.emplace_back(A->getValue(0)); 1835 Opts.ProgramAction = frontend::PluginAction; 1836 Opts.ActionName = A->getValue(); 1837 } 1838 Opts.AddPluginActions = Args.getAllArgValues(OPT_add_plugin); 1839 for (const auto *AA : Args.filtered(OPT_plugin_arg)) 1840 Opts.PluginArgs[AA->getValue(0)].emplace_back(AA->getValue(1)); 1841 1842 for (const std::string &Arg : 1843 Args.getAllArgValues(OPT_ftest_module_file_extension_EQ)) { 1844 std::string BlockName; 1845 unsigned MajorVersion; 1846 unsigned MinorVersion; 1847 bool Hashed; 1848 std::string UserInfo; 1849 if (parseTestModuleFileExtensionArg(Arg, BlockName, MajorVersion, 1850 MinorVersion, Hashed, UserInfo)) { 1851 Diags.Report(diag::err_test_module_file_extension_format) << Arg; 1852 1853 continue; 1854 } 1855 1856 // Add the testing module file extension. 1857 Opts.ModuleFileExtensions.push_back( 1858 std::make_shared<TestModuleFileExtension>( 1859 BlockName, MajorVersion, MinorVersion, Hashed, UserInfo)); 1860 } 1861 1862 if (const Arg *A = Args.getLastArg(OPT_code_completion_at)) { 1863 Opts.CodeCompletionAt = 1864 ParsedSourceLocation::FromString(A->getValue()); 1865 if (Opts.CodeCompletionAt.FileName.empty()) 1866 Diags.Report(diag::err_drv_invalid_value) 1867 << A->getAsString(Args) << A->getValue(); 1868 } 1869 Opts.DisableFree = Args.hasArg(OPT_disable_free); 1870 1871 Opts.OutputFile = Args.getLastArgValue(OPT_o); 1872 Opts.Plugins = Args.getAllArgValues(OPT_load); 1873 Opts.RelocatablePCH = Args.hasArg(OPT_relocatable_pch); 1874 Opts.ShowHelp = Args.hasArg(OPT_help); 1875 Opts.ShowStats = Args.hasArg(OPT_print_stats); 1876 Opts.ShowTimers = Args.hasArg(OPT_ftime_report); 1877 Opts.PrintSupportedCPUs = Args.hasArg(OPT_print_supported_cpus); 1878 Opts.TimeTrace = Args.hasArg(OPT_ftime_trace); 1879 Opts.TimeTraceGranularity = getLastArgIntValue( 1880 Args, OPT_ftime_trace_granularity_EQ, Opts.TimeTraceGranularity, Diags); 1881 Opts.ShowVersion = Args.hasArg(OPT_version); 1882 Opts.ASTMergeFiles = Args.getAllArgValues(OPT_ast_merge); 1883 Opts.LLVMArgs = Args.getAllArgValues(OPT_mllvm); 1884 Opts.FixWhatYouCan = Args.hasArg(OPT_fix_what_you_can); 1885 Opts.FixOnlyWarnings = Args.hasArg(OPT_fix_only_warnings); 1886 Opts.FixAndRecompile = Args.hasArg(OPT_fixit_recompile); 1887 Opts.FixToTemporaries = Args.hasArg(OPT_fixit_to_temp); 1888 Opts.ASTDumpDecls = Args.hasArg(OPT_ast_dump, OPT_ast_dump_EQ); 1889 Opts.ASTDumpAll = Args.hasArg(OPT_ast_dump_all, OPT_ast_dump_all_EQ); 1890 Opts.ASTDumpFilter = Args.getLastArgValue(OPT_ast_dump_filter); 1891 Opts.ASTDumpLookups = Args.hasArg(OPT_ast_dump_lookups); 1892 Opts.UseGlobalModuleIndex = !Args.hasArg(OPT_fno_modules_global_index); 1893 Opts.GenerateGlobalModuleIndex = Opts.UseGlobalModuleIndex; 1894 Opts.ModuleMapFiles = Args.getAllArgValues(OPT_fmodule_map_file); 1895 // Only the -fmodule-file=<file> form. 1896 for (const auto *A : Args.filtered(OPT_fmodule_file)) { 1897 StringRef Val = A->getValue(); 1898 if (Val.find('=') == StringRef::npos) 1899 Opts.ModuleFiles.push_back(Val); 1900 } 1901 Opts.ModulesEmbedFiles = Args.getAllArgValues(OPT_fmodules_embed_file_EQ); 1902 Opts.ModulesEmbedAllFiles = Args.hasArg(OPT_fmodules_embed_all_files); 1903 Opts.IncludeTimestamps = !Args.hasArg(OPT_fno_pch_timestamp); 1904 Opts.UseTemporary = !Args.hasArg(OPT_fno_temp_file); 1905 1906 Opts.CodeCompleteOpts.IncludeMacros 1907 = Args.hasArg(OPT_code_completion_macros); 1908 Opts.CodeCompleteOpts.IncludeCodePatterns 1909 = Args.hasArg(OPT_code_completion_patterns); 1910 Opts.CodeCompleteOpts.IncludeGlobals 1911 = !Args.hasArg(OPT_no_code_completion_globals); 1912 Opts.CodeCompleteOpts.IncludeNamespaceLevelDecls 1913 = !Args.hasArg(OPT_no_code_completion_ns_level_decls); 1914 Opts.CodeCompleteOpts.IncludeBriefComments 1915 = Args.hasArg(OPT_code_completion_brief_comments); 1916 Opts.CodeCompleteOpts.IncludeFixIts 1917 = Args.hasArg(OPT_code_completion_with_fixits); 1918 1919 Opts.OverrideRecordLayoutsFile 1920 = Args.getLastArgValue(OPT_foverride_record_layout_EQ); 1921 Opts.AuxTriple = Args.getLastArgValue(OPT_aux_triple); 1922 Opts.StatsFile = Args.getLastArgValue(OPT_stats_file); 1923 1924 if (const Arg *A = Args.getLastArg(OPT_arcmt_check, 1925 OPT_arcmt_modify, 1926 OPT_arcmt_migrate)) { 1927 switch (A->getOption().getID()) { 1928 default: 1929 llvm_unreachable("missed a case"); 1930 case OPT_arcmt_check: 1931 Opts.ARCMTAction = FrontendOptions::ARCMT_Check; 1932 break; 1933 case OPT_arcmt_modify: 1934 Opts.ARCMTAction = FrontendOptions::ARCMT_Modify; 1935 break; 1936 case OPT_arcmt_migrate: 1937 Opts.ARCMTAction = FrontendOptions::ARCMT_Migrate; 1938 break; 1939 } 1940 } 1941 Opts.MTMigrateDir = Args.getLastArgValue(OPT_mt_migrate_directory); 1942 Opts.ARCMTMigrateReportOut 1943 = Args.getLastArgValue(OPT_arcmt_migrate_report_output); 1944 Opts.ARCMTMigrateEmitARCErrors 1945 = Args.hasArg(OPT_arcmt_migrate_emit_arc_errors); 1946 1947 if (Args.hasArg(OPT_objcmt_migrate_literals)) 1948 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Literals; 1949 if (Args.hasArg(OPT_objcmt_migrate_subscripting)) 1950 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Subscripting; 1951 if (Args.hasArg(OPT_objcmt_migrate_property_dot_syntax)) 1952 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_PropertyDotSyntax; 1953 if (Args.hasArg(OPT_objcmt_migrate_property)) 1954 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Property; 1955 if (Args.hasArg(OPT_objcmt_migrate_readonly_property)) 1956 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_ReadonlyProperty; 1957 if (Args.hasArg(OPT_objcmt_migrate_readwrite_property)) 1958 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_ReadwriteProperty; 1959 if (Args.hasArg(OPT_objcmt_migrate_annotation)) 1960 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Annotation; 1961 if (Args.hasArg(OPT_objcmt_returns_innerpointer_property)) 1962 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_ReturnsInnerPointerProperty; 1963 if (Args.hasArg(OPT_objcmt_migrate_instancetype)) 1964 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Instancetype; 1965 if (Args.hasArg(OPT_objcmt_migrate_nsmacros)) 1966 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_NsMacros; 1967 if (Args.hasArg(OPT_objcmt_migrate_protocol_conformance)) 1968 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_ProtocolConformance; 1969 if (Args.hasArg(OPT_objcmt_atomic_property)) 1970 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_AtomicProperty; 1971 if (Args.hasArg(OPT_objcmt_ns_nonatomic_iosonly)) 1972 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty; 1973 if (Args.hasArg(OPT_objcmt_migrate_designated_init)) 1974 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_DesignatedInitializer; 1975 if (Args.hasArg(OPT_objcmt_migrate_all)) 1976 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_MigrateDecls; 1977 1978 Opts.ObjCMTWhiteListPath = Args.getLastArgValue(OPT_objcmt_whitelist_dir_path); 1979 1980 if (Opts.ARCMTAction != FrontendOptions::ARCMT_None && 1981 Opts.ObjCMTAction != FrontendOptions::ObjCMT_None) { 1982 Diags.Report(diag::err_drv_argument_not_allowed_with) 1983 << "ARC migration" << "ObjC migration"; 1984 } 1985 1986 InputKind DashX(Language::Unknown); 1987 if (const Arg *A = Args.getLastArg(OPT_x)) { 1988 StringRef XValue = A->getValue(); 1989 1990 // Parse suffixes: '<lang>(-header|[-module-map][-cpp-output])'. 1991 // FIXME: Supporting '<lang>-header-cpp-output' would be useful. 1992 bool Preprocessed = XValue.consume_back("-cpp-output"); 1993 bool ModuleMap = XValue.consume_back("-module-map"); 1994 IsHeaderFile = 1995 !Preprocessed && !ModuleMap && XValue.consume_back("-header"); 1996 1997 // Principal languages. 1998 DashX = llvm::StringSwitch<InputKind>(XValue) 1999 .Case("c", Language::C) 2000 .Case("cl", Language::OpenCL) 2001 .Case("cuda", Language::CUDA) 2002 .Case("hip", Language::HIP) 2003 .Case("c++", Language::CXX) 2004 .Case("objective-c", Language::ObjC) 2005 .Case("objective-c++", Language::ObjCXX) 2006 .Case("renderscript", Language::RenderScript) 2007 .Default(Language::Unknown); 2008 2009 // "objc[++]-cpp-output" is an acceptable synonym for 2010 // "objective-c[++]-cpp-output". 2011 if (DashX.isUnknown() && Preprocessed && !IsHeaderFile && !ModuleMap) 2012 DashX = llvm::StringSwitch<InputKind>(XValue) 2013 .Case("objc", Language::ObjC) 2014 .Case("objc++", Language::ObjCXX) 2015 .Default(Language::Unknown); 2016 2017 // Some special cases cannot be combined with suffixes. 2018 if (DashX.isUnknown() && !Preprocessed && !ModuleMap && !IsHeaderFile) 2019 DashX = llvm::StringSwitch<InputKind>(XValue) 2020 .Case("cpp-output", InputKind(Language::C).getPreprocessed()) 2021 .Case("assembler-with-cpp", Language::Asm) 2022 .Cases("ast", "pcm", 2023 InputKind(Language::Unknown, InputKind::Precompiled)) 2024 .Case("ir", Language::LLVM_IR) 2025 .Default(Language::Unknown); 2026 2027 if (DashX.isUnknown()) 2028 Diags.Report(diag::err_drv_invalid_value) 2029 << A->getAsString(Args) << A->getValue(); 2030 2031 if (Preprocessed) 2032 DashX = DashX.getPreprocessed(); 2033 if (ModuleMap) 2034 DashX = DashX.withFormat(InputKind::ModuleMap); 2035 } 2036 2037 // '-' is the default input if none is given. 2038 std::vector<std::string> Inputs = Args.getAllArgValues(OPT_INPUT); 2039 Opts.Inputs.clear(); 2040 if (Inputs.empty()) 2041 Inputs.push_back("-"); 2042 for (unsigned i = 0, e = Inputs.size(); i != e; ++i) { 2043 InputKind IK = DashX; 2044 if (IK.isUnknown()) { 2045 IK = FrontendOptions::getInputKindForExtension( 2046 StringRef(Inputs[i]).rsplit('.').second); 2047 // FIXME: Warn on this? 2048 if (IK.isUnknown()) 2049 IK = Language::C; 2050 // FIXME: Remove this hack. 2051 if (i == 0) 2052 DashX = IK; 2053 } 2054 2055 // The -emit-module action implicitly takes a module map. 2056 if (Opts.ProgramAction == frontend::GenerateModule && 2057 IK.getFormat() == InputKind::Source) 2058 IK = IK.withFormat(InputKind::ModuleMap); 2059 2060 Opts.Inputs.emplace_back(std::move(Inputs[i]), IK); 2061 } 2062 2063 return DashX; 2064 } 2065 2066 std::string CompilerInvocation::GetResourcesPath(const char *Argv0, 2067 void *MainAddr) { 2068 std::string ClangExecutable = 2069 llvm::sys::fs::getMainExecutable(Argv0, MainAddr); 2070 return Driver::GetResourcesPath(ClangExecutable, CLANG_RESOURCE_DIR); 2071 } 2072 2073 static void ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args, 2074 const std::string &WorkingDir) { 2075 Opts.Sysroot = Args.getLastArgValue(OPT_isysroot, "/"); 2076 Opts.Verbose = Args.hasArg(OPT_v); 2077 Opts.UseBuiltinIncludes = !Args.hasArg(OPT_nobuiltininc); 2078 Opts.UseStandardSystemIncludes = !Args.hasArg(OPT_nostdsysteminc); 2079 Opts.UseStandardCXXIncludes = !Args.hasArg(OPT_nostdincxx); 2080 if (const Arg *A = Args.getLastArg(OPT_stdlib_EQ)) 2081 Opts.UseLibcxx = (strcmp(A->getValue(), "libc++") == 0); 2082 Opts.ResourceDir = Args.getLastArgValue(OPT_resource_dir); 2083 2084 // Canonicalize -fmodules-cache-path before storing it. 2085 SmallString<128> P(Args.getLastArgValue(OPT_fmodules_cache_path)); 2086 if (!(P.empty() || llvm::sys::path::is_absolute(P))) { 2087 if (WorkingDir.empty()) 2088 llvm::sys::fs::make_absolute(P); 2089 else 2090 llvm::sys::fs::make_absolute(WorkingDir, P); 2091 } 2092 llvm::sys::path::remove_dots(P); 2093 Opts.ModuleCachePath = P.str(); 2094 2095 Opts.ModuleUserBuildPath = Args.getLastArgValue(OPT_fmodules_user_build_path); 2096 // Only the -fmodule-file=<name>=<file> form. 2097 for (const auto *A : Args.filtered(OPT_fmodule_file)) { 2098 StringRef Val = A->getValue(); 2099 if (Val.find('=') != StringRef::npos) 2100 Opts.PrebuiltModuleFiles.insert(Val.split('=')); 2101 } 2102 for (const auto *A : Args.filtered(OPT_fprebuilt_module_path)) 2103 Opts.AddPrebuiltModulePath(A->getValue()); 2104 Opts.DisableModuleHash = Args.hasArg(OPT_fdisable_module_hash); 2105 Opts.ModulesHashContent = Args.hasArg(OPT_fmodules_hash_content); 2106 Opts.ModulesStrictContextHash = Args.hasArg(OPT_fmodules_strict_context_hash); 2107 Opts.ModulesValidateDiagnosticOptions = 2108 !Args.hasArg(OPT_fmodules_disable_diagnostic_validation); 2109 Opts.ImplicitModuleMaps = Args.hasArg(OPT_fimplicit_module_maps); 2110 Opts.ModuleMapFileHomeIsCwd = Args.hasArg(OPT_fmodule_map_file_home_is_cwd); 2111 Opts.ModuleCachePruneInterval = 2112 getLastArgIntValue(Args, OPT_fmodules_prune_interval, 7 * 24 * 60 * 60); 2113 Opts.ModuleCachePruneAfter = 2114 getLastArgIntValue(Args, OPT_fmodules_prune_after, 31 * 24 * 60 * 60); 2115 Opts.ModulesValidateOncePerBuildSession = 2116 Args.hasArg(OPT_fmodules_validate_once_per_build_session); 2117 Opts.BuildSessionTimestamp = 2118 getLastArgUInt64Value(Args, OPT_fbuild_session_timestamp, 0); 2119 Opts.ModulesValidateSystemHeaders = 2120 Args.hasArg(OPT_fmodules_validate_system_headers); 2121 Opts.ValidateASTInputFilesContent = 2122 Args.hasArg(OPT_fvalidate_ast_input_files_content); 2123 if (const Arg *A = Args.getLastArg(OPT_fmodule_format_EQ)) 2124 Opts.ModuleFormat = A->getValue(); 2125 2126 for (const auto *A : Args.filtered(OPT_fmodules_ignore_macro)) { 2127 StringRef MacroDef = A->getValue(); 2128 Opts.ModulesIgnoreMacros.insert( 2129 llvm::CachedHashString(MacroDef.split('=').first)); 2130 } 2131 2132 // Add -I..., -F..., and -index-header-map options in order. 2133 bool IsIndexHeaderMap = false; 2134 bool IsSysrootSpecified = 2135 Args.hasArg(OPT__sysroot_EQ) || Args.hasArg(OPT_isysroot); 2136 for (const auto *A : Args.filtered(OPT_I, OPT_F, OPT_index_header_map)) { 2137 if (A->getOption().matches(OPT_index_header_map)) { 2138 // -index-header-map applies to the next -I or -F. 2139 IsIndexHeaderMap = true; 2140 continue; 2141 } 2142 2143 frontend::IncludeDirGroup Group = 2144 IsIndexHeaderMap ? frontend::IndexHeaderMap : frontend::Angled; 2145 2146 bool IsFramework = A->getOption().matches(OPT_F); 2147 std::string Path = A->getValue(); 2148 2149 if (IsSysrootSpecified && !IsFramework && A->getValue()[0] == '=') { 2150 SmallString<32> Buffer; 2151 llvm::sys::path::append(Buffer, Opts.Sysroot, 2152 llvm::StringRef(A->getValue()).substr(1)); 2153 Path = Buffer.str(); 2154 } 2155 2156 Opts.AddPath(Path, Group, IsFramework, 2157 /*IgnoreSysroot*/ true); 2158 IsIndexHeaderMap = false; 2159 } 2160 2161 // Add -iprefix/-iwithprefix/-iwithprefixbefore options. 2162 StringRef Prefix = ""; // FIXME: This isn't the correct default prefix. 2163 for (const auto *A : 2164 Args.filtered(OPT_iprefix, OPT_iwithprefix, OPT_iwithprefixbefore)) { 2165 if (A->getOption().matches(OPT_iprefix)) 2166 Prefix = A->getValue(); 2167 else if (A->getOption().matches(OPT_iwithprefix)) 2168 Opts.AddPath(Prefix.str() + A->getValue(), frontend::After, false, true); 2169 else 2170 Opts.AddPath(Prefix.str() + A->getValue(), frontend::Angled, false, true); 2171 } 2172 2173 for (const auto *A : Args.filtered(OPT_idirafter)) 2174 Opts.AddPath(A->getValue(), frontend::After, false, true); 2175 for (const auto *A : Args.filtered(OPT_iquote)) 2176 Opts.AddPath(A->getValue(), frontend::Quoted, false, true); 2177 for (const auto *A : Args.filtered(OPT_isystem, OPT_iwithsysroot)) 2178 Opts.AddPath(A->getValue(), frontend::System, false, 2179 !A->getOption().matches(OPT_iwithsysroot)); 2180 for (const auto *A : Args.filtered(OPT_iframework)) 2181 Opts.AddPath(A->getValue(), frontend::System, true, true); 2182 for (const auto *A : Args.filtered(OPT_iframeworkwithsysroot)) 2183 Opts.AddPath(A->getValue(), frontend::System, /*IsFramework=*/true, 2184 /*IgnoreSysRoot=*/false); 2185 2186 // Add the paths for the various language specific isystem flags. 2187 for (const auto *A : Args.filtered(OPT_c_isystem)) 2188 Opts.AddPath(A->getValue(), frontend::CSystem, false, true); 2189 for (const auto *A : Args.filtered(OPT_cxx_isystem)) 2190 Opts.AddPath(A->getValue(), frontend::CXXSystem, false, true); 2191 for (const auto *A : Args.filtered(OPT_objc_isystem)) 2192 Opts.AddPath(A->getValue(), frontend::ObjCSystem, false,true); 2193 for (const auto *A : Args.filtered(OPT_objcxx_isystem)) 2194 Opts.AddPath(A->getValue(), frontend::ObjCXXSystem, false, true); 2195 2196 // Add the internal paths from a driver that detects standard include paths. 2197 for (const auto *A : 2198 Args.filtered(OPT_internal_isystem, OPT_internal_externc_isystem)) { 2199 frontend::IncludeDirGroup Group = frontend::System; 2200 if (A->getOption().matches(OPT_internal_externc_isystem)) 2201 Group = frontend::ExternCSystem; 2202 Opts.AddPath(A->getValue(), Group, false, true); 2203 } 2204 2205 // Add the path prefixes which are implicitly treated as being system headers. 2206 for (const auto *A : 2207 Args.filtered(OPT_system_header_prefix, OPT_no_system_header_prefix)) 2208 Opts.AddSystemHeaderPrefix( 2209 A->getValue(), A->getOption().matches(OPT_system_header_prefix)); 2210 2211 for (const auto *A : Args.filtered(OPT_ivfsoverlay)) 2212 Opts.AddVFSOverlayFile(A->getValue()); 2213 } 2214 2215 void CompilerInvocation::setLangDefaults(LangOptions &Opts, InputKind IK, 2216 const llvm::Triple &T, 2217 PreprocessorOptions &PPOpts, 2218 LangStandard::Kind LangStd) { 2219 // Set some properties which depend solely on the input kind; it would be nice 2220 // to move these to the language standard, and have the driver resolve the 2221 // input kind + language standard. 2222 // 2223 // FIXME: Perhaps a better model would be for a single source file to have 2224 // multiple language standards (C / C++ std, ObjC std, OpenCL std, OpenMP std) 2225 // simultaneously active? 2226 if (IK.getLanguage() == Language::Asm) { 2227 Opts.AsmPreprocessor = 1; 2228 } else if (IK.isObjectiveC()) { 2229 Opts.ObjC = 1; 2230 } 2231 2232 if (LangStd == LangStandard::lang_unspecified) { 2233 // Based on the base language, pick one. 2234 switch (IK.getLanguage()) { 2235 case Language::Unknown: 2236 case Language::LLVM_IR: 2237 llvm_unreachable("Invalid input kind!"); 2238 case Language::OpenCL: 2239 LangStd = LangStandard::lang_opencl10; 2240 break; 2241 case Language::CUDA: 2242 LangStd = LangStandard::lang_cuda; 2243 break; 2244 case Language::Asm: 2245 case Language::C: 2246 #if defined(CLANG_DEFAULT_STD_C) 2247 LangStd = CLANG_DEFAULT_STD_C; 2248 #else 2249 // The PS4 uses C99 as the default C standard. 2250 if (T.isPS4()) 2251 LangStd = LangStandard::lang_gnu99; 2252 else 2253 LangStd = LangStandard::lang_gnu11; 2254 #endif 2255 break; 2256 case Language::ObjC: 2257 #if defined(CLANG_DEFAULT_STD_C) 2258 LangStd = CLANG_DEFAULT_STD_C; 2259 #else 2260 LangStd = LangStandard::lang_gnu11; 2261 #endif 2262 break; 2263 case Language::CXX: 2264 case Language::ObjCXX: 2265 #if defined(CLANG_DEFAULT_STD_CXX) 2266 LangStd = CLANG_DEFAULT_STD_CXX; 2267 #else 2268 LangStd = LangStandard::lang_gnucxx14; 2269 #endif 2270 break; 2271 case Language::RenderScript: 2272 LangStd = LangStandard::lang_c99; 2273 break; 2274 case Language::HIP: 2275 LangStd = LangStandard::lang_hip; 2276 break; 2277 } 2278 } 2279 2280 const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd); 2281 Opts.LineComment = Std.hasLineComments(); 2282 Opts.C99 = Std.isC99(); 2283 Opts.C11 = Std.isC11(); 2284 Opts.C17 = Std.isC17(); 2285 Opts.C2x = Std.isC2x(); 2286 Opts.CPlusPlus = Std.isCPlusPlus(); 2287 Opts.CPlusPlus11 = Std.isCPlusPlus11(); 2288 Opts.CPlusPlus14 = Std.isCPlusPlus14(); 2289 Opts.CPlusPlus17 = Std.isCPlusPlus17(); 2290 Opts.CPlusPlus2a = Std.isCPlusPlus2a(); 2291 Opts.Digraphs = Std.hasDigraphs(); 2292 Opts.GNUMode = Std.isGNUMode(); 2293 Opts.GNUInline = !Opts.C99 && !Opts.CPlusPlus; 2294 Opts.GNUCVersion = 0; 2295 Opts.HexFloats = Std.hasHexFloats(); 2296 Opts.ImplicitInt = Std.hasImplicitInt(); 2297 2298 // Set OpenCL Version. 2299 Opts.OpenCL = Std.isOpenCL(); 2300 if (LangStd == LangStandard::lang_opencl10) 2301 Opts.OpenCLVersion = 100; 2302 else if (LangStd == LangStandard::lang_opencl11) 2303 Opts.OpenCLVersion = 110; 2304 else if (LangStd == LangStandard::lang_opencl12) 2305 Opts.OpenCLVersion = 120; 2306 else if (LangStd == LangStandard::lang_opencl20) 2307 Opts.OpenCLVersion = 200; 2308 else if (LangStd == LangStandard::lang_openclcpp) 2309 Opts.OpenCLCPlusPlusVersion = 100; 2310 2311 // OpenCL has some additional defaults. 2312 if (Opts.OpenCL) { 2313 Opts.AltiVec = 0; 2314 Opts.ZVector = 0; 2315 Opts.setLaxVectorConversions(LangOptions::LaxVectorConversionKind::None); 2316 Opts.setDefaultFPContractMode(LangOptions::FPC_On); 2317 Opts.NativeHalfType = 1; 2318 Opts.NativeHalfArgsAndReturns = 1; 2319 Opts.OpenCLCPlusPlus = Opts.CPlusPlus; 2320 2321 // Include default header file for OpenCL. 2322 if (Opts.IncludeDefaultHeader) { 2323 if (Opts.DeclareOpenCLBuiltins) { 2324 // Only include base header file for builtin types and constants. 2325 PPOpts.Includes.push_back("opencl-c-base.h"); 2326 } else { 2327 PPOpts.Includes.push_back("opencl-c.h"); 2328 } 2329 } 2330 } 2331 2332 Opts.HIP = IK.getLanguage() == Language::HIP; 2333 Opts.CUDA = IK.getLanguage() == Language::CUDA || Opts.HIP; 2334 if (Opts.CUDA) 2335 // Set default FP_CONTRACT to FAST. 2336 Opts.setDefaultFPContractMode(LangOptions::FPC_Fast); 2337 2338 Opts.RenderScript = IK.getLanguage() == Language::RenderScript; 2339 if (Opts.RenderScript) { 2340 Opts.NativeHalfType = 1; 2341 Opts.NativeHalfArgsAndReturns = 1; 2342 } 2343 2344 // OpenCL and C++ both have bool, true, false keywords. 2345 Opts.Bool = Opts.OpenCL || Opts.CPlusPlus; 2346 2347 // OpenCL has half keyword 2348 Opts.Half = Opts.OpenCL; 2349 2350 // C++ has wchar_t keyword. 2351 Opts.WChar = Opts.CPlusPlus; 2352 2353 Opts.GNUKeywords = Opts.GNUMode; 2354 Opts.CXXOperatorNames = Opts.CPlusPlus; 2355 2356 Opts.AlignedAllocation = Opts.CPlusPlus17; 2357 2358 Opts.DollarIdents = !Opts.AsmPreprocessor; 2359 2360 // Enable [[]] attributes in C++11 and C2x by default. 2361 Opts.DoubleSquareBracketAttributes = Opts.CPlusPlus11 || Opts.C2x; 2362 } 2363 2364 /// Attempt to parse a visibility value out of the given argument. 2365 static Visibility parseVisibility(Arg *arg, ArgList &args, 2366 DiagnosticsEngine &diags) { 2367 StringRef value = arg->getValue(); 2368 if (value == "default") { 2369 return DefaultVisibility; 2370 } else if (value == "hidden" || value == "internal") { 2371 return HiddenVisibility; 2372 } else if (value == "protected") { 2373 // FIXME: diagnose if target does not support protected visibility 2374 return ProtectedVisibility; 2375 } 2376 2377 diags.Report(diag::err_drv_invalid_value) 2378 << arg->getAsString(args) << value; 2379 return DefaultVisibility; 2380 } 2381 2382 /// Check if input file kind and language standard are compatible. 2383 static bool IsInputCompatibleWithStandard(InputKind IK, 2384 const LangStandard &S) { 2385 switch (IK.getLanguage()) { 2386 case Language::Unknown: 2387 case Language::LLVM_IR: 2388 llvm_unreachable("should not parse language flags for this input"); 2389 2390 case Language::C: 2391 case Language::ObjC: 2392 case Language::RenderScript: 2393 return S.getLanguage() == Language::C; 2394 2395 case Language::OpenCL: 2396 return S.getLanguage() == Language::OpenCL; 2397 2398 case Language::CXX: 2399 case Language::ObjCXX: 2400 return S.getLanguage() == Language::CXX; 2401 2402 case Language::CUDA: 2403 // FIXME: What -std= values should be permitted for CUDA compilations? 2404 return S.getLanguage() == Language::CUDA || 2405 S.getLanguage() == Language::CXX; 2406 2407 case Language::HIP: 2408 return S.getLanguage() == Language::CXX || S.getLanguage() == Language::HIP; 2409 2410 case Language::Asm: 2411 // Accept (and ignore) all -std= values. 2412 // FIXME: The -std= value is not ignored; it affects the tokenization 2413 // and preprocessing rules if we're preprocessing this asm input. 2414 return true; 2415 } 2416 2417 llvm_unreachable("unexpected input language"); 2418 } 2419 2420 /// Get language name for given input kind. 2421 static const StringRef GetInputKindName(InputKind IK) { 2422 switch (IK.getLanguage()) { 2423 case Language::C: 2424 return "C"; 2425 case Language::ObjC: 2426 return "Objective-C"; 2427 case Language::CXX: 2428 return "C++"; 2429 case Language::ObjCXX: 2430 return "Objective-C++"; 2431 case Language::OpenCL: 2432 return "OpenCL"; 2433 case Language::CUDA: 2434 return "CUDA"; 2435 case Language::RenderScript: 2436 return "RenderScript"; 2437 case Language::HIP: 2438 return "HIP"; 2439 2440 case Language::Asm: 2441 return "Asm"; 2442 case Language::LLVM_IR: 2443 return "LLVM IR"; 2444 2445 case Language::Unknown: 2446 break; 2447 } 2448 llvm_unreachable("unknown input language"); 2449 } 2450 2451 static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK, 2452 const TargetOptions &TargetOpts, 2453 PreprocessorOptions &PPOpts, 2454 DiagnosticsEngine &Diags) { 2455 // FIXME: Cleanup per-file based stuff. 2456 LangStandard::Kind LangStd = LangStandard::lang_unspecified; 2457 if (const Arg *A = Args.getLastArg(OPT_std_EQ)) { 2458 LangStd = LangStandard::getLangKind(A->getValue()); 2459 if (LangStd == LangStandard::lang_unspecified) { 2460 Diags.Report(diag::err_drv_invalid_value) 2461 << A->getAsString(Args) << A->getValue(); 2462 // Report supported standards with short description. 2463 for (unsigned KindValue = 0; 2464 KindValue != LangStandard::lang_unspecified; 2465 ++KindValue) { 2466 const LangStandard &Std = LangStandard::getLangStandardForKind( 2467 static_cast<LangStandard::Kind>(KindValue)); 2468 if (IsInputCompatibleWithStandard(IK, Std)) { 2469 auto Diag = Diags.Report(diag::note_drv_use_standard); 2470 Diag << Std.getName() << Std.getDescription(); 2471 unsigned NumAliases = 0; 2472 #define LANGSTANDARD(id, name, lang, desc, features) 2473 #define LANGSTANDARD_ALIAS(id, alias) \ 2474 if (KindValue == LangStandard::lang_##id) ++NumAliases; 2475 #define LANGSTANDARD_ALIAS_DEPR(id, alias) 2476 #include "clang/Basic/LangStandards.def" 2477 Diag << NumAliases; 2478 #define LANGSTANDARD(id, name, lang, desc, features) 2479 #define LANGSTANDARD_ALIAS(id, alias) \ 2480 if (KindValue == LangStandard::lang_##id) Diag << alias; 2481 #define LANGSTANDARD_ALIAS_DEPR(id, alias) 2482 #include "clang/Basic/LangStandards.def" 2483 } 2484 } 2485 } else { 2486 // Valid standard, check to make sure language and standard are 2487 // compatible. 2488 const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd); 2489 if (!IsInputCompatibleWithStandard(IK, Std)) { 2490 Diags.Report(diag::err_drv_argument_not_allowed_with) 2491 << A->getAsString(Args) << GetInputKindName(IK); 2492 } 2493 } 2494 } 2495 2496 if (Args.hasArg(OPT_fno_dllexport_inlines)) 2497 Opts.DllExportInlines = false; 2498 2499 if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) { 2500 StringRef Name = A->getValue(); 2501 if (Name == "full" || Name == "branch") { 2502 Opts.CFProtectionBranch = 1; 2503 } 2504 } 2505 // -cl-std only applies for OpenCL language standards. 2506 // Override the -std option in this case. 2507 if (const Arg *A = Args.getLastArg(OPT_cl_std_EQ)) { 2508 LangStandard::Kind OpenCLLangStd 2509 = llvm::StringSwitch<LangStandard::Kind>(A->getValue()) 2510 .Cases("cl", "CL", LangStandard::lang_opencl10) 2511 .Cases("cl1.1", "CL1.1", LangStandard::lang_opencl11) 2512 .Cases("cl1.2", "CL1.2", LangStandard::lang_opencl12) 2513 .Cases("cl2.0", "CL2.0", LangStandard::lang_opencl20) 2514 .Cases("clc++", "CLC++", LangStandard::lang_openclcpp) 2515 .Default(LangStandard::lang_unspecified); 2516 2517 if (OpenCLLangStd == LangStandard::lang_unspecified) { 2518 Diags.Report(diag::err_drv_invalid_value) 2519 << A->getAsString(Args) << A->getValue(); 2520 } 2521 else 2522 LangStd = OpenCLLangStd; 2523 } 2524 2525 Opts.IncludeDefaultHeader = Args.hasArg(OPT_finclude_default_header); 2526 Opts.DeclareOpenCLBuiltins = Args.hasArg(OPT_fdeclare_opencl_builtins); 2527 2528 llvm::Triple T(TargetOpts.Triple); 2529 CompilerInvocation::setLangDefaults(Opts, IK, T, PPOpts, LangStd); 2530 2531 // -cl-strict-aliasing needs to emit diagnostic in the case where CL > 1.0. 2532 // This option should be deprecated for CL > 1.0 because 2533 // this option was added for compatibility with OpenCL 1.0. 2534 if (Args.getLastArg(OPT_cl_strict_aliasing) 2535 && Opts.OpenCLVersion > 100) { 2536 Diags.Report(diag::warn_option_invalid_ocl_version) 2537 << Opts.getOpenCLVersionTuple().getAsString() 2538 << Args.getLastArg(OPT_cl_strict_aliasing)->getAsString(Args); 2539 } 2540 2541 // We abuse '-f[no-]gnu-keywords' to force overriding all GNU-extension 2542 // keywords. This behavior is provided by GCC's poorly named '-fasm' flag, 2543 // while a subset (the non-C++ GNU keywords) is provided by GCC's 2544 // '-fgnu-keywords'. Clang conflates the two for simplicity under the single 2545 // name, as it doesn't seem a useful distinction. 2546 Opts.GNUKeywords = Args.hasFlag(OPT_fgnu_keywords, OPT_fno_gnu_keywords, 2547 Opts.GNUKeywords); 2548 2549 Opts.Digraphs = Args.hasFlag(OPT_fdigraphs, OPT_fno_digraphs, Opts.Digraphs); 2550 2551 if (Args.hasArg(OPT_fno_operator_names)) 2552 Opts.CXXOperatorNames = 0; 2553 2554 if (Args.hasArg(OPT_fcuda_is_device)) 2555 Opts.CUDAIsDevice = 1; 2556 2557 if (Args.hasArg(OPT_fcuda_allow_variadic_functions)) 2558 Opts.CUDAAllowVariadicFunctions = 1; 2559 2560 if (Args.hasArg(OPT_fno_cuda_host_device_constexpr)) 2561 Opts.CUDAHostDeviceConstexpr = 0; 2562 2563 if (Opts.CUDAIsDevice && Args.hasArg(OPT_fcuda_approx_transcendentals)) 2564 Opts.CUDADeviceApproxTranscendentals = 1; 2565 2566 Opts.GPURelocatableDeviceCode = Args.hasArg(OPT_fgpu_rdc); 2567 if (Args.hasArg(OPT_fgpu_allow_device_init)) { 2568 if (Opts.HIP) 2569 Opts.GPUAllowDeviceInit = 1; 2570 else 2571 Diags.Report(diag::warn_ignored_hip_only_option) 2572 << Args.getLastArg(OPT_fgpu_allow_device_init)->getAsString(Args); 2573 } 2574 Opts.HIPUseNewLaunchAPI = Args.hasArg(OPT_fhip_new_launch_api); 2575 if (Opts.HIP) 2576 Opts.GPUMaxThreadsPerBlock = getLastArgIntValue( 2577 Args, OPT_gpu_max_threads_per_block_EQ, Opts.GPUMaxThreadsPerBlock); 2578 else if (Args.hasArg(OPT_gpu_max_threads_per_block_EQ)) 2579 Diags.Report(diag::warn_ignored_hip_only_option) 2580 << Args.getLastArg(OPT_gpu_max_threads_per_block_EQ)->getAsString(Args); 2581 2582 if (Opts.ObjC) { 2583 if (Arg *arg = Args.getLastArg(OPT_fobjc_runtime_EQ)) { 2584 StringRef value = arg->getValue(); 2585 if (Opts.ObjCRuntime.tryParse(value)) 2586 Diags.Report(diag::err_drv_unknown_objc_runtime) << value; 2587 } 2588 2589 if (Args.hasArg(OPT_fobjc_gc_only)) 2590 Opts.setGC(LangOptions::GCOnly); 2591 else if (Args.hasArg(OPT_fobjc_gc)) 2592 Opts.setGC(LangOptions::HybridGC); 2593 else if (Args.hasArg(OPT_fobjc_arc)) { 2594 Opts.ObjCAutoRefCount = 1; 2595 if (!Opts.ObjCRuntime.allowsARC()) 2596 Diags.Report(diag::err_arc_unsupported_on_runtime); 2597 } 2598 2599 // ObjCWeakRuntime tracks whether the runtime supports __weak, not 2600 // whether the feature is actually enabled. This is predominantly 2601 // determined by -fobjc-runtime, but we allow it to be overridden 2602 // from the command line for testing purposes. 2603 if (Args.hasArg(OPT_fobjc_runtime_has_weak)) 2604 Opts.ObjCWeakRuntime = 1; 2605 else 2606 Opts.ObjCWeakRuntime = Opts.ObjCRuntime.allowsWeak(); 2607 2608 // ObjCWeak determines whether __weak is actually enabled. 2609 // Note that we allow -fno-objc-weak to disable this even in ARC mode. 2610 if (auto weakArg = Args.getLastArg(OPT_fobjc_weak, OPT_fno_objc_weak)) { 2611 if (!weakArg->getOption().matches(OPT_fobjc_weak)) { 2612 assert(!Opts.ObjCWeak); 2613 } else if (Opts.getGC() != LangOptions::NonGC) { 2614 Diags.Report(diag::err_objc_weak_with_gc); 2615 } else if (!Opts.ObjCWeakRuntime) { 2616 Diags.Report(diag::err_objc_weak_unsupported); 2617 } else { 2618 Opts.ObjCWeak = 1; 2619 } 2620 } else if (Opts.ObjCAutoRefCount) { 2621 Opts.ObjCWeak = Opts.ObjCWeakRuntime; 2622 } 2623 2624 if (Args.hasArg(OPT_fno_objc_infer_related_result_type)) 2625 Opts.ObjCInferRelatedResultType = 0; 2626 2627 if (Args.hasArg(OPT_fobjc_subscripting_legacy_runtime)) 2628 Opts.ObjCSubscriptingLegacyRuntime = 2629 (Opts.ObjCRuntime.getKind() == ObjCRuntime::FragileMacOSX); 2630 } 2631 2632 if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) { 2633 // Check that the version has 1 to 3 components and the minor and patch 2634 // versions fit in two decimal digits. 2635 VersionTuple GNUCVer; 2636 bool Invalid = GNUCVer.tryParse(A->getValue()); 2637 unsigned Major = GNUCVer.getMajor(); 2638 unsigned Minor = GNUCVer.getMinor().getValueOr(0); 2639 unsigned Patch = GNUCVer.getSubminor().getValueOr(0); 2640 if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) { 2641 Diags.Report(diag::err_drv_invalid_value) 2642 << A->getAsString(Args) << A->getValue(); 2643 } 2644 Opts.GNUCVersion = Major * 100 * 100 + Minor * 100 + Patch; 2645 } 2646 2647 if (Args.hasArg(OPT_fgnu89_inline)) { 2648 if (Opts.CPlusPlus) 2649 Diags.Report(diag::err_drv_argument_not_allowed_with) 2650 << "-fgnu89-inline" << GetInputKindName(IK); 2651 else 2652 Opts.GNUInline = 1; 2653 } 2654 2655 if (Args.hasArg(OPT_fapple_kext)) { 2656 if (!Opts.CPlusPlus) 2657 Diags.Report(diag::warn_c_kext); 2658 else 2659 Opts.AppleKext = 1; 2660 } 2661 2662 if (Args.hasArg(OPT_print_ivar_layout)) 2663 Opts.ObjCGCBitmapPrint = 1; 2664 2665 if (Args.hasArg(OPT_fno_constant_cfstrings)) 2666 Opts.NoConstantCFStrings = 1; 2667 if (const auto *A = Args.getLastArg(OPT_fcf_runtime_abi_EQ)) 2668 Opts.CFRuntime = 2669 llvm::StringSwitch<LangOptions::CoreFoundationABI>(A->getValue()) 2670 .Cases("unspecified", "standalone", "objc", 2671 LangOptions::CoreFoundationABI::ObjectiveC) 2672 .Cases("swift", "swift-5.0", 2673 LangOptions::CoreFoundationABI::Swift5_0) 2674 .Case("swift-4.2", LangOptions::CoreFoundationABI::Swift4_2) 2675 .Case("swift-4.1", LangOptions::CoreFoundationABI::Swift4_1) 2676 .Default(LangOptions::CoreFoundationABI::ObjectiveC); 2677 2678 if (Args.hasArg(OPT_fzvector)) 2679 Opts.ZVector = 1; 2680 2681 if (Args.hasArg(OPT_pthread)) 2682 Opts.POSIXThreads = 1; 2683 2684 // The value-visibility mode defaults to "default". 2685 if (Arg *visOpt = Args.getLastArg(OPT_fvisibility)) { 2686 Opts.setValueVisibilityMode(parseVisibility(visOpt, Args, Diags)); 2687 } else { 2688 Opts.setValueVisibilityMode(DefaultVisibility); 2689 } 2690 2691 // The type-visibility mode defaults to the value-visibility mode. 2692 if (Arg *typeVisOpt = Args.getLastArg(OPT_ftype_visibility)) { 2693 Opts.setTypeVisibilityMode(parseVisibility(typeVisOpt, Args, Diags)); 2694 } else { 2695 Opts.setTypeVisibilityMode(Opts.getValueVisibilityMode()); 2696 } 2697 2698 if (Args.hasArg(OPT_fvisibility_inlines_hidden)) 2699 Opts.InlineVisibilityHidden = 1; 2700 2701 if (Args.hasArg(OPT_fvisibility_global_new_delete_hidden)) 2702 Opts.GlobalAllocationFunctionVisibilityHidden = 1; 2703 2704 if (Args.hasArg(OPT_fapply_global_visibility_to_externs)) 2705 Opts.SetVisibilityForExternDecls = 1; 2706 2707 if (Args.hasArg(OPT_ftrapv)) { 2708 Opts.setSignedOverflowBehavior(LangOptions::SOB_Trapping); 2709 // Set the handler, if one is specified. 2710 Opts.OverflowHandler = 2711 Args.getLastArgValue(OPT_ftrapv_handler); 2712 } 2713 else if (Args.hasArg(OPT_fwrapv)) 2714 Opts.setSignedOverflowBehavior(LangOptions::SOB_Defined); 2715 2716 Opts.MSVCCompat = Args.hasArg(OPT_fms_compatibility); 2717 Opts.MicrosoftExt = Opts.MSVCCompat || Args.hasArg(OPT_fms_extensions); 2718 Opts.AsmBlocks = Args.hasArg(OPT_fasm_blocks) || Opts.MicrosoftExt; 2719 Opts.MSCompatibilityVersion = 0; 2720 if (const Arg *A = Args.getLastArg(OPT_fms_compatibility_version)) { 2721 VersionTuple VT; 2722 if (VT.tryParse(A->getValue())) 2723 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) 2724 << A->getValue(); 2725 Opts.MSCompatibilityVersion = VT.getMajor() * 10000000 + 2726 VT.getMinor().getValueOr(0) * 100000 + 2727 VT.getSubminor().getValueOr(0); 2728 } 2729 2730 // Mimicking gcc's behavior, trigraphs are only enabled if -trigraphs 2731 // is specified, or -std is set to a conforming mode. 2732 // Trigraphs are disabled by default in c++1z onwards. 2733 Opts.Trigraphs = !Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus17; 2734 Opts.Trigraphs = 2735 Args.hasFlag(OPT_ftrigraphs, OPT_fno_trigraphs, Opts.Trigraphs); 2736 2737 Opts.DollarIdents = Args.hasFlag(OPT_fdollars_in_identifiers, 2738 OPT_fno_dollars_in_identifiers, 2739 Opts.DollarIdents); 2740 Opts.PascalStrings = Args.hasArg(OPT_fpascal_strings); 2741 Opts.setVtorDispMode( 2742 MSVtorDispMode(getLastArgIntValue(Args, OPT_vtordisp_mode_EQ, 1, Diags))); 2743 Opts.Borland = Args.hasArg(OPT_fborland_extensions); 2744 Opts.WritableStrings = Args.hasArg(OPT_fwritable_strings); 2745 Opts.ConstStrings = Args.hasFlag(OPT_fconst_strings, OPT_fno_const_strings, 2746 Opts.ConstStrings); 2747 if (Arg *A = Args.getLastArg(OPT_flax_vector_conversions_EQ)) { 2748 using LaxKind = LangOptions::LaxVectorConversionKind; 2749 if (auto Kind = llvm::StringSwitch<Optional<LaxKind>>(A->getValue()) 2750 .Case("none", LaxKind::None) 2751 .Case("integer", LaxKind::Integer) 2752 .Case("all", LaxKind::All) 2753 .Default(llvm::None)) 2754 Opts.setLaxVectorConversions(*Kind); 2755 else 2756 Diags.Report(diag::err_drv_invalid_value) 2757 << A->getAsString(Args) << A->getValue(); 2758 } 2759 if (Args.hasArg(OPT_fno_threadsafe_statics)) 2760 Opts.ThreadsafeStatics = 0; 2761 Opts.Exceptions = Args.hasArg(OPT_fexceptions); 2762 Opts.ObjCExceptions = Args.hasArg(OPT_fobjc_exceptions); 2763 Opts.CXXExceptions = Args.hasArg(OPT_fcxx_exceptions); 2764 2765 // -ffixed-point 2766 Opts.FixedPoint = 2767 Args.hasFlag(OPT_ffixed_point, OPT_fno_fixed_point, /*Default=*/false) && 2768 !Opts.CPlusPlus; 2769 Opts.PaddingOnUnsignedFixedPoint = 2770 Args.hasFlag(OPT_fpadding_on_unsigned_fixed_point, 2771 OPT_fno_padding_on_unsigned_fixed_point, 2772 /*Default=*/false) && 2773 Opts.FixedPoint; 2774 2775 // Handle exception personalities 2776 Arg *A = Args.getLastArg( 2777 options::OPT_fsjlj_exceptions, options::OPT_fseh_exceptions, 2778 options::OPT_fdwarf_exceptions, options::OPT_fwasm_exceptions); 2779 if (A) { 2780 const Option &Opt = A->getOption(); 2781 llvm::Triple T(TargetOpts.Triple); 2782 if (T.isWindowsMSVCEnvironment()) 2783 Diags.Report(diag::err_fe_invalid_exception_model) 2784 << Opt.getName() << T.str(); 2785 2786 Opts.SjLjExceptions = Opt.matches(options::OPT_fsjlj_exceptions); 2787 Opts.SEHExceptions = Opt.matches(options::OPT_fseh_exceptions); 2788 Opts.DWARFExceptions = Opt.matches(options::OPT_fdwarf_exceptions); 2789 Opts.WasmExceptions = Opt.matches(options::OPT_fwasm_exceptions); 2790 } 2791 2792 Opts.ExternCNoUnwind = Args.hasArg(OPT_fexternc_nounwind); 2793 Opts.TraditionalCPP = Args.hasArg(OPT_traditional_cpp); 2794 2795 Opts.RTTI = Opts.CPlusPlus && !Args.hasArg(OPT_fno_rtti); 2796 Opts.RTTIData = Opts.RTTI && !Args.hasArg(OPT_fno_rtti_data); 2797 Opts.Blocks = Args.hasArg(OPT_fblocks) || (Opts.OpenCL 2798 && Opts.OpenCLVersion == 200); 2799 Opts.BlocksRuntimeOptional = Args.hasArg(OPT_fblocks_runtime_optional); 2800 Opts.Coroutines = Opts.CPlusPlus2a || Args.hasArg(OPT_fcoroutines_ts); 2801 2802 Opts.ConvergentFunctions = Opts.OpenCL || (Opts.CUDA && Opts.CUDAIsDevice) || 2803 Args.hasArg(OPT_fconvergent_functions); 2804 2805 Opts.DoubleSquareBracketAttributes = 2806 Args.hasFlag(OPT_fdouble_square_bracket_attributes, 2807 OPT_fno_double_square_bracket_attributes, 2808 Opts.DoubleSquareBracketAttributes); 2809 2810 Opts.CPlusPlusModules = Opts.CPlusPlus2a; 2811 Opts.ModulesTS = Args.hasArg(OPT_fmodules_ts); 2812 Opts.Modules = 2813 Args.hasArg(OPT_fmodules) || Opts.ModulesTS || Opts.CPlusPlusModules; 2814 Opts.ModulesStrictDeclUse = Args.hasArg(OPT_fmodules_strict_decluse); 2815 Opts.ModulesDeclUse = 2816 Args.hasArg(OPT_fmodules_decluse) || Opts.ModulesStrictDeclUse; 2817 // FIXME: We only need this in C++ modules / Modules TS if we might textually 2818 // enter a different module (eg, when building a header unit). 2819 Opts.ModulesLocalVisibility = 2820 Args.hasArg(OPT_fmodules_local_submodule_visibility) || Opts.ModulesTS || 2821 Opts.CPlusPlusModules; 2822 Opts.ModulesCodegen = Args.hasArg(OPT_fmodules_codegen); 2823 Opts.ModulesDebugInfo = Args.hasArg(OPT_fmodules_debuginfo); 2824 Opts.ModulesSearchAll = Opts.Modules && 2825 !Args.hasArg(OPT_fno_modules_search_all) && 2826 Args.hasArg(OPT_fmodules_search_all); 2827 Opts.ModulesErrorRecovery = !Args.hasArg(OPT_fno_modules_error_recovery); 2828 Opts.ImplicitModules = !Args.hasArg(OPT_fno_implicit_modules); 2829 Opts.CharIsSigned = Opts.OpenCL || !Args.hasArg(OPT_fno_signed_char); 2830 Opts.WChar = Opts.CPlusPlus && !Args.hasArg(OPT_fno_wchar); 2831 Opts.Char8 = Args.hasFlag(OPT_fchar8__t, OPT_fno_char8__t, Opts.CPlusPlus2a); 2832 if (const Arg *A = Args.getLastArg(OPT_fwchar_type_EQ)) { 2833 Opts.WCharSize = llvm::StringSwitch<unsigned>(A->getValue()) 2834 .Case("char", 1) 2835 .Case("short", 2) 2836 .Case("int", 4) 2837 .Default(0); 2838 if (Opts.WCharSize == 0) 2839 Diags.Report(diag::err_fe_invalid_wchar_type) << A->getValue(); 2840 } 2841 Opts.WCharIsSigned = Args.hasFlag(OPT_fsigned_wchar, OPT_fno_signed_wchar, true); 2842 Opts.ShortEnums = Args.hasArg(OPT_fshort_enums); 2843 Opts.Freestanding = Args.hasArg(OPT_ffreestanding); 2844 Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding; 2845 if (!Opts.NoBuiltin) 2846 getAllNoBuiltinFuncValues(Args, Opts.NoBuiltinFuncs); 2847 Opts.NoMathBuiltin = Args.hasArg(OPT_fno_math_builtin); 2848 Opts.RelaxedTemplateTemplateArgs = 2849 Args.hasArg(OPT_frelaxed_template_template_args); 2850 Opts.SizedDeallocation = Args.hasArg(OPT_fsized_deallocation); 2851 Opts.AlignedAllocation = 2852 Args.hasFlag(OPT_faligned_allocation, OPT_fno_aligned_allocation, 2853 Opts.AlignedAllocation); 2854 Opts.AlignedAllocationUnavailable = 2855 Opts.AlignedAllocation && Args.hasArg(OPT_aligned_alloc_unavailable); 2856 Opts.NewAlignOverride = 2857 getLastArgIntValue(Args, OPT_fnew_alignment_EQ, 0, Diags); 2858 if (Opts.NewAlignOverride && !llvm::isPowerOf2_32(Opts.NewAlignOverride)) { 2859 Arg *A = Args.getLastArg(OPT_fnew_alignment_EQ); 2860 Diags.Report(diag::err_fe_invalid_alignment) << A->getAsString(Args) 2861 << A->getValue(); 2862 Opts.NewAlignOverride = 0; 2863 } 2864 Opts.ConceptSatisfactionCaching = 2865 !Args.hasArg(OPT_fno_concept_satisfaction_caching); 2866 if (Args.hasArg(OPT_fconcepts_ts)) 2867 Diags.Report(diag::warn_fe_concepts_ts_flag); 2868 Opts.HeinousExtensions = Args.hasArg(OPT_fheinous_gnu_extensions); 2869 Opts.AccessControl = !Args.hasArg(OPT_fno_access_control); 2870 Opts.ElideConstructors = !Args.hasArg(OPT_fno_elide_constructors); 2871 Opts.MathErrno = !Opts.OpenCL && Args.hasArg(OPT_fmath_errno); 2872 Opts.InstantiationDepth = 2873 getLastArgIntValue(Args, OPT_ftemplate_depth, 1024, Diags); 2874 Opts.ArrowDepth = 2875 getLastArgIntValue(Args, OPT_foperator_arrow_depth, 256, Diags); 2876 Opts.ConstexprCallDepth = 2877 getLastArgIntValue(Args, OPT_fconstexpr_depth, 512, Diags); 2878 Opts.ConstexprStepLimit = 2879 getLastArgIntValue(Args, OPT_fconstexpr_steps, 1048576, Diags); 2880 Opts.EnableNewConstInterp = 2881 Args.hasArg(OPT_fexperimental_new_constant_interpreter); 2882 Opts.BracketDepth = getLastArgIntValue(Args, OPT_fbracket_depth, 256, Diags); 2883 Opts.DelayedTemplateParsing = Args.hasArg(OPT_fdelayed_template_parsing); 2884 Opts.NumLargeByValueCopy = 2885 getLastArgIntValue(Args, OPT_Wlarge_by_value_copy_EQ, 0, Diags); 2886 Opts.MSBitfields = Args.hasArg(OPT_mms_bitfields); 2887 Opts.ObjCConstantStringClass = 2888 Args.getLastArgValue(OPT_fconstant_string_class); 2889 Opts.ObjCDefaultSynthProperties = 2890 !Args.hasArg(OPT_disable_objc_default_synthesize_properties); 2891 Opts.EncodeExtendedBlockSig = 2892 Args.hasArg(OPT_fencode_extended_block_signature); 2893 Opts.EmitAllDecls = Args.hasArg(OPT_femit_all_decls); 2894 Opts.PackStruct = getLastArgIntValue(Args, OPT_fpack_struct_EQ, 0, Diags); 2895 Opts.MaxTypeAlign = getLastArgIntValue(Args, OPT_fmax_type_align_EQ, 0, Diags); 2896 Opts.AlignDouble = Args.hasArg(OPT_malign_double); 2897 Opts.LongDoubleSize = Args.hasArg(OPT_mlong_double_128) 2898 ? 128 2899 : Args.hasArg(OPT_mlong_double_64) ? 64 : 0; 2900 Opts.PPCIEEELongDouble = Args.hasArg(OPT_mabi_EQ_ieeelongdouble); 2901 Opts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags); 2902 Opts.ROPI = Args.hasArg(OPT_fropi); 2903 Opts.RWPI = Args.hasArg(OPT_frwpi); 2904 Opts.PIE = Args.hasArg(OPT_pic_is_pie); 2905 Opts.Static = Args.hasArg(OPT_static_define); 2906 Opts.DumpRecordLayoutsSimple = Args.hasArg(OPT_fdump_record_layouts_simple); 2907 Opts.DumpRecordLayouts = Opts.DumpRecordLayoutsSimple 2908 || Args.hasArg(OPT_fdump_record_layouts); 2909 Opts.DumpVTableLayouts = Args.hasArg(OPT_fdump_vtable_layouts); 2910 Opts.SpellChecking = !Args.hasArg(OPT_fno_spell_checking); 2911 Opts.NoBitFieldTypeAlign = Args.hasArg(OPT_fno_bitfield_type_align); 2912 Opts.SinglePrecisionConstants = Args.hasArg(OPT_cl_single_precision_constant); 2913 Opts.FastRelaxedMath = Args.hasArg(OPT_cl_fast_relaxed_math); 2914 Opts.HexagonQdsp6Compat = Args.hasArg(OPT_mqdsp6_compat); 2915 Opts.FakeAddressSpaceMap = Args.hasArg(OPT_ffake_address_space_map); 2916 Opts.ParseUnknownAnytype = Args.hasArg(OPT_funknown_anytype); 2917 Opts.DebuggerSupport = Args.hasArg(OPT_fdebugger_support); 2918 Opts.DebuggerCastResultToId = Args.hasArg(OPT_fdebugger_cast_result_to_id); 2919 Opts.DebuggerObjCLiteral = Args.hasArg(OPT_fdebugger_objc_literal); 2920 Opts.ApplePragmaPack = Args.hasArg(OPT_fapple_pragma_pack); 2921 Opts.ModuleName = Args.getLastArgValue(OPT_fmodule_name_EQ); 2922 Opts.CurrentModule = Opts.ModuleName; 2923 Opts.AppExt = Args.hasArg(OPT_fapplication_extension); 2924 Opts.ModuleFeatures = Args.getAllArgValues(OPT_fmodule_feature); 2925 llvm::sort(Opts.ModuleFeatures); 2926 Opts.NativeHalfType |= Args.hasArg(OPT_fnative_half_type); 2927 Opts.NativeHalfArgsAndReturns |= Args.hasArg(OPT_fnative_half_arguments_and_returns); 2928 // Enable HalfArgsAndReturns if present in Args or if NativeHalfArgsAndReturns 2929 // is enabled. 2930 Opts.HalfArgsAndReturns = Args.hasArg(OPT_fallow_half_arguments_and_returns) 2931 | Opts.NativeHalfArgsAndReturns; 2932 Opts.GNUAsm = !Args.hasArg(OPT_fno_gnu_inline_asm); 2933 Opts.Cmse = Args.hasArg(OPT_mcmse); // Armv8-M Security Extensions 2934 2935 // __declspec is enabled by default for the PS4 by the driver, and also 2936 // enabled for Microsoft Extensions or Borland Extensions, here. 2937 // 2938 // FIXME: __declspec is also currently enabled for CUDA, but isn't really a 2939 // CUDA extension. However, it is required for supporting 2940 // __clang_cuda_builtin_vars.h, which uses __declspec(property). Once that has 2941 // been rewritten in terms of something more generic, remove the Opts.CUDA 2942 // term here. 2943 Opts.DeclSpecKeyword = 2944 Args.hasFlag(OPT_fdeclspec, OPT_fno_declspec, 2945 (Opts.MicrosoftExt || Opts.Borland || Opts.CUDA)); 2946 2947 if (Arg *A = Args.getLastArg(OPT_faddress_space_map_mangling_EQ)) { 2948 switch (llvm::StringSwitch<unsigned>(A->getValue()) 2949 .Case("target", LangOptions::ASMM_Target) 2950 .Case("no", LangOptions::ASMM_Off) 2951 .Case("yes", LangOptions::ASMM_On) 2952 .Default(255)) { 2953 default: 2954 Diags.Report(diag::err_drv_invalid_value) 2955 << "-faddress-space-map-mangling=" << A->getValue(); 2956 break; 2957 case LangOptions::ASMM_Target: 2958 Opts.setAddressSpaceMapMangling(LangOptions::ASMM_Target); 2959 break; 2960 case LangOptions::ASMM_On: 2961 Opts.setAddressSpaceMapMangling(LangOptions::ASMM_On); 2962 break; 2963 case LangOptions::ASMM_Off: 2964 Opts.setAddressSpaceMapMangling(LangOptions::ASMM_Off); 2965 break; 2966 } 2967 } 2968 2969 if (Arg *A = Args.getLastArg(OPT_fms_memptr_rep_EQ)) { 2970 LangOptions::PragmaMSPointersToMembersKind InheritanceModel = 2971 llvm::StringSwitch<LangOptions::PragmaMSPointersToMembersKind>( 2972 A->getValue()) 2973 .Case("single", 2974 LangOptions::PPTMK_FullGeneralitySingleInheritance) 2975 .Case("multiple", 2976 LangOptions::PPTMK_FullGeneralityMultipleInheritance) 2977 .Case("virtual", 2978 LangOptions::PPTMK_FullGeneralityVirtualInheritance) 2979 .Default(LangOptions::PPTMK_BestCase); 2980 if (InheritanceModel == LangOptions::PPTMK_BestCase) 2981 Diags.Report(diag::err_drv_invalid_value) 2982 << "-fms-memptr-rep=" << A->getValue(); 2983 2984 Opts.setMSPointerToMemberRepresentationMethod(InheritanceModel); 2985 } 2986 2987 // Check for MS default calling conventions being specified. 2988 if (Arg *A = Args.getLastArg(OPT_fdefault_calling_conv_EQ)) { 2989 LangOptions::DefaultCallingConvention DefaultCC = 2990 llvm::StringSwitch<LangOptions::DefaultCallingConvention>(A->getValue()) 2991 .Case("cdecl", LangOptions::DCC_CDecl) 2992 .Case("fastcall", LangOptions::DCC_FastCall) 2993 .Case("stdcall", LangOptions::DCC_StdCall) 2994 .Case("vectorcall", LangOptions::DCC_VectorCall) 2995 .Case("regcall", LangOptions::DCC_RegCall) 2996 .Default(LangOptions::DCC_None); 2997 if (DefaultCC == LangOptions::DCC_None) 2998 Diags.Report(diag::err_drv_invalid_value) 2999 << "-fdefault-calling-conv=" << A->getValue(); 3000 3001 llvm::Triple T(TargetOpts.Triple); 3002 llvm::Triple::ArchType Arch = T.getArch(); 3003 bool emitError = (DefaultCC == LangOptions::DCC_FastCall || 3004 DefaultCC == LangOptions::DCC_StdCall) && 3005 Arch != llvm::Triple::x86; 3006 emitError |= (DefaultCC == LangOptions::DCC_VectorCall || 3007 DefaultCC == LangOptions::DCC_RegCall) && 3008 !T.isX86(); 3009 if (emitError) 3010 Diags.Report(diag::err_drv_argument_not_allowed_with) 3011 << A->getSpelling() << T.getTriple(); 3012 else 3013 Opts.setDefaultCallingConv(DefaultCC); 3014 } 3015 3016 // -mrtd option 3017 if (Arg *A = Args.getLastArg(OPT_mrtd)) { 3018 if (Opts.getDefaultCallingConv() != LangOptions::DCC_None) 3019 Diags.Report(diag::err_drv_argument_not_allowed_with) 3020 << A->getSpelling() << "-fdefault-calling-conv"; 3021 else { 3022 llvm::Triple T(TargetOpts.Triple); 3023 if (T.getArch() != llvm::Triple::x86) 3024 Diags.Report(diag::err_drv_argument_not_allowed_with) 3025 << A->getSpelling() << T.getTriple(); 3026 else 3027 Opts.setDefaultCallingConv(LangOptions::DCC_StdCall); 3028 } 3029 } 3030 3031 // Check if -fopenmp is specified and set default version to 4.5. 3032 Opts.OpenMP = Args.hasArg(options::OPT_fopenmp) ? 45 : 0; 3033 // Check if -fopenmp-simd is specified. 3034 bool IsSimdSpecified = 3035 Args.hasFlag(options::OPT_fopenmp_simd, options::OPT_fno_openmp_simd, 3036 /*Default=*/false); 3037 Opts.OpenMPSimd = !Opts.OpenMP && IsSimdSpecified; 3038 Opts.OpenMPUseTLS = 3039 Opts.OpenMP && !Args.hasArg(options::OPT_fnoopenmp_use_tls); 3040 Opts.OpenMPIsDevice = 3041 Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_is_device); 3042 Opts.OpenMPIRBuilder = 3043 Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_enable_irbuilder); 3044 bool IsTargetSpecified = 3045 Opts.OpenMPIsDevice || Args.hasArg(options::OPT_fopenmp_targets_EQ); 3046 3047 if (Opts.OpenMP || Opts.OpenMPSimd) { 3048 if (int Version = getLastArgIntValue( 3049 Args, OPT_fopenmp_version_EQ, 3050 (IsSimdSpecified || IsTargetSpecified) ? 45 : Opts.OpenMP, Diags)) 3051 Opts.OpenMP = Version; 3052 else if (IsSimdSpecified || IsTargetSpecified) 3053 Opts.OpenMP = 45; 3054 // Provide diagnostic when a given target is not expected to be an OpenMP 3055 // device or host. 3056 if (!Opts.OpenMPIsDevice) { 3057 switch (T.getArch()) { 3058 default: 3059 break; 3060 // Add unsupported host targets here: 3061 case llvm::Triple::nvptx: 3062 case llvm::Triple::nvptx64: 3063 Diags.Report(diag::err_drv_omp_host_target_not_supported) 3064 << TargetOpts.Triple; 3065 break; 3066 } 3067 } 3068 } 3069 3070 // Set the flag to prevent the implementation from emitting device exception 3071 // handling code for those requiring so. 3072 if ((Opts.OpenMPIsDevice && T.isNVPTX()) || Opts.OpenCLCPlusPlus) { 3073 Opts.Exceptions = 0; 3074 Opts.CXXExceptions = 0; 3075 } 3076 if (Opts.OpenMPIsDevice && T.isNVPTX()) { 3077 Opts.OpenMPCUDANumSMs = 3078 getLastArgIntValue(Args, options::OPT_fopenmp_cuda_number_of_sm_EQ, 3079 Opts.OpenMPCUDANumSMs, Diags); 3080 Opts.OpenMPCUDABlocksPerSM = 3081 getLastArgIntValue(Args, options::OPT_fopenmp_cuda_blocks_per_sm_EQ, 3082 Opts.OpenMPCUDABlocksPerSM, Diags); 3083 Opts.OpenMPCUDAReductionBufNum = getLastArgIntValue( 3084 Args, options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ, 3085 Opts.OpenMPCUDAReductionBufNum, Diags); 3086 } 3087 3088 // Prevent auto-widening the representation of loop counters during an 3089 // OpenMP collapse clause. 3090 Opts.OpenMPOptimisticCollapse = 3091 Args.hasArg(options::OPT_fopenmp_optimistic_collapse) ? 1 : 0; 3092 3093 // Get the OpenMP target triples if any. 3094 if (Arg *A = Args.getLastArg(options::OPT_fopenmp_targets_EQ)) { 3095 3096 for (unsigned i = 0; i < A->getNumValues(); ++i) { 3097 llvm::Triple TT(A->getValue(i)); 3098 3099 if (TT.getArch() == llvm::Triple::UnknownArch || 3100 !(TT.getArch() == llvm::Triple::aarch64 || 3101 TT.getArch() == llvm::Triple::ppc || 3102 TT.getArch() == llvm::Triple::ppc64 || 3103 TT.getArch() == llvm::Triple::ppc64le || 3104 TT.getArch() == llvm::Triple::nvptx || 3105 TT.getArch() == llvm::Triple::nvptx64 || 3106 TT.getArch() == llvm::Triple::x86 || 3107 TT.getArch() == llvm::Triple::x86_64)) 3108 Diags.Report(diag::err_drv_invalid_omp_target) << A->getValue(i); 3109 else 3110 Opts.OMPTargetTriples.push_back(TT); 3111 } 3112 } 3113 3114 // Get OpenMP host file path if any and report if a non existent file is 3115 // found 3116 if (Arg *A = Args.getLastArg(options::OPT_fopenmp_host_ir_file_path)) { 3117 Opts.OMPHostIRFile = A->getValue(); 3118 if (!llvm::sys::fs::exists(Opts.OMPHostIRFile)) 3119 Diags.Report(diag::err_drv_omp_host_ir_file_not_found) 3120 << Opts.OMPHostIRFile; 3121 } 3122 3123 Opts.SYCLIsDevice = Args.hasArg(options::OPT_fsycl_is_device); 3124 3125 // Set CUDA mode for OpenMP target NVPTX if specified in options 3126 Opts.OpenMPCUDAMode = Opts.OpenMPIsDevice && T.isNVPTX() && 3127 Args.hasArg(options::OPT_fopenmp_cuda_mode); 3128 3129 // Set CUDA mode for OpenMP target NVPTX if specified in options 3130 Opts.OpenMPCUDAForceFullRuntime = 3131 Opts.OpenMPIsDevice && T.isNVPTX() && 3132 Args.hasArg(options::OPT_fopenmp_cuda_force_full_runtime); 3133 3134 // Record whether the __DEPRECATED define was requested. 3135 Opts.Deprecated = Args.hasFlag(OPT_fdeprecated_macro, 3136 OPT_fno_deprecated_macro, 3137 Opts.Deprecated); 3138 3139 // FIXME: Eliminate this dependency. 3140 unsigned Opt = getOptimizationLevel(Args, IK, Diags), 3141 OptSize = getOptimizationLevelSize(Args); 3142 Opts.Optimize = Opt != 0; 3143 Opts.OptimizeSize = OptSize != 0; 3144 3145 // This is the __NO_INLINE__ define, which just depends on things like the 3146 // optimization level and -fno-inline, not actually whether the backend has 3147 // inlining enabled. 3148 Opts.NoInlineDefine = !Opts.Optimize; 3149 if (Arg *InlineArg = Args.getLastArg( 3150 options::OPT_finline_functions, options::OPT_finline_hint_functions, 3151 options::OPT_fno_inline_functions, options::OPT_fno_inline)) 3152 if (InlineArg->getOption().matches(options::OPT_fno_inline)) 3153 Opts.NoInlineDefine = true; 3154 3155 Opts.FastMath = Args.hasArg(OPT_ffast_math) || 3156 Args.hasArg(OPT_cl_fast_relaxed_math); 3157 Opts.FiniteMathOnly = Args.hasArg(OPT_ffinite_math_only) || 3158 Args.hasArg(OPT_cl_finite_math_only) || 3159 Args.hasArg(OPT_cl_fast_relaxed_math); 3160 Opts.UnsafeFPMath = Args.hasArg(OPT_menable_unsafe_fp_math) || 3161 Args.hasArg(OPT_cl_unsafe_math_optimizations) || 3162 Args.hasArg(OPT_cl_fast_relaxed_math); 3163 3164 if (Arg *A = Args.getLastArg(OPT_ffp_contract)) { 3165 StringRef Val = A->getValue(); 3166 if (Val == "fast") 3167 Opts.setDefaultFPContractMode(LangOptions::FPC_Fast); 3168 else if (Val == "on") 3169 Opts.setDefaultFPContractMode(LangOptions::FPC_On); 3170 else if (Val == "off") 3171 Opts.setDefaultFPContractMode(LangOptions::FPC_Off); 3172 else 3173 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val; 3174 } 3175 3176 LangOptions::FPRoundingModeKind FPRM = LangOptions::FPR_ToNearest; 3177 if (Args.hasArg(OPT_frounding_math)) { 3178 FPRM = LangOptions::FPR_Dynamic; 3179 } 3180 Opts.setFPRoundingMode(FPRM); 3181 3182 if (Args.hasArg(OPT_ftrapping_math)) { 3183 Opts.setFPExceptionMode(LangOptions::FPE_Strict); 3184 } 3185 3186 if (Args.hasArg(OPT_fno_trapping_math)) { 3187 Opts.setFPExceptionMode(LangOptions::FPE_Ignore); 3188 } 3189 3190 LangOptions::FPExceptionModeKind FPEB = LangOptions::FPE_Ignore; 3191 if (Arg *A = Args.getLastArg(OPT_ffp_exception_behavior_EQ)) { 3192 StringRef Val = A->getValue(); 3193 if (Val.equals("ignore")) 3194 FPEB = LangOptions::FPE_Ignore; 3195 else if (Val.equals("maytrap")) 3196 FPEB = LangOptions::FPE_MayTrap; 3197 else if (Val.equals("strict")) 3198 FPEB = LangOptions::FPE_Strict; 3199 else 3200 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val; 3201 } 3202 Opts.setFPExceptionMode(FPEB); 3203 3204 Opts.RetainCommentsFromSystemHeaders = 3205 Args.hasArg(OPT_fretain_comments_from_system_headers); 3206 3207 unsigned SSP = getLastArgIntValue(Args, OPT_stack_protector, 0, Diags); 3208 switch (SSP) { 3209 default: 3210 Diags.Report(diag::err_drv_invalid_value) 3211 << Args.getLastArg(OPT_stack_protector)->getAsString(Args) << SSP; 3212 break; 3213 case 0: Opts.setStackProtector(LangOptions::SSPOff); break; 3214 case 1: Opts.setStackProtector(LangOptions::SSPOn); break; 3215 case 2: Opts.setStackProtector(LangOptions::SSPStrong); break; 3216 case 3: Opts.setStackProtector(LangOptions::SSPReq); break; 3217 } 3218 3219 if (Arg *A = Args.getLastArg(OPT_ftrivial_auto_var_init)) { 3220 StringRef Val = A->getValue(); 3221 if (Val == "uninitialized") 3222 Opts.setTrivialAutoVarInit( 3223 LangOptions::TrivialAutoVarInitKind::Uninitialized); 3224 else if (Val == "zero") 3225 Opts.setTrivialAutoVarInit(LangOptions::TrivialAutoVarInitKind::Zero); 3226 else if (Val == "pattern") 3227 Opts.setTrivialAutoVarInit(LangOptions::TrivialAutoVarInitKind::Pattern); 3228 else 3229 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val; 3230 } 3231 3232 // Parse -fsanitize= arguments. 3233 parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ), 3234 Diags, Opts.Sanitize); 3235 // -fsanitize-address-field-padding=N has to be a LangOpt, parse it here. 3236 Opts.SanitizeAddressFieldPadding = 3237 getLastArgIntValue(Args, OPT_fsanitize_address_field_padding, 0, Diags); 3238 Opts.SanitizerBlacklistFiles = Args.getAllArgValues(OPT_fsanitize_blacklist); 3239 std::vector<std::string> systemBlacklists = 3240 Args.getAllArgValues(OPT_fsanitize_system_blacklist); 3241 Opts.SanitizerBlacklistFiles.insert(Opts.SanitizerBlacklistFiles.end(), 3242 systemBlacklists.begin(), 3243 systemBlacklists.end()); 3244 3245 // -fxray-instrument 3246 Opts.XRayInstrument = 3247 Args.hasFlag(OPT_fxray_instrument, OPT_fnoxray_instrument, false); 3248 3249 // -fxray-always-emit-customevents 3250 Opts.XRayAlwaysEmitCustomEvents = 3251 Args.hasFlag(OPT_fxray_always_emit_customevents, 3252 OPT_fnoxray_always_emit_customevents, false); 3253 3254 // -fxray-always-emit-typedevents 3255 Opts.XRayAlwaysEmitTypedEvents = 3256 Args.hasFlag(OPT_fxray_always_emit_typedevents, 3257 OPT_fnoxray_always_emit_customevents, false); 3258 3259 // -fxray-{always,never}-instrument= filenames. 3260 Opts.XRayAlwaysInstrumentFiles = 3261 Args.getAllArgValues(OPT_fxray_always_instrument); 3262 Opts.XRayNeverInstrumentFiles = 3263 Args.getAllArgValues(OPT_fxray_never_instrument); 3264 Opts.XRayAttrListFiles = Args.getAllArgValues(OPT_fxray_attr_list); 3265 3266 // -fforce-emit-vtables 3267 Opts.ForceEmitVTables = Args.hasArg(OPT_fforce_emit_vtables); 3268 3269 // -fallow-editor-placeholders 3270 Opts.AllowEditorPlaceholders = Args.hasArg(OPT_fallow_editor_placeholders); 3271 3272 Opts.RegisterStaticDestructors = !Args.hasArg(OPT_fno_cxx_static_destructors); 3273 3274 if (Arg *A = Args.getLastArg(OPT_fclang_abi_compat_EQ)) { 3275 Opts.setClangABICompat(LangOptions::ClangABI::Latest); 3276 3277 StringRef Ver = A->getValue(); 3278 std::pair<StringRef, StringRef> VerParts = Ver.split('.'); 3279 unsigned Major, Minor = 0; 3280 3281 // Check the version number is valid: either 3.x (0 <= x <= 9) or 3282 // y or y.0 (4 <= y <= current version). 3283 if (!VerParts.first.startswith("0") && 3284 !VerParts.first.getAsInteger(10, Major) && 3285 3 <= Major && Major <= CLANG_VERSION_MAJOR && 3286 (Major == 3 ? VerParts.second.size() == 1 && 3287 !VerParts.second.getAsInteger(10, Minor) 3288 : VerParts.first.size() == Ver.size() || 3289 VerParts.second == "0")) { 3290 // Got a valid version number. 3291 if (Major == 3 && Minor <= 8) 3292 Opts.setClangABICompat(LangOptions::ClangABI::Ver3_8); 3293 else if (Major <= 4) 3294 Opts.setClangABICompat(LangOptions::ClangABI::Ver4); 3295 else if (Major <= 6) 3296 Opts.setClangABICompat(LangOptions::ClangABI::Ver6); 3297 else if (Major <= 7) 3298 Opts.setClangABICompat(LangOptions::ClangABI::Ver7); 3299 else if (Major <= 9) 3300 Opts.setClangABICompat(LangOptions::ClangABI::Ver9); 3301 } else if (Ver != "latest") { 3302 Diags.Report(diag::err_drv_invalid_value) 3303 << A->getAsString(Args) << A->getValue(); 3304 } 3305 } 3306 3307 Opts.CompleteMemberPointers = Args.hasArg(OPT_fcomplete_member_pointers); 3308 Opts.BuildingPCHWithObjectFile = Args.hasArg(OPT_building_pch_with_obj); 3309 } 3310 3311 static bool isStrictlyPreprocessorAction(frontend::ActionKind Action) { 3312 switch (Action) { 3313 case frontend::ASTDeclList: 3314 case frontend::ASTDump: 3315 case frontend::ASTPrint: 3316 case frontend::ASTView: 3317 case frontend::EmitAssembly: 3318 case frontend::EmitBC: 3319 case frontend::EmitHTML: 3320 case frontend::EmitLLVM: 3321 case frontend::EmitLLVMOnly: 3322 case frontend::EmitCodeGenOnly: 3323 case frontend::EmitObj: 3324 case frontend::FixIt: 3325 case frontend::GenerateModule: 3326 case frontend::GenerateModuleInterface: 3327 case frontend::GenerateHeaderModule: 3328 case frontend::GeneratePCH: 3329 case frontend::GenerateInterfaceIfsExpV1: 3330 case frontend::ParseSyntaxOnly: 3331 case frontend::ModuleFileInfo: 3332 case frontend::VerifyPCH: 3333 case frontend::PluginAction: 3334 case frontend::RewriteObjC: 3335 case frontend::RewriteTest: 3336 case frontend::RunAnalysis: 3337 case frontend::TemplightDump: 3338 case frontend::MigrateSource: 3339 return false; 3340 3341 case frontend::DumpCompilerOptions: 3342 case frontend::DumpRawTokens: 3343 case frontend::DumpTokens: 3344 case frontend::InitOnly: 3345 case frontend::PrintPreamble: 3346 case frontend::PrintPreprocessedInput: 3347 case frontend::RewriteMacros: 3348 case frontend::RunPreprocessorOnly: 3349 case frontend::PrintDependencyDirectivesSourceMinimizerOutput: 3350 return true; 3351 } 3352 llvm_unreachable("invalid frontend action"); 3353 } 3354 3355 static void ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args, 3356 DiagnosticsEngine &Diags, 3357 frontend::ActionKind Action) { 3358 Opts.ImplicitPCHInclude = Args.getLastArgValue(OPT_include_pch); 3359 Opts.PCHWithHdrStop = Args.hasArg(OPT_pch_through_hdrstop_create) || 3360 Args.hasArg(OPT_pch_through_hdrstop_use); 3361 Opts.PCHWithHdrStopCreate = Args.hasArg(OPT_pch_through_hdrstop_create); 3362 Opts.PCHThroughHeader = Args.getLastArgValue(OPT_pch_through_header_EQ); 3363 Opts.UsePredefines = !Args.hasArg(OPT_undef); 3364 Opts.DetailedRecord = Args.hasArg(OPT_detailed_preprocessing_record); 3365 Opts.DisablePCHValidation = Args.hasArg(OPT_fno_validate_pch); 3366 Opts.AllowPCHWithCompilerErrors = Args.hasArg(OPT_fallow_pch_with_errors); 3367 3368 Opts.DumpDeserializedPCHDecls = Args.hasArg(OPT_dump_deserialized_pch_decls); 3369 for (const auto *A : Args.filtered(OPT_error_on_deserialized_pch_decl)) 3370 Opts.DeserializedPCHDeclsToErrorOn.insert(A->getValue()); 3371 3372 for (const auto &A : Args.getAllArgValues(OPT_fmacro_prefix_map_EQ)) 3373 Opts.MacroPrefixMap.insert(StringRef(A).split('=')); 3374 3375 if (const Arg *A = Args.getLastArg(OPT_preamble_bytes_EQ)) { 3376 StringRef Value(A->getValue()); 3377 size_t Comma = Value.find(','); 3378 unsigned Bytes = 0; 3379 unsigned EndOfLine = 0; 3380 3381 if (Comma == StringRef::npos || 3382 Value.substr(0, Comma).getAsInteger(10, Bytes) || 3383 Value.substr(Comma + 1).getAsInteger(10, EndOfLine)) 3384 Diags.Report(diag::err_drv_preamble_format); 3385 else { 3386 Opts.PrecompiledPreambleBytes.first = Bytes; 3387 Opts.PrecompiledPreambleBytes.second = (EndOfLine != 0); 3388 } 3389 } 3390 3391 // Add the __CET__ macro if a CFProtection option is set. 3392 if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) { 3393 StringRef Name = A->getValue(); 3394 if (Name == "branch") 3395 Opts.addMacroDef("__CET__=1"); 3396 else if (Name == "return") 3397 Opts.addMacroDef("__CET__=2"); 3398 else if (Name == "full") 3399 Opts.addMacroDef("__CET__=3"); 3400 } 3401 3402 // Add macros from the command line. 3403 for (const auto *A : Args.filtered(OPT_D, OPT_U)) { 3404 if (A->getOption().matches(OPT_D)) 3405 Opts.addMacroDef(A->getValue()); 3406 else 3407 Opts.addMacroUndef(A->getValue()); 3408 } 3409 3410 Opts.MacroIncludes = Args.getAllArgValues(OPT_imacros); 3411 3412 // Add the ordered list of -includes. 3413 for (const auto *A : Args.filtered(OPT_include)) 3414 Opts.Includes.emplace_back(A->getValue()); 3415 3416 for (const auto *A : Args.filtered(OPT_chain_include)) 3417 Opts.ChainedIncludes.emplace_back(A->getValue()); 3418 3419 for (const auto *A : Args.filtered(OPT_remap_file)) { 3420 std::pair<StringRef, StringRef> Split = StringRef(A->getValue()).split(';'); 3421 3422 if (Split.second.empty()) { 3423 Diags.Report(diag::err_drv_invalid_remap_file) << A->getAsString(Args); 3424 continue; 3425 } 3426 3427 Opts.addRemappedFile(Split.first, Split.second); 3428 } 3429 3430 if (Arg *A = Args.getLastArg(OPT_fobjc_arc_cxxlib_EQ)) { 3431 StringRef Name = A->getValue(); 3432 unsigned Library = llvm::StringSwitch<unsigned>(Name) 3433 .Case("libc++", ARCXX_libcxx) 3434 .Case("libstdc++", ARCXX_libstdcxx) 3435 .Case("none", ARCXX_nolib) 3436 .Default(~0U); 3437 if (Library == ~0U) 3438 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name; 3439 else 3440 Opts.ObjCXXARCStandardLibrary = (ObjCXXARCStandardLibraryKind)Library; 3441 } 3442 3443 // Always avoid lexing editor placeholders when we're just running the 3444 // preprocessor as we never want to emit the 3445 // "editor placeholder in source file" error in PP only mode. 3446 if (isStrictlyPreprocessorAction(Action)) 3447 Opts.LexEditorPlaceholders = false; 3448 3449 Opts.SetUpStaticAnalyzer = Args.hasArg(OPT_setup_static_analyzer); 3450 Opts.DisablePragmaDebugCrash = Args.hasArg(OPT_disable_pragma_debug_crash); 3451 } 3452 3453 static void ParsePreprocessorOutputArgs(PreprocessorOutputOptions &Opts, 3454 ArgList &Args, 3455 frontend::ActionKind Action) { 3456 if (isStrictlyPreprocessorAction(Action)) 3457 Opts.ShowCPP = !Args.hasArg(OPT_dM); 3458 else 3459 Opts.ShowCPP = 0; 3460 3461 Opts.ShowComments = Args.hasArg(OPT_C); 3462 Opts.ShowLineMarkers = !Args.hasArg(OPT_P); 3463 Opts.ShowMacroComments = Args.hasArg(OPT_CC); 3464 Opts.ShowMacros = Args.hasArg(OPT_dM) || Args.hasArg(OPT_dD); 3465 Opts.ShowIncludeDirectives = Args.hasArg(OPT_dI); 3466 Opts.RewriteIncludes = Args.hasArg(OPT_frewrite_includes); 3467 Opts.RewriteImports = Args.hasArg(OPT_frewrite_imports); 3468 Opts.UseLineDirectives = Args.hasArg(OPT_fuse_line_directives); 3469 } 3470 3471 static void ParseTargetArgs(TargetOptions &Opts, ArgList &Args, 3472 DiagnosticsEngine &Diags) { 3473 Opts.CodeModel = getCodeModel(Args, Diags); 3474 Opts.ABI = Args.getLastArgValue(OPT_target_abi); 3475 if (Arg *A = Args.getLastArg(OPT_meabi)) { 3476 StringRef Value = A->getValue(); 3477 llvm::EABI EABIVersion = llvm::StringSwitch<llvm::EABI>(Value) 3478 .Case("default", llvm::EABI::Default) 3479 .Case("4", llvm::EABI::EABI4) 3480 .Case("5", llvm::EABI::EABI5) 3481 .Case("gnu", llvm::EABI::GNU) 3482 .Default(llvm::EABI::Unknown); 3483 if (EABIVersion == llvm::EABI::Unknown) 3484 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) 3485 << Value; 3486 else 3487 Opts.EABIVersion = EABIVersion; 3488 } 3489 Opts.CPU = Args.getLastArgValue(OPT_target_cpu); 3490 Opts.FPMath = Args.getLastArgValue(OPT_mfpmath); 3491 Opts.FeaturesAsWritten = Args.getAllArgValues(OPT_target_feature); 3492 Opts.LinkerVersion = Args.getLastArgValue(OPT_target_linker_version); 3493 Opts.Triple = Args.getLastArgValue(OPT_triple); 3494 // Use the default target triple if unspecified. 3495 if (Opts.Triple.empty()) 3496 Opts.Triple = llvm::sys::getDefaultTargetTriple(); 3497 Opts.Triple = llvm::Triple::normalize(Opts.Triple); 3498 Opts.OpenCLExtensionsAsWritten = Args.getAllArgValues(OPT_cl_ext_EQ); 3499 Opts.ForceEnableInt128 = Args.hasArg(OPT_fforce_enable_int128); 3500 Opts.NVPTXUseShortPointers = Args.hasFlag( 3501 options::OPT_fcuda_short_ptr, options::OPT_fno_cuda_short_ptr, false); 3502 if (Arg *A = Args.getLastArg(options::OPT_target_sdk_version_EQ)) { 3503 llvm::VersionTuple Version; 3504 if (Version.tryParse(A->getValue())) 3505 Diags.Report(diag::err_drv_invalid_value) 3506 << A->getAsString(Args) << A->getValue(); 3507 else 3508 Opts.SDKVersion = Version; 3509 } 3510 } 3511 3512 bool CompilerInvocation::CreateFromArgs(CompilerInvocation &Res, 3513 ArrayRef<const char *> CommandLineArgs, 3514 DiagnosticsEngine &Diags) { 3515 bool Success = true; 3516 3517 // Parse the arguments. 3518 const OptTable &Opts = getDriverOptTable(); 3519 const unsigned IncludedFlagsBitmask = options::CC1Option; 3520 unsigned MissingArgIndex, MissingArgCount; 3521 InputArgList Args = Opts.ParseArgs(CommandLineArgs, MissingArgIndex, 3522 MissingArgCount, IncludedFlagsBitmask); 3523 LangOptions &LangOpts = *Res.getLangOpts(); 3524 3525 // Check for missing argument error. 3526 if (MissingArgCount) { 3527 Diags.Report(diag::err_drv_missing_argument) 3528 << Args.getArgString(MissingArgIndex) << MissingArgCount; 3529 Success = false; 3530 } 3531 3532 // Issue errors on unknown arguments. 3533 for (const auto *A : Args.filtered(OPT_UNKNOWN)) { 3534 auto ArgString = A->getAsString(Args); 3535 std::string Nearest; 3536 if (Opts.findNearest(ArgString, Nearest, IncludedFlagsBitmask) > 1) 3537 Diags.Report(diag::err_drv_unknown_argument) << ArgString; 3538 else 3539 Diags.Report(diag::err_drv_unknown_argument_with_suggestion) 3540 << ArgString << Nearest; 3541 Success = false; 3542 } 3543 3544 Success &= ParseAnalyzerArgs(*Res.getAnalyzerOpts(), Args, Diags); 3545 Success &= ParseMigratorArgs(Res.getMigratorOpts(), Args); 3546 ParseDependencyOutputArgs(Res.getDependencyOutputOpts(), Args); 3547 if (!Res.getDependencyOutputOpts().OutputFile.empty() && 3548 Res.getDependencyOutputOpts().Targets.empty()) { 3549 Diags.Report(diag::err_fe_dependency_file_requires_MT); 3550 Success = false; 3551 } 3552 Success &= 3553 ParseDiagnosticArgs(Res.getDiagnosticOpts(), Args, &Diags, 3554 false /*DefaultDiagColor*/, false /*DefaultShowOpt*/); 3555 ParseCommentArgs(LangOpts.CommentOpts, Args); 3556 ParseFileSystemArgs(Res.getFileSystemOpts(), Args); 3557 // FIXME: We shouldn't have to pass the DashX option around here 3558 InputKind DashX = ParseFrontendArgs(Res.getFrontendOpts(), Args, Diags, 3559 LangOpts.IsHeaderFile); 3560 ParseTargetArgs(Res.getTargetOpts(), Args, Diags); 3561 Success &= ParseCodeGenArgs(Res.getCodeGenOpts(), Args, DashX, Diags, 3562 Res.getTargetOpts(), Res.getFrontendOpts()); 3563 ParseHeaderSearchArgs(Res.getHeaderSearchOpts(), Args, 3564 Res.getFileSystemOpts().WorkingDir); 3565 llvm::Triple T(Res.getTargetOpts().Triple); 3566 if (DashX.getFormat() == InputKind::Precompiled || 3567 DashX.getLanguage() == Language::LLVM_IR) { 3568 // ObjCAAutoRefCount and Sanitize LangOpts are used to setup the 3569 // PassManager in BackendUtil.cpp. They need to be initializd no matter 3570 // what the input type is. 3571 if (Args.hasArg(OPT_fobjc_arc)) 3572 LangOpts.ObjCAutoRefCount = 1; 3573 // PIClevel and PIELevel are needed during code generation and this should be 3574 // set regardless of the input type. 3575 LangOpts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags); 3576 LangOpts.PIE = Args.hasArg(OPT_pic_is_pie); 3577 parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ), 3578 Diags, LangOpts.Sanitize); 3579 } else { 3580 // Other LangOpts are only initialized when the input is not AST or LLVM IR. 3581 // FIXME: Should we really be calling this for an Language::Asm input? 3582 ParseLangArgs(LangOpts, Args, DashX, Res.getTargetOpts(), 3583 Res.getPreprocessorOpts(), Diags); 3584 if (Res.getFrontendOpts().ProgramAction == frontend::RewriteObjC) 3585 LangOpts.ObjCExceptions = 1; 3586 if (T.isOSDarwin() && DashX.isPreprocessed()) { 3587 // Supress the darwin-specific 'stdlibcxx-not-found' diagnostic for 3588 // preprocessed input as we don't expect it to be used with -std=libc++ 3589 // anyway. 3590 Res.getDiagnosticOpts().Warnings.push_back("no-stdlibcxx-not-found"); 3591 } 3592 } 3593 3594 if (Diags.isIgnored(diag::warn_profile_data_misexpect, SourceLocation())) 3595 Res.FrontendOpts.LLVMArgs.push_back("-pgo-warn-misexpect"); 3596 3597 LangOpts.FunctionAlignment = 3598 getLastArgIntValue(Args, OPT_function_alignment, 0, Diags); 3599 3600 if (LangOpts.CUDA) { 3601 // During CUDA device-side compilation, the aux triple is the 3602 // triple used for host compilation. 3603 if (LangOpts.CUDAIsDevice) 3604 Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple; 3605 } 3606 3607 // Set the triple of the host for OpenMP device compile. 3608 if (LangOpts.OpenMPIsDevice) 3609 Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple; 3610 3611 // FIXME: Override value name discarding when asan or msan is used because the 3612 // backend passes depend on the name of the alloca in order to print out 3613 // names. 3614 Res.getCodeGenOpts().DiscardValueNames &= 3615 !LangOpts.Sanitize.has(SanitizerKind::Address) && 3616 !LangOpts.Sanitize.has(SanitizerKind::KernelAddress) && 3617 !LangOpts.Sanitize.has(SanitizerKind::Memory) && 3618 !LangOpts.Sanitize.has(SanitizerKind::KernelMemory); 3619 3620 ParsePreprocessorArgs(Res.getPreprocessorOpts(), Args, Diags, 3621 Res.getFrontendOpts().ProgramAction); 3622 ParsePreprocessorOutputArgs(Res.getPreprocessorOutputOpts(), Args, 3623 Res.getFrontendOpts().ProgramAction); 3624 3625 // Turn on -Wspir-compat for SPIR target. 3626 if (T.isSPIR()) 3627 Res.getDiagnosticOpts().Warnings.push_back("spir-compat"); 3628 3629 // If sanitizer is enabled, disable OPT_ffine_grained_bitfield_accesses. 3630 if (Res.getCodeGenOpts().FineGrainedBitfieldAccesses && 3631 !Res.getLangOpts()->Sanitize.empty()) { 3632 Res.getCodeGenOpts().FineGrainedBitfieldAccesses = false; 3633 Diags.Report(diag::warn_drv_fine_grained_bitfield_accesses_ignored); 3634 } 3635 return Success; 3636 } 3637 3638 std::string CompilerInvocation::getModuleHash() const { 3639 // Note: For QoI reasons, the things we use as a hash here should all be 3640 // dumped via the -module-info flag. 3641 using llvm::hash_code; 3642 using llvm::hash_value; 3643 using llvm::hash_combine; 3644 using llvm::hash_combine_range; 3645 3646 // Start the signature with the compiler version. 3647 // FIXME: We'd rather use something more cryptographically sound than 3648 // CityHash, but this will do for now. 3649 hash_code code = hash_value(getClangFullRepositoryVersion()); 3650 3651 // Extend the signature with the language options 3652 #define LANGOPT(Name, Bits, Default, Description) \ 3653 code = hash_combine(code, LangOpts->Name); 3654 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \ 3655 code = hash_combine(code, static_cast<unsigned>(LangOpts->get##Name())); 3656 #define BENIGN_LANGOPT(Name, Bits, Default, Description) 3657 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description) 3658 #include "clang/Basic/LangOptions.def" 3659 3660 for (StringRef Feature : LangOpts->ModuleFeatures) 3661 code = hash_combine(code, Feature); 3662 3663 // Extend the signature with the target options. 3664 code = hash_combine(code, TargetOpts->Triple, TargetOpts->CPU, 3665 TargetOpts->ABI); 3666 for (const auto &FeatureAsWritten : TargetOpts->FeaturesAsWritten) 3667 code = hash_combine(code, FeatureAsWritten); 3668 3669 // Extend the signature with preprocessor options. 3670 const PreprocessorOptions &ppOpts = getPreprocessorOpts(); 3671 const HeaderSearchOptions &hsOpts = getHeaderSearchOpts(); 3672 code = hash_combine(code, ppOpts.UsePredefines, ppOpts.DetailedRecord); 3673 3674 for (const auto &I : getPreprocessorOpts().Macros) { 3675 // If we're supposed to ignore this macro for the purposes of modules, 3676 // don't put it into the hash. 3677 if (!hsOpts.ModulesIgnoreMacros.empty()) { 3678 // Check whether we're ignoring this macro. 3679 StringRef MacroDef = I.first; 3680 if (hsOpts.ModulesIgnoreMacros.count( 3681 llvm::CachedHashString(MacroDef.split('=').first))) 3682 continue; 3683 } 3684 3685 code = hash_combine(code, I.first, I.second); 3686 } 3687 3688 // Extend the signature with the sysroot and other header search options. 3689 code = hash_combine(code, hsOpts.Sysroot, 3690 hsOpts.ModuleFormat, 3691 hsOpts.UseDebugInfo, 3692 hsOpts.UseBuiltinIncludes, 3693 hsOpts.UseStandardSystemIncludes, 3694 hsOpts.UseStandardCXXIncludes, 3695 hsOpts.UseLibcxx, 3696 hsOpts.ModulesValidateDiagnosticOptions); 3697 code = hash_combine(code, hsOpts.ResourceDir); 3698 3699 if (hsOpts.ModulesStrictContextHash) { 3700 hash_code SHPC = hash_combine_range(hsOpts.SystemHeaderPrefixes.begin(), 3701 hsOpts.SystemHeaderPrefixes.end()); 3702 hash_code UEC = hash_combine_range(hsOpts.UserEntries.begin(), 3703 hsOpts.UserEntries.end()); 3704 code = hash_combine(code, hsOpts.SystemHeaderPrefixes.size(), SHPC, 3705 hsOpts.UserEntries.size(), UEC); 3706 3707 const DiagnosticOptions &diagOpts = getDiagnosticOpts(); 3708 #define DIAGOPT(Name, Bits, Default) \ 3709 code = hash_combine(code, diagOpts.Name); 3710 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \ 3711 code = hash_combine(code, diagOpts.get##Name()); 3712 #include "clang/Basic/DiagnosticOptions.def" 3713 #undef DIAGOPT 3714 #undef ENUM_DIAGOPT 3715 } 3716 3717 // Extend the signature with the user build path. 3718 code = hash_combine(code, hsOpts.ModuleUserBuildPath); 3719 3720 // Extend the signature with the module file extensions. 3721 const FrontendOptions &frontendOpts = getFrontendOpts(); 3722 for (const auto &ext : frontendOpts.ModuleFileExtensions) { 3723 code = ext->hashExtension(code); 3724 } 3725 3726 // When compiling with -gmodules, also hash -fdebug-prefix-map as it 3727 // affects the debug info in the PCM. 3728 if (getCodeGenOpts().DebugTypeExtRefs) 3729 for (const auto &KeyValue : getCodeGenOpts().DebugPrefixMap) 3730 code = hash_combine(code, KeyValue.first, KeyValue.second); 3731 3732 // Extend the signature with the enabled sanitizers, if at least one is 3733 // enabled. Sanitizers which cannot affect AST generation aren't hashed. 3734 SanitizerSet SanHash = LangOpts->Sanitize; 3735 SanHash.clear(getPPTransparentSanitizers()); 3736 if (!SanHash.empty()) 3737 code = hash_combine(code, SanHash.Mask); 3738 3739 return llvm::APInt(64, code).toString(36, /*Signed=*/false); 3740 } 3741 3742 namespace clang { 3743 3744 IntrusiveRefCntPtr<llvm::vfs::FileSystem> 3745 createVFSFromCompilerInvocation(const CompilerInvocation &CI, 3746 DiagnosticsEngine &Diags) { 3747 return createVFSFromCompilerInvocation(CI, Diags, 3748 llvm::vfs::getRealFileSystem()); 3749 } 3750 3751 IntrusiveRefCntPtr<llvm::vfs::FileSystem> createVFSFromCompilerInvocation( 3752 const CompilerInvocation &CI, DiagnosticsEngine &Diags, 3753 IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS) { 3754 if (CI.getHeaderSearchOpts().VFSOverlayFiles.empty()) 3755 return BaseFS; 3756 3757 IntrusiveRefCntPtr<llvm::vfs::FileSystem> Result = BaseFS; 3758 // earlier vfs files are on the bottom 3759 for (const auto &File : CI.getHeaderSearchOpts().VFSOverlayFiles) { 3760 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer = 3761 Result->getBufferForFile(File); 3762 if (!Buffer) { 3763 Diags.Report(diag::err_missing_vfs_overlay_file) << File; 3764 continue; 3765 } 3766 3767 IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS = llvm::vfs::getVFSFromYAML( 3768 std::move(Buffer.get()), /*DiagHandler*/ nullptr, File, 3769 /*DiagContext*/ nullptr, Result); 3770 if (!FS) { 3771 Diags.Report(diag::err_invalid_vfs_overlay) << File; 3772 continue; 3773 } 3774 3775 Result = FS; 3776 } 3777 return Result; 3778 } 3779 3780 } // namespace clang 3781