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