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/DiagnosticDriver.h" 18 #include "clang/Basic/DiagnosticOptions.h" 19 #include "clang/Basic/FileSystemOptions.h" 20 #include "clang/Basic/LLVM.h" 21 #include "clang/Basic/LangOptions.h" 22 #include "clang/Basic/LangStandard.h" 23 #include "clang/Basic/ObjCRuntime.h" 24 #include "clang/Basic/Sanitizers.h" 25 #include "clang/Basic/SourceLocation.h" 26 #include "clang/Basic/TargetOptions.h" 27 #include "clang/Basic/Version.h" 28 #include "clang/Basic/Visibility.h" 29 #include "clang/Basic/XRayInstr.h" 30 #include "clang/Config/config.h" 31 #include "clang/Driver/Driver.h" 32 #include "clang/Driver/DriverDiagnostic.h" 33 #include "clang/Driver/Options.h" 34 #include "clang/Frontend/CommandLineSourceLoc.h" 35 #include "clang/Frontend/DependencyOutputOptions.h" 36 #include "clang/Frontend/FrontendDiagnostic.h" 37 #include "clang/Frontend/FrontendOptions.h" 38 #include "clang/Frontend/FrontendPluginRegistry.h" 39 #include "clang/Frontend/MigratorOptions.h" 40 #include "clang/Frontend/PreprocessorOutputOptions.h" 41 #include "clang/Frontend/Utils.h" 42 #include "clang/Lex/HeaderSearchOptions.h" 43 #include "clang/Lex/PreprocessorOptions.h" 44 #include "clang/Sema/CodeCompleteOptions.h" 45 #include "clang/Serialization/ASTBitCodes.h" 46 #include "clang/Serialization/ModuleFileExtension.h" 47 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h" 48 #include "llvm/ADT/APInt.h" 49 #include "llvm/ADT/ArrayRef.h" 50 #include "llvm/ADT/CachedHashString.h" 51 #include "llvm/ADT/FloatingPointMode.h" 52 #include "llvm/ADT/Hashing.h" 53 #include "llvm/ADT/None.h" 54 #include "llvm/ADT/Optional.h" 55 #include "llvm/ADT/SmallString.h" 56 #include "llvm/ADT/SmallVector.h" 57 #include "llvm/ADT/StringRef.h" 58 #include "llvm/ADT/StringSwitch.h" 59 #include "llvm/ADT/Triple.h" 60 #include "llvm/ADT/Twine.h" 61 #include "llvm/Config/llvm-config.h" 62 #include "llvm/IR/DebugInfoMetadata.h" 63 #include "llvm/Linker/Linker.h" 64 #include "llvm/MC/MCTargetOptions.h" 65 #include "llvm/Option/Arg.h" 66 #include "llvm/Option/ArgList.h" 67 #include "llvm/Option/OptSpecifier.h" 68 #include "llvm/Option/OptTable.h" 69 #include "llvm/Option/Option.h" 70 #include "llvm/ProfileData/InstrProfReader.h" 71 #include "llvm/Remarks/HotnessThresholdParser.h" 72 #include "llvm/Support/CodeGen.h" 73 #include "llvm/Support/Compiler.h" 74 #include "llvm/Support/Error.h" 75 #include "llvm/Support/ErrorHandling.h" 76 #include "llvm/Support/ErrorOr.h" 77 #include "llvm/Support/FileSystem.h" 78 #include "llvm/Support/Host.h" 79 #include "llvm/Support/MathExtras.h" 80 #include "llvm/Support/MemoryBuffer.h" 81 #include "llvm/Support/Path.h" 82 #include "llvm/Support/Process.h" 83 #include "llvm/Support/Regex.h" 84 #include "llvm/Support/VersionTuple.h" 85 #include "llvm/Support/VirtualFileSystem.h" 86 #include "llvm/Support/raw_ostream.h" 87 #include "llvm/Target/TargetOptions.h" 88 #include <algorithm> 89 #include <atomic> 90 #include <cassert> 91 #include <cstddef> 92 #include <cstring> 93 #include <memory> 94 #include <string> 95 #include <tuple> 96 #include <type_traits> 97 #include <utility> 98 #include <vector> 99 100 using namespace clang; 101 using namespace driver; 102 using namespace options; 103 using namespace llvm::opt; 104 105 //===----------------------------------------------------------------------===// 106 // Initialization. 107 //===----------------------------------------------------------------------===// 108 109 CompilerInvocationBase::CompilerInvocationBase() 110 : LangOpts(new LangOptions()), TargetOpts(new TargetOptions()), 111 DiagnosticOpts(new DiagnosticOptions()), 112 HeaderSearchOpts(new HeaderSearchOptions()), 113 PreprocessorOpts(new PreprocessorOptions()) {} 114 115 CompilerInvocationBase::CompilerInvocationBase(const CompilerInvocationBase &X) 116 : LangOpts(new LangOptions(*X.getLangOpts())), 117 TargetOpts(new TargetOptions(X.getTargetOpts())), 118 DiagnosticOpts(new DiagnosticOptions(X.getDiagnosticOpts())), 119 HeaderSearchOpts(new HeaderSearchOptions(X.getHeaderSearchOpts())), 120 PreprocessorOpts(new PreprocessorOptions(X.getPreprocessorOpts())) {} 121 122 CompilerInvocationBase::~CompilerInvocationBase() = default; 123 124 //===----------------------------------------------------------------------===// 125 // Normalizers 126 //===----------------------------------------------------------------------===// 127 128 #define SIMPLE_ENUM_VALUE_TABLE 129 #include "clang/Driver/Options.inc" 130 #undef SIMPLE_ENUM_VALUE_TABLE 131 132 static llvm::Optional<bool> normalizeSimpleFlag(OptSpecifier Opt, 133 unsigned TableIndex, 134 const ArgList &Args, 135 DiagnosticsEngine &Diags) { 136 if (Args.hasArg(Opt)) 137 return true; 138 return None; 139 } 140 141 static Optional<bool> normalizeSimpleNegativeFlag(OptSpecifier Opt, unsigned, 142 const ArgList &Args, 143 DiagnosticsEngine &) { 144 if (Args.hasArg(Opt)) 145 return false; 146 return None; 147 } 148 149 /// The tblgen-erated code passes in a fifth parameter of an arbitrary type, but 150 /// denormalizeSimpleFlags never looks at it. Avoid bloating compile-time with 151 /// unnecessary template instantiations and just ignore it with a variadic 152 /// argument. 153 static void denormalizeSimpleFlag(SmallVectorImpl<const char *> &Args, 154 const char *Spelling, 155 CompilerInvocation::StringAllocator, 156 Option::OptionClass, unsigned, /*T*/...) { 157 Args.push_back(Spelling); 158 } 159 160 template <typename T> static constexpr bool is_uint64_t_convertible() { 161 return !std::is_same<T, uint64_t>::value && 162 llvm::is_integral_or_enum<T>::value; 163 } 164 165 template <typename T, 166 std::enable_if_t<!is_uint64_t_convertible<T>(), bool> = false> 167 static auto makeFlagToValueNormalizer(T Value) { 168 return [Value](OptSpecifier Opt, unsigned, const ArgList &Args, 169 DiagnosticsEngine &) -> Optional<T> { 170 if (Args.hasArg(Opt)) 171 return Value; 172 return None; 173 }; 174 } 175 176 template <typename T, 177 std::enable_if_t<is_uint64_t_convertible<T>(), bool> = false> 178 static auto makeFlagToValueNormalizer(T Value) { 179 return makeFlagToValueNormalizer(uint64_t(Value)); 180 } 181 182 static auto makeBooleanOptionNormalizer(bool Value, bool OtherValue, 183 OptSpecifier OtherOpt) { 184 return [Value, OtherValue, OtherOpt](OptSpecifier Opt, unsigned, 185 const ArgList &Args, 186 DiagnosticsEngine &) -> Optional<bool> { 187 if (const Arg *A = Args.getLastArg(Opt, OtherOpt)) { 188 return A->getOption().matches(Opt) ? Value : OtherValue; 189 } 190 return None; 191 }; 192 } 193 194 static auto makeBooleanOptionDenormalizer(bool Value) { 195 return [Value](SmallVectorImpl<const char *> &Args, const char *Spelling, 196 CompilerInvocation::StringAllocator, Option::OptionClass, 197 unsigned, bool KeyPath) { 198 if (KeyPath == Value) 199 Args.push_back(Spelling); 200 }; 201 } 202 203 static void denormalizeStringImpl(SmallVectorImpl<const char *> &Args, 204 const char *Spelling, 205 CompilerInvocation::StringAllocator SA, 206 Option::OptionClass OptClass, unsigned, 207 Twine Value) { 208 switch (OptClass) { 209 case Option::SeparateClass: 210 case Option::JoinedOrSeparateClass: 211 Args.push_back(Spelling); 212 Args.push_back(SA(Value)); 213 break; 214 case Option::JoinedClass: 215 Args.push_back(SA(Twine(Spelling) + Value)); 216 break; 217 default: 218 llvm_unreachable("Cannot denormalize an option with option class " 219 "incompatible with string denormalization."); 220 } 221 } 222 223 template <typename T> 224 static void 225 denormalizeString(SmallVectorImpl<const char *> &Args, const char *Spelling, 226 CompilerInvocation::StringAllocator SA, 227 Option::OptionClass OptClass, unsigned TableIndex, T Value) { 228 denormalizeStringImpl(Args, Spelling, SA, OptClass, TableIndex, Twine(Value)); 229 } 230 231 static Optional<SimpleEnumValue> 232 findValueTableByName(const SimpleEnumValueTable &Table, StringRef Name) { 233 for (int I = 0, E = Table.Size; I != E; ++I) 234 if (Name == Table.Table[I].Name) 235 return Table.Table[I]; 236 237 return None; 238 } 239 240 static Optional<SimpleEnumValue> 241 findValueTableByValue(const SimpleEnumValueTable &Table, unsigned Value) { 242 for (int I = 0, E = Table.Size; I != E; ++I) 243 if (Value == Table.Table[I].Value) 244 return Table.Table[I]; 245 246 return None; 247 } 248 249 static llvm::Optional<unsigned> normalizeSimpleEnum(OptSpecifier Opt, 250 unsigned TableIndex, 251 const ArgList &Args, 252 DiagnosticsEngine &Diags) { 253 assert(TableIndex < SimpleEnumValueTablesSize); 254 const SimpleEnumValueTable &Table = SimpleEnumValueTables[TableIndex]; 255 256 auto *Arg = Args.getLastArg(Opt); 257 if (!Arg) 258 return None; 259 260 StringRef ArgValue = Arg->getValue(); 261 if (auto MaybeEnumVal = findValueTableByName(Table, ArgValue)) 262 return MaybeEnumVal->Value; 263 264 Diags.Report(diag::err_drv_invalid_value) 265 << Arg->getAsString(Args) << ArgValue; 266 return None; 267 } 268 269 static void denormalizeSimpleEnumImpl(SmallVectorImpl<const char *> &Args, 270 const char *Spelling, 271 CompilerInvocation::StringAllocator SA, 272 Option::OptionClass OptClass, 273 unsigned TableIndex, unsigned Value) { 274 assert(TableIndex < SimpleEnumValueTablesSize); 275 const SimpleEnumValueTable &Table = SimpleEnumValueTables[TableIndex]; 276 if (auto MaybeEnumVal = findValueTableByValue(Table, Value)) { 277 denormalizeString(Args, Spelling, SA, OptClass, TableIndex, 278 MaybeEnumVal->Name); 279 } else { 280 llvm_unreachable("The simple enum value was not correctly defined in " 281 "the tablegen option description"); 282 } 283 } 284 285 template <typename T> 286 static void denormalizeSimpleEnum(SmallVectorImpl<const char *> &Args, 287 const char *Spelling, 288 CompilerInvocation::StringAllocator SA, 289 Option::OptionClass OptClass, 290 unsigned TableIndex, T Value) { 291 return denormalizeSimpleEnumImpl(Args, Spelling, SA, OptClass, TableIndex, 292 static_cast<unsigned>(Value)); 293 } 294 295 static Optional<std::string> normalizeString(OptSpecifier Opt, int TableIndex, 296 const ArgList &Args, 297 DiagnosticsEngine &Diags) { 298 auto *Arg = Args.getLastArg(Opt); 299 if (!Arg) 300 return None; 301 return std::string(Arg->getValue()); 302 } 303 304 template <typename IntTy> 305 static Optional<IntTy> normalizeStringIntegral(OptSpecifier Opt, int, 306 const ArgList &Args, 307 DiagnosticsEngine &Diags) { 308 auto *Arg = Args.getLastArg(Opt); 309 if (!Arg) 310 return None; 311 IntTy Res; 312 if (StringRef(Arg->getValue()).getAsInteger(0, Res)) { 313 Diags.Report(diag::err_drv_invalid_int_value) 314 << Arg->getAsString(Args) << Arg->getValue(); 315 } 316 return Res; 317 } 318 319 static Optional<std::vector<std::string>> 320 normalizeStringVector(OptSpecifier Opt, int, const ArgList &Args, 321 DiagnosticsEngine &) { 322 return Args.getAllArgValues(Opt); 323 } 324 325 static void denormalizeStringVector(SmallVectorImpl<const char *> &Args, 326 const char *Spelling, 327 CompilerInvocation::StringAllocator SA, 328 Option::OptionClass OptClass, 329 unsigned TableIndex, 330 const std::vector<std::string> &Values) { 331 for (const std::string &Value : Values) { 332 denormalizeString(Args, Spelling, SA, OptClass, TableIndex, Value); 333 } 334 } 335 336 static Optional<std::string> normalizeTriple(OptSpecifier Opt, int TableIndex, 337 const ArgList &Args, 338 DiagnosticsEngine &Diags) { 339 auto *Arg = Args.getLastArg(Opt); 340 if (!Arg) 341 return None; 342 return llvm::Triple::normalize(Arg->getValue()); 343 } 344 345 template <typename T, typename U> 346 static T mergeForwardValue(T KeyPath, U Value) { 347 return static_cast<T>(Value); 348 } 349 350 template <typename T, typename U> static T mergeMaskValue(T KeyPath, U Value) { 351 return KeyPath | Value; 352 } 353 354 template <typename T> static T extractForwardValue(T KeyPath) { 355 return KeyPath; 356 } 357 358 template <typename T, typename U, U Value> 359 static T extractMaskValue(T KeyPath) { 360 return KeyPath & Value; 361 } 362 363 static void FixupInvocation(CompilerInvocation &Invocation, 364 DiagnosticsEngine &Diags, 365 const InputArgList &Args) { 366 LangOptions &LangOpts = *Invocation.getLangOpts(); 367 DiagnosticOptions &DiagOpts = Invocation.getDiagnosticOpts(); 368 CodeGenOptions &CodeGenOpts = Invocation.getCodeGenOpts(); 369 TargetOptions &TargetOpts = Invocation.getTargetOpts(); 370 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts(); 371 CodeGenOpts.XRayInstrumentFunctions = LangOpts.XRayInstrument; 372 CodeGenOpts.XRayAlwaysEmitCustomEvents = LangOpts.XRayAlwaysEmitCustomEvents; 373 CodeGenOpts.XRayAlwaysEmitTypedEvents = LangOpts.XRayAlwaysEmitTypedEvents; 374 CodeGenOpts.DisableFree = FrontendOpts.DisableFree; 375 FrontendOpts.GenerateGlobalModuleIndex = FrontendOpts.UseGlobalModuleIndex; 376 377 LangOpts.ForceEmitVTables = CodeGenOpts.ForceEmitVTables; 378 LangOpts.SpeculativeLoadHardening = CodeGenOpts.SpeculativeLoadHardening; 379 LangOpts.CurrentModule = LangOpts.ModuleName; 380 381 llvm::sys::Process::UseANSIEscapeCodes(DiagOpts.UseANSIEscapeCodes); 382 383 llvm::Triple T(TargetOpts.Triple); 384 llvm::Triple::ArchType Arch = T.getArch(); 385 386 if (LangOpts.getExceptionHandling() != llvm::ExceptionHandling::None && 387 T.isWindowsMSVCEnvironment()) 388 Diags.Report(diag::err_fe_invalid_exception_model) 389 << static_cast<unsigned>(LangOpts.getExceptionHandling()) << T.str(); 390 391 if (LangOpts.AppleKext && !LangOpts.CPlusPlus) 392 Diags.Report(diag::warn_c_kext); 393 394 if (LangOpts.NewAlignOverride && 395 !llvm::isPowerOf2_32(LangOpts.NewAlignOverride)) { 396 Arg *A = Args.getLastArg(OPT_fnew_alignment_EQ); 397 Diags.Report(diag::err_fe_invalid_alignment) 398 << A->getAsString(Args) << A->getValue(); 399 LangOpts.NewAlignOverride = 0; 400 } 401 402 if (Arg *A = Args.getLastArg(OPT_fdefault_calling_conv_EQ)) { 403 auto DefaultCC = LangOpts.getDefaultCallingConv(); 404 405 bool emitError = (DefaultCC == LangOptions::DCC_FastCall || 406 DefaultCC == LangOptions::DCC_StdCall) && 407 Arch != llvm::Triple::x86; 408 emitError |= (DefaultCC == LangOptions::DCC_VectorCall || 409 DefaultCC == LangOptions::DCC_RegCall) && 410 !T.isX86(); 411 if (emitError) 412 Diags.Report(diag::err_drv_argument_not_allowed_with) 413 << A->getSpelling() << T.getTriple(); 414 } 415 416 if (!CodeGenOpts.ProfileRemappingFile.empty() && CodeGenOpts.LegacyPassManager) 417 Diags.Report(diag::err_drv_argument_only_allowed_with) 418 << Args.getLastArg(OPT_fprofile_remapping_file_EQ)->getAsString(Args) 419 << "-fno-legacy-pass-manager"; 420 } 421 422 //===----------------------------------------------------------------------===// 423 // Deserialization (from args) 424 //===----------------------------------------------------------------------===// 425 426 static unsigned getOptimizationLevel(ArgList &Args, InputKind IK, 427 DiagnosticsEngine &Diags) { 428 unsigned DefaultOpt = llvm::CodeGenOpt::None; 429 if (IK.getLanguage() == Language::OpenCL && !Args.hasArg(OPT_cl_opt_disable)) 430 DefaultOpt = llvm::CodeGenOpt::Default; 431 432 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) { 433 if (A->getOption().matches(options::OPT_O0)) 434 return llvm::CodeGenOpt::None; 435 436 if (A->getOption().matches(options::OPT_Ofast)) 437 return llvm::CodeGenOpt::Aggressive; 438 439 assert(A->getOption().matches(options::OPT_O)); 440 441 StringRef S(A->getValue()); 442 if (S == "s" || S == "z") 443 return llvm::CodeGenOpt::Default; 444 445 if (S == "g") 446 return llvm::CodeGenOpt::Less; 447 448 return getLastArgIntValue(Args, OPT_O, DefaultOpt, Diags); 449 } 450 451 return DefaultOpt; 452 } 453 454 static unsigned getOptimizationLevelSize(ArgList &Args) { 455 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) { 456 if (A->getOption().matches(options::OPT_O)) { 457 switch (A->getValue()[0]) { 458 default: 459 return 0; 460 case 's': 461 return 1; 462 case 'z': 463 return 2; 464 } 465 } 466 } 467 return 0; 468 } 469 470 static void addDiagnosticArgs(ArgList &Args, OptSpecifier Group, 471 OptSpecifier GroupWithValue, 472 std::vector<std::string> &Diagnostics) { 473 for (auto *A : Args.filtered(Group)) { 474 if (A->getOption().getKind() == Option::FlagClass) { 475 // The argument is a pure flag (such as OPT_Wall or OPT_Wdeprecated). Add 476 // its name (minus the "W" or "R" at the beginning) to the warning list. 477 Diagnostics.push_back( 478 std::string(A->getOption().getName().drop_front(1))); 479 } else if (A->getOption().matches(GroupWithValue)) { 480 // This is -Wfoo= or -Rfoo=, where foo is the name of the diagnostic group. 481 Diagnostics.push_back( 482 std::string(A->getOption().getName().drop_front(1).rtrim("=-"))); 483 } else { 484 // Otherwise, add its value (for OPT_W_Joined and similar). 485 for (const auto *Arg : A->getValues()) 486 Diagnostics.emplace_back(Arg); 487 } 488 } 489 } 490 491 // Parse the Static Analyzer configuration. If \p Diags is set to nullptr, 492 // it won't verify the input. 493 static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts, 494 DiagnosticsEngine *Diags); 495 496 static void getAllNoBuiltinFuncValues(ArgList &Args, 497 std::vector<std::string> &Funcs) { 498 SmallVector<const char *, 8> Values; 499 for (const auto &Arg : Args) { 500 const Option &O = Arg->getOption(); 501 if (O.matches(options::OPT_fno_builtin_)) { 502 const char *FuncName = Arg->getValue(); 503 if (Builtin::Context::isBuiltinFunc(FuncName)) 504 Values.push_back(FuncName); 505 } 506 } 507 Funcs.insert(Funcs.end(), Values.begin(), Values.end()); 508 } 509 510 static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args, 511 DiagnosticsEngine &Diags) { 512 bool Success = true; 513 if (Arg *A = Args.getLastArg(OPT_analyzer_store)) { 514 StringRef Name = A->getValue(); 515 AnalysisStores Value = llvm::StringSwitch<AnalysisStores>(Name) 516 #define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN) \ 517 .Case(CMDFLAG, NAME##Model) 518 #include "clang/StaticAnalyzer/Core/Analyses.def" 519 .Default(NumStores); 520 if (Value == NumStores) { 521 Diags.Report(diag::err_drv_invalid_value) 522 << A->getAsString(Args) << Name; 523 Success = false; 524 } else { 525 Opts.AnalysisStoreOpt = Value; 526 } 527 } 528 529 if (Arg *A = Args.getLastArg(OPT_analyzer_constraints)) { 530 StringRef Name = A->getValue(); 531 AnalysisConstraints Value = llvm::StringSwitch<AnalysisConstraints>(Name) 532 #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \ 533 .Case(CMDFLAG, NAME##Model) 534 #include "clang/StaticAnalyzer/Core/Analyses.def" 535 .Default(NumConstraints); 536 if (Value == NumConstraints) { 537 Diags.Report(diag::err_drv_invalid_value) 538 << A->getAsString(Args) << Name; 539 Success = false; 540 } else { 541 Opts.AnalysisConstraintsOpt = Value; 542 } 543 } 544 545 if (Arg *A = Args.getLastArg(OPT_analyzer_output)) { 546 StringRef Name = A->getValue(); 547 AnalysisDiagClients Value = llvm::StringSwitch<AnalysisDiagClients>(Name) 548 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \ 549 .Case(CMDFLAG, PD_##NAME) 550 #include "clang/StaticAnalyzer/Core/Analyses.def" 551 .Default(NUM_ANALYSIS_DIAG_CLIENTS); 552 if (Value == NUM_ANALYSIS_DIAG_CLIENTS) { 553 Diags.Report(diag::err_drv_invalid_value) 554 << A->getAsString(Args) << Name; 555 Success = false; 556 } else { 557 Opts.AnalysisDiagOpt = Value; 558 } 559 } 560 561 if (Arg *A = Args.getLastArg(OPT_analyzer_purge)) { 562 StringRef Name = A->getValue(); 563 AnalysisPurgeMode Value = llvm::StringSwitch<AnalysisPurgeMode>(Name) 564 #define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \ 565 .Case(CMDFLAG, NAME) 566 #include "clang/StaticAnalyzer/Core/Analyses.def" 567 .Default(NumPurgeModes); 568 if (Value == NumPurgeModes) { 569 Diags.Report(diag::err_drv_invalid_value) 570 << A->getAsString(Args) << Name; 571 Success = false; 572 } else { 573 Opts.AnalysisPurgeOpt = Value; 574 } 575 } 576 577 if (Arg *A = Args.getLastArg(OPT_analyzer_inlining_mode)) { 578 StringRef Name = A->getValue(); 579 AnalysisInliningMode Value = llvm::StringSwitch<AnalysisInliningMode>(Name) 580 #define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \ 581 .Case(CMDFLAG, NAME) 582 #include "clang/StaticAnalyzer/Core/Analyses.def" 583 .Default(NumInliningModes); 584 if (Value == NumInliningModes) { 585 Diags.Report(diag::err_drv_invalid_value) 586 << A->getAsString(Args) << Name; 587 Success = false; 588 } else { 589 Opts.InliningMode = Value; 590 } 591 } 592 593 Opts.ShouldEmitErrorsOnInvalidConfigValue = 594 /* negated */!llvm::StringSwitch<bool>( 595 Args.getLastArgValue(OPT_analyzer_config_compatibility_mode)) 596 .Case("true", true) 597 .Case("false", false) 598 .Default(false); 599 600 Opts.CheckersAndPackages.clear(); 601 for (const Arg *A : 602 Args.filtered(OPT_analyzer_checker, OPT_analyzer_disable_checker)) { 603 A->claim(); 604 bool IsEnabled = A->getOption().getID() == OPT_analyzer_checker; 605 // We can have a list of comma separated checker names, e.g: 606 // '-analyzer-checker=cocoa,unix' 607 StringRef CheckerAndPackageList = A->getValue(); 608 SmallVector<StringRef, 16> CheckersAndPackages; 609 CheckerAndPackageList.split(CheckersAndPackages, ","); 610 for (const StringRef &CheckerOrPackage : CheckersAndPackages) 611 Opts.CheckersAndPackages.emplace_back(std::string(CheckerOrPackage), 612 IsEnabled); 613 } 614 615 // Go through the analyzer configuration options. 616 for (const auto *A : Args.filtered(OPT_analyzer_config)) { 617 618 // We can have a list of comma separated config names, e.g: 619 // '-analyzer-config key1=val1,key2=val2' 620 StringRef configList = A->getValue(); 621 SmallVector<StringRef, 4> configVals; 622 configList.split(configVals, ","); 623 for (const auto &configVal : configVals) { 624 StringRef key, val; 625 std::tie(key, val) = configVal.split("="); 626 if (val.empty()) { 627 Diags.Report(SourceLocation(), 628 diag::err_analyzer_config_no_value) << configVal; 629 Success = false; 630 break; 631 } 632 if (val.find('=') != StringRef::npos) { 633 Diags.Report(SourceLocation(), 634 diag::err_analyzer_config_multiple_values) 635 << configVal; 636 Success = false; 637 break; 638 } 639 640 // TODO: Check checker options too, possibly in CheckerRegistry. 641 // Leave unknown non-checker configs unclaimed. 642 if (!key.contains(":") && Opts.isUnknownAnalyzerConfig(key)) { 643 if (Opts.ShouldEmitErrorsOnInvalidConfigValue) 644 Diags.Report(diag::err_analyzer_config_unknown) << key; 645 continue; 646 } 647 648 A->claim(); 649 Opts.Config[key] = std::string(val); 650 } 651 } 652 653 if (Opts.ShouldEmitErrorsOnInvalidConfigValue) 654 parseAnalyzerConfigs(Opts, &Diags); 655 else 656 parseAnalyzerConfigs(Opts, nullptr); 657 658 llvm::raw_string_ostream os(Opts.FullCompilerInvocation); 659 for (unsigned i = 0; i < Args.getNumInputArgStrings(); ++i) { 660 if (i != 0) 661 os << " "; 662 os << Args.getArgString(i); 663 } 664 os.flush(); 665 666 return Success; 667 } 668 669 static StringRef getStringOption(AnalyzerOptions::ConfigTable &Config, 670 StringRef OptionName, StringRef DefaultVal) { 671 return Config.insert({OptionName, std::string(DefaultVal)}).first->second; 672 } 673 674 static void initOption(AnalyzerOptions::ConfigTable &Config, 675 DiagnosticsEngine *Diags, 676 StringRef &OptionField, StringRef Name, 677 StringRef DefaultVal) { 678 // String options may be known to invalid (e.g. if the expected string is a 679 // file name, but the file does not exist), those will have to be checked in 680 // parseConfigs. 681 OptionField = getStringOption(Config, Name, DefaultVal); 682 } 683 684 static void initOption(AnalyzerOptions::ConfigTable &Config, 685 DiagnosticsEngine *Diags, 686 bool &OptionField, StringRef Name, bool DefaultVal) { 687 auto PossiblyInvalidVal = llvm::StringSwitch<Optional<bool>>( 688 getStringOption(Config, Name, (DefaultVal ? "true" : "false"))) 689 .Case("true", true) 690 .Case("false", false) 691 .Default(None); 692 693 if (!PossiblyInvalidVal) { 694 if (Diags) 695 Diags->Report(diag::err_analyzer_config_invalid_input) 696 << Name << "a boolean"; 697 else 698 OptionField = DefaultVal; 699 } else 700 OptionField = PossiblyInvalidVal.getValue(); 701 } 702 703 static void initOption(AnalyzerOptions::ConfigTable &Config, 704 DiagnosticsEngine *Diags, 705 unsigned &OptionField, StringRef Name, 706 unsigned DefaultVal) { 707 708 OptionField = DefaultVal; 709 bool HasFailed = getStringOption(Config, Name, std::to_string(DefaultVal)) 710 .getAsInteger(0, OptionField); 711 if (Diags && HasFailed) 712 Diags->Report(diag::err_analyzer_config_invalid_input) 713 << Name << "an unsigned"; 714 } 715 716 static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts, 717 DiagnosticsEngine *Diags) { 718 // TODO: There's no need to store the entire configtable, it'd be plenty 719 // enough tostore checker options. 720 721 #define ANALYZER_OPTION(TYPE, NAME, CMDFLAG, DESC, DEFAULT_VAL) \ 722 initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, DEFAULT_VAL); 723 724 #define ANALYZER_OPTION_DEPENDS_ON_USER_MODE(TYPE, NAME, CMDFLAG, DESC, \ 725 SHALLOW_VAL, DEEP_VAL) \ 726 switch (AnOpts.getUserMode()) { \ 727 case UMK_Shallow: \ 728 initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, SHALLOW_VAL); \ 729 break; \ 730 case UMK_Deep: \ 731 initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, DEEP_VAL); \ 732 break; \ 733 } \ 734 735 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.def" 736 #undef ANALYZER_OPTION 737 #undef ANALYZER_OPTION_DEPENDS_ON_USER_MODE 738 739 // At this point, AnalyzerOptions is configured. Let's validate some options. 740 741 // FIXME: Here we try to validate the silenced checkers or packages are valid. 742 // The current approach only validates the registered checkers which does not 743 // contain the runtime enabled checkers and optimally we would validate both. 744 if (!AnOpts.RawSilencedCheckersAndPackages.empty()) { 745 std::vector<StringRef> Checkers = 746 AnOpts.getRegisteredCheckers(/*IncludeExperimental=*/true); 747 std::vector<StringRef> Packages = 748 AnOpts.getRegisteredPackages(/*IncludeExperimental=*/true); 749 750 SmallVector<StringRef, 16> CheckersAndPackages; 751 AnOpts.RawSilencedCheckersAndPackages.split(CheckersAndPackages, ";"); 752 753 for (const StringRef &CheckerOrPackage : CheckersAndPackages) { 754 if (Diags) { 755 bool IsChecker = CheckerOrPackage.contains('.'); 756 bool IsValidName = 757 IsChecker 758 ? llvm::find(Checkers, CheckerOrPackage) != Checkers.end() 759 : llvm::find(Packages, CheckerOrPackage) != Packages.end(); 760 761 if (!IsValidName) 762 Diags->Report(diag::err_unknown_analyzer_checker_or_package) 763 << CheckerOrPackage; 764 } 765 766 AnOpts.SilencedCheckersAndPackages.emplace_back(CheckerOrPackage); 767 } 768 } 769 770 if (!Diags) 771 return; 772 773 if (AnOpts.ShouldTrackConditionsDebug && !AnOpts.ShouldTrackConditions) 774 Diags->Report(diag::err_analyzer_config_invalid_input) 775 << "track-conditions-debug" << "'track-conditions' to also be enabled"; 776 777 if (!AnOpts.CTUDir.empty() && !llvm::sys::fs::is_directory(AnOpts.CTUDir)) 778 Diags->Report(diag::err_analyzer_config_invalid_input) << "ctu-dir" 779 << "a filename"; 780 781 if (!AnOpts.ModelPath.empty() && 782 !llvm::sys::fs::is_directory(AnOpts.ModelPath)) 783 Diags->Report(diag::err_analyzer_config_invalid_input) << "model-path" 784 << "a filename"; 785 } 786 787 static void ParseCommentArgs(CommentOptions &Opts, ArgList &Args) { 788 Opts.BlockCommandNames = Args.getAllArgValues(OPT_fcomment_block_commands); 789 Opts.ParseAllComments = Args.hasArg(OPT_fparse_all_comments); 790 } 791 792 /// Create a new Regex instance out of the string value in \p RpassArg. 793 /// It returns a pointer to the newly generated Regex instance. 794 static std::shared_ptr<llvm::Regex> 795 GenerateOptimizationRemarkRegex(DiagnosticsEngine &Diags, ArgList &Args, 796 Arg *RpassArg) { 797 StringRef Val = RpassArg->getValue(); 798 std::string RegexError; 799 std::shared_ptr<llvm::Regex> Pattern = std::make_shared<llvm::Regex>(Val); 800 if (!Pattern->isValid(RegexError)) { 801 Diags.Report(diag::err_drv_optimization_remark_pattern) 802 << RegexError << RpassArg->getAsString(Args); 803 Pattern.reset(); 804 } 805 return Pattern; 806 } 807 808 static bool parseDiagnosticLevelMask(StringRef FlagName, 809 const std::vector<std::string> &Levels, 810 DiagnosticsEngine *Diags, 811 DiagnosticLevelMask &M) { 812 bool Success = true; 813 for (const auto &Level : Levels) { 814 DiagnosticLevelMask const PM = 815 llvm::StringSwitch<DiagnosticLevelMask>(Level) 816 .Case("note", DiagnosticLevelMask::Note) 817 .Case("remark", DiagnosticLevelMask::Remark) 818 .Case("warning", DiagnosticLevelMask::Warning) 819 .Case("error", DiagnosticLevelMask::Error) 820 .Default(DiagnosticLevelMask::None); 821 if (PM == DiagnosticLevelMask::None) { 822 Success = false; 823 if (Diags) 824 Diags->Report(diag::err_drv_invalid_value) << FlagName << Level; 825 } 826 M = M | PM; 827 } 828 return Success; 829 } 830 831 static void parseSanitizerKinds(StringRef FlagName, 832 const std::vector<std::string> &Sanitizers, 833 DiagnosticsEngine &Diags, SanitizerSet &S) { 834 for (const auto &Sanitizer : Sanitizers) { 835 SanitizerMask K = parseSanitizerValue(Sanitizer, /*AllowGroups=*/false); 836 if (K == SanitizerMask()) 837 Diags.Report(diag::err_drv_invalid_value) << FlagName << Sanitizer; 838 else 839 S.set(K, true); 840 } 841 } 842 843 static void parseXRayInstrumentationBundle(StringRef FlagName, StringRef Bundle, 844 ArgList &Args, DiagnosticsEngine &D, 845 XRayInstrSet &S) { 846 llvm::SmallVector<StringRef, 2> BundleParts; 847 llvm::SplitString(Bundle, BundleParts, ","); 848 for (const auto &B : BundleParts) { 849 auto Mask = parseXRayInstrValue(B); 850 if (Mask == XRayInstrKind::None) 851 if (B != "none") 852 D.Report(diag::err_drv_invalid_value) << FlagName << Bundle; 853 else 854 S.Mask = Mask; 855 else if (Mask == XRayInstrKind::All) 856 S.Mask = Mask; 857 else 858 S.set(Mask, true); 859 } 860 } 861 862 // Set the profile kind using fprofile-instrument-use-path. 863 static void setPGOUseInstrumentor(CodeGenOptions &Opts, 864 const Twine &ProfileName) { 865 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(ProfileName); 866 // In error, return silently and let Clang PGOUse report the error message. 867 if (auto E = ReaderOrErr.takeError()) { 868 llvm::consumeError(std::move(E)); 869 Opts.setProfileUse(CodeGenOptions::ProfileClangInstr); 870 return; 871 } 872 std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader = 873 std::move(ReaderOrErr.get()); 874 if (PGOReader->isIRLevelProfile()) { 875 if (PGOReader->hasCSIRLevelProfile()) 876 Opts.setProfileUse(CodeGenOptions::ProfileCSIRInstr); 877 else 878 Opts.setProfileUse(CodeGenOptions::ProfileIRInstr); 879 } else 880 Opts.setProfileUse(CodeGenOptions::ProfileClangInstr); 881 } 882 883 static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK, 884 DiagnosticsEngine &Diags, 885 const TargetOptions &TargetOpts, 886 const FrontendOptions &FrontendOpts) { 887 bool Success = true; 888 llvm::Triple Triple = llvm::Triple(TargetOpts.Triple); 889 890 unsigned OptimizationLevel = getOptimizationLevel(Args, IK, Diags); 891 // TODO: This could be done in Driver 892 unsigned MaxOptLevel = 3; 893 if (OptimizationLevel > MaxOptLevel) { 894 // If the optimization level is not supported, fall back on the default 895 // optimization 896 Diags.Report(diag::warn_drv_optimization_value) 897 << Args.getLastArg(OPT_O)->getAsString(Args) << "-O" << MaxOptLevel; 898 OptimizationLevel = MaxOptLevel; 899 } 900 Opts.OptimizationLevel = OptimizationLevel; 901 902 // At O0 we want to fully disable inlining outside of cases marked with 903 // 'alwaysinline' that are required for correctness. 904 Opts.setInlining((Opts.OptimizationLevel == 0) 905 ? CodeGenOptions::OnlyAlwaysInlining 906 : CodeGenOptions::NormalInlining); 907 // Explicit inlining flags can disable some or all inlining even at 908 // optimization levels above zero. 909 if (Arg *InlineArg = Args.getLastArg( 910 options::OPT_finline_functions, options::OPT_finline_hint_functions, 911 options::OPT_fno_inline_functions, options::OPT_fno_inline)) { 912 if (Opts.OptimizationLevel > 0) { 913 const Option &InlineOpt = InlineArg->getOption(); 914 if (InlineOpt.matches(options::OPT_finline_functions)) 915 Opts.setInlining(CodeGenOptions::NormalInlining); 916 else if (InlineOpt.matches(options::OPT_finline_hint_functions)) 917 Opts.setInlining(CodeGenOptions::OnlyHintInlining); 918 else 919 Opts.setInlining(CodeGenOptions::OnlyAlwaysInlining); 920 } 921 } 922 923 // If -fuse-ctor-homing is set and limited debug info is already on, then use 924 // constructor homing. 925 if (Args.getLastArg(OPT_fuse_ctor_homing)) 926 if (Opts.getDebugInfo() == codegenoptions::LimitedDebugInfo) 927 Opts.setDebugInfo(codegenoptions::DebugInfoConstructor); 928 929 for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ)) { 930 auto Split = StringRef(Arg).split('='); 931 Opts.DebugPrefixMap.insert( 932 {std::string(Split.first), std::string(Split.second)}); 933 } 934 935 const llvm::Triple::ArchType DebugEntryValueArchs[] = { 936 llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::aarch64, 937 llvm::Triple::arm, llvm::Triple::armeb, llvm::Triple::mips, 938 llvm::Triple::mipsel, llvm::Triple::mips64, llvm::Triple::mips64el}; 939 940 llvm::Triple T(TargetOpts.Triple); 941 if (Opts.OptimizationLevel > 0 && Opts.hasReducedDebugInfo() && 942 llvm::is_contained(DebugEntryValueArchs, T.getArch())) 943 Opts.EmitCallSiteInfo = true; 944 945 Opts.NewStructPathTBAA = !Args.hasArg(OPT_no_struct_path_tbaa) && 946 Args.hasArg(OPT_new_struct_path_tbaa); 947 Opts.OptimizeSize = getOptimizationLevelSize(Args); 948 Opts.SimplifyLibCalls = !(Args.hasArg(OPT_fno_builtin) || 949 Args.hasArg(OPT_ffreestanding)); 950 if (Opts.SimplifyLibCalls) 951 getAllNoBuiltinFuncValues(Args, Opts.NoBuiltinFuncs); 952 Opts.UnrollLoops = 953 Args.hasFlag(OPT_funroll_loops, OPT_fno_unroll_loops, 954 (Opts.OptimizationLevel > 1)); 955 956 Opts.DebugNameTable = static_cast<unsigned>( 957 Args.hasArg(OPT_ggnu_pubnames) 958 ? llvm::DICompileUnit::DebugNameTableKind::GNU 959 : Args.hasArg(OPT_gpubnames) 960 ? llvm::DICompileUnit::DebugNameTableKind::Default 961 : llvm::DICompileUnit::DebugNameTableKind::None); 962 963 if (!Opts.ProfileInstrumentUsePath.empty()) 964 setPGOUseInstrumentor(Opts, Opts.ProfileInstrumentUsePath); 965 966 Opts.CodeModel = TargetOpts.CodeModel; 967 968 if (const Arg *A = Args.getLastArg(OPT_ftime_report, OPT_ftime_report_EQ)) { 969 Opts.TimePasses = true; 970 971 // -ftime-report= is only for new pass manager. 972 if (A->getOption().getID() == OPT_ftime_report_EQ) { 973 if (Opts.LegacyPassManager) 974 Diags.Report(diag::err_drv_argument_only_allowed_with) 975 << A->getAsString(Args) << "-fno-legacy-pass-manager"; 976 977 StringRef Val = A->getValue(); 978 if (Val == "per-pass") 979 Opts.TimePassesPerRun = false; 980 else if (Val == "per-pass-run") 981 Opts.TimePassesPerRun = true; 982 else 983 Diags.Report(diag::err_drv_invalid_value) 984 << A->getAsString(Args) << A->getValue(); 985 } 986 } 987 988 Opts.Reciprocals = Args.getAllArgValues(OPT_mrecip_EQ); 989 990 // Basic Block Sections implies Function Sections. 991 Opts.FunctionSections = 992 Args.hasArg(OPT_ffunction_sections) || 993 (Opts.BBSections != "none" && Opts.BBSections != "labels"); 994 995 Opts.PrepareForLTO = Args.hasArg(OPT_flto, OPT_flto_EQ); 996 Opts.PrepareForThinLTO = false; 997 if (Arg *A = Args.getLastArg(OPT_flto_EQ)) { 998 StringRef S = A->getValue(); 999 if (S == "thin") 1000 Opts.PrepareForThinLTO = true; 1001 else if (S != "full") 1002 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << S; 1003 } 1004 if (Arg *A = Args.getLastArg(OPT_fthinlto_index_EQ)) { 1005 if (IK.getLanguage() != Language::LLVM_IR) 1006 Diags.Report(diag::err_drv_argument_only_allowed_with) 1007 << A->getAsString(Args) << "-x ir"; 1008 Opts.ThinLTOIndexFile = 1009 std::string(Args.getLastArgValue(OPT_fthinlto_index_EQ)); 1010 } 1011 if (Arg *A = Args.getLastArg(OPT_save_temps_EQ)) 1012 Opts.SaveTempsFilePrefix = 1013 llvm::StringSwitch<std::string>(A->getValue()) 1014 .Case("obj", FrontendOpts.OutputFile) 1015 .Default(llvm::sys::path::filename(FrontendOpts.OutputFile).str()); 1016 1017 // The memory profile runtime appends the pid to make this name more unique. 1018 const char *MemProfileBasename = "memprof.profraw"; 1019 if (Args.hasArg(OPT_fmemory_profile_EQ)) { 1020 SmallString<128> Path( 1021 std::string(Args.getLastArgValue(OPT_fmemory_profile_EQ))); 1022 llvm::sys::path::append(Path, MemProfileBasename); 1023 Opts.MemoryProfileOutput = std::string(Path); 1024 } else if (Args.hasArg(OPT_fmemory_profile)) 1025 Opts.MemoryProfileOutput = MemProfileBasename; 1026 1027 if (Opts.EmitGcovArcs || Opts.EmitGcovNotes) { 1028 Opts.CoverageDataFile = 1029 std::string(Args.getLastArgValue(OPT_coverage_data_file)); 1030 Opts.CoverageNotesFile = 1031 std::string(Args.getLastArgValue(OPT_coverage_notes_file)); 1032 Opts.ProfileFilterFiles = 1033 std::string(Args.getLastArgValue(OPT_fprofile_filter_files_EQ)); 1034 Opts.ProfileExcludeFiles = 1035 std::string(Args.getLastArgValue(OPT_fprofile_exclude_files_EQ)); 1036 if (Args.hasArg(OPT_coverage_version_EQ)) { 1037 StringRef CoverageVersion = Args.getLastArgValue(OPT_coverage_version_EQ); 1038 if (CoverageVersion.size() != 4) { 1039 Diags.Report(diag::err_drv_invalid_value) 1040 << Args.getLastArg(OPT_coverage_version_EQ)->getAsString(Args) 1041 << CoverageVersion; 1042 } else { 1043 memcpy(Opts.CoverageVersion, CoverageVersion.data(), 4); 1044 } 1045 } 1046 } 1047 // FIXME: For backend options that are not yet recorded as function 1048 // attributes in the IR, keep track of them so we can embed them in a 1049 // separate data section and use them when building the bitcode. 1050 for (const auto &A : Args) { 1051 // Do not encode output and input. 1052 if (A->getOption().getID() == options::OPT_o || 1053 A->getOption().getID() == options::OPT_INPUT || 1054 A->getOption().getID() == options::OPT_x || 1055 A->getOption().getID() == options::OPT_fembed_bitcode || 1056 A->getOption().matches(options::OPT_W_Group)) 1057 continue; 1058 ArgStringList ASL; 1059 A->render(Args, ASL); 1060 for (const auto &arg : ASL) { 1061 StringRef ArgStr(arg); 1062 Opts.CmdArgs.insert(Opts.CmdArgs.end(), ArgStr.begin(), ArgStr.end()); 1063 // using \00 to separate each commandline options. 1064 Opts.CmdArgs.push_back('\0'); 1065 } 1066 } 1067 1068 Opts.XRayTotalFunctionGroups = 1069 getLastArgIntValue(Args, OPT_fxray_function_groups, 1, Diags); 1070 Opts.XRaySelectedFunctionGroup = 1071 getLastArgIntValue(Args, OPT_fxray_selected_function_group, 0, Diags); 1072 1073 auto XRayInstrBundles = 1074 Args.getAllArgValues(OPT_fxray_instrumentation_bundle); 1075 if (XRayInstrBundles.empty()) 1076 Opts.XRayInstrumentationBundle.Mask = XRayInstrKind::All; 1077 else 1078 for (const auto &A : XRayInstrBundles) 1079 parseXRayInstrumentationBundle("-fxray-instrumentation-bundle=", A, Args, 1080 Diags, Opts.XRayInstrumentationBundle); 1081 1082 if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) { 1083 StringRef Name = A->getValue(); 1084 if (Name == "full") { 1085 Opts.CFProtectionReturn = 1; 1086 Opts.CFProtectionBranch = 1; 1087 } else if (Name == "return") 1088 Opts.CFProtectionReturn = 1; 1089 else if (Name == "branch") 1090 Opts.CFProtectionBranch = 1; 1091 else if (Name != "none") { 1092 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name; 1093 Success = false; 1094 } 1095 } 1096 1097 if (const Arg *A = Args.getLastArg(OPT_compress_debug_sections_EQ)) { 1098 auto DCT = llvm::StringSwitch<llvm::DebugCompressionType>(A->getValue()) 1099 .Case("none", llvm::DebugCompressionType::None) 1100 .Case("zlib", llvm::DebugCompressionType::Z) 1101 .Case("zlib-gnu", llvm::DebugCompressionType::GNU) 1102 .Default(llvm::DebugCompressionType::None); 1103 Opts.setCompressDebugSections(DCT); 1104 } 1105 1106 for (auto *A : 1107 Args.filtered(OPT_mlink_bitcode_file, OPT_mlink_builtin_bitcode)) { 1108 CodeGenOptions::BitcodeFileToLink F; 1109 F.Filename = A->getValue(); 1110 if (A->getOption().matches(OPT_mlink_builtin_bitcode)) { 1111 F.LinkFlags = llvm::Linker::Flags::LinkOnlyNeeded; 1112 // When linking CUDA bitcode, propagate function attributes so that 1113 // e.g. libdevice gets fast-math attrs if we're building with fast-math. 1114 F.PropagateAttrs = true; 1115 F.Internalize = true; 1116 } 1117 Opts.LinkBitcodeFiles.push_back(F); 1118 } 1119 Opts.SanitizeCoverageAllowlistFiles = 1120 Args.getAllArgValues(OPT_fsanitize_coverage_allowlist); 1121 Opts.SanitizeCoverageBlocklistFiles = 1122 Args.getAllArgValues(OPT_fsanitize_coverage_blocklist); 1123 Opts.SSPBufferSize = 1124 getLastArgIntValue(Args, OPT_stack_protector_buffer_size, 8, Diags); 1125 1126 Opts.StackProtectorGuard = 1127 std::string(Args.getLastArgValue(OPT_mstack_protector_guard_EQ)); 1128 1129 if (Arg *A = Args.getLastArg(OPT_mstack_protector_guard_offset_EQ)) { 1130 StringRef Val = A->getValue(); 1131 unsigned Offset = Opts.StackProtectorGuardOffset; 1132 Val.getAsInteger(10, Offset); 1133 Opts.StackProtectorGuardOffset = Offset; 1134 } 1135 1136 Opts.StackProtectorGuardReg = 1137 std::string(Args.getLastArgValue(OPT_mstack_protector_guard_reg_EQ, 1138 "none")); 1139 1140 1141 if (Args.getLastArg(OPT_femulated_tls) || 1142 Args.getLastArg(OPT_fno_emulated_tls)) { 1143 Opts.ExplicitEmulatedTLS = true; 1144 Opts.EmulatedTLS = 1145 Args.hasFlag(OPT_femulated_tls, OPT_fno_emulated_tls, false); 1146 } 1147 1148 if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_EQ)) { 1149 StringRef Val = A->getValue(); 1150 Opts.FPDenormalMode = llvm::parseDenormalFPAttribute(Val); 1151 if (!Opts.FPDenormalMode.isValid()) 1152 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val; 1153 } 1154 1155 if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_f32_EQ)) { 1156 StringRef Val = A->getValue(); 1157 Opts.FP32DenormalMode = llvm::parseDenormalFPAttribute(Val); 1158 if (!Opts.FP32DenormalMode.isValid()) 1159 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val; 1160 } 1161 1162 // X86_32 has -fppc-struct-return and -freg-struct-return. 1163 // PPC32 has -maix-struct-return and -msvr4-struct-return. 1164 if (Arg *A = 1165 Args.getLastArg(OPT_fpcc_struct_return, OPT_freg_struct_return, 1166 OPT_maix_struct_return, OPT_msvr4_struct_return)) { 1167 // TODO: We might want to consider enabling these options on AIX in the 1168 // future. 1169 if (T.isOSAIX()) 1170 Diags.Report(diag::err_drv_unsupported_opt_for_target) 1171 << A->getSpelling() << T.str(); 1172 1173 const Option &O = A->getOption(); 1174 if (O.matches(OPT_fpcc_struct_return) || 1175 O.matches(OPT_maix_struct_return)) { 1176 Opts.setStructReturnConvention(CodeGenOptions::SRCK_OnStack); 1177 } else { 1178 assert(O.matches(OPT_freg_struct_return) || 1179 O.matches(OPT_msvr4_struct_return)); 1180 Opts.setStructReturnConvention(CodeGenOptions::SRCK_InRegs); 1181 } 1182 } 1183 1184 if (T.isOSAIX() && (Args.hasArg(OPT_mignore_xcoff_visibility) || 1185 !Args.hasArg(OPT_fvisibility))) 1186 Opts.IgnoreXCOFFVisibility = 1; 1187 1188 if (Arg *A = 1189 Args.getLastArg(OPT_mabi_EQ_vec_default, OPT_mabi_EQ_vec_extabi)) { 1190 if (!T.isOSAIX()) 1191 Diags.Report(diag::err_drv_unsupported_opt_for_target) 1192 << A->getSpelling() << T.str(); 1193 1194 const Option &O = A->getOption(); 1195 if (O.matches(OPT_mabi_EQ_vec_default)) 1196 Diags.Report(diag::err_aix_default_altivec_abi) 1197 << A->getSpelling() << T.str(); 1198 else { 1199 assert(O.matches(OPT_mabi_EQ_vec_extabi)); 1200 Opts.EnableAIXExtendedAltivecABI = 1; 1201 } 1202 } 1203 1204 Opts.DependentLibraries = Args.getAllArgValues(OPT_dependent_lib); 1205 Opts.LinkerOptions = Args.getAllArgValues(OPT_linker_option); 1206 bool NeedLocTracking = false; 1207 1208 if (!Opts.OptRecordFile.empty()) 1209 NeedLocTracking = true; 1210 1211 if (Arg *A = Args.getLastArg(OPT_opt_record_passes)) { 1212 Opts.OptRecordPasses = A->getValue(); 1213 NeedLocTracking = true; 1214 } 1215 1216 if (Arg *A = Args.getLastArg(OPT_opt_record_format)) { 1217 Opts.OptRecordFormat = A->getValue(); 1218 NeedLocTracking = true; 1219 } 1220 1221 if (Arg *A = Args.getLastArg(OPT_Rpass_EQ)) { 1222 Opts.OptimizationRemarkPattern = 1223 GenerateOptimizationRemarkRegex(Diags, Args, A); 1224 NeedLocTracking = true; 1225 } 1226 1227 if (Arg *A = Args.getLastArg(OPT_Rpass_missed_EQ)) { 1228 Opts.OptimizationRemarkMissedPattern = 1229 GenerateOptimizationRemarkRegex(Diags, Args, A); 1230 NeedLocTracking = true; 1231 } 1232 1233 if (Arg *A = Args.getLastArg(OPT_Rpass_analysis_EQ)) { 1234 Opts.OptimizationRemarkAnalysisPattern = 1235 GenerateOptimizationRemarkRegex(Diags, Args, A); 1236 NeedLocTracking = true; 1237 } 1238 1239 bool UsingSampleProfile = !Opts.SampleProfileFile.empty(); 1240 bool UsingProfile = UsingSampleProfile || 1241 (Opts.getProfileUse() != CodeGenOptions::ProfileNone); 1242 1243 if (Opts.DiagnosticsWithHotness && !UsingProfile && 1244 // An IR file will contain PGO as metadata 1245 IK.getLanguage() != Language::LLVM_IR) 1246 Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo) 1247 << "-fdiagnostics-show-hotness"; 1248 1249 // Parse remarks hotness threshold. Valid value is either integer or 'auto'. 1250 if (auto *arg = 1251 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) { 1252 auto ResultOrErr = 1253 llvm::remarks::parseHotnessThresholdOption(arg->getValue()); 1254 1255 if (!ResultOrErr) { 1256 Diags.Report(diag::err_drv_invalid_diagnotics_hotness_threshold) 1257 << "-fdiagnostics-hotness-threshold="; 1258 } else { 1259 Opts.DiagnosticsHotnessThreshold = *ResultOrErr; 1260 if ((!Opts.DiagnosticsHotnessThreshold.hasValue() || 1261 Opts.DiagnosticsHotnessThreshold.getValue() > 0) && 1262 !UsingProfile) 1263 Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo) 1264 << "-fdiagnostics-hotness-threshold="; 1265 } 1266 } 1267 1268 // If the user requested to use a sample profile for PGO, then the 1269 // backend will need to track source location information so the profile 1270 // can be incorporated into the IR. 1271 if (UsingSampleProfile) 1272 NeedLocTracking = true; 1273 1274 // If the user requested a flag that requires source locations available in 1275 // the backend, make sure that the backend tracks source location information. 1276 if (NeedLocTracking && Opts.getDebugInfo() == codegenoptions::NoDebugInfo) 1277 Opts.setDebugInfo(codegenoptions::LocTrackingOnly); 1278 1279 Opts.RewriteMapFiles = Args.getAllArgValues(OPT_frewrite_map_file); 1280 1281 // Parse -fsanitize-recover= arguments. 1282 // FIXME: Report unrecoverable sanitizers incorrectly specified here. 1283 parseSanitizerKinds("-fsanitize-recover=", 1284 Args.getAllArgValues(OPT_fsanitize_recover_EQ), Diags, 1285 Opts.SanitizeRecover); 1286 parseSanitizerKinds("-fsanitize-trap=", 1287 Args.getAllArgValues(OPT_fsanitize_trap_EQ), Diags, 1288 Opts.SanitizeTrap); 1289 1290 Opts.EmitVersionIdentMetadata = Args.hasFlag(OPT_Qy, OPT_Qn, true); 1291 1292 Opts.DefaultFunctionAttrs = Args.getAllArgValues(OPT_default_function_attr); 1293 1294 Opts.PassPlugins = Args.getAllArgValues(OPT_fpass_plugin_EQ); 1295 1296 return Success; 1297 } 1298 1299 static void ParseDependencyOutputArgs(DependencyOutputOptions &Opts, 1300 ArgList &Args) { 1301 Opts.Targets = Args.getAllArgValues(OPT_MT); 1302 if (Args.hasArg(OPT_show_includes)) { 1303 // Writing both /showIncludes and preprocessor output to stdout 1304 // would produce interleaved output, so use stderr for /showIncludes. 1305 // This behaves the same as cl.exe, when /E, /EP or /P are passed. 1306 if (Args.hasArg(options::OPT_E) || Args.hasArg(options::OPT_P)) 1307 Opts.ShowIncludesDest = ShowIncludesDestination::Stderr; 1308 else 1309 Opts.ShowIncludesDest = ShowIncludesDestination::Stdout; 1310 } else { 1311 Opts.ShowIncludesDest = ShowIncludesDestination::None; 1312 } 1313 // Add sanitizer blacklists as extra dependencies. 1314 // They won't be discovered by the regular preprocessor, so 1315 // we let make / ninja to know about this implicit dependency. 1316 if (!Args.hasArg(OPT_fno_sanitize_blacklist)) { 1317 for (const auto *A : Args.filtered(OPT_fsanitize_blacklist)) { 1318 StringRef Val = A->getValue(); 1319 if (Val.find('=') == StringRef::npos) 1320 Opts.ExtraDeps.push_back(std::string(Val)); 1321 } 1322 if (Opts.IncludeSystemHeaders) { 1323 for (const auto *A : Args.filtered(OPT_fsanitize_system_blacklist)) { 1324 StringRef Val = A->getValue(); 1325 if (Val.find('=') == StringRef::npos) 1326 Opts.ExtraDeps.push_back(std::string(Val)); 1327 } 1328 } 1329 } 1330 1331 // Propagate the extra dependencies. 1332 for (const auto *A : Args.filtered(OPT_fdepfile_entry)) { 1333 Opts.ExtraDeps.push_back(A->getValue()); 1334 } 1335 1336 // Only the -fmodule-file=<file> form. 1337 for (const auto *A : Args.filtered(OPT_fmodule_file)) { 1338 StringRef Val = A->getValue(); 1339 if (Val.find('=') == StringRef::npos) 1340 Opts.ExtraDeps.push_back(std::string(Val)); 1341 } 1342 } 1343 1344 static bool parseShowColorsArgs(const ArgList &Args, bool DefaultColor) { 1345 // Color diagnostics default to auto ("on" if terminal supports) in the driver 1346 // but default to off in cc1, needing an explicit OPT_fdiagnostics_color. 1347 // Support both clang's -f[no-]color-diagnostics and gcc's 1348 // -f[no-]diagnostics-colors[=never|always|auto]. 1349 enum { 1350 Colors_On, 1351 Colors_Off, 1352 Colors_Auto 1353 } ShowColors = DefaultColor ? Colors_Auto : Colors_Off; 1354 for (auto *A : Args) { 1355 const Option &O = A->getOption(); 1356 if (O.matches(options::OPT_fcolor_diagnostics) || 1357 O.matches(options::OPT_fdiagnostics_color)) { 1358 ShowColors = Colors_On; 1359 } else if (O.matches(options::OPT_fno_color_diagnostics) || 1360 O.matches(options::OPT_fno_diagnostics_color)) { 1361 ShowColors = Colors_Off; 1362 } else if (O.matches(options::OPT_fdiagnostics_color_EQ)) { 1363 StringRef Value(A->getValue()); 1364 if (Value == "always") 1365 ShowColors = Colors_On; 1366 else if (Value == "never") 1367 ShowColors = Colors_Off; 1368 else if (Value == "auto") 1369 ShowColors = Colors_Auto; 1370 } 1371 } 1372 return ShowColors == Colors_On || 1373 (ShowColors == Colors_Auto && 1374 llvm::sys::Process::StandardErrHasColors()); 1375 } 1376 1377 static bool checkVerifyPrefixes(const std::vector<std::string> &VerifyPrefixes, 1378 DiagnosticsEngine *Diags) { 1379 bool Success = true; 1380 for (const auto &Prefix : VerifyPrefixes) { 1381 // Every prefix must start with a letter and contain only alphanumeric 1382 // characters, hyphens, and underscores. 1383 auto BadChar = llvm::find_if(Prefix, [](char C) { 1384 return !isAlphanumeric(C) && C != '-' && C != '_'; 1385 }); 1386 if (BadChar != Prefix.end() || !isLetter(Prefix[0])) { 1387 Success = false; 1388 if (Diags) { 1389 Diags->Report(diag::err_drv_invalid_value) << "-verify=" << Prefix; 1390 Diags->Report(diag::note_drv_verify_prefix_spelling); 1391 } 1392 } 1393 } 1394 return Success; 1395 } 1396 1397 bool clang::ParseDiagnosticArgs(DiagnosticOptions &Opts, ArgList &Args, 1398 DiagnosticsEngine *Diags, 1399 bool DefaultDiagColor) { 1400 bool Success = true; 1401 1402 Opts.DiagnosticLogFile = 1403 std::string(Args.getLastArgValue(OPT_diagnostic_log_file)); 1404 if (Arg *A = 1405 Args.getLastArg(OPT_diagnostic_serialized_file, OPT__serialize_diags)) 1406 Opts.DiagnosticSerializationFile = A->getValue(); 1407 Opts.IgnoreWarnings = Args.hasArg(OPT_w); 1408 Opts.NoRewriteMacros = Args.hasArg(OPT_Wno_rewrite_macros); 1409 Opts.Pedantic = Args.hasArg(OPT_pedantic); 1410 Opts.PedanticErrors = Args.hasArg(OPT_pedantic_errors); 1411 Opts.ShowCarets = !Args.hasArg(OPT_fno_caret_diagnostics); 1412 Opts.ShowColors = parseShowColorsArgs(Args, DefaultDiagColor); 1413 Opts.ShowColumn = !Args.hasArg(OPT_fno_show_column); 1414 Opts.ShowFixits = !Args.hasArg(OPT_fno_diagnostics_fixit_info); 1415 Opts.ShowLocation = !Args.hasArg(OPT_fno_show_source_location); 1416 Opts.AbsolutePath = Args.hasArg(OPT_fdiagnostics_absolute_paths); 1417 Opts.ShowOptionNames = !Args.hasArg(OPT_fno_diagnostics_show_option); 1418 1419 // Default behavior is to not to show note include stacks. 1420 Opts.ShowNoteIncludeStack = false; 1421 if (Arg *A = Args.getLastArg(OPT_fdiagnostics_show_note_include_stack, 1422 OPT_fno_diagnostics_show_note_include_stack)) 1423 if (A->getOption().matches(OPT_fdiagnostics_show_note_include_stack)) 1424 Opts.ShowNoteIncludeStack = true; 1425 1426 StringRef ShowOverloads = 1427 Args.getLastArgValue(OPT_fshow_overloads_EQ, "all"); 1428 if (ShowOverloads == "best") 1429 Opts.setShowOverloads(Ovl_Best); 1430 else if (ShowOverloads == "all") 1431 Opts.setShowOverloads(Ovl_All); 1432 else { 1433 Success = false; 1434 if (Diags) 1435 Diags->Report(diag::err_drv_invalid_value) 1436 << Args.getLastArg(OPT_fshow_overloads_EQ)->getAsString(Args) 1437 << ShowOverloads; 1438 } 1439 1440 StringRef ShowCategory = 1441 Args.getLastArgValue(OPT_fdiagnostics_show_category, "none"); 1442 if (ShowCategory == "none") 1443 Opts.ShowCategories = 0; 1444 else if (ShowCategory == "id") 1445 Opts.ShowCategories = 1; 1446 else if (ShowCategory == "name") 1447 Opts.ShowCategories = 2; 1448 else { 1449 Success = false; 1450 if (Diags) 1451 Diags->Report(diag::err_drv_invalid_value) 1452 << Args.getLastArg(OPT_fdiagnostics_show_category)->getAsString(Args) 1453 << ShowCategory; 1454 } 1455 1456 StringRef Format = 1457 Args.getLastArgValue(OPT_fdiagnostics_format, "clang"); 1458 if (Format == "clang") 1459 Opts.setFormat(DiagnosticOptions::Clang); 1460 else if (Format == "msvc") 1461 Opts.setFormat(DiagnosticOptions::MSVC); 1462 else if (Format == "msvc-fallback") { 1463 Opts.setFormat(DiagnosticOptions::MSVC); 1464 Opts.CLFallbackMode = true; 1465 } else if (Format == "vi") 1466 Opts.setFormat(DiagnosticOptions::Vi); 1467 else { 1468 Success = false; 1469 if (Diags) 1470 Diags->Report(diag::err_drv_invalid_value) 1471 << Args.getLastArg(OPT_fdiagnostics_format)->getAsString(Args) 1472 << Format; 1473 } 1474 1475 Opts.ShowSourceRanges = Args.hasArg(OPT_fdiagnostics_print_source_range_info); 1476 Opts.ShowParseableFixits = Args.hasArg(OPT_fdiagnostics_parseable_fixits); 1477 Opts.ShowPresumedLoc = !Args.hasArg(OPT_fno_diagnostics_use_presumed_location); 1478 Opts.VerifyDiagnostics = Args.hasArg(OPT_verify) || Args.hasArg(OPT_verify_EQ); 1479 Opts.VerifyPrefixes = Args.getAllArgValues(OPT_verify_EQ); 1480 if (Args.hasArg(OPT_verify)) 1481 Opts.VerifyPrefixes.push_back("expected"); 1482 // Keep VerifyPrefixes in its original order for the sake of diagnostics, and 1483 // then sort it to prepare for fast lookup using std::binary_search. 1484 if (!checkVerifyPrefixes(Opts.VerifyPrefixes, Diags)) { 1485 Opts.VerifyDiagnostics = false; 1486 Success = false; 1487 } 1488 else 1489 llvm::sort(Opts.VerifyPrefixes); 1490 DiagnosticLevelMask DiagMask = DiagnosticLevelMask::None; 1491 Success &= parseDiagnosticLevelMask("-verify-ignore-unexpected=", 1492 Args.getAllArgValues(OPT_verify_ignore_unexpected_EQ), 1493 Diags, DiagMask); 1494 if (Args.hasArg(OPT_verify_ignore_unexpected)) 1495 DiagMask = DiagnosticLevelMask::All; 1496 Opts.setVerifyIgnoreUnexpected(DiagMask); 1497 Opts.ElideType = !Args.hasArg(OPT_fno_elide_type); 1498 Opts.ShowTemplateTree = Args.hasArg(OPT_fdiagnostics_show_template_tree); 1499 Opts.ErrorLimit = getLastArgIntValue(Args, OPT_ferror_limit, 0, Diags); 1500 Opts.MacroBacktraceLimit = 1501 getLastArgIntValue(Args, OPT_fmacro_backtrace_limit, 1502 DiagnosticOptions::DefaultMacroBacktraceLimit, Diags); 1503 Opts.TemplateBacktraceLimit = getLastArgIntValue( 1504 Args, OPT_ftemplate_backtrace_limit, 1505 DiagnosticOptions::DefaultTemplateBacktraceLimit, Diags); 1506 Opts.ConstexprBacktraceLimit = getLastArgIntValue( 1507 Args, OPT_fconstexpr_backtrace_limit, 1508 DiagnosticOptions::DefaultConstexprBacktraceLimit, Diags); 1509 Opts.SpellCheckingLimit = getLastArgIntValue( 1510 Args, OPT_fspell_checking_limit, 1511 DiagnosticOptions::DefaultSpellCheckingLimit, Diags); 1512 Opts.SnippetLineLimit = getLastArgIntValue( 1513 Args, OPT_fcaret_diagnostics_max_lines, 1514 DiagnosticOptions::DefaultSnippetLineLimit, Diags); 1515 Opts.TabStop = getLastArgIntValue(Args, OPT_ftabstop, 1516 DiagnosticOptions::DefaultTabStop, Diags); 1517 if (Opts.TabStop == 0 || Opts.TabStop > DiagnosticOptions::MaxTabStop) { 1518 Opts.TabStop = DiagnosticOptions::DefaultTabStop; 1519 if (Diags) 1520 Diags->Report(diag::warn_ignoring_ftabstop_value) 1521 << Opts.TabStop << DiagnosticOptions::DefaultTabStop; 1522 } 1523 Opts.MessageLength = 1524 getLastArgIntValue(Args, OPT_fmessage_length_EQ, 0, Diags); 1525 1526 Opts.UndefPrefixes = Args.getAllArgValues(OPT_Wundef_prefix_EQ); 1527 1528 addDiagnosticArgs(Args, OPT_W_Group, OPT_W_value_Group, Opts.Warnings); 1529 addDiagnosticArgs(Args, OPT_R_Group, OPT_R_value_Group, Opts.Remarks); 1530 1531 return Success; 1532 } 1533 1534 /// Parse the argument to the -ftest-module-file-extension 1535 /// command-line argument. 1536 /// 1537 /// \returns true on error, false on success. 1538 static bool parseTestModuleFileExtensionArg(StringRef Arg, 1539 std::string &BlockName, 1540 unsigned &MajorVersion, 1541 unsigned &MinorVersion, 1542 bool &Hashed, 1543 std::string &UserInfo) { 1544 SmallVector<StringRef, 5> Args; 1545 Arg.split(Args, ':', 5); 1546 if (Args.size() < 5) 1547 return true; 1548 1549 BlockName = std::string(Args[0]); 1550 if (Args[1].getAsInteger(10, MajorVersion)) return true; 1551 if (Args[2].getAsInteger(10, MinorVersion)) return true; 1552 if (Args[3].getAsInteger(2, Hashed)) return true; 1553 if (Args.size() > 4) 1554 UserInfo = std::string(Args[4]); 1555 return false; 1556 } 1557 1558 static InputKind ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args, 1559 DiagnosticsEngine &Diags, 1560 bool &IsHeaderFile) { 1561 Opts.ProgramAction = frontend::ParseSyntaxOnly; 1562 if (const Arg *A = Args.getLastArg(OPT_Action_Group)) { 1563 switch (A->getOption().getID()) { 1564 default: 1565 llvm_unreachable("Invalid option in group!"); 1566 case OPT_ast_list: 1567 Opts.ProgramAction = frontend::ASTDeclList; break; 1568 case OPT_ast_dump_all_EQ: 1569 case OPT_ast_dump_EQ: { 1570 unsigned Val = llvm::StringSwitch<unsigned>(A->getValue()) 1571 .CaseLower("default", ADOF_Default) 1572 .CaseLower("json", ADOF_JSON) 1573 .Default(std::numeric_limits<unsigned>::max()); 1574 1575 if (Val != std::numeric_limits<unsigned>::max()) 1576 Opts.ASTDumpFormat = static_cast<ASTDumpOutputFormat>(Val); 1577 else { 1578 Diags.Report(diag::err_drv_invalid_value) 1579 << A->getAsString(Args) << A->getValue(); 1580 Opts.ASTDumpFormat = ADOF_Default; 1581 } 1582 LLVM_FALLTHROUGH; 1583 } 1584 case OPT_ast_dump: 1585 case OPT_ast_dump_all: 1586 case OPT_ast_dump_lookups: 1587 case OPT_ast_dump_decl_types: 1588 Opts.ProgramAction = frontend::ASTDump; break; 1589 case OPT_ast_print: 1590 Opts.ProgramAction = frontend::ASTPrint; break; 1591 case OPT_ast_view: 1592 Opts.ProgramAction = frontend::ASTView; break; 1593 case OPT_compiler_options_dump: 1594 Opts.ProgramAction = frontend::DumpCompilerOptions; break; 1595 case OPT_dump_raw_tokens: 1596 Opts.ProgramAction = frontend::DumpRawTokens; break; 1597 case OPT_dump_tokens: 1598 Opts.ProgramAction = frontend::DumpTokens; break; 1599 case OPT_S: 1600 Opts.ProgramAction = frontend::EmitAssembly; break; 1601 case OPT_emit_llvm_bc: 1602 Opts.ProgramAction = frontend::EmitBC; break; 1603 case OPT_emit_html: 1604 Opts.ProgramAction = frontend::EmitHTML; break; 1605 case OPT_emit_llvm: 1606 Opts.ProgramAction = frontend::EmitLLVM; break; 1607 case OPT_emit_llvm_only: 1608 Opts.ProgramAction = frontend::EmitLLVMOnly; break; 1609 case OPT_emit_codegen_only: 1610 Opts.ProgramAction = frontend::EmitCodeGenOnly; break; 1611 case OPT_emit_obj: 1612 Opts.ProgramAction = frontend::EmitObj; break; 1613 case OPT_fixit_EQ: 1614 Opts.FixItSuffix = A->getValue(); 1615 LLVM_FALLTHROUGH; 1616 case OPT_fixit: 1617 Opts.ProgramAction = frontend::FixIt; break; 1618 case OPT_emit_module: 1619 Opts.ProgramAction = frontend::GenerateModule; break; 1620 case OPT_emit_module_interface: 1621 Opts.ProgramAction = frontend::GenerateModuleInterface; break; 1622 case OPT_emit_header_module: 1623 Opts.ProgramAction = frontend::GenerateHeaderModule; break; 1624 case OPT_emit_pch: 1625 Opts.ProgramAction = frontend::GeneratePCH; break; 1626 case OPT_emit_interface_stubs: { 1627 StringRef ArgStr = 1628 Args.hasArg(OPT_interface_stub_version_EQ) 1629 ? Args.getLastArgValue(OPT_interface_stub_version_EQ) 1630 : "experimental-ifs-v2"; 1631 if (ArgStr == "experimental-yaml-elf-v1" || 1632 ArgStr == "experimental-ifs-v1" || 1633 ArgStr == "experimental-tapi-elf-v1") { 1634 std::string ErrorMessage = 1635 "Invalid interface stub format: " + ArgStr.str() + 1636 " is deprecated."; 1637 Diags.Report(diag::err_drv_invalid_value) 1638 << "Must specify a valid interface stub format type, ie: " 1639 "-interface-stub-version=experimental-ifs-v2" 1640 << ErrorMessage; 1641 } else if (!ArgStr.startswith("experimental-ifs-")) { 1642 std::string ErrorMessage = 1643 "Invalid interface stub format: " + ArgStr.str() + "."; 1644 Diags.Report(diag::err_drv_invalid_value) 1645 << "Must specify a valid interface stub format type, ie: " 1646 "-interface-stub-version=experimental-ifs-v2" 1647 << ErrorMessage; 1648 } else { 1649 Opts.ProgramAction = frontend::GenerateInterfaceStubs; 1650 } 1651 break; 1652 } 1653 case OPT_init_only: 1654 Opts.ProgramAction = frontend::InitOnly; break; 1655 case OPT_fsyntax_only: 1656 Opts.ProgramAction = frontend::ParseSyntaxOnly; break; 1657 case OPT_module_file_info: 1658 Opts.ProgramAction = frontend::ModuleFileInfo; break; 1659 case OPT_verify_pch: 1660 Opts.ProgramAction = frontend::VerifyPCH; break; 1661 case OPT_print_preamble: 1662 Opts.ProgramAction = frontend::PrintPreamble; break; 1663 case OPT_E: 1664 Opts.ProgramAction = frontend::PrintPreprocessedInput; break; 1665 case OPT_templight_dump: 1666 Opts.ProgramAction = frontend::TemplightDump; break; 1667 case OPT_rewrite_macros: 1668 Opts.ProgramAction = frontend::RewriteMacros; break; 1669 case OPT_rewrite_objc: 1670 Opts.ProgramAction = frontend::RewriteObjC; break; 1671 case OPT_rewrite_test: 1672 Opts.ProgramAction = frontend::RewriteTest; break; 1673 case OPT_analyze: 1674 Opts.ProgramAction = frontend::RunAnalysis; break; 1675 case OPT_migrate: 1676 Opts.ProgramAction = frontend::MigrateSource; break; 1677 case OPT_Eonly: 1678 Opts.ProgramAction = frontend::RunPreprocessorOnly; break; 1679 case OPT_print_dependency_directives_minimized_source: 1680 Opts.ProgramAction = 1681 frontend::PrintDependencyDirectivesSourceMinimizerOutput; 1682 break; 1683 } 1684 } 1685 1686 if (const Arg* A = Args.getLastArg(OPT_plugin)) { 1687 Opts.Plugins.emplace_back(A->getValue(0)); 1688 Opts.ProgramAction = frontend::PluginAction; 1689 Opts.ActionName = A->getValue(); 1690 } 1691 Opts.AddPluginActions = Args.getAllArgValues(OPT_add_plugin); 1692 for (const auto *AA : Args.filtered(OPT_plugin_arg)) 1693 Opts.PluginArgs[AA->getValue(0)].emplace_back(AA->getValue(1)); 1694 1695 for (const std::string &Arg : 1696 Args.getAllArgValues(OPT_ftest_module_file_extension_EQ)) { 1697 std::string BlockName; 1698 unsigned MajorVersion; 1699 unsigned MinorVersion; 1700 bool Hashed; 1701 std::string UserInfo; 1702 if (parseTestModuleFileExtensionArg(Arg, BlockName, MajorVersion, 1703 MinorVersion, Hashed, UserInfo)) { 1704 Diags.Report(diag::err_test_module_file_extension_format) << Arg; 1705 1706 continue; 1707 } 1708 1709 // Add the testing module file extension. 1710 Opts.ModuleFileExtensions.push_back( 1711 std::make_shared<TestModuleFileExtension>( 1712 BlockName, MajorVersion, MinorVersion, Hashed, UserInfo)); 1713 } 1714 1715 if (const Arg *A = Args.getLastArg(OPT_code_completion_at)) { 1716 Opts.CodeCompletionAt = 1717 ParsedSourceLocation::FromString(A->getValue()); 1718 if (Opts.CodeCompletionAt.FileName.empty()) 1719 Diags.Report(diag::err_drv_invalid_value) 1720 << A->getAsString(Args) << A->getValue(); 1721 } 1722 1723 Opts.Plugins = Args.getAllArgValues(OPT_load); 1724 Opts.ASTMergeFiles = Args.getAllArgValues(OPT_ast_merge); 1725 Opts.LLVMArgs = Args.getAllArgValues(OPT_mllvm); 1726 Opts.ASTDumpDecls = Args.hasArg(OPT_ast_dump, OPT_ast_dump_EQ); 1727 Opts.ASTDumpAll = Args.hasArg(OPT_ast_dump_all, OPT_ast_dump_all_EQ); 1728 // Only the -fmodule-file=<file> form. 1729 for (const auto *A : Args.filtered(OPT_fmodule_file)) { 1730 StringRef Val = A->getValue(); 1731 if (Val.find('=') == StringRef::npos) 1732 Opts.ModuleFiles.push_back(std::string(Val)); 1733 } 1734 Opts.ModulesEmbedFiles = Args.getAllArgValues(OPT_fmodules_embed_file_EQ); 1735 Opts.AllowPCMWithCompilerErrors = Args.hasArg(OPT_fallow_pcm_with_errors); 1736 1737 if (Opts.ProgramAction != frontend::GenerateModule && Opts.IsSystemModule) 1738 Diags.Report(diag::err_drv_argument_only_allowed_with) << "-fsystem-module" 1739 << "-emit-module"; 1740 1741 if (Args.hasArg(OPT_aux_target_cpu)) 1742 Opts.AuxTargetCPU = std::string(Args.getLastArgValue(OPT_aux_target_cpu)); 1743 if (Args.hasArg(OPT_aux_target_feature)) 1744 Opts.AuxTargetFeatures = Args.getAllArgValues(OPT_aux_target_feature); 1745 1746 if (Opts.ARCMTAction != FrontendOptions::ARCMT_None && 1747 Opts.ObjCMTAction != FrontendOptions::ObjCMT_None) { 1748 Diags.Report(diag::err_drv_argument_not_allowed_with) 1749 << "ARC migration" << "ObjC migration"; 1750 } 1751 1752 InputKind DashX(Language::Unknown); 1753 if (const Arg *A = Args.getLastArg(OPT_x)) { 1754 StringRef XValue = A->getValue(); 1755 1756 // Parse suffixes: '<lang>(-header|[-module-map][-cpp-output])'. 1757 // FIXME: Supporting '<lang>-header-cpp-output' would be useful. 1758 bool Preprocessed = XValue.consume_back("-cpp-output"); 1759 bool ModuleMap = XValue.consume_back("-module-map"); 1760 IsHeaderFile = !Preprocessed && !ModuleMap && 1761 XValue != "precompiled-header" && 1762 XValue.consume_back("-header"); 1763 1764 // Principal languages. 1765 DashX = llvm::StringSwitch<InputKind>(XValue) 1766 .Case("c", Language::C) 1767 .Case("cl", Language::OpenCL) 1768 .Case("cuda", Language::CUDA) 1769 .Case("hip", Language::HIP) 1770 .Case("c++", Language::CXX) 1771 .Case("objective-c", Language::ObjC) 1772 .Case("objective-c++", Language::ObjCXX) 1773 .Case("renderscript", Language::RenderScript) 1774 .Default(Language::Unknown); 1775 1776 // "objc[++]-cpp-output" is an acceptable synonym for 1777 // "objective-c[++]-cpp-output". 1778 if (DashX.isUnknown() && Preprocessed && !IsHeaderFile && !ModuleMap) 1779 DashX = llvm::StringSwitch<InputKind>(XValue) 1780 .Case("objc", Language::ObjC) 1781 .Case("objc++", Language::ObjCXX) 1782 .Default(Language::Unknown); 1783 1784 // Some special cases cannot be combined with suffixes. 1785 if (DashX.isUnknown() && !Preprocessed && !ModuleMap && !IsHeaderFile) 1786 DashX = llvm::StringSwitch<InputKind>(XValue) 1787 .Case("cpp-output", InputKind(Language::C).getPreprocessed()) 1788 .Case("assembler-with-cpp", Language::Asm) 1789 .Cases("ast", "pcm", "precompiled-header", 1790 InputKind(Language::Unknown, InputKind::Precompiled)) 1791 .Case("ir", Language::LLVM_IR) 1792 .Default(Language::Unknown); 1793 1794 if (DashX.isUnknown()) 1795 Diags.Report(diag::err_drv_invalid_value) 1796 << A->getAsString(Args) << A->getValue(); 1797 1798 if (Preprocessed) 1799 DashX = DashX.getPreprocessed(); 1800 if (ModuleMap) 1801 DashX = DashX.withFormat(InputKind::ModuleMap); 1802 } 1803 1804 // '-' is the default input if none is given. 1805 std::vector<std::string> Inputs = Args.getAllArgValues(OPT_INPUT); 1806 Opts.Inputs.clear(); 1807 if (Inputs.empty()) 1808 Inputs.push_back("-"); 1809 for (unsigned i = 0, e = Inputs.size(); i != e; ++i) { 1810 InputKind IK = DashX; 1811 if (IK.isUnknown()) { 1812 IK = FrontendOptions::getInputKindForExtension( 1813 StringRef(Inputs[i]).rsplit('.').second); 1814 // FIXME: Warn on this? 1815 if (IK.isUnknown()) 1816 IK = Language::C; 1817 // FIXME: Remove this hack. 1818 if (i == 0) 1819 DashX = IK; 1820 } 1821 1822 bool IsSystem = false; 1823 1824 // The -emit-module action implicitly takes a module map. 1825 if (Opts.ProgramAction == frontend::GenerateModule && 1826 IK.getFormat() == InputKind::Source) { 1827 IK = IK.withFormat(InputKind::ModuleMap); 1828 IsSystem = Opts.IsSystemModule; 1829 } 1830 1831 Opts.Inputs.emplace_back(std::move(Inputs[i]), IK, IsSystem); 1832 } 1833 1834 return DashX; 1835 } 1836 1837 std::string CompilerInvocation::GetResourcesPath(const char *Argv0, 1838 void *MainAddr) { 1839 std::string ClangExecutable = 1840 llvm::sys::fs::getMainExecutable(Argv0, MainAddr); 1841 return Driver::GetResourcesPath(ClangExecutable, CLANG_RESOURCE_DIR); 1842 } 1843 1844 static void ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args, 1845 const std::string &WorkingDir) { 1846 if (const Arg *A = Args.getLastArg(OPT_stdlib_EQ)) 1847 Opts.UseLibcxx = (strcmp(A->getValue(), "libc++") == 0); 1848 1849 // Canonicalize -fmodules-cache-path before storing it. 1850 SmallString<128> P(Args.getLastArgValue(OPT_fmodules_cache_path)); 1851 if (!(P.empty() || llvm::sys::path::is_absolute(P))) { 1852 if (WorkingDir.empty()) 1853 llvm::sys::fs::make_absolute(P); 1854 else 1855 llvm::sys::fs::make_absolute(WorkingDir, P); 1856 } 1857 llvm::sys::path::remove_dots(P); 1858 Opts.ModuleCachePath = std::string(P.str()); 1859 1860 // Only the -fmodule-file=<name>=<file> form. 1861 for (const auto *A : Args.filtered(OPT_fmodule_file)) { 1862 StringRef Val = A->getValue(); 1863 if (Val.find('=') != StringRef::npos){ 1864 auto Split = Val.split('='); 1865 Opts.PrebuiltModuleFiles.insert( 1866 {std::string(Split.first), std::string(Split.second)}); 1867 } 1868 } 1869 for (const auto *A : Args.filtered(OPT_fprebuilt_module_path)) 1870 Opts.AddPrebuiltModulePath(A->getValue()); 1871 1872 for (const auto *A : Args.filtered(OPT_fmodules_ignore_macro)) { 1873 StringRef MacroDef = A->getValue(); 1874 Opts.ModulesIgnoreMacros.insert( 1875 llvm::CachedHashString(MacroDef.split('=').first)); 1876 } 1877 1878 // Add -I..., -F..., and -index-header-map options in order. 1879 bool IsIndexHeaderMap = false; 1880 bool IsSysrootSpecified = 1881 Args.hasArg(OPT__sysroot_EQ) || Args.hasArg(OPT_isysroot); 1882 for (const auto *A : Args.filtered(OPT_I, OPT_F, OPT_index_header_map)) { 1883 if (A->getOption().matches(OPT_index_header_map)) { 1884 // -index-header-map applies to the next -I or -F. 1885 IsIndexHeaderMap = true; 1886 continue; 1887 } 1888 1889 frontend::IncludeDirGroup Group = 1890 IsIndexHeaderMap ? frontend::IndexHeaderMap : frontend::Angled; 1891 1892 bool IsFramework = A->getOption().matches(OPT_F); 1893 std::string Path = A->getValue(); 1894 1895 if (IsSysrootSpecified && !IsFramework && A->getValue()[0] == '=') { 1896 SmallString<32> Buffer; 1897 llvm::sys::path::append(Buffer, Opts.Sysroot, 1898 llvm::StringRef(A->getValue()).substr(1)); 1899 Path = std::string(Buffer.str()); 1900 } 1901 1902 Opts.AddPath(Path, Group, IsFramework, 1903 /*IgnoreSysroot*/ true); 1904 IsIndexHeaderMap = false; 1905 } 1906 1907 // Add -iprefix/-iwithprefix/-iwithprefixbefore options. 1908 StringRef Prefix = ""; // FIXME: This isn't the correct default prefix. 1909 for (const auto *A : 1910 Args.filtered(OPT_iprefix, OPT_iwithprefix, OPT_iwithprefixbefore)) { 1911 if (A->getOption().matches(OPT_iprefix)) 1912 Prefix = A->getValue(); 1913 else if (A->getOption().matches(OPT_iwithprefix)) 1914 Opts.AddPath(Prefix.str() + A->getValue(), frontend::After, false, true); 1915 else 1916 Opts.AddPath(Prefix.str() + A->getValue(), frontend::Angled, false, true); 1917 } 1918 1919 for (const auto *A : Args.filtered(OPT_idirafter)) 1920 Opts.AddPath(A->getValue(), frontend::After, false, true); 1921 for (const auto *A : Args.filtered(OPT_iquote)) 1922 Opts.AddPath(A->getValue(), frontend::Quoted, false, true); 1923 for (const auto *A : Args.filtered(OPT_isystem, OPT_iwithsysroot)) 1924 Opts.AddPath(A->getValue(), frontend::System, false, 1925 !A->getOption().matches(OPT_iwithsysroot)); 1926 for (const auto *A : Args.filtered(OPT_iframework)) 1927 Opts.AddPath(A->getValue(), frontend::System, true, true); 1928 for (const auto *A : Args.filtered(OPT_iframeworkwithsysroot)) 1929 Opts.AddPath(A->getValue(), frontend::System, /*IsFramework=*/true, 1930 /*IgnoreSysRoot=*/false); 1931 1932 // Add the paths for the various language specific isystem flags. 1933 for (const auto *A : Args.filtered(OPT_c_isystem)) 1934 Opts.AddPath(A->getValue(), frontend::CSystem, false, true); 1935 for (const auto *A : Args.filtered(OPT_cxx_isystem)) 1936 Opts.AddPath(A->getValue(), frontend::CXXSystem, false, true); 1937 for (const auto *A : Args.filtered(OPT_objc_isystem)) 1938 Opts.AddPath(A->getValue(), frontend::ObjCSystem, false,true); 1939 for (const auto *A : Args.filtered(OPT_objcxx_isystem)) 1940 Opts.AddPath(A->getValue(), frontend::ObjCXXSystem, false, true); 1941 1942 // Add the internal paths from a driver that detects standard include paths. 1943 for (const auto *A : 1944 Args.filtered(OPT_internal_isystem, OPT_internal_externc_isystem)) { 1945 frontend::IncludeDirGroup Group = frontend::System; 1946 if (A->getOption().matches(OPT_internal_externc_isystem)) 1947 Group = frontend::ExternCSystem; 1948 Opts.AddPath(A->getValue(), Group, false, true); 1949 } 1950 1951 // Add the path prefixes which are implicitly treated as being system headers. 1952 for (const auto *A : 1953 Args.filtered(OPT_system_header_prefix, OPT_no_system_header_prefix)) 1954 Opts.AddSystemHeaderPrefix( 1955 A->getValue(), A->getOption().matches(OPT_system_header_prefix)); 1956 1957 for (const auto *A : Args.filtered(OPT_ivfsoverlay)) 1958 Opts.AddVFSOverlayFile(A->getValue()); 1959 } 1960 1961 void CompilerInvocation::setLangDefaults(LangOptions &Opts, InputKind IK, 1962 const llvm::Triple &T, 1963 PreprocessorOptions &PPOpts, 1964 LangStandard::Kind LangStd) { 1965 // Set some properties which depend solely on the input kind; it would be nice 1966 // to move these to the language standard, and have the driver resolve the 1967 // input kind + language standard. 1968 // 1969 // FIXME: Perhaps a better model would be for a single source file to have 1970 // multiple language standards (C / C++ std, ObjC std, OpenCL std, OpenMP std) 1971 // simultaneously active? 1972 if (IK.getLanguage() == Language::Asm) { 1973 Opts.AsmPreprocessor = 1; 1974 } else if (IK.isObjectiveC()) { 1975 Opts.ObjC = 1; 1976 } 1977 1978 if (LangStd == LangStandard::lang_unspecified) { 1979 // Based on the base language, pick one. 1980 switch (IK.getLanguage()) { 1981 case Language::Unknown: 1982 case Language::LLVM_IR: 1983 llvm_unreachable("Invalid input kind!"); 1984 case Language::OpenCL: 1985 LangStd = LangStandard::lang_opencl10; 1986 break; 1987 case Language::CUDA: 1988 LangStd = LangStandard::lang_cuda; 1989 break; 1990 case Language::Asm: 1991 case Language::C: 1992 #if defined(CLANG_DEFAULT_STD_C) 1993 LangStd = CLANG_DEFAULT_STD_C; 1994 #else 1995 // The PS4 uses C99 as the default C standard. 1996 if (T.isPS4()) 1997 LangStd = LangStandard::lang_gnu99; 1998 else 1999 LangStd = LangStandard::lang_gnu17; 2000 #endif 2001 break; 2002 case Language::ObjC: 2003 #if defined(CLANG_DEFAULT_STD_C) 2004 LangStd = CLANG_DEFAULT_STD_C; 2005 #else 2006 LangStd = LangStandard::lang_gnu11; 2007 #endif 2008 break; 2009 case Language::CXX: 2010 case Language::ObjCXX: 2011 #if defined(CLANG_DEFAULT_STD_CXX) 2012 LangStd = CLANG_DEFAULT_STD_CXX; 2013 #else 2014 LangStd = LangStandard::lang_gnucxx14; 2015 #endif 2016 break; 2017 case Language::RenderScript: 2018 LangStd = LangStandard::lang_c99; 2019 break; 2020 case Language::HIP: 2021 LangStd = LangStandard::lang_hip; 2022 break; 2023 } 2024 } 2025 2026 const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd); 2027 Opts.LineComment = Std.hasLineComments(); 2028 Opts.C99 = Std.isC99(); 2029 Opts.C11 = Std.isC11(); 2030 Opts.C17 = Std.isC17(); 2031 Opts.C2x = Std.isC2x(); 2032 Opts.CPlusPlus = Std.isCPlusPlus(); 2033 Opts.CPlusPlus11 = Std.isCPlusPlus11(); 2034 Opts.CPlusPlus14 = Std.isCPlusPlus14(); 2035 Opts.CPlusPlus17 = Std.isCPlusPlus17(); 2036 Opts.CPlusPlus20 = Std.isCPlusPlus20(); 2037 Opts.CPlusPlus2b = Std.isCPlusPlus2b(); 2038 Opts.Digraphs = Std.hasDigraphs(); 2039 Opts.GNUMode = Std.isGNUMode(); 2040 Opts.GNUInline = !Opts.C99 && !Opts.CPlusPlus; 2041 Opts.GNUCVersion = 0; 2042 Opts.HexFloats = Std.hasHexFloats(); 2043 Opts.ImplicitInt = Std.hasImplicitInt(); 2044 2045 // Set OpenCL Version. 2046 Opts.OpenCL = Std.isOpenCL(); 2047 if (LangStd == LangStandard::lang_opencl10) 2048 Opts.OpenCLVersion = 100; 2049 else if (LangStd == LangStandard::lang_opencl11) 2050 Opts.OpenCLVersion = 110; 2051 else if (LangStd == LangStandard::lang_opencl12) 2052 Opts.OpenCLVersion = 120; 2053 else if (LangStd == LangStandard::lang_opencl20) 2054 Opts.OpenCLVersion = 200; 2055 else if (LangStd == LangStandard::lang_opencl30) 2056 Opts.OpenCLVersion = 300; 2057 else if (LangStd == LangStandard::lang_openclcpp) 2058 Opts.OpenCLCPlusPlusVersion = 100; 2059 2060 // OpenCL has some additional defaults. 2061 if (Opts.OpenCL) { 2062 Opts.AltiVec = 0; 2063 Opts.ZVector = 0; 2064 Opts.setLaxVectorConversions(LangOptions::LaxVectorConversionKind::None); 2065 Opts.setDefaultFPContractMode(LangOptions::FPM_On); 2066 Opts.NativeHalfType = 1; 2067 Opts.NativeHalfArgsAndReturns = 1; 2068 Opts.OpenCLCPlusPlus = Opts.CPlusPlus; 2069 2070 // Include default header file for OpenCL. 2071 if (Opts.IncludeDefaultHeader) { 2072 if (Opts.DeclareOpenCLBuiltins) { 2073 // Only include base header file for builtin types and constants. 2074 PPOpts.Includes.push_back("opencl-c-base.h"); 2075 } else { 2076 PPOpts.Includes.push_back("opencl-c.h"); 2077 } 2078 } 2079 } 2080 2081 Opts.HIP = IK.getLanguage() == Language::HIP; 2082 Opts.CUDA = IK.getLanguage() == Language::CUDA || Opts.HIP; 2083 if (Opts.HIP) { 2084 // HIP toolchain does not support 'Fast' FPOpFusion in backends since it 2085 // fuses multiplication/addition instructions without contract flag from 2086 // device library functions in LLVM bitcode, which causes accuracy loss in 2087 // certain math functions, e.g. tan(-1e20) becomes -0.933 instead of 0.8446. 2088 // For device library functions in bitcode to work, 'Strict' or 'Standard' 2089 // FPOpFusion options in backends is needed. Therefore 'fast-honor-pragmas' 2090 // FP contract option is used to allow fuse across statements in frontend 2091 // whereas respecting contract flag in backend. 2092 Opts.setDefaultFPContractMode(LangOptions::FPM_FastHonorPragmas); 2093 } else if (Opts.CUDA) { 2094 // Allow fuse across statements disregarding pragmas. 2095 Opts.setDefaultFPContractMode(LangOptions::FPM_Fast); 2096 } 2097 2098 Opts.RenderScript = IK.getLanguage() == Language::RenderScript; 2099 if (Opts.RenderScript) { 2100 Opts.NativeHalfType = 1; 2101 Opts.NativeHalfArgsAndReturns = 1; 2102 } 2103 2104 // OpenCL and C++ both have bool, true, false keywords. 2105 Opts.Bool = Opts.OpenCL || Opts.CPlusPlus; 2106 2107 // OpenCL has half keyword 2108 Opts.Half = Opts.OpenCL; 2109 2110 // C++ has wchar_t keyword. 2111 Opts.WChar = Opts.CPlusPlus; 2112 2113 Opts.GNUKeywords = Opts.GNUMode; 2114 Opts.CXXOperatorNames = Opts.CPlusPlus; 2115 2116 Opts.AlignedAllocation = Opts.CPlusPlus17; 2117 2118 Opts.DollarIdents = !Opts.AsmPreprocessor; 2119 2120 // Enable [[]] attributes in C++11 and C2x by default. 2121 Opts.DoubleSquareBracketAttributes = Opts.CPlusPlus11 || Opts.C2x; 2122 } 2123 2124 /// Attempt to parse a visibility value out of the given argument. 2125 static Visibility parseVisibility(Arg *arg, ArgList &args, 2126 DiagnosticsEngine &diags) { 2127 StringRef value = arg->getValue(); 2128 if (value == "default") { 2129 return DefaultVisibility; 2130 } else if (value == "hidden" || value == "internal") { 2131 return HiddenVisibility; 2132 } else if (value == "protected") { 2133 // FIXME: diagnose if target does not support protected visibility 2134 return ProtectedVisibility; 2135 } 2136 2137 diags.Report(diag::err_drv_invalid_value) 2138 << arg->getAsString(args) << value; 2139 return DefaultVisibility; 2140 } 2141 2142 /// Check if input file kind and language standard are compatible. 2143 static bool IsInputCompatibleWithStandard(InputKind IK, 2144 const LangStandard &S) { 2145 switch (IK.getLanguage()) { 2146 case Language::Unknown: 2147 case Language::LLVM_IR: 2148 llvm_unreachable("should not parse language flags for this input"); 2149 2150 case Language::C: 2151 case Language::ObjC: 2152 case Language::RenderScript: 2153 return S.getLanguage() == Language::C; 2154 2155 case Language::OpenCL: 2156 return S.getLanguage() == Language::OpenCL; 2157 2158 case Language::CXX: 2159 case Language::ObjCXX: 2160 return S.getLanguage() == Language::CXX; 2161 2162 case Language::CUDA: 2163 // FIXME: What -std= values should be permitted for CUDA compilations? 2164 return S.getLanguage() == Language::CUDA || 2165 S.getLanguage() == Language::CXX; 2166 2167 case Language::HIP: 2168 return S.getLanguage() == Language::CXX || S.getLanguage() == Language::HIP; 2169 2170 case Language::Asm: 2171 // Accept (and ignore) all -std= values. 2172 // FIXME: The -std= value is not ignored; it affects the tokenization 2173 // and preprocessing rules if we're preprocessing this asm input. 2174 return true; 2175 } 2176 2177 llvm_unreachable("unexpected input language"); 2178 } 2179 2180 /// Get language name for given input kind. 2181 static const StringRef GetInputKindName(InputKind IK) { 2182 switch (IK.getLanguage()) { 2183 case Language::C: 2184 return "C"; 2185 case Language::ObjC: 2186 return "Objective-C"; 2187 case Language::CXX: 2188 return "C++"; 2189 case Language::ObjCXX: 2190 return "Objective-C++"; 2191 case Language::OpenCL: 2192 return "OpenCL"; 2193 case Language::CUDA: 2194 return "CUDA"; 2195 case Language::RenderScript: 2196 return "RenderScript"; 2197 case Language::HIP: 2198 return "HIP"; 2199 2200 case Language::Asm: 2201 return "Asm"; 2202 case Language::LLVM_IR: 2203 return "LLVM IR"; 2204 2205 case Language::Unknown: 2206 break; 2207 } 2208 llvm_unreachable("unknown input language"); 2209 } 2210 2211 static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK, 2212 const TargetOptions &TargetOpts, 2213 PreprocessorOptions &PPOpts, 2214 DiagnosticsEngine &Diags) { 2215 // FIXME: Cleanup per-file based stuff. 2216 LangStandard::Kind LangStd = LangStandard::lang_unspecified; 2217 if (const Arg *A = Args.getLastArg(OPT_std_EQ)) { 2218 LangStd = LangStandard::getLangKind(A->getValue()); 2219 if (LangStd == LangStandard::lang_unspecified) { 2220 Diags.Report(diag::err_drv_invalid_value) 2221 << A->getAsString(Args) << A->getValue(); 2222 // Report supported standards with short description. 2223 for (unsigned KindValue = 0; 2224 KindValue != LangStandard::lang_unspecified; 2225 ++KindValue) { 2226 const LangStandard &Std = LangStandard::getLangStandardForKind( 2227 static_cast<LangStandard::Kind>(KindValue)); 2228 if (IsInputCompatibleWithStandard(IK, Std)) { 2229 auto Diag = Diags.Report(diag::note_drv_use_standard); 2230 Diag << Std.getName() << Std.getDescription(); 2231 unsigned NumAliases = 0; 2232 #define LANGSTANDARD(id, name, lang, desc, features) 2233 #define LANGSTANDARD_ALIAS(id, alias) \ 2234 if (KindValue == LangStandard::lang_##id) ++NumAliases; 2235 #define LANGSTANDARD_ALIAS_DEPR(id, alias) 2236 #include "clang/Basic/LangStandards.def" 2237 Diag << NumAliases; 2238 #define LANGSTANDARD(id, name, lang, desc, features) 2239 #define LANGSTANDARD_ALIAS(id, alias) \ 2240 if (KindValue == LangStandard::lang_##id) Diag << alias; 2241 #define LANGSTANDARD_ALIAS_DEPR(id, alias) 2242 #include "clang/Basic/LangStandards.def" 2243 } 2244 } 2245 } else { 2246 // Valid standard, check to make sure language and standard are 2247 // compatible. 2248 const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd); 2249 if (!IsInputCompatibleWithStandard(IK, Std)) { 2250 Diags.Report(diag::err_drv_argument_not_allowed_with) 2251 << A->getAsString(Args) << GetInputKindName(IK); 2252 } 2253 } 2254 } 2255 2256 if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) { 2257 StringRef Name = A->getValue(); 2258 if (Name == "full" || Name == "branch") { 2259 Opts.CFProtectionBranch = 1; 2260 } 2261 } 2262 // -cl-std only applies for OpenCL language standards. 2263 // Override the -std option in this case. 2264 if (const Arg *A = Args.getLastArg(OPT_cl_std_EQ)) { 2265 LangStandard::Kind OpenCLLangStd 2266 = llvm::StringSwitch<LangStandard::Kind>(A->getValue()) 2267 .Cases("cl", "CL", LangStandard::lang_opencl10) 2268 .Cases("cl1.0", "CL1.0", LangStandard::lang_opencl10) 2269 .Cases("cl1.1", "CL1.1", LangStandard::lang_opencl11) 2270 .Cases("cl1.2", "CL1.2", LangStandard::lang_opencl12) 2271 .Cases("cl2.0", "CL2.0", LangStandard::lang_opencl20) 2272 .Cases("cl3.0", "CL3.0", LangStandard::lang_opencl30) 2273 .Cases("clc++", "CLC++", LangStandard::lang_openclcpp) 2274 .Default(LangStandard::lang_unspecified); 2275 2276 if (OpenCLLangStd == LangStandard::lang_unspecified) { 2277 Diags.Report(diag::err_drv_invalid_value) 2278 << A->getAsString(Args) << A->getValue(); 2279 } 2280 else 2281 LangStd = OpenCLLangStd; 2282 } 2283 2284 Opts.SYCLIsDevice = Opts.SYCL && Args.hasArg(options::OPT_fsycl_is_device); 2285 if (Opts.SYCL) { 2286 // -sycl-std applies to any SYCL source, not only those containing kernels, 2287 // but also those using the SYCL API 2288 if (const Arg *A = Args.getLastArg(OPT_sycl_std_EQ)) { 2289 Opts.setSYCLVersion( 2290 llvm::StringSwitch<LangOptions::SYCLMajorVersion>(A->getValue()) 2291 .Cases("2017", "1.2.1", "121", "sycl-1.2.1", 2292 LangOptions::SYCL_2017) 2293 .Default(LangOptions::SYCL_None)); 2294 2295 if (Opts.getSYCLVersion() == LangOptions::SYCL_None) { 2296 // User has passed an invalid value to the flag, this is an error 2297 Diags.Report(diag::err_drv_invalid_value) 2298 << A->getAsString(Args) << A->getValue(); 2299 } 2300 } 2301 } 2302 2303 llvm::Triple T(TargetOpts.Triple); 2304 CompilerInvocation::setLangDefaults(Opts, IK, T, PPOpts, LangStd); 2305 2306 // -cl-strict-aliasing needs to emit diagnostic in the case where CL > 1.0. 2307 // This option should be deprecated for CL > 1.0 because 2308 // this option was added for compatibility with OpenCL 1.0. 2309 if (Args.getLastArg(OPT_cl_strict_aliasing) 2310 && Opts.OpenCLVersion > 100) { 2311 Diags.Report(diag::warn_option_invalid_ocl_version) 2312 << Opts.getOpenCLVersionTuple().getAsString() 2313 << Args.getLastArg(OPT_cl_strict_aliasing)->getAsString(Args); 2314 } 2315 2316 // We abuse '-f[no-]gnu-keywords' to force overriding all GNU-extension 2317 // keywords. This behavior is provided by GCC's poorly named '-fasm' flag, 2318 // while a subset (the non-C++ GNU keywords) is provided by GCC's 2319 // '-fgnu-keywords'. Clang conflates the two for simplicity under the single 2320 // name, as it doesn't seem a useful distinction. 2321 Opts.GNUKeywords = Args.hasFlag(OPT_fgnu_keywords, OPT_fno_gnu_keywords, 2322 Opts.GNUKeywords); 2323 2324 Opts.Digraphs = Args.hasFlag(OPT_fdigraphs, OPT_fno_digraphs, Opts.Digraphs); 2325 2326 if (Args.hasArg(OPT_fno_operator_names)) 2327 Opts.CXXOperatorNames = 0; 2328 2329 if (Opts.CUDAIsDevice && Args.hasArg(OPT_fcuda_approx_transcendentals)) 2330 Opts.CUDADeviceApproxTranscendentals = 1; 2331 2332 if (Args.hasArg(OPT_fgpu_allow_device_init)) { 2333 if (Opts.HIP) 2334 Opts.GPUAllowDeviceInit = 1; 2335 else 2336 Diags.Report(diag::warn_ignored_hip_only_option) 2337 << Args.getLastArg(OPT_fgpu_allow_device_init)->getAsString(Args); 2338 } 2339 if (Opts.HIP) 2340 Opts.GPUMaxThreadsPerBlock = getLastArgIntValue( 2341 Args, OPT_gpu_max_threads_per_block_EQ, Opts.GPUMaxThreadsPerBlock); 2342 else if (Args.hasArg(OPT_gpu_max_threads_per_block_EQ)) 2343 Diags.Report(diag::warn_ignored_hip_only_option) 2344 << Args.getLastArg(OPT_gpu_max_threads_per_block_EQ)->getAsString(Args); 2345 2346 if (Opts.ObjC) { 2347 if (Arg *arg = Args.getLastArg(OPT_fobjc_runtime_EQ)) { 2348 StringRef value = arg->getValue(); 2349 if (Opts.ObjCRuntime.tryParse(value)) 2350 Diags.Report(diag::err_drv_unknown_objc_runtime) << value; 2351 } 2352 2353 if (Args.hasArg(OPT_fobjc_gc_only)) 2354 Opts.setGC(LangOptions::GCOnly); 2355 else if (Args.hasArg(OPT_fobjc_gc)) 2356 Opts.setGC(LangOptions::HybridGC); 2357 else if (Args.hasArg(OPT_fobjc_arc)) { 2358 Opts.ObjCAutoRefCount = 1; 2359 if (!Opts.ObjCRuntime.allowsARC()) 2360 Diags.Report(diag::err_arc_unsupported_on_runtime); 2361 } 2362 2363 // ObjCWeakRuntime tracks whether the runtime supports __weak, not 2364 // whether the feature is actually enabled. This is predominantly 2365 // determined by -fobjc-runtime, but we allow it to be overridden 2366 // from the command line for testing purposes. 2367 if (Args.hasArg(OPT_fobjc_runtime_has_weak)) 2368 Opts.ObjCWeakRuntime = 1; 2369 else 2370 Opts.ObjCWeakRuntime = Opts.ObjCRuntime.allowsWeak(); 2371 2372 // ObjCWeak determines whether __weak is actually enabled. 2373 // Note that we allow -fno-objc-weak to disable this even in ARC mode. 2374 if (auto weakArg = Args.getLastArg(OPT_fobjc_weak, OPT_fno_objc_weak)) { 2375 if (!weakArg->getOption().matches(OPT_fobjc_weak)) { 2376 assert(!Opts.ObjCWeak); 2377 } else if (Opts.getGC() != LangOptions::NonGC) { 2378 Diags.Report(diag::err_objc_weak_with_gc); 2379 } else if (!Opts.ObjCWeakRuntime) { 2380 Diags.Report(diag::err_objc_weak_unsupported); 2381 } else { 2382 Opts.ObjCWeak = 1; 2383 } 2384 } else if (Opts.ObjCAutoRefCount) { 2385 Opts.ObjCWeak = Opts.ObjCWeakRuntime; 2386 } 2387 2388 if (Args.hasArg(OPT_fobjc_subscripting_legacy_runtime)) 2389 Opts.ObjCSubscriptingLegacyRuntime = 2390 (Opts.ObjCRuntime.getKind() == ObjCRuntime::FragileMacOSX); 2391 } 2392 2393 if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) { 2394 // Check that the version has 1 to 3 components and the minor and patch 2395 // versions fit in two decimal digits. 2396 VersionTuple GNUCVer; 2397 bool Invalid = GNUCVer.tryParse(A->getValue()); 2398 unsigned Major = GNUCVer.getMajor(); 2399 unsigned Minor = GNUCVer.getMinor().getValueOr(0); 2400 unsigned Patch = GNUCVer.getSubminor().getValueOr(0); 2401 if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) { 2402 Diags.Report(diag::err_drv_invalid_value) 2403 << A->getAsString(Args) << A->getValue(); 2404 } 2405 Opts.GNUCVersion = Major * 100 * 100 + Minor * 100 + Patch; 2406 } 2407 2408 if (Args.hasArg(OPT_fgnu89_inline)) { 2409 if (Opts.CPlusPlus) 2410 Diags.Report(diag::err_drv_argument_not_allowed_with) 2411 << "-fgnu89-inline" << GetInputKindName(IK); 2412 else 2413 Opts.GNUInline = 1; 2414 } 2415 2416 // The type-visibility mode defaults to the value-visibility mode. 2417 if (Arg *typeVisOpt = Args.getLastArg(OPT_ftype_visibility)) { 2418 Opts.setTypeVisibilityMode(parseVisibility(typeVisOpt, Args, Diags)); 2419 } else { 2420 Opts.setTypeVisibilityMode(Opts.getValueVisibilityMode()); 2421 } 2422 2423 if (Args.hasArg(OPT_fvisibility_from_dllstorageclass)) { 2424 Opts.VisibilityFromDLLStorageClass = 1; 2425 2426 // Translate dllexport defintions to default visibility, by default. 2427 if (Arg *O = Args.getLastArg(OPT_fvisibility_dllexport_EQ)) 2428 Opts.setDLLExportVisibility(parseVisibility(O, Args, Diags)); 2429 else 2430 Opts.setDLLExportVisibility(DefaultVisibility); 2431 2432 // Translate defintions without an explict DLL storage class to hidden 2433 // visibility, by default. 2434 if (Arg *O = Args.getLastArg(OPT_fvisibility_nodllstorageclass_EQ)) 2435 Opts.setNoDLLStorageClassVisibility(parseVisibility(O, Args, Diags)); 2436 else 2437 Opts.setNoDLLStorageClassVisibility(HiddenVisibility); 2438 2439 // Translate dllimport external declarations to default visibility, by 2440 // default. 2441 if (Arg *O = Args.getLastArg(OPT_fvisibility_externs_dllimport_EQ)) 2442 Opts.setExternDeclDLLImportVisibility(parseVisibility(O, Args, Diags)); 2443 else 2444 Opts.setExternDeclDLLImportVisibility(DefaultVisibility); 2445 2446 // Translate external declarations without an explicit DLL storage class 2447 // to hidden visibility, by default. 2448 if (Arg *O = Args.getLastArg(OPT_fvisibility_externs_nodllstorageclass_EQ)) 2449 Opts.setExternDeclNoDLLStorageClassVisibility( 2450 parseVisibility(O, Args, Diags)); 2451 else 2452 Opts.setExternDeclNoDLLStorageClassVisibility(HiddenVisibility); 2453 } 2454 2455 if (Args.hasArg(OPT_ftrapv)) { 2456 Opts.setSignedOverflowBehavior(LangOptions::SOB_Trapping); 2457 // Set the handler, if one is specified. 2458 Opts.OverflowHandler = 2459 std::string(Args.getLastArgValue(OPT_ftrapv_handler)); 2460 } 2461 else if (Args.hasArg(OPT_fwrapv)) 2462 Opts.setSignedOverflowBehavior(LangOptions::SOB_Defined); 2463 2464 Opts.MicrosoftExt = Opts.MSVCCompat || Args.hasArg(OPT_fms_extensions); 2465 Opts.AsmBlocks = Args.hasArg(OPT_fasm_blocks) || Opts.MicrosoftExt; 2466 Opts.MSCompatibilityVersion = 0; 2467 if (const Arg *A = Args.getLastArg(OPT_fms_compatibility_version)) { 2468 VersionTuple VT; 2469 if (VT.tryParse(A->getValue())) 2470 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) 2471 << A->getValue(); 2472 Opts.MSCompatibilityVersion = VT.getMajor() * 10000000 + 2473 VT.getMinor().getValueOr(0) * 100000 + 2474 VT.getSubminor().getValueOr(0); 2475 } 2476 2477 // Mimicking gcc's behavior, trigraphs are only enabled if -trigraphs 2478 // is specified, or -std is set to a conforming mode. 2479 // Trigraphs are disabled by default in c++1z onwards. 2480 // For z/OS, trigraphs are enabled by default (without regard to the above). 2481 Opts.Trigraphs = 2482 (!Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus17) || T.isOSzOS(); 2483 Opts.Trigraphs = 2484 Args.hasFlag(OPT_ftrigraphs, OPT_fno_trigraphs, Opts.Trigraphs); 2485 2486 Opts.DollarIdents = Args.hasFlag(OPT_fdollars_in_identifiers, 2487 OPT_fno_dollars_in_identifiers, 2488 Opts.DollarIdents); 2489 2490 // -ffixed-point 2491 Opts.FixedPoint = 2492 Args.hasFlag(OPT_ffixed_point, OPT_fno_fixed_point, /*Default=*/false) && 2493 !Opts.CPlusPlus; 2494 Opts.PaddingOnUnsignedFixedPoint = 2495 Args.hasFlag(OPT_fpadding_on_unsigned_fixed_point, 2496 OPT_fno_padding_on_unsigned_fixed_point, 2497 /*Default=*/false) && 2498 Opts.FixedPoint; 2499 2500 Opts.RTTI = Opts.CPlusPlus && !Args.hasArg(OPT_fno_rtti); 2501 Opts.RTTIData = Opts.RTTI && !Args.hasArg(OPT_fno_rtti_data); 2502 Opts.Blocks = Args.hasArg(OPT_fblocks) || (Opts.OpenCL 2503 && Opts.OpenCLVersion == 200); 2504 Opts.Coroutines = Opts.CPlusPlus20 || Args.hasArg(OPT_fcoroutines_ts); 2505 2506 Opts.ConvergentFunctions = Opts.OpenCL || (Opts.CUDA && Opts.CUDAIsDevice) || 2507 Opts.SYCLIsDevice || 2508 Args.hasArg(OPT_fconvergent_functions); 2509 2510 Opts.DoubleSquareBracketAttributes = 2511 Args.hasFlag(OPT_fdouble_square_bracket_attributes, 2512 OPT_fno_double_square_bracket_attributes, 2513 Opts.DoubleSquareBracketAttributes); 2514 2515 Opts.CPlusPlusModules = Opts.CPlusPlus20; 2516 Opts.Modules = 2517 Args.hasArg(OPT_fmodules) || Opts.ModulesTS || Opts.CPlusPlusModules; 2518 Opts.ModulesDeclUse = 2519 Args.hasArg(OPT_fmodules_decluse) || Opts.ModulesStrictDeclUse; 2520 // FIXME: We only need this in C++ modules / Modules TS if we might textually 2521 // enter a different module (eg, when building a header unit). 2522 Opts.ModulesLocalVisibility = 2523 Args.hasArg(OPT_fmodules_local_submodule_visibility) || Opts.ModulesTS || 2524 Opts.CPlusPlusModules; 2525 Opts.ModulesSearchAll = Opts.Modules && 2526 !Args.hasArg(OPT_fno_modules_search_all) && 2527 Args.hasArg(OPT_fmodules_search_all); 2528 Opts.CharIsSigned = Opts.OpenCL || !Args.hasArg(OPT_fno_signed_char); 2529 Opts.WChar = Opts.CPlusPlus && !Args.hasArg(OPT_fno_wchar); 2530 Opts.Char8 = Args.hasFlag(OPT_fchar8__t, OPT_fno_char8__t, Opts.CPlusPlus20); 2531 Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding; 2532 if (!Opts.NoBuiltin) 2533 getAllNoBuiltinFuncValues(Args, Opts.NoBuiltinFuncs); 2534 Opts.AlignedAllocation = 2535 Args.hasFlag(OPT_faligned_allocation, OPT_fno_aligned_allocation, 2536 Opts.AlignedAllocation); 2537 Opts.AlignedAllocationUnavailable = 2538 Opts.AlignedAllocation && Args.hasArg(OPT_aligned_alloc_unavailable); 2539 if (Args.hasArg(OPT_fconcepts_ts)) 2540 Diags.Report(diag::warn_fe_concepts_ts_flag); 2541 Opts.MathErrno = !Opts.OpenCL && Args.hasArg(OPT_fmath_errno); 2542 Opts.LongDoubleSize = Args.hasArg(OPT_mlong_double_128) 2543 ? 128 2544 : Args.hasArg(OPT_mlong_double_64) ? 64 : 0; 2545 Opts.EnableAIXExtendedAltivecABI = Args.hasArg(OPT_mabi_EQ_vec_extabi); 2546 Opts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags); 2547 Opts.DumpRecordLayouts = Opts.DumpRecordLayoutsSimple 2548 || Args.hasArg(OPT_fdump_record_layouts); 2549 if (Opts.FastRelaxedMath) 2550 Opts.setDefaultFPContractMode(LangOptions::FPM_Fast); 2551 Opts.ModuleFeatures = Args.getAllArgValues(OPT_fmodule_feature); 2552 llvm::sort(Opts.ModuleFeatures); 2553 Opts.NativeHalfType |= Args.hasArg(OPT_fnative_half_type); 2554 Opts.NativeHalfArgsAndReturns |= Args.hasArg(OPT_fnative_half_arguments_and_returns); 2555 // Enable HalfArgsAndReturns if present in Args or if NativeHalfArgsAndReturns 2556 // is enabled. 2557 Opts.HalfArgsAndReturns = Args.hasArg(OPT_fallow_half_arguments_and_returns) 2558 | Opts.NativeHalfArgsAndReturns; 2559 2560 Opts.ArmSveVectorBits = 2561 getLastArgIntValue(Args, options::OPT_msve_vector_bits_EQ, 0, Diags); 2562 2563 // __declspec is enabled by default for the PS4 by the driver, and also 2564 // enabled for Microsoft Extensions or Borland Extensions, here. 2565 // 2566 // FIXME: __declspec is also currently enabled for CUDA, but isn't really a 2567 // CUDA extension. However, it is required for supporting 2568 // __clang_cuda_builtin_vars.h, which uses __declspec(property). Once that has 2569 // been rewritten in terms of something more generic, remove the Opts.CUDA 2570 // term here. 2571 Opts.DeclSpecKeyword = 2572 Args.hasFlag(OPT_fdeclspec, OPT_fno_declspec, 2573 (Opts.MicrosoftExt || Opts.Borland || Opts.CUDA)); 2574 2575 // -mrtd option 2576 if (Arg *A = Args.getLastArg(OPT_mrtd)) { 2577 if (Opts.getDefaultCallingConv() != LangOptions::DCC_None) 2578 Diags.Report(diag::err_drv_argument_not_allowed_with) 2579 << A->getSpelling() << "-fdefault-calling-conv"; 2580 else { 2581 llvm::Triple T(TargetOpts.Triple); 2582 if (T.getArch() != llvm::Triple::x86) 2583 Diags.Report(diag::err_drv_argument_not_allowed_with) 2584 << A->getSpelling() << T.getTriple(); 2585 else 2586 Opts.setDefaultCallingConv(LangOptions::DCC_StdCall); 2587 } 2588 } 2589 2590 // Check if -fopenmp-simd is specified. 2591 bool IsSimdSpecified = 2592 Args.hasFlag(options::OPT_fopenmp_simd, options::OPT_fno_openmp_simd, 2593 /*Default=*/false); 2594 Opts.OpenMPSimd = !Opts.OpenMP && IsSimdSpecified; 2595 Opts.OpenMPUseTLS = 2596 Opts.OpenMP && !Args.hasArg(options::OPT_fnoopenmp_use_tls); 2597 Opts.OpenMPIsDevice = 2598 Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_is_device); 2599 Opts.OpenMPIRBuilder = 2600 Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_enable_irbuilder); 2601 bool IsTargetSpecified = 2602 Opts.OpenMPIsDevice || Args.hasArg(options::OPT_fopenmp_targets_EQ); 2603 2604 if (Opts.OpenMP || Opts.OpenMPSimd) { 2605 if (int Version = getLastArgIntValue( 2606 Args, OPT_fopenmp_version_EQ, 2607 (IsSimdSpecified || IsTargetSpecified) ? 50 : Opts.OpenMP, Diags)) 2608 Opts.OpenMP = Version; 2609 // Provide diagnostic when a given target is not expected to be an OpenMP 2610 // device or host. 2611 if (!Opts.OpenMPIsDevice) { 2612 switch (T.getArch()) { 2613 default: 2614 break; 2615 // Add unsupported host targets here: 2616 case llvm::Triple::nvptx: 2617 case llvm::Triple::nvptx64: 2618 Diags.Report(diag::err_drv_omp_host_target_not_supported) 2619 << TargetOpts.Triple; 2620 break; 2621 } 2622 } 2623 } 2624 2625 // Set the flag to prevent the implementation from emitting device exception 2626 // handling code for those requiring so. 2627 if ((Opts.OpenMPIsDevice && (T.isNVPTX() || T.isAMDGCN())) || 2628 Opts.OpenCLCPlusPlus) { 2629 Opts.Exceptions = 0; 2630 Opts.CXXExceptions = 0; 2631 } 2632 if (Opts.OpenMPIsDevice && T.isNVPTX()) { 2633 Opts.OpenMPCUDANumSMs = 2634 getLastArgIntValue(Args, options::OPT_fopenmp_cuda_number_of_sm_EQ, 2635 Opts.OpenMPCUDANumSMs, Diags); 2636 Opts.OpenMPCUDABlocksPerSM = 2637 getLastArgIntValue(Args, options::OPT_fopenmp_cuda_blocks_per_sm_EQ, 2638 Opts.OpenMPCUDABlocksPerSM, Diags); 2639 Opts.OpenMPCUDAReductionBufNum = getLastArgIntValue( 2640 Args, options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ, 2641 Opts.OpenMPCUDAReductionBufNum, Diags); 2642 } 2643 2644 // Get the OpenMP target triples if any. 2645 if (Arg *A = Args.getLastArg(options::OPT_fopenmp_targets_EQ)) { 2646 enum ArchPtrSize { Arch16Bit, Arch32Bit, Arch64Bit }; 2647 auto getArchPtrSize = [](const llvm::Triple &T) { 2648 if (T.isArch16Bit()) 2649 return Arch16Bit; 2650 if (T.isArch32Bit()) 2651 return Arch32Bit; 2652 assert(T.isArch64Bit() && "Expected 64-bit architecture"); 2653 return Arch64Bit; 2654 }; 2655 2656 for (unsigned i = 0; i < A->getNumValues(); ++i) { 2657 llvm::Triple TT(A->getValue(i)); 2658 2659 if (TT.getArch() == llvm::Triple::UnknownArch || 2660 !(TT.getArch() == llvm::Triple::aarch64 || TT.isPPC() || 2661 TT.getArch() == llvm::Triple::nvptx || 2662 TT.getArch() == llvm::Triple::nvptx64 || 2663 TT.getArch() == llvm::Triple::amdgcn || 2664 TT.getArch() == llvm::Triple::x86 || 2665 TT.getArch() == llvm::Triple::x86_64)) 2666 Diags.Report(diag::err_drv_invalid_omp_target) << A->getValue(i); 2667 else if (getArchPtrSize(T) != getArchPtrSize(TT)) 2668 Diags.Report(diag::err_drv_incompatible_omp_arch) 2669 << A->getValue(i) << T.str(); 2670 else 2671 Opts.OMPTargetTriples.push_back(TT); 2672 } 2673 } 2674 2675 // Get OpenMP host file path if any and report if a non existent file is 2676 // found 2677 if (Arg *A = Args.getLastArg(options::OPT_fopenmp_host_ir_file_path)) { 2678 Opts.OMPHostIRFile = A->getValue(); 2679 if (!llvm::sys::fs::exists(Opts.OMPHostIRFile)) 2680 Diags.Report(diag::err_drv_omp_host_ir_file_not_found) 2681 << Opts.OMPHostIRFile; 2682 } 2683 2684 // Set CUDA mode for OpenMP target NVPTX/AMDGCN if specified in options 2685 Opts.OpenMPCUDAMode = Opts.OpenMPIsDevice && (T.isNVPTX() || T.isAMDGCN()) && 2686 Args.hasArg(options::OPT_fopenmp_cuda_mode); 2687 2688 // Set CUDA support for parallel execution of target regions for OpenMP target 2689 // NVPTX/AMDGCN if specified in options. 2690 Opts.OpenMPCUDATargetParallel = 2691 Opts.OpenMPIsDevice && (T.isNVPTX() || T.isAMDGCN()) && 2692 Args.hasArg(options::OPT_fopenmp_cuda_parallel_target_regions); 2693 2694 // Set CUDA mode for OpenMP target NVPTX/AMDGCN if specified in options 2695 Opts.OpenMPCUDAForceFullRuntime = 2696 Opts.OpenMPIsDevice && (T.isNVPTX() || T.isAMDGCN()) && 2697 Args.hasArg(options::OPT_fopenmp_cuda_force_full_runtime); 2698 2699 // Record whether the __DEPRECATED define was requested. 2700 Opts.Deprecated = Args.hasFlag(OPT_fdeprecated_macro, 2701 OPT_fno_deprecated_macro, 2702 Opts.Deprecated); 2703 2704 // FIXME: Eliminate this dependency. 2705 unsigned Opt = getOptimizationLevel(Args, IK, Diags), 2706 OptSize = getOptimizationLevelSize(Args); 2707 Opts.Optimize = Opt != 0; 2708 Opts.OptimizeSize = OptSize != 0; 2709 2710 // This is the __NO_INLINE__ define, which just depends on things like the 2711 // optimization level and -fno-inline, not actually whether the backend has 2712 // inlining enabled. 2713 Opts.NoInlineDefine = !Opts.Optimize; 2714 if (Arg *InlineArg = Args.getLastArg( 2715 options::OPT_finline_functions, options::OPT_finline_hint_functions, 2716 options::OPT_fno_inline_functions, options::OPT_fno_inline)) 2717 if (InlineArg->getOption().matches(options::OPT_fno_inline)) 2718 Opts.NoInlineDefine = true; 2719 2720 if (Arg *A = Args.getLastArg(OPT_ffp_contract)) { 2721 StringRef Val = A->getValue(); 2722 if (Val == "fast") 2723 Opts.setDefaultFPContractMode(LangOptions::FPM_Fast); 2724 else if (Val == "on") 2725 Opts.setDefaultFPContractMode(LangOptions::FPM_On); 2726 else if (Val == "off") 2727 Opts.setDefaultFPContractMode(LangOptions::FPM_Off); 2728 else if (Val == "fast-honor-pragmas") 2729 Opts.setDefaultFPContractMode(LangOptions::FPM_FastHonorPragmas); 2730 else 2731 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val; 2732 } 2733 2734 if (Args.hasArg(OPT_ftrapping_math)) { 2735 Opts.setFPExceptionMode(LangOptions::FPE_Strict); 2736 } 2737 2738 if (Args.hasArg(OPT_fno_trapping_math)) { 2739 Opts.setFPExceptionMode(LangOptions::FPE_Ignore); 2740 } 2741 2742 LangOptions::FPExceptionModeKind FPEB = LangOptions::FPE_Ignore; 2743 if (Arg *A = Args.getLastArg(OPT_ffp_exception_behavior_EQ)) { 2744 StringRef Val = A->getValue(); 2745 if (Val.equals("ignore")) 2746 FPEB = LangOptions::FPE_Ignore; 2747 else if (Val.equals("maytrap")) 2748 FPEB = LangOptions::FPE_MayTrap; 2749 else if (Val.equals("strict")) 2750 FPEB = LangOptions::FPE_Strict; 2751 else 2752 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val; 2753 } 2754 Opts.setFPExceptionMode(FPEB); 2755 2756 // Parse -fsanitize= arguments. 2757 parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ), 2758 Diags, Opts.Sanitize); 2759 Opts.SanitizerBlacklistFiles = Args.getAllArgValues(OPT_fsanitize_blacklist); 2760 std::vector<std::string> systemBlacklists = 2761 Args.getAllArgValues(OPT_fsanitize_system_blacklist); 2762 Opts.SanitizerBlacklistFiles.insert(Opts.SanitizerBlacklistFiles.end(), 2763 systemBlacklists.begin(), 2764 systemBlacklists.end()); 2765 2766 // -fxray-{always,never}-instrument= filenames. 2767 Opts.XRayAlwaysInstrumentFiles = 2768 Args.getAllArgValues(OPT_fxray_always_instrument); 2769 Opts.XRayNeverInstrumentFiles = 2770 Args.getAllArgValues(OPT_fxray_never_instrument); 2771 Opts.XRayAttrListFiles = Args.getAllArgValues(OPT_fxray_attr_list); 2772 2773 if (Arg *A = Args.getLastArg(OPT_fclang_abi_compat_EQ)) { 2774 Opts.setClangABICompat(LangOptions::ClangABI::Latest); 2775 2776 StringRef Ver = A->getValue(); 2777 std::pair<StringRef, StringRef> VerParts = Ver.split('.'); 2778 unsigned Major, Minor = 0; 2779 2780 // Check the version number is valid: either 3.x (0 <= x <= 9) or 2781 // y or y.0 (4 <= y <= current version). 2782 if (!VerParts.first.startswith("0") && 2783 !VerParts.first.getAsInteger(10, Major) && 2784 3 <= Major && Major <= CLANG_VERSION_MAJOR && 2785 (Major == 3 ? VerParts.second.size() == 1 && 2786 !VerParts.second.getAsInteger(10, Minor) 2787 : VerParts.first.size() == Ver.size() || 2788 VerParts.second == "0")) { 2789 // Got a valid version number. 2790 if (Major == 3 && Minor <= 8) 2791 Opts.setClangABICompat(LangOptions::ClangABI::Ver3_8); 2792 else if (Major <= 4) 2793 Opts.setClangABICompat(LangOptions::ClangABI::Ver4); 2794 else if (Major <= 6) 2795 Opts.setClangABICompat(LangOptions::ClangABI::Ver6); 2796 else if (Major <= 7) 2797 Opts.setClangABICompat(LangOptions::ClangABI::Ver7); 2798 else if (Major <= 9) 2799 Opts.setClangABICompat(LangOptions::ClangABI::Ver9); 2800 else if (Major <= 11) 2801 Opts.setClangABICompat(LangOptions::ClangABI::Ver11); 2802 } else if (Ver != "latest") { 2803 Diags.Report(diag::err_drv_invalid_value) 2804 << A->getAsString(Args) << A->getValue(); 2805 } 2806 } 2807 2808 if (Arg *A = Args.getLastArg(OPT_msign_return_address_EQ)) { 2809 StringRef SignScope = A->getValue(); 2810 2811 if (SignScope.equals_lower("none")) 2812 Opts.setSignReturnAddressScope( 2813 LangOptions::SignReturnAddressScopeKind::None); 2814 else if (SignScope.equals_lower("all")) 2815 Opts.setSignReturnAddressScope( 2816 LangOptions::SignReturnAddressScopeKind::All); 2817 else if (SignScope.equals_lower("non-leaf")) 2818 Opts.setSignReturnAddressScope( 2819 LangOptions::SignReturnAddressScopeKind::NonLeaf); 2820 else 2821 Diags.Report(diag::err_drv_invalid_value) 2822 << A->getAsString(Args) << SignScope; 2823 2824 if (Arg *A = Args.getLastArg(OPT_msign_return_address_key_EQ)) { 2825 StringRef SignKey = A->getValue(); 2826 if (!SignScope.empty() && !SignKey.empty()) { 2827 if (SignKey.equals_lower("a_key")) 2828 Opts.setSignReturnAddressKey( 2829 LangOptions::SignReturnAddressKeyKind::AKey); 2830 else if (SignKey.equals_lower("b_key")) 2831 Opts.setSignReturnAddressKey( 2832 LangOptions::SignReturnAddressKeyKind::BKey); 2833 else 2834 Diags.Report(diag::err_drv_invalid_value) 2835 << A->getAsString(Args) << SignKey; 2836 } 2837 } 2838 } 2839 2840 std::string ThreadModel = 2841 std::string(Args.getLastArgValue(OPT_mthread_model, "posix")); 2842 if (ThreadModel != "posix" && ThreadModel != "single") 2843 Diags.Report(diag::err_drv_invalid_value) 2844 << Args.getLastArg(OPT_mthread_model)->getAsString(Args) << ThreadModel; 2845 Opts.setThreadModel( 2846 llvm::StringSwitch<LangOptions::ThreadModelKind>(ThreadModel) 2847 .Case("posix", LangOptions::ThreadModelKind::POSIX) 2848 .Case("single", LangOptions::ThreadModelKind::Single)); 2849 } 2850 2851 static bool isStrictlyPreprocessorAction(frontend::ActionKind Action) { 2852 switch (Action) { 2853 case frontend::ASTDeclList: 2854 case frontend::ASTDump: 2855 case frontend::ASTPrint: 2856 case frontend::ASTView: 2857 case frontend::EmitAssembly: 2858 case frontend::EmitBC: 2859 case frontend::EmitHTML: 2860 case frontend::EmitLLVM: 2861 case frontend::EmitLLVMOnly: 2862 case frontend::EmitCodeGenOnly: 2863 case frontend::EmitObj: 2864 case frontend::FixIt: 2865 case frontend::GenerateModule: 2866 case frontend::GenerateModuleInterface: 2867 case frontend::GenerateHeaderModule: 2868 case frontend::GeneratePCH: 2869 case frontend::GenerateInterfaceStubs: 2870 case frontend::ParseSyntaxOnly: 2871 case frontend::ModuleFileInfo: 2872 case frontend::VerifyPCH: 2873 case frontend::PluginAction: 2874 case frontend::RewriteObjC: 2875 case frontend::RewriteTest: 2876 case frontend::RunAnalysis: 2877 case frontend::TemplightDump: 2878 case frontend::MigrateSource: 2879 return false; 2880 2881 case frontend::DumpCompilerOptions: 2882 case frontend::DumpRawTokens: 2883 case frontend::DumpTokens: 2884 case frontend::InitOnly: 2885 case frontend::PrintPreamble: 2886 case frontend::PrintPreprocessedInput: 2887 case frontend::RewriteMacros: 2888 case frontend::RunPreprocessorOnly: 2889 case frontend::PrintDependencyDirectivesSourceMinimizerOutput: 2890 return true; 2891 } 2892 llvm_unreachable("invalid frontend action"); 2893 } 2894 2895 static void ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args, 2896 DiagnosticsEngine &Diags, 2897 frontend::ActionKind Action) { 2898 Opts.PCHWithHdrStop = Args.hasArg(OPT_pch_through_hdrstop_create) || 2899 Args.hasArg(OPT_pch_through_hdrstop_use); 2900 Opts.AllowPCHWithCompilerErrors = 2901 Args.hasArg(OPT_fallow_pch_with_errors, OPT_fallow_pcm_with_errors); 2902 2903 for (const auto *A : Args.filtered(OPT_error_on_deserialized_pch_decl)) 2904 Opts.DeserializedPCHDeclsToErrorOn.insert(A->getValue()); 2905 2906 for (const auto &A : Args.getAllArgValues(OPT_fmacro_prefix_map_EQ)) { 2907 auto Split = StringRef(A).split('='); 2908 Opts.MacroPrefixMap.insert( 2909 {std::string(Split.first), std::string(Split.second)}); 2910 } 2911 2912 if (const Arg *A = Args.getLastArg(OPT_preamble_bytes_EQ)) { 2913 StringRef Value(A->getValue()); 2914 size_t Comma = Value.find(','); 2915 unsigned Bytes = 0; 2916 unsigned EndOfLine = 0; 2917 2918 if (Comma == StringRef::npos || 2919 Value.substr(0, Comma).getAsInteger(10, Bytes) || 2920 Value.substr(Comma + 1).getAsInteger(10, EndOfLine)) 2921 Diags.Report(diag::err_drv_preamble_format); 2922 else { 2923 Opts.PrecompiledPreambleBytes.first = Bytes; 2924 Opts.PrecompiledPreambleBytes.second = (EndOfLine != 0); 2925 } 2926 } 2927 2928 // Add the __CET__ macro if a CFProtection option is set. 2929 if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) { 2930 StringRef Name = A->getValue(); 2931 if (Name == "branch") 2932 Opts.addMacroDef("__CET__=1"); 2933 else if (Name == "return") 2934 Opts.addMacroDef("__CET__=2"); 2935 else if (Name == "full") 2936 Opts.addMacroDef("__CET__=3"); 2937 } 2938 2939 // Add macros from the command line. 2940 for (const auto *A : Args.filtered(OPT_D, OPT_U)) { 2941 if (A->getOption().matches(OPT_D)) 2942 Opts.addMacroDef(A->getValue()); 2943 else 2944 Opts.addMacroUndef(A->getValue()); 2945 } 2946 2947 Opts.MacroIncludes = Args.getAllArgValues(OPT_imacros); 2948 2949 // Add the ordered list of -includes. 2950 for (const auto *A : Args.filtered(OPT_include)) 2951 Opts.Includes.emplace_back(A->getValue()); 2952 2953 for (const auto *A : Args.filtered(OPT_chain_include)) 2954 Opts.ChainedIncludes.emplace_back(A->getValue()); 2955 2956 for (const auto *A : Args.filtered(OPT_remap_file)) { 2957 std::pair<StringRef, StringRef> Split = StringRef(A->getValue()).split(';'); 2958 2959 if (Split.second.empty()) { 2960 Diags.Report(diag::err_drv_invalid_remap_file) << A->getAsString(Args); 2961 continue; 2962 } 2963 2964 Opts.addRemappedFile(Split.first, Split.second); 2965 } 2966 2967 // Always avoid lexing editor placeholders when we're just running the 2968 // preprocessor as we never want to emit the 2969 // "editor placeholder in source file" error in PP only mode. 2970 if (isStrictlyPreprocessorAction(Action)) 2971 Opts.LexEditorPlaceholders = false; 2972 } 2973 2974 static void ParsePreprocessorOutputArgs(PreprocessorOutputOptions &Opts, 2975 ArgList &Args, 2976 frontend::ActionKind Action) { 2977 if (isStrictlyPreprocessorAction(Action)) 2978 Opts.ShowCPP = !Args.hasArg(OPT_dM); 2979 else 2980 Opts.ShowCPP = 0; 2981 2982 Opts.ShowMacros = Args.hasArg(OPT_dM) || Args.hasArg(OPT_dD); 2983 } 2984 2985 static void ParseTargetArgs(TargetOptions &Opts, ArgList &Args, 2986 DiagnosticsEngine &Diags) { 2987 Opts.FeaturesAsWritten = Args.getAllArgValues(OPT_target_feature); 2988 Opts.OpenCLExtensionsAsWritten = Args.getAllArgValues(OPT_cl_ext_EQ); 2989 Opts.AllowAMDGPUUnsafeFPAtomics = 2990 Args.hasFlag(options::OPT_munsafe_fp_atomics, 2991 options::OPT_mno_unsafe_fp_atomics, false); 2992 if (Arg *A = Args.getLastArg(options::OPT_target_sdk_version_EQ)) { 2993 llvm::VersionTuple Version; 2994 if (Version.tryParse(A->getValue())) 2995 Diags.Report(diag::err_drv_invalid_value) 2996 << A->getAsString(Args) << A->getValue(); 2997 else 2998 Opts.SDKVersion = Version; 2999 } 3000 } 3001 3002 bool CompilerInvocation::parseSimpleArgs(const ArgList &Args, 3003 DiagnosticsEngine &Diags) { 3004 #define OPTION_WITH_MARSHALLING( \ 3005 PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ 3006 HELPTEXT, METAVAR, VALUES, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \ 3007 IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, MERGER, EXTRACTOR, \ 3008 TABLE_INDEX) \ 3009 if ((FLAGS)&options::CC1Option) { \ 3010 this->KEYPATH = MERGER(this->KEYPATH, DEFAULT_VALUE); \ 3011 if (IMPLIED_CHECK) \ 3012 this->KEYPATH = MERGER(this->KEYPATH, IMPLIED_VALUE); \ 3013 if (auto MaybeValue = NORMALIZER(OPT_##ID, TABLE_INDEX, Args, Diags)) \ 3014 this->KEYPATH = MERGER( \ 3015 this->KEYPATH, static_cast<decltype(this->KEYPATH)>(*MaybeValue)); \ 3016 } 3017 3018 #include "clang/Driver/Options.inc" 3019 #undef OPTION_WITH_MARSHALLING 3020 return true; 3021 } 3022 3023 bool CompilerInvocation::CreateFromArgs(CompilerInvocation &Res, 3024 ArrayRef<const char *> CommandLineArgs, 3025 DiagnosticsEngine &Diags, 3026 const char *Argv0) { 3027 bool Success = true; 3028 3029 // Parse the arguments. 3030 const OptTable &Opts = getDriverOptTable(); 3031 const unsigned IncludedFlagsBitmask = options::CC1Option; 3032 unsigned MissingArgIndex, MissingArgCount; 3033 InputArgList Args = Opts.ParseArgs(CommandLineArgs, MissingArgIndex, 3034 MissingArgCount, IncludedFlagsBitmask); 3035 LangOptions &LangOpts = *Res.getLangOpts(); 3036 3037 // Check for missing argument error. 3038 if (MissingArgCount) { 3039 Diags.Report(diag::err_drv_missing_argument) 3040 << Args.getArgString(MissingArgIndex) << MissingArgCount; 3041 Success = false; 3042 } 3043 3044 // Issue errors on unknown arguments. 3045 for (const auto *A : Args.filtered(OPT_UNKNOWN)) { 3046 auto ArgString = A->getAsString(Args); 3047 std::string Nearest; 3048 if (Opts.findNearest(ArgString, Nearest, IncludedFlagsBitmask) > 1) 3049 Diags.Report(diag::err_drv_unknown_argument) << ArgString; 3050 else 3051 Diags.Report(diag::err_drv_unknown_argument_with_suggestion) 3052 << ArgString << Nearest; 3053 Success = false; 3054 } 3055 3056 Success &= Res.parseSimpleArgs(Args, Diags); 3057 3058 Success &= ParseAnalyzerArgs(*Res.getAnalyzerOpts(), Args, Diags); 3059 ParseDependencyOutputArgs(Res.getDependencyOutputOpts(), Args); 3060 if (!Res.getDependencyOutputOpts().OutputFile.empty() && 3061 Res.getDependencyOutputOpts().Targets.empty()) { 3062 Diags.Report(diag::err_fe_dependency_file_requires_MT); 3063 Success = false; 3064 } 3065 Success &= ParseDiagnosticArgs(Res.getDiagnosticOpts(), Args, &Diags, 3066 /*DefaultDiagColor=*/false); 3067 ParseCommentArgs(LangOpts.CommentOpts, Args); 3068 // FIXME: We shouldn't have to pass the DashX option around here 3069 InputKind DashX = ParseFrontendArgs(Res.getFrontendOpts(), Args, Diags, 3070 LangOpts.IsHeaderFile); 3071 ParseTargetArgs(Res.getTargetOpts(), Args, Diags); 3072 Success &= ParseCodeGenArgs(Res.getCodeGenOpts(), Args, DashX, Diags, 3073 Res.getTargetOpts(), Res.getFrontendOpts()); 3074 ParseHeaderSearchArgs(Res.getHeaderSearchOpts(), Args, 3075 Res.getFileSystemOpts().WorkingDir); 3076 llvm::Triple T(Res.getTargetOpts().Triple); 3077 if (DashX.getFormat() == InputKind::Precompiled || 3078 DashX.getLanguage() == Language::LLVM_IR) { 3079 // ObjCAAutoRefCount and Sanitize LangOpts are used to setup the 3080 // PassManager in BackendUtil.cpp. They need to be initializd no matter 3081 // what the input type is. 3082 if (Args.hasArg(OPT_fobjc_arc)) 3083 LangOpts.ObjCAutoRefCount = 1; 3084 // PIClevel and PIELevel are needed during code generation and this should be 3085 // set regardless of the input type. 3086 LangOpts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags); 3087 parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ), 3088 Diags, LangOpts.Sanitize); 3089 } else { 3090 // Other LangOpts are only initialized when the input is not AST or LLVM IR. 3091 // FIXME: Should we really be calling this for an Language::Asm input? 3092 ParseLangArgs(LangOpts, Args, DashX, Res.getTargetOpts(), 3093 Res.getPreprocessorOpts(), Diags); 3094 if (Res.getFrontendOpts().ProgramAction == frontend::RewriteObjC) 3095 LangOpts.ObjCExceptions = 1; 3096 if (T.isOSDarwin() && DashX.isPreprocessed()) { 3097 // Supress the darwin-specific 'stdlibcxx-not-found' diagnostic for 3098 // preprocessed input as we don't expect it to be used with -std=libc++ 3099 // anyway. 3100 Res.getDiagnosticOpts().Warnings.push_back("no-stdlibcxx-not-found"); 3101 } 3102 } 3103 3104 if (LangOpts.CUDA) { 3105 // During CUDA device-side compilation, the aux triple is the 3106 // triple used for host compilation. 3107 if (LangOpts.CUDAIsDevice) 3108 Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple; 3109 } 3110 3111 // Set the triple of the host for OpenMP device compile. 3112 if (LangOpts.OpenMPIsDevice) 3113 Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple; 3114 3115 // FIXME: Override value name discarding when asan or msan is used because the 3116 // backend passes depend on the name of the alloca in order to print out 3117 // names. 3118 Res.getCodeGenOpts().DiscardValueNames &= 3119 !LangOpts.Sanitize.has(SanitizerKind::Address) && 3120 !LangOpts.Sanitize.has(SanitizerKind::KernelAddress) && 3121 !LangOpts.Sanitize.has(SanitizerKind::Memory) && 3122 !LangOpts.Sanitize.has(SanitizerKind::KernelMemory); 3123 3124 ParsePreprocessorArgs(Res.getPreprocessorOpts(), Args, Diags, 3125 Res.getFrontendOpts().ProgramAction); 3126 ParsePreprocessorOutputArgs(Res.getPreprocessorOutputOpts(), Args, 3127 Res.getFrontendOpts().ProgramAction); 3128 3129 // Turn on -Wspir-compat for SPIR target. 3130 if (T.isSPIR()) 3131 Res.getDiagnosticOpts().Warnings.push_back("spir-compat"); 3132 3133 // If sanitizer is enabled, disable OPT_ffine_grained_bitfield_accesses. 3134 if (Res.getCodeGenOpts().FineGrainedBitfieldAccesses && 3135 !Res.getLangOpts()->Sanitize.empty()) { 3136 Res.getCodeGenOpts().FineGrainedBitfieldAccesses = false; 3137 Diags.Report(diag::warn_drv_fine_grained_bitfield_accesses_ignored); 3138 } 3139 3140 // Store the command-line for using in the CodeView backend. 3141 Res.getCodeGenOpts().Argv0 = Argv0; 3142 Res.getCodeGenOpts().CommandLineArgs = CommandLineArgs; 3143 3144 FixupInvocation(Res, Diags, Args); 3145 3146 return Success; 3147 } 3148 3149 std::string CompilerInvocation::getModuleHash() const { 3150 // Note: For QoI reasons, the things we use as a hash here should all be 3151 // dumped via the -module-info flag. 3152 using llvm::hash_code; 3153 using llvm::hash_value; 3154 using llvm::hash_combine; 3155 using llvm::hash_combine_range; 3156 3157 // Start the signature with the compiler version. 3158 // FIXME: We'd rather use something more cryptographically sound than 3159 // CityHash, but this will do for now. 3160 hash_code code = hash_value(getClangFullRepositoryVersion()); 3161 3162 // Also include the serialization version, in case LLVM_APPEND_VC_REV is off 3163 // and getClangFullRepositoryVersion() doesn't include git revision. 3164 code = hash_combine(code, serialization::VERSION_MAJOR, 3165 serialization::VERSION_MINOR); 3166 3167 // Extend the signature with the language options 3168 #define LANGOPT(Name, Bits, Default, Description) \ 3169 code = hash_combine(code, LangOpts->Name); 3170 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \ 3171 code = hash_combine(code, static_cast<unsigned>(LangOpts->get##Name())); 3172 #define BENIGN_LANGOPT(Name, Bits, Default, Description) 3173 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description) 3174 #include "clang/Basic/LangOptions.def" 3175 3176 for (StringRef Feature : LangOpts->ModuleFeatures) 3177 code = hash_combine(code, Feature); 3178 3179 code = hash_combine(code, LangOpts->ObjCRuntime); 3180 const auto &BCN = LangOpts->CommentOpts.BlockCommandNames; 3181 code = hash_combine(code, hash_combine_range(BCN.begin(), BCN.end())); 3182 3183 // Extend the signature with the target options. 3184 code = hash_combine(code, TargetOpts->Triple, TargetOpts->CPU, 3185 TargetOpts->TuneCPU, TargetOpts->ABI); 3186 for (const auto &FeatureAsWritten : TargetOpts->FeaturesAsWritten) 3187 code = hash_combine(code, FeatureAsWritten); 3188 3189 // Extend the signature with preprocessor options. 3190 const PreprocessorOptions &ppOpts = getPreprocessorOpts(); 3191 const HeaderSearchOptions &hsOpts = getHeaderSearchOpts(); 3192 code = hash_combine(code, ppOpts.UsePredefines, ppOpts.DetailedRecord); 3193 3194 for (const auto &I : getPreprocessorOpts().Macros) { 3195 // If we're supposed to ignore this macro for the purposes of modules, 3196 // don't put it into the hash. 3197 if (!hsOpts.ModulesIgnoreMacros.empty()) { 3198 // Check whether we're ignoring this macro. 3199 StringRef MacroDef = I.first; 3200 if (hsOpts.ModulesIgnoreMacros.count( 3201 llvm::CachedHashString(MacroDef.split('=').first))) 3202 continue; 3203 } 3204 3205 code = hash_combine(code, I.first, I.second); 3206 } 3207 3208 // Extend the signature with the sysroot and other header search options. 3209 code = hash_combine(code, hsOpts.Sysroot, 3210 hsOpts.ModuleFormat, 3211 hsOpts.UseDebugInfo, 3212 hsOpts.UseBuiltinIncludes, 3213 hsOpts.UseStandardSystemIncludes, 3214 hsOpts.UseStandardCXXIncludes, 3215 hsOpts.UseLibcxx, 3216 hsOpts.ModulesValidateDiagnosticOptions); 3217 code = hash_combine(code, hsOpts.ResourceDir); 3218 3219 if (hsOpts.ModulesStrictContextHash) { 3220 hash_code SHPC = hash_combine_range(hsOpts.SystemHeaderPrefixes.begin(), 3221 hsOpts.SystemHeaderPrefixes.end()); 3222 hash_code UEC = hash_combine_range(hsOpts.UserEntries.begin(), 3223 hsOpts.UserEntries.end()); 3224 code = hash_combine(code, hsOpts.SystemHeaderPrefixes.size(), SHPC, 3225 hsOpts.UserEntries.size(), UEC); 3226 3227 const DiagnosticOptions &diagOpts = getDiagnosticOpts(); 3228 #define DIAGOPT(Name, Bits, Default) \ 3229 code = hash_combine(code, diagOpts.Name); 3230 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \ 3231 code = hash_combine(code, diagOpts.get##Name()); 3232 #include "clang/Basic/DiagnosticOptions.def" 3233 #undef DIAGOPT 3234 #undef ENUM_DIAGOPT 3235 } 3236 3237 // Extend the signature with the user build path. 3238 code = hash_combine(code, hsOpts.ModuleUserBuildPath); 3239 3240 // Extend the signature with the module file extensions. 3241 const FrontendOptions &frontendOpts = getFrontendOpts(); 3242 for (const auto &ext : frontendOpts.ModuleFileExtensions) { 3243 code = ext->hashExtension(code); 3244 } 3245 3246 // When compiling with -gmodules, also hash -fdebug-prefix-map as it 3247 // affects the debug info in the PCM. 3248 if (getCodeGenOpts().DebugTypeExtRefs) 3249 for (const auto &KeyValue : getCodeGenOpts().DebugPrefixMap) 3250 code = hash_combine(code, KeyValue.first, KeyValue.second); 3251 3252 // Extend the signature with the enabled sanitizers, if at least one is 3253 // enabled. Sanitizers which cannot affect AST generation aren't hashed. 3254 SanitizerSet SanHash = LangOpts->Sanitize; 3255 SanHash.clear(getPPTransparentSanitizers()); 3256 if (!SanHash.empty()) 3257 code = hash_combine(code, SanHash.Mask); 3258 3259 return llvm::APInt(64, code).toString(36, /*Signed=*/false); 3260 } 3261 3262 void CompilerInvocation::generateCC1CommandLine( 3263 SmallVectorImpl<const char *> &Args, StringAllocator SA) const { 3264 // Capture the extracted value as a lambda argument to avoid potential issues 3265 // with lifetime extension of the reference. 3266 #define OPTION_WITH_MARSHALLING( \ 3267 PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ 3268 HELPTEXT, METAVAR, VALUES, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \ 3269 IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, MERGER, EXTRACTOR, \ 3270 TABLE_INDEX) \ 3271 if ((FLAGS)&options::CC1Option) { \ 3272 [&](const auto &Extracted) { \ 3273 if (ALWAYS_EMIT || \ 3274 (Extracted != \ 3275 static_cast<decltype(this->KEYPATH)>( \ 3276 (IMPLIED_CHECK) ? (IMPLIED_VALUE) : (DEFAULT_VALUE)))) \ 3277 DENORMALIZER(Args, SPELLING, SA, Option::KIND##Class, TABLE_INDEX, \ 3278 Extracted); \ 3279 }(EXTRACTOR(this->KEYPATH)); \ 3280 } 3281 3282 #include "clang/Driver/Options.inc" 3283 #undef OPTION_WITH_MARSHALLING 3284 } 3285 3286 IntrusiveRefCntPtr<llvm::vfs::FileSystem> 3287 clang::createVFSFromCompilerInvocation(const CompilerInvocation &CI, 3288 DiagnosticsEngine &Diags) { 3289 return createVFSFromCompilerInvocation(CI, Diags, 3290 llvm::vfs::getRealFileSystem()); 3291 } 3292 3293 IntrusiveRefCntPtr<llvm::vfs::FileSystem> 3294 clang::createVFSFromCompilerInvocation( 3295 const CompilerInvocation &CI, DiagnosticsEngine &Diags, 3296 IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS) { 3297 if (CI.getHeaderSearchOpts().VFSOverlayFiles.empty()) 3298 return BaseFS; 3299 3300 IntrusiveRefCntPtr<llvm::vfs::FileSystem> Result = BaseFS; 3301 // earlier vfs files are on the bottom 3302 for (const auto &File : CI.getHeaderSearchOpts().VFSOverlayFiles) { 3303 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer = 3304 Result->getBufferForFile(File); 3305 if (!Buffer) { 3306 Diags.Report(diag::err_missing_vfs_overlay_file) << File; 3307 continue; 3308 } 3309 3310 IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS = llvm::vfs::getVFSFromYAML( 3311 std::move(Buffer.get()), /*DiagHandler*/ nullptr, File, 3312 /*DiagContext*/ nullptr, Result); 3313 if (!FS) { 3314 Diags.Report(diag::err_invalid_vfs_overlay) << File; 3315 continue; 3316 } 3317 3318 Result = FS; 3319 } 3320 return Result; 3321 } 3322