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