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