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