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