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