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