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