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/Diagnostic.h" 16 #include "clang/Basic/DiagnosticDriver.h" 17 #include "clang/Basic/DiagnosticOptions.h" 18 #include "clang/Basic/FileSystemOptions.h" 19 #include "clang/Basic/LLVM.h" 20 #include "clang/Basic/LangOptions.h" 21 #include "clang/Basic/LangStandard.h" 22 #include "clang/Basic/ObjCRuntime.h" 23 #include "clang/Basic/Sanitizers.h" 24 #include "clang/Basic/SourceLocation.h" 25 #include "clang/Basic/TargetOptions.h" 26 #include "clang/Basic/Version.h" 27 #include "clang/Basic/Visibility.h" 28 #include "clang/Basic/XRayInstr.h" 29 #include "clang/Config/config.h" 30 #include "clang/Driver/Driver.h" 31 #include "clang/Driver/DriverDiagnostic.h" 32 #include "clang/Driver/Options.h" 33 #include "clang/Frontend/CommandLineSourceLoc.h" 34 #include "clang/Frontend/DependencyOutputOptions.h" 35 #include "clang/Frontend/FrontendDiagnostic.h" 36 #include "clang/Frontend/FrontendOptions.h" 37 #include "clang/Frontend/FrontendPluginRegistry.h" 38 #include "clang/Frontend/MigratorOptions.h" 39 #include "clang/Frontend/PreprocessorOutputOptions.h" 40 #include "clang/Frontend/TextDiagnosticBuffer.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/DenseSet.h" 52 #include "llvm/ADT/FloatingPointMode.h" 53 #include "llvm/ADT/Hashing.h" 54 #include "llvm/ADT/STLExtras.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/Twine.h" 60 #include "llvm/Config/llvm-config.h" 61 #include "llvm/Frontend/Debug/Options.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/HashBuilder.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 "llvm/TargetParser/Host.h" 89 #include "llvm/TargetParser/Triple.h" 90 #include <algorithm> 91 #include <atomic> 92 #include <cassert> 93 #include <cstddef> 94 #include <cstring> 95 #include <ctime> 96 #include <fstream> 97 #include <limits> 98 #include <memory> 99 #include <optional> 100 #include <string> 101 #include <tuple> 102 #include <type_traits> 103 #include <utility> 104 #include <vector> 105 106 using namespace clang; 107 using namespace driver; 108 using namespace options; 109 using namespace llvm::opt; 110 111 //===----------------------------------------------------------------------===// 112 // Helpers. 113 //===----------------------------------------------------------------------===// 114 115 // Parse misexpect tolerance argument value. 116 // Valid option values are integers in the range [0, 100) 117 static Expected<std::optional<uint32_t>> parseToleranceOption(StringRef Arg) { 118 uint32_t Val; 119 if (Arg.getAsInteger(10, Val)) 120 return llvm::createStringError(llvm::inconvertibleErrorCode(), 121 "Not an integer: %s", Arg.data()); 122 return Val; 123 } 124 125 //===----------------------------------------------------------------------===// 126 // Initialization. 127 //===----------------------------------------------------------------------===// 128 129 namespace { 130 template <class T> std::shared_ptr<T> make_shared_copy(const T &X) { 131 return std::make_shared<T>(X); 132 } 133 134 template <class T> 135 llvm::IntrusiveRefCntPtr<T> makeIntrusiveRefCntCopy(const T &X) { 136 return llvm::makeIntrusiveRefCnt<T>(X); 137 } 138 } // namespace 139 140 CompilerInvocationBase::CompilerInvocationBase() 141 : LangOpts(std::make_shared<LangOptions>()), 142 TargetOpts(std::make_shared<TargetOptions>()), 143 DiagnosticOpts(llvm::makeIntrusiveRefCnt<DiagnosticOptions>()), 144 HSOpts(std::make_shared<HeaderSearchOptions>()), 145 PPOpts(std::make_shared<PreprocessorOptions>()), 146 AnalyzerOpts(llvm::makeIntrusiveRefCnt<AnalyzerOptions>()), 147 MigratorOpts(std::make_shared<MigratorOptions>()), 148 CodeGenOpts(std::make_shared<CodeGenOptions>()), 149 FSOpts(std::make_shared<FileSystemOptions>()), 150 FrontendOpts(std::make_shared<FrontendOptions>()), 151 DependencyOutputOpts(std::make_shared<DependencyOutputOptions>()), 152 PreprocessorOutputOpts(std::make_shared<PreprocessorOutputOptions>()) {} 153 154 CompilerInvocationBase & 155 CompilerInvocationBase::deep_copy_assign(const CompilerInvocationBase &X) { 156 if (this != &X) { 157 LangOpts = make_shared_copy(X.getLangOpts()); 158 TargetOpts = make_shared_copy(X.getTargetOpts()); 159 DiagnosticOpts = makeIntrusiveRefCntCopy(X.getDiagnosticOpts()); 160 HSOpts = make_shared_copy(X.getHeaderSearchOpts()); 161 PPOpts = make_shared_copy(X.getPreprocessorOpts()); 162 AnalyzerOpts = makeIntrusiveRefCntCopy(X.getAnalyzerOpts()); 163 MigratorOpts = make_shared_copy(X.getMigratorOpts()); 164 CodeGenOpts = make_shared_copy(X.getCodeGenOpts()); 165 FSOpts = make_shared_copy(X.getFileSystemOpts()); 166 FrontendOpts = make_shared_copy(X.getFrontendOpts()); 167 DependencyOutputOpts = make_shared_copy(X.getDependencyOutputOpts()); 168 PreprocessorOutputOpts = make_shared_copy(X.getPreprocessorOutputOpts()); 169 } 170 return *this; 171 } 172 173 CompilerInvocationBase & 174 CompilerInvocationBase::shallow_copy_assign(const CompilerInvocationBase &X) { 175 if (this != &X) { 176 LangOpts = X.LangOpts; 177 TargetOpts = X.TargetOpts; 178 DiagnosticOpts = X.DiagnosticOpts; 179 HSOpts = X.HSOpts; 180 PPOpts = X.PPOpts; 181 AnalyzerOpts = X.AnalyzerOpts; 182 MigratorOpts = X.MigratorOpts; 183 CodeGenOpts = X.CodeGenOpts; 184 FSOpts = X.FSOpts; 185 FrontendOpts = X.FrontendOpts; 186 DependencyOutputOpts = X.DependencyOutputOpts; 187 PreprocessorOutputOpts = X.PreprocessorOutputOpts; 188 } 189 return *this; 190 } 191 192 namespace { 193 template <typename T> 194 T &ensureOwned(std::shared_ptr<T> &Storage) { 195 if (Storage.use_count() > 1) 196 Storage = std::make_shared<T>(*Storage); 197 return *Storage; 198 } 199 200 template <typename T> 201 T &ensureOwned(llvm::IntrusiveRefCntPtr<T> &Storage) { 202 if (Storage.useCount() > 1) 203 Storage = llvm::makeIntrusiveRefCnt<T>(*Storage); 204 return *Storage; 205 } 206 } // namespace 207 208 LangOptions &CowCompilerInvocation::getMutLangOpts() { 209 return ensureOwned(LangOpts); 210 } 211 212 TargetOptions &CowCompilerInvocation::getMutTargetOpts() { 213 return ensureOwned(TargetOpts); 214 } 215 216 DiagnosticOptions &CowCompilerInvocation::getMutDiagnosticOpts() { 217 return ensureOwned(DiagnosticOpts); 218 } 219 220 HeaderSearchOptions &CowCompilerInvocation::getMutHeaderSearchOpts() { 221 return ensureOwned(HSOpts); 222 } 223 224 PreprocessorOptions &CowCompilerInvocation::getMutPreprocessorOpts() { 225 return ensureOwned(PPOpts); 226 } 227 228 AnalyzerOptions &CowCompilerInvocation::getMutAnalyzerOpts() { 229 return ensureOwned(AnalyzerOpts); 230 } 231 232 MigratorOptions &CowCompilerInvocation::getMutMigratorOpts() { 233 return ensureOwned(MigratorOpts); 234 } 235 236 CodeGenOptions &CowCompilerInvocation::getMutCodeGenOpts() { 237 return ensureOwned(CodeGenOpts); 238 } 239 240 FileSystemOptions &CowCompilerInvocation::getMutFileSystemOpts() { 241 return ensureOwned(FSOpts); 242 } 243 244 FrontendOptions &CowCompilerInvocation::getMutFrontendOpts() { 245 return ensureOwned(FrontendOpts); 246 } 247 248 DependencyOutputOptions &CowCompilerInvocation::getMutDependencyOutputOpts() { 249 return ensureOwned(DependencyOutputOpts); 250 } 251 252 PreprocessorOutputOptions & 253 CowCompilerInvocation::getMutPreprocessorOutputOpts() { 254 return ensureOwned(PreprocessorOutputOpts); 255 } 256 257 //===----------------------------------------------------------------------===// 258 // Normalizers 259 //===----------------------------------------------------------------------===// 260 261 using ArgumentConsumer = CompilerInvocation::ArgumentConsumer; 262 263 #define SIMPLE_ENUM_VALUE_TABLE 264 #include "clang/Driver/Options.inc" 265 #undef SIMPLE_ENUM_VALUE_TABLE 266 267 static std::optional<bool> normalizeSimpleFlag(OptSpecifier Opt, 268 unsigned TableIndex, 269 const ArgList &Args, 270 DiagnosticsEngine &Diags) { 271 if (Args.hasArg(Opt)) 272 return true; 273 return std::nullopt; 274 } 275 276 static std::optional<bool> normalizeSimpleNegativeFlag(OptSpecifier Opt, 277 unsigned, 278 const ArgList &Args, 279 DiagnosticsEngine &) { 280 if (Args.hasArg(Opt)) 281 return false; 282 return std::nullopt; 283 } 284 285 /// The tblgen-erated code passes in a fifth parameter of an arbitrary type, but 286 /// denormalizeSimpleFlags never looks at it. Avoid bloating compile-time with 287 /// unnecessary template instantiations and just ignore it with a variadic 288 /// argument. 289 static void denormalizeSimpleFlag(ArgumentConsumer Consumer, 290 const Twine &Spelling, Option::OptionClass, 291 unsigned, /*T*/...) { 292 Consumer(Spelling); 293 } 294 295 template <typename T> static constexpr bool is_uint64_t_convertible() { 296 return !std::is_same_v<T, uint64_t> && llvm::is_integral_or_enum<T>::value; 297 } 298 299 template <typename T, 300 std::enable_if_t<!is_uint64_t_convertible<T>(), bool> = false> 301 static auto makeFlagToValueNormalizer(T Value) { 302 return [Value](OptSpecifier Opt, unsigned, const ArgList &Args, 303 DiagnosticsEngine &) -> std::optional<T> { 304 if (Args.hasArg(Opt)) 305 return Value; 306 return std::nullopt; 307 }; 308 } 309 310 template <typename T, 311 std::enable_if_t<is_uint64_t_convertible<T>(), bool> = false> 312 static auto makeFlagToValueNormalizer(T Value) { 313 return makeFlagToValueNormalizer(uint64_t(Value)); 314 } 315 316 static auto makeBooleanOptionNormalizer(bool Value, bool OtherValue, 317 OptSpecifier OtherOpt) { 318 return [Value, OtherValue, 319 OtherOpt](OptSpecifier Opt, unsigned, const ArgList &Args, 320 DiagnosticsEngine &) -> std::optional<bool> { 321 if (const Arg *A = Args.getLastArg(Opt, OtherOpt)) { 322 return A->getOption().matches(Opt) ? Value : OtherValue; 323 } 324 return std::nullopt; 325 }; 326 } 327 328 static auto makeBooleanOptionDenormalizer(bool Value) { 329 return [Value](ArgumentConsumer Consumer, const Twine &Spelling, 330 Option::OptionClass, unsigned, bool KeyPath) { 331 if (KeyPath == Value) 332 Consumer(Spelling); 333 }; 334 } 335 336 static void denormalizeStringImpl(ArgumentConsumer Consumer, 337 const Twine &Spelling, 338 Option::OptionClass OptClass, unsigned, 339 const Twine &Value) { 340 switch (OptClass) { 341 case Option::SeparateClass: 342 case Option::JoinedOrSeparateClass: 343 case Option::JoinedAndSeparateClass: 344 Consumer(Spelling); 345 Consumer(Value); 346 break; 347 case Option::JoinedClass: 348 case Option::CommaJoinedClass: 349 Consumer(Spelling + Value); 350 break; 351 default: 352 llvm_unreachable("Cannot denormalize an option with option class " 353 "incompatible with string denormalization."); 354 } 355 } 356 357 template <typename T> 358 static void denormalizeString(ArgumentConsumer Consumer, const Twine &Spelling, 359 Option::OptionClass OptClass, unsigned TableIndex, 360 T Value) { 361 denormalizeStringImpl(Consumer, Spelling, OptClass, TableIndex, Twine(Value)); 362 } 363 364 static std::optional<SimpleEnumValue> 365 findValueTableByName(const SimpleEnumValueTable &Table, StringRef Name) { 366 for (int I = 0, E = Table.Size; I != E; ++I) 367 if (Name == Table.Table[I].Name) 368 return Table.Table[I]; 369 370 return std::nullopt; 371 } 372 373 static std::optional<SimpleEnumValue> 374 findValueTableByValue(const SimpleEnumValueTable &Table, unsigned Value) { 375 for (int I = 0, E = Table.Size; I != E; ++I) 376 if (Value == Table.Table[I].Value) 377 return Table.Table[I]; 378 379 return std::nullopt; 380 } 381 382 static std::optional<unsigned> normalizeSimpleEnum(OptSpecifier Opt, 383 unsigned TableIndex, 384 const ArgList &Args, 385 DiagnosticsEngine &Diags) { 386 assert(TableIndex < SimpleEnumValueTablesSize); 387 const SimpleEnumValueTable &Table = SimpleEnumValueTables[TableIndex]; 388 389 auto *Arg = Args.getLastArg(Opt); 390 if (!Arg) 391 return std::nullopt; 392 393 StringRef ArgValue = Arg->getValue(); 394 if (auto MaybeEnumVal = findValueTableByName(Table, ArgValue)) 395 return MaybeEnumVal->Value; 396 397 Diags.Report(diag::err_drv_invalid_value) 398 << Arg->getAsString(Args) << ArgValue; 399 return std::nullopt; 400 } 401 402 static void denormalizeSimpleEnumImpl(ArgumentConsumer Consumer, 403 const Twine &Spelling, 404 Option::OptionClass OptClass, 405 unsigned TableIndex, unsigned Value) { 406 assert(TableIndex < SimpleEnumValueTablesSize); 407 const SimpleEnumValueTable &Table = SimpleEnumValueTables[TableIndex]; 408 if (auto MaybeEnumVal = findValueTableByValue(Table, Value)) { 409 denormalizeString(Consumer, Spelling, OptClass, TableIndex, 410 MaybeEnumVal->Name); 411 } else { 412 llvm_unreachable("The simple enum value was not correctly defined in " 413 "the tablegen option description"); 414 } 415 } 416 417 template <typename T> 418 static void denormalizeSimpleEnum(ArgumentConsumer Consumer, 419 const Twine &Spelling, 420 Option::OptionClass OptClass, 421 unsigned TableIndex, T Value) { 422 return denormalizeSimpleEnumImpl(Consumer, Spelling, OptClass, TableIndex, 423 static_cast<unsigned>(Value)); 424 } 425 426 static std::optional<std::string> normalizeString(OptSpecifier Opt, 427 int TableIndex, 428 const ArgList &Args, 429 DiagnosticsEngine &Diags) { 430 auto *Arg = Args.getLastArg(Opt); 431 if (!Arg) 432 return std::nullopt; 433 return std::string(Arg->getValue()); 434 } 435 436 template <typename IntTy> 437 static std::optional<IntTy> normalizeStringIntegral(OptSpecifier Opt, int, 438 const ArgList &Args, 439 DiagnosticsEngine &Diags) { 440 auto *Arg = Args.getLastArg(Opt); 441 if (!Arg) 442 return std::nullopt; 443 IntTy Res; 444 if (StringRef(Arg->getValue()).getAsInteger(0, Res)) { 445 Diags.Report(diag::err_drv_invalid_int_value) 446 << Arg->getAsString(Args) << Arg->getValue(); 447 return std::nullopt; 448 } 449 return Res; 450 } 451 452 static std::optional<std::vector<std::string>> 453 normalizeStringVector(OptSpecifier Opt, int, const ArgList &Args, 454 DiagnosticsEngine &) { 455 return Args.getAllArgValues(Opt); 456 } 457 458 static void denormalizeStringVector(ArgumentConsumer Consumer, 459 const Twine &Spelling, 460 Option::OptionClass OptClass, 461 unsigned TableIndex, 462 const std::vector<std::string> &Values) { 463 switch (OptClass) { 464 case Option::CommaJoinedClass: { 465 std::string CommaJoinedValue; 466 if (!Values.empty()) { 467 CommaJoinedValue.append(Values.front()); 468 for (const std::string &Value : llvm::drop_begin(Values, 1)) { 469 CommaJoinedValue.append(","); 470 CommaJoinedValue.append(Value); 471 } 472 } 473 denormalizeString(Consumer, Spelling, Option::OptionClass::JoinedClass, 474 TableIndex, CommaJoinedValue); 475 break; 476 } 477 case Option::JoinedClass: 478 case Option::SeparateClass: 479 case Option::JoinedOrSeparateClass: 480 for (const std::string &Value : Values) 481 denormalizeString(Consumer, Spelling, OptClass, TableIndex, Value); 482 break; 483 default: 484 llvm_unreachable("Cannot denormalize an option with option class " 485 "incompatible with string vector denormalization."); 486 } 487 } 488 489 static std::optional<std::string> normalizeTriple(OptSpecifier Opt, 490 int TableIndex, 491 const ArgList &Args, 492 DiagnosticsEngine &Diags) { 493 auto *Arg = Args.getLastArg(Opt); 494 if (!Arg) 495 return std::nullopt; 496 return llvm::Triple::normalize(Arg->getValue()); 497 } 498 499 template <typename T, typename U> 500 static T mergeForwardValue(T KeyPath, U Value) { 501 return static_cast<T>(Value); 502 } 503 504 template <typename T, typename U> static T mergeMaskValue(T KeyPath, U Value) { 505 return KeyPath | Value; 506 } 507 508 template <typename T> static T extractForwardValue(T KeyPath) { 509 return KeyPath; 510 } 511 512 template <typename T, typename U, U Value> 513 static T extractMaskValue(T KeyPath) { 514 return ((KeyPath & Value) == Value) ? static_cast<T>(Value) : T(); 515 } 516 517 #define PARSE_OPTION_WITH_MARSHALLING( \ 518 ARGS, DIAGS, PREFIX_TYPE, SPELLING, ID, KIND, GROUP, ALIAS, ALIASARGS, \ 519 FLAGS, VISIBILITY, PARAM, HELPTEXT, METAVAR, VALUES, SHOULD_PARSE, \ 520 ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, \ 521 NORMALIZER, DENORMALIZER, MERGER, EXTRACTOR, TABLE_INDEX) \ 522 if ((VISIBILITY)&options::CC1Option) { \ 523 KEYPATH = MERGER(KEYPATH, DEFAULT_VALUE); \ 524 if (IMPLIED_CHECK) \ 525 KEYPATH = MERGER(KEYPATH, IMPLIED_VALUE); \ 526 if (SHOULD_PARSE) \ 527 if (auto MaybeValue = NORMALIZER(OPT_##ID, TABLE_INDEX, ARGS, DIAGS)) \ 528 KEYPATH = \ 529 MERGER(KEYPATH, static_cast<decltype(KEYPATH)>(*MaybeValue)); \ 530 } 531 532 // Capture the extracted value as a lambda argument to avoid potential issues 533 // with lifetime extension of the reference. 534 #define GENERATE_OPTION_WITH_MARSHALLING( \ 535 CONSUMER, PREFIX_TYPE, SPELLING, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, \ 536 VISIBILITY, PARAM, HELPTEXT, METAVAR, VALUES, SHOULD_PARSE, ALWAYS_EMIT, \ 537 KEYPATH, DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, \ 538 DENORMALIZER, MERGER, EXTRACTOR, TABLE_INDEX) \ 539 if ((VISIBILITY)&options::CC1Option) { \ 540 [&](const auto &Extracted) { \ 541 if (ALWAYS_EMIT || \ 542 (Extracted != \ 543 static_cast<decltype(KEYPATH)>((IMPLIED_CHECK) ? (IMPLIED_VALUE) \ 544 : (DEFAULT_VALUE)))) \ 545 DENORMALIZER(CONSUMER, SPELLING, Option::KIND##Class, TABLE_INDEX, \ 546 Extracted); \ 547 }(EXTRACTOR(KEYPATH)); \ 548 } 549 550 static StringRef GetInputKindName(InputKind IK); 551 552 static bool FixupInvocation(CompilerInvocation &Invocation, 553 DiagnosticsEngine &Diags, const ArgList &Args, 554 InputKind IK) { 555 unsigned NumErrorsBefore = Diags.getNumErrors(); 556 557 LangOptions &LangOpts = Invocation.getLangOpts(); 558 CodeGenOptions &CodeGenOpts = Invocation.getCodeGenOpts(); 559 TargetOptions &TargetOpts = Invocation.getTargetOpts(); 560 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts(); 561 CodeGenOpts.XRayInstrumentFunctions = LangOpts.XRayInstrument; 562 CodeGenOpts.XRayAlwaysEmitCustomEvents = LangOpts.XRayAlwaysEmitCustomEvents; 563 CodeGenOpts.XRayAlwaysEmitTypedEvents = LangOpts.XRayAlwaysEmitTypedEvents; 564 CodeGenOpts.DisableFree = FrontendOpts.DisableFree; 565 FrontendOpts.GenerateGlobalModuleIndex = FrontendOpts.UseGlobalModuleIndex; 566 if (FrontendOpts.ShowStats) 567 CodeGenOpts.ClearASTBeforeBackend = false; 568 LangOpts.SanitizeCoverage = CodeGenOpts.hasSanitizeCoverage(); 569 LangOpts.ForceEmitVTables = CodeGenOpts.ForceEmitVTables; 570 LangOpts.SpeculativeLoadHardening = CodeGenOpts.SpeculativeLoadHardening; 571 LangOpts.CurrentModule = LangOpts.ModuleName; 572 573 llvm::Triple T(TargetOpts.Triple); 574 llvm::Triple::ArchType Arch = T.getArch(); 575 576 CodeGenOpts.CodeModel = TargetOpts.CodeModel; 577 578 if (LangOpts.getExceptionHandling() != 579 LangOptions::ExceptionHandlingKind::None && 580 T.isWindowsMSVCEnvironment()) 581 Diags.Report(diag::err_fe_invalid_exception_model) 582 << static_cast<unsigned>(LangOpts.getExceptionHandling()) << T.str(); 583 584 if (LangOpts.AppleKext && !LangOpts.CPlusPlus) 585 Diags.Report(diag::warn_c_kext); 586 587 if (LangOpts.NewAlignOverride && 588 !llvm::isPowerOf2_32(LangOpts.NewAlignOverride)) { 589 Arg *A = Args.getLastArg(OPT_fnew_alignment_EQ); 590 Diags.Report(diag::err_fe_invalid_alignment) 591 << A->getAsString(Args) << A->getValue(); 592 LangOpts.NewAlignOverride = 0; 593 } 594 595 // Prevent the user from specifying both -fsycl-is-device and -fsycl-is-host. 596 if (LangOpts.SYCLIsDevice && LangOpts.SYCLIsHost) 597 Diags.Report(diag::err_drv_argument_not_allowed_with) << "-fsycl-is-device" 598 << "-fsycl-is-host"; 599 600 if (Args.hasArg(OPT_fgnu89_inline) && LangOpts.CPlusPlus) 601 Diags.Report(diag::err_drv_argument_not_allowed_with) 602 << "-fgnu89-inline" << GetInputKindName(IK); 603 604 if (Args.hasArg(OPT_hlsl_entrypoint) && !LangOpts.HLSL) 605 Diags.Report(diag::err_drv_argument_not_allowed_with) 606 << "-hlsl-entry" << GetInputKindName(IK); 607 608 if (Args.hasArg(OPT_fgpu_allow_device_init) && !LangOpts.HIP) 609 Diags.Report(diag::warn_ignored_hip_only_option) 610 << Args.getLastArg(OPT_fgpu_allow_device_init)->getAsString(Args); 611 612 if (Args.hasArg(OPT_gpu_max_threads_per_block_EQ) && !LangOpts.HIP) 613 Diags.Report(diag::warn_ignored_hip_only_option) 614 << Args.getLastArg(OPT_gpu_max_threads_per_block_EQ)->getAsString(Args); 615 616 // When these options are used, the compiler is allowed to apply 617 // optimizations that may affect the final result. For example 618 // (x+y)+z is transformed to x+(y+z) but may not give the same 619 // final result; it's not value safe. 620 // Another example can be to simplify x/x to 1.0 but x could be 0.0, INF 621 // or NaN. Final result may then differ. An error is issued when the eval 622 // method is set with one of these options. 623 if (Args.hasArg(OPT_ffp_eval_method_EQ)) { 624 if (LangOpts.ApproxFunc) 625 Diags.Report(diag::err_incompatible_fp_eval_method_options) << 0; 626 if (LangOpts.AllowFPReassoc) 627 Diags.Report(diag::err_incompatible_fp_eval_method_options) << 1; 628 if (LangOpts.AllowRecip) 629 Diags.Report(diag::err_incompatible_fp_eval_method_options) << 2; 630 } 631 632 // -cl-strict-aliasing needs to emit diagnostic in the case where CL > 1.0. 633 // This option should be deprecated for CL > 1.0 because 634 // this option was added for compatibility with OpenCL 1.0. 635 if (Args.getLastArg(OPT_cl_strict_aliasing) && 636 (LangOpts.getOpenCLCompatibleVersion() > 100)) 637 Diags.Report(diag::warn_option_invalid_ocl_version) 638 << LangOpts.getOpenCLVersionString() 639 << Args.getLastArg(OPT_cl_strict_aliasing)->getAsString(Args); 640 641 if (Arg *A = Args.getLastArg(OPT_fdefault_calling_conv_EQ)) { 642 auto DefaultCC = LangOpts.getDefaultCallingConv(); 643 644 bool emitError = (DefaultCC == LangOptions::DCC_FastCall || 645 DefaultCC == LangOptions::DCC_StdCall) && 646 Arch != llvm::Triple::x86; 647 emitError |= (DefaultCC == LangOptions::DCC_VectorCall || 648 DefaultCC == LangOptions::DCC_RegCall) && 649 !T.isX86(); 650 if (emitError) 651 Diags.Report(diag::err_drv_argument_not_allowed_with) 652 << A->getSpelling() << T.getTriple(); 653 } 654 655 return Diags.getNumErrors() == NumErrorsBefore; 656 } 657 658 //===----------------------------------------------------------------------===// 659 // Deserialization (from args) 660 //===----------------------------------------------------------------------===// 661 662 static unsigned getOptimizationLevel(ArgList &Args, InputKind IK, 663 DiagnosticsEngine &Diags) { 664 unsigned DefaultOpt = 0; 665 if ((IK.getLanguage() == Language::OpenCL || 666 IK.getLanguage() == Language::OpenCLCXX) && 667 !Args.hasArg(OPT_cl_opt_disable)) 668 DefaultOpt = 2; 669 670 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) { 671 if (A->getOption().matches(options::OPT_O0)) 672 return 0; 673 674 if (A->getOption().matches(options::OPT_Ofast)) 675 return 3; 676 677 assert(A->getOption().matches(options::OPT_O)); 678 679 StringRef S(A->getValue()); 680 if (S == "s" || S == "z") 681 return 2; 682 683 if (S == "g") 684 return 1; 685 686 return getLastArgIntValue(Args, OPT_O, DefaultOpt, Diags); 687 } 688 689 return DefaultOpt; 690 } 691 692 static unsigned getOptimizationLevelSize(ArgList &Args) { 693 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) { 694 if (A->getOption().matches(options::OPT_O)) { 695 switch (A->getValue()[0]) { 696 default: 697 return 0; 698 case 's': 699 return 1; 700 case 'z': 701 return 2; 702 } 703 } 704 } 705 return 0; 706 } 707 708 static void GenerateArg(ArgumentConsumer Consumer, 709 llvm::opt::OptSpecifier OptSpecifier) { 710 Option Opt = getDriverOptTable().getOption(OptSpecifier); 711 denormalizeSimpleFlag(Consumer, Opt.getPrefixedName(), 712 Option::OptionClass::FlagClass, 0); 713 } 714 715 static void GenerateArg(ArgumentConsumer Consumer, 716 llvm::opt::OptSpecifier OptSpecifier, 717 const Twine &Value) { 718 Option Opt = getDriverOptTable().getOption(OptSpecifier); 719 denormalizeString(Consumer, Opt.getPrefixedName(), Opt.getKind(), 0, Value); 720 } 721 722 // Parse command line arguments into CompilerInvocation. 723 using ParseFn = 724 llvm::function_ref<bool(CompilerInvocation &, ArrayRef<const char *>, 725 DiagnosticsEngine &, const char *)>; 726 727 // Generate command line arguments from CompilerInvocation. 728 using GenerateFn = llvm::function_ref<void( 729 CompilerInvocation &, SmallVectorImpl<const char *> &, 730 CompilerInvocation::StringAllocator)>; 731 732 /// May perform round-trip of command line arguments. By default, the round-trip 733 /// is enabled in assert builds. This can be overwritten at run-time via the 734 /// "-round-trip-args" and "-no-round-trip-args" command line flags, or via the 735 /// ForceRoundTrip parameter. 736 /// 737 /// During round-trip, the command line arguments are parsed into a dummy 738 /// CompilerInvocation, which is used to generate the command line arguments 739 /// again. The real CompilerInvocation is then created by parsing the generated 740 /// arguments, not the original ones. This (in combination with tests covering 741 /// argument behavior) ensures the generated command line is complete (doesn't 742 /// drop/mangle any arguments). 743 /// 744 /// Finally, we check the command line that was used to create the real 745 /// CompilerInvocation instance. By default, we compare it to the command line 746 /// the real CompilerInvocation generates. This checks whether the generator is 747 /// deterministic. If \p CheckAgainstOriginalInvocation is enabled, we instead 748 /// compare it to the original command line to verify the original command-line 749 /// was canonical and can round-trip exactly. 750 static bool RoundTrip(ParseFn Parse, GenerateFn Generate, 751 CompilerInvocation &RealInvocation, 752 CompilerInvocation &DummyInvocation, 753 ArrayRef<const char *> CommandLineArgs, 754 DiagnosticsEngine &Diags, const char *Argv0, 755 bool CheckAgainstOriginalInvocation = false, 756 bool ForceRoundTrip = false) { 757 #ifndef NDEBUG 758 bool DoRoundTripDefault = true; 759 #else 760 bool DoRoundTripDefault = false; 761 #endif 762 763 bool DoRoundTrip = DoRoundTripDefault; 764 if (ForceRoundTrip) { 765 DoRoundTrip = true; 766 } else { 767 for (const auto *Arg : CommandLineArgs) { 768 if (Arg == StringRef("-round-trip-args")) 769 DoRoundTrip = true; 770 if (Arg == StringRef("-no-round-trip-args")) 771 DoRoundTrip = false; 772 } 773 } 774 775 // If round-trip was not requested, simply run the parser with the real 776 // invocation diagnostics. 777 if (!DoRoundTrip) 778 return Parse(RealInvocation, CommandLineArgs, Diags, Argv0); 779 780 // Serializes quoted (and potentially escaped) arguments. 781 auto SerializeArgs = [](ArrayRef<const char *> Args) { 782 std::string Buffer; 783 llvm::raw_string_ostream OS(Buffer); 784 for (const char *Arg : Args) { 785 llvm::sys::printArg(OS, Arg, /*Quote=*/true); 786 OS << ' '; 787 } 788 OS.flush(); 789 return Buffer; 790 }; 791 792 // Setup a dummy DiagnosticsEngine. 793 DiagnosticsEngine DummyDiags(new DiagnosticIDs(), new DiagnosticOptions()); 794 DummyDiags.setClient(new TextDiagnosticBuffer()); 795 796 // Run the first parse on the original arguments with the dummy invocation and 797 // diagnostics. 798 if (!Parse(DummyInvocation, CommandLineArgs, DummyDiags, Argv0) || 799 DummyDiags.getNumWarnings() != 0) { 800 // If the first parse did not succeed, it must be user mistake (invalid 801 // command line arguments). We won't be able to generate arguments that 802 // would reproduce the same result. Let's fail again with the real 803 // invocation and diagnostics, so all side-effects of parsing are visible. 804 unsigned NumWarningsBefore = Diags.getNumWarnings(); 805 auto Success = Parse(RealInvocation, CommandLineArgs, Diags, Argv0); 806 if (!Success || Diags.getNumWarnings() != NumWarningsBefore) 807 return Success; 808 809 // Parse with original options and diagnostics succeeded even though it 810 // shouldn't have. Something is off. 811 Diags.Report(diag::err_cc1_round_trip_fail_then_ok); 812 Diags.Report(diag::note_cc1_round_trip_original) 813 << SerializeArgs(CommandLineArgs); 814 return false; 815 } 816 817 // Setup string allocator. 818 llvm::BumpPtrAllocator Alloc; 819 llvm::StringSaver StringPool(Alloc); 820 auto SA = [&StringPool](const Twine &Arg) { 821 return StringPool.save(Arg).data(); 822 }; 823 824 // Generate arguments from the dummy invocation. If Generate is the 825 // inverse of Parse, the newly generated arguments must have the same 826 // semantics as the original. 827 SmallVector<const char *> GeneratedArgs; 828 Generate(DummyInvocation, GeneratedArgs, SA); 829 830 // Run the second parse, now on the generated arguments, and with the real 831 // invocation and diagnostics. The result is what we will end up using for the 832 // rest of compilation, so if Generate is not inverse of Parse, something down 833 // the line will break. 834 bool Success2 = Parse(RealInvocation, GeneratedArgs, Diags, Argv0); 835 836 // The first parse on original arguments succeeded, but second parse of 837 // generated arguments failed. Something must be wrong with the generator. 838 if (!Success2) { 839 Diags.Report(diag::err_cc1_round_trip_ok_then_fail); 840 Diags.Report(diag::note_cc1_round_trip_generated) 841 << 1 << SerializeArgs(GeneratedArgs); 842 return false; 843 } 844 845 SmallVector<const char *> ComparisonArgs; 846 if (CheckAgainstOriginalInvocation) 847 // Compare against original arguments. 848 ComparisonArgs.assign(CommandLineArgs.begin(), CommandLineArgs.end()); 849 else 850 // Generate arguments again, this time from the options we will end up using 851 // for the rest of the compilation. 852 Generate(RealInvocation, ComparisonArgs, SA); 853 854 // Compares two lists of arguments. 855 auto Equal = [](const ArrayRef<const char *> A, 856 const ArrayRef<const char *> B) { 857 return std::equal(A.begin(), A.end(), B.begin(), B.end(), 858 [](const char *AElem, const char *BElem) { 859 return StringRef(AElem) == StringRef(BElem); 860 }); 861 }; 862 863 // If we generated different arguments from what we assume are two 864 // semantically equivalent CompilerInvocations, the Generate function may 865 // be non-deterministic. 866 if (!Equal(GeneratedArgs, ComparisonArgs)) { 867 Diags.Report(diag::err_cc1_round_trip_mismatch); 868 Diags.Report(diag::note_cc1_round_trip_generated) 869 << 1 << SerializeArgs(GeneratedArgs); 870 Diags.Report(diag::note_cc1_round_trip_generated) 871 << 2 << SerializeArgs(ComparisonArgs); 872 return false; 873 } 874 875 Diags.Report(diag::remark_cc1_round_trip_generated) 876 << 1 << SerializeArgs(GeneratedArgs); 877 Diags.Report(diag::remark_cc1_round_trip_generated) 878 << 2 << SerializeArgs(ComparisonArgs); 879 880 return Success2; 881 } 882 883 bool CompilerInvocation::checkCC1RoundTrip(ArrayRef<const char *> Args, 884 DiagnosticsEngine &Diags, 885 const char *Argv0) { 886 CompilerInvocation DummyInvocation1, DummyInvocation2; 887 return RoundTrip( 888 [](CompilerInvocation &Invocation, ArrayRef<const char *> CommandLineArgs, 889 DiagnosticsEngine &Diags, const char *Argv0) { 890 return CreateFromArgsImpl(Invocation, CommandLineArgs, Diags, Argv0); 891 }, 892 [](CompilerInvocation &Invocation, SmallVectorImpl<const char *> &Args, 893 StringAllocator SA) { 894 Args.push_back("-cc1"); 895 Invocation.generateCC1CommandLine(Args, SA); 896 }, 897 DummyInvocation1, DummyInvocation2, Args, Diags, Argv0, 898 /*CheckAgainstOriginalInvocation=*/true, /*ForceRoundTrip=*/true); 899 } 900 901 static void addDiagnosticArgs(ArgList &Args, OptSpecifier Group, 902 OptSpecifier GroupWithValue, 903 std::vector<std::string> &Diagnostics) { 904 for (auto *A : Args.filtered(Group)) { 905 if (A->getOption().getKind() == Option::FlagClass) { 906 // The argument is a pure flag (such as OPT_Wall or OPT_Wdeprecated). Add 907 // its name (minus the "W" or "R" at the beginning) to the diagnostics. 908 Diagnostics.push_back( 909 std::string(A->getOption().getName().drop_front(1))); 910 } else if (A->getOption().matches(GroupWithValue)) { 911 // This is -Wfoo= or -Rfoo=, where foo is the name of the diagnostic 912 // group. Add only the group name to the diagnostics. 913 Diagnostics.push_back( 914 std::string(A->getOption().getName().drop_front(1).rtrim("=-"))); 915 } else { 916 // Otherwise, add its value (for OPT_W_Joined and similar). 917 Diagnostics.push_back(A->getValue()); 918 } 919 } 920 } 921 922 // Parse the Static Analyzer configuration. If \p Diags is set to nullptr, 923 // it won't verify the input. 924 static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts, 925 DiagnosticsEngine *Diags); 926 927 static void getAllNoBuiltinFuncValues(ArgList &Args, 928 std::vector<std::string> &Funcs) { 929 std::vector<std::string> Values = Args.getAllArgValues(OPT_fno_builtin_); 930 auto BuiltinEnd = llvm::partition(Values, Builtin::Context::isBuiltinFunc); 931 Funcs.insert(Funcs.end(), Values.begin(), BuiltinEnd); 932 } 933 934 static void GenerateAnalyzerArgs(const AnalyzerOptions &Opts, 935 ArgumentConsumer Consumer) { 936 const AnalyzerOptions *AnalyzerOpts = &Opts; 937 938 #define ANALYZER_OPTION_WITH_MARSHALLING(...) \ 939 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__) 940 #include "clang/Driver/Options.inc" 941 #undef ANALYZER_OPTION_WITH_MARSHALLING 942 943 if (Opts.AnalysisConstraintsOpt != RangeConstraintsModel) { 944 switch (Opts.AnalysisConstraintsOpt) { 945 #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \ 946 case NAME##Model: \ 947 GenerateArg(Consumer, OPT_analyzer_constraints, CMDFLAG); \ 948 break; 949 #include "clang/StaticAnalyzer/Core/Analyses.def" 950 default: 951 llvm_unreachable("Tried to generate unknown analysis constraint."); 952 } 953 } 954 955 if (Opts.AnalysisDiagOpt != PD_HTML) { 956 switch (Opts.AnalysisDiagOpt) { 957 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \ 958 case PD_##NAME: \ 959 GenerateArg(Consumer, OPT_analyzer_output, CMDFLAG); \ 960 break; 961 #include "clang/StaticAnalyzer/Core/Analyses.def" 962 default: 963 llvm_unreachable("Tried to generate unknown analysis diagnostic client."); 964 } 965 } 966 967 if (Opts.AnalysisPurgeOpt != PurgeStmt) { 968 switch (Opts.AnalysisPurgeOpt) { 969 #define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \ 970 case NAME: \ 971 GenerateArg(Consumer, OPT_analyzer_purge, CMDFLAG); \ 972 break; 973 #include "clang/StaticAnalyzer/Core/Analyses.def" 974 default: 975 llvm_unreachable("Tried to generate unknown analysis purge mode."); 976 } 977 } 978 979 if (Opts.InliningMode != NoRedundancy) { 980 switch (Opts.InliningMode) { 981 #define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \ 982 case NAME: \ 983 GenerateArg(Consumer, OPT_analyzer_inlining_mode, CMDFLAG); \ 984 break; 985 #include "clang/StaticAnalyzer/Core/Analyses.def" 986 default: 987 llvm_unreachable("Tried to generate unknown analysis inlining mode."); 988 } 989 } 990 991 for (const auto &CP : Opts.CheckersAndPackages) { 992 OptSpecifier Opt = 993 CP.second ? OPT_analyzer_checker : OPT_analyzer_disable_checker; 994 GenerateArg(Consumer, Opt, CP.first); 995 } 996 997 AnalyzerOptions ConfigOpts; 998 parseAnalyzerConfigs(ConfigOpts, nullptr); 999 1000 // Sort options by key to avoid relying on StringMap iteration order. 1001 SmallVector<std::pair<StringRef, StringRef>, 4> SortedConfigOpts; 1002 for (const auto &C : Opts.Config) 1003 SortedConfigOpts.emplace_back(C.getKey(), C.getValue()); 1004 llvm::sort(SortedConfigOpts, llvm::less_first()); 1005 1006 for (const auto &[Key, Value] : SortedConfigOpts) { 1007 // Don't generate anything that came from parseAnalyzerConfigs. It would be 1008 // redundant and may not be valid on the command line. 1009 auto Entry = ConfigOpts.Config.find(Key); 1010 if (Entry != ConfigOpts.Config.end() && Entry->getValue() == Value) 1011 continue; 1012 1013 GenerateArg(Consumer, OPT_analyzer_config, Key + "=" + Value); 1014 } 1015 1016 // Nothing to generate for FullCompilerInvocation. 1017 } 1018 1019 static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args, 1020 DiagnosticsEngine &Diags) { 1021 unsigned NumErrorsBefore = Diags.getNumErrors(); 1022 1023 AnalyzerOptions *AnalyzerOpts = &Opts; 1024 1025 #define ANALYZER_OPTION_WITH_MARSHALLING(...) \ 1026 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__) 1027 #include "clang/Driver/Options.inc" 1028 #undef ANALYZER_OPTION_WITH_MARSHALLING 1029 1030 if (Arg *A = Args.getLastArg(OPT_analyzer_constraints)) { 1031 StringRef Name = A->getValue(); 1032 AnalysisConstraints Value = llvm::StringSwitch<AnalysisConstraints>(Name) 1033 #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \ 1034 .Case(CMDFLAG, NAME##Model) 1035 #include "clang/StaticAnalyzer/Core/Analyses.def" 1036 .Default(NumConstraints); 1037 if (Value == NumConstraints) { 1038 Diags.Report(diag::err_drv_invalid_value) 1039 << A->getAsString(Args) << Name; 1040 } else { 1041 #ifndef LLVM_WITH_Z3 1042 if (Value == AnalysisConstraints::Z3ConstraintsModel) { 1043 Diags.Report(diag::err_analyzer_not_built_with_z3); 1044 } 1045 #endif // LLVM_WITH_Z3 1046 Opts.AnalysisConstraintsOpt = Value; 1047 } 1048 } 1049 1050 if (Arg *A = Args.getLastArg(OPT_analyzer_output)) { 1051 StringRef Name = A->getValue(); 1052 AnalysisDiagClients Value = llvm::StringSwitch<AnalysisDiagClients>(Name) 1053 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \ 1054 .Case(CMDFLAG, PD_##NAME) 1055 #include "clang/StaticAnalyzer/Core/Analyses.def" 1056 .Default(NUM_ANALYSIS_DIAG_CLIENTS); 1057 if (Value == NUM_ANALYSIS_DIAG_CLIENTS) { 1058 Diags.Report(diag::err_drv_invalid_value) 1059 << A->getAsString(Args) << Name; 1060 } else { 1061 Opts.AnalysisDiagOpt = Value; 1062 } 1063 } 1064 1065 if (Arg *A = Args.getLastArg(OPT_analyzer_purge)) { 1066 StringRef Name = A->getValue(); 1067 AnalysisPurgeMode Value = llvm::StringSwitch<AnalysisPurgeMode>(Name) 1068 #define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \ 1069 .Case(CMDFLAG, NAME) 1070 #include "clang/StaticAnalyzer/Core/Analyses.def" 1071 .Default(NumPurgeModes); 1072 if (Value == NumPurgeModes) { 1073 Diags.Report(diag::err_drv_invalid_value) 1074 << A->getAsString(Args) << Name; 1075 } else { 1076 Opts.AnalysisPurgeOpt = Value; 1077 } 1078 } 1079 1080 if (Arg *A = Args.getLastArg(OPT_analyzer_inlining_mode)) { 1081 StringRef Name = A->getValue(); 1082 AnalysisInliningMode Value = llvm::StringSwitch<AnalysisInliningMode>(Name) 1083 #define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \ 1084 .Case(CMDFLAG, NAME) 1085 #include "clang/StaticAnalyzer/Core/Analyses.def" 1086 .Default(NumInliningModes); 1087 if (Value == NumInliningModes) { 1088 Diags.Report(diag::err_drv_invalid_value) 1089 << A->getAsString(Args) << Name; 1090 } else { 1091 Opts.InliningMode = Value; 1092 } 1093 } 1094 1095 Opts.CheckersAndPackages.clear(); 1096 for (const Arg *A : 1097 Args.filtered(OPT_analyzer_checker, OPT_analyzer_disable_checker)) { 1098 A->claim(); 1099 bool IsEnabled = A->getOption().getID() == OPT_analyzer_checker; 1100 // We can have a list of comma separated checker names, e.g: 1101 // '-analyzer-checker=cocoa,unix' 1102 StringRef CheckerAndPackageList = A->getValue(); 1103 SmallVector<StringRef, 16> CheckersAndPackages; 1104 CheckerAndPackageList.split(CheckersAndPackages, ","); 1105 for (const StringRef &CheckerOrPackage : CheckersAndPackages) 1106 Opts.CheckersAndPackages.emplace_back(std::string(CheckerOrPackage), 1107 IsEnabled); 1108 } 1109 1110 // Go through the analyzer configuration options. 1111 for (const auto *A : Args.filtered(OPT_analyzer_config)) { 1112 1113 // We can have a list of comma separated config names, e.g: 1114 // '-analyzer-config key1=val1,key2=val2' 1115 StringRef configList = A->getValue(); 1116 SmallVector<StringRef, 4> configVals; 1117 configList.split(configVals, ","); 1118 for (const auto &configVal : configVals) { 1119 StringRef key, val; 1120 std::tie(key, val) = configVal.split("="); 1121 if (val.empty()) { 1122 Diags.Report(SourceLocation(), 1123 diag::err_analyzer_config_no_value) << configVal; 1124 break; 1125 } 1126 if (val.contains('=')) { 1127 Diags.Report(SourceLocation(), 1128 diag::err_analyzer_config_multiple_values) 1129 << configVal; 1130 break; 1131 } 1132 1133 // TODO: Check checker options too, possibly in CheckerRegistry. 1134 // Leave unknown non-checker configs unclaimed. 1135 if (!key.contains(":") && Opts.isUnknownAnalyzerConfig(key)) { 1136 if (Opts.ShouldEmitErrorsOnInvalidConfigValue) 1137 Diags.Report(diag::err_analyzer_config_unknown) << key; 1138 continue; 1139 } 1140 1141 A->claim(); 1142 Opts.Config[key] = std::string(val); 1143 } 1144 } 1145 1146 if (Opts.ShouldEmitErrorsOnInvalidConfigValue) 1147 parseAnalyzerConfigs(Opts, &Diags); 1148 else 1149 parseAnalyzerConfigs(Opts, nullptr); 1150 1151 llvm::raw_string_ostream os(Opts.FullCompilerInvocation); 1152 for (unsigned i = 0; i < Args.getNumInputArgStrings(); ++i) { 1153 if (i != 0) 1154 os << " "; 1155 os << Args.getArgString(i); 1156 } 1157 os.flush(); 1158 1159 return Diags.getNumErrors() == NumErrorsBefore; 1160 } 1161 1162 static StringRef getStringOption(AnalyzerOptions::ConfigTable &Config, 1163 StringRef OptionName, StringRef DefaultVal) { 1164 return Config.insert({OptionName, std::string(DefaultVal)}).first->second; 1165 } 1166 1167 static void initOption(AnalyzerOptions::ConfigTable &Config, 1168 DiagnosticsEngine *Diags, 1169 StringRef &OptionField, StringRef Name, 1170 StringRef DefaultVal) { 1171 // String options may be known to invalid (e.g. if the expected string is a 1172 // file name, but the file does not exist), those will have to be checked in 1173 // parseConfigs. 1174 OptionField = getStringOption(Config, Name, DefaultVal); 1175 } 1176 1177 static void initOption(AnalyzerOptions::ConfigTable &Config, 1178 DiagnosticsEngine *Diags, 1179 bool &OptionField, StringRef Name, bool DefaultVal) { 1180 auto PossiblyInvalidVal = 1181 llvm::StringSwitch<std::optional<bool>>( 1182 getStringOption(Config, Name, (DefaultVal ? "true" : "false"))) 1183 .Case("true", true) 1184 .Case("false", false) 1185 .Default(std::nullopt); 1186 1187 if (!PossiblyInvalidVal) { 1188 if (Diags) 1189 Diags->Report(diag::err_analyzer_config_invalid_input) 1190 << Name << "a boolean"; 1191 else 1192 OptionField = DefaultVal; 1193 } else 1194 OptionField = *PossiblyInvalidVal; 1195 } 1196 1197 static void initOption(AnalyzerOptions::ConfigTable &Config, 1198 DiagnosticsEngine *Diags, 1199 unsigned &OptionField, StringRef Name, 1200 unsigned DefaultVal) { 1201 1202 OptionField = DefaultVal; 1203 bool HasFailed = getStringOption(Config, Name, std::to_string(DefaultVal)) 1204 .getAsInteger(0, OptionField); 1205 if (Diags && HasFailed) 1206 Diags->Report(diag::err_analyzer_config_invalid_input) 1207 << Name << "an unsigned"; 1208 } 1209 1210 static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts, 1211 DiagnosticsEngine *Diags) { 1212 // TODO: There's no need to store the entire configtable, it'd be plenty 1213 // enough to store checker options. 1214 1215 #define ANALYZER_OPTION(TYPE, NAME, CMDFLAG, DESC, DEFAULT_VAL) \ 1216 initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, DEFAULT_VAL); 1217 #define ANALYZER_OPTION_DEPENDS_ON_USER_MODE(...) 1218 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.def" 1219 1220 assert(AnOpts.UserMode == "shallow" || AnOpts.UserMode == "deep"); 1221 const bool InShallowMode = AnOpts.UserMode == "shallow"; 1222 1223 #define ANALYZER_OPTION(...) 1224 #define ANALYZER_OPTION_DEPENDS_ON_USER_MODE(TYPE, NAME, CMDFLAG, DESC, \ 1225 SHALLOW_VAL, DEEP_VAL) \ 1226 initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, \ 1227 InShallowMode ? SHALLOW_VAL : DEEP_VAL); 1228 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.def" 1229 1230 // At this point, AnalyzerOptions is configured. Let's validate some options. 1231 1232 // FIXME: Here we try to validate the silenced checkers or packages are valid. 1233 // The current approach only validates the registered checkers which does not 1234 // contain the runtime enabled checkers and optimally we would validate both. 1235 if (!AnOpts.RawSilencedCheckersAndPackages.empty()) { 1236 std::vector<StringRef> Checkers = 1237 AnOpts.getRegisteredCheckers(/*IncludeExperimental=*/true); 1238 std::vector<StringRef> Packages = 1239 AnOpts.getRegisteredPackages(/*IncludeExperimental=*/true); 1240 1241 SmallVector<StringRef, 16> CheckersAndPackages; 1242 AnOpts.RawSilencedCheckersAndPackages.split(CheckersAndPackages, ";"); 1243 1244 for (const StringRef &CheckerOrPackage : CheckersAndPackages) { 1245 if (Diags) { 1246 bool IsChecker = CheckerOrPackage.contains('.'); 1247 bool IsValidName = IsChecker 1248 ? llvm::is_contained(Checkers, CheckerOrPackage) 1249 : llvm::is_contained(Packages, CheckerOrPackage); 1250 1251 if (!IsValidName) 1252 Diags->Report(diag::err_unknown_analyzer_checker_or_package) 1253 << CheckerOrPackage; 1254 } 1255 1256 AnOpts.SilencedCheckersAndPackages.emplace_back(CheckerOrPackage); 1257 } 1258 } 1259 1260 if (!Diags) 1261 return; 1262 1263 if (AnOpts.ShouldTrackConditionsDebug && !AnOpts.ShouldTrackConditions) 1264 Diags->Report(diag::err_analyzer_config_invalid_input) 1265 << "track-conditions-debug" << "'track-conditions' to also be enabled"; 1266 1267 if (!AnOpts.CTUDir.empty() && !llvm::sys::fs::is_directory(AnOpts.CTUDir)) 1268 Diags->Report(diag::err_analyzer_config_invalid_input) << "ctu-dir" 1269 << "a filename"; 1270 1271 if (!AnOpts.ModelPath.empty() && 1272 !llvm::sys::fs::is_directory(AnOpts.ModelPath)) 1273 Diags->Report(diag::err_analyzer_config_invalid_input) << "model-path" 1274 << "a filename"; 1275 } 1276 1277 /// Generate a remark argument. This is an inverse of `ParseOptimizationRemark`. 1278 static void 1279 GenerateOptimizationRemark(ArgumentConsumer Consumer, OptSpecifier OptEQ, 1280 StringRef Name, 1281 const CodeGenOptions::OptRemark &Remark) { 1282 if (Remark.hasValidPattern()) { 1283 GenerateArg(Consumer, OptEQ, Remark.Pattern); 1284 } else if (Remark.Kind == CodeGenOptions::RK_Enabled) { 1285 GenerateArg(Consumer, OPT_R_Joined, Name); 1286 } else if (Remark.Kind == CodeGenOptions::RK_Disabled) { 1287 GenerateArg(Consumer, OPT_R_Joined, StringRef("no-") + Name); 1288 } 1289 } 1290 1291 /// Parse a remark command line argument. It may be missing, disabled/enabled by 1292 /// '-R[no-]group' or specified with a regular expression by '-Rgroup=regexp'. 1293 /// On top of that, it can be disabled/enabled globally by '-R[no-]everything'. 1294 static CodeGenOptions::OptRemark 1295 ParseOptimizationRemark(DiagnosticsEngine &Diags, ArgList &Args, 1296 OptSpecifier OptEQ, StringRef Name) { 1297 CodeGenOptions::OptRemark Result; 1298 1299 auto InitializeResultPattern = [&Diags, &Args, &Result](const Arg *A, 1300 StringRef Pattern) { 1301 Result.Pattern = Pattern.str(); 1302 1303 std::string RegexError; 1304 Result.Regex = std::make_shared<llvm::Regex>(Result.Pattern); 1305 if (!Result.Regex->isValid(RegexError)) { 1306 Diags.Report(diag::err_drv_optimization_remark_pattern) 1307 << RegexError << A->getAsString(Args); 1308 return false; 1309 } 1310 1311 return true; 1312 }; 1313 1314 for (Arg *A : Args) { 1315 if (A->getOption().matches(OPT_R_Joined)) { 1316 StringRef Value = A->getValue(); 1317 1318 if (Value == Name) 1319 Result.Kind = CodeGenOptions::RK_Enabled; 1320 else if (Value == "everything") 1321 Result.Kind = CodeGenOptions::RK_EnabledEverything; 1322 else if (Value.split('-') == std::make_pair(StringRef("no"), Name)) 1323 Result.Kind = CodeGenOptions::RK_Disabled; 1324 else if (Value == "no-everything") 1325 Result.Kind = CodeGenOptions::RK_DisabledEverything; 1326 else 1327 continue; 1328 1329 if (Result.Kind == CodeGenOptions::RK_Disabled || 1330 Result.Kind == CodeGenOptions::RK_DisabledEverything) { 1331 Result.Pattern = ""; 1332 Result.Regex = nullptr; 1333 } else { 1334 InitializeResultPattern(A, ".*"); 1335 } 1336 } else if (A->getOption().matches(OptEQ)) { 1337 Result.Kind = CodeGenOptions::RK_WithPattern; 1338 if (!InitializeResultPattern(A, A->getValue())) 1339 return CodeGenOptions::OptRemark(); 1340 } 1341 } 1342 1343 return Result; 1344 } 1345 1346 static bool parseDiagnosticLevelMask(StringRef FlagName, 1347 const std::vector<std::string> &Levels, 1348 DiagnosticsEngine &Diags, 1349 DiagnosticLevelMask &M) { 1350 bool Success = true; 1351 for (const auto &Level : Levels) { 1352 DiagnosticLevelMask const PM = 1353 llvm::StringSwitch<DiagnosticLevelMask>(Level) 1354 .Case("note", DiagnosticLevelMask::Note) 1355 .Case("remark", DiagnosticLevelMask::Remark) 1356 .Case("warning", DiagnosticLevelMask::Warning) 1357 .Case("error", DiagnosticLevelMask::Error) 1358 .Default(DiagnosticLevelMask::None); 1359 if (PM == DiagnosticLevelMask::None) { 1360 Success = false; 1361 Diags.Report(diag::err_drv_invalid_value) << FlagName << Level; 1362 } 1363 M = M | PM; 1364 } 1365 return Success; 1366 } 1367 1368 static void parseSanitizerKinds(StringRef FlagName, 1369 const std::vector<std::string> &Sanitizers, 1370 DiagnosticsEngine &Diags, SanitizerSet &S) { 1371 for (const auto &Sanitizer : Sanitizers) { 1372 SanitizerMask K = parseSanitizerValue(Sanitizer, /*AllowGroups=*/false); 1373 if (K == SanitizerMask()) 1374 Diags.Report(diag::err_drv_invalid_value) << FlagName << Sanitizer; 1375 else 1376 S.set(K, true); 1377 } 1378 } 1379 1380 static SmallVector<StringRef, 4> serializeSanitizerKinds(SanitizerSet S) { 1381 SmallVector<StringRef, 4> Values; 1382 serializeSanitizerSet(S, Values); 1383 return Values; 1384 } 1385 1386 static void parseXRayInstrumentationBundle(StringRef FlagName, StringRef Bundle, 1387 ArgList &Args, DiagnosticsEngine &D, 1388 XRayInstrSet &S) { 1389 llvm::SmallVector<StringRef, 2> BundleParts; 1390 llvm::SplitString(Bundle, BundleParts, ","); 1391 for (const auto &B : BundleParts) { 1392 auto Mask = parseXRayInstrValue(B); 1393 if (Mask == XRayInstrKind::None) 1394 if (B != "none") 1395 D.Report(diag::err_drv_invalid_value) << FlagName << Bundle; 1396 else 1397 S.Mask = Mask; 1398 else if (Mask == XRayInstrKind::All) 1399 S.Mask = Mask; 1400 else 1401 S.set(Mask, true); 1402 } 1403 } 1404 1405 static std::string serializeXRayInstrumentationBundle(const XRayInstrSet &S) { 1406 llvm::SmallVector<StringRef, 2> BundleParts; 1407 serializeXRayInstrValue(S, BundleParts); 1408 std::string Buffer; 1409 llvm::raw_string_ostream OS(Buffer); 1410 llvm::interleave(BundleParts, OS, [&OS](StringRef Part) { OS << Part; }, ","); 1411 return Buffer; 1412 } 1413 1414 // Set the profile kind using fprofile-instrument-use-path. 1415 static void setPGOUseInstrumentor(CodeGenOptions &Opts, 1416 const Twine &ProfileName, 1417 llvm::vfs::FileSystem &FS, 1418 DiagnosticsEngine &Diags) { 1419 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(ProfileName, FS); 1420 if (auto E = ReaderOrErr.takeError()) { 1421 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 1422 "Error in reading profile %0: %1"); 1423 llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) { 1424 Diags.Report(DiagID) << ProfileName.str() << EI.message(); 1425 }); 1426 return; 1427 } 1428 std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader = 1429 std::move(ReaderOrErr.get()); 1430 // Currently memprof profiles are only added at the IR level. Mark the profile 1431 // type as IR in that case as well and the subsequent matching needs to detect 1432 // which is available (might be one or both). 1433 if (PGOReader->isIRLevelProfile() || PGOReader->hasMemoryProfile()) { 1434 if (PGOReader->hasCSIRLevelProfile()) 1435 Opts.setProfileUse(CodeGenOptions::ProfileCSIRInstr); 1436 else 1437 Opts.setProfileUse(CodeGenOptions::ProfileIRInstr); 1438 } else 1439 Opts.setProfileUse(CodeGenOptions::ProfileClangInstr); 1440 } 1441 1442 void CompilerInvocationBase::GenerateCodeGenArgs(const CodeGenOptions &Opts, 1443 ArgumentConsumer Consumer, 1444 const llvm::Triple &T, 1445 const std::string &OutputFile, 1446 const LangOptions *LangOpts) { 1447 const CodeGenOptions &CodeGenOpts = Opts; 1448 1449 if (Opts.OptimizationLevel == 0) 1450 GenerateArg(Consumer, OPT_O0); 1451 else 1452 GenerateArg(Consumer, OPT_O, Twine(Opts.OptimizationLevel)); 1453 1454 #define CODEGEN_OPTION_WITH_MARSHALLING(...) \ 1455 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__) 1456 #include "clang/Driver/Options.inc" 1457 #undef CODEGEN_OPTION_WITH_MARSHALLING 1458 1459 if (Opts.OptimizationLevel > 0) { 1460 if (Opts.Inlining == CodeGenOptions::NormalInlining) 1461 GenerateArg(Consumer, OPT_finline_functions); 1462 else if (Opts.Inlining == CodeGenOptions::OnlyHintInlining) 1463 GenerateArg(Consumer, OPT_finline_hint_functions); 1464 else if (Opts.Inlining == CodeGenOptions::OnlyAlwaysInlining) 1465 GenerateArg(Consumer, OPT_fno_inline); 1466 } 1467 1468 if (Opts.DirectAccessExternalData && LangOpts->PICLevel != 0) 1469 GenerateArg(Consumer, OPT_fdirect_access_external_data); 1470 else if (!Opts.DirectAccessExternalData && LangOpts->PICLevel == 0) 1471 GenerateArg(Consumer, OPT_fno_direct_access_external_data); 1472 1473 std::optional<StringRef> DebugInfoVal; 1474 switch (Opts.DebugInfo) { 1475 case llvm::codegenoptions::DebugLineTablesOnly: 1476 DebugInfoVal = "line-tables-only"; 1477 break; 1478 case llvm::codegenoptions::DebugDirectivesOnly: 1479 DebugInfoVal = "line-directives-only"; 1480 break; 1481 case llvm::codegenoptions::DebugInfoConstructor: 1482 DebugInfoVal = "constructor"; 1483 break; 1484 case llvm::codegenoptions::LimitedDebugInfo: 1485 DebugInfoVal = "limited"; 1486 break; 1487 case llvm::codegenoptions::FullDebugInfo: 1488 DebugInfoVal = "standalone"; 1489 break; 1490 case llvm::codegenoptions::UnusedTypeInfo: 1491 DebugInfoVal = "unused-types"; 1492 break; 1493 case llvm::codegenoptions::NoDebugInfo: // default value 1494 DebugInfoVal = std::nullopt; 1495 break; 1496 case llvm::codegenoptions::LocTrackingOnly: // implied value 1497 DebugInfoVal = std::nullopt; 1498 break; 1499 } 1500 if (DebugInfoVal) 1501 GenerateArg(Consumer, OPT_debug_info_kind_EQ, *DebugInfoVal); 1502 1503 for (const auto &Prefix : Opts.DebugPrefixMap) 1504 GenerateArg(Consumer, OPT_fdebug_prefix_map_EQ, 1505 Prefix.first + "=" + Prefix.second); 1506 1507 for (const auto &Prefix : Opts.CoveragePrefixMap) 1508 GenerateArg(Consumer, OPT_fcoverage_prefix_map_EQ, 1509 Prefix.first + "=" + Prefix.second); 1510 1511 if (Opts.NewStructPathTBAA) 1512 GenerateArg(Consumer, OPT_new_struct_path_tbaa); 1513 1514 if (Opts.OptimizeSize == 1) 1515 GenerateArg(Consumer, OPT_O, "s"); 1516 else if (Opts.OptimizeSize == 2) 1517 GenerateArg(Consumer, OPT_O, "z"); 1518 1519 // SimplifyLibCalls is set only in the absence of -fno-builtin and 1520 // -ffreestanding. We'll consider that when generating them. 1521 1522 // NoBuiltinFuncs are generated by LangOptions. 1523 1524 if (Opts.UnrollLoops && Opts.OptimizationLevel <= 1) 1525 GenerateArg(Consumer, OPT_funroll_loops); 1526 else if (!Opts.UnrollLoops && Opts.OptimizationLevel > 1) 1527 GenerateArg(Consumer, OPT_fno_unroll_loops); 1528 1529 if (!Opts.BinutilsVersion.empty()) 1530 GenerateArg(Consumer, OPT_fbinutils_version_EQ, Opts.BinutilsVersion); 1531 1532 if (Opts.DebugNameTable == 1533 static_cast<unsigned>(llvm::DICompileUnit::DebugNameTableKind::GNU)) 1534 GenerateArg(Consumer, OPT_ggnu_pubnames); 1535 else if (Opts.DebugNameTable == 1536 static_cast<unsigned>( 1537 llvm::DICompileUnit::DebugNameTableKind::Default)) 1538 GenerateArg(Consumer, OPT_gpubnames); 1539 1540 auto TNK = Opts.getDebugSimpleTemplateNames(); 1541 if (TNK != llvm::codegenoptions::DebugTemplateNamesKind::Full) { 1542 if (TNK == llvm::codegenoptions::DebugTemplateNamesKind::Simple) 1543 GenerateArg(Consumer, OPT_gsimple_template_names_EQ, "simple"); 1544 else if (TNK == llvm::codegenoptions::DebugTemplateNamesKind::Mangled) 1545 GenerateArg(Consumer, OPT_gsimple_template_names_EQ, "mangled"); 1546 } 1547 // ProfileInstrumentUsePath is marshalled automatically, no need to generate 1548 // it or PGOUseInstrumentor. 1549 1550 if (Opts.TimePasses) { 1551 if (Opts.TimePassesPerRun) 1552 GenerateArg(Consumer, OPT_ftime_report_EQ, "per-pass-run"); 1553 else 1554 GenerateArg(Consumer, OPT_ftime_report); 1555 } 1556 1557 if (Opts.PrepareForLTO && !Opts.PrepareForThinLTO) 1558 GenerateArg(Consumer, OPT_flto_EQ, "full"); 1559 1560 if (Opts.PrepareForThinLTO) 1561 GenerateArg(Consumer, OPT_flto_EQ, "thin"); 1562 1563 if (!Opts.ThinLTOIndexFile.empty()) 1564 GenerateArg(Consumer, OPT_fthinlto_index_EQ, Opts.ThinLTOIndexFile); 1565 1566 if (Opts.SaveTempsFilePrefix == OutputFile) 1567 GenerateArg(Consumer, OPT_save_temps_EQ, "obj"); 1568 1569 StringRef MemProfileBasename("memprof.profraw"); 1570 if (!Opts.MemoryProfileOutput.empty()) { 1571 if (Opts.MemoryProfileOutput == MemProfileBasename) { 1572 GenerateArg(Consumer, OPT_fmemory_profile); 1573 } else { 1574 size_t ArgLength = 1575 Opts.MemoryProfileOutput.size() - MemProfileBasename.size(); 1576 GenerateArg(Consumer, OPT_fmemory_profile_EQ, 1577 Opts.MemoryProfileOutput.substr(0, ArgLength)); 1578 } 1579 } 1580 1581 if (memcmp(Opts.CoverageVersion, "408*", 4) != 0) 1582 GenerateArg(Consumer, OPT_coverage_version_EQ, 1583 StringRef(Opts.CoverageVersion, 4)); 1584 1585 // TODO: Check if we need to generate arguments stored in CmdArgs. (Namely 1586 // '-fembed_bitcode', which does not map to any CompilerInvocation field and 1587 // won't be generated.) 1588 1589 if (Opts.XRayInstrumentationBundle.Mask != XRayInstrKind::All) { 1590 std::string InstrBundle = 1591 serializeXRayInstrumentationBundle(Opts.XRayInstrumentationBundle); 1592 if (!InstrBundle.empty()) 1593 GenerateArg(Consumer, OPT_fxray_instrumentation_bundle, InstrBundle); 1594 } 1595 1596 if (Opts.CFProtectionReturn && Opts.CFProtectionBranch) 1597 GenerateArg(Consumer, OPT_fcf_protection_EQ, "full"); 1598 else if (Opts.CFProtectionReturn) 1599 GenerateArg(Consumer, OPT_fcf_protection_EQ, "return"); 1600 else if (Opts.CFProtectionBranch) 1601 GenerateArg(Consumer, OPT_fcf_protection_EQ, "branch"); 1602 1603 if (Opts.FunctionReturnThunks) 1604 GenerateArg(Consumer, OPT_mfunction_return_EQ, "thunk-extern"); 1605 1606 for (const auto &F : Opts.LinkBitcodeFiles) { 1607 bool Builtint = F.LinkFlags == llvm::Linker::Flags::LinkOnlyNeeded && 1608 F.PropagateAttrs && F.Internalize; 1609 GenerateArg(Consumer, 1610 Builtint ? OPT_mlink_builtin_bitcode : OPT_mlink_bitcode_file, 1611 F.Filename); 1612 } 1613 1614 if (Opts.EmulatedTLS) 1615 GenerateArg(Consumer, OPT_femulated_tls); 1616 1617 if (Opts.FPDenormalMode != llvm::DenormalMode::getIEEE()) 1618 GenerateArg(Consumer, OPT_fdenormal_fp_math_EQ, Opts.FPDenormalMode.str()); 1619 1620 if ((Opts.FPDenormalMode != Opts.FP32DenormalMode) || 1621 (Opts.FP32DenormalMode != llvm::DenormalMode::getIEEE())) 1622 GenerateArg(Consumer, OPT_fdenormal_fp_math_f32_EQ, 1623 Opts.FP32DenormalMode.str()); 1624 1625 if (Opts.StructReturnConvention == CodeGenOptions::SRCK_OnStack) { 1626 OptSpecifier Opt = 1627 T.isPPC32() ? OPT_maix_struct_return : OPT_fpcc_struct_return; 1628 GenerateArg(Consumer, Opt); 1629 } else if (Opts.StructReturnConvention == CodeGenOptions::SRCK_InRegs) { 1630 OptSpecifier Opt = 1631 T.isPPC32() ? OPT_msvr4_struct_return : OPT_freg_struct_return; 1632 GenerateArg(Consumer, Opt); 1633 } 1634 1635 if (Opts.EnableAIXExtendedAltivecABI) 1636 GenerateArg(Consumer, OPT_mabi_EQ_vec_extabi); 1637 1638 if (Opts.XCOFFReadOnlyPointers) 1639 GenerateArg(Consumer, OPT_mxcoff_roptr); 1640 1641 if (!Opts.OptRecordPasses.empty()) 1642 GenerateArg(Consumer, OPT_opt_record_passes, Opts.OptRecordPasses); 1643 1644 if (!Opts.OptRecordFormat.empty()) 1645 GenerateArg(Consumer, OPT_opt_record_format, Opts.OptRecordFormat); 1646 1647 GenerateOptimizationRemark(Consumer, OPT_Rpass_EQ, "pass", 1648 Opts.OptimizationRemark); 1649 1650 GenerateOptimizationRemark(Consumer, OPT_Rpass_missed_EQ, "pass-missed", 1651 Opts.OptimizationRemarkMissed); 1652 1653 GenerateOptimizationRemark(Consumer, OPT_Rpass_analysis_EQ, "pass-analysis", 1654 Opts.OptimizationRemarkAnalysis); 1655 1656 GenerateArg(Consumer, OPT_fdiagnostics_hotness_threshold_EQ, 1657 Opts.DiagnosticsHotnessThreshold 1658 ? Twine(*Opts.DiagnosticsHotnessThreshold) 1659 : "auto"); 1660 1661 GenerateArg(Consumer, OPT_fdiagnostics_misexpect_tolerance_EQ, 1662 Twine(*Opts.DiagnosticsMisExpectTolerance)); 1663 1664 for (StringRef Sanitizer : serializeSanitizerKinds(Opts.SanitizeRecover)) 1665 GenerateArg(Consumer, OPT_fsanitize_recover_EQ, Sanitizer); 1666 1667 for (StringRef Sanitizer : serializeSanitizerKinds(Opts.SanitizeTrap)) 1668 GenerateArg(Consumer, OPT_fsanitize_trap_EQ, Sanitizer); 1669 1670 if (!Opts.EmitVersionIdentMetadata) 1671 GenerateArg(Consumer, OPT_Qn); 1672 1673 switch (Opts.FiniteLoops) { 1674 case CodeGenOptions::FiniteLoopsKind::Language: 1675 break; 1676 case CodeGenOptions::FiniteLoopsKind::Always: 1677 GenerateArg(Consumer, OPT_ffinite_loops); 1678 break; 1679 case CodeGenOptions::FiniteLoopsKind::Never: 1680 GenerateArg(Consumer, OPT_fno_finite_loops); 1681 break; 1682 } 1683 } 1684 1685 bool CompilerInvocation::ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, 1686 InputKind IK, 1687 DiagnosticsEngine &Diags, 1688 const llvm::Triple &T, 1689 const std::string &OutputFile, 1690 const LangOptions &LangOptsRef) { 1691 unsigned NumErrorsBefore = Diags.getNumErrors(); 1692 1693 unsigned OptimizationLevel = getOptimizationLevel(Args, IK, Diags); 1694 // TODO: This could be done in Driver 1695 unsigned MaxOptLevel = 3; 1696 if (OptimizationLevel > MaxOptLevel) { 1697 // If the optimization level is not supported, fall back on the default 1698 // optimization 1699 Diags.Report(diag::warn_drv_optimization_value) 1700 << Args.getLastArg(OPT_O)->getAsString(Args) << "-O" << MaxOptLevel; 1701 OptimizationLevel = MaxOptLevel; 1702 } 1703 Opts.OptimizationLevel = OptimizationLevel; 1704 1705 // The key paths of codegen options defined in Options.td start with 1706 // "CodeGenOpts.". Let's provide the expected variable name and type. 1707 CodeGenOptions &CodeGenOpts = Opts; 1708 // Some codegen options depend on language options. Let's provide the expected 1709 // variable name and type. 1710 const LangOptions *LangOpts = &LangOptsRef; 1711 1712 #define CODEGEN_OPTION_WITH_MARSHALLING(...) \ 1713 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__) 1714 #include "clang/Driver/Options.inc" 1715 #undef CODEGEN_OPTION_WITH_MARSHALLING 1716 1717 // At O0 we want to fully disable inlining outside of cases marked with 1718 // 'alwaysinline' that are required for correctness. 1719 if (Opts.OptimizationLevel == 0) { 1720 Opts.setInlining(CodeGenOptions::OnlyAlwaysInlining); 1721 } else if (const Arg *A = Args.getLastArg(options::OPT_finline_functions, 1722 options::OPT_finline_hint_functions, 1723 options::OPT_fno_inline_functions, 1724 options::OPT_fno_inline)) { 1725 // Explicit inlining flags can disable some or all inlining even at 1726 // optimization levels above zero. 1727 if (A->getOption().matches(options::OPT_finline_functions)) 1728 Opts.setInlining(CodeGenOptions::NormalInlining); 1729 else if (A->getOption().matches(options::OPT_finline_hint_functions)) 1730 Opts.setInlining(CodeGenOptions::OnlyHintInlining); 1731 else 1732 Opts.setInlining(CodeGenOptions::OnlyAlwaysInlining); 1733 } else { 1734 Opts.setInlining(CodeGenOptions::NormalInlining); 1735 } 1736 1737 // PIC defaults to -fno-direct-access-external-data while non-PIC defaults to 1738 // -fdirect-access-external-data. 1739 Opts.DirectAccessExternalData = 1740 Args.hasArg(OPT_fdirect_access_external_data) || 1741 (!Args.hasArg(OPT_fno_direct_access_external_data) && 1742 LangOpts->PICLevel == 0); 1743 1744 if (Arg *A = Args.getLastArg(OPT_debug_info_kind_EQ)) { 1745 unsigned Val = 1746 llvm::StringSwitch<unsigned>(A->getValue()) 1747 .Case("line-tables-only", llvm::codegenoptions::DebugLineTablesOnly) 1748 .Case("line-directives-only", 1749 llvm::codegenoptions::DebugDirectivesOnly) 1750 .Case("constructor", llvm::codegenoptions::DebugInfoConstructor) 1751 .Case("limited", llvm::codegenoptions::LimitedDebugInfo) 1752 .Case("standalone", llvm::codegenoptions::FullDebugInfo) 1753 .Case("unused-types", llvm::codegenoptions::UnusedTypeInfo) 1754 .Default(~0U); 1755 if (Val == ~0U) 1756 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) 1757 << A->getValue(); 1758 else 1759 Opts.setDebugInfo(static_cast<llvm::codegenoptions::DebugInfoKind>(Val)); 1760 } 1761 1762 // If -fuse-ctor-homing is set and limited debug info is already on, then use 1763 // constructor homing, and vice versa for -fno-use-ctor-homing. 1764 if (const Arg *A = 1765 Args.getLastArg(OPT_fuse_ctor_homing, OPT_fno_use_ctor_homing)) { 1766 if (A->getOption().matches(OPT_fuse_ctor_homing) && 1767 Opts.getDebugInfo() == llvm::codegenoptions::LimitedDebugInfo) 1768 Opts.setDebugInfo(llvm::codegenoptions::DebugInfoConstructor); 1769 if (A->getOption().matches(OPT_fno_use_ctor_homing) && 1770 Opts.getDebugInfo() == llvm::codegenoptions::DebugInfoConstructor) 1771 Opts.setDebugInfo(llvm::codegenoptions::LimitedDebugInfo); 1772 } 1773 1774 for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ)) { 1775 auto Split = StringRef(Arg).split('='); 1776 Opts.DebugPrefixMap.emplace_back(Split.first, Split.second); 1777 } 1778 1779 for (const auto &Arg : Args.getAllArgValues(OPT_fcoverage_prefix_map_EQ)) { 1780 auto Split = StringRef(Arg).split('='); 1781 Opts.CoveragePrefixMap.emplace_back(Split.first, Split.second); 1782 } 1783 1784 const llvm::Triple::ArchType DebugEntryValueArchs[] = { 1785 llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::aarch64, 1786 llvm::Triple::arm, llvm::Triple::armeb, llvm::Triple::mips, 1787 llvm::Triple::mipsel, llvm::Triple::mips64, llvm::Triple::mips64el}; 1788 1789 if (Opts.OptimizationLevel > 0 && Opts.hasReducedDebugInfo() && 1790 llvm::is_contained(DebugEntryValueArchs, T.getArch())) 1791 Opts.EmitCallSiteInfo = true; 1792 1793 if (!Opts.EnableDIPreservationVerify && Opts.DIBugsReportFilePath.size()) { 1794 Diags.Report(diag::warn_ignoring_verify_debuginfo_preserve_export) 1795 << Opts.DIBugsReportFilePath; 1796 Opts.DIBugsReportFilePath = ""; 1797 } 1798 1799 Opts.NewStructPathTBAA = !Args.hasArg(OPT_no_struct_path_tbaa) && 1800 Args.hasArg(OPT_new_struct_path_tbaa); 1801 Opts.OptimizeSize = getOptimizationLevelSize(Args); 1802 Opts.SimplifyLibCalls = !LangOpts->NoBuiltin; 1803 if (Opts.SimplifyLibCalls) 1804 Opts.NoBuiltinFuncs = LangOpts->NoBuiltinFuncs; 1805 Opts.UnrollLoops = 1806 Args.hasFlag(OPT_funroll_loops, OPT_fno_unroll_loops, 1807 (Opts.OptimizationLevel > 1)); 1808 Opts.BinutilsVersion = 1809 std::string(Args.getLastArgValue(OPT_fbinutils_version_EQ)); 1810 1811 Opts.DebugNameTable = static_cast<unsigned>( 1812 Args.hasArg(OPT_ggnu_pubnames) 1813 ? llvm::DICompileUnit::DebugNameTableKind::GNU 1814 : Args.hasArg(OPT_gpubnames) 1815 ? llvm::DICompileUnit::DebugNameTableKind::Default 1816 : llvm::DICompileUnit::DebugNameTableKind::None); 1817 if (const Arg *A = Args.getLastArg(OPT_gsimple_template_names_EQ)) { 1818 StringRef Value = A->getValue(); 1819 if (Value != "simple" && Value != "mangled") 1820 Diags.Report(diag::err_drv_unsupported_option_argument) 1821 << A->getSpelling() << A->getValue(); 1822 Opts.setDebugSimpleTemplateNames( 1823 StringRef(A->getValue()) == "simple" 1824 ? llvm::codegenoptions::DebugTemplateNamesKind::Simple 1825 : llvm::codegenoptions::DebugTemplateNamesKind::Mangled); 1826 } 1827 1828 if (const Arg *A = Args.getLastArg(OPT_ftime_report, OPT_ftime_report_EQ)) { 1829 Opts.TimePasses = true; 1830 1831 // -ftime-report= is only for new pass manager. 1832 if (A->getOption().getID() == OPT_ftime_report_EQ) { 1833 StringRef Val = A->getValue(); 1834 if (Val == "per-pass") 1835 Opts.TimePassesPerRun = false; 1836 else if (Val == "per-pass-run") 1837 Opts.TimePassesPerRun = true; 1838 else 1839 Diags.Report(diag::err_drv_invalid_value) 1840 << A->getAsString(Args) << A->getValue(); 1841 } 1842 } 1843 1844 Opts.PrepareForLTO = false; 1845 Opts.PrepareForThinLTO = false; 1846 if (Arg *A = Args.getLastArg(OPT_flto_EQ)) { 1847 Opts.PrepareForLTO = true; 1848 StringRef S = A->getValue(); 1849 if (S == "thin") 1850 Opts.PrepareForThinLTO = true; 1851 else if (S != "full") 1852 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << S; 1853 if (Args.hasArg(OPT_funified_lto)) 1854 Opts.PrepareForThinLTO = true; 1855 } 1856 if (Arg *A = Args.getLastArg(OPT_fthinlto_index_EQ)) { 1857 if (IK.getLanguage() != Language::LLVM_IR) 1858 Diags.Report(diag::err_drv_argument_only_allowed_with) 1859 << A->getAsString(Args) << "-x ir"; 1860 Opts.ThinLTOIndexFile = 1861 std::string(Args.getLastArgValue(OPT_fthinlto_index_EQ)); 1862 } 1863 if (Arg *A = Args.getLastArg(OPT_save_temps_EQ)) 1864 Opts.SaveTempsFilePrefix = 1865 llvm::StringSwitch<std::string>(A->getValue()) 1866 .Case("obj", OutputFile) 1867 .Default(llvm::sys::path::filename(OutputFile).str()); 1868 1869 // The memory profile runtime appends the pid to make this name more unique. 1870 const char *MemProfileBasename = "memprof.profraw"; 1871 if (Args.hasArg(OPT_fmemory_profile_EQ)) { 1872 SmallString<128> Path( 1873 std::string(Args.getLastArgValue(OPT_fmemory_profile_EQ))); 1874 llvm::sys::path::append(Path, MemProfileBasename); 1875 Opts.MemoryProfileOutput = std::string(Path); 1876 } else if (Args.hasArg(OPT_fmemory_profile)) 1877 Opts.MemoryProfileOutput = MemProfileBasename; 1878 1879 memcpy(Opts.CoverageVersion, "408*", 4); 1880 if (Opts.CoverageNotesFile.size() || Opts.CoverageDataFile.size()) { 1881 if (Args.hasArg(OPT_coverage_version_EQ)) { 1882 StringRef CoverageVersion = Args.getLastArgValue(OPT_coverage_version_EQ); 1883 if (CoverageVersion.size() != 4) { 1884 Diags.Report(diag::err_drv_invalid_value) 1885 << Args.getLastArg(OPT_coverage_version_EQ)->getAsString(Args) 1886 << CoverageVersion; 1887 } else { 1888 memcpy(Opts.CoverageVersion, CoverageVersion.data(), 4); 1889 } 1890 } 1891 } 1892 // FIXME: For backend options that are not yet recorded as function 1893 // attributes in the IR, keep track of them so we can embed them in a 1894 // separate data section and use them when building the bitcode. 1895 for (const auto &A : Args) { 1896 // Do not encode output and input. 1897 if (A->getOption().getID() == options::OPT_o || 1898 A->getOption().getID() == options::OPT_INPUT || 1899 A->getOption().getID() == options::OPT_x || 1900 A->getOption().getID() == options::OPT_fembed_bitcode || 1901 A->getOption().matches(options::OPT_W_Group)) 1902 continue; 1903 ArgStringList ASL; 1904 A->render(Args, ASL); 1905 for (const auto &arg : ASL) { 1906 StringRef ArgStr(arg); 1907 Opts.CmdArgs.insert(Opts.CmdArgs.end(), ArgStr.begin(), ArgStr.end()); 1908 // using \00 to separate each commandline options. 1909 Opts.CmdArgs.push_back('\0'); 1910 } 1911 } 1912 1913 auto XRayInstrBundles = 1914 Args.getAllArgValues(OPT_fxray_instrumentation_bundle); 1915 if (XRayInstrBundles.empty()) 1916 Opts.XRayInstrumentationBundle.Mask = XRayInstrKind::All; 1917 else 1918 for (const auto &A : XRayInstrBundles) 1919 parseXRayInstrumentationBundle("-fxray-instrumentation-bundle=", A, Args, 1920 Diags, Opts.XRayInstrumentationBundle); 1921 1922 if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) { 1923 StringRef Name = A->getValue(); 1924 if (Name == "full") { 1925 Opts.CFProtectionReturn = 1; 1926 Opts.CFProtectionBranch = 1; 1927 } else if (Name == "return") 1928 Opts.CFProtectionReturn = 1; 1929 else if (Name == "branch") 1930 Opts.CFProtectionBranch = 1; 1931 else if (Name != "none") 1932 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name; 1933 } 1934 1935 if (const Arg *A = Args.getLastArg(OPT_mfunction_return_EQ)) { 1936 auto Val = llvm::StringSwitch<llvm::FunctionReturnThunksKind>(A->getValue()) 1937 .Case("keep", llvm::FunctionReturnThunksKind::Keep) 1938 .Case("thunk-extern", llvm::FunctionReturnThunksKind::Extern) 1939 .Default(llvm::FunctionReturnThunksKind::Invalid); 1940 // SystemZ might want to add support for "expolines." 1941 if (!T.isX86()) 1942 Diags.Report(diag::err_drv_argument_not_allowed_with) 1943 << A->getSpelling() << T.getTriple(); 1944 else if (Val == llvm::FunctionReturnThunksKind::Invalid) 1945 Diags.Report(diag::err_drv_invalid_value) 1946 << A->getAsString(Args) << A->getValue(); 1947 else if (Val == llvm::FunctionReturnThunksKind::Extern && 1948 Args.getLastArgValue(OPT_mcmodel_EQ).equals("large")) 1949 Diags.Report(diag::err_drv_argument_not_allowed_with) 1950 << A->getAsString(Args) 1951 << Args.getLastArg(OPT_mcmodel_EQ)->getAsString(Args); 1952 else 1953 Opts.FunctionReturnThunks = static_cast<unsigned>(Val); 1954 } 1955 1956 for (auto *A : 1957 Args.filtered(OPT_mlink_bitcode_file, OPT_mlink_builtin_bitcode)) { 1958 CodeGenOptions::BitcodeFileToLink F; 1959 F.Filename = A->getValue(); 1960 if (A->getOption().matches(OPT_mlink_builtin_bitcode)) { 1961 F.LinkFlags = llvm::Linker::Flags::LinkOnlyNeeded; 1962 // When linking CUDA bitcode, propagate function attributes so that 1963 // e.g. libdevice gets fast-math attrs if we're building with fast-math. 1964 F.PropagateAttrs = true; 1965 F.Internalize = true; 1966 } 1967 Opts.LinkBitcodeFiles.push_back(F); 1968 } 1969 1970 if (Arg *A = Args.getLastArg(OPT_ftlsmodel_EQ)) { 1971 if (T.isOSAIX()) { 1972 StringRef Name = A->getValue(); 1973 if (Name == "local-dynamic") 1974 Diags.Report(diag::err_aix_unsupported_tls_model) << Name; 1975 } 1976 } 1977 1978 if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_EQ)) { 1979 StringRef Val = A->getValue(); 1980 Opts.FPDenormalMode = llvm::parseDenormalFPAttribute(Val); 1981 Opts.FP32DenormalMode = Opts.FPDenormalMode; 1982 if (!Opts.FPDenormalMode.isValid()) 1983 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val; 1984 } 1985 1986 if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_f32_EQ)) { 1987 StringRef Val = A->getValue(); 1988 Opts.FP32DenormalMode = llvm::parseDenormalFPAttribute(Val); 1989 if (!Opts.FP32DenormalMode.isValid()) 1990 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val; 1991 } 1992 1993 // X86_32 has -fppc-struct-return and -freg-struct-return. 1994 // PPC32 has -maix-struct-return and -msvr4-struct-return. 1995 if (Arg *A = 1996 Args.getLastArg(OPT_fpcc_struct_return, OPT_freg_struct_return, 1997 OPT_maix_struct_return, OPT_msvr4_struct_return)) { 1998 // TODO: We might want to consider enabling these options on AIX in the 1999 // future. 2000 if (T.isOSAIX()) 2001 Diags.Report(diag::err_drv_unsupported_opt_for_target) 2002 << A->getSpelling() << T.str(); 2003 2004 const Option &O = A->getOption(); 2005 if (O.matches(OPT_fpcc_struct_return) || 2006 O.matches(OPT_maix_struct_return)) { 2007 Opts.setStructReturnConvention(CodeGenOptions::SRCK_OnStack); 2008 } else { 2009 assert(O.matches(OPT_freg_struct_return) || 2010 O.matches(OPT_msvr4_struct_return)); 2011 Opts.setStructReturnConvention(CodeGenOptions::SRCK_InRegs); 2012 } 2013 } 2014 2015 if (Arg *A = Args.getLastArg(OPT_mxcoff_roptr)) { 2016 if (!T.isOSAIX()) 2017 Diags.Report(diag::err_drv_unsupported_opt_for_target) 2018 << A->getSpelling() << T.str(); 2019 2020 // Since the storage mapping class is specified per csect, 2021 // without using data sections, it is less effective to use read-only 2022 // pointers. Using read-only pointers may cause other RO variables in the 2023 // same csect to become RW when the linker acts upon `-bforceimprw`; 2024 // therefore, we require that separate data sections 2025 // are used when `-mxcoff-roptr` is in effect. We respect the setting of 2026 // data-sections since we have not found reasons to do otherwise that 2027 // overcome the user surprise of not respecting the setting. 2028 if (!Args.hasFlag(OPT_fdata_sections, OPT_fno_data_sections, false)) 2029 Diags.Report(diag::err_roptr_requires_data_sections); 2030 2031 Opts.XCOFFReadOnlyPointers = true; 2032 } 2033 2034 if (Arg *A = Args.getLastArg(OPT_mabi_EQ_quadword_atomics)) { 2035 if (!T.isOSAIX() || T.isPPC32()) 2036 Diags.Report(diag::err_drv_unsupported_opt_for_target) 2037 << A->getSpelling() << T.str(); 2038 } 2039 2040 bool NeedLocTracking = false; 2041 2042 if (!Opts.OptRecordFile.empty()) 2043 NeedLocTracking = true; 2044 2045 if (Arg *A = Args.getLastArg(OPT_opt_record_passes)) { 2046 Opts.OptRecordPasses = A->getValue(); 2047 NeedLocTracking = true; 2048 } 2049 2050 if (Arg *A = Args.getLastArg(OPT_opt_record_format)) { 2051 Opts.OptRecordFormat = A->getValue(); 2052 NeedLocTracking = true; 2053 } 2054 2055 Opts.OptimizationRemark = 2056 ParseOptimizationRemark(Diags, Args, OPT_Rpass_EQ, "pass"); 2057 2058 Opts.OptimizationRemarkMissed = 2059 ParseOptimizationRemark(Diags, Args, OPT_Rpass_missed_EQ, "pass-missed"); 2060 2061 Opts.OptimizationRemarkAnalysis = ParseOptimizationRemark( 2062 Diags, Args, OPT_Rpass_analysis_EQ, "pass-analysis"); 2063 2064 NeedLocTracking |= Opts.OptimizationRemark.hasValidPattern() || 2065 Opts.OptimizationRemarkMissed.hasValidPattern() || 2066 Opts.OptimizationRemarkAnalysis.hasValidPattern(); 2067 2068 bool UsingSampleProfile = !Opts.SampleProfileFile.empty(); 2069 bool UsingProfile = 2070 UsingSampleProfile || !Opts.ProfileInstrumentUsePath.empty(); 2071 2072 if (Opts.DiagnosticsWithHotness && !UsingProfile && 2073 // An IR file will contain PGO as metadata 2074 IK.getLanguage() != Language::LLVM_IR) 2075 Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo) 2076 << "-fdiagnostics-show-hotness"; 2077 2078 // Parse remarks hotness threshold. Valid value is either integer or 'auto'. 2079 if (auto *arg = 2080 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) { 2081 auto ResultOrErr = 2082 llvm::remarks::parseHotnessThresholdOption(arg->getValue()); 2083 2084 if (!ResultOrErr) { 2085 Diags.Report(diag::err_drv_invalid_diagnotics_hotness_threshold) 2086 << "-fdiagnostics-hotness-threshold="; 2087 } else { 2088 Opts.DiagnosticsHotnessThreshold = *ResultOrErr; 2089 if ((!Opts.DiagnosticsHotnessThreshold || 2090 *Opts.DiagnosticsHotnessThreshold > 0) && 2091 !UsingProfile) 2092 Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo) 2093 << "-fdiagnostics-hotness-threshold="; 2094 } 2095 } 2096 2097 if (auto *arg = 2098 Args.getLastArg(options::OPT_fdiagnostics_misexpect_tolerance_EQ)) { 2099 auto ResultOrErr = parseToleranceOption(arg->getValue()); 2100 2101 if (!ResultOrErr) { 2102 Diags.Report(diag::err_drv_invalid_diagnotics_misexpect_tolerance) 2103 << "-fdiagnostics-misexpect-tolerance="; 2104 } else { 2105 Opts.DiagnosticsMisExpectTolerance = *ResultOrErr; 2106 if ((!Opts.DiagnosticsMisExpectTolerance || 2107 *Opts.DiagnosticsMisExpectTolerance > 0) && 2108 !UsingProfile) 2109 Diags.Report(diag::warn_drv_diagnostics_misexpect_requires_pgo) 2110 << "-fdiagnostics-misexpect-tolerance="; 2111 } 2112 } 2113 2114 // If the user requested to use a sample profile for PGO, then the 2115 // backend will need to track source location information so the profile 2116 // can be incorporated into the IR. 2117 if (UsingSampleProfile) 2118 NeedLocTracking = true; 2119 2120 if (!Opts.StackUsageOutput.empty()) 2121 NeedLocTracking = true; 2122 2123 // If the user requested a flag that requires source locations available in 2124 // the backend, make sure that the backend tracks source location information. 2125 if (NeedLocTracking && 2126 Opts.getDebugInfo() == llvm::codegenoptions::NoDebugInfo) 2127 Opts.setDebugInfo(llvm::codegenoptions::LocTrackingOnly); 2128 2129 // Parse -fsanitize-recover= arguments. 2130 // FIXME: Report unrecoverable sanitizers incorrectly specified here. 2131 parseSanitizerKinds("-fsanitize-recover=", 2132 Args.getAllArgValues(OPT_fsanitize_recover_EQ), Diags, 2133 Opts.SanitizeRecover); 2134 parseSanitizerKinds("-fsanitize-trap=", 2135 Args.getAllArgValues(OPT_fsanitize_trap_EQ), Diags, 2136 Opts.SanitizeTrap); 2137 2138 Opts.EmitVersionIdentMetadata = Args.hasFlag(OPT_Qy, OPT_Qn, true); 2139 2140 if (Args.hasArg(options::OPT_ffinite_loops)) 2141 Opts.FiniteLoops = CodeGenOptions::FiniteLoopsKind::Always; 2142 else if (Args.hasArg(options::OPT_fno_finite_loops)) 2143 Opts.FiniteLoops = CodeGenOptions::FiniteLoopsKind::Never; 2144 2145 Opts.EmitIEEENaNCompliantInsts = Args.hasFlag( 2146 options::OPT_mamdgpu_ieee, options::OPT_mno_amdgpu_ieee, true); 2147 if (!Opts.EmitIEEENaNCompliantInsts && !LangOptsRef.NoHonorNaNs) 2148 Diags.Report(diag::err_drv_amdgpu_ieee_without_no_honor_nans); 2149 2150 return Diags.getNumErrors() == NumErrorsBefore; 2151 } 2152 2153 static void GenerateDependencyOutputArgs(const DependencyOutputOptions &Opts, 2154 ArgumentConsumer Consumer) { 2155 const DependencyOutputOptions &DependencyOutputOpts = Opts; 2156 #define DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING(...) \ 2157 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__) 2158 #include "clang/Driver/Options.inc" 2159 #undef DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING 2160 2161 if (Opts.ShowIncludesDest != ShowIncludesDestination::None) 2162 GenerateArg(Consumer, OPT_show_includes); 2163 2164 for (const auto &Dep : Opts.ExtraDeps) { 2165 switch (Dep.second) { 2166 case EDK_SanitizeIgnorelist: 2167 // Sanitizer ignorelist arguments are generated from LanguageOptions. 2168 continue; 2169 case EDK_ModuleFile: 2170 // Module file arguments are generated from FrontendOptions and 2171 // HeaderSearchOptions. 2172 continue; 2173 case EDK_ProfileList: 2174 // Profile list arguments are generated from LanguageOptions via the 2175 // marshalling infrastructure. 2176 continue; 2177 case EDK_DepFileEntry: 2178 GenerateArg(Consumer, OPT_fdepfile_entry, Dep.first); 2179 break; 2180 } 2181 } 2182 } 2183 2184 static bool ParseDependencyOutputArgs(DependencyOutputOptions &Opts, 2185 ArgList &Args, DiagnosticsEngine &Diags, 2186 frontend::ActionKind Action, 2187 bool ShowLineMarkers) { 2188 unsigned NumErrorsBefore = Diags.getNumErrors(); 2189 2190 DependencyOutputOptions &DependencyOutputOpts = Opts; 2191 #define DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING(...) \ 2192 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__) 2193 #include "clang/Driver/Options.inc" 2194 #undef DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING 2195 2196 if (Args.hasArg(OPT_show_includes)) { 2197 // Writing both /showIncludes and preprocessor output to stdout 2198 // would produce interleaved output, so use stderr for /showIncludes. 2199 // This behaves the same as cl.exe, when /E, /EP or /P are passed. 2200 if (Action == frontend::PrintPreprocessedInput || !ShowLineMarkers) 2201 Opts.ShowIncludesDest = ShowIncludesDestination::Stderr; 2202 else 2203 Opts.ShowIncludesDest = ShowIncludesDestination::Stdout; 2204 } else { 2205 Opts.ShowIncludesDest = ShowIncludesDestination::None; 2206 } 2207 2208 // Add sanitizer ignorelists as extra dependencies. 2209 // They won't be discovered by the regular preprocessor, so 2210 // we let make / ninja to know about this implicit dependency. 2211 if (!Args.hasArg(OPT_fno_sanitize_ignorelist)) { 2212 for (const auto *A : Args.filtered(OPT_fsanitize_ignorelist_EQ)) { 2213 StringRef Val = A->getValue(); 2214 if (!Val.contains('=')) 2215 Opts.ExtraDeps.emplace_back(std::string(Val), EDK_SanitizeIgnorelist); 2216 } 2217 if (Opts.IncludeSystemHeaders) { 2218 for (const auto *A : Args.filtered(OPT_fsanitize_system_ignorelist_EQ)) { 2219 StringRef Val = A->getValue(); 2220 if (!Val.contains('=')) 2221 Opts.ExtraDeps.emplace_back(std::string(Val), EDK_SanitizeIgnorelist); 2222 } 2223 } 2224 } 2225 2226 // -fprofile-list= dependencies. 2227 for (const auto &Filename : Args.getAllArgValues(OPT_fprofile_list_EQ)) 2228 Opts.ExtraDeps.emplace_back(Filename, EDK_ProfileList); 2229 2230 // Propagate the extra dependencies. 2231 for (const auto *A : Args.filtered(OPT_fdepfile_entry)) 2232 Opts.ExtraDeps.emplace_back(A->getValue(), EDK_DepFileEntry); 2233 2234 // Only the -fmodule-file=<file> form. 2235 for (const auto *A : Args.filtered(OPT_fmodule_file)) { 2236 StringRef Val = A->getValue(); 2237 if (!Val.contains('=')) 2238 Opts.ExtraDeps.emplace_back(std::string(Val), EDK_ModuleFile); 2239 } 2240 2241 // Check for invalid combinations of header-include-format 2242 // and header-include-filtering. 2243 if ((Opts.HeaderIncludeFormat == HIFMT_Textual && 2244 Opts.HeaderIncludeFiltering != HIFIL_None) || 2245 (Opts.HeaderIncludeFormat == HIFMT_JSON && 2246 Opts.HeaderIncludeFiltering != HIFIL_Only_Direct_System)) 2247 Diags.Report(diag::err_drv_print_header_env_var_combination_cc1) 2248 << Args.getLastArg(OPT_header_include_format_EQ)->getValue() 2249 << Args.getLastArg(OPT_header_include_filtering_EQ)->getValue(); 2250 2251 return Diags.getNumErrors() == NumErrorsBefore; 2252 } 2253 2254 static bool parseShowColorsArgs(const ArgList &Args, bool DefaultColor) { 2255 // Color diagnostics default to auto ("on" if terminal supports) in the driver 2256 // but default to off in cc1, needing an explicit OPT_fdiagnostics_color. 2257 // Support both clang's -f[no-]color-diagnostics and gcc's 2258 // -f[no-]diagnostics-colors[=never|always|auto]. 2259 enum { 2260 Colors_On, 2261 Colors_Off, 2262 Colors_Auto 2263 } ShowColors = DefaultColor ? Colors_Auto : Colors_Off; 2264 for (auto *A : Args) { 2265 const Option &O = A->getOption(); 2266 if (O.matches(options::OPT_fcolor_diagnostics)) { 2267 ShowColors = Colors_On; 2268 } else if (O.matches(options::OPT_fno_color_diagnostics)) { 2269 ShowColors = Colors_Off; 2270 } else if (O.matches(options::OPT_fdiagnostics_color_EQ)) { 2271 StringRef Value(A->getValue()); 2272 if (Value == "always") 2273 ShowColors = Colors_On; 2274 else if (Value == "never") 2275 ShowColors = Colors_Off; 2276 else if (Value == "auto") 2277 ShowColors = Colors_Auto; 2278 } 2279 } 2280 return ShowColors == Colors_On || 2281 (ShowColors == Colors_Auto && 2282 llvm::sys::Process::StandardErrHasColors()); 2283 } 2284 2285 static bool checkVerifyPrefixes(const std::vector<std::string> &VerifyPrefixes, 2286 DiagnosticsEngine &Diags) { 2287 bool Success = true; 2288 for (const auto &Prefix : VerifyPrefixes) { 2289 // Every prefix must start with a letter and contain only alphanumeric 2290 // characters, hyphens, and underscores. 2291 auto BadChar = llvm::find_if(Prefix, [](char C) { 2292 return !isAlphanumeric(C) && C != '-' && C != '_'; 2293 }); 2294 if (BadChar != Prefix.end() || !isLetter(Prefix[0])) { 2295 Success = false; 2296 Diags.Report(diag::err_drv_invalid_value) << "-verify=" << Prefix; 2297 Diags.Report(diag::note_drv_verify_prefix_spelling); 2298 } 2299 } 2300 return Success; 2301 } 2302 2303 static void GenerateFileSystemArgs(const FileSystemOptions &Opts, 2304 ArgumentConsumer Consumer) { 2305 const FileSystemOptions &FileSystemOpts = Opts; 2306 2307 #define FILE_SYSTEM_OPTION_WITH_MARSHALLING(...) \ 2308 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__) 2309 #include "clang/Driver/Options.inc" 2310 #undef FILE_SYSTEM_OPTION_WITH_MARSHALLING 2311 } 2312 2313 static bool ParseFileSystemArgs(FileSystemOptions &Opts, const ArgList &Args, 2314 DiagnosticsEngine &Diags) { 2315 unsigned NumErrorsBefore = Diags.getNumErrors(); 2316 2317 FileSystemOptions &FileSystemOpts = Opts; 2318 2319 #define FILE_SYSTEM_OPTION_WITH_MARSHALLING(...) \ 2320 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__) 2321 #include "clang/Driver/Options.inc" 2322 #undef FILE_SYSTEM_OPTION_WITH_MARSHALLING 2323 2324 return Diags.getNumErrors() == NumErrorsBefore; 2325 } 2326 2327 static void GenerateMigratorArgs(const MigratorOptions &Opts, 2328 ArgumentConsumer Consumer) { 2329 const MigratorOptions &MigratorOpts = Opts; 2330 #define MIGRATOR_OPTION_WITH_MARSHALLING(...) \ 2331 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__) 2332 #include "clang/Driver/Options.inc" 2333 #undef MIGRATOR_OPTION_WITH_MARSHALLING 2334 } 2335 2336 static bool ParseMigratorArgs(MigratorOptions &Opts, const ArgList &Args, 2337 DiagnosticsEngine &Diags) { 2338 unsigned NumErrorsBefore = Diags.getNumErrors(); 2339 2340 MigratorOptions &MigratorOpts = Opts; 2341 2342 #define MIGRATOR_OPTION_WITH_MARSHALLING(...) \ 2343 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__) 2344 #include "clang/Driver/Options.inc" 2345 #undef MIGRATOR_OPTION_WITH_MARSHALLING 2346 2347 return Diags.getNumErrors() == NumErrorsBefore; 2348 } 2349 2350 void CompilerInvocationBase::GenerateDiagnosticArgs( 2351 const DiagnosticOptions &Opts, ArgumentConsumer Consumer, 2352 bool DefaultDiagColor) { 2353 const DiagnosticOptions *DiagnosticOpts = &Opts; 2354 #define DIAG_OPTION_WITH_MARSHALLING(...) \ 2355 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__) 2356 #include "clang/Driver/Options.inc" 2357 #undef DIAG_OPTION_WITH_MARSHALLING 2358 2359 if (!Opts.DiagnosticSerializationFile.empty()) 2360 GenerateArg(Consumer, OPT_diagnostic_serialized_file, 2361 Opts.DiagnosticSerializationFile); 2362 2363 if (Opts.ShowColors) 2364 GenerateArg(Consumer, OPT_fcolor_diagnostics); 2365 2366 if (Opts.VerifyDiagnostics && 2367 llvm::is_contained(Opts.VerifyPrefixes, "expected")) 2368 GenerateArg(Consumer, OPT_verify); 2369 2370 for (const auto &Prefix : Opts.VerifyPrefixes) 2371 if (Prefix != "expected") 2372 GenerateArg(Consumer, OPT_verify_EQ, Prefix); 2373 2374 DiagnosticLevelMask VIU = Opts.getVerifyIgnoreUnexpected(); 2375 if (VIU == DiagnosticLevelMask::None) { 2376 // This is the default, don't generate anything. 2377 } else if (VIU == DiagnosticLevelMask::All) { 2378 GenerateArg(Consumer, OPT_verify_ignore_unexpected); 2379 } else { 2380 if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Note) != 0) 2381 GenerateArg(Consumer, OPT_verify_ignore_unexpected_EQ, "note"); 2382 if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Remark) != 0) 2383 GenerateArg(Consumer, OPT_verify_ignore_unexpected_EQ, "remark"); 2384 if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Warning) != 0) 2385 GenerateArg(Consumer, OPT_verify_ignore_unexpected_EQ, "warning"); 2386 if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Error) != 0) 2387 GenerateArg(Consumer, OPT_verify_ignore_unexpected_EQ, "error"); 2388 } 2389 2390 for (const auto &Warning : Opts.Warnings) { 2391 // This option is automatically generated from UndefPrefixes. 2392 if (Warning == "undef-prefix") 2393 continue; 2394 Consumer(StringRef("-W") + Warning); 2395 } 2396 2397 for (const auto &Remark : Opts.Remarks) { 2398 // These arguments are generated from OptimizationRemark fields of 2399 // CodeGenOptions. 2400 StringRef IgnoredRemarks[] = {"pass", "no-pass", 2401 "pass-analysis", "no-pass-analysis", 2402 "pass-missed", "no-pass-missed"}; 2403 if (llvm::is_contained(IgnoredRemarks, Remark)) 2404 continue; 2405 2406 Consumer(StringRef("-R") + Remark); 2407 } 2408 } 2409 2410 std::unique_ptr<DiagnosticOptions> 2411 clang::CreateAndPopulateDiagOpts(ArrayRef<const char *> Argv) { 2412 auto DiagOpts = std::make_unique<DiagnosticOptions>(); 2413 unsigned MissingArgIndex, MissingArgCount; 2414 InputArgList Args = getDriverOptTable().ParseArgs( 2415 Argv.slice(1), MissingArgIndex, MissingArgCount); 2416 2417 bool ShowColors = true; 2418 if (std::optional<std::string> NoColor = 2419 llvm::sys::Process::GetEnv("NO_COLOR"); 2420 NoColor && !NoColor->empty()) { 2421 // If the user set the NO_COLOR environment variable, we'll honor that 2422 // unless the command line overrides it. 2423 ShowColors = false; 2424 } 2425 2426 // We ignore MissingArgCount and the return value of ParseDiagnosticArgs. 2427 // Any errors that would be diagnosed here will also be diagnosed later, 2428 // when the DiagnosticsEngine actually exists. 2429 (void)ParseDiagnosticArgs(*DiagOpts, Args, /*Diags=*/nullptr, ShowColors); 2430 return DiagOpts; 2431 } 2432 2433 bool clang::ParseDiagnosticArgs(DiagnosticOptions &Opts, ArgList &Args, 2434 DiagnosticsEngine *Diags, 2435 bool DefaultDiagColor) { 2436 std::optional<DiagnosticsEngine> IgnoringDiags; 2437 if (!Diags) { 2438 IgnoringDiags.emplace(new DiagnosticIDs(), new DiagnosticOptions(), 2439 new IgnoringDiagConsumer()); 2440 Diags = &*IgnoringDiags; 2441 } 2442 2443 unsigned NumErrorsBefore = Diags->getNumErrors(); 2444 2445 // The key paths of diagnostic options defined in Options.td start with 2446 // "DiagnosticOpts->". Let's provide the expected variable name and type. 2447 DiagnosticOptions *DiagnosticOpts = &Opts; 2448 2449 #define DIAG_OPTION_WITH_MARSHALLING(...) \ 2450 PARSE_OPTION_WITH_MARSHALLING(Args, *Diags, __VA_ARGS__) 2451 #include "clang/Driver/Options.inc" 2452 #undef DIAG_OPTION_WITH_MARSHALLING 2453 2454 llvm::sys::Process::UseANSIEscapeCodes(Opts.UseANSIEscapeCodes); 2455 2456 if (Arg *A = 2457 Args.getLastArg(OPT_diagnostic_serialized_file, OPT__serialize_diags)) 2458 Opts.DiagnosticSerializationFile = A->getValue(); 2459 Opts.ShowColors = parseShowColorsArgs(Args, DefaultDiagColor); 2460 2461 Opts.VerifyDiagnostics = Args.hasArg(OPT_verify) || Args.hasArg(OPT_verify_EQ); 2462 Opts.VerifyPrefixes = Args.getAllArgValues(OPT_verify_EQ); 2463 if (Args.hasArg(OPT_verify)) 2464 Opts.VerifyPrefixes.push_back("expected"); 2465 // Keep VerifyPrefixes in its original order for the sake of diagnostics, and 2466 // then sort it to prepare for fast lookup using std::binary_search. 2467 if (!checkVerifyPrefixes(Opts.VerifyPrefixes, *Diags)) 2468 Opts.VerifyDiagnostics = false; 2469 else 2470 llvm::sort(Opts.VerifyPrefixes); 2471 DiagnosticLevelMask DiagMask = DiagnosticLevelMask::None; 2472 parseDiagnosticLevelMask( 2473 "-verify-ignore-unexpected=", 2474 Args.getAllArgValues(OPT_verify_ignore_unexpected_EQ), *Diags, DiagMask); 2475 if (Args.hasArg(OPT_verify_ignore_unexpected)) 2476 DiagMask = DiagnosticLevelMask::All; 2477 Opts.setVerifyIgnoreUnexpected(DiagMask); 2478 if (Opts.TabStop == 0 || Opts.TabStop > DiagnosticOptions::MaxTabStop) { 2479 Diags->Report(diag::warn_ignoring_ftabstop_value) 2480 << Opts.TabStop << DiagnosticOptions::DefaultTabStop; 2481 Opts.TabStop = DiagnosticOptions::DefaultTabStop; 2482 } 2483 2484 addDiagnosticArgs(Args, OPT_W_Group, OPT_W_value_Group, Opts.Warnings); 2485 addDiagnosticArgs(Args, OPT_R_Group, OPT_R_value_Group, Opts.Remarks); 2486 2487 return Diags->getNumErrors() == NumErrorsBefore; 2488 } 2489 2490 /// Parse the argument to the -ftest-module-file-extension 2491 /// command-line argument. 2492 /// 2493 /// \returns true on error, false on success. 2494 static bool parseTestModuleFileExtensionArg(StringRef Arg, 2495 std::string &BlockName, 2496 unsigned &MajorVersion, 2497 unsigned &MinorVersion, 2498 bool &Hashed, 2499 std::string &UserInfo) { 2500 SmallVector<StringRef, 5> Args; 2501 Arg.split(Args, ':', 5); 2502 if (Args.size() < 5) 2503 return true; 2504 2505 BlockName = std::string(Args[0]); 2506 if (Args[1].getAsInteger(10, MajorVersion)) return true; 2507 if (Args[2].getAsInteger(10, MinorVersion)) return true; 2508 if (Args[3].getAsInteger(2, Hashed)) return true; 2509 if (Args.size() > 4) 2510 UserInfo = std::string(Args[4]); 2511 return false; 2512 } 2513 2514 /// Return a table that associates command line option specifiers with the 2515 /// frontend action. Note: The pair {frontend::PluginAction, OPT_plugin} is 2516 /// intentionally missing, as this case is handled separately from other 2517 /// frontend options. 2518 static const auto &getFrontendActionTable() { 2519 static const std::pair<frontend::ActionKind, unsigned> Table[] = { 2520 {frontend::ASTDeclList, OPT_ast_list}, 2521 2522 {frontend::ASTDump, OPT_ast_dump_all_EQ}, 2523 {frontend::ASTDump, OPT_ast_dump_all}, 2524 {frontend::ASTDump, OPT_ast_dump_EQ}, 2525 {frontend::ASTDump, OPT_ast_dump}, 2526 {frontend::ASTDump, OPT_ast_dump_lookups}, 2527 {frontend::ASTDump, OPT_ast_dump_decl_types}, 2528 2529 {frontend::ASTPrint, OPT_ast_print}, 2530 {frontend::ASTView, OPT_ast_view}, 2531 {frontend::DumpCompilerOptions, OPT_compiler_options_dump}, 2532 {frontend::DumpRawTokens, OPT_dump_raw_tokens}, 2533 {frontend::DumpTokens, OPT_dump_tokens}, 2534 {frontend::EmitAssembly, OPT_S}, 2535 {frontend::EmitBC, OPT_emit_llvm_bc}, 2536 {frontend::EmitHTML, OPT_emit_html}, 2537 {frontend::EmitLLVM, OPT_emit_llvm}, 2538 {frontend::EmitLLVMOnly, OPT_emit_llvm_only}, 2539 {frontend::EmitCodeGenOnly, OPT_emit_codegen_only}, 2540 {frontend::EmitObj, OPT_emit_obj}, 2541 {frontend::ExtractAPI, OPT_extract_api}, 2542 2543 {frontend::FixIt, OPT_fixit_EQ}, 2544 {frontend::FixIt, OPT_fixit}, 2545 2546 {frontend::GenerateModule, OPT_emit_module}, 2547 {frontend::GenerateModuleInterface, OPT_emit_module_interface}, 2548 {frontend::GenerateHeaderUnit, OPT_emit_header_unit}, 2549 {frontend::GeneratePCH, OPT_emit_pch}, 2550 {frontend::GenerateInterfaceStubs, OPT_emit_interface_stubs}, 2551 {frontend::InitOnly, OPT_init_only}, 2552 {frontend::ParseSyntaxOnly, OPT_fsyntax_only}, 2553 {frontend::ModuleFileInfo, OPT_module_file_info}, 2554 {frontend::VerifyPCH, OPT_verify_pch}, 2555 {frontend::PrintPreamble, OPT_print_preamble}, 2556 {frontend::PrintPreprocessedInput, OPT_E}, 2557 {frontend::TemplightDump, OPT_templight_dump}, 2558 {frontend::RewriteMacros, OPT_rewrite_macros}, 2559 {frontend::RewriteObjC, OPT_rewrite_objc}, 2560 {frontend::RewriteTest, OPT_rewrite_test}, 2561 {frontend::RunAnalysis, OPT_analyze}, 2562 {frontend::MigrateSource, OPT_migrate}, 2563 {frontend::RunPreprocessorOnly, OPT_Eonly}, 2564 {frontend::PrintDependencyDirectivesSourceMinimizerOutput, 2565 OPT_print_dependency_directives_minimized_source}, 2566 }; 2567 2568 return Table; 2569 } 2570 2571 /// Maps command line option to frontend action. 2572 static std::optional<frontend::ActionKind> 2573 getFrontendAction(OptSpecifier &Opt) { 2574 for (const auto &ActionOpt : getFrontendActionTable()) 2575 if (ActionOpt.second == Opt.getID()) 2576 return ActionOpt.first; 2577 2578 return std::nullopt; 2579 } 2580 2581 /// Maps frontend action to command line option. 2582 static std::optional<OptSpecifier> 2583 getProgramActionOpt(frontend::ActionKind ProgramAction) { 2584 for (const auto &ActionOpt : getFrontendActionTable()) 2585 if (ActionOpt.first == ProgramAction) 2586 return OptSpecifier(ActionOpt.second); 2587 2588 return std::nullopt; 2589 } 2590 2591 static void GenerateFrontendArgs(const FrontendOptions &Opts, 2592 ArgumentConsumer Consumer, bool IsHeader) { 2593 const FrontendOptions &FrontendOpts = Opts; 2594 #define FRONTEND_OPTION_WITH_MARSHALLING(...) \ 2595 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__) 2596 #include "clang/Driver/Options.inc" 2597 #undef FRONTEND_OPTION_WITH_MARSHALLING 2598 2599 std::optional<OptSpecifier> ProgramActionOpt = 2600 getProgramActionOpt(Opts.ProgramAction); 2601 2602 // Generating a simple flag covers most frontend actions. 2603 std::function<void()> GenerateProgramAction = [&]() { 2604 GenerateArg(Consumer, *ProgramActionOpt); 2605 }; 2606 2607 if (!ProgramActionOpt) { 2608 // PluginAction is the only program action handled separately. 2609 assert(Opts.ProgramAction == frontend::PluginAction && 2610 "Frontend action without option."); 2611 GenerateProgramAction = [&]() { 2612 GenerateArg(Consumer, OPT_plugin, Opts.ActionName); 2613 }; 2614 } 2615 2616 // FIXME: Simplify the complex 'AST dump' command line. 2617 if (Opts.ProgramAction == frontend::ASTDump) { 2618 GenerateProgramAction = [&]() { 2619 // ASTDumpLookups, ASTDumpDeclTypes and ASTDumpFilter are generated via 2620 // marshalling infrastructure. 2621 2622 if (Opts.ASTDumpFormat != ADOF_Default) { 2623 StringRef Format; 2624 switch (Opts.ASTDumpFormat) { 2625 case ADOF_Default: 2626 llvm_unreachable("Default AST dump format."); 2627 case ADOF_JSON: 2628 Format = "json"; 2629 break; 2630 } 2631 2632 if (Opts.ASTDumpAll) 2633 GenerateArg(Consumer, OPT_ast_dump_all_EQ, Format); 2634 if (Opts.ASTDumpDecls) 2635 GenerateArg(Consumer, OPT_ast_dump_EQ, Format); 2636 } else { 2637 if (Opts.ASTDumpAll) 2638 GenerateArg(Consumer, OPT_ast_dump_all); 2639 if (Opts.ASTDumpDecls) 2640 GenerateArg(Consumer, OPT_ast_dump); 2641 } 2642 }; 2643 } 2644 2645 if (Opts.ProgramAction == frontend::FixIt && !Opts.FixItSuffix.empty()) { 2646 GenerateProgramAction = [&]() { 2647 GenerateArg(Consumer, OPT_fixit_EQ, Opts.FixItSuffix); 2648 }; 2649 } 2650 2651 GenerateProgramAction(); 2652 2653 for (const auto &PluginArgs : Opts.PluginArgs) { 2654 Option Opt = getDriverOptTable().getOption(OPT_plugin_arg); 2655 for (const auto &PluginArg : PluginArgs.second) 2656 denormalizeString(Consumer, 2657 Opt.getPrefix() + Opt.getName() + PluginArgs.first, 2658 Opt.getKind(), 0, PluginArg); 2659 } 2660 2661 for (const auto &Ext : Opts.ModuleFileExtensions) 2662 if (auto *TestExt = dyn_cast_or_null<TestModuleFileExtension>(Ext.get())) 2663 GenerateArg(Consumer, OPT_ftest_module_file_extension_EQ, TestExt->str()); 2664 2665 if (!Opts.CodeCompletionAt.FileName.empty()) 2666 GenerateArg(Consumer, OPT_code_completion_at, 2667 Opts.CodeCompletionAt.ToString()); 2668 2669 for (const auto &Plugin : Opts.Plugins) 2670 GenerateArg(Consumer, OPT_load, Plugin); 2671 2672 // ASTDumpDecls and ASTDumpAll already handled with ProgramAction. 2673 2674 for (const auto &ModuleFile : Opts.ModuleFiles) 2675 GenerateArg(Consumer, OPT_fmodule_file, ModuleFile); 2676 2677 if (Opts.AuxTargetCPU) 2678 GenerateArg(Consumer, OPT_aux_target_cpu, *Opts.AuxTargetCPU); 2679 2680 if (Opts.AuxTargetFeatures) 2681 for (const auto &Feature : *Opts.AuxTargetFeatures) 2682 GenerateArg(Consumer, OPT_aux_target_feature, Feature); 2683 2684 { 2685 StringRef Preprocessed = Opts.DashX.isPreprocessed() ? "-cpp-output" : ""; 2686 StringRef ModuleMap = 2687 Opts.DashX.getFormat() == InputKind::ModuleMap ? "-module-map" : ""; 2688 StringRef HeaderUnit = ""; 2689 switch (Opts.DashX.getHeaderUnitKind()) { 2690 case InputKind::HeaderUnit_None: 2691 break; 2692 case InputKind::HeaderUnit_User: 2693 HeaderUnit = "-user"; 2694 break; 2695 case InputKind::HeaderUnit_System: 2696 HeaderUnit = "-system"; 2697 break; 2698 case InputKind::HeaderUnit_Abs: 2699 HeaderUnit = "-header-unit"; 2700 break; 2701 } 2702 StringRef Header = IsHeader ? "-header" : ""; 2703 2704 StringRef Lang; 2705 switch (Opts.DashX.getLanguage()) { 2706 case Language::C: 2707 Lang = "c"; 2708 break; 2709 case Language::OpenCL: 2710 Lang = "cl"; 2711 break; 2712 case Language::OpenCLCXX: 2713 Lang = "clcpp"; 2714 break; 2715 case Language::CUDA: 2716 Lang = "cuda"; 2717 break; 2718 case Language::HIP: 2719 Lang = "hip"; 2720 break; 2721 case Language::CXX: 2722 Lang = "c++"; 2723 break; 2724 case Language::ObjC: 2725 Lang = "objective-c"; 2726 break; 2727 case Language::ObjCXX: 2728 Lang = "objective-c++"; 2729 break; 2730 case Language::RenderScript: 2731 Lang = "renderscript"; 2732 break; 2733 case Language::Asm: 2734 Lang = "assembler-with-cpp"; 2735 break; 2736 case Language::Unknown: 2737 assert(Opts.DashX.getFormat() == InputKind::Precompiled && 2738 "Generating -x argument for unknown language (not precompiled)."); 2739 Lang = "ast"; 2740 break; 2741 case Language::LLVM_IR: 2742 Lang = "ir"; 2743 break; 2744 case Language::HLSL: 2745 Lang = "hlsl"; 2746 break; 2747 } 2748 2749 GenerateArg(Consumer, OPT_x, 2750 Lang + HeaderUnit + Header + ModuleMap + Preprocessed); 2751 } 2752 2753 // OPT_INPUT has a unique class, generate it directly. 2754 for (const auto &Input : Opts.Inputs) 2755 Consumer(Input.getFile()); 2756 } 2757 2758 static bool ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args, 2759 DiagnosticsEngine &Diags, bool &IsHeaderFile) { 2760 unsigned NumErrorsBefore = Diags.getNumErrors(); 2761 2762 FrontendOptions &FrontendOpts = Opts; 2763 2764 #define FRONTEND_OPTION_WITH_MARSHALLING(...) \ 2765 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__) 2766 #include "clang/Driver/Options.inc" 2767 #undef FRONTEND_OPTION_WITH_MARSHALLING 2768 2769 Opts.ProgramAction = frontend::ParseSyntaxOnly; 2770 if (const Arg *A = Args.getLastArg(OPT_Action_Group)) { 2771 OptSpecifier Opt = OptSpecifier(A->getOption().getID()); 2772 std::optional<frontend::ActionKind> ProgramAction = getFrontendAction(Opt); 2773 assert(ProgramAction && "Option specifier not in Action_Group."); 2774 2775 if (ProgramAction == frontend::ASTDump && 2776 (Opt == OPT_ast_dump_all_EQ || Opt == OPT_ast_dump_EQ)) { 2777 unsigned Val = llvm::StringSwitch<unsigned>(A->getValue()) 2778 .CaseLower("default", ADOF_Default) 2779 .CaseLower("json", ADOF_JSON) 2780 .Default(std::numeric_limits<unsigned>::max()); 2781 2782 if (Val != std::numeric_limits<unsigned>::max()) 2783 Opts.ASTDumpFormat = static_cast<ASTDumpOutputFormat>(Val); 2784 else { 2785 Diags.Report(diag::err_drv_invalid_value) 2786 << A->getAsString(Args) << A->getValue(); 2787 Opts.ASTDumpFormat = ADOF_Default; 2788 } 2789 } 2790 2791 if (ProgramAction == frontend::FixIt && Opt == OPT_fixit_EQ) 2792 Opts.FixItSuffix = A->getValue(); 2793 2794 if (ProgramAction == frontend::GenerateInterfaceStubs) { 2795 StringRef ArgStr = 2796 Args.hasArg(OPT_interface_stub_version_EQ) 2797 ? Args.getLastArgValue(OPT_interface_stub_version_EQ) 2798 : "ifs-v1"; 2799 if (ArgStr == "experimental-yaml-elf-v1" || 2800 ArgStr == "experimental-ifs-v1" || ArgStr == "experimental-ifs-v2" || 2801 ArgStr == "experimental-tapi-elf-v1") { 2802 std::string ErrorMessage = 2803 "Invalid interface stub format: " + ArgStr.str() + 2804 " is deprecated."; 2805 Diags.Report(diag::err_drv_invalid_value) 2806 << "Must specify a valid interface stub format type, ie: " 2807 "-interface-stub-version=ifs-v1" 2808 << ErrorMessage; 2809 ProgramAction = frontend::ParseSyntaxOnly; 2810 } else if (!ArgStr.startswith("ifs-")) { 2811 std::string ErrorMessage = 2812 "Invalid interface stub format: " + ArgStr.str() + "."; 2813 Diags.Report(diag::err_drv_invalid_value) 2814 << "Must specify a valid interface stub format type, ie: " 2815 "-interface-stub-version=ifs-v1" 2816 << ErrorMessage; 2817 ProgramAction = frontend::ParseSyntaxOnly; 2818 } 2819 } 2820 2821 Opts.ProgramAction = *ProgramAction; 2822 } 2823 2824 if (const Arg* A = Args.getLastArg(OPT_plugin)) { 2825 Opts.Plugins.emplace_back(A->getValue(0)); 2826 Opts.ProgramAction = frontend::PluginAction; 2827 Opts.ActionName = A->getValue(); 2828 } 2829 for (const auto *AA : Args.filtered(OPT_plugin_arg)) 2830 Opts.PluginArgs[AA->getValue(0)].emplace_back(AA->getValue(1)); 2831 2832 for (const std::string &Arg : 2833 Args.getAllArgValues(OPT_ftest_module_file_extension_EQ)) { 2834 std::string BlockName; 2835 unsigned MajorVersion; 2836 unsigned MinorVersion; 2837 bool Hashed; 2838 std::string UserInfo; 2839 if (parseTestModuleFileExtensionArg(Arg, BlockName, MajorVersion, 2840 MinorVersion, Hashed, UserInfo)) { 2841 Diags.Report(diag::err_test_module_file_extension_format) << Arg; 2842 2843 continue; 2844 } 2845 2846 // Add the testing module file extension. 2847 Opts.ModuleFileExtensions.push_back( 2848 std::make_shared<TestModuleFileExtension>( 2849 BlockName, MajorVersion, MinorVersion, Hashed, UserInfo)); 2850 } 2851 2852 if (const Arg *A = Args.getLastArg(OPT_code_completion_at)) { 2853 Opts.CodeCompletionAt = 2854 ParsedSourceLocation::FromString(A->getValue()); 2855 if (Opts.CodeCompletionAt.FileName.empty()) 2856 Diags.Report(diag::err_drv_invalid_value) 2857 << A->getAsString(Args) << A->getValue(); 2858 } 2859 2860 Opts.Plugins = Args.getAllArgValues(OPT_load); 2861 Opts.ASTDumpDecls = Args.hasArg(OPT_ast_dump, OPT_ast_dump_EQ); 2862 Opts.ASTDumpAll = Args.hasArg(OPT_ast_dump_all, OPT_ast_dump_all_EQ); 2863 // Only the -fmodule-file=<file> form. 2864 for (const auto *A : Args.filtered(OPT_fmodule_file)) { 2865 StringRef Val = A->getValue(); 2866 if (!Val.contains('=')) 2867 Opts.ModuleFiles.push_back(std::string(Val)); 2868 } 2869 2870 if (Opts.ProgramAction != frontend::GenerateModule && Opts.IsSystemModule) 2871 Diags.Report(diag::err_drv_argument_only_allowed_with) << "-fsystem-module" 2872 << "-emit-module"; 2873 2874 if (Args.hasArg(OPT_aux_target_cpu)) 2875 Opts.AuxTargetCPU = std::string(Args.getLastArgValue(OPT_aux_target_cpu)); 2876 if (Args.hasArg(OPT_aux_target_feature)) 2877 Opts.AuxTargetFeatures = Args.getAllArgValues(OPT_aux_target_feature); 2878 2879 if (Opts.ARCMTAction != FrontendOptions::ARCMT_None && 2880 Opts.ObjCMTAction != FrontendOptions::ObjCMT_None) { 2881 Diags.Report(diag::err_drv_argument_not_allowed_with) 2882 << "ARC migration" << "ObjC migration"; 2883 } 2884 2885 InputKind DashX(Language::Unknown); 2886 if (const Arg *A = Args.getLastArg(OPT_x)) { 2887 StringRef XValue = A->getValue(); 2888 2889 // Parse suffixes: 2890 // '<lang>(-[{header-unit,user,system}-]header|[-module-map][-cpp-output])'. 2891 // FIXME: Supporting '<lang>-header-cpp-output' would be useful. 2892 bool Preprocessed = XValue.consume_back("-cpp-output"); 2893 bool ModuleMap = XValue.consume_back("-module-map"); 2894 // Detect and consume the header indicator. 2895 bool IsHeader = 2896 XValue != "precompiled-header" && XValue.consume_back("-header"); 2897 2898 // If we have c++-{user,system}-header, that indicates a header unit input 2899 // likewise, if the user put -fmodule-header together with a header with an 2900 // absolute path (header-unit-header). 2901 InputKind::HeaderUnitKind HUK = InputKind::HeaderUnit_None; 2902 if (IsHeader || Preprocessed) { 2903 if (XValue.consume_back("-header-unit")) 2904 HUK = InputKind::HeaderUnit_Abs; 2905 else if (XValue.consume_back("-system")) 2906 HUK = InputKind::HeaderUnit_System; 2907 else if (XValue.consume_back("-user")) 2908 HUK = InputKind::HeaderUnit_User; 2909 } 2910 2911 // The value set by this processing is an un-preprocessed source which is 2912 // not intended to be a module map or header unit. 2913 IsHeaderFile = IsHeader && !Preprocessed && !ModuleMap && 2914 HUK == InputKind::HeaderUnit_None; 2915 2916 // Principal languages. 2917 DashX = llvm::StringSwitch<InputKind>(XValue) 2918 .Case("c", Language::C) 2919 .Case("cl", Language::OpenCL) 2920 .Case("clcpp", Language::OpenCLCXX) 2921 .Case("cuda", Language::CUDA) 2922 .Case("hip", Language::HIP) 2923 .Case("c++", Language::CXX) 2924 .Case("objective-c", Language::ObjC) 2925 .Case("objective-c++", Language::ObjCXX) 2926 .Case("renderscript", Language::RenderScript) 2927 .Case("hlsl", Language::HLSL) 2928 .Default(Language::Unknown); 2929 2930 // "objc[++]-cpp-output" is an acceptable synonym for 2931 // "objective-c[++]-cpp-output". 2932 if (DashX.isUnknown() && Preprocessed && !IsHeaderFile && !ModuleMap && 2933 HUK == InputKind::HeaderUnit_None) 2934 DashX = llvm::StringSwitch<InputKind>(XValue) 2935 .Case("objc", Language::ObjC) 2936 .Case("objc++", Language::ObjCXX) 2937 .Default(Language::Unknown); 2938 2939 // Some special cases cannot be combined with suffixes. 2940 if (DashX.isUnknown() && !Preprocessed && !IsHeaderFile && !ModuleMap && 2941 HUK == InputKind::HeaderUnit_None) 2942 DashX = llvm::StringSwitch<InputKind>(XValue) 2943 .Case("cpp-output", InputKind(Language::C).getPreprocessed()) 2944 .Case("assembler-with-cpp", Language::Asm) 2945 .Cases("ast", "pcm", "precompiled-header", 2946 InputKind(Language::Unknown, InputKind::Precompiled)) 2947 .Case("ir", Language::LLVM_IR) 2948 .Default(Language::Unknown); 2949 2950 if (DashX.isUnknown()) 2951 Diags.Report(diag::err_drv_invalid_value) 2952 << A->getAsString(Args) << A->getValue(); 2953 2954 if (Preprocessed) 2955 DashX = DashX.getPreprocessed(); 2956 // A regular header is considered mutually exclusive with a header unit. 2957 if (HUK != InputKind::HeaderUnit_None) { 2958 DashX = DashX.withHeaderUnit(HUK); 2959 IsHeaderFile = true; 2960 } else if (IsHeaderFile) 2961 DashX = DashX.getHeader(); 2962 if (ModuleMap) 2963 DashX = DashX.withFormat(InputKind::ModuleMap); 2964 } 2965 2966 // '-' is the default input if none is given. 2967 std::vector<std::string> Inputs = Args.getAllArgValues(OPT_INPUT); 2968 Opts.Inputs.clear(); 2969 if (Inputs.empty()) 2970 Inputs.push_back("-"); 2971 2972 if (DashX.getHeaderUnitKind() != InputKind::HeaderUnit_None && 2973 Inputs.size() > 1) 2974 Diags.Report(diag::err_drv_header_unit_extra_inputs) << Inputs[1]; 2975 2976 for (unsigned i = 0, e = Inputs.size(); i != e; ++i) { 2977 InputKind IK = DashX; 2978 if (IK.isUnknown()) { 2979 IK = FrontendOptions::getInputKindForExtension( 2980 StringRef(Inputs[i]).rsplit('.').second); 2981 // FIXME: Warn on this? 2982 if (IK.isUnknown()) 2983 IK = Language::C; 2984 // FIXME: Remove this hack. 2985 if (i == 0) 2986 DashX = IK; 2987 } 2988 2989 bool IsSystem = false; 2990 2991 // The -emit-module action implicitly takes a module map. 2992 if (Opts.ProgramAction == frontend::GenerateModule && 2993 IK.getFormat() == InputKind::Source) { 2994 IK = IK.withFormat(InputKind::ModuleMap); 2995 IsSystem = Opts.IsSystemModule; 2996 } 2997 2998 Opts.Inputs.emplace_back(std::move(Inputs[i]), IK, IsSystem); 2999 } 3000 3001 Opts.DashX = DashX; 3002 3003 return Diags.getNumErrors() == NumErrorsBefore; 3004 } 3005 3006 std::string CompilerInvocation::GetResourcesPath(const char *Argv0, 3007 void *MainAddr) { 3008 std::string ClangExecutable = 3009 llvm::sys::fs::getMainExecutable(Argv0, MainAddr); 3010 return Driver::GetResourcesPath(ClangExecutable, CLANG_RESOURCE_DIR); 3011 } 3012 3013 static void GenerateHeaderSearchArgs(const HeaderSearchOptions &Opts, 3014 ArgumentConsumer Consumer) { 3015 const HeaderSearchOptions *HeaderSearchOpts = &Opts; 3016 #define HEADER_SEARCH_OPTION_WITH_MARSHALLING(...) \ 3017 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__) 3018 #include "clang/Driver/Options.inc" 3019 #undef HEADER_SEARCH_OPTION_WITH_MARSHALLING 3020 3021 if (Opts.UseLibcxx) 3022 GenerateArg(Consumer, OPT_stdlib_EQ, "libc++"); 3023 3024 if (!Opts.ModuleCachePath.empty()) 3025 GenerateArg(Consumer, OPT_fmodules_cache_path, Opts.ModuleCachePath); 3026 3027 for (const auto &File : Opts.PrebuiltModuleFiles) 3028 GenerateArg(Consumer, OPT_fmodule_file, File.first + "=" + File.second); 3029 3030 for (const auto &Path : Opts.PrebuiltModulePaths) 3031 GenerateArg(Consumer, OPT_fprebuilt_module_path, Path); 3032 3033 for (const auto &Macro : Opts.ModulesIgnoreMacros) 3034 GenerateArg(Consumer, OPT_fmodules_ignore_macro, Macro.val()); 3035 3036 auto Matches = [](const HeaderSearchOptions::Entry &Entry, 3037 llvm::ArrayRef<frontend::IncludeDirGroup> Groups, 3038 std::optional<bool> IsFramework, 3039 std::optional<bool> IgnoreSysRoot) { 3040 return llvm::is_contained(Groups, Entry.Group) && 3041 (!IsFramework || (Entry.IsFramework == *IsFramework)) && 3042 (!IgnoreSysRoot || (Entry.IgnoreSysRoot == *IgnoreSysRoot)); 3043 }; 3044 3045 auto It = Opts.UserEntries.begin(); 3046 auto End = Opts.UserEntries.end(); 3047 3048 // Add -I..., -F..., and -index-header-map options in order. 3049 for (; It < End && Matches(*It, {frontend::IndexHeaderMap, frontend::Angled}, 3050 std::nullopt, true); 3051 ++It) { 3052 OptSpecifier Opt = [It, Matches]() { 3053 if (Matches(*It, frontend::IndexHeaderMap, true, true)) 3054 return OPT_F; 3055 if (Matches(*It, frontend::IndexHeaderMap, false, true)) 3056 return OPT_I; 3057 if (Matches(*It, frontend::Angled, true, true)) 3058 return OPT_F; 3059 if (Matches(*It, frontend::Angled, false, true)) 3060 return OPT_I; 3061 llvm_unreachable("Unexpected HeaderSearchOptions::Entry."); 3062 }(); 3063 3064 if (It->Group == frontend::IndexHeaderMap) 3065 GenerateArg(Consumer, OPT_index_header_map); 3066 GenerateArg(Consumer, Opt, It->Path); 3067 }; 3068 3069 // Note: some paths that came from "[-iprefix=xx] -iwithprefixbefore=yy" may 3070 // have already been generated as "-I[xx]yy". If that's the case, their 3071 // position on command line was such that this has no semantic impact on 3072 // include paths. 3073 for (; It < End && 3074 Matches(*It, {frontend::After, frontend::Angled}, false, true); 3075 ++It) { 3076 OptSpecifier Opt = 3077 It->Group == frontend::After ? OPT_iwithprefix : OPT_iwithprefixbefore; 3078 GenerateArg(Consumer, Opt, It->Path); 3079 } 3080 3081 // Note: Some paths that came from "-idirafter=xxyy" may have already been 3082 // generated as "-iwithprefix=xxyy". If that's the case, their position on 3083 // command line was such that this has no semantic impact on include paths. 3084 for (; It < End && Matches(*It, {frontend::After}, false, true); ++It) 3085 GenerateArg(Consumer, OPT_idirafter, It->Path); 3086 for (; It < End && Matches(*It, {frontend::Quoted}, false, true); ++It) 3087 GenerateArg(Consumer, OPT_iquote, It->Path); 3088 for (; It < End && Matches(*It, {frontend::System}, false, std::nullopt); 3089 ++It) 3090 GenerateArg(Consumer, It->IgnoreSysRoot ? OPT_isystem : OPT_iwithsysroot, 3091 It->Path); 3092 for (; It < End && Matches(*It, {frontend::System}, true, true); ++It) 3093 GenerateArg(Consumer, OPT_iframework, It->Path); 3094 for (; It < End && Matches(*It, {frontend::System}, true, false); ++It) 3095 GenerateArg(Consumer, OPT_iframeworkwithsysroot, It->Path); 3096 3097 // Add the paths for the various language specific isystem flags. 3098 for (; It < End && Matches(*It, {frontend::CSystem}, false, true); ++It) 3099 GenerateArg(Consumer, OPT_c_isystem, It->Path); 3100 for (; It < End && Matches(*It, {frontend::CXXSystem}, false, true); ++It) 3101 GenerateArg(Consumer, OPT_cxx_isystem, It->Path); 3102 for (; It < End && Matches(*It, {frontend::ObjCSystem}, false, true); ++It) 3103 GenerateArg(Consumer, OPT_objc_isystem, It->Path); 3104 for (; It < End && Matches(*It, {frontend::ObjCXXSystem}, false, true); ++It) 3105 GenerateArg(Consumer, OPT_objcxx_isystem, It->Path); 3106 3107 // Add the internal paths from a driver that detects standard include paths. 3108 // Note: Some paths that came from "-internal-isystem" arguments may have 3109 // already been generated as "-isystem". If that's the case, their position on 3110 // command line was such that this has no semantic impact on include paths. 3111 for (; It < End && 3112 Matches(*It, {frontend::System, frontend::ExternCSystem}, false, true); 3113 ++It) { 3114 OptSpecifier Opt = It->Group == frontend::System 3115 ? OPT_internal_isystem 3116 : OPT_internal_externc_isystem; 3117 GenerateArg(Consumer, Opt, It->Path); 3118 } 3119 3120 assert(It == End && "Unhandled HeaderSearchOption::Entry."); 3121 3122 // Add the path prefixes which are implicitly treated as being system headers. 3123 for (const auto &P : Opts.SystemHeaderPrefixes) { 3124 OptSpecifier Opt = P.IsSystemHeader ? OPT_system_header_prefix 3125 : OPT_no_system_header_prefix; 3126 GenerateArg(Consumer, Opt, P.Prefix); 3127 } 3128 3129 for (const std::string &F : Opts.VFSOverlayFiles) 3130 GenerateArg(Consumer, OPT_ivfsoverlay, F); 3131 } 3132 3133 static bool ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args, 3134 DiagnosticsEngine &Diags, 3135 const std::string &WorkingDir) { 3136 unsigned NumErrorsBefore = Diags.getNumErrors(); 3137 3138 HeaderSearchOptions *HeaderSearchOpts = &Opts; 3139 3140 #define HEADER_SEARCH_OPTION_WITH_MARSHALLING(...) \ 3141 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__) 3142 #include "clang/Driver/Options.inc" 3143 #undef HEADER_SEARCH_OPTION_WITH_MARSHALLING 3144 3145 if (const Arg *A = Args.getLastArg(OPT_stdlib_EQ)) 3146 Opts.UseLibcxx = (strcmp(A->getValue(), "libc++") == 0); 3147 3148 // Canonicalize -fmodules-cache-path before storing it. 3149 SmallString<128> P(Args.getLastArgValue(OPT_fmodules_cache_path)); 3150 if (!(P.empty() || llvm::sys::path::is_absolute(P))) { 3151 if (WorkingDir.empty()) 3152 llvm::sys::fs::make_absolute(P); 3153 else 3154 llvm::sys::fs::make_absolute(WorkingDir, P); 3155 } 3156 llvm::sys::path::remove_dots(P); 3157 Opts.ModuleCachePath = std::string(P.str()); 3158 3159 // Only the -fmodule-file=<name>=<file> form. 3160 for (const auto *A : Args.filtered(OPT_fmodule_file)) { 3161 StringRef Val = A->getValue(); 3162 if (Val.contains('=')) { 3163 auto Split = Val.split('='); 3164 Opts.PrebuiltModuleFiles.insert( 3165 {std::string(Split.first), std::string(Split.second)}); 3166 } 3167 } 3168 for (const auto *A : Args.filtered(OPT_fprebuilt_module_path)) 3169 Opts.AddPrebuiltModulePath(A->getValue()); 3170 3171 for (const auto *A : Args.filtered(OPT_fmodules_ignore_macro)) { 3172 StringRef MacroDef = A->getValue(); 3173 Opts.ModulesIgnoreMacros.insert( 3174 llvm::CachedHashString(MacroDef.split('=').first)); 3175 } 3176 3177 // Add -I..., -F..., and -index-header-map options in order. 3178 bool IsIndexHeaderMap = false; 3179 bool IsSysrootSpecified = 3180 Args.hasArg(OPT__sysroot_EQ) || Args.hasArg(OPT_isysroot); 3181 for (const auto *A : Args.filtered(OPT_I, OPT_F, OPT_index_header_map)) { 3182 if (A->getOption().matches(OPT_index_header_map)) { 3183 // -index-header-map applies to the next -I or -F. 3184 IsIndexHeaderMap = true; 3185 continue; 3186 } 3187 3188 frontend::IncludeDirGroup Group = 3189 IsIndexHeaderMap ? frontend::IndexHeaderMap : frontend::Angled; 3190 3191 bool IsFramework = A->getOption().matches(OPT_F); 3192 std::string Path = A->getValue(); 3193 3194 if (IsSysrootSpecified && !IsFramework && A->getValue()[0] == '=') { 3195 SmallString<32> Buffer; 3196 llvm::sys::path::append(Buffer, Opts.Sysroot, 3197 llvm::StringRef(A->getValue()).substr(1)); 3198 Path = std::string(Buffer.str()); 3199 } 3200 3201 Opts.AddPath(Path, Group, IsFramework, 3202 /*IgnoreSysroot*/ true); 3203 IsIndexHeaderMap = false; 3204 } 3205 3206 // Add -iprefix/-iwithprefix/-iwithprefixbefore options. 3207 StringRef Prefix = ""; // FIXME: This isn't the correct default prefix. 3208 for (const auto *A : 3209 Args.filtered(OPT_iprefix, OPT_iwithprefix, OPT_iwithprefixbefore)) { 3210 if (A->getOption().matches(OPT_iprefix)) 3211 Prefix = A->getValue(); 3212 else if (A->getOption().matches(OPT_iwithprefix)) 3213 Opts.AddPath(Prefix.str() + A->getValue(), frontend::After, false, true); 3214 else 3215 Opts.AddPath(Prefix.str() + A->getValue(), frontend::Angled, false, true); 3216 } 3217 3218 for (const auto *A : Args.filtered(OPT_idirafter)) 3219 Opts.AddPath(A->getValue(), frontend::After, false, true); 3220 for (const auto *A : Args.filtered(OPT_iquote)) 3221 Opts.AddPath(A->getValue(), frontend::Quoted, false, true); 3222 for (const auto *A : Args.filtered(OPT_isystem, OPT_iwithsysroot)) 3223 Opts.AddPath(A->getValue(), frontend::System, false, 3224 !A->getOption().matches(OPT_iwithsysroot)); 3225 for (const auto *A : Args.filtered(OPT_iframework)) 3226 Opts.AddPath(A->getValue(), frontend::System, true, true); 3227 for (const auto *A : Args.filtered(OPT_iframeworkwithsysroot)) 3228 Opts.AddPath(A->getValue(), frontend::System, /*IsFramework=*/true, 3229 /*IgnoreSysRoot=*/false); 3230 3231 // Add the paths for the various language specific isystem flags. 3232 for (const auto *A : Args.filtered(OPT_c_isystem)) 3233 Opts.AddPath(A->getValue(), frontend::CSystem, false, true); 3234 for (const auto *A : Args.filtered(OPT_cxx_isystem)) 3235 Opts.AddPath(A->getValue(), frontend::CXXSystem, false, true); 3236 for (const auto *A : Args.filtered(OPT_objc_isystem)) 3237 Opts.AddPath(A->getValue(), frontend::ObjCSystem, false,true); 3238 for (const auto *A : Args.filtered(OPT_objcxx_isystem)) 3239 Opts.AddPath(A->getValue(), frontend::ObjCXXSystem, false, true); 3240 3241 // Add the internal paths from a driver that detects standard include paths. 3242 for (const auto *A : 3243 Args.filtered(OPT_internal_isystem, OPT_internal_externc_isystem)) { 3244 frontend::IncludeDirGroup Group = frontend::System; 3245 if (A->getOption().matches(OPT_internal_externc_isystem)) 3246 Group = frontend::ExternCSystem; 3247 Opts.AddPath(A->getValue(), Group, false, true); 3248 } 3249 3250 // Add the path prefixes which are implicitly treated as being system headers. 3251 for (const auto *A : 3252 Args.filtered(OPT_system_header_prefix, OPT_no_system_header_prefix)) 3253 Opts.AddSystemHeaderPrefix( 3254 A->getValue(), A->getOption().matches(OPT_system_header_prefix)); 3255 3256 for (const auto *A : Args.filtered(OPT_ivfsoverlay, OPT_vfsoverlay)) 3257 Opts.AddVFSOverlayFile(A->getValue()); 3258 3259 return Diags.getNumErrors() == NumErrorsBefore; 3260 } 3261 3262 /// Check if input file kind and language standard are compatible. 3263 static bool IsInputCompatibleWithStandard(InputKind IK, 3264 const LangStandard &S) { 3265 switch (IK.getLanguage()) { 3266 case Language::Unknown: 3267 case Language::LLVM_IR: 3268 llvm_unreachable("should not parse language flags for this input"); 3269 3270 case Language::C: 3271 case Language::ObjC: 3272 case Language::RenderScript: 3273 return S.getLanguage() == Language::C; 3274 3275 case Language::OpenCL: 3276 return S.getLanguage() == Language::OpenCL || 3277 S.getLanguage() == Language::OpenCLCXX; 3278 3279 case Language::OpenCLCXX: 3280 return S.getLanguage() == Language::OpenCLCXX; 3281 3282 case Language::CXX: 3283 case Language::ObjCXX: 3284 return S.getLanguage() == Language::CXX; 3285 3286 case Language::CUDA: 3287 // FIXME: What -std= values should be permitted for CUDA compilations? 3288 return S.getLanguage() == Language::CUDA || 3289 S.getLanguage() == Language::CXX; 3290 3291 case Language::HIP: 3292 return S.getLanguage() == Language::CXX || S.getLanguage() == Language::HIP; 3293 3294 case Language::Asm: 3295 // Accept (and ignore) all -std= values. 3296 // FIXME: The -std= value is not ignored; it affects the tokenization 3297 // and preprocessing rules if we're preprocessing this asm input. 3298 return true; 3299 3300 case Language::HLSL: 3301 return S.getLanguage() == Language::HLSL; 3302 } 3303 3304 llvm_unreachable("unexpected input language"); 3305 } 3306 3307 /// Get language name for given input kind. 3308 static StringRef GetInputKindName(InputKind IK) { 3309 switch (IK.getLanguage()) { 3310 case Language::C: 3311 return "C"; 3312 case Language::ObjC: 3313 return "Objective-C"; 3314 case Language::CXX: 3315 return "C++"; 3316 case Language::ObjCXX: 3317 return "Objective-C++"; 3318 case Language::OpenCL: 3319 return "OpenCL"; 3320 case Language::OpenCLCXX: 3321 return "C++ for OpenCL"; 3322 case Language::CUDA: 3323 return "CUDA"; 3324 case Language::RenderScript: 3325 return "RenderScript"; 3326 case Language::HIP: 3327 return "HIP"; 3328 3329 case Language::Asm: 3330 return "Asm"; 3331 case Language::LLVM_IR: 3332 return "LLVM IR"; 3333 3334 case Language::HLSL: 3335 return "HLSL"; 3336 3337 case Language::Unknown: 3338 break; 3339 } 3340 llvm_unreachable("unknown input language"); 3341 } 3342 3343 void CompilerInvocationBase::GenerateLangArgs(const LangOptions &Opts, 3344 ArgumentConsumer Consumer, 3345 const llvm::Triple &T, 3346 InputKind IK) { 3347 if (IK.getFormat() == InputKind::Precompiled || 3348 IK.getLanguage() == Language::LLVM_IR) { 3349 if (Opts.ObjCAutoRefCount) 3350 GenerateArg(Consumer, OPT_fobjc_arc); 3351 if (Opts.PICLevel != 0) 3352 GenerateArg(Consumer, OPT_pic_level, Twine(Opts.PICLevel)); 3353 if (Opts.PIE) 3354 GenerateArg(Consumer, OPT_pic_is_pie); 3355 for (StringRef Sanitizer : serializeSanitizerKinds(Opts.Sanitize)) 3356 GenerateArg(Consumer, OPT_fsanitize_EQ, Sanitizer); 3357 3358 return; 3359 } 3360 3361 OptSpecifier StdOpt; 3362 switch (Opts.LangStd) { 3363 case LangStandard::lang_opencl10: 3364 case LangStandard::lang_opencl11: 3365 case LangStandard::lang_opencl12: 3366 case LangStandard::lang_opencl20: 3367 case LangStandard::lang_opencl30: 3368 case LangStandard::lang_openclcpp10: 3369 case LangStandard::lang_openclcpp2021: 3370 StdOpt = OPT_cl_std_EQ; 3371 break; 3372 default: 3373 StdOpt = OPT_std_EQ; 3374 break; 3375 } 3376 3377 auto LangStandard = LangStandard::getLangStandardForKind(Opts.LangStd); 3378 GenerateArg(Consumer, StdOpt, LangStandard.getName()); 3379 3380 if (Opts.IncludeDefaultHeader) 3381 GenerateArg(Consumer, OPT_finclude_default_header); 3382 if (Opts.DeclareOpenCLBuiltins) 3383 GenerateArg(Consumer, OPT_fdeclare_opencl_builtins); 3384 3385 const LangOptions *LangOpts = &Opts; 3386 3387 #define LANG_OPTION_WITH_MARSHALLING(...) \ 3388 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__) 3389 #include "clang/Driver/Options.inc" 3390 #undef LANG_OPTION_WITH_MARSHALLING 3391 3392 // The '-fcf-protection=' option is generated by CodeGenOpts generator. 3393 3394 if (Opts.ObjC) { 3395 GenerateArg(Consumer, OPT_fobjc_runtime_EQ, Opts.ObjCRuntime.getAsString()); 3396 3397 if (Opts.GC == LangOptions::GCOnly) 3398 GenerateArg(Consumer, OPT_fobjc_gc_only); 3399 else if (Opts.GC == LangOptions::HybridGC) 3400 GenerateArg(Consumer, OPT_fobjc_gc); 3401 else if (Opts.ObjCAutoRefCount == 1) 3402 GenerateArg(Consumer, OPT_fobjc_arc); 3403 3404 if (Opts.ObjCWeakRuntime) 3405 GenerateArg(Consumer, OPT_fobjc_runtime_has_weak); 3406 3407 if (Opts.ObjCWeak) 3408 GenerateArg(Consumer, OPT_fobjc_weak); 3409 3410 if (Opts.ObjCSubscriptingLegacyRuntime) 3411 GenerateArg(Consumer, OPT_fobjc_subscripting_legacy_runtime); 3412 } 3413 3414 if (Opts.GNUCVersion != 0) { 3415 unsigned Major = Opts.GNUCVersion / 100 / 100; 3416 unsigned Minor = (Opts.GNUCVersion / 100) % 100; 3417 unsigned Patch = Opts.GNUCVersion % 100; 3418 GenerateArg(Consumer, OPT_fgnuc_version_EQ, 3419 Twine(Major) + "." + Twine(Minor) + "." + Twine(Patch)); 3420 } 3421 3422 if (Opts.IgnoreXCOFFVisibility) 3423 GenerateArg(Consumer, OPT_mignore_xcoff_visibility); 3424 3425 if (Opts.SignedOverflowBehavior == LangOptions::SOB_Trapping) { 3426 GenerateArg(Consumer, OPT_ftrapv); 3427 GenerateArg(Consumer, OPT_ftrapv_handler, Opts.OverflowHandler); 3428 } else if (Opts.SignedOverflowBehavior == LangOptions::SOB_Defined) { 3429 GenerateArg(Consumer, OPT_fwrapv); 3430 } 3431 3432 if (Opts.MSCompatibilityVersion != 0) { 3433 unsigned Major = Opts.MSCompatibilityVersion / 10000000; 3434 unsigned Minor = (Opts.MSCompatibilityVersion / 100000) % 100; 3435 unsigned Subminor = Opts.MSCompatibilityVersion % 100000; 3436 GenerateArg(Consumer, OPT_fms_compatibility_version, 3437 Twine(Major) + "." + Twine(Minor) + "." + Twine(Subminor)); 3438 } 3439 3440 if ((!Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus17) || T.isOSzOS()) { 3441 if (!Opts.Trigraphs) 3442 GenerateArg(Consumer, OPT_fno_trigraphs); 3443 } else { 3444 if (Opts.Trigraphs) 3445 GenerateArg(Consumer, OPT_ftrigraphs); 3446 } 3447 3448 if (Opts.Blocks && !(Opts.OpenCL && Opts.OpenCLVersion == 200)) 3449 GenerateArg(Consumer, OPT_fblocks); 3450 3451 if (Opts.ConvergentFunctions && 3452 !(Opts.OpenCL || (Opts.CUDA && Opts.CUDAIsDevice) || Opts.SYCLIsDevice)) 3453 GenerateArg(Consumer, OPT_fconvergent_functions); 3454 3455 if (Opts.NoBuiltin && !Opts.Freestanding) 3456 GenerateArg(Consumer, OPT_fno_builtin); 3457 3458 if (!Opts.NoBuiltin) 3459 for (const auto &Func : Opts.NoBuiltinFuncs) 3460 GenerateArg(Consumer, OPT_fno_builtin_, Func); 3461 3462 if (Opts.LongDoubleSize == 128) 3463 GenerateArg(Consumer, OPT_mlong_double_128); 3464 else if (Opts.LongDoubleSize == 64) 3465 GenerateArg(Consumer, OPT_mlong_double_64); 3466 else if (Opts.LongDoubleSize == 80) 3467 GenerateArg(Consumer, OPT_mlong_double_80); 3468 3469 // Not generating '-mrtd', it's just an alias for '-fdefault-calling-conv='. 3470 3471 // OpenMP was requested via '-fopenmp', not implied by '-fopenmp-simd' or 3472 // '-fopenmp-targets='. 3473 if (Opts.OpenMP && !Opts.OpenMPSimd) { 3474 GenerateArg(Consumer, OPT_fopenmp); 3475 3476 if (Opts.OpenMP != 51) 3477 GenerateArg(Consumer, OPT_fopenmp_version_EQ, Twine(Opts.OpenMP)); 3478 3479 if (!Opts.OpenMPUseTLS) 3480 GenerateArg(Consumer, OPT_fnoopenmp_use_tls); 3481 3482 if (Opts.OpenMPIsTargetDevice) 3483 GenerateArg(Consumer, OPT_fopenmp_is_target_device); 3484 3485 if (Opts.OpenMPIRBuilder) 3486 GenerateArg(Consumer, OPT_fopenmp_enable_irbuilder); 3487 } 3488 3489 if (Opts.OpenMPSimd) { 3490 GenerateArg(Consumer, OPT_fopenmp_simd); 3491 3492 if (Opts.OpenMP != 51) 3493 GenerateArg(Consumer, OPT_fopenmp_version_EQ, Twine(Opts.OpenMP)); 3494 } 3495 3496 if (Opts.OpenMPThreadSubscription) 3497 GenerateArg(Consumer, OPT_fopenmp_assume_threads_oversubscription); 3498 3499 if (Opts.OpenMPTeamSubscription) 3500 GenerateArg(Consumer, OPT_fopenmp_assume_teams_oversubscription); 3501 3502 if (Opts.OpenMPTargetDebug != 0) 3503 GenerateArg(Consumer, OPT_fopenmp_target_debug_EQ, 3504 Twine(Opts.OpenMPTargetDebug)); 3505 3506 if (Opts.OpenMPCUDANumSMs != 0) 3507 GenerateArg(Consumer, OPT_fopenmp_cuda_number_of_sm_EQ, 3508 Twine(Opts.OpenMPCUDANumSMs)); 3509 3510 if (Opts.OpenMPCUDABlocksPerSM != 0) 3511 GenerateArg(Consumer, OPT_fopenmp_cuda_blocks_per_sm_EQ, 3512 Twine(Opts.OpenMPCUDABlocksPerSM)); 3513 3514 if (Opts.OpenMPCUDAReductionBufNum != 1024) 3515 GenerateArg(Consumer, OPT_fopenmp_cuda_teams_reduction_recs_num_EQ, 3516 Twine(Opts.OpenMPCUDAReductionBufNum)); 3517 3518 if (!Opts.OMPTargetTriples.empty()) { 3519 std::string Targets; 3520 llvm::raw_string_ostream OS(Targets); 3521 llvm::interleave( 3522 Opts.OMPTargetTriples, OS, 3523 [&OS](const llvm::Triple &T) { OS << T.str(); }, ","); 3524 GenerateArg(Consumer, OPT_fopenmp_targets_EQ, OS.str()); 3525 } 3526 3527 if (!Opts.OMPHostIRFile.empty()) 3528 GenerateArg(Consumer, OPT_fopenmp_host_ir_file_path, Opts.OMPHostIRFile); 3529 3530 if (Opts.OpenMPCUDAMode) 3531 GenerateArg(Consumer, OPT_fopenmp_cuda_mode); 3532 3533 // The arguments used to set Optimize, OptimizeSize and NoInlineDefine are 3534 // generated from CodeGenOptions. 3535 3536 if (Opts.DefaultFPContractMode == LangOptions::FPM_Fast) 3537 GenerateArg(Consumer, OPT_ffp_contract, "fast"); 3538 else if (Opts.DefaultFPContractMode == LangOptions::FPM_On) 3539 GenerateArg(Consumer, OPT_ffp_contract, "on"); 3540 else if (Opts.DefaultFPContractMode == LangOptions::FPM_Off) 3541 GenerateArg(Consumer, OPT_ffp_contract, "off"); 3542 else if (Opts.DefaultFPContractMode == LangOptions::FPM_FastHonorPragmas) 3543 GenerateArg(Consumer, OPT_ffp_contract, "fast-honor-pragmas"); 3544 3545 for (StringRef Sanitizer : serializeSanitizerKinds(Opts.Sanitize)) 3546 GenerateArg(Consumer, OPT_fsanitize_EQ, Sanitizer); 3547 3548 // Conflating '-fsanitize-system-ignorelist' and '-fsanitize-ignorelist'. 3549 for (const std::string &F : Opts.NoSanitizeFiles) 3550 GenerateArg(Consumer, OPT_fsanitize_ignorelist_EQ, F); 3551 3552 switch (Opts.getClangABICompat()) { 3553 case LangOptions::ClangABI::Ver3_8: 3554 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "3.8"); 3555 break; 3556 case LangOptions::ClangABI::Ver4: 3557 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "4.0"); 3558 break; 3559 case LangOptions::ClangABI::Ver6: 3560 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "6.0"); 3561 break; 3562 case LangOptions::ClangABI::Ver7: 3563 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "7.0"); 3564 break; 3565 case LangOptions::ClangABI::Ver9: 3566 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "9.0"); 3567 break; 3568 case LangOptions::ClangABI::Ver11: 3569 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "11.0"); 3570 break; 3571 case LangOptions::ClangABI::Ver12: 3572 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "12.0"); 3573 break; 3574 case LangOptions::ClangABI::Ver14: 3575 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "14.0"); 3576 break; 3577 case LangOptions::ClangABI::Ver15: 3578 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "15.0"); 3579 break; 3580 case LangOptions::ClangABI::Ver17: 3581 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "17.0"); 3582 break; 3583 case LangOptions::ClangABI::Latest: 3584 break; 3585 } 3586 3587 if (Opts.getSignReturnAddressScope() == 3588 LangOptions::SignReturnAddressScopeKind::All) 3589 GenerateArg(Consumer, OPT_msign_return_address_EQ, "all"); 3590 else if (Opts.getSignReturnAddressScope() == 3591 LangOptions::SignReturnAddressScopeKind::NonLeaf) 3592 GenerateArg(Consumer, OPT_msign_return_address_EQ, "non-leaf"); 3593 3594 if (Opts.getSignReturnAddressKey() == 3595 LangOptions::SignReturnAddressKeyKind::BKey) 3596 GenerateArg(Consumer, OPT_msign_return_address_key_EQ, "b_key"); 3597 3598 if (Opts.CXXABI) 3599 GenerateArg(Consumer, OPT_fcxx_abi_EQ, 3600 TargetCXXABI::getSpelling(*Opts.CXXABI)); 3601 3602 if (Opts.RelativeCXXABIVTables) 3603 GenerateArg(Consumer, OPT_fexperimental_relative_cxx_abi_vtables); 3604 else 3605 GenerateArg(Consumer, OPT_fno_experimental_relative_cxx_abi_vtables); 3606 3607 if (Opts.UseTargetPathSeparator) 3608 GenerateArg(Consumer, OPT_ffile_reproducible); 3609 else 3610 GenerateArg(Consumer, OPT_fno_file_reproducible); 3611 3612 for (const auto &MP : Opts.MacroPrefixMap) 3613 GenerateArg(Consumer, OPT_fmacro_prefix_map_EQ, MP.first + "=" + MP.second); 3614 3615 if (!Opts.RandstructSeed.empty()) 3616 GenerateArg(Consumer, OPT_frandomize_layout_seed_EQ, Opts.RandstructSeed); 3617 } 3618 3619 bool CompilerInvocation::ParseLangArgs(LangOptions &Opts, ArgList &Args, 3620 InputKind IK, const llvm::Triple &T, 3621 std::vector<std::string> &Includes, 3622 DiagnosticsEngine &Diags) { 3623 unsigned NumErrorsBefore = Diags.getNumErrors(); 3624 3625 if (IK.getFormat() == InputKind::Precompiled || 3626 IK.getLanguage() == Language::LLVM_IR) { 3627 // ObjCAAutoRefCount and Sanitize LangOpts are used to setup the 3628 // PassManager in BackendUtil.cpp. They need to be initialized no matter 3629 // what the input type is. 3630 if (Args.hasArg(OPT_fobjc_arc)) 3631 Opts.ObjCAutoRefCount = 1; 3632 // PICLevel and PIELevel are needed during code generation and this should 3633 // be set regardless of the input type. 3634 Opts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags); 3635 Opts.PIE = Args.hasArg(OPT_pic_is_pie); 3636 parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ), 3637 Diags, Opts.Sanitize); 3638 3639 return Diags.getNumErrors() == NumErrorsBefore; 3640 } 3641 3642 // Other LangOpts are only initialized when the input is not AST or LLVM IR. 3643 // FIXME: Should we really be parsing this for an Language::Asm input? 3644 3645 // FIXME: Cleanup per-file based stuff. 3646 LangStandard::Kind LangStd = LangStandard::lang_unspecified; 3647 if (const Arg *A = Args.getLastArg(OPT_std_EQ)) { 3648 LangStd = LangStandard::getLangKind(A->getValue()); 3649 if (LangStd == LangStandard::lang_unspecified) { 3650 Diags.Report(diag::err_drv_invalid_value) 3651 << A->getAsString(Args) << A->getValue(); 3652 // Report supported standards with short description. 3653 for (unsigned KindValue = 0; 3654 KindValue != LangStandard::lang_unspecified; 3655 ++KindValue) { 3656 const LangStandard &Std = LangStandard::getLangStandardForKind( 3657 static_cast<LangStandard::Kind>(KindValue)); 3658 if (IsInputCompatibleWithStandard(IK, Std)) { 3659 auto Diag = Diags.Report(diag::note_drv_use_standard); 3660 Diag << Std.getName() << Std.getDescription(); 3661 unsigned NumAliases = 0; 3662 #define LANGSTANDARD(id, name, lang, desc, features) 3663 #define LANGSTANDARD_ALIAS(id, alias) \ 3664 if (KindValue == LangStandard::lang_##id) ++NumAliases; 3665 #define LANGSTANDARD_ALIAS_DEPR(id, alias) 3666 #include "clang/Basic/LangStandards.def" 3667 Diag << NumAliases; 3668 #define LANGSTANDARD(id, name, lang, desc, features) 3669 #define LANGSTANDARD_ALIAS(id, alias) \ 3670 if (KindValue == LangStandard::lang_##id) Diag << alias; 3671 #define LANGSTANDARD_ALIAS_DEPR(id, alias) 3672 #include "clang/Basic/LangStandards.def" 3673 } 3674 } 3675 } else { 3676 // Valid standard, check to make sure language and standard are 3677 // compatible. 3678 const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd); 3679 if (!IsInputCompatibleWithStandard(IK, Std)) { 3680 Diags.Report(diag::err_drv_argument_not_allowed_with) 3681 << A->getAsString(Args) << GetInputKindName(IK); 3682 } 3683 } 3684 } 3685 3686 // -cl-std only applies for OpenCL language standards. 3687 // Override the -std option in this case. 3688 if (const Arg *A = Args.getLastArg(OPT_cl_std_EQ)) { 3689 LangStandard::Kind OpenCLLangStd 3690 = llvm::StringSwitch<LangStandard::Kind>(A->getValue()) 3691 .Cases("cl", "CL", LangStandard::lang_opencl10) 3692 .Cases("cl1.0", "CL1.0", LangStandard::lang_opencl10) 3693 .Cases("cl1.1", "CL1.1", LangStandard::lang_opencl11) 3694 .Cases("cl1.2", "CL1.2", LangStandard::lang_opencl12) 3695 .Cases("cl2.0", "CL2.0", LangStandard::lang_opencl20) 3696 .Cases("cl3.0", "CL3.0", LangStandard::lang_opencl30) 3697 .Cases("clc++", "CLC++", LangStandard::lang_openclcpp10) 3698 .Cases("clc++1.0", "CLC++1.0", LangStandard::lang_openclcpp10) 3699 .Cases("clc++2021", "CLC++2021", LangStandard::lang_openclcpp2021) 3700 .Default(LangStandard::lang_unspecified); 3701 3702 if (OpenCLLangStd == LangStandard::lang_unspecified) { 3703 Diags.Report(diag::err_drv_invalid_value) 3704 << A->getAsString(Args) << A->getValue(); 3705 } 3706 else 3707 LangStd = OpenCLLangStd; 3708 } 3709 3710 // These need to be parsed now. They are used to set OpenCL defaults. 3711 Opts.IncludeDefaultHeader = Args.hasArg(OPT_finclude_default_header); 3712 Opts.DeclareOpenCLBuiltins = Args.hasArg(OPT_fdeclare_opencl_builtins); 3713 3714 LangOptions::setLangDefaults(Opts, IK.getLanguage(), T, Includes, LangStd); 3715 3716 // The key paths of codegen options defined in Options.td start with 3717 // "LangOpts->". Let's provide the expected variable name and type. 3718 LangOptions *LangOpts = &Opts; 3719 3720 #define LANG_OPTION_WITH_MARSHALLING(...) \ 3721 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__) 3722 #include "clang/Driver/Options.inc" 3723 #undef LANG_OPTION_WITH_MARSHALLING 3724 3725 if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) { 3726 StringRef Name = A->getValue(); 3727 if (Name == "full" || Name == "branch") { 3728 Opts.CFProtectionBranch = 1; 3729 } 3730 } 3731 3732 if ((Args.hasArg(OPT_fsycl_is_device) || Args.hasArg(OPT_fsycl_is_host)) && 3733 !Args.hasArg(OPT_sycl_std_EQ)) { 3734 // If the user supplied -fsycl-is-device or -fsycl-is-host, but failed to 3735 // provide -sycl-std=, we want to default it to whatever the default SYCL 3736 // version is. I could not find a way to express this with the options 3737 // tablegen because we still want this value to be SYCL_None when the user 3738 // is not in device or host mode. 3739 Opts.setSYCLVersion(LangOptions::SYCL_Default); 3740 } 3741 3742 if (Opts.ObjC) { 3743 if (Arg *arg = Args.getLastArg(OPT_fobjc_runtime_EQ)) { 3744 StringRef value = arg->getValue(); 3745 if (Opts.ObjCRuntime.tryParse(value)) 3746 Diags.Report(diag::err_drv_unknown_objc_runtime) << value; 3747 } 3748 3749 if (Args.hasArg(OPT_fobjc_gc_only)) 3750 Opts.setGC(LangOptions::GCOnly); 3751 else if (Args.hasArg(OPT_fobjc_gc)) 3752 Opts.setGC(LangOptions::HybridGC); 3753 else if (Args.hasArg(OPT_fobjc_arc)) { 3754 Opts.ObjCAutoRefCount = 1; 3755 if (!Opts.ObjCRuntime.allowsARC()) 3756 Diags.Report(diag::err_arc_unsupported_on_runtime); 3757 } 3758 3759 // ObjCWeakRuntime tracks whether the runtime supports __weak, not 3760 // whether the feature is actually enabled. This is predominantly 3761 // determined by -fobjc-runtime, but we allow it to be overridden 3762 // from the command line for testing purposes. 3763 if (Args.hasArg(OPT_fobjc_runtime_has_weak)) 3764 Opts.ObjCWeakRuntime = 1; 3765 else 3766 Opts.ObjCWeakRuntime = Opts.ObjCRuntime.allowsWeak(); 3767 3768 // ObjCWeak determines whether __weak is actually enabled. 3769 // Note that we allow -fno-objc-weak to disable this even in ARC mode. 3770 if (auto weakArg = Args.getLastArg(OPT_fobjc_weak, OPT_fno_objc_weak)) { 3771 if (!weakArg->getOption().matches(OPT_fobjc_weak)) { 3772 assert(!Opts.ObjCWeak); 3773 } else if (Opts.getGC() != LangOptions::NonGC) { 3774 Diags.Report(diag::err_objc_weak_with_gc); 3775 } else if (!Opts.ObjCWeakRuntime) { 3776 Diags.Report(diag::err_objc_weak_unsupported); 3777 } else { 3778 Opts.ObjCWeak = 1; 3779 } 3780 } else if (Opts.ObjCAutoRefCount) { 3781 Opts.ObjCWeak = Opts.ObjCWeakRuntime; 3782 } 3783 3784 if (Args.hasArg(OPT_fobjc_subscripting_legacy_runtime)) 3785 Opts.ObjCSubscriptingLegacyRuntime = 3786 (Opts.ObjCRuntime.getKind() == ObjCRuntime::FragileMacOSX); 3787 } 3788 3789 if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) { 3790 // Check that the version has 1 to 3 components and the minor and patch 3791 // versions fit in two decimal digits. 3792 VersionTuple GNUCVer; 3793 bool Invalid = GNUCVer.tryParse(A->getValue()); 3794 unsigned Major = GNUCVer.getMajor(); 3795 unsigned Minor = GNUCVer.getMinor().value_or(0); 3796 unsigned Patch = GNUCVer.getSubminor().value_or(0); 3797 if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) { 3798 Diags.Report(diag::err_drv_invalid_value) 3799 << A->getAsString(Args) << A->getValue(); 3800 } 3801 Opts.GNUCVersion = Major * 100 * 100 + Minor * 100 + Patch; 3802 } 3803 3804 if (T.isOSAIX() && (Args.hasArg(OPT_mignore_xcoff_visibility))) 3805 Opts.IgnoreXCOFFVisibility = 1; 3806 3807 if (Args.hasArg(OPT_ftrapv)) { 3808 Opts.setSignedOverflowBehavior(LangOptions::SOB_Trapping); 3809 // Set the handler, if one is specified. 3810 Opts.OverflowHandler = 3811 std::string(Args.getLastArgValue(OPT_ftrapv_handler)); 3812 } 3813 else if (Args.hasArg(OPT_fwrapv)) 3814 Opts.setSignedOverflowBehavior(LangOptions::SOB_Defined); 3815 3816 Opts.MSCompatibilityVersion = 0; 3817 if (const Arg *A = Args.getLastArg(OPT_fms_compatibility_version)) { 3818 VersionTuple VT; 3819 if (VT.tryParse(A->getValue())) 3820 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) 3821 << A->getValue(); 3822 Opts.MSCompatibilityVersion = VT.getMajor() * 10000000 + 3823 VT.getMinor().value_or(0) * 100000 + 3824 VT.getSubminor().value_or(0); 3825 } 3826 3827 // Mimicking gcc's behavior, trigraphs are only enabled if -trigraphs 3828 // is specified, or -std is set to a conforming mode. 3829 // Trigraphs are disabled by default in c++1z onwards. 3830 // For z/OS, trigraphs are enabled by default (without regard to the above). 3831 Opts.Trigraphs = 3832 (!Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus17) || T.isOSzOS(); 3833 Opts.Trigraphs = 3834 Args.hasFlag(OPT_ftrigraphs, OPT_fno_trigraphs, Opts.Trigraphs); 3835 3836 Opts.Blocks = Args.hasArg(OPT_fblocks) || (Opts.OpenCL 3837 && Opts.OpenCLVersion == 200); 3838 3839 Opts.ConvergentFunctions = Args.hasArg(OPT_fconvergent_functions) || 3840 Opts.OpenCL || (Opts.CUDA && Opts.CUDAIsDevice) || 3841 Opts.SYCLIsDevice; 3842 3843 Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding; 3844 if (!Opts.NoBuiltin) 3845 getAllNoBuiltinFuncValues(Args, Opts.NoBuiltinFuncs); 3846 if (Arg *A = Args.getLastArg(options::OPT_LongDouble_Group)) { 3847 if (A->getOption().matches(options::OPT_mlong_double_64)) 3848 Opts.LongDoubleSize = 64; 3849 else if (A->getOption().matches(options::OPT_mlong_double_80)) 3850 Opts.LongDoubleSize = 80; 3851 else if (A->getOption().matches(options::OPT_mlong_double_128)) 3852 Opts.LongDoubleSize = 128; 3853 else 3854 Opts.LongDoubleSize = 0; 3855 } 3856 if (Opts.FastRelaxedMath || Opts.CLUnsafeMath) 3857 Opts.setDefaultFPContractMode(LangOptions::FPM_Fast); 3858 3859 llvm::sort(Opts.ModuleFeatures); 3860 3861 // -mrtd option 3862 if (Arg *A = Args.getLastArg(OPT_mrtd)) { 3863 if (Opts.getDefaultCallingConv() != LangOptions::DCC_None) 3864 Diags.Report(diag::err_drv_argument_not_allowed_with) 3865 << A->getSpelling() << "-fdefault-calling-conv"; 3866 else { 3867 if (T.getArch() != llvm::Triple::x86) 3868 Diags.Report(diag::err_drv_argument_not_allowed_with) 3869 << A->getSpelling() << T.getTriple(); 3870 else 3871 Opts.setDefaultCallingConv(LangOptions::DCC_StdCall); 3872 } 3873 } 3874 3875 // Check if -fopenmp is specified and set default version to 5.0. 3876 Opts.OpenMP = Args.hasArg(OPT_fopenmp) ? 51 : 0; 3877 // Check if -fopenmp-simd is specified. 3878 bool IsSimdSpecified = 3879 Args.hasFlag(options::OPT_fopenmp_simd, options::OPT_fno_openmp_simd, 3880 /*Default=*/false); 3881 Opts.OpenMPSimd = !Opts.OpenMP && IsSimdSpecified; 3882 Opts.OpenMPUseTLS = 3883 Opts.OpenMP && !Args.hasArg(options::OPT_fnoopenmp_use_tls); 3884 Opts.OpenMPIsTargetDevice = 3885 Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_is_target_device); 3886 Opts.OpenMPIRBuilder = 3887 Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_enable_irbuilder); 3888 bool IsTargetSpecified = 3889 Opts.OpenMPIsTargetDevice || Args.hasArg(options::OPT_fopenmp_targets_EQ); 3890 3891 Opts.ConvergentFunctions = 3892 Opts.ConvergentFunctions || Opts.OpenMPIsTargetDevice; 3893 3894 if (Opts.OpenMP || Opts.OpenMPSimd) { 3895 if (int Version = getLastArgIntValue( 3896 Args, OPT_fopenmp_version_EQ, 3897 (IsSimdSpecified || IsTargetSpecified) ? 51 : Opts.OpenMP, Diags)) 3898 Opts.OpenMP = Version; 3899 // Provide diagnostic when a given target is not expected to be an OpenMP 3900 // device or host. 3901 if (!Opts.OpenMPIsTargetDevice) { 3902 switch (T.getArch()) { 3903 default: 3904 break; 3905 // Add unsupported host targets here: 3906 case llvm::Triple::nvptx: 3907 case llvm::Triple::nvptx64: 3908 Diags.Report(diag::err_drv_omp_host_target_not_supported) << T.str(); 3909 break; 3910 } 3911 } 3912 } 3913 3914 // Set the flag to prevent the implementation from emitting device exception 3915 // handling code for those requiring so. 3916 if ((Opts.OpenMPIsTargetDevice && (T.isNVPTX() || T.isAMDGCN())) || 3917 Opts.OpenCLCPlusPlus) { 3918 3919 Opts.Exceptions = 0; 3920 Opts.CXXExceptions = 0; 3921 } 3922 if (Opts.OpenMPIsTargetDevice && T.isNVPTX()) { 3923 Opts.OpenMPCUDANumSMs = 3924 getLastArgIntValue(Args, options::OPT_fopenmp_cuda_number_of_sm_EQ, 3925 Opts.OpenMPCUDANumSMs, Diags); 3926 Opts.OpenMPCUDABlocksPerSM = 3927 getLastArgIntValue(Args, options::OPT_fopenmp_cuda_blocks_per_sm_EQ, 3928 Opts.OpenMPCUDABlocksPerSM, Diags); 3929 Opts.OpenMPCUDAReductionBufNum = getLastArgIntValue( 3930 Args, options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ, 3931 Opts.OpenMPCUDAReductionBufNum, Diags); 3932 } 3933 3934 // Set the value of the debugging flag used in the new offloading device RTL. 3935 // Set either by a specific value or to a default if not specified. 3936 if (Opts.OpenMPIsTargetDevice && (Args.hasArg(OPT_fopenmp_target_debug) || 3937 Args.hasArg(OPT_fopenmp_target_debug_EQ))) { 3938 Opts.OpenMPTargetDebug = getLastArgIntValue( 3939 Args, OPT_fopenmp_target_debug_EQ, Opts.OpenMPTargetDebug, Diags); 3940 if (!Opts.OpenMPTargetDebug && Args.hasArg(OPT_fopenmp_target_debug)) 3941 Opts.OpenMPTargetDebug = 1; 3942 } 3943 3944 if (Opts.OpenMPIsTargetDevice) { 3945 if (Args.hasArg(OPT_fopenmp_assume_teams_oversubscription)) 3946 Opts.OpenMPTeamSubscription = true; 3947 if (Args.hasArg(OPT_fopenmp_assume_threads_oversubscription)) 3948 Opts.OpenMPThreadSubscription = true; 3949 } 3950 3951 // Get the OpenMP target triples if any. 3952 if (Arg *A = Args.getLastArg(options::OPT_fopenmp_targets_EQ)) { 3953 enum ArchPtrSize { Arch16Bit, Arch32Bit, Arch64Bit }; 3954 auto getArchPtrSize = [](const llvm::Triple &T) { 3955 if (T.isArch16Bit()) 3956 return Arch16Bit; 3957 if (T.isArch32Bit()) 3958 return Arch32Bit; 3959 assert(T.isArch64Bit() && "Expected 64-bit architecture"); 3960 return Arch64Bit; 3961 }; 3962 3963 for (unsigned i = 0; i < A->getNumValues(); ++i) { 3964 llvm::Triple TT(A->getValue(i)); 3965 3966 if (TT.getArch() == llvm::Triple::UnknownArch || 3967 !(TT.getArch() == llvm::Triple::aarch64 || TT.isPPC() || 3968 TT.getArch() == llvm::Triple::nvptx || 3969 TT.getArch() == llvm::Triple::nvptx64 || 3970 TT.getArch() == llvm::Triple::amdgcn || 3971 TT.getArch() == llvm::Triple::x86 || 3972 TT.getArch() == llvm::Triple::x86_64)) 3973 Diags.Report(diag::err_drv_invalid_omp_target) << A->getValue(i); 3974 else if (getArchPtrSize(T) != getArchPtrSize(TT)) 3975 Diags.Report(diag::err_drv_incompatible_omp_arch) 3976 << A->getValue(i) << T.str(); 3977 else 3978 Opts.OMPTargetTriples.push_back(TT); 3979 } 3980 } 3981 3982 // Get OpenMP host file path if any and report if a non existent file is 3983 // found 3984 if (Arg *A = Args.getLastArg(options::OPT_fopenmp_host_ir_file_path)) { 3985 Opts.OMPHostIRFile = A->getValue(); 3986 if (!llvm::sys::fs::exists(Opts.OMPHostIRFile)) 3987 Diags.Report(diag::err_drv_omp_host_ir_file_not_found) 3988 << Opts.OMPHostIRFile; 3989 } 3990 3991 // Set CUDA mode for OpenMP target NVPTX/AMDGCN if specified in options 3992 Opts.OpenMPCUDAMode = Opts.OpenMPIsTargetDevice && 3993 (T.isNVPTX() || T.isAMDGCN()) && 3994 Args.hasArg(options::OPT_fopenmp_cuda_mode); 3995 3996 // FIXME: Eliminate this dependency. 3997 unsigned Opt = getOptimizationLevel(Args, IK, Diags), 3998 OptSize = getOptimizationLevelSize(Args); 3999 Opts.Optimize = Opt != 0; 4000 Opts.OptimizeSize = OptSize != 0; 4001 4002 // This is the __NO_INLINE__ define, which just depends on things like the 4003 // optimization level and -fno-inline, not actually whether the backend has 4004 // inlining enabled. 4005 Opts.NoInlineDefine = !Opts.Optimize; 4006 if (Arg *InlineArg = Args.getLastArg( 4007 options::OPT_finline_functions, options::OPT_finline_hint_functions, 4008 options::OPT_fno_inline_functions, options::OPT_fno_inline)) 4009 if (InlineArg->getOption().matches(options::OPT_fno_inline)) 4010 Opts.NoInlineDefine = true; 4011 4012 if (Arg *A = Args.getLastArg(OPT_ffp_contract)) { 4013 StringRef Val = A->getValue(); 4014 if (Val == "fast") 4015 Opts.setDefaultFPContractMode(LangOptions::FPM_Fast); 4016 else if (Val == "on") 4017 Opts.setDefaultFPContractMode(LangOptions::FPM_On); 4018 else if (Val == "off") 4019 Opts.setDefaultFPContractMode(LangOptions::FPM_Off); 4020 else if (Val == "fast-honor-pragmas") 4021 Opts.setDefaultFPContractMode(LangOptions::FPM_FastHonorPragmas); 4022 else 4023 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val; 4024 } 4025 4026 // Parse -fsanitize= arguments. 4027 parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ), 4028 Diags, Opts.Sanitize); 4029 Opts.NoSanitizeFiles = Args.getAllArgValues(OPT_fsanitize_ignorelist_EQ); 4030 std::vector<std::string> systemIgnorelists = 4031 Args.getAllArgValues(OPT_fsanitize_system_ignorelist_EQ); 4032 Opts.NoSanitizeFiles.insert(Opts.NoSanitizeFiles.end(), 4033 systemIgnorelists.begin(), 4034 systemIgnorelists.end()); 4035 4036 if (Arg *A = Args.getLastArg(OPT_fclang_abi_compat_EQ)) { 4037 Opts.setClangABICompat(LangOptions::ClangABI::Latest); 4038 4039 StringRef Ver = A->getValue(); 4040 std::pair<StringRef, StringRef> VerParts = Ver.split('.'); 4041 unsigned Major, Minor = 0; 4042 4043 // Check the version number is valid: either 3.x (0 <= x <= 9) or 4044 // y or y.0 (4 <= y <= current version). 4045 if (!VerParts.first.startswith("0") && 4046 !VerParts.first.getAsInteger(10, Major) && 4047 3 <= Major && Major <= CLANG_VERSION_MAJOR && 4048 (Major == 3 ? VerParts.second.size() == 1 && 4049 !VerParts.second.getAsInteger(10, Minor) 4050 : VerParts.first.size() == Ver.size() || 4051 VerParts.second == "0")) { 4052 // Got a valid version number. 4053 if (Major == 3 && Minor <= 8) 4054 Opts.setClangABICompat(LangOptions::ClangABI::Ver3_8); 4055 else if (Major <= 4) 4056 Opts.setClangABICompat(LangOptions::ClangABI::Ver4); 4057 else if (Major <= 6) 4058 Opts.setClangABICompat(LangOptions::ClangABI::Ver6); 4059 else if (Major <= 7) 4060 Opts.setClangABICompat(LangOptions::ClangABI::Ver7); 4061 else if (Major <= 9) 4062 Opts.setClangABICompat(LangOptions::ClangABI::Ver9); 4063 else if (Major <= 11) 4064 Opts.setClangABICompat(LangOptions::ClangABI::Ver11); 4065 else if (Major <= 12) 4066 Opts.setClangABICompat(LangOptions::ClangABI::Ver12); 4067 else if (Major <= 14) 4068 Opts.setClangABICompat(LangOptions::ClangABI::Ver14); 4069 else if (Major <= 15) 4070 Opts.setClangABICompat(LangOptions::ClangABI::Ver15); 4071 else if (Major <= 17) 4072 Opts.setClangABICompat(LangOptions::ClangABI::Ver17); 4073 } else if (Ver != "latest") { 4074 Diags.Report(diag::err_drv_invalid_value) 4075 << A->getAsString(Args) << A->getValue(); 4076 } 4077 } 4078 4079 if (Arg *A = Args.getLastArg(OPT_msign_return_address_EQ)) { 4080 StringRef SignScope = A->getValue(); 4081 4082 if (SignScope.equals_insensitive("none")) 4083 Opts.setSignReturnAddressScope( 4084 LangOptions::SignReturnAddressScopeKind::None); 4085 else if (SignScope.equals_insensitive("all")) 4086 Opts.setSignReturnAddressScope( 4087 LangOptions::SignReturnAddressScopeKind::All); 4088 else if (SignScope.equals_insensitive("non-leaf")) 4089 Opts.setSignReturnAddressScope( 4090 LangOptions::SignReturnAddressScopeKind::NonLeaf); 4091 else 4092 Diags.Report(diag::err_drv_invalid_value) 4093 << A->getAsString(Args) << SignScope; 4094 4095 if (Arg *A = Args.getLastArg(OPT_msign_return_address_key_EQ)) { 4096 StringRef SignKey = A->getValue(); 4097 if (!SignScope.empty() && !SignKey.empty()) { 4098 if (SignKey.equals_insensitive("a_key")) 4099 Opts.setSignReturnAddressKey( 4100 LangOptions::SignReturnAddressKeyKind::AKey); 4101 else if (SignKey.equals_insensitive("b_key")) 4102 Opts.setSignReturnAddressKey( 4103 LangOptions::SignReturnAddressKeyKind::BKey); 4104 else 4105 Diags.Report(diag::err_drv_invalid_value) 4106 << A->getAsString(Args) << SignKey; 4107 } 4108 } 4109 } 4110 4111 // The value can be empty, which indicates the system default should be used. 4112 StringRef CXXABI = Args.getLastArgValue(OPT_fcxx_abi_EQ); 4113 if (!CXXABI.empty()) { 4114 if (!TargetCXXABI::isABI(CXXABI)) { 4115 Diags.Report(diag::err_invalid_cxx_abi) << CXXABI; 4116 } else { 4117 auto Kind = TargetCXXABI::getKind(CXXABI); 4118 if (!TargetCXXABI::isSupportedCXXABI(T, Kind)) 4119 Diags.Report(diag::err_unsupported_cxx_abi) << CXXABI << T.str(); 4120 else 4121 Opts.CXXABI = Kind; 4122 } 4123 } 4124 4125 Opts.RelativeCXXABIVTables = 4126 Args.hasFlag(options::OPT_fexperimental_relative_cxx_abi_vtables, 4127 options::OPT_fno_experimental_relative_cxx_abi_vtables, 4128 TargetCXXABI::usesRelativeVTables(T)); 4129 4130 // RTTI is on by default. 4131 bool HasRTTI = Args.hasFlag(options::OPT_frtti, options::OPT_fno_rtti, true); 4132 Opts.OmitVTableRTTI = 4133 Args.hasFlag(options::OPT_fexperimental_omit_vtable_rtti, 4134 options::OPT_fno_experimental_omit_vtable_rtti, false); 4135 if (Opts.OmitVTableRTTI && HasRTTI) 4136 Diags.Report(diag::err_drv_using_omit_rtti_component_without_no_rtti); 4137 4138 for (const auto &A : Args.getAllArgValues(OPT_fmacro_prefix_map_EQ)) { 4139 auto Split = StringRef(A).split('='); 4140 Opts.MacroPrefixMap.insert( 4141 {std::string(Split.first), std::string(Split.second)}); 4142 } 4143 4144 Opts.UseTargetPathSeparator = 4145 !Args.getLastArg(OPT_fno_file_reproducible) && 4146 (Args.getLastArg(OPT_ffile_compilation_dir_EQ) || 4147 Args.getLastArg(OPT_fmacro_prefix_map_EQ) || 4148 Args.getLastArg(OPT_ffile_reproducible)); 4149 4150 // Error if -mvscale-min is unbounded. 4151 if (Arg *A = Args.getLastArg(options::OPT_mvscale_min_EQ)) { 4152 unsigned VScaleMin; 4153 if (StringRef(A->getValue()).getAsInteger(10, VScaleMin) || VScaleMin == 0) 4154 Diags.Report(diag::err_cc1_unbounded_vscale_min); 4155 } 4156 4157 if (const Arg *A = Args.getLastArg(OPT_frandomize_layout_seed_file_EQ)) { 4158 std::ifstream SeedFile(A->getValue(0)); 4159 4160 if (!SeedFile.is_open()) 4161 Diags.Report(diag::err_drv_cannot_open_randomize_layout_seed_file) 4162 << A->getValue(0); 4163 4164 std::getline(SeedFile, Opts.RandstructSeed); 4165 } 4166 4167 if (const Arg *A = Args.getLastArg(OPT_frandomize_layout_seed_EQ)) 4168 Opts.RandstructSeed = A->getValue(0); 4169 4170 // Validate options for HLSL 4171 if (Opts.HLSL) { 4172 // TODO: Revisit restricting SPIR-V to logical once we've figured out how to 4173 // handle PhysicalStorageBuffer64 memory model 4174 if (T.isDXIL() || T.isSPIRVLogical()) { 4175 enum { ShaderModel, ShaderStage }; 4176 if (T.getOSName().empty()) { 4177 Diags.Report(diag::err_drv_hlsl_bad_shader_required_in_target) 4178 << ShaderModel << T.str(); 4179 } else if (!T.isShaderModelOS() || T.getOSVersion() == VersionTuple(0)) { 4180 Diags.Report(diag::err_drv_hlsl_bad_shader_unsupported) 4181 << ShaderModel << T.getOSName() << T.str(); 4182 } else if (T.getEnvironmentName().empty()) { 4183 Diags.Report(diag::err_drv_hlsl_bad_shader_required_in_target) 4184 << ShaderStage << T.str(); 4185 } else if (!T.isShaderStageEnvironment()) { 4186 Diags.Report(diag::err_drv_hlsl_bad_shader_unsupported) 4187 << ShaderStage << T.getEnvironmentName() << T.str(); 4188 } 4189 } else 4190 Diags.Report(diag::err_drv_hlsl_unsupported_target) << T.str(); 4191 } 4192 4193 return Diags.getNumErrors() == NumErrorsBefore; 4194 } 4195 4196 static bool isStrictlyPreprocessorAction(frontend::ActionKind Action) { 4197 switch (Action) { 4198 case frontend::ASTDeclList: 4199 case frontend::ASTDump: 4200 case frontend::ASTPrint: 4201 case frontend::ASTView: 4202 case frontend::EmitAssembly: 4203 case frontend::EmitBC: 4204 case frontend::EmitHTML: 4205 case frontend::EmitLLVM: 4206 case frontend::EmitLLVMOnly: 4207 case frontend::EmitCodeGenOnly: 4208 case frontend::EmitObj: 4209 case frontend::ExtractAPI: 4210 case frontend::FixIt: 4211 case frontend::GenerateModule: 4212 case frontend::GenerateModuleInterface: 4213 case frontend::GenerateHeaderUnit: 4214 case frontend::GeneratePCH: 4215 case frontend::GenerateInterfaceStubs: 4216 case frontend::ParseSyntaxOnly: 4217 case frontend::ModuleFileInfo: 4218 case frontend::VerifyPCH: 4219 case frontend::PluginAction: 4220 case frontend::RewriteObjC: 4221 case frontend::RewriteTest: 4222 case frontend::RunAnalysis: 4223 case frontend::TemplightDump: 4224 case frontend::MigrateSource: 4225 return false; 4226 4227 case frontend::DumpCompilerOptions: 4228 case frontend::DumpRawTokens: 4229 case frontend::DumpTokens: 4230 case frontend::InitOnly: 4231 case frontend::PrintPreamble: 4232 case frontend::PrintPreprocessedInput: 4233 case frontend::RewriteMacros: 4234 case frontend::RunPreprocessorOnly: 4235 case frontend::PrintDependencyDirectivesSourceMinimizerOutput: 4236 return true; 4237 } 4238 llvm_unreachable("invalid frontend action"); 4239 } 4240 4241 static void GeneratePreprocessorArgs(const PreprocessorOptions &Opts, 4242 ArgumentConsumer Consumer, 4243 const LangOptions &LangOpts, 4244 const FrontendOptions &FrontendOpts, 4245 const CodeGenOptions &CodeGenOpts) { 4246 const PreprocessorOptions *PreprocessorOpts = &Opts; 4247 4248 #define PREPROCESSOR_OPTION_WITH_MARSHALLING(...) \ 4249 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__) 4250 #include "clang/Driver/Options.inc" 4251 #undef PREPROCESSOR_OPTION_WITH_MARSHALLING 4252 4253 if (Opts.PCHWithHdrStop && !Opts.PCHWithHdrStopCreate) 4254 GenerateArg(Consumer, OPT_pch_through_hdrstop_use); 4255 4256 for (const auto &D : Opts.DeserializedPCHDeclsToErrorOn) 4257 GenerateArg(Consumer, OPT_error_on_deserialized_pch_decl, D); 4258 4259 if (Opts.PrecompiledPreambleBytes != std::make_pair(0u, false)) 4260 GenerateArg(Consumer, OPT_preamble_bytes_EQ, 4261 Twine(Opts.PrecompiledPreambleBytes.first) + "," + 4262 (Opts.PrecompiledPreambleBytes.second ? "1" : "0")); 4263 4264 for (const auto &M : Opts.Macros) { 4265 // Don't generate __CET__ macro definitions. They are implied by the 4266 // -fcf-protection option that is generated elsewhere. 4267 if (M.first == "__CET__=1" && !M.second && 4268 !CodeGenOpts.CFProtectionReturn && CodeGenOpts.CFProtectionBranch) 4269 continue; 4270 if (M.first == "__CET__=2" && !M.second && CodeGenOpts.CFProtectionReturn && 4271 !CodeGenOpts.CFProtectionBranch) 4272 continue; 4273 if (M.first == "__CET__=3" && !M.second && CodeGenOpts.CFProtectionReturn && 4274 CodeGenOpts.CFProtectionBranch) 4275 continue; 4276 4277 GenerateArg(Consumer, M.second ? OPT_U : OPT_D, M.first); 4278 } 4279 4280 for (const auto &I : Opts.Includes) { 4281 // Don't generate OpenCL includes. They are implied by other flags that are 4282 // generated elsewhere. 4283 if (LangOpts.OpenCL && LangOpts.IncludeDefaultHeader && 4284 ((LangOpts.DeclareOpenCLBuiltins && I == "opencl-c-base.h") || 4285 I == "opencl-c.h")) 4286 continue; 4287 // Don't generate HLSL includes. They are implied by other flags that are 4288 // generated elsewhere. 4289 if (LangOpts.HLSL && I == "hlsl.h") 4290 continue; 4291 4292 GenerateArg(Consumer, OPT_include, I); 4293 } 4294 4295 for (const auto &CI : Opts.ChainedIncludes) 4296 GenerateArg(Consumer, OPT_chain_include, CI); 4297 4298 for (const auto &RF : Opts.RemappedFiles) 4299 GenerateArg(Consumer, OPT_remap_file, RF.first + ";" + RF.second); 4300 4301 if (Opts.SourceDateEpoch) 4302 GenerateArg(Consumer, OPT_source_date_epoch, Twine(*Opts.SourceDateEpoch)); 4303 4304 // Don't handle LexEditorPlaceholders. It is implied by the action that is 4305 // generated elsewhere. 4306 } 4307 4308 static bool ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args, 4309 DiagnosticsEngine &Diags, 4310 frontend::ActionKind Action, 4311 const FrontendOptions &FrontendOpts) { 4312 unsigned NumErrorsBefore = Diags.getNumErrors(); 4313 4314 PreprocessorOptions *PreprocessorOpts = &Opts; 4315 4316 #define PREPROCESSOR_OPTION_WITH_MARSHALLING(...) \ 4317 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__) 4318 #include "clang/Driver/Options.inc" 4319 #undef PREPROCESSOR_OPTION_WITH_MARSHALLING 4320 4321 Opts.PCHWithHdrStop = Args.hasArg(OPT_pch_through_hdrstop_create) || 4322 Args.hasArg(OPT_pch_through_hdrstop_use); 4323 4324 for (const auto *A : Args.filtered(OPT_error_on_deserialized_pch_decl)) 4325 Opts.DeserializedPCHDeclsToErrorOn.insert(A->getValue()); 4326 4327 if (const Arg *A = Args.getLastArg(OPT_preamble_bytes_EQ)) { 4328 StringRef Value(A->getValue()); 4329 size_t Comma = Value.find(','); 4330 unsigned Bytes = 0; 4331 unsigned EndOfLine = 0; 4332 4333 if (Comma == StringRef::npos || 4334 Value.substr(0, Comma).getAsInteger(10, Bytes) || 4335 Value.substr(Comma + 1).getAsInteger(10, EndOfLine)) 4336 Diags.Report(diag::err_drv_preamble_format); 4337 else { 4338 Opts.PrecompiledPreambleBytes.first = Bytes; 4339 Opts.PrecompiledPreambleBytes.second = (EndOfLine != 0); 4340 } 4341 } 4342 4343 // Add the __CET__ macro if a CFProtection option is set. 4344 if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) { 4345 StringRef Name = A->getValue(); 4346 if (Name == "branch") 4347 Opts.addMacroDef("__CET__=1"); 4348 else if (Name == "return") 4349 Opts.addMacroDef("__CET__=2"); 4350 else if (Name == "full") 4351 Opts.addMacroDef("__CET__=3"); 4352 } 4353 4354 // Add macros from the command line. 4355 for (const auto *A : Args.filtered(OPT_D, OPT_U)) { 4356 if (A->getOption().matches(OPT_D)) 4357 Opts.addMacroDef(A->getValue()); 4358 else 4359 Opts.addMacroUndef(A->getValue()); 4360 } 4361 4362 // Add the ordered list of -includes. 4363 for (const auto *A : Args.filtered(OPT_include)) 4364 Opts.Includes.emplace_back(A->getValue()); 4365 4366 for (const auto *A : Args.filtered(OPT_chain_include)) 4367 Opts.ChainedIncludes.emplace_back(A->getValue()); 4368 4369 for (const auto *A : Args.filtered(OPT_remap_file)) { 4370 std::pair<StringRef, StringRef> Split = StringRef(A->getValue()).split(';'); 4371 4372 if (Split.second.empty()) { 4373 Diags.Report(diag::err_drv_invalid_remap_file) << A->getAsString(Args); 4374 continue; 4375 } 4376 4377 Opts.addRemappedFile(Split.first, Split.second); 4378 } 4379 4380 if (const Arg *A = Args.getLastArg(OPT_source_date_epoch)) { 4381 StringRef Epoch = A->getValue(); 4382 // SOURCE_DATE_EPOCH, if specified, must be a non-negative decimal integer. 4383 // On time64 systems, pick 253402300799 (the UNIX timestamp of 4384 // 9999-12-31T23:59:59Z) as the upper bound. 4385 const uint64_t MaxTimestamp = 4386 std::min<uint64_t>(std::numeric_limits<time_t>::max(), 253402300799); 4387 uint64_t V; 4388 if (Epoch.getAsInteger(10, V) || V > MaxTimestamp) { 4389 Diags.Report(diag::err_fe_invalid_source_date_epoch) 4390 << Epoch << MaxTimestamp; 4391 } else { 4392 Opts.SourceDateEpoch = V; 4393 } 4394 } 4395 4396 // Always avoid lexing editor placeholders when we're just running the 4397 // preprocessor as we never want to emit the 4398 // "editor placeholder in source file" error in PP only mode. 4399 if (isStrictlyPreprocessorAction(Action)) 4400 Opts.LexEditorPlaceholders = false; 4401 4402 return Diags.getNumErrors() == NumErrorsBefore; 4403 } 4404 4405 static void 4406 GeneratePreprocessorOutputArgs(const PreprocessorOutputOptions &Opts, 4407 ArgumentConsumer Consumer, 4408 frontend::ActionKind Action) { 4409 const PreprocessorOutputOptions &PreprocessorOutputOpts = Opts; 4410 4411 #define PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING(...) \ 4412 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__) 4413 #include "clang/Driver/Options.inc" 4414 #undef PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING 4415 4416 bool Generate_dM = isStrictlyPreprocessorAction(Action) && !Opts.ShowCPP; 4417 if (Generate_dM) 4418 GenerateArg(Consumer, OPT_dM); 4419 if (!Generate_dM && Opts.ShowMacros) 4420 GenerateArg(Consumer, OPT_dD); 4421 if (Opts.DirectivesOnly) 4422 GenerateArg(Consumer, OPT_fdirectives_only); 4423 } 4424 4425 static bool ParsePreprocessorOutputArgs(PreprocessorOutputOptions &Opts, 4426 ArgList &Args, DiagnosticsEngine &Diags, 4427 frontend::ActionKind Action) { 4428 unsigned NumErrorsBefore = Diags.getNumErrors(); 4429 4430 PreprocessorOutputOptions &PreprocessorOutputOpts = Opts; 4431 4432 #define PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING(...) \ 4433 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__) 4434 #include "clang/Driver/Options.inc" 4435 #undef PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING 4436 4437 Opts.ShowCPP = isStrictlyPreprocessorAction(Action) && !Args.hasArg(OPT_dM); 4438 Opts.ShowMacros = Args.hasArg(OPT_dM) || Args.hasArg(OPT_dD); 4439 Opts.DirectivesOnly = Args.hasArg(OPT_fdirectives_only); 4440 4441 return Diags.getNumErrors() == NumErrorsBefore; 4442 } 4443 4444 static void GenerateTargetArgs(const TargetOptions &Opts, 4445 ArgumentConsumer Consumer) { 4446 const TargetOptions *TargetOpts = &Opts; 4447 #define TARGET_OPTION_WITH_MARSHALLING(...) \ 4448 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__) 4449 #include "clang/Driver/Options.inc" 4450 #undef TARGET_OPTION_WITH_MARSHALLING 4451 4452 if (!Opts.SDKVersion.empty()) 4453 GenerateArg(Consumer, OPT_target_sdk_version_EQ, 4454 Opts.SDKVersion.getAsString()); 4455 if (!Opts.DarwinTargetVariantSDKVersion.empty()) 4456 GenerateArg(Consumer, OPT_darwin_target_variant_sdk_version_EQ, 4457 Opts.DarwinTargetVariantSDKVersion.getAsString()); 4458 } 4459 4460 static bool ParseTargetArgs(TargetOptions &Opts, ArgList &Args, 4461 DiagnosticsEngine &Diags) { 4462 unsigned NumErrorsBefore = Diags.getNumErrors(); 4463 4464 TargetOptions *TargetOpts = &Opts; 4465 4466 #define TARGET_OPTION_WITH_MARSHALLING(...) \ 4467 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__) 4468 #include "clang/Driver/Options.inc" 4469 #undef TARGET_OPTION_WITH_MARSHALLING 4470 4471 if (Arg *A = Args.getLastArg(options::OPT_target_sdk_version_EQ)) { 4472 llvm::VersionTuple Version; 4473 if (Version.tryParse(A->getValue())) 4474 Diags.Report(diag::err_drv_invalid_value) 4475 << A->getAsString(Args) << A->getValue(); 4476 else 4477 Opts.SDKVersion = Version; 4478 } 4479 if (Arg *A = 4480 Args.getLastArg(options::OPT_darwin_target_variant_sdk_version_EQ)) { 4481 llvm::VersionTuple Version; 4482 if (Version.tryParse(A->getValue())) 4483 Diags.Report(diag::err_drv_invalid_value) 4484 << A->getAsString(Args) << A->getValue(); 4485 else 4486 Opts.DarwinTargetVariantSDKVersion = Version; 4487 } 4488 4489 return Diags.getNumErrors() == NumErrorsBefore; 4490 } 4491 4492 bool CompilerInvocation::CreateFromArgsImpl( 4493 CompilerInvocation &Res, ArrayRef<const char *> CommandLineArgs, 4494 DiagnosticsEngine &Diags, const char *Argv0) { 4495 unsigned NumErrorsBefore = Diags.getNumErrors(); 4496 4497 // Parse the arguments. 4498 const OptTable &Opts = getDriverOptTable(); 4499 llvm::opt::Visibility VisibilityMask(options::CC1Option); 4500 unsigned MissingArgIndex, MissingArgCount; 4501 InputArgList Args = Opts.ParseArgs(CommandLineArgs, MissingArgIndex, 4502 MissingArgCount, VisibilityMask); 4503 LangOptions &LangOpts = Res.getLangOpts(); 4504 4505 // Check for missing argument error. 4506 if (MissingArgCount) 4507 Diags.Report(diag::err_drv_missing_argument) 4508 << Args.getArgString(MissingArgIndex) << MissingArgCount; 4509 4510 // Issue errors on unknown arguments. 4511 for (const auto *A : Args.filtered(OPT_UNKNOWN)) { 4512 auto ArgString = A->getAsString(Args); 4513 std::string Nearest; 4514 if (Opts.findNearest(ArgString, Nearest, VisibilityMask) > 1) 4515 Diags.Report(diag::err_drv_unknown_argument) << ArgString; 4516 else 4517 Diags.Report(diag::err_drv_unknown_argument_with_suggestion) 4518 << ArgString << Nearest; 4519 } 4520 4521 ParseFileSystemArgs(Res.getFileSystemOpts(), Args, Diags); 4522 ParseMigratorArgs(Res.getMigratorOpts(), Args, Diags); 4523 ParseAnalyzerArgs(Res.getAnalyzerOpts(), Args, Diags); 4524 ParseDiagnosticArgs(Res.getDiagnosticOpts(), Args, &Diags, 4525 /*DefaultDiagColor=*/false); 4526 ParseFrontendArgs(Res.getFrontendOpts(), Args, Diags, LangOpts.IsHeaderFile); 4527 // FIXME: We shouldn't have to pass the DashX option around here 4528 InputKind DashX = Res.getFrontendOpts().DashX; 4529 ParseTargetArgs(Res.getTargetOpts(), Args, Diags); 4530 llvm::Triple T(Res.getTargetOpts().Triple); 4531 ParseHeaderSearchArgs(Res.getHeaderSearchOpts(), Args, Diags, 4532 Res.getFileSystemOpts().WorkingDir); 4533 4534 ParseLangArgs(LangOpts, Args, DashX, T, Res.getPreprocessorOpts().Includes, 4535 Diags); 4536 if (Res.getFrontendOpts().ProgramAction == frontend::RewriteObjC) 4537 LangOpts.ObjCExceptions = 1; 4538 4539 for (auto Warning : Res.getDiagnosticOpts().Warnings) { 4540 if (Warning == "misexpect" && 4541 !Diags.isIgnored(diag::warn_profile_data_misexpect, SourceLocation())) { 4542 Res.getCodeGenOpts().MisExpect = true; 4543 } 4544 } 4545 4546 if (LangOpts.CUDA) { 4547 // During CUDA device-side compilation, the aux triple is the 4548 // triple used for host compilation. 4549 if (LangOpts.CUDAIsDevice) 4550 Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple; 4551 } 4552 4553 // Set the triple of the host for OpenMP device compile. 4554 if (LangOpts.OpenMPIsTargetDevice) 4555 Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple; 4556 4557 ParseCodeGenArgs(Res.getCodeGenOpts(), Args, DashX, Diags, T, 4558 Res.getFrontendOpts().OutputFile, LangOpts); 4559 4560 // FIXME: Override value name discarding when asan or msan is used because the 4561 // backend passes depend on the name of the alloca in order to print out 4562 // names. 4563 Res.getCodeGenOpts().DiscardValueNames &= 4564 !LangOpts.Sanitize.has(SanitizerKind::Address) && 4565 !LangOpts.Sanitize.has(SanitizerKind::KernelAddress) && 4566 !LangOpts.Sanitize.has(SanitizerKind::Memory) && 4567 !LangOpts.Sanitize.has(SanitizerKind::KernelMemory); 4568 4569 ParsePreprocessorArgs(Res.getPreprocessorOpts(), Args, Diags, 4570 Res.getFrontendOpts().ProgramAction, 4571 Res.getFrontendOpts()); 4572 ParsePreprocessorOutputArgs(Res.getPreprocessorOutputOpts(), Args, Diags, 4573 Res.getFrontendOpts().ProgramAction); 4574 4575 ParseDependencyOutputArgs(Res.getDependencyOutputOpts(), Args, Diags, 4576 Res.getFrontendOpts().ProgramAction, 4577 Res.getPreprocessorOutputOpts().ShowLineMarkers); 4578 if (!Res.getDependencyOutputOpts().OutputFile.empty() && 4579 Res.getDependencyOutputOpts().Targets.empty()) 4580 Diags.Report(diag::err_fe_dependency_file_requires_MT); 4581 4582 // If sanitizer is enabled, disable OPT_ffine_grained_bitfield_accesses. 4583 if (Res.getCodeGenOpts().FineGrainedBitfieldAccesses && 4584 !Res.getLangOpts().Sanitize.empty()) { 4585 Res.getCodeGenOpts().FineGrainedBitfieldAccesses = false; 4586 Diags.Report(diag::warn_drv_fine_grained_bitfield_accesses_ignored); 4587 } 4588 4589 // Store the command-line for using in the CodeView backend. 4590 if (Res.getCodeGenOpts().CodeViewCommandLine) { 4591 Res.getCodeGenOpts().Argv0 = Argv0; 4592 append_range(Res.getCodeGenOpts().CommandLineArgs, CommandLineArgs); 4593 } 4594 4595 // Set PGOOptions. Need to create a temporary VFS to read the profile 4596 // to determine the PGO type. 4597 if (!Res.getCodeGenOpts().ProfileInstrumentUsePath.empty()) { 4598 auto FS = 4599 createVFSFromOverlayFiles(Res.getHeaderSearchOpts().VFSOverlayFiles, 4600 Diags, llvm::vfs::getRealFileSystem()); 4601 setPGOUseInstrumentor(Res.getCodeGenOpts(), 4602 Res.getCodeGenOpts().ProfileInstrumentUsePath, *FS, 4603 Diags); 4604 } 4605 4606 FixupInvocation(Res, Diags, Args, DashX); 4607 4608 return Diags.getNumErrors() == NumErrorsBefore; 4609 } 4610 4611 bool CompilerInvocation::CreateFromArgs(CompilerInvocation &Invocation, 4612 ArrayRef<const char *> CommandLineArgs, 4613 DiagnosticsEngine &Diags, 4614 const char *Argv0) { 4615 CompilerInvocation DummyInvocation; 4616 4617 return RoundTrip( 4618 [](CompilerInvocation &Invocation, ArrayRef<const char *> CommandLineArgs, 4619 DiagnosticsEngine &Diags, const char *Argv0) { 4620 return CreateFromArgsImpl(Invocation, CommandLineArgs, Diags, Argv0); 4621 }, 4622 [](CompilerInvocation &Invocation, SmallVectorImpl<const char *> &Args, 4623 StringAllocator SA) { 4624 Args.push_back("-cc1"); 4625 Invocation.generateCC1CommandLine(Args, SA); 4626 }, 4627 Invocation, DummyInvocation, CommandLineArgs, Diags, Argv0); 4628 } 4629 4630 std::string CompilerInvocation::getModuleHash() const { 4631 // FIXME: Consider using SHA1 instead of MD5. 4632 llvm::HashBuilder<llvm::MD5, llvm::support::endianness::native> HBuilder; 4633 4634 // Note: For QoI reasons, the things we use as a hash here should all be 4635 // dumped via the -module-info flag. 4636 4637 // Start the signature with the compiler version. 4638 HBuilder.add(getClangFullRepositoryVersion()); 4639 4640 // Also include the serialization version, in case LLVM_APPEND_VC_REV is off 4641 // and getClangFullRepositoryVersion() doesn't include git revision. 4642 HBuilder.add(serialization::VERSION_MAJOR, serialization::VERSION_MINOR); 4643 4644 // Extend the signature with the language options 4645 #define LANGOPT(Name, Bits, Default, Description) HBuilder.add(LangOpts->Name); 4646 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \ 4647 HBuilder.add(static_cast<unsigned>(LangOpts->get##Name())); 4648 #define BENIGN_LANGOPT(Name, Bits, Default, Description) 4649 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description) 4650 #include "clang/Basic/LangOptions.def" 4651 4652 HBuilder.addRange(getLangOpts().ModuleFeatures); 4653 4654 HBuilder.add(getLangOpts().ObjCRuntime); 4655 HBuilder.addRange(getLangOpts().CommentOpts.BlockCommandNames); 4656 4657 // Extend the signature with the target options. 4658 HBuilder.add(getTargetOpts().Triple, getTargetOpts().CPU, 4659 getTargetOpts().TuneCPU, getTargetOpts().ABI); 4660 HBuilder.addRange(getTargetOpts().FeaturesAsWritten); 4661 4662 // Extend the signature with preprocessor options. 4663 const PreprocessorOptions &ppOpts = getPreprocessorOpts(); 4664 HBuilder.add(ppOpts.UsePredefines, ppOpts.DetailedRecord); 4665 4666 const HeaderSearchOptions &hsOpts = getHeaderSearchOpts(); 4667 for (const auto &Macro : getPreprocessorOpts().Macros) { 4668 // If we're supposed to ignore this macro for the purposes of modules, 4669 // don't put it into the hash. 4670 if (!hsOpts.ModulesIgnoreMacros.empty()) { 4671 // Check whether we're ignoring this macro. 4672 StringRef MacroDef = Macro.first; 4673 if (hsOpts.ModulesIgnoreMacros.count( 4674 llvm::CachedHashString(MacroDef.split('=').first))) 4675 continue; 4676 } 4677 4678 HBuilder.add(Macro); 4679 } 4680 4681 // Extend the signature with the sysroot and other header search options. 4682 HBuilder.add(hsOpts.Sysroot, hsOpts.ModuleFormat, hsOpts.UseDebugInfo, 4683 hsOpts.UseBuiltinIncludes, hsOpts.UseStandardSystemIncludes, 4684 hsOpts.UseStandardCXXIncludes, hsOpts.UseLibcxx, 4685 hsOpts.ModulesValidateDiagnosticOptions); 4686 HBuilder.add(hsOpts.ResourceDir); 4687 4688 if (hsOpts.ModulesStrictContextHash) { 4689 HBuilder.addRange(hsOpts.SystemHeaderPrefixes); 4690 HBuilder.addRange(hsOpts.UserEntries); 4691 4692 const DiagnosticOptions &diagOpts = getDiagnosticOpts(); 4693 #define DIAGOPT(Name, Bits, Default) HBuilder.add(diagOpts.Name); 4694 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \ 4695 HBuilder.add(diagOpts.get##Name()); 4696 #include "clang/Basic/DiagnosticOptions.def" 4697 #undef DIAGOPT 4698 #undef ENUM_DIAGOPT 4699 } 4700 4701 // Extend the signature with the user build path. 4702 HBuilder.add(hsOpts.ModuleUserBuildPath); 4703 4704 // Extend the signature with the module file extensions. 4705 for (const auto &ext : getFrontendOpts().ModuleFileExtensions) 4706 ext->hashExtension(HBuilder); 4707 4708 // When compiling with -gmodules, also hash -fdebug-prefix-map as it 4709 // affects the debug info in the PCM. 4710 if (getCodeGenOpts().DebugTypeExtRefs) 4711 HBuilder.addRange(getCodeGenOpts().DebugPrefixMap); 4712 4713 // Extend the signature with the enabled sanitizers, if at least one is 4714 // enabled. Sanitizers which cannot affect AST generation aren't hashed. 4715 SanitizerSet SanHash = getLangOpts().Sanitize; 4716 SanHash.clear(getPPTransparentSanitizers()); 4717 if (!SanHash.empty()) 4718 HBuilder.add(SanHash.Mask); 4719 4720 llvm::MD5::MD5Result Result; 4721 HBuilder.getHasher().final(Result); 4722 uint64_t Hash = Result.high() ^ Result.low(); 4723 return toString(llvm::APInt(64, Hash), 36, /*Signed=*/false); 4724 } 4725 4726 void CompilerInvocationBase::generateCC1CommandLine( 4727 ArgumentConsumer Consumer) const { 4728 llvm::Triple T(getTargetOpts().Triple); 4729 4730 GenerateFileSystemArgs(getFileSystemOpts(), Consumer); 4731 GenerateMigratorArgs(getMigratorOpts(), Consumer); 4732 GenerateAnalyzerArgs(getAnalyzerOpts(), Consumer); 4733 GenerateDiagnosticArgs(getDiagnosticOpts(), Consumer, 4734 /*DefaultDiagColor=*/false); 4735 GenerateFrontendArgs(getFrontendOpts(), Consumer, getLangOpts().IsHeaderFile); 4736 GenerateTargetArgs(getTargetOpts(), Consumer); 4737 GenerateHeaderSearchArgs(getHeaderSearchOpts(), Consumer); 4738 GenerateLangArgs(getLangOpts(), Consumer, T, getFrontendOpts().DashX); 4739 GenerateCodeGenArgs(getCodeGenOpts(), Consumer, T, 4740 getFrontendOpts().OutputFile, &getLangOpts()); 4741 GeneratePreprocessorArgs(getPreprocessorOpts(), Consumer, getLangOpts(), 4742 getFrontendOpts(), getCodeGenOpts()); 4743 GeneratePreprocessorOutputArgs(getPreprocessorOutputOpts(), Consumer, 4744 getFrontendOpts().ProgramAction); 4745 GenerateDependencyOutputArgs(getDependencyOutputOpts(), Consumer); 4746 } 4747 4748 std::vector<std::string> CompilerInvocationBase::getCC1CommandLine() const { 4749 std::vector<std::string> Args{"-cc1"}; 4750 generateCC1CommandLine( 4751 [&Args](const Twine &Arg) { Args.push_back(Arg.str()); }); 4752 return Args; 4753 } 4754 4755 void CompilerInvocation::resetNonModularOptions() { 4756 getLangOpts().resetNonModularOptions(); 4757 getPreprocessorOpts().resetNonModularOptions(); 4758 } 4759 4760 void CompilerInvocation::clearImplicitModuleBuildOptions() { 4761 getLangOpts().ImplicitModules = false; 4762 getHeaderSearchOpts().ImplicitModuleMaps = false; 4763 getHeaderSearchOpts().ModuleCachePath.clear(); 4764 getHeaderSearchOpts().ModulesValidateOncePerBuildSession = false; 4765 getHeaderSearchOpts().BuildSessionTimestamp = 0; 4766 // The specific values we canonicalize to for pruning don't affect behaviour, 4767 /// so use the default values so they may be dropped from the command-line. 4768 getHeaderSearchOpts().ModuleCachePruneInterval = 7 * 24 * 60 * 60; 4769 getHeaderSearchOpts().ModuleCachePruneAfter = 31 * 24 * 60 * 60; 4770 } 4771 4772 IntrusiveRefCntPtr<llvm::vfs::FileSystem> 4773 clang::createVFSFromCompilerInvocation(const CompilerInvocation &CI, 4774 DiagnosticsEngine &Diags) { 4775 return createVFSFromCompilerInvocation(CI, Diags, 4776 llvm::vfs::getRealFileSystem()); 4777 } 4778 4779 IntrusiveRefCntPtr<llvm::vfs::FileSystem> 4780 clang::createVFSFromCompilerInvocation( 4781 const CompilerInvocation &CI, DiagnosticsEngine &Diags, 4782 IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS) { 4783 return createVFSFromOverlayFiles(CI.getHeaderSearchOpts().VFSOverlayFiles, 4784 Diags, std::move(BaseFS)); 4785 } 4786 4787 IntrusiveRefCntPtr<llvm::vfs::FileSystem> clang::createVFSFromOverlayFiles( 4788 ArrayRef<std::string> VFSOverlayFiles, DiagnosticsEngine &Diags, 4789 IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS) { 4790 if (VFSOverlayFiles.empty()) 4791 return BaseFS; 4792 4793 IntrusiveRefCntPtr<llvm::vfs::FileSystem> Result = BaseFS; 4794 // earlier vfs files are on the bottom 4795 for (const auto &File : VFSOverlayFiles) { 4796 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer = 4797 Result->getBufferForFile(File); 4798 if (!Buffer) { 4799 Diags.Report(diag::err_missing_vfs_overlay_file) << File; 4800 continue; 4801 } 4802 4803 IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS = llvm::vfs::getVFSFromYAML( 4804 std::move(Buffer.get()), /*DiagHandler*/ nullptr, File, 4805 /*DiagContext*/ nullptr, Result); 4806 if (!FS) { 4807 Diags.Report(diag::err_invalid_vfs_overlay) << File; 4808 continue; 4809 } 4810 4811 Result = FS; 4812 } 4813 return Result; 4814 } 4815