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