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