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