[HLSL][SPIR-V] Add Vulkan to target triple (#76749)
[llvm-project.git] / clang / lib / Frontend / CompilerInvocation.cpp
blobb5e192d54465b174726588a940516b33e070b594
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 //===----------------------------------------------------------------------===//
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/Diagnostic.h"
16 #include "clang/Basic/DiagnosticDriver.h"
17 #include "clang/Basic/DiagnosticOptions.h"
18 #include "clang/Basic/FileSystemOptions.h"
19 #include "clang/Basic/LLVM.h"
20 #include "clang/Basic/LangOptions.h"
21 #include "clang/Basic/LangStandard.h"
22 #include "clang/Basic/ObjCRuntime.h"
23 #include "clang/Basic/Sanitizers.h"
24 #include "clang/Basic/SourceLocation.h"
25 #include "clang/Basic/TargetOptions.h"
26 #include "clang/Basic/Version.h"
27 #include "clang/Basic/Visibility.h"
28 #include "clang/Basic/XRayInstr.h"
29 #include "clang/Config/config.h"
30 #include "clang/Driver/Driver.h"
31 #include "clang/Driver/DriverDiagnostic.h"
32 #include "clang/Driver/Options.h"
33 #include "clang/Frontend/CommandLineSourceLoc.h"
34 #include "clang/Frontend/DependencyOutputOptions.h"
35 #include "clang/Frontend/FrontendDiagnostic.h"
36 #include "clang/Frontend/FrontendOptions.h"
37 #include "clang/Frontend/FrontendPluginRegistry.h"
38 #include "clang/Frontend/MigratorOptions.h"
39 #include "clang/Frontend/PreprocessorOutputOptions.h"
40 #include "clang/Frontend/TextDiagnosticBuffer.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/STLExtras.h"
54 #include "llvm/ADT/SmallString.h"
55 #include "llvm/ADT/SmallVector.h"
56 #include "llvm/ADT/StringRef.h"
57 #include "llvm/ADT/StringSwitch.h"
58 #include "llvm/ADT/Twine.h"
59 #include "llvm/Config/llvm-config.h"
60 #include "llvm/Frontend/Debug/Options.h"
61 #include "llvm/IR/DebugInfoMetadata.h"
62 #include "llvm/Linker/Linker.h"
63 #include "llvm/MC/MCTargetOptions.h"
64 #include "llvm/Option/Arg.h"
65 #include "llvm/Option/ArgList.h"
66 #include "llvm/Option/OptSpecifier.h"
67 #include "llvm/Option/OptTable.h"
68 #include "llvm/Option/Option.h"
69 #include "llvm/ProfileData/InstrProfReader.h"
70 #include "llvm/Remarks/HotnessThresholdParser.h"
71 #include "llvm/Support/CodeGen.h"
72 #include "llvm/Support/Compiler.h"
73 #include "llvm/Support/Error.h"
74 #include "llvm/Support/ErrorHandling.h"
75 #include "llvm/Support/ErrorOr.h"
76 #include "llvm/Support/FileSystem.h"
77 #include "llvm/Support/HashBuilder.h"
78 #include "llvm/Support/MathExtras.h"
79 #include "llvm/Support/MemoryBuffer.h"
80 #include "llvm/Support/Path.h"
81 #include "llvm/Support/Process.h"
82 #include "llvm/Support/Regex.h"
83 #include "llvm/Support/VersionTuple.h"
84 #include "llvm/Support/VirtualFileSystem.h"
85 #include "llvm/Support/raw_ostream.h"
86 #include "llvm/Target/TargetOptions.h"
87 #include "llvm/TargetParser/Host.h"
88 #include "llvm/TargetParser/Triple.h"
89 #include <algorithm>
90 #include <atomic>
91 #include <cassert>
92 #include <cstddef>
93 #include <cstring>
94 #include <ctime>
95 #include <fstream>
96 #include <limits>
97 #include <memory>
98 #include <optional>
99 #include <string>
100 #include <tuple>
101 #include <type_traits>
102 #include <utility>
103 #include <vector>
105 using namespace clang;
106 using namespace driver;
107 using namespace options;
108 using namespace llvm::opt;
110 //===----------------------------------------------------------------------===//
111 // Helpers.
112 //===----------------------------------------------------------------------===//
114 // Parse misexpect tolerance argument value.
115 // Valid option values are integers in the range [0, 100)
116 static Expected<std::optional<uint32_t>> parseToleranceOption(StringRef Arg) {
117 uint32_t Val;
118 if (Arg.getAsInteger(10, Val))
119 return llvm::createStringError(llvm::inconvertibleErrorCode(),
120 "Not an integer: %s", Arg.data());
121 return Val;
124 //===----------------------------------------------------------------------===//
125 // Initialization.
126 //===----------------------------------------------------------------------===//
128 namespace {
129 template <class T> std::shared_ptr<T> make_shared_copy(const T &X) {
130 return std::make_shared<T>(X);
133 template <class T>
134 llvm::IntrusiveRefCntPtr<T> makeIntrusiveRefCntCopy(const T &X) {
135 return llvm::makeIntrusiveRefCnt<T>(X);
137 } // namespace
139 CompilerInvocationBase::CompilerInvocationBase()
140 : LangOpts(std::make_shared<LangOptions>()),
141 TargetOpts(std::make_shared<TargetOptions>()),
142 DiagnosticOpts(llvm::makeIntrusiveRefCnt<DiagnosticOptions>()),
143 HSOpts(std::make_shared<HeaderSearchOptions>()),
144 PPOpts(std::make_shared<PreprocessorOptions>()),
145 AnalyzerOpts(llvm::makeIntrusiveRefCnt<AnalyzerOptions>()),
146 MigratorOpts(std::make_shared<MigratorOptions>()),
147 APINotesOpts(std::make_shared<APINotesOptions>()),
148 CodeGenOpts(std::make_shared<CodeGenOptions>()),
149 FSOpts(std::make_shared<FileSystemOptions>()),
150 FrontendOpts(std::make_shared<FrontendOptions>()),
151 DependencyOutputOpts(std::make_shared<DependencyOutputOptions>()),
152 PreprocessorOutputOpts(std::make_shared<PreprocessorOutputOptions>()) {}
154 CompilerInvocationBase &
155 CompilerInvocationBase::deep_copy_assign(const CompilerInvocationBase &X) {
156 if (this != &X) {
157 LangOpts = make_shared_copy(X.getLangOpts());
158 TargetOpts = make_shared_copy(X.getTargetOpts());
159 DiagnosticOpts = makeIntrusiveRefCntCopy(X.getDiagnosticOpts());
160 HSOpts = make_shared_copy(X.getHeaderSearchOpts());
161 PPOpts = make_shared_copy(X.getPreprocessorOpts());
162 AnalyzerOpts = makeIntrusiveRefCntCopy(X.getAnalyzerOpts());
163 MigratorOpts = make_shared_copy(X.getMigratorOpts());
164 APINotesOpts = make_shared_copy(X.getAPINotesOpts());
165 CodeGenOpts = make_shared_copy(X.getCodeGenOpts());
166 FSOpts = make_shared_copy(X.getFileSystemOpts());
167 FrontendOpts = make_shared_copy(X.getFrontendOpts());
168 DependencyOutputOpts = make_shared_copy(X.getDependencyOutputOpts());
169 PreprocessorOutputOpts = make_shared_copy(X.getPreprocessorOutputOpts());
171 return *this;
174 CompilerInvocationBase &
175 CompilerInvocationBase::shallow_copy_assign(const CompilerInvocationBase &X) {
176 if (this != &X) {
177 LangOpts = X.LangOpts;
178 TargetOpts = X.TargetOpts;
179 DiagnosticOpts = X.DiagnosticOpts;
180 HSOpts = X.HSOpts;
181 PPOpts = X.PPOpts;
182 AnalyzerOpts = X.AnalyzerOpts;
183 MigratorOpts = X.MigratorOpts;
184 APINotesOpts = X.APINotesOpts;
185 CodeGenOpts = X.CodeGenOpts;
186 FSOpts = X.FSOpts;
187 FrontendOpts = X.FrontendOpts;
188 DependencyOutputOpts = X.DependencyOutputOpts;
189 PreprocessorOutputOpts = X.PreprocessorOutputOpts;
191 return *this;
194 namespace {
195 template <typename T>
196 T &ensureOwned(std::shared_ptr<T> &Storage) {
197 if (Storage.use_count() > 1)
198 Storage = std::make_shared<T>(*Storage);
199 return *Storage;
202 template <typename T>
203 T &ensureOwned(llvm::IntrusiveRefCntPtr<T> &Storage) {
204 if (Storage.useCount() > 1)
205 Storage = llvm::makeIntrusiveRefCnt<T>(*Storage);
206 return *Storage;
208 } // namespace
210 LangOptions &CowCompilerInvocation::getMutLangOpts() {
211 return ensureOwned(LangOpts);
214 TargetOptions &CowCompilerInvocation::getMutTargetOpts() {
215 return ensureOwned(TargetOpts);
218 DiagnosticOptions &CowCompilerInvocation::getMutDiagnosticOpts() {
219 return ensureOwned(DiagnosticOpts);
222 HeaderSearchOptions &CowCompilerInvocation::getMutHeaderSearchOpts() {
223 return ensureOwned(HSOpts);
226 PreprocessorOptions &CowCompilerInvocation::getMutPreprocessorOpts() {
227 return ensureOwned(PPOpts);
230 AnalyzerOptions &CowCompilerInvocation::getMutAnalyzerOpts() {
231 return ensureOwned(AnalyzerOpts);
234 MigratorOptions &CowCompilerInvocation::getMutMigratorOpts() {
235 return ensureOwned(MigratorOpts);
238 APINotesOptions &CowCompilerInvocation::getMutAPINotesOpts() {
239 return ensureOwned(APINotesOpts);
242 CodeGenOptions &CowCompilerInvocation::getMutCodeGenOpts() {
243 return ensureOwned(CodeGenOpts);
246 FileSystemOptions &CowCompilerInvocation::getMutFileSystemOpts() {
247 return ensureOwned(FSOpts);
250 FrontendOptions &CowCompilerInvocation::getMutFrontendOpts() {
251 return ensureOwned(FrontendOpts);
254 DependencyOutputOptions &CowCompilerInvocation::getMutDependencyOutputOpts() {
255 return ensureOwned(DependencyOutputOpts);
258 PreprocessorOutputOptions &
259 CowCompilerInvocation::getMutPreprocessorOutputOpts() {
260 return ensureOwned(PreprocessorOutputOpts);
263 //===----------------------------------------------------------------------===//
264 // Normalizers
265 //===----------------------------------------------------------------------===//
267 using ArgumentConsumer = CompilerInvocation::ArgumentConsumer;
269 #define SIMPLE_ENUM_VALUE_TABLE
270 #include "clang/Driver/Options.inc"
271 #undef SIMPLE_ENUM_VALUE_TABLE
273 static std::optional<bool> normalizeSimpleFlag(OptSpecifier Opt,
274 unsigned TableIndex,
275 const ArgList &Args,
276 DiagnosticsEngine &Diags) {
277 if (Args.hasArg(Opt))
278 return true;
279 return std::nullopt;
282 static std::optional<bool> normalizeSimpleNegativeFlag(OptSpecifier Opt,
283 unsigned,
284 const ArgList &Args,
285 DiagnosticsEngine &) {
286 if (Args.hasArg(Opt))
287 return false;
288 return std::nullopt;
291 /// The tblgen-erated code passes in a fifth parameter of an arbitrary type, but
292 /// denormalizeSimpleFlags never looks at it. Avoid bloating compile-time with
293 /// unnecessary template instantiations and just ignore it with a variadic
294 /// argument.
295 static void denormalizeSimpleFlag(ArgumentConsumer Consumer,
296 const Twine &Spelling, Option::OptionClass,
297 unsigned, /*T*/...) {
298 Consumer(Spelling);
301 template <typename T> static constexpr bool is_uint64_t_convertible() {
302 return !std::is_same_v<T, uint64_t> && llvm::is_integral_or_enum<T>::value;
305 template <typename T,
306 std::enable_if_t<!is_uint64_t_convertible<T>(), bool> = false>
307 static auto makeFlagToValueNormalizer(T Value) {
308 return [Value](OptSpecifier Opt, unsigned, const ArgList &Args,
309 DiagnosticsEngine &) -> std::optional<T> {
310 if (Args.hasArg(Opt))
311 return Value;
312 return std::nullopt;
316 template <typename T,
317 std::enable_if_t<is_uint64_t_convertible<T>(), bool> = false>
318 static auto makeFlagToValueNormalizer(T Value) {
319 return makeFlagToValueNormalizer(uint64_t(Value));
322 static auto makeBooleanOptionNormalizer(bool Value, bool OtherValue,
323 OptSpecifier OtherOpt) {
324 return [Value, OtherValue,
325 OtherOpt](OptSpecifier Opt, unsigned, const ArgList &Args,
326 DiagnosticsEngine &) -> std::optional<bool> {
327 if (const Arg *A = Args.getLastArg(Opt, OtherOpt)) {
328 return A->getOption().matches(Opt) ? Value : OtherValue;
330 return std::nullopt;
334 static auto makeBooleanOptionDenormalizer(bool Value) {
335 return [Value](ArgumentConsumer Consumer, const Twine &Spelling,
336 Option::OptionClass, unsigned, bool KeyPath) {
337 if (KeyPath == Value)
338 Consumer(Spelling);
342 static void denormalizeStringImpl(ArgumentConsumer Consumer,
343 const Twine &Spelling,
344 Option::OptionClass OptClass, unsigned,
345 const Twine &Value) {
346 switch (OptClass) {
347 case Option::SeparateClass:
348 case Option::JoinedOrSeparateClass:
349 case Option::JoinedAndSeparateClass:
350 Consumer(Spelling);
351 Consumer(Value);
352 break;
353 case Option::JoinedClass:
354 case Option::CommaJoinedClass:
355 Consumer(Spelling + Value);
356 break;
357 default:
358 llvm_unreachable("Cannot denormalize an option with option class "
359 "incompatible with string denormalization.");
363 template <typename T>
364 static void denormalizeString(ArgumentConsumer Consumer, const Twine &Spelling,
365 Option::OptionClass OptClass, unsigned TableIndex,
366 T Value) {
367 denormalizeStringImpl(Consumer, Spelling, OptClass, TableIndex, Twine(Value));
370 static std::optional<SimpleEnumValue>
371 findValueTableByName(const SimpleEnumValueTable &Table, StringRef Name) {
372 for (int I = 0, E = Table.Size; I != E; ++I)
373 if (Name == Table.Table[I].Name)
374 return Table.Table[I];
376 return std::nullopt;
379 static std::optional<SimpleEnumValue>
380 findValueTableByValue(const SimpleEnumValueTable &Table, unsigned Value) {
381 for (int I = 0, E = Table.Size; I != E; ++I)
382 if (Value == Table.Table[I].Value)
383 return Table.Table[I];
385 return std::nullopt;
388 static std::optional<unsigned> normalizeSimpleEnum(OptSpecifier Opt,
389 unsigned TableIndex,
390 const ArgList &Args,
391 DiagnosticsEngine &Diags) {
392 assert(TableIndex < SimpleEnumValueTablesSize);
393 const SimpleEnumValueTable &Table = SimpleEnumValueTables[TableIndex];
395 auto *Arg = Args.getLastArg(Opt);
396 if (!Arg)
397 return std::nullopt;
399 StringRef ArgValue = Arg->getValue();
400 if (auto MaybeEnumVal = findValueTableByName(Table, ArgValue))
401 return MaybeEnumVal->Value;
403 Diags.Report(diag::err_drv_invalid_value)
404 << Arg->getAsString(Args) << ArgValue;
405 return std::nullopt;
408 static void denormalizeSimpleEnumImpl(ArgumentConsumer Consumer,
409 const Twine &Spelling,
410 Option::OptionClass OptClass,
411 unsigned TableIndex, unsigned Value) {
412 assert(TableIndex < SimpleEnumValueTablesSize);
413 const SimpleEnumValueTable &Table = SimpleEnumValueTables[TableIndex];
414 if (auto MaybeEnumVal = findValueTableByValue(Table, Value)) {
415 denormalizeString(Consumer, Spelling, OptClass, TableIndex,
416 MaybeEnumVal->Name);
417 } else {
418 llvm_unreachable("The simple enum value was not correctly defined in "
419 "the tablegen option description");
423 template <typename T>
424 static void denormalizeSimpleEnum(ArgumentConsumer Consumer,
425 const Twine &Spelling,
426 Option::OptionClass OptClass,
427 unsigned TableIndex, T Value) {
428 return denormalizeSimpleEnumImpl(Consumer, Spelling, OptClass, TableIndex,
429 static_cast<unsigned>(Value));
432 static std::optional<std::string> normalizeString(OptSpecifier Opt,
433 int TableIndex,
434 const ArgList &Args,
435 DiagnosticsEngine &Diags) {
436 auto *Arg = Args.getLastArg(Opt);
437 if (!Arg)
438 return std::nullopt;
439 return std::string(Arg->getValue());
442 template <typename IntTy>
443 static std::optional<IntTy> normalizeStringIntegral(OptSpecifier Opt, int,
444 const ArgList &Args,
445 DiagnosticsEngine &Diags) {
446 auto *Arg = Args.getLastArg(Opt);
447 if (!Arg)
448 return std::nullopt;
449 IntTy Res;
450 if (StringRef(Arg->getValue()).getAsInteger(0, Res)) {
451 Diags.Report(diag::err_drv_invalid_int_value)
452 << Arg->getAsString(Args) << Arg->getValue();
453 return std::nullopt;
455 return Res;
458 static std::optional<std::vector<std::string>>
459 normalizeStringVector(OptSpecifier Opt, int, const ArgList &Args,
460 DiagnosticsEngine &) {
461 return Args.getAllArgValues(Opt);
464 static void denormalizeStringVector(ArgumentConsumer Consumer,
465 const Twine &Spelling,
466 Option::OptionClass OptClass,
467 unsigned TableIndex,
468 const std::vector<std::string> &Values) {
469 switch (OptClass) {
470 case Option::CommaJoinedClass: {
471 std::string CommaJoinedValue;
472 if (!Values.empty()) {
473 CommaJoinedValue.append(Values.front());
474 for (const std::string &Value : llvm::drop_begin(Values, 1)) {
475 CommaJoinedValue.append(",");
476 CommaJoinedValue.append(Value);
479 denormalizeString(Consumer, Spelling, Option::OptionClass::JoinedClass,
480 TableIndex, CommaJoinedValue);
481 break;
483 case Option::JoinedClass:
484 case Option::SeparateClass:
485 case Option::JoinedOrSeparateClass:
486 for (const std::string &Value : Values)
487 denormalizeString(Consumer, Spelling, OptClass, TableIndex, Value);
488 break;
489 default:
490 llvm_unreachable("Cannot denormalize an option with option class "
491 "incompatible with string vector denormalization.");
495 static std::optional<std::string> normalizeTriple(OptSpecifier Opt,
496 int TableIndex,
497 const ArgList &Args,
498 DiagnosticsEngine &Diags) {
499 auto *Arg = Args.getLastArg(Opt);
500 if (!Arg)
501 return std::nullopt;
502 return llvm::Triple::normalize(Arg->getValue());
505 template <typename T, typename U>
506 static T mergeForwardValue(T KeyPath, U Value) {
507 return static_cast<T>(Value);
510 template <typename T, typename U> static T mergeMaskValue(T KeyPath, U Value) {
511 return KeyPath | Value;
514 template <typename T> static T extractForwardValue(T KeyPath) {
515 return KeyPath;
518 template <typename T, typename U, U Value>
519 static T extractMaskValue(T KeyPath) {
520 return ((KeyPath & Value) == Value) ? static_cast<T>(Value) : T();
523 #define PARSE_OPTION_WITH_MARSHALLING( \
524 ARGS, DIAGS, PREFIX_TYPE, SPELLING, ID, KIND, GROUP, ALIAS, ALIASARGS, \
525 FLAGS, VISIBILITY, PARAM, HELPTEXT, METAVAR, VALUES, SHOULD_PARSE, \
526 ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, \
527 NORMALIZER, DENORMALIZER, MERGER, EXTRACTOR, TABLE_INDEX) \
528 if ((VISIBILITY)&options::CC1Option) { \
529 KEYPATH = MERGER(KEYPATH, DEFAULT_VALUE); \
530 if (IMPLIED_CHECK) \
531 KEYPATH = MERGER(KEYPATH, IMPLIED_VALUE); \
532 if (SHOULD_PARSE) \
533 if (auto MaybeValue = NORMALIZER(OPT_##ID, TABLE_INDEX, ARGS, DIAGS)) \
534 KEYPATH = \
535 MERGER(KEYPATH, static_cast<decltype(KEYPATH)>(*MaybeValue)); \
538 // Capture the extracted value as a lambda argument to avoid potential issues
539 // with lifetime extension of the reference.
540 #define GENERATE_OPTION_WITH_MARSHALLING( \
541 CONSUMER, PREFIX_TYPE, SPELLING, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, \
542 VISIBILITY, PARAM, HELPTEXT, METAVAR, VALUES, SHOULD_PARSE, ALWAYS_EMIT, \
543 KEYPATH, DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, \
544 DENORMALIZER, MERGER, EXTRACTOR, TABLE_INDEX) \
545 if ((VISIBILITY)&options::CC1Option) { \
546 [&](const auto &Extracted) { \
547 if (ALWAYS_EMIT || \
548 (Extracted != \
549 static_cast<decltype(KEYPATH)>((IMPLIED_CHECK) ? (IMPLIED_VALUE) \
550 : (DEFAULT_VALUE)))) \
551 DENORMALIZER(CONSUMER, SPELLING, Option::KIND##Class, TABLE_INDEX, \
552 Extracted); \
553 }(EXTRACTOR(KEYPATH)); \
556 static StringRef GetInputKindName(InputKind IK);
558 static bool FixupInvocation(CompilerInvocation &Invocation,
559 DiagnosticsEngine &Diags, const ArgList &Args,
560 InputKind IK) {
561 unsigned NumErrorsBefore = Diags.getNumErrors();
563 LangOptions &LangOpts = Invocation.getLangOpts();
564 CodeGenOptions &CodeGenOpts = Invocation.getCodeGenOpts();
565 TargetOptions &TargetOpts = Invocation.getTargetOpts();
566 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
567 CodeGenOpts.XRayInstrumentFunctions = LangOpts.XRayInstrument;
568 CodeGenOpts.XRayAlwaysEmitCustomEvents = LangOpts.XRayAlwaysEmitCustomEvents;
569 CodeGenOpts.XRayAlwaysEmitTypedEvents = LangOpts.XRayAlwaysEmitTypedEvents;
570 CodeGenOpts.DisableFree = FrontendOpts.DisableFree;
571 FrontendOpts.GenerateGlobalModuleIndex = FrontendOpts.UseGlobalModuleIndex;
572 if (FrontendOpts.ShowStats)
573 CodeGenOpts.ClearASTBeforeBackend = false;
574 LangOpts.SanitizeCoverage = CodeGenOpts.hasSanitizeCoverage();
575 LangOpts.ForceEmitVTables = CodeGenOpts.ForceEmitVTables;
576 LangOpts.SpeculativeLoadHardening = CodeGenOpts.SpeculativeLoadHardening;
577 LangOpts.CurrentModule = LangOpts.ModuleName;
579 llvm::Triple T(TargetOpts.Triple);
580 llvm::Triple::ArchType Arch = T.getArch();
582 CodeGenOpts.CodeModel = TargetOpts.CodeModel;
583 CodeGenOpts.LargeDataThreshold = TargetOpts.LargeDataThreshold;
585 if (LangOpts.getExceptionHandling() !=
586 LangOptions::ExceptionHandlingKind::None &&
587 T.isWindowsMSVCEnvironment())
588 Diags.Report(diag::err_fe_invalid_exception_model)
589 << static_cast<unsigned>(LangOpts.getExceptionHandling()) << T.str();
591 if (LangOpts.AppleKext && !LangOpts.CPlusPlus)
592 Diags.Report(diag::warn_c_kext);
594 if (LangOpts.NewAlignOverride &&
595 !llvm::isPowerOf2_32(LangOpts.NewAlignOverride)) {
596 Arg *A = Args.getLastArg(OPT_fnew_alignment_EQ);
597 Diags.Report(diag::err_fe_invalid_alignment)
598 << A->getAsString(Args) << A->getValue();
599 LangOpts.NewAlignOverride = 0;
602 // Prevent the user from specifying both -fsycl-is-device and -fsycl-is-host.
603 if (LangOpts.SYCLIsDevice && LangOpts.SYCLIsHost)
604 Diags.Report(diag::err_drv_argument_not_allowed_with) << "-fsycl-is-device"
605 << "-fsycl-is-host";
607 if (Args.hasArg(OPT_fgnu89_inline) && LangOpts.CPlusPlus)
608 Diags.Report(diag::err_drv_argument_not_allowed_with)
609 << "-fgnu89-inline" << GetInputKindName(IK);
611 if (Args.hasArg(OPT_hlsl_entrypoint) && !LangOpts.HLSL)
612 Diags.Report(diag::err_drv_argument_not_allowed_with)
613 << "-hlsl-entry" << GetInputKindName(IK);
615 if (Args.hasArg(OPT_fgpu_allow_device_init) && !LangOpts.HIP)
616 Diags.Report(diag::warn_ignored_hip_only_option)
617 << Args.getLastArg(OPT_fgpu_allow_device_init)->getAsString(Args);
619 if (Args.hasArg(OPT_gpu_max_threads_per_block_EQ) && !LangOpts.HIP)
620 Diags.Report(diag::warn_ignored_hip_only_option)
621 << Args.getLastArg(OPT_gpu_max_threads_per_block_EQ)->getAsString(Args);
623 // When these options are used, the compiler is allowed to apply
624 // optimizations that may affect the final result. For example
625 // (x+y)+z is transformed to x+(y+z) but may not give the same
626 // final result; it's not value safe.
627 // Another example can be to simplify x/x to 1.0 but x could be 0.0, INF
628 // or NaN. Final result may then differ. An error is issued when the eval
629 // method is set with one of these options.
630 if (Args.hasArg(OPT_ffp_eval_method_EQ)) {
631 if (LangOpts.ApproxFunc)
632 Diags.Report(diag::err_incompatible_fp_eval_method_options) << 0;
633 if (LangOpts.AllowFPReassoc)
634 Diags.Report(diag::err_incompatible_fp_eval_method_options) << 1;
635 if (LangOpts.AllowRecip)
636 Diags.Report(diag::err_incompatible_fp_eval_method_options) << 2;
639 // -cl-strict-aliasing needs to emit diagnostic in the case where CL > 1.0.
640 // This option should be deprecated for CL > 1.0 because
641 // this option was added for compatibility with OpenCL 1.0.
642 if (Args.getLastArg(OPT_cl_strict_aliasing) &&
643 (LangOpts.getOpenCLCompatibleVersion() > 100))
644 Diags.Report(diag::warn_option_invalid_ocl_version)
645 << LangOpts.getOpenCLVersionString()
646 << Args.getLastArg(OPT_cl_strict_aliasing)->getAsString(Args);
648 if (Arg *A = Args.getLastArg(OPT_fdefault_calling_conv_EQ)) {
649 auto DefaultCC = LangOpts.getDefaultCallingConv();
651 bool emitError = (DefaultCC == LangOptions::DCC_FastCall ||
652 DefaultCC == LangOptions::DCC_StdCall) &&
653 Arch != llvm::Triple::x86;
654 emitError |= (DefaultCC == LangOptions::DCC_VectorCall ||
655 DefaultCC == LangOptions::DCC_RegCall) &&
656 !T.isX86();
657 emitError |= DefaultCC == LangOptions::DCC_RtdCall && Arch != llvm::Triple::m68k;
658 if (emitError)
659 Diags.Report(diag::err_drv_argument_not_allowed_with)
660 << A->getSpelling() << T.getTriple();
663 return Diags.getNumErrors() == NumErrorsBefore;
666 //===----------------------------------------------------------------------===//
667 // Deserialization (from args)
668 //===----------------------------------------------------------------------===//
670 static unsigned getOptimizationLevel(ArgList &Args, InputKind IK,
671 DiagnosticsEngine &Diags) {
672 unsigned DefaultOpt = 0;
673 if ((IK.getLanguage() == Language::OpenCL ||
674 IK.getLanguage() == Language::OpenCLCXX) &&
675 !Args.hasArg(OPT_cl_opt_disable))
676 DefaultOpt = 2;
678 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
679 if (A->getOption().matches(options::OPT_O0))
680 return 0;
682 if (A->getOption().matches(options::OPT_Ofast))
683 return 3;
685 assert(A->getOption().matches(options::OPT_O));
687 StringRef S(A->getValue());
688 if (S == "s" || S == "z")
689 return 2;
691 if (S == "g")
692 return 1;
694 return getLastArgIntValue(Args, OPT_O, DefaultOpt, Diags);
697 return DefaultOpt;
700 static unsigned getOptimizationLevelSize(ArgList &Args) {
701 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
702 if (A->getOption().matches(options::OPT_O)) {
703 switch (A->getValue()[0]) {
704 default:
705 return 0;
706 case 's':
707 return 1;
708 case 'z':
709 return 2;
713 return 0;
716 static void GenerateArg(ArgumentConsumer Consumer,
717 llvm::opt::OptSpecifier OptSpecifier) {
718 Option Opt = getDriverOptTable().getOption(OptSpecifier);
719 denormalizeSimpleFlag(Consumer, Opt.getPrefixedName(),
720 Option::OptionClass::FlagClass, 0);
723 static void GenerateArg(ArgumentConsumer Consumer,
724 llvm::opt::OptSpecifier OptSpecifier,
725 const Twine &Value) {
726 Option Opt = getDriverOptTable().getOption(OptSpecifier);
727 denormalizeString(Consumer, Opt.getPrefixedName(), Opt.getKind(), 0, Value);
730 // Parse command line arguments into CompilerInvocation.
731 using ParseFn =
732 llvm::function_ref<bool(CompilerInvocation &, ArrayRef<const char *>,
733 DiagnosticsEngine &, const char *)>;
735 // Generate command line arguments from CompilerInvocation.
736 using GenerateFn = llvm::function_ref<void(
737 CompilerInvocation &, SmallVectorImpl<const char *> &,
738 CompilerInvocation::StringAllocator)>;
740 /// May perform round-trip of command line arguments. By default, the round-trip
741 /// is enabled in assert builds. This can be overwritten at run-time via the
742 /// "-round-trip-args" and "-no-round-trip-args" command line flags, or via the
743 /// ForceRoundTrip parameter.
745 /// During round-trip, the command line arguments are parsed into a dummy
746 /// CompilerInvocation, which is used to generate the command line arguments
747 /// again. The real CompilerInvocation is then created by parsing the generated
748 /// arguments, not the original ones. This (in combination with tests covering
749 /// argument behavior) ensures the generated command line is complete (doesn't
750 /// drop/mangle any arguments).
752 /// Finally, we check the command line that was used to create the real
753 /// CompilerInvocation instance. By default, we compare it to the command line
754 /// the real CompilerInvocation generates. This checks whether the generator is
755 /// deterministic. If \p CheckAgainstOriginalInvocation is enabled, we instead
756 /// compare it to the original command line to verify the original command-line
757 /// was canonical and can round-trip exactly.
758 static bool RoundTrip(ParseFn Parse, GenerateFn Generate,
759 CompilerInvocation &RealInvocation,
760 CompilerInvocation &DummyInvocation,
761 ArrayRef<const char *> CommandLineArgs,
762 DiagnosticsEngine &Diags, const char *Argv0,
763 bool CheckAgainstOriginalInvocation = false,
764 bool ForceRoundTrip = false) {
765 #ifndef NDEBUG
766 bool DoRoundTripDefault = true;
767 #else
768 bool DoRoundTripDefault = false;
769 #endif
771 bool DoRoundTrip = DoRoundTripDefault;
772 if (ForceRoundTrip) {
773 DoRoundTrip = true;
774 } else {
775 for (const auto *Arg : CommandLineArgs) {
776 if (Arg == StringRef("-round-trip-args"))
777 DoRoundTrip = true;
778 if (Arg == StringRef("-no-round-trip-args"))
779 DoRoundTrip = false;
783 // If round-trip was not requested, simply run the parser with the real
784 // invocation diagnostics.
785 if (!DoRoundTrip)
786 return Parse(RealInvocation, CommandLineArgs, Diags, Argv0);
788 // Serializes quoted (and potentially escaped) arguments.
789 auto SerializeArgs = [](ArrayRef<const char *> Args) {
790 std::string Buffer;
791 llvm::raw_string_ostream OS(Buffer);
792 for (const char *Arg : Args) {
793 llvm::sys::printArg(OS, Arg, /*Quote=*/true);
794 OS << ' ';
796 OS.flush();
797 return Buffer;
800 // Setup a dummy DiagnosticsEngine.
801 DiagnosticsEngine DummyDiags(new DiagnosticIDs(), new DiagnosticOptions());
802 DummyDiags.setClient(new TextDiagnosticBuffer());
804 // Run the first parse on the original arguments with the dummy invocation and
805 // diagnostics.
806 if (!Parse(DummyInvocation, CommandLineArgs, DummyDiags, Argv0) ||
807 DummyDiags.getNumWarnings() != 0) {
808 // If the first parse did not succeed, it must be user mistake (invalid
809 // command line arguments). We won't be able to generate arguments that
810 // would reproduce the same result. Let's fail again with the real
811 // invocation and diagnostics, so all side-effects of parsing are visible.
812 unsigned NumWarningsBefore = Diags.getNumWarnings();
813 auto Success = Parse(RealInvocation, CommandLineArgs, Diags, Argv0);
814 if (!Success || Diags.getNumWarnings() != NumWarningsBefore)
815 return Success;
817 // Parse with original options and diagnostics succeeded even though it
818 // shouldn't have. Something is off.
819 Diags.Report(diag::err_cc1_round_trip_fail_then_ok);
820 Diags.Report(diag::note_cc1_round_trip_original)
821 << SerializeArgs(CommandLineArgs);
822 return false;
825 // Setup string allocator.
826 llvm::BumpPtrAllocator Alloc;
827 llvm::StringSaver StringPool(Alloc);
828 auto SA = [&StringPool](const Twine &Arg) {
829 return StringPool.save(Arg).data();
832 // Generate arguments from the dummy invocation. If Generate is the
833 // inverse of Parse, the newly generated arguments must have the same
834 // semantics as the original.
835 SmallVector<const char *> GeneratedArgs;
836 Generate(DummyInvocation, GeneratedArgs, SA);
838 // Run the second parse, now on the generated arguments, and with the real
839 // invocation and diagnostics. The result is what we will end up using for the
840 // rest of compilation, so if Generate is not inverse of Parse, something down
841 // the line will break.
842 bool Success2 = Parse(RealInvocation, GeneratedArgs, Diags, Argv0);
844 // The first parse on original arguments succeeded, but second parse of
845 // generated arguments failed. Something must be wrong with the generator.
846 if (!Success2) {
847 Diags.Report(diag::err_cc1_round_trip_ok_then_fail);
848 Diags.Report(diag::note_cc1_round_trip_generated)
849 << 1 << SerializeArgs(GeneratedArgs);
850 return false;
853 SmallVector<const char *> ComparisonArgs;
854 if (CheckAgainstOriginalInvocation)
855 // Compare against original arguments.
856 ComparisonArgs.assign(CommandLineArgs.begin(), CommandLineArgs.end());
857 else
858 // Generate arguments again, this time from the options we will end up using
859 // for the rest of the compilation.
860 Generate(RealInvocation, ComparisonArgs, SA);
862 // Compares two lists of arguments.
863 auto Equal = [](const ArrayRef<const char *> A,
864 const ArrayRef<const char *> B) {
865 return std::equal(A.begin(), A.end(), B.begin(), B.end(),
866 [](const char *AElem, const char *BElem) {
867 return StringRef(AElem) == StringRef(BElem);
871 // If we generated different arguments from what we assume are two
872 // semantically equivalent CompilerInvocations, the Generate function may
873 // be non-deterministic.
874 if (!Equal(GeneratedArgs, ComparisonArgs)) {
875 Diags.Report(diag::err_cc1_round_trip_mismatch);
876 Diags.Report(diag::note_cc1_round_trip_generated)
877 << 1 << SerializeArgs(GeneratedArgs);
878 Diags.Report(diag::note_cc1_round_trip_generated)
879 << 2 << SerializeArgs(ComparisonArgs);
880 return false;
883 Diags.Report(diag::remark_cc1_round_trip_generated)
884 << 1 << SerializeArgs(GeneratedArgs);
885 Diags.Report(diag::remark_cc1_round_trip_generated)
886 << 2 << SerializeArgs(ComparisonArgs);
888 return Success2;
891 bool CompilerInvocation::checkCC1RoundTrip(ArrayRef<const char *> Args,
892 DiagnosticsEngine &Diags,
893 const char *Argv0) {
894 CompilerInvocation DummyInvocation1, DummyInvocation2;
895 return RoundTrip(
896 [](CompilerInvocation &Invocation, ArrayRef<const char *> CommandLineArgs,
897 DiagnosticsEngine &Diags, const char *Argv0) {
898 return CreateFromArgsImpl(Invocation, CommandLineArgs, Diags, Argv0);
900 [](CompilerInvocation &Invocation, SmallVectorImpl<const char *> &Args,
901 StringAllocator SA) {
902 Args.push_back("-cc1");
903 Invocation.generateCC1CommandLine(Args, SA);
905 DummyInvocation1, DummyInvocation2, Args, Diags, Argv0,
906 /*CheckAgainstOriginalInvocation=*/true, /*ForceRoundTrip=*/true);
909 static void addDiagnosticArgs(ArgList &Args, OptSpecifier Group,
910 OptSpecifier GroupWithValue,
911 std::vector<std::string> &Diagnostics) {
912 for (auto *A : Args.filtered(Group)) {
913 if (A->getOption().getKind() == Option::FlagClass) {
914 // The argument is a pure flag (such as OPT_Wall or OPT_Wdeprecated). Add
915 // its name (minus the "W" or "R" at the beginning) to the diagnostics.
916 Diagnostics.push_back(
917 std::string(A->getOption().getName().drop_front(1)));
918 } else if (A->getOption().matches(GroupWithValue)) {
919 // This is -Wfoo= or -Rfoo=, where foo is the name of the diagnostic
920 // group. Add only the group name to the diagnostics.
921 Diagnostics.push_back(
922 std::string(A->getOption().getName().drop_front(1).rtrim("=-")));
923 } else {
924 // Otherwise, add its value (for OPT_W_Joined and similar).
925 Diagnostics.push_back(A->getValue());
930 // Parse the Static Analyzer configuration. If \p Diags is set to nullptr,
931 // it won't verify the input.
932 static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts,
933 DiagnosticsEngine *Diags);
935 static void getAllNoBuiltinFuncValues(ArgList &Args,
936 std::vector<std::string> &Funcs) {
937 std::vector<std::string> Values = Args.getAllArgValues(OPT_fno_builtin_);
938 auto BuiltinEnd = llvm::partition(Values, Builtin::Context::isBuiltinFunc);
939 Funcs.insert(Funcs.end(), Values.begin(), BuiltinEnd);
942 static void GenerateAnalyzerArgs(const AnalyzerOptions &Opts,
943 ArgumentConsumer Consumer) {
944 const AnalyzerOptions *AnalyzerOpts = &Opts;
946 #define ANALYZER_OPTION_WITH_MARSHALLING(...) \
947 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
948 #include "clang/Driver/Options.inc"
949 #undef ANALYZER_OPTION_WITH_MARSHALLING
951 if (Opts.AnalysisConstraintsOpt != RangeConstraintsModel) {
952 switch (Opts.AnalysisConstraintsOpt) {
953 #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \
954 case NAME##Model: \
955 GenerateArg(Consumer, OPT_analyzer_constraints, CMDFLAG); \
956 break;
957 #include "clang/StaticAnalyzer/Core/Analyses.def"
958 default:
959 llvm_unreachable("Tried to generate unknown analysis constraint.");
963 if (Opts.AnalysisDiagOpt != PD_HTML) {
964 switch (Opts.AnalysisDiagOpt) {
965 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \
966 case PD_##NAME: \
967 GenerateArg(Consumer, OPT_analyzer_output, CMDFLAG); \
968 break;
969 #include "clang/StaticAnalyzer/Core/Analyses.def"
970 default:
971 llvm_unreachable("Tried to generate unknown analysis diagnostic client.");
975 if (Opts.AnalysisPurgeOpt != PurgeStmt) {
976 switch (Opts.AnalysisPurgeOpt) {
977 #define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \
978 case NAME: \
979 GenerateArg(Consumer, OPT_analyzer_purge, CMDFLAG); \
980 break;
981 #include "clang/StaticAnalyzer/Core/Analyses.def"
982 default:
983 llvm_unreachable("Tried to generate unknown analysis purge mode.");
987 if (Opts.InliningMode != NoRedundancy) {
988 switch (Opts.InliningMode) {
989 #define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \
990 case NAME: \
991 GenerateArg(Consumer, OPT_analyzer_inlining_mode, CMDFLAG); \
992 break;
993 #include "clang/StaticAnalyzer/Core/Analyses.def"
994 default:
995 llvm_unreachable("Tried to generate unknown analysis inlining mode.");
999 for (const auto &CP : Opts.CheckersAndPackages) {
1000 OptSpecifier Opt =
1001 CP.second ? OPT_analyzer_checker : OPT_analyzer_disable_checker;
1002 GenerateArg(Consumer, Opt, CP.first);
1005 AnalyzerOptions ConfigOpts;
1006 parseAnalyzerConfigs(ConfigOpts, nullptr);
1008 // Sort options by key to avoid relying on StringMap iteration order.
1009 SmallVector<std::pair<StringRef, StringRef>, 4> SortedConfigOpts;
1010 for (const auto &C : Opts.Config)
1011 SortedConfigOpts.emplace_back(C.getKey(), C.getValue());
1012 llvm::sort(SortedConfigOpts, llvm::less_first());
1014 for (const auto &[Key, Value] : SortedConfigOpts) {
1015 // Don't generate anything that came from parseAnalyzerConfigs. It would be
1016 // redundant and may not be valid on the command line.
1017 auto Entry = ConfigOpts.Config.find(Key);
1018 if (Entry != ConfigOpts.Config.end() && Entry->getValue() == Value)
1019 continue;
1021 GenerateArg(Consumer, OPT_analyzer_config, Key + "=" + Value);
1024 // Nothing to generate for FullCompilerInvocation.
1027 static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args,
1028 DiagnosticsEngine &Diags) {
1029 unsigned NumErrorsBefore = Diags.getNumErrors();
1031 AnalyzerOptions *AnalyzerOpts = &Opts;
1033 #define ANALYZER_OPTION_WITH_MARSHALLING(...) \
1034 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
1035 #include "clang/Driver/Options.inc"
1036 #undef ANALYZER_OPTION_WITH_MARSHALLING
1038 if (Arg *A = Args.getLastArg(OPT_analyzer_constraints)) {
1039 StringRef Name = A->getValue();
1040 AnalysisConstraints Value = llvm::StringSwitch<AnalysisConstraints>(Name)
1041 #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \
1042 .Case(CMDFLAG, NAME##Model)
1043 #include "clang/StaticAnalyzer/Core/Analyses.def"
1044 .Default(NumConstraints);
1045 if (Value == NumConstraints) {
1046 Diags.Report(diag::err_drv_invalid_value)
1047 << A->getAsString(Args) << Name;
1048 } else {
1049 #ifndef LLVM_WITH_Z3
1050 if (Value == AnalysisConstraints::Z3ConstraintsModel) {
1051 Diags.Report(diag::err_analyzer_not_built_with_z3);
1053 #endif // LLVM_WITH_Z3
1054 Opts.AnalysisConstraintsOpt = Value;
1058 if (Arg *A = Args.getLastArg(OPT_analyzer_output)) {
1059 StringRef Name = A->getValue();
1060 AnalysisDiagClients Value = llvm::StringSwitch<AnalysisDiagClients>(Name)
1061 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \
1062 .Case(CMDFLAG, PD_##NAME)
1063 #include "clang/StaticAnalyzer/Core/Analyses.def"
1064 .Default(NUM_ANALYSIS_DIAG_CLIENTS);
1065 if (Value == NUM_ANALYSIS_DIAG_CLIENTS) {
1066 Diags.Report(diag::err_drv_invalid_value)
1067 << A->getAsString(Args) << Name;
1068 } else {
1069 Opts.AnalysisDiagOpt = Value;
1073 if (Arg *A = Args.getLastArg(OPT_analyzer_purge)) {
1074 StringRef Name = A->getValue();
1075 AnalysisPurgeMode Value = llvm::StringSwitch<AnalysisPurgeMode>(Name)
1076 #define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \
1077 .Case(CMDFLAG, NAME)
1078 #include "clang/StaticAnalyzer/Core/Analyses.def"
1079 .Default(NumPurgeModes);
1080 if (Value == NumPurgeModes) {
1081 Diags.Report(diag::err_drv_invalid_value)
1082 << A->getAsString(Args) << Name;
1083 } else {
1084 Opts.AnalysisPurgeOpt = Value;
1088 if (Arg *A = Args.getLastArg(OPT_analyzer_inlining_mode)) {
1089 StringRef Name = A->getValue();
1090 AnalysisInliningMode Value = llvm::StringSwitch<AnalysisInliningMode>(Name)
1091 #define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \
1092 .Case(CMDFLAG, NAME)
1093 #include "clang/StaticAnalyzer/Core/Analyses.def"
1094 .Default(NumInliningModes);
1095 if (Value == NumInliningModes) {
1096 Diags.Report(diag::err_drv_invalid_value)
1097 << A->getAsString(Args) << Name;
1098 } else {
1099 Opts.InliningMode = Value;
1103 Opts.CheckersAndPackages.clear();
1104 for (const Arg *A :
1105 Args.filtered(OPT_analyzer_checker, OPT_analyzer_disable_checker)) {
1106 A->claim();
1107 bool IsEnabled = A->getOption().getID() == OPT_analyzer_checker;
1108 // We can have a list of comma separated checker names, e.g:
1109 // '-analyzer-checker=cocoa,unix'
1110 StringRef CheckerAndPackageList = A->getValue();
1111 SmallVector<StringRef, 16> CheckersAndPackages;
1112 CheckerAndPackageList.split(CheckersAndPackages, ",");
1113 for (const StringRef &CheckerOrPackage : CheckersAndPackages)
1114 Opts.CheckersAndPackages.emplace_back(std::string(CheckerOrPackage),
1115 IsEnabled);
1118 // Go through the analyzer configuration options.
1119 for (const auto *A : Args.filtered(OPT_analyzer_config)) {
1121 // We can have a list of comma separated config names, e.g:
1122 // '-analyzer-config key1=val1,key2=val2'
1123 StringRef configList = A->getValue();
1124 SmallVector<StringRef, 4> configVals;
1125 configList.split(configVals, ",");
1126 for (const auto &configVal : configVals) {
1127 StringRef key, val;
1128 std::tie(key, val) = configVal.split("=");
1129 if (val.empty()) {
1130 Diags.Report(SourceLocation(),
1131 diag::err_analyzer_config_no_value) << configVal;
1132 break;
1134 if (val.contains('=')) {
1135 Diags.Report(SourceLocation(),
1136 diag::err_analyzer_config_multiple_values)
1137 << configVal;
1138 break;
1141 // TODO: Check checker options too, possibly in CheckerRegistry.
1142 // Leave unknown non-checker configs unclaimed.
1143 if (!key.contains(":") && Opts.isUnknownAnalyzerConfig(key)) {
1144 if (Opts.ShouldEmitErrorsOnInvalidConfigValue)
1145 Diags.Report(diag::err_analyzer_config_unknown) << key;
1146 continue;
1149 A->claim();
1150 Opts.Config[key] = std::string(val);
1154 if (Opts.ShouldEmitErrorsOnInvalidConfigValue)
1155 parseAnalyzerConfigs(Opts, &Diags);
1156 else
1157 parseAnalyzerConfigs(Opts, nullptr);
1159 llvm::raw_string_ostream os(Opts.FullCompilerInvocation);
1160 for (unsigned i = 0; i < Args.getNumInputArgStrings(); ++i) {
1161 if (i != 0)
1162 os << " ";
1163 os << Args.getArgString(i);
1165 os.flush();
1167 return Diags.getNumErrors() == NumErrorsBefore;
1170 static StringRef getStringOption(AnalyzerOptions::ConfigTable &Config,
1171 StringRef OptionName, StringRef DefaultVal) {
1172 return Config.insert({OptionName, std::string(DefaultVal)}).first->second;
1175 static void initOption(AnalyzerOptions::ConfigTable &Config,
1176 DiagnosticsEngine *Diags,
1177 StringRef &OptionField, StringRef Name,
1178 StringRef DefaultVal) {
1179 // String options may be known to invalid (e.g. if the expected string is a
1180 // file name, but the file does not exist), those will have to be checked in
1181 // parseConfigs.
1182 OptionField = getStringOption(Config, Name, DefaultVal);
1185 static void initOption(AnalyzerOptions::ConfigTable &Config,
1186 DiagnosticsEngine *Diags,
1187 bool &OptionField, StringRef Name, bool DefaultVal) {
1188 auto PossiblyInvalidVal =
1189 llvm::StringSwitch<std::optional<bool>>(
1190 getStringOption(Config, Name, (DefaultVal ? "true" : "false")))
1191 .Case("true", true)
1192 .Case("false", false)
1193 .Default(std::nullopt);
1195 if (!PossiblyInvalidVal) {
1196 if (Diags)
1197 Diags->Report(diag::err_analyzer_config_invalid_input)
1198 << Name << "a boolean";
1199 else
1200 OptionField = DefaultVal;
1201 } else
1202 OptionField = *PossiblyInvalidVal;
1205 static void initOption(AnalyzerOptions::ConfigTable &Config,
1206 DiagnosticsEngine *Diags,
1207 unsigned &OptionField, StringRef Name,
1208 unsigned DefaultVal) {
1210 OptionField = DefaultVal;
1211 bool HasFailed = getStringOption(Config, Name, std::to_string(DefaultVal))
1212 .getAsInteger(0, OptionField);
1213 if (Diags && HasFailed)
1214 Diags->Report(diag::err_analyzer_config_invalid_input)
1215 << Name << "an unsigned";
1218 static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts,
1219 DiagnosticsEngine *Diags) {
1220 // TODO: There's no need to store the entire configtable, it'd be plenty
1221 // enough to store checker options.
1223 #define ANALYZER_OPTION(TYPE, NAME, CMDFLAG, DESC, DEFAULT_VAL) \
1224 initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, DEFAULT_VAL);
1225 #define ANALYZER_OPTION_DEPENDS_ON_USER_MODE(...)
1226 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.def"
1228 assert(AnOpts.UserMode == "shallow" || AnOpts.UserMode == "deep");
1229 const bool InShallowMode = AnOpts.UserMode == "shallow";
1231 #define ANALYZER_OPTION(...)
1232 #define ANALYZER_OPTION_DEPENDS_ON_USER_MODE(TYPE, NAME, CMDFLAG, DESC, \
1233 SHALLOW_VAL, DEEP_VAL) \
1234 initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, \
1235 InShallowMode ? SHALLOW_VAL : DEEP_VAL);
1236 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.def"
1238 // At this point, AnalyzerOptions is configured. Let's validate some options.
1240 // FIXME: Here we try to validate the silenced checkers or packages are valid.
1241 // The current approach only validates the registered checkers which does not
1242 // contain the runtime enabled checkers and optimally we would validate both.
1243 if (!AnOpts.RawSilencedCheckersAndPackages.empty()) {
1244 std::vector<StringRef> Checkers =
1245 AnOpts.getRegisteredCheckers(/*IncludeExperimental=*/true);
1246 std::vector<StringRef> Packages =
1247 AnOpts.getRegisteredPackages(/*IncludeExperimental=*/true);
1249 SmallVector<StringRef, 16> CheckersAndPackages;
1250 AnOpts.RawSilencedCheckersAndPackages.split(CheckersAndPackages, ";");
1252 for (const StringRef &CheckerOrPackage : CheckersAndPackages) {
1253 if (Diags) {
1254 bool IsChecker = CheckerOrPackage.contains('.');
1255 bool IsValidName = IsChecker
1256 ? llvm::is_contained(Checkers, CheckerOrPackage)
1257 : llvm::is_contained(Packages, CheckerOrPackage);
1259 if (!IsValidName)
1260 Diags->Report(diag::err_unknown_analyzer_checker_or_package)
1261 << CheckerOrPackage;
1264 AnOpts.SilencedCheckersAndPackages.emplace_back(CheckerOrPackage);
1268 if (!Diags)
1269 return;
1271 if (AnOpts.ShouldTrackConditionsDebug && !AnOpts.ShouldTrackConditions)
1272 Diags->Report(diag::err_analyzer_config_invalid_input)
1273 << "track-conditions-debug" << "'track-conditions' to also be enabled";
1275 if (!AnOpts.CTUDir.empty() && !llvm::sys::fs::is_directory(AnOpts.CTUDir))
1276 Diags->Report(diag::err_analyzer_config_invalid_input) << "ctu-dir"
1277 << "a filename";
1279 if (!AnOpts.ModelPath.empty() &&
1280 !llvm::sys::fs::is_directory(AnOpts.ModelPath))
1281 Diags->Report(diag::err_analyzer_config_invalid_input) << "model-path"
1282 << "a filename";
1285 /// Generate a remark argument. This is an inverse of `ParseOptimizationRemark`.
1286 static void
1287 GenerateOptimizationRemark(ArgumentConsumer Consumer, OptSpecifier OptEQ,
1288 StringRef Name,
1289 const CodeGenOptions::OptRemark &Remark) {
1290 if (Remark.hasValidPattern()) {
1291 GenerateArg(Consumer, OptEQ, Remark.Pattern);
1292 } else if (Remark.Kind == CodeGenOptions::RK_Enabled) {
1293 GenerateArg(Consumer, OPT_R_Joined, Name);
1294 } else if (Remark.Kind == CodeGenOptions::RK_Disabled) {
1295 GenerateArg(Consumer, OPT_R_Joined, StringRef("no-") + Name);
1299 /// Parse a remark command line argument. It may be missing, disabled/enabled by
1300 /// '-R[no-]group' or specified with a regular expression by '-Rgroup=regexp'.
1301 /// On top of that, it can be disabled/enabled globally by '-R[no-]everything'.
1302 static CodeGenOptions::OptRemark
1303 ParseOptimizationRemark(DiagnosticsEngine &Diags, ArgList &Args,
1304 OptSpecifier OptEQ, StringRef Name) {
1305 CodeGenOptions::OptRemark Result;
1307 auto InitializeResultPattern = [&Diags, &Args, &Result](const Arg *A,
1308 StringRef Pattern) {
1309 Result.Pattern = Pattern.str();
1311 std::string RegexError;
1312 Result.Regex = std::make_shared<llvm::Regex>(Result.Pattern);
1313 if (!Result.Regex->isValid(RegexError)) {
1314 Diags.Report(diag::err_drv_optimization_remark_pattern)
1315 << RegexError << A->getAsString(Args);
1316 return false;
1319 return true;
1322 for (Arg *A : Args) {
1323 if (A->getOption().matches(OPT_R_Joined)) {
1324 StringRef Value = A->getValue();
1326 if (Value == Name)
1327 Result.Kind = CodeGenOptions::RK_Enabled;
1328 else if (Value == "everything")
1329 Result.Kind = CodeGenOptions::RK_EnabledEverything;
1330 else if (Value.split('-') == std::make_pair(StringRef("no"), Name))
1331 Result.Kind = CodeGenOptions::RK_Disabled;
1332 else if (Value == "no-everything")
1333 Result.Kind = CodeGenOptions::RK_DisabledEverything;
1334 else
1335 continue;
1337 if (Result.Kind == CodeGenOptions::RK_Disabled ||
1338 Result.Kind == CodeGenOptions::RK_DisabledEverything) {
1339 Result.Pattern = "";
1340 Result.Regex = nullptr;
1341 } else {
1342 InitializeResultPattern(A, ".*");
1344 } else if (A->getOption().matches(OptEQ)) {
1345 Result.Kind = CodeGenOptions::RK_WithPattern;
1346 if (!InitializeResultPattern(A, A->getValue()))
1347 return CodeGenOptions::OptRemark();
1351 return Result;
1354 static bool parseDiagnosticLevelMask(StringRef FlagName,
1355 const std::vector<std::string> &Levels,
1356 DiagnosticsEngine &Diags,
1357 DiagnosticLevelMask &M) {
1358 bool Success = true;
1359 for (const auto &Level : Levels) {
1360 DiagnosticLevelMask const PM =
1361 llvm::StringSwitch<DiagnosticLevelMask>(Level)
1362 .Case("note", DiagnosticLevelMask::Note)
1363 .Case("remark", DiagnosticLevelMask::Remark)
1364 .Case("warning", DiagnosticLevelMask::Warning)
1365 .Case("error", DiagnosticLevelMask::Error)
1366 .Default(DiagnosticLevelMask::None);
1367 if (PM == DiagnosticLevelMask::None) {
1368 Success = false;
1369 Diags.Report(diag::err_drv_invalid_value) << FlagName << Level;
1371 M = M | PM;
1373 return Success;
1376 static void parseSanitizerKinds(StringRef FlagName,
1377 const std::vector<std::string> &Sanitizers,
1378 DiagnosticsEngine &Diags, SanitizerSet &S) {
1379 for (const auto &Sanitizer : Sanitizers) {
1380 SanitizerMask K = parseSanitizerValue(Sanitizer, /*AllowGroups=*/false);
1381 if (K == SanitizerMask())
1382 Diags.Report(diag::err_drv_invalid_value) << FlagName << Sanitizer;
1383 else
1384 S.set(K, true);
1388 static SmallVector<StringRef, 4> serializeSanitizerKinds(SanitizerSet S) {
1389 SmallVector<StringRef, 4> Values;
1390 serializeSanitizerSet(S, Values);
1391 return Values;
1394 static void parseXRayInstrumentationBundle(StringRef FlagName, StringRef Bundle,
1395 ArgList &Args, DiagnosticsEngine &D,
1396 XRayInstrSet &S) {
1397 llvm::SmallVector<StringRef, 2> BundleParts;
1398 llvm::SplitString(Bundle, BundleParts, ",");
1399 for (const auto &B : BundleParts) {
1400 auto Mask = parseXRayInstrValue(B);
1401 if (Mask == XRayInstrKind::None)
1402 if (B != "none")
1403 D.Report(diag::err_drv_invalid_value) << FlagName << Bundle;
1404 else
1405 S.Mask = Mask;
1406 else if (Mask == XRayInstrKind::All)
1407 S.Mask = Mask;
1408 else
1409 S.set(Mask, true);
1413 static std::string serializeXRayInstrumentationBundle(const XRayInstrSet &S) {
1414 llvm::SmallVector<StringRef, 2> BundleParts;
1415 serializeXRayInstrValue(S, BundleParts);
1416 std::string Buffer;
1417 llvm::raw_string_ostream OS(Buffer);
1418 llvm::interleave(BundleParts, OS, [&OS](StringRef Part) { OS << Part; }, ",");
1419 return Buffer;
1422 // Set the profile kind using fprofile-instrument-use-path.
1423 static void setPGOUseInstrumentor(CodeGenOptions &Opts,
1424 const Twine &ProfileName,
1425 llvm::vfs::FileSystem &FS,
1426 DiagnosticsEngine &Diags) {
1427 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(ProfileName, FS);
1428 if (auto E = ReaderOrErr.takeError()) {
1429 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1430 "Error in reading profile %0: %1");
1431 llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
1432 Diags.Report(DiagID) << ProfileName.str() << EI.message();
1434 return;
1436 std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader =
1437 std::move(ReaderOrErr.get());
1438 // Currently memprof profiles are only added at the IR level. Mark the profile
1439 // type as IR in that case as well and the subsequent matching needs to detect
1440 // which is available (might be one or both).
1441 if (PGOReader->isIRLevelProfile() || PGOReader->hasMemoryProfile()) {
1442 if (PGOReader->hasCSIRLevelProfile())
1443 Opts.setProfileUse(CodeGenOptions::ProfileCSIRInstr);
1444 else
1445 Opts.setProfileUse(CodeGenOptions::ProfileIRInstr);
1446 } else
1447 Opts.setProfileUse(CodeGenOptions::ProfileClangInstr);
1450 void CompilerInvocationBase::GenerateCodeGenArgs(const CodeGenOptions &Opts,
1451 ArgumentConsumer Consumer,
1452 const llvm::Triple &T,
1453 const std::string &OutputFile,
1454 const LangOptions *LangOpts) {
1455 const CodeGenOptions &CodeGenOpts = Opts;
1457 if (Opts.OptimizationLevel == 0)
1458 GenerateArg(Consumer, OPT_O0);
1459 else
1460 GenerateArg(Consumer, OPT_O, Twine(Opts.OptimizationLevel));
1462 #define CODEGEN_OPTION_WITH_MARSHALLING(...) \
1463 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
1464 #include "clang/Driver/Options.inc"
1465 #undef CODEGEN_OPTION_WITH_MARSHALLING
1467 if (Opts.OptimizationLevel > 0) {
1468 if (Opts.Inlining == CodeGenOptions::NormalInlining)
1469 GenerateArg(Consumer, OPT_finline_functions);
1470 else if (Opts.Inlining == CodeGenOptions::OnlyHintInlining)
1471 GenerateArg(Consumer, OPT_finline_hint_functions);
1472 else if (Opts.Inlining == CodeGenOptions::OnlyAlwaysInlining)
1473 GenerateArg(Consumer, OPT_fno_inline);
1476 if (Opts.DirectAccessExternalData && LangOpts->PICLevel != 0)
1477 GenerateArg(Consumer, OPT_fdirect_access_external_data);
1478 else if (!Opts.DirectAccessExternalData && LangOpts->PICLevel == 0)
1479 GenerateArg(Consumer, OPT_fno_direct_access_external_data);
1481 std::optional<StringRef> DebugInfoVal;
1482 switch (Opts.DebugInfo) {
1483 case llvm::codegenoptions::DebugLineTablesOnly:
1484 DebugInfoVal = "line-tables-only";
1485 break;
1486 case llvm::codegenoptions::DebugDirectivesOnly:
1487 DebugInfoVal = "line-directives-only";
1488 break;
1489 case llvm::codegenoptions::DebugInfoConstructor:
1490 DebugInfoVal = "constructor";
1491 break;
1492 case llvm::codegenoptions::LimitedDebugInfo:
1493 DebugInfoVal = "limited";
1494 break;
1495 case llvm::codegenoptions::FullDebugInfo:
1496 DebugInfoVal = "standalone";
1497 break;
1498 case llvm::codegenoptions::UnusedTypeInfo:
1499 DebugInfoVal = "unused-types";
1500 break;
1501 case llvm::codegenoptions::NoDebugInfo: // default value
1502 DebugInfoVal = std::nullopt;
1503 break;
1504 case llvm::codegenoptions::LocTrackingOnly: // implied value
1505 DebugInfoVal = std::nullopt;
1506 break;
1508 if (DebugInfoVal)
1509 GenerateArg(Consumer, OPT_debug_info_kind_EQ, *DebugInfoVal);
1511 for (const auto &Prefix : Opts.DebugPrefixMap)
1512 GenerateArg(Consumer, OPT_fdebug_prefix_map_EQ,
1513 Prefix.first + "=" + Prefix.second);
1515 for (const auto &Prefix : Opts.CoveragePrefixMap)
1516 GenerateArg(Consumer, OPT_fcoverage_prefix_map_EQ,
1517 Prefix.first + "=" + Prefix.second);
1519 if (Opts.NewStructPathTBAA)
1520 GenerateArg(Consumer, OPT_new_struct_path_tbaa);
1522 if (Opts.OptimizeSize == 1)
1523 GenerateArg(Consumer, OPT_O, "s");
1524 else if (Opts.OptimizeSize == 2)
1525 GenerateArg(Consumer, OPT_O, "z");
1527 // SimplifyLibCalls is set only in the absence of -fno-builtin and
1528 // -ffreestanding. We'll consider that when generating them.
1530 // NoBuiltinFuncs are generated by LangOptions.
1532 if (Opts.UnrollLoops && Opts.OptimizationLevel <= 1)
1533 GenerateArg(Consumer, OPT_funroll_loops);
1534 else if (!Opts.UnrollLoops && Opts.OptimizationLevel > 1)
1535 GenerateArg(Consumer, OPT_fno_unroll_loops);
1537 if (!Opts.BinutilsVersion.empty())
1538 GenerateArg(Consumer, OPT_fbinutils_version_EQ, Opts.BinutilsVersion);
1540 if (Opts.DebugNameTable ==
1541 static_cast<unsigned>(llvm::DICompileUnit::DebugNameTableKind::GNU))
1542 GenerateArg(Consumer, OPT_ggnu_pubnames);
1543 else if (Opts.DebugNameTable ==
1544 static_cast<unsigned>(
1545 llvm::DICompileUnit::DebugNameTableKind::Default))
1546 GenerateArg(Consumer, OPT_gpubnames);
1548 auto TNK = Opts.getDebugSimpleTemplateNames();
1549 if (TNK != llvm::codegenoptions::DebugTemplateNamesKind::Full) {
1550 if (TNK == llvm::codegenoptions::DebugTemplateNamesKind::Simple)
1551 GenerateArg(Consumer, OPT_gsimple_template_names_EQ, "simple");
1552 else if (TNK == llvm::codegenoptions::DebugTemplateNamesKind::Mangled)
1553 GenerateArg(Consumer, OPT_gsimple_template_names_EQ, "mangled");
1555 // ProfileInstrumentUsePath is marshalled automatically, no need to generate
1556 // it or PGOUseInstrumentor.
1558 if (Opts.TimePasses) {
1559 if (Opts.TimePassesPerRun)
1560 GenerateArg(Consumer, OPT_ftime_report_EQ, "per-pass-run");
1561 else
1562 GenerateArg(Consumer, OPT_ftime_report);
1565 if (Opts.PrepareForLTO && !Opts.PrepareForThinLTO)
1566 GenerateArg(Consumer, OPT_flto_EQ, "full");
1568 if (Opts.PrepareForThinLTO)
1569 GenerateArg(Consumer, OPT_flto_EQ, "thin");
1571 if (!Opts.ThinLTOIndexFile.empty())
1572 GenerateArg(Consumer, OPT_fthinlto_index_EQ, Opts.ThinLTOIndexFile);
1574 if (Opts.SaveTempsFilePrefix == OutputFile)
1575 GenerateArg(Consumer, OPT_save_temps_EQ, "obj");
1577 StringRef MemProfileBasename("memprof.profraw");
1578 if (!Opts.MemoryProfileOutput.empty()) {
1579 if (Opts.MemoryProfileOutput == MemProfileBasename) {
1580 GenerateArg(Consumer, OPT_fmemory_profile);
1581 } else {
1582 size_t ArgLength =
1583 Opts.MemoryProfileOutput.size() - MemProfileBasename.size();
1584 GenerateArg(Consumer, OPT_fmemory_profile_EQ,
1585 Opts.MemoryProfileOutput.substr(0, ArgLength));
1589 if (memcmp(Opts.CoverageVersion, "408*", 4) != 0)
1590 GenerateArg(Consumer, OPT_coverage_version_EQ,
1591 StringRef(Opts.CoverageVersion, 4));
1593 // TODO: Check if we need to generate arguments stored in CmdArgs. (Namely
1594 // '-fembed_bitcode', which does not map to any CompilerInvocation field and
1595 // won't be generated.)
1597 if (Opts.XRayInstrumentationBundle.Mask != XRayInstrKind::All) {
1598 std::string InstrBundle =
1599 serializeXRayInstrumentationBundle(Opts.XRayInstrumentationBundle);
1600 if (!InstrBundle.empty())
1601 GenerateArg(Consumer, OPT_fxray_instrumentation_bundle, InstrBundle);
1604 if (Opts.CFProtectionReturn && Opts.CFProtectionBranch)
1605 GenerateArg(Consumer, OPT_fcf_protection_EQ, "full");
1606 else if (Opts.CFProtectionReturn)
1607 GenerateArg(Consumer, OPT_fcf_protection_EQ, "return");
1608 else if (Opts.CFProtectionBranch)
1609 GenerateArg(Consumer, OPT_fcf_protection_EQ, "branch");
1611 if (Opts.FunctionReturnThunks)
1612 GenerateArg(Consumer, OPT_mfunction_return_EQ, "thunk-extern");
1614 for (const auto &F : Opts.LinkBitcodeFiles) {
1615 bool Builtint = F.LinkFlags == llvm::Linker::Flags::LinkOnlyNeeded &&
1616 F.PropagateAttrs && F.Internalize;
1617 GenerateArg(Consumer,
1618 Builtint ? OPT_mlink_builtin_bitcode : OPT_mlink_bitcode_file,
1619 F.Filename);
1622 if (Opts.EmulatedTLS)
1623 GenerateArg(Consumer, OPT_femulated_tls);
1625 if (Opts.FPDenormalMode != llvm::DenormalMode::getIEEE())
1626 GenerateArg(Consumer, OPT_fdenormal_fp_math_EQ, Opts.FPDenormalMode.str());
1628 if ((Opts.FPDenormalMode != Opts.FP32DenormalMode) ||
1629 (Opts.FP32DenormalMode != llvm::DenormalMode::getIEEE()))
1630 GenerateArg(Consumer, OPT_fdenormal_fp_math_f32_EQ,
1631 Opts.FP32DenormalMode.str());
1633 if (Opts.StructReturnConvention == CodeGenOptions::SRCK_OnStack) {
1634 OptSpecifier Opt =
1635 T.isPPC32() ? OPT_maix_struct_return : OPT_fpcc_struct_return;
1636 GenerateArg(Consumer, Opt);
1637 } else if (Opts.StructReturnConvention == CodeGenOptions::SRCK_InRegs) {
1638 OptSpecifier Opt =
1639 T.isPPC32() ? OPT_msvr4_struct_return : OPT_freg_struct_return;
1640 GenerateArg(Consumer, Opt);
1643 if (Opts.EnableAIXExtendedAltivecABI)
1644 GenerateArg(Consumer, OPT_mabi_EQ_vec_extabi);
1646 if (Opts.XCOFFReadOnlyPointers)
1647 GenerateArg(Consumer, OPT_mxcoff_roptr);
1649 if (!Opts.OptRecordPasses.empty())
1650 GenerateArg(Consumer, OPT_opt_record_passes, Opts.OptRecordPasses);
1652 if (!Opts.OptRecordFormat.empty())
1653 GenerateArg(Consumer, OPT_opt_record_format, Opts.OptRecordFormat);
1655 GenerateOptimizationRemark(Consumer, OPT_Rpass_EQ, "pass",
1656 Opts.OptimizationRemark);
1658 GenerateOptimizationRemark(Consumer, OPT_Rpass_missed_EQ, "pass-missed",
1659 Opts.OptimizationRemarkMissed);
1661 GenerateOptimizationRemark(Consumer, OPT_Rpass_analysis_EQ, "pass-analysis",
1662 Opts.OptimizationRemarkAnalysis);
1664 GenerateArg(Consumer, OPT_fdiagnostics_hotness_threshold_EQ,
1665 Opts.DiagnosticsHotnessThreshold
1666 ? Twine(*Opts.DiagnosticsHotnessThreshold)
1667 : "auto");
1669 GenerateArg(Consumer, OPT_fdiagnostics_misexpect_tolerance_EQ,
1670 Twine(*Opts.DiagnosticsMisExpectTolerance));
1672 for (StringRef Sanitizer : serializeSanitizerKinds(Opts.SanitizeRecover))
1673 GenerateArg(Consumer, OPT_fsanitize_recover_EQ, Sanitizer);
1675 for (StringRef Sanitizer : serializeSanitizerKinds(Opts.SanitizeTrap))
1676 GenerateArg(Consumer, OPT_fsanitize_trap_EQ, Sanitizer);
1678 if (!Opts.EmitVersionIdentMetadata)
1679 GenerateArg(Consumer, OPT_Qn);
1681 switch (Opts.FiniteLoops) {
1682 case CodeGenOptions::FiniteLoopsKind::Language:
1683 break;
1684 case CodeGenOptions::FiniteLoopsKind::Always:
1685 GenerateArg(Consumer, OPT_ffinite_loops);
1686 break;
1687 case CodeGenOptions::FiniteLoopsKind::Never:
1688 GenerateArg(Consumer, OPT_fno_finite_loops);
1689 break;
1693 bool CompilerInvocation::ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args,
1694 InputKind IK,
1695 DiagnosticsEngine &Diags,
1696 const llvm::Triple &T,
1697 const std::string &OutputFile,
1698 const LangOptions &LangOptsRef) {
1699 unsigned NumErrorsBefore = Diags.getNumErrors();
1701 unsigned OptimizationLevel = getOptimizationLevel(Args, IK, Diags);
1702 // TODO: This could be done in Driver
1703 unsigned MaxOptLevel = 3;
1704 if (OptimizationLevel > MaxOptLevel) {
1705 // If the optimization level is not supported, fall back on the default
1706 // optimization
1707 Diags.Report(diag::warn_drv_optimization_value)
1708 << Args.getLastArg(OPT_O)->getAsString(Args) << "-O" << MaxOptLevel;
1709 OptimizationLevel = MaxOptLevel;
1711 Opts.OptimizationLevel = OptimizationLevel;
1713 // The key paths of codegen options defined in Options.td start with
1714 // "CodeGenOpts.". Let's provide the expected variable name and type.
1715 CodeGenOptions &CodeGenOpts = Opts;
1716 // Some codegen options depend on language options. Let's provide the expected
1717 // variable name and type.
1718 const LangOptions *LangOpts = &LangOptsRef;
1720 #define CODEGEN_OPTION_WITH_MARSHALLING(...) \
1721 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
1722 #include "clang/Driver/Options.inc"
1723 #undef CODEGEN_OPTION_WITH_MARSHALLING
1725 // At O0 we want to fully disable inlining outside of cases marked with
1726 // 'alwaysinline' that are required for correctness.
1727 if (Opts.OptimizationLevel == 0) {
1728 Opts.setInlining(CodeGenOptions::OnlyAlwaysInlining);
1729 } else if (const Arg *A = Args.getLastArg(options::OPT_finline_functions,
1730 options::OPT_finline_hint_functions,
1731 options::OPT_fno_inline_functions,
1732 options::OPT_fno_inline)) {
1733 // Explicit inlining flags can disable some or all inlining even at
1734 // optimization levels above zero.
1735 if (A->getOption().matches(options::OPT_finline_functions))
1736 Opts.setInlining(CodeGenOptions::NormalInlining);
1737 else if (A->getOption().matches(options::OPT_finline_hint_functions))
1738 Opts.setInlining(CodeGenOptions::OnlyHintInlining);
1739 else
1740 Opts.setInlining(CodeGenOptions::OnlyAlwaysInlining);
1741 } else {
1742 Opts.setInlining(CodeGenOptions::NormalInlining);
1745 // PIC defaults to -fno-direct-access-external-data while non-PIC defaults to
1746 // -fdirect-access-external-data.
1747 Opts.DirectAccessExternalData =
1748 Args.hasArg(OPT_fdirect_access_external_data) ||
1749 (!Args.hasArg(OPT_fno_direct_access_external_data) &&
1750 LangOpts->PICLevel == 0);
1752 if (Arg *A = Args.getLastArg(OPT_debug_info_kind_EQ)) {
1753 unsigned Val =
1754 llvm::StringSwitch<unsigned>(A->getValue())
1755 .Case("line-tables-only", llvm::codegenoptions::DebugLineTablesOnly)
1756 .Case("line-directives-only",
1757 llvm::codegenoptions::DebugDirectivesOnly)
1758 .Case("constructor", llvm::codegenoptions::DebugInfoConstructor)
1759 .Case("limited", llvm::codegenoptions::LimitedDebugInfo)
1760 .Case("standalone", llvm::codegenoptions::FullDebugInfo)
1761 .Case("unused-types", llvm::codegenoptions::UnusedTypeInfo)
1762 .Default(~0U);
1763 if (Val == ~0U)
1764 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
1765 << A->getValue();
1766 else
1767 Opts.setDebugInfo(static_cast<llvm::codegenoptions::DebugInfoKind>(Val));
1770 // If -fuse-ctor-homing is set and limited debug info is already on, then use
1771 // constructor homing, and vice versa for -fno-use-ctor-homing.
1772 if (const Arg *A =
1773 Args.getLastArg(OPT_fuse_ctor_homing, OPT_fno_use_ctor_homing)) {
1774 if (A->getOption().matches(OPT_fuse_ctor_homing) &&
1775 Opts.getDebugInfo() == llvm::codegenoptions::LimitedDebugInfo)
1776 Opts.setDebugInfo(llvm::codegenoptions::DebugInfoConstructor);
1777 if (A->getOption().matches(OPT_fno_use_ctor_homing) &&
1778 Opts.getDebugInfo() == llvm::codegenoptions::DebugInfoConstructor)
1779 Opts.setDebugInfo(llvm::codegenoptions::LimitedDebugInfo);
1782 for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ)) {
1783 auto Split = StringRef(Arg).split('=');
1784 Opts.DebugPrefixMap.emplace_back(Split.first, Split.second);
1787 for (const auto &Arg : Args.getAllArgValues(OPT_fcoverage_prefix_map_EQ)) {
1788 auto Split = StringRef(Arg).split('=');
1789 Opts.CoveragePrefixMap.emplace_back(Split.first, Split.second);
1792 const llvm::Triple::ArchType DebugEntryValueArchs[] = {
1793 llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::aarch64,
1794 llvm::Triple::arm, llvm::Triple::armeb, llvm::Triple::mips,
1795 llvm::Triple::mipsel, llvm::Triple::mips64, llvm::Triple::mips64el};
1797 if (Opts.OptimizationLevel > 0 && Opts.hasReducedDebugInfo() &&
1798 llvm::is_contained(DebugEntryValueArchs, T.getArch()))
1799 Opts.EmitCallSiteInfo = true;
1801 if (!Opts.EnableDIPreservationVerify && Opts.DIBugsReportFilePath.size()) {
1802 Diags.Report(diag::warn_ignoring_verify_debuginfo_preserve_export)
1803 << Opts.DIBugsReportFilePath;
1804 Opts.DIBugsReportFilePath = "";
1807 Opts.NewStructPathTBAA = !Args.hasArg(OPT_no_struct_path_tbaa) &&
1808 Args.hasArg(OPT_new_struct_path_tbaa);
1809 Opts.OptimizeSize = getOptimizationLevelSize(Args);
1810 Opts.SimplifyLibCalls = !LangOpts->NoBuiltin;
1811 if (Opts.SimplifyLibCalls)
1812 Opts.NoBuiltinFuncs = LangOpts->NoBuiltinFuncs;
1813 Opts.UnrollLoops =
1814 Args.hasFlag(OPT_funroll_loops, OPT_fno_unroll_loops,
1815 (Opts.OptimizationLevel > 1));
1816 Opts.BinutilsVersion =
1817 std::string(Args.getLastArgValue(OPT_fbinutils_version_EQ));
1819 Opts.DebugNameTable = static_cast<unsigned>(
1820 Args.hasArg(OPT_ggnu_pubnames)
1821 ? llvm::DICompileUnit::DebugNameTableKind::GNU
1822 : Args.hasArg(OPT_gpubnames)
1823 ? llvm::DICompileUnit::DebugNameTableKind::Default
1824 : llvm::DICompileUnit::DebugNameTableKind::None);
1825 if (const Arg *A = Args.getLastArg(OPT_gsimple_template_names_EQ)) {
1826 StringRef Value = A->getValue();
1827 if (Value != "simple" && Value != "mangled")
1828 Diags.Report(diag::err_drv_unsupported_option_argument)
1829 << A->getSpelling() << A->getValue();
1830 Opts.setDebugSimpleTemplateNames(
1831 StringRef(A->getValue()) == "simple"
1832 ? llvm::codegenoptions::DebugTemplateNamesKind::Simple
1833 : llvm::codegenoptions::DebugTemplateNamesKind::Mangled);
1836 if (const Arg *A = Args.getLastArg(OPT_ftime_report, OPT_ftime_report_EQ)) {
1837 Opts.TimePasses = true;
1839 // -ftime-report= is only for new pass manager.
1840 if (A->getOption().getID() == OPT_ftime_report_EQ) {
1841 StringRef Val = A->getValue();
1842 if (Val == "per-pass")
1843 Opts.TimePassesPerRun = false;
1844 else if (Val == "per-pass-run")
1845 Opts.TimePassesPerRun = true;
1846 else
1847 Diags.Report(diag::err_drv_invalid_value)
1848 << A->getAsString(Args) << A->getValue();
1852 Opts.PrepareForLTO = false;
1853 Opts.PrepareForThinLTO = false;
1854 if (Arg *A = Args.getLastArg(OPT_flto_EQ)) {
1855 Opts.PrepareForLTO = true;
1856 StringRef S = A->getValue();
1857 if (S == "thin")
1858 Opts.PrepareForThinLTO = true;
1859 else if (S != "full")
1860 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << S;
1861 if (Args.hasArg(OPT_funified_lto))
1862 Opts.PrepareForThinLTO = true;
1864 if (Arg *A = Args.getLastArg(options::OPT_ffat_lto_objects,
1865 options::OPT_fno_fat_lto_objects)) {
1866 if (A->getOption().matches(options::OPT_ffat_lto_objects)) {
1867 if (Arg *Uni = Args.getLastArg(options::OPT_funified_lto,
1868 options::OPT_fno_unified_lto)) {
1869 if (Uni->getOption().matches(options::OPT_fno_unified_lto))
1870 Diags.Report(diag::err_drv_incompatible_options)
1871 << A->getAsString(Args) << "-fno-unified-lto";
1872 } else
1873 Diags.Report(diag::err_drv_argument_only_allowed_with)
1874 << A->getAsString(Args) << "-funified-lto";
1878 if (Arg *A = Args.getLastArg(OPT_fthinlto_index_EQ)) {
1879 if (IK.getLanguage() != Language::LLVM_IR)
1880 Diags.Report(diag::err_drv_argument_only_allowed_with)
1881 << A->getAsString(Args) << "-x ir";
1882 Opts.ThinLTOIndexFile =
1883 std::string(Args.getLastArgValue(OPT_fthinlto_index_EQ));
1885 if (Arg *A = Args.getLastArg(OPT_save_temps_EQ))
1886 Opts.SaveTempsFilePrefix =
1887 llvm::StringSwitch<std::string>(A->getValue())
1888 .Case("obj", OutputFile)
1889 .Default(llvm::sys::path::filename(OutputFile).str());
1891 // The memory profile runtime appends the pid to make this name more unique.
1892 const char *MemProfileBasename = "memprof.profraw";
1893 if (Args.hasArg(OPT_fmemory_profile_EQ)) {
1894 SmallString<128> Path(
1895 std::string(Args.getLastArgValue(OPT_fmemory_profile_EQ)));
1896 llvm::sys::path::append(Path, MemProfileBasename);
1897 Opts.MemoryProfileOutput = std::string(Path);
1898 } else if (Args.hasArg(OPT_fmemory_profile))
1899 Opts.MemoryProfileOutput = MemProfileBasename;
1901 memcpy(Opts.CoverageVersion, "408*", 4);
1902 if (Opts.CoverageNotesFile.size() || Opts.CoverageDataFile.size()) {
1903 if (Args.hasArg(OPT_coverage_version_EQ)) {
1904 StringRef CoverageVersion = Args.getLastArgValue(OPT_coverage_version_EQ);
1905 if (CoverageVersion.size() != 4) {
1906 Diags.Report(diag::err_drv_invalid_value)
1907 << Args.getLastArg(OPT_coverage_version_EQ)->getAsString(Args)
1908 << CoverageVersion;
1909 } else {
1910 memcpy(Opts.CoverageVersion, CoverageVersion.data(), 4);
1914 // FIXME: For backend options that are not yet recorded as function
1915 // attributes in the IR, keep track of them so we can embed them in a
1916 // separate data section and use them when building the bitcode.
1917 for (const auto &A : Args) {
1918 // Do not encode output and input.
1919 if (A->getOption().getID() == options::OPT_o ||
1920 A->getOption().getID() == options::OPT_INPUT ||
1921 A->getOption().getID() == options::OPT_x ||
1922 A->getOption().getID() == options::OPT_fembed_bitcode ||
1923 A->getOption().matches(options::OPT_W_Group))
1924 continue;
1925 ArgStringList ASL;
1926 A->render(Args, ASL);
1927 for (const auto &arg : ASL) {
1928 StringRef ArgStr(arg);
1929 Opts.CmdArgs.insert(Opts.CmdArgs.end(), ArgStr.begin(), ArgStr.end());
1930 // using \00 to separate each commandline options.
1931 Opts.CmdArgs.push_back('\0');
1935 auto XRayInstrBundles =
1936 Args.getAllArgValues(OPT_fxray_instrumentation_bundle);
1937 if (XRayInstrBundles.empty())
1938 Opts.XRayInstrumentationBundle.Mask = XRayInstrKind::All;
1939 else
1940 for (const auto &A : XRayInstrBundles)
1941 parseXRayInstrumentationBundle("-fxray-instrumentation-bundle=", A, Args,
1942 Diags, Opts.XRayInstrumentationBundle);
1944 if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
1945 StringRef Name = A->getValue();
1946 if (Name == "full") {
1947 Opts.CFProtectionReturn = 1;
1948 Opts.CFProtectionBranch = 1;
1949 } else if (Name == "return")
1950 Opts.CFProtectionReturn = 1;
1951 else if (Name == "branch")
1952 Opts.CFProtectionBranch = 1;
1953 else if (Name != "none")
1954 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
1957 if (const Arg *A = Args.getLastArg(OPT_mfunction_return_EQ)) {
1958 auto Val = llvm::StringSwitch<llvm::FunctionReturnThunksKind>(A->getValue())
1959 .Case("keep", llvm::FunctionReturnThunksKind::Keep)
1960 .Case("thunk-extern", llvm::FunctionReturnThunksKind::Extern)
1961 .Default(llvm::FunctionReturnThunksKind::Invalid);
1962 // SystemZ might want to add support for "expolines."
1963 if (!T.isX86())
1964 Diags.Report(diag::err_drv_argument_not_allowed_with)
1965 << A->getSpelling() << T.getTriple();
1966 else if (Val == llvm::FunctionReturnThunksKind::Invalid)
1967 Diags.Report(diag::err_drv_invalid_value)
1968 << A->getAsString(Args) << A->getValue();
1969 else if (Val == llvm::FunctionReturnThunksKind::Extern &&
1970 Args.getLastArgValue(OPT_mcmodel_EQ).equals("large"))
1971 Diags.Report(diag::err_drv_argument_not_allowed_with)
1972 << A->getAsString(Args)
1973 << Args.getLastArg(OPT_mcmodel_EQ)->getAsString(Args);
1974 else
1975 Opts.FunctionReturnThunks = static_cast<unsigned>(Val);
1978 for (auto *A :
1979 Args.filtered(OPT_mlink_bitcode_file, OPT_mlink_builtin_bitcode)) {
1980 CodeGenOptions::BitcodeFileToLink F;
1981 F.Filename = A->getValue();
1982 if (A->getOption().matches(OPT_mlink_builtin_bitcode)) {
1983 F.LinkFlags = llvm::Linker::Flags::LinkOnlyNeeded;
1984 // When linking CUDA bitcode, propagate function attributes so that
1985 // e.g. libdevice gets fast-math attrs if we're building with fast-math.
1986 F.PropagateAttrs = true;
1987 F.Internalize = true;
1989 Opts.LinkBitcodeFiles.push_back(F);
1992 if (Arg *A = Args.getLastArg(OPT_ftlsmodel_EQ)) {
1993 if (T.isOSAIX()) {
1994 StringRef Name = A->getValue();
1995 if (Name == "local-dynamic")
1996 Diags.Report(diag::err_aix_unsupported_tls_model) << Name;
2000 if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_EQ)) {
2001 StringRef Val = A->getValue();
2002 Opts.FPDenormalMode = llvm::parseDenormalFPAttribute(Val);
2003 Opts.FP32DenormalMode = Opts.FPDenormalMode;
2004 if (!Opts.FPDenormalMode.isValid())
2005 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
2008 if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_f32_EQ)) {
2009 StringRef Val = A->getValue();
2010 Opts.FP32DenormalMode = llvm::parseDenormalFPAttribute(Val);
2011 if (!Opts.FP32DenormalMode.isValid())
2012 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
2015 // X86_32 has -fppc-struct-return and -freg-struct-return.
2016 // PPC32 has -maix-struct-return and -msvr4-struct-return.
2017 if (Arg *A =
2018 Args.getLastArg(OPT_fpcc_struct_return, OPT_freg_struct_return,
2019 OPT_maix_struct_return, OPT_msvr4_struct_return)) {
2020 // TODO: We might want to consider enabling these options on AIX in the
2021 // future.
2022 if (T.isOSAIX())
2023 Diags.Report(diag::err_drv_unsupported_opt_for_target)
2024 << A->getSpelling() << T.str();
2026 const Option &O = A->getOption();
2027 if (O.matches(OPT_fpcc_struct_return) ||
2028 O.matches(OPT_maix_struct_return)) {
2029 Opts.setStructReturnConvention(CodeGenOptions::SRCK_OnStack);
2030 } else {
2031 assert(O.matches(OPT_freg_struct_return) ||
2032 O.matches(OPT_msvr4_struct_return));
2033 Opts.setStructReturnConvention(CodeGenOptions::SRCK_InRegs);
2037 if (Arg *A = Args.getLastArg(OPT_mxcoff_roptr)) {
2038 if (!T.isOSAIX())
2039 Diags.Report(diag::err_drv_unsupported_opt_for_target)
2040 << A->getSpelling() << T.str();
2042 // Since the storage mapping class is specified per csect,
2043 // without using data sections, it is less effective to use read-only
2044 // pointers. Using read-only pointers may cause other RO variables in the
2045 // same csect to become RW when the linker acts upon `-bforceimprw`;
2046 // therefore, we require that separate data sections
2047 // are used when `-mxcoff-roptr` is in effect. We respect the setting of
2048 // data-sections since we have not found reasons to do otherwise that
2049 // overcome the user surprise of not respecting the setting.
2050 if (!Args.hasFlag(OPT_fdata_sections, OPT_fno_data_sections, false))
2051 Diags.Report(diag::err_roptr_requires_data_sections);
2053 Opts.XCOFFReadOnlyPointers = true;
2056 if (Arg *A = Args.getLastArg(OPT_mabi_EQ_quadword_atomics)) {
2057 if (!T.isOSAIX() || T.isPPC32())
2058 Diags.Report(diag::err_drv_unsupported_opt_for_target)
2059 << A->getSpelling() << T.str();
2062 bool NeedLocTracking = false;
2064 if (!Opts.OptRecordFile.empty())
2065 NeedLocTracking = true;
2067 if (Arg *A = Args.getLastArg(OPT_opt_record_passes)) {
2068 Opts.OptRecordPasses = A->getValue();
2069 NeedLocTracking = true;
2072 if (Arg *A = Args.getLastArg(OPT_opt_record_format)) {
2073 Opts.OptRecordFormat = A->getValue();
2074 NeedLocTracking = true;
2077 Opts.OptimizationRemark =
2078 ParseOptimizationRemark(Diags, Args, OPT_Rpass_EQ, "pass");
2080 Opts.OptimizationRemarkMissed =
2081 ParseOptimizationRemark(Diags, Args, OPT_Rpass_missed_EQ, "pass-missed");
2083 Opts.OptimizationRemarkAnalysis = ParseOptimizationRemark(
2084 Diags, Args, OPT_Rpass_analysis_EQ, "pass-analysis");
2086 NeedLocTracking |= Opts.OptimizationRemark.hasValidPattern() ||
2087 Opts.OptimizationRemarkMissed.hasValidPattern() ||
2088 Opts.OptimizationRemarkAnalysis.hasValidPattern();
2090 bool UsingSampleProfile = !Opts.SampleProfileFile.empty();
2091 bool UsingProfile =
2092 UsingSampleProfile || !Opts.ProfileInstrumentUsePath.empty();
2094 if (Opts.DiagnosticsWithHotness && !UsingProfile &&
2095 // An IR file will contain PGO as metadata
2096 IK.getLanguage() != Language::LLVM_IR)
2097 Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
2098 << "-fdiagnostics-show-hotness";
2100 // Parse remarks hotness threshold. Valid value is either integer or 'auto'.
2101 if (auto *arg =
2102 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
2103 auto ResultOrErr =
2104 llvm::remarks::parseHotnessThresholdOption(arg->getValue());
2106 if (!ResultOrErr) {
2107 Diags.Report(diag::err_drv_invalid_diagnotics_hotness_threshold)
2108 << "-fdiagnostics-hotness-threshold=";
2109 } else {
2110 Opts.DiagnosticsHotnessThreshold = *ResultOrErr;
2111 if ((!Opts.DiagnosticsHotnessThreshold ||
2112 *Opts.DiagnosticsHotnessThreshold > 0) &&
2113 !UsingProfile)
2114 Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
2115 << "-fdiagnostics-hotness-threshold=";
2119 if (auto *arg =
2120 Args.getLastArg(options::OPT_fdiagnostics_misexpect_tolerance_EQ)) {
2121 auto ResultOrErr = parseToleranceOption(arg->getValue());
2123 if (!ResultOrErr) {
2124 Diags.Report(diag::err_drv_invalid_diagnotics_misexpect_tolerance)
2125 << "-fdiagnostics-misexpect-tolerance=";
2126 } else {
2127 Opts.DiagnosticsMisExpectTolerance = *ResultOrErr;
2128 if ((!Opts.DiagnosticsMisExpectTolerance ||
2129 *Opts.DiagnosticsMisExpectTolerance > 0) &&
2130 !UsingProfile)
2131 Diags.Report(diag::warn_drv_diagnostics_misexpect_requires_pgo)
2132 << "-fdiagnostics-misexpect-tolerance=";
2136 // If the user requested to use a sample profile for PGO, then the
2137 // backend will need to track source location information so the profile
2138 // can be incorporated into the IR.
2139 if (UsingSampleProfile)
2140 NeedLocTracking = true;
2142 if (!Opts.StackUsageOutput.empty())
2143 NeedLocTracking = true;
2145 // If the user requested a flag that requires source locations available in
2146 // the backend, make sure that the backend tracks source location information.
2147 if (NeedLocTracking &&
2148 Opts.getDebugInfo() == llvm::codegenoptions::NoDebugInfo)
2149 Opts.setDebugInfo(llvm::codegenoptions::LocTrackingOnly);
2151 // Parse -fsanitize-recover= arguments.
2152 // FIXME: Report unrecoverable sanitizers incorrectly specified here.
2153 parseSanitizerKinds("-fsanitize-recover=",
2154 Args.getAllArgValues(OPT_fsanitize_recover_EQ), Diags,
2155 Opts.SanitizeRecover);
2156 parseSanitizerKinds("-fsanitize-trap=",
2157 Args.getAllArgValues(OPT_fsanitize_trap_EQ), Diags,
2158 Opts.SanitizeTrap);
2160 Opts.EmitVersionIdentMetadata = Args.hasFlag(OPT_Qy, OPT_Qn, true);
2162 if (Args.hasArg(options::OPT_ffinite_loops))
2163 Opts.FiniteLoops = CodeGenOptions::FiniteLoopsKind::Always;
2164 else if (Args.hasArg(options::OPT_fno_finite_loops))
2165 Opts.FiniteLoops = CodeGenOptions::FiniteLoopsKind::Never;
2167 Opts.EmitIEEENaNCompliantInsts = Args.hasFlag(
2168 options::OPT_mamdgpu_ieee, options::OPT_mno_amdgpu_ieee, true);
2169 if (!Opts.EmitIEEENaNCompliantInsts && !LangOptsRef.NoHonorNaNs)
2170 Diags.Report(diag::err_drv_amdgpu_ieee_without_no_honor_nans);
2172 return Diags.getNumErrors() == NumErrorsBefore;
2175 static void GenerateDependencyOutputArgs(const DependencyOutputOptions &Opts,
2176 ArgumentConsumer Consumer) {
2177 const DependencyOutputOptions &DependencyOutputOpts = Opts;
2178 #define DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING(...) \
2179 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
2180 #include "clang/Driver/Options.inc"
2181 #undef DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING
2183 if (Opts.ShowIncludesDest != ShowIncludesDestination::None)
2184 GenerateArg(Consumer, OPT_show_includes);
2186 for (const auto &Dep : Opts.ExtraDeps) {
2187 switch (Dep.second) {
2188 case EDK_SanitizeIgnorelist:
2189 // Sanitizer ignorelist arguments are generated from LanguageOptions.
2190 continue;
2191 case EDK_ModuleFile:
2192 // Module file arguments are generated from FrontendOptions and
2193 // HeaderSearchOptions.
2194 continue;
2195 case EDK_ProfileList:
2196 // Profile list arguments are generated from LanguageOptions via the
2197 // marshalling infrastructure.
2198 continue;
2199 case EDK_DepFileEntry:
2200 GenerateArg(Consumer, OPT_fdepfile_entry, Dep.first);
2201 break;
2206 static bool ParseDependencyOutputArgs(DependencyOutputOptions &Opts,
2207 ArgList &Args, DiagnosticsEngine &Diags,
2208 frontend::ActionKind Action,
2209 bool ShowLineMarkers) {
2210 unsigned NumErrorsBefore = Diags.getNumErrors();
2212 DependencyOutputOptions &DependencyOutputOpts = Opts;
2213 #define DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING(...) \
2214 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
2215 #include "clang/Driver/Options.inc"
2216 #undef DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING
2218 if (Args.hasArg(OPT_show_includes)) {
2219 // Writing both /showIncludes and preprocessor output to stdout
2220 // would produce interleaved output, so use stderr for /showIncludes.
2221 // This behaves the same as cl.exe, when /E, /EP or /P are passed.
2222 if (Action == frontend::PrintPreprocessedInput || !ShowLineMarkers)
2223 Opts.ShowIncludesDest = ShowIncludesDestination::Stderr;
2224 else
2225 Opts.ShowIncludesDest = ShowIncludesDestination::Stdout;
2226 } else {
2227 Opts.ShowIncludesDest = ShowIncludesDestination::None;
2230 // Add sanitizer ignorelists as extra dependencies.
2231 // They won't be discovered by the regular preprocessor, so
2232 // we let make / ninja to know about this implicit dependency.
2233 if (!Args.hasArg(OPT_fno_sanitize_ignorelist)) {
2234 for (const auto *A : Args.filtered(OPT_fsanitize_ignorelist_EQ)) {
2235 StringRef Val = A->getValue();
2236 if (!Val.contains('='))
2237 Opts.ExtraDeps.emplace_back(std::string(Val), EDK_SanitizeIgnorelist);
2239 if (Opts.IncludeSystemHeaders) {
2240 for (const auto *A : Args.filtered(OPT_fsanitize_system_ignorelist_EQ)) {
2241 StringRef Val = A->getValue();
2242 if (!Val.contains('='))
2243 Opts.ExtraDeps.emplace_back(std::string(Val), EDK_SanitizeIgnorelist);
2248 // -fprofile-list= dependencies.
2249 for (const auto &Filename : Args.getAllArgValues(OPT_fprofile_list_EQ))
2250 Opts.ExtraDeps.emplace_back(Filename, EDK_ProfileList);
2252 // Propagate the extra dependencies.
2253 for (const auto *A : Args.filtered(OPT_fdepfile_entry))
2254 Opts.ExtraDeps.emplace_back(A->getValue(), EDK_DepFileEntry);
2256 // Only the -fmodule-file=<file> form.
2257 for (const auto *A : Args.filtered(OPT_fmodule_file)) {
2258 StringRef Val = A->getValue();
2259 if (!Val.contains('='))
2260 Opts.ExtraDeps.emplace_back(std::string(Val), EDK_ModuleFile);
2263 // Check for invalid combinations of header-include-format
2264 // and header-include-filtering.
2265 if ((Opts.HeaderIncludeFormat == HIFMT_Textual &&
2266 Opts.HeaderIncludeFiltering != HIFIL_None) ||
2267 (Opts.HeaderIncludeFormat == HIFMT_JSON &&
2268 Opts.HeaderIncludeFiltering != HIFIL_Only_Direct_System))
2269 Diags.Report(diag::err_drv_print_header_env_var_combination_cc1)
2270 << Args.getLastArg(OPT_header_include_format_EQ)->getValue()
2271 << Args.getLastArg(OPT_header_include_filtering_EQ)->getValue();
2273 return Diags.getNumErrors() == NumErrorsBefore;
2276 static bool parseShowColorsArgs(const ArgList &Args, bool DefaultColor) {
2277 // Color diagnostics default to auto ("on" if terminal supports) in the driver
2278 // but default to off in cc1, needing an explicit OPT_fdiagnostics_color.
2279 // Support both clang's -f[no-]color-diagnostics and gcc's
2280 // -f[no-]diagnostics-colors[=never|always|auto].
2281 enum {
2282 Colors_On,
2283 Colors_Off,
2284 Colors_Auto
2285 } ShowColors = DefaultColor ? Colors_Auto : Colors_Off;
2286 for (auto *A : Args) {
2287 const Option &O = A->getOption();
2288 if (O.matches(options::OPT_fcolor_diagnostics)) {
2289 ShowColors = Colors_On;
2290 } else if (O.matches(options::OPT_fno_color_diagnostics)) {
2291 ShowColors = Colors_Off;
2292 } else if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
2293 StringRef Value(A->getValue());
2294 if (Value == "always")
2295 ShowColors = Colors_On;
2296 else if (Value == "never")
2297 ShowColors = Colors_Off;
2298 else if (Value == "auto")
2299 ShowColors = Colors_Auto;
2302 return ShowColors == Colors_On ||
2303 (ShowColors == Colors_Auto &&
2304 llvm::sys::Process::StandardErrHasColors());
2307 static bool checkVerifyPrefixes(const std::vector<std::string> &VerifyPrefixes,
2308 DiagnosticsEngine &Diags) {
2309 bool Success = true;
2310 for (const auto &Prefix : VerifyPrefixes) {
2311 // Every prefix must start with a letter and contain only alphanumeric
2312 // characters, hyphens, and underscores.
2313 auto BadChar = llvm::find_if(Prefix, [](char C) {
2314 return !isAlphanumeric(C) && C != '-' && C != '_';
2316 if (BadChar != Prefix.end() || !isLetter(Prefix[0])) {
2317 Success = false;
2318 Diags.Report(diag::err_drv_invalid_value) << "-verify=" << Prefix;
2319 Diags.Report(diag::note_drv_verify_prefix_spelling);
2322 return Success;
2325 static void GenerateFileSystemArgs(const FileSystemOptions &Opts,
2326 ArgumentConsumer Consumer) {
2327 const FileSystemOptions &FileSystemOpts = Opts;
2329 #define FILE_SYSTEM_OPTION_WITH_MARSHALLING(...) \
2330 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
2331 #include "clang/Driver/Options.inc"
2332 #undef FILE_SYSTEM_OPTION_WITH_MARSHALLING
2335 static bool ParseFileSystemArgs(FileSystemOptions &Opts, const ArgList &Args,
2336 DiagnosticsEngine &Diags) {
2337 unsigned NumErrorsBefore = Diags.getNumErrors();
2339 FileSystemOptions &FileSystemOpts = Opts;
2341 #define FILE_SYSTEM_OPTION_WITH_MARSHALLING(...) \
2342 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
2343 #include "clang/Driver/Options.inc"
2344 #undef FILE_SYSTEM_OPTION_WITH_MARSHALLING
2346 return Diags.getNumErrors() == NumErrorsBefore;
2349 static void GenerateMigratorArgs(const MigratorOptions &Opts,
2350 ArgumentConsumer Consumer) {
2351 const MigratorOptions &MigratorOpts = Opts;
2352 #define MIGRATOR_OPTION_WITH_MARSHALLING(...) \
2353 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
2354 #include "clang/Driver/Options.inc"
2355 #undef MIGRATOR_OPTION_WITH_MARSHALLING
2358 static bool ParseMigratorArgs(MigratorOptions &Opts, const ArgList &Args,
2359 DiagnosticsEngine &Diags) {
2360 unsigned NumErrorsBefore = Diags.getNumErrors();
2362 MigratorOptions &MigratorOpts = Opts;
2364 #define MIGRATOR_OPTION_WITH_MARSHALLING(...) \
2365 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
2366 #include "clang/Driver/Options.inc"
2367 #undef MIGRATOR_OPTION_WITH_MARSHALLING
2369 return Diags.getNumErrors() == NumErrorsBefore;
2372 void CompilerInvocationBase::GenerateDiagnosticArgs(
2373 const DiagnosticOptions &Opts, ArgumentConsumer Consumer,
2374 bool DefaultDiagColor) {
2375 const DiagnosticOptions *DiagnosticOpts = &Opts;
2376 #define DIAG_OPTION_WITH_MARSHALLING(...) \
2377 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
2378 #include "clang/Driver/Options.inc"
2379 #undef DIAG_OPTION_WITH_MARSHALLING
2381 if (!Opts.DiagnosticSerializationFile.empty())
2382 GenerateArg(Consumer, OPT_diagnostic_serialized_file,
2383 Opts.DiagnosticSerializationFile);
2385 if (Opts.ShowColors)
2386 GenerateArg(Consumer, OPT_fcolor_diagnostics);
2388 if (Opts.VerifyDiagnostics &&
2389 llvm::is_contained(Opts.VerifyPrefixes, "expected"))
2390 GenerateArg(Consumer, OPT_verify);
2392 for (const auto &Prefix : Opts.VerifyPrefixes)
2393 if (Prefix != "expected")
2394 GenerateArg(Consumer, OPT_verify_EQ, Prefix);
2396 DiagnosticLevelMask VIU = Opts.getVerifyIgnoreUnexpected();
2397 if (VIU == DiagnosticLevelMask::None) {
2398 // This is the default, don't generate anything.
2399 } else if (VIU == DiagnosticLevelMask::All) {
2400 GenerateArg(Consumer, OPT_verify_ignore_unexpected);
2401 } else {
2402 if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Note) != 0)
2403 GenerateArg(Consumer, OPT_verify_ignore_unexpected_EQ, "note");
2404 if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Remark) != 0)
2405 GenerateArg(Consumer, OPT_verify_ignore_unexpected_EQ, "remark");
2406 if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Warning) != 0)
2407 GenerateArg(Consumer, OPT_verify_ignore_unexpected_EQ, "warning");
2408 if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Error) != 0)
2409 GenerateArg(Consumer, OPT_verify_ignore_unexpected_EQ, "error");
2412 for (const auto &Warning : Opts.Warnings) {
2413 // This option is automatically generated from UndefPrefixes.
2414 if (Warning == "undef-prefix")
2415 continue;
2416 Consumer(StringRef("-W") + Warning);
2419 for (const auto &Remark : Opts.Remarks) {
2420 // These arguments are generated from OptimizationRemark fields of
2421 // CodeGenOptions.
2422 StringRef IgnoredRemarks[] = {"pass", "no-pass",
2423 "pass-analysis", "no-pass-analysis",
2424 "pass-missed", "no-pass-missed"};
2425 if (llvm::is_contained(IgnoredRemarks, Remark))
2426 continue;
2428 Consumer(StringRef("-R") + Remark);
2432 std::unique_ptr<DiagnosticOptions>
2433 clang::CreateAndPopulateDiagOpts(ArrayRef<const char *> Argv) {
2434 auto DiagOpts = std::make_unique<DiagnosticOptions>();
2435 unsigned MissingArgIndex, MissingArgCount;
2436 InputArgList Args = getDriverOptTable().ParseArgs(
2437 Argv.slice(1), MissingArgIndex, MissingArgCount);
2439 bool ShowColors = true;
2440 if (std::optional<std::string> NoColor =
2441 llvm::sys::Process::GetEnv("NO_COLOR");
2442 NoColor && !NoColor->empty()) {
2443 // If the user set the NO_COLOR environment variable, we'll honor that
2444 // unless the command line overrides it.
2445 ShowColors = false;
2448 // We ignore MissingArgCount and the return value of ParseDiagnosticArgs.
2449 // Any errors that would be diagnosed here will also be diagnosed later,
2450 // when the DiagnosticsEngine actually exists.
2451 (void)ParseDiagnosticArgs(*DiagOpts, Args, /*Diags=*/nullptr, ShowColors);
2452 return DiagOpts;
2455 bool clang::ParseDiagnosticArgs(DiagnosticOptions &Opts, ArgList &Args,
2456 DiagnosticsEngine *Diags,
2457 bool DefaultDiagColor) {
2458 std::optional<DiagnosticsEngine> IgnoringDiags;
2459 if (!Diags) {
2460 IgnoringDiags.emplace(new DiagnosticIDs(), new DiagnosticOptions(),
2461 new IgnoringDiagConsumer());
2462 Diags = &*IgnoringDiags;
2465 unsigned NumErrorsBefore = Diags->getNumErrors();
2467 // The key paths of diagnostic options defined in Options.td start with
2468 // "DiagnosticOpts->". Let's provide the expected variable name and type.
2469 DiagnosticOptions *DiagnosticOpts = &Opts;
2471 #define DIAG_OPTION_WITH_MARSHALLING(...) \
2472 PARSE_OPTION_WITH_MARSHALLING(Args, *Diags, __VA_ARGS__)
2473 #include "clang/Driver/Options.inc"
2474 #undef DIAG_OPTION_WITH_MARSHALLING
2476 llvm::sys::Process::UseANSIEscapeCodes(Opts.UseANSIEscapeCodes);
2478 if (Arg *A =
2479 Args.getLastArg(OPT_diagnostic_serialized_file, OPT__serialize_diags))
2480 Opts.DiagnosticSerializationFile = A->getValue();
2481 Opts.ShowColors = parseShowColorsArgs(Args, DefaultDiagColor);
2483 Opts.VerifyDiagnostics = Args.hasArg(OPT_verify) || Args.hasArg(OPT_verify_EQ);
2484 Opts.VerifyPrefixes = Args.getAllArgValues(OPT_verify_EQ);
2485 if (Args.hasArg(OPT_verify))
2486 Opts.VerifyPrefixes.push_back("expected");
2487 // Keep VerifyPrefixes in its original order for the sake of diagnostics, and
2488 // then sort it to prepare for fast lookup using std::binary_search.
2489 if (!checkVerifyPrefixes(Opts.VerifyPrefixes, *Diags))
2490 Opts.VerifyDiagnostics = false;
2491 else
2492 llvm::sort(Opts.VerifyPrefixes);
2493 DiagnosticLevelMask DiagMask = DiagnosticLevelMask::None;
2494 parseDiagnosticLevelMask(
2495 "-verify-ignore-unexpected=",
2496 Args.getAllArgValues(OPT_verify_ignore_unexpected_EQ), *Diags, DiagMask);
2497 if (Args.hasArg(OPT_verify_ignore_unexpected))
2498 DiagMask = DiagnosticLevelMask::All;
2499 Opts.setVerifyIgnoreUnexpected(DiagMask);
2500 if (Opts.TabStop == 0 || Opts.TabStop > DiagnosticOptions::MaxTabStop) {
2501 Diags->Report(diag::warn_ignoring_ftabstop_value)
2502 << Opts.TabStop << DiagnosticOptions::DefaultTabStop;
2503 Opts.TabStop = DiagnosticOptions::DefaultTabStop;
2506 addDiagnosticArgs(Args, OPT_W_Group, OPT_W_value_Group, Opts.Warnings);
2507 addDiagnosticArgs(Args, OPT_R_Group, OPT_R_value_Group, Opts.Remarks);
2509 return Diags->getNumErrors() == NumErrorsBefore;
2512 /// Parse the argument to the -ftest-module-file-extension
2513 /// command-line argument.
2515 /// \returns true on error, false on success.
2516 static bool parseTestModuleFileExtensionArg(StringRef Arg,
2517 std::string &BlockName,
2518 unsigned &MajorVersion,
2519 unsigned &MinorVersion,
2520 bool &Hashed,
2521 std::string &UserInfo) {
2522 SmallVector<StringRef, 5> Args;
2523 Arg.split(Args, ':', 5);
2524 if (Args.size() < 5)
2525 return true;
2527 BlockName = std::string(Args[0]);
2528 if (Args[1].getAsInteger(10, MajorVersion)) return true;
2529 if (Args[2].getAsInteger(10, MinorVersion)) return true;
2530 if (Args[3].getAsInteger(2, Hashed)) return true;
2531 if (Args.size() > 4)
2532 UserInfo = std::string(Args[4]);
2533 return false;
2536 /// Return a table that associates command line option specifiers with the
2537 /// frontend action. Note: The pair {frontend::PluginAction, OPT_plugin} is
2538 /// intentionally missing, as this case is handled separately from other
2539 /// frontend options.
2540 static const auto &getFrontendActionTable() {
2541 static const std::pair<frontend::ActionKind, unsigned> Table[] = {
2542 {frontend::ASTDeclList, OPT_ast_list},
2544 {frontend::ASTDump, OPT_ast_dump_all_EQ},
2545 {frontend::ASTDump, OPT_ast_dump_all},
2546 {frontend::ASTDump, OPT_ast_dump_EQ},
2547 {frontend::ASTDump, OPT_ast_dump},
2548 {frontend::ASTDump, OPT_ast_dump_lookups},
2549 {frontend::ASTDump, OPT_ast_dump_decl_types},
2551 {frontend::ASTPrint, OPT_ast_print},
2552 {frontend::ASTView, OPT_ast_view},
2553 {frontend::DumpCompilerOptions, OPT_compiler_options_dump},
2554 {frontend::DumpRawTokens, OPT_dump_raw_tokens},
2555 {frontend::DumpTokens, OPT_dump_tokens},
2556 {frontend::EmitAssembly, OPT_S},
2557 {frontend::EmitBC, OPT_emit_llvm_bc},
2558 {frontend::EmitHTML, OPT_emit_html},
2559 {frontend::EmitLLVM, OPT_emit_llvm},
2560 {frontend::EmitLLVMOnly, OPT_emit_llvm_only},
2561 {frontend::EmitCodeGenOnly, OPT_emit_codegen_only},
2562 {frontend::EmitObj, OPT_emit_obj},
2563 {frontend::ExtractAPI, OPT_extract_api},
2565 {frontend::FixIt, OPT_fixit_EQ},
2566 {frontend::FixIt, OPT_fixit},
2568 {frontend::GenerateModule, OPT_emit_module},
2569 {frontend::GenerateModuleInterface, OPT_emit_module_interface},
2570 {frontend::GenerateHeaderUnit, OPT_emit_header_unit},
2571 {frontend::GeneratePCH, OPT_emit_pch},
2572 {frontend::GenerateInterfaceStubs, OPT_emit_interface_stubs},
2573 {frontend::InitOnly, OPT_init_only},
2574 {frontend::ParseSyntaxOnly, OPT_fsyntax_only},
2575 {frontend::ModuleFileInfo, OPT_module_file_info},
2576 {frontend::VerifyPCH, OPT_verify_pch},
2577 {frontend::PrintPreamble, OPT_print_preamble},
2578 {frontend::PrintPreprocessedInput, OPT_E},
2579 {frontend::TemplightDump, OPT_templight_dump},
2580 {frontend::RewriteMacros, OPT_rewrite_macros},
2581 {frontend::RewriteObjC, OPT_rewrite_objc},
2582 {frontend::RewriteTest, OPT_rewrite_test},
2583 {frontend::RunAnalysis, OPT_analyze},
2584 {frontend::MigrateSource, OPT_migrate},
2585 {frontend::RunPreprocessorOnly, OPT_Eonly},
2586 {frontend::PrintDependencyDirectivesSourceMinimizerOutput,
2587 OPT_print_dependency_directives_minimized_source},
2590 return Table;
2593 /// Maps command line option to frontend action.
2594 static std::optional<frontend::ActionKind>
2595 getFrontendAction(OptSpecifier &Opt) {
2596 for (const auto &ActionOpt : getFrontendActionTable())
2597 if (ActionOpt.second == Opt.getID())
2598 return ActionOpt.first;
2600 return std::nullopt;
2603 /// Maps frontend action to command line option.
2604 static std::optional<OptSpecifier>
2605 getProgramActionOpt(frontend::ActionKind ProgramAction) {
2606 for (const auto &ActionOpt : getFrontendActionTable())
2607 if (ActionOpt.first == ProgramAction)
2608 return OptSpecifier(ActionOpt.second);
2610 return std::nullopt;
2613 static void GenerateFrontendArgs(const FrontendOptions &Opts,
2614 ArgumentConsumer Consumer, bool IsHeader) {
2615 const FrontendOptions &FrontendOpts = Opts;
2616 #define FRONTEND_OPTION_WITH_MARSHALLING(...) \
2617 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
2618 #include "clang/Driver/Options.inc"
2619 #undef FRONTEND_OPTION_WITH_MARSHALLING
2621 std::optional<OptSpecifier> ProgramActionOpt =
2622 getProgramActionOpt(Opts.ProgramAction);
2624 // Generating a simple flag covers most frontend actions.
2625 std::function<void()> GenerateProgramAction = [&]() {
2626 GenerateArg(Consumer, *ProgramActionOpt);
2629 if (!ProgramActionOpt) {
2630 // PluginAction is the only program action handled separately.
2631 assert(Opts.ProgramAction == frontend::PluginAction &&
2632 "Frontend action without option.");
2633 GenerateProgramAction = [&]() {
2634 GenerateArg(Consumer, OPT_plugin, Opts.ActionName);
2638 // FIXME: Simplify the complex 'AST dump' command line.
2639 if (Opts.ProgramAction == frontend::ASTDump) {
2640 GenerateProgramAction = [&]() {
2641 // ASTDumpLookups, ASTDumpDeclTypes and ASTDumpFilter are generated via
2642 // marshalling infrastructure.
2644 if (Opts.ASTDumpFormat != ADOF_Default) {
2645 StringRef Format;
2646 switch (Opts.ASTDumpFormat) {
2647 case ADOF_Default:
2648 llvm_unreachable("Default AST dump format.");
2649 case ADOF_JSON:
2650 Format = "json";
2651 break;
2654 if (Opts.ASTDumpAll)
2655 GenerateArg(Consumer, OPT_ast_dump_all_EQ, Format);
2656 if (Opts.ASTDumpDecls)
2657 GenerateArg(Consumer, OPT_ast_dump_EQ, Format);
2658 } else {
2659 if (Opts.ASTDumpAll)
2660 GenerateArg(Consumer, OPT_ast_dump_all);
2661 if (Opts.ASTDumpDecls)
2662 GenerateArg(Consumer, OPT_ast_dump);
2667 if (Opts.ProgramAction == frontend::FixIt && !Opts.FixItSuffix.empty()) {
2668 GenerateProgramAction = [&]() {
2669 GenerateArg(Consumer, OPT_fixit_EQ, Opts.FixItSuffix);
2673 GenerateProgramAction();
2675 for (const auto &PluginArgs : Opts.PluginArgs) {
2676 Option Opt = getDriverOptTable().getOption(OPT_plugin_arg);
2677 for (const auto &PluginArg : PluginArgs.second)
2678 denormalizeString(Consumer,
2679 Opt.getPrefix() + Opt.getName() + PluginArgs.first,
2680 Opt.getKind(), 0, PluginArg);
2683 for (const auto &Ext : Opts.ModuleFileExtensions)
2684 if (auto *TestExt = dyn_cast_or_null<TestModuleFileExtension>(Ext.get()))
2685 GenerateArg(Consumer, OPT_ftest_module_file_extension_EQ, TestExt->str());
2687 if (!Opts.CodeCompletionAt.FileName.empty())
2688 GenerateArg(Consumer, OPT_code_completion_at,
2689 Opts.CodeCompletionAt.ToString());
2691 for (const auto &Plugin : Opts.Plugins)
2692 GenerateArg(Consumer, OPT_load, Plugin);
2694 // ASTDumpDecls and ASTDumpAll already handled with ProgramAction.
2696 for (const auto &ModuleFile : Opts.ModuleFiles)
2697 GenerateArg(Consumer, OPT_fmodule_file, ModuleFile);
2699 if (Opts.AuxTargetCPU)
2700 GenerateArg(Consumer, OPT_aux_target_cpu, *Opts.AuxTargetCPU);
2702 if (Opts.AuxTargetFeatures)
2703 for (const auto &Feature : *Opts.AuxTargetFeatures)
2704 GenerateArg(Consumer, OPT_aux_target_feature, Feature);
2707 StringRef Preprocessed = Opts.DashX.isPreprocessed() ? "-cpp-output" : "";
2708 StringRef ModuleMap =
2709 Opts.DashX.getFormat() == InputKind::ModuleMap ? "-module-map" : "";
2710 StringRef HeaderUnit = "";
2711 switch (Opts.DashX.getHeaderUnitKind()) {
2712 case InputKind::HeaderUnit_None:
2713 break;
2714 case InputKind::HeaderUnit_User:
2715 HeaderUnit = "-user";
2716 break;
2717 case InputKind::HeaderUnit_System:
2718 HeaderUnit = "-system";
2719 break;
2720 case InputKind::HeaderUnit_Abs:
2721 HeaderUnit = "-header-unit";
2722 break;
2724 StringRef Header = IsHeader ? "-header" : "";
2726 StringRef Lang;
2727 switch (Opts.DashX.getLanguage()) {
2728 case Language::C:
2729 Lang = "c";
2730 break;
2731 case Language::OpenCL:
2732 Lang = "cl";
2733 break;
2734 case Language::OpenCLCXX:
2735 Lang = "clcpp";
2736 break;
2737 case Language::CUDA:
2738 Lang = "cuda";
2739 break;
2740 case Language::HIP:
2741 Lang = "hip";
2742 break;
2743 case Language::CXX:
2744 Lang = "c++";
2745 break;
2746 case Language::ObjC:
2747 Lang = "objective-c";
2748 break;
2749 case Language::ObjCXX:
2750 Lang = "objective-c++";
2751 break;
2752 case Language::RenderScript:
2753 Lang = "renderscript";
2754 break;
2755 case Language::Asm:
2756 Lang = "assembler-with-cpp";
2757 break;
2758 case Language::Unknown:
2759 assert(Opts.DashX.getFormat() == InputKind::Precompiled &&
2760 "Generating -x argument for unknown language (not precompiled).");
2761 Lang = "ast";
2762 break;
2763 case Language::LLVM_IR:
2764 Lang = "ir";
2765 break;
2766 case Language::HLSL:
2767 Lang = "hlsl";
2768 break;
2771 GenerateArg(Consumer, OPT_x,
2772 Lang + HeaderUnit + Header + ModuleMap + Preprocessed);
2775 // OPT_INPUT has a unique class, generate it directly.
2776 for (const auto &Input : Opts.Inputs)
2777 Consumer(Input.getFile());
2780 static bool ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args,
2781 DiagnosticsEngine &Diags, bool &IsHeaderFile) {
2782 unsigned NumErrorsBefore = Diags.getNumErrors();
2784 FrontendOptions &FrontendOpts = Opts;
2786 #define FRONTEND_OPTION_WITH_MARSHALLING(...) \
2787 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
2788 #include "clang/Driver/Options.inc"
2789 #undef FRONTEND_OPTION_WITH_MARSHALLING
2791 Opts.ProgramAction = frontend::ParseSyntaxOnly;
2792 if (const Arg *A = Args.getLastArg(OPT_Action_Group)) {
2793 OptSpecifier Opt = OptSpecifier(A->getOption().getID());
2794 std::optional<frontend::ActionKind> ProgramAction = getFrontendAction(Opt);
2795 assert(ProgramAction && "Option specifier not in Action_Group.");
2797 if (ProgramAction == frontend::ASTDump &&
2798 (Opt == OPT_ast_dump_all_EQ || Opt == OPT_ast_dump_EQ)) {
2799 unsigned Val = llvm::StringSwitch<unsigned>(A->getValue())
2800 .CaseLower("default", ADOF_Default)
2801 .CaseLower("json", ADOF_JSON)
2802 .Default(std::numeric_limits<unsigned>::max());
2804 if (Val != std::numeric_limits<unsigned>::max())
2805 Opts.ASTDumpFormat = static_cast<ASTDumpOutputFormat>(Val);
2806 else {
2807 Diags.Report(diag::err_drv_invalid_value)
2808 << A->getAsString(Args) << A->getValue();
2809 Opts.ASTDumpFormat = ADOF_Default;
2813 if (ProgramAction == frontend::FixIt && Opt == OPT_fixit_EQ)
2814 Opts.FixItSuffix = A->getValue();
2816 if (ProgramAction == frontend::GenerateInterfaceStubs) {
2817 StringRef ArgStr =
2818 Args.hasArg(OPT_interface_stub_version_EQ)
2819 ? Args.getLastArgValue(OPT_interface_stub_version_EQ)
2820 : "ifs-v1";
2821 if (ArgStr == "experimental-yaml-elf-v1" ||
2822 ArgStr == "experimental-ifs-v1" || ArgStr == "experimental-ifs-v2" ||
2823 ArgStr == "experimental-tapi-elf-v1") {
2824 std::string ErrorMessage =
2825 "Invalid interface stub format: " + ArgStr.str() +
2826 " is deprecated.";
2827 Diags.Report(diag::err_drv_invalid_value)
2828 << "Must specify a valid interface stub format type, ie: "
2829 "-interface-stub-version=ifs-v1"
2830 << ErrorMessage;
2831 ProgramAction = frontend::ParseSyntaxOnly;
2832 } else if (!ArgStr.starts_with("ifs-")) {
2833 std::string ErrorMessage =
2834 "Invalid interface stub format: " + ArgStr.str() + ".";
2835 Diags.Report(diag::err_drv_invalid_value)
2836 << "Must specify a valid interface stub format type, ie: "
2837 "-interface-stub-version=ifs-v1"
2838 << ErrorMessage;
2839 ProgramAction = frontend::ParseSyntaxOnly;
2843 Opts.ProgramAction = *ProgramAction;
2846 if (const Arg* A = Args.getLastArg(OPT_plugin)) {
2847 Opts.Plugins.emplace_back(A->getValue(0));
2848 Opts.ProgramAction = frontend::PluginAction;
2849 Opts.ActionName = A->getValue();
2851 for (const auto *AA : Args.filtered(OPT_plugin_arg))
2852 Opts.PluginArgs[AA->getValue(0)].emplace_back(AA->getValue(1));
2854 for (const std::string &Arg :
2855 Args.getAllArgValues(OPT_ftest_module_file_extension_EQ)) {
2856 std::string BlockName;
2857 unsigned MajorVersion;
2858 unsigned MinorVersion;
2859 bool Hashed;
2860 std::string UserInfo;
2861 if (parseTestModuleFileExtensionArg(Arg, BlockName, MajorVersion,
2862 MinorVersion, Hashed, UserInfo)) {
2863 Diags.Report(diag::err_test_module_file_extension_format) << Arg;
2865 continue;
2868 // Add the testing module file extension.
2869 Opts.ModuleFileExtensions.push_back(
2870 std::make_shared<TestModuleFileExtension>(
2871 BlockName, MajorVersion, MinorVersion, Hashed, UserInfo));
2874 if (const Arg *A = Args.getLastArg(OPT_code_completion_at)) {
2875 Opts.CodeCompletionAt =
2876 ParsedSourceLocation::FromString(A->getValue());
2877 if (Opts.CodeCompletionAt.FileName.empty())
2878 Diags.Report(diag::err_drv_invalid_value)
2879 << A->getAsString(Args) << A->getValue();
2882 Opts.Plugins = Args.getAllArgValues(OPT_load);
2883 Opts.ASTDumpDecls = Args.hasArg(OPT_ast_dump, OPT_ast_dump_EQ);
2884 Opts.ASTDumpAll = Args.hasArg(OPT_ast_dump_all, OPT_ast_dump_all_EQ);
2885 // Only the -fmodule-file=<file> form.
2886 for (const auto *A : Args.filtered(OPT_fmodule_file)) {
2887 StringRef Val = A->getValue();
2888 if (!Val.contains('='))
2889 Opts.ModuleFiles.push_back(std::string(Val));
2892 if (Opts.ProgramAction != frontend::GenerateModule && Opts.IsSystemModule)
2893 Diags.Report(diag::err_drv_argument_only_allowed_with) << "-fsystem-module"
2894 << "-emit-module";
2896 if (Args.hasArg(OPT_aux_target_cpu))
2897 Opts.AuxTargetCPU = std::string(Args.getLastArgValue(OPT_aux_target_cpu));
2898 if (Args.hasArg(OPT_aux_target_feature))
2899 Opts.AuxTargetFeatures = Args.getAllArgValues(OPT_aux_target_feature);
2901 if (Opts.ARCMTAction != FrontendOptions::ARCMT_None &&
2902 Opts.ObjCMTAction != FrontendOptions::ObjCMT_None) {
2903 Diags.Report(diag::err_drv_argument_not_allowed_with)
2904 << "ARC migration" << "ObjC migration";
2907 InputKind DashX(Language::Unknown);
2908 if (const Arg *A = Args.getLastArg(OPT_x)) {
2909 StringRef XValue = A->getValue();
2911 // Parse suffixes:
2912 // '<lang>(-[{header-unit,user,system}-]header|[-module-map][-cpp-output])'.
2913 // FIXME: Supporting '<lang>-header-cpp-output' would be useful.
2914 bool Preprocessed = XValue.consume_back("-cpp-output");
2915 bool ModuleMap = XValue.consume_back("-module-map");
2916 // Detect and consume the header indicator.
2917 bool IsHeader =
2918 XValue != "precompiled-header" && XValue.consume_back("-header");
2920 // If we have c++-{user,system}-header, that indicates a header unit input
2921 // likewise, if the user put -fmodule-header together with a header with an
2922 // absolute path (header-unit-header).
2923 InputKind::HeaderUnitKind HUK = InputKind::HeaderUnit_None;
2924 if (IsHeader || Preprocessed) {
2925 if (XValue.consume_back("-header-unit"))
2926 HUK = InputKind::HeaderUnit_Abs;
2927 else if (XValue.consume_back("-system"))
2928 HUK = InputKind::HeaderUnit_System;
2929 else if (XValue.consume_back("-user"))
2930 HUK = InputKind::HeaderUnit_User;
2933 // The value set by this processing is an un-preprocessed source which is
2934 // not intended to be a module map or header unit.
2935 IsHeaderFile = IsHeader && !Preprocessed && !ModuleMap &&
2936 HUK == InputKind::HeaderUnit_None;
2938 // Principal languages.
2939 DashX = llvm::StringSwitch<InputKind>(XValue)
2940 .Case("c", Language::C)
2941 .Case("cl", Language::OpenCL)
2942 .Case("clcpp", Language::OpenCLCXX)
2943 .Case("cuda", Language::CUDA)
2944 .Case("hip", Language::HIP)
2945 .Case("c++", Language::CXX)
2946 .Case("objective-c", Language::ObjC)
2947 .Case("objective-c++", Language::ObjCXX)
2948 .Case("renderscript", Language::RenderScript)
2949 .Case("hlsl", Language::HLSL)
2950 .Default(Language::Unknown);
2952 // "objc[++]-cpp-output" is an acceptable synonym for
2953 // "objective-c[++]-cpp-output".
2954 if (DashX.isUnknown() && Preprocessed && !IsHeaderFile && !ModuleMap &&
2955 HUK == InputKind::HeaderUnit_None)
2956 DashX = llvm::StringSwitch<InputKind>(XValue)
2957 .Case("objc", Language::ObjC)
2958 .Case("objc++", Language::ObjCXX)
2959 .Default(Language::Unknown);
2961 // Some special cases cannot be combined with suffixes.
2962 if (DashX.isUnknown() && !Preprocessed && !IsHeaderFile && !ModuleMap &&
2963 HUK == InputKind::HeaderUnit_None)
2964 DashX = llvm::StringSwitch<InputKind>(XValue)
2965 .Case("cpp-output", InputKind(Language::C).getPreprocessed())
2966 .Case("assembler-with-cpp", Language::Asm)
2967 .Cases("ast", "pcm", "precompiled-header",
2968 InputKind(Language::Unknown, InputKind::Precompiled))
2969 .Case("ir", Language::LLVM_IR)
2970 .Default(Language::Unknown);
2972 if (DashX.isUnknown())
2973 Diags.Report(diag::err_drv_invalid_value)
2974 << A->getAsString(Args) << A->getValue();
2976 if (Preprocessed)
2977 DashX = DashX.getPreprocessed();
2978 // A regular header is considered mutually exclusive with a header unit.
2979 if (HUK != InputKind::HeaderUnit_None) {
2980 DashX = DashX.withHeaderUnit(HUK);
2981 IsHeaderFile = true;
2982 } else if (IsHeaderFile)
2983 DashX = DashX.getHeader();
2984 if (ModuleMap)
2985 DashX = DashX.withFormat(InputKind::ModuleMap);
2988 // '-' is the default input if none is given.
2989 std::vector<std::string> Inputs = Args.getAllArgValues(OPT_INPUT);
2990 Opts.Inputs.clear();
2991 if (Inputs.empty())
2992 Inputs.push_back("-");
2994 if (DashX.getHeaderUnitKind() != InputKind::HeaderUnit_None &&
2995 Inputs.size() > 1)
2996 Diags.Report(diag::err_drv_header_unit_extra_inputs) << Inputs[1];
2998 for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
2999 InputKind IK = DashX;
3000 if (IK.isUnknown()) {
3001 IK = FrontendOptions::getInputKindForExtension(
3002 StringRef(Inputs[i]).rsplit('.').second);
3003 // FIXME: Warn on this?
3004 if (IK.isUnknown())
3005 IK = Language::C;
3006 // FIXME: Remove this hack.
3007 if (i == 0)
3008 DashX = IK;
3011 bool IsSystem = false;
3013 // The -emit-module action implicitly takes a module map.
3014 if (Opts.ProgramAction == frontend::GenerateModule &&
3015 IK.getFormat() == InputKind::Source) {
3016 IK = IK.withFormat(InputKind::ModuleMap);
3017 IsSystem = Opts.IsSystemModule;
3020 Opts.Inputs.emplace_back(std::move(Inputs[i]), IK, IsSystem);
3023 Opts.DashX = DashX;
3025 return Diags.getNumErrors() == NumErrorsBefore;
3028 std::string CompilerInvocation::GetResourcesPath(const char *Argv0,
3029 void *MainAddr) {
3030 std::string ClangExecutable =
3031 llvm::sys::fs::getMainExecutable(Argv0, MainAddr);
3032 return Driver::GetResourcesPath(ClangExecutable, CLANG_RESOURCE_DIR);
3035 static void GenerateHeaderSearchArgs(const HeaderSearchOptions &Opts,
3036 ArgumentConsumer Consumer) {
3037 const HeaderSearchOptions *HeaderSearchOpts = &Opts;
3038 #define HEADER_SEARCH_OPTION_WITH_MARSHALLING(...) \
3039 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
3040 #include "clang/Driver/Options.inc"
3041 #undef HEADER_SEARCH_OPTION_WITH_MARSHALLING
3043 if (Opts.UseLibcxx)
3044 GenerateArg(Consumer, OPT_stdlib_EQ, "libc++");
3046 if (!Opts.ModuleCachePath.empty())
3047 GenerateArg(Consumer, OPT_fmodules_cache_path, Opts.ModuleCachePath);
3049 for (const auto &File : Opts.PrebuiltModuleFiles)
3050 GenerateArg(Consumer, OPT_fmodule_file, File.first + "=" + File.second);
3052 for (const auto &Path : Opts.PrebuiltModulePaths)
3053 GenerateArg(Consumer, OPT_fprebuilt_module_path, Path);
3055 for (const auto &Macro : Opts.ModulesIgnoreMacros)
3056 GenerateArg(Consumer, OPT_fmodules_ignore_macro, Macro.val());
3058 auto Matches = [](const HeaderSearchOptions::Entry &Entry,
3059 llvm::ArrayRef<frontend::IncludeDirGroup> Groups,
3060 std::optional<bool> IsFramework,
3061 std::optional<bool> IgnoreSysRoot) {
3062 return llvm::is_contained(Groups, Entry.Group) &&
3063 (!IsFramework || (Entry.IsFramework == *IsFramework)) &&
3064 (!IgnoreSysRoot || (Entry.IgnoreSysRoot == *IgnoreSysRoot));
3067 auto It = Opts.UserEntries.begin();
3068 auto End = Opts.UserEntries.end();
3070 // Add -I..., -F..., and -index-header-map options in order.
3071 for (; It < End && Matches(*It, {frontend::IndexHeaderMap, frontend::Angled},
3072 std::nullopt, true);
3073 ++It) {
3074 OptSpecifier Opt = [It, Matches]() {
3075 if (Matches(*It, frontend::IndexHeaderMap, true, true))
3076 return OPT_F;
3077 if (Matches(*It, frontend::IndexHeaderMap, false, true))
3078 return OPT_I;
3079 if (Matches(*It, frontend::Angled, true, true))
3080 return OPT_F;
3081 if (Matches(*It, frontend::Angled, false, true))
3082 return OPT_I;
3083 llvm_unreachable("Unexpected HeaderSearchOptions::Entry.");
3084 }();
3086 if (It->Group == frontend::IndexHeaderMap)
3087 GenerateArg(Consumer, OPT_index_header_map);
3088 GenerateArg(Consumer, Opt, It->Path);
3091 // Note: some paths that came from "[-iprefix=xx] -iwithprefixbefore=yy" may
3092 // have already been generated as "-I[xx]yy". If that's the case, their
3093 // position on command line was such that this has no semantic impact on
3094 // include paths.
3095 for (; It < End &&
3096 Matches(*It, {frontend::After, frontend::Angled}, false, true);
3097 ++It) {
3098 OptSpecifier Opt =
3099 It->Group == frontend::After ? OPT_iwithprefix : OPT_iwithprefixbefore;
3100 GenerateArg(Consumer, Opt, It->Path);
3103 // Note: Some paths that came from "-idirafter=xxyy" may have already been
3104 // generated as "-iwithprefix=xxyy". If that's the case, their position on
3105 // command line was such that this has no semantic impact on include paths.
3106 for (; It < End && Matches(*It, {frontend::After}, false, true); ++It)
3107 GenerateArg(Consumer, OPT_idirafter, It->Path);
3108 for (; It < End && Matches(*It, {frontend::Quoted}, false, true); ++It)
3109 GenerateArg(Consumer, OPT_iquote, It->Path);
3110 for (; It < End && Matches(*It, {frontend::System}, false, std::nullopt);
3111 ++It)
3112 GenerateArg(Consumer, It->IgnoreSysRoot ? OPT_isystem : OPT_iwithsysroot,
3113 It->Path);
3114 for (; It < End && Matches(*It, {frontend::System}, true, true); ++It)
3115 GenerateArg(Consumer, OPT_iframework, It->Path);
3116 for (; It < End && Matches(*It, {frontend::System}, true, false); ++It)
3117 GenerateArg(Consumer, OPT_iframeworkwithsysroot, It->Path);
3119 // Add the paths for the various language specific isystem flags.
3120 for (; It < End && Matches(*It, {frontend::CSystem}, false, true); ++It)
3121 GenerateArg(Consumer, OPT_c_isystem, It->Path);
3122 for (; It < End && Matches(*It, {frontend::CXXSystem}, false, true); ++It)
3123 GenerateArg(Consumer, OPT_cxx_isystem, It->Path);
3124 for (; It < End && Matches(*It, {frontend::ObjCSystem}, false, true); ++It)
3125 GenerateArg(Consumer, OPT_objc_isystem, It->Path);
3126 for (; It < End && Matches(*It, {frontend::ObjCXXSystem}, false, true); ++It)
3127 GenerateArg(Consumer, OPT_objcxx_isystem, It->Path);
3129 // Add the internal paths from a driver that detects standard include paths.
3130 // Note: Some paths that came from "-internal-isystem" arguments may have
3131 // already been generated as "-isystem". If that's the case, their position on
3132 // command line was such that this has no semantic impact on include paths.
3133 for (; It < End &&
3134 Matches(*It, {frontend::System, frontend::ExternCSystem}, false, true);
3135 ++It) {
3136 OptSpecifier Opt = It->Group == frontend::System
3137 ? OPT_internal_isystem
3138 : OPT_internal_externc_isystem;
3139 GenerateArg(Consumer, Opt, It->Path);
3142 assert(It == End && "Unhandled HeaderSearchOption::Entry.");
3144 // Add the path prefixes which are implicitly treated as being system headers.
3145 for (const auto &P : Opts.SystemHeaderPrefixes) {
3146 OptSpecifier Opt = P.IsSystemHeader ? OPT_system_header_prefix
3147 : OPT_no_system_header_prefix;
3148 GenerateArg(Consumer, Opt, P.Prefix);
3151 for (const std::string &F : Opts.VFSOverlayFiles)
3152 GenerateArg(Consumer, OPT_ivfsoverlay, F);
3155 static bool ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args,
3156 DiagnosticsEngine &Diags,
3157 const std::string &WorkingDir) {
3158 unsigned NumErrorsBefore = Diags.getNumErrors();
3160 HeaderSearchOptions *HeaderSearchOpts = &Opts;
3162 #define HEADER_SEARCH_OPTION_WITH_MARSHALLING(...) \
3163 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
3164 #include "clang/Driver/Options.inc"
3165 #undef HEADER_SEARCH_OPTION_WITH_MARSHALLING
3167 if (const Arg *A = Args.getLastArg(OPT_stdlib_EQ))
3168 Opts.UseLibcxx = (strcmp(A->getValue(), "libc++") == 0);
3170 // Canonicalize -fmodules-cache-path before storing it.
3171 SmallString<128> P(Args.getLastArgValue(OPT_fmodules_cache_path));
3172 if (!(P.empty() || llvm::sys::path::is_absolute(P))) {
3173 if (WorkingDir.empty())
3174 llvm::sys::fs::make_absolute(P);
3175 else
3176 llvm::sys::fs::make_absolute(WorkingDir, P);
3178 llvm::sys::path::remove_dots(P);
3179 Opts.ModuleCachePath = std::string(P.str());
3181 // Only the -fmodule-file=<name>=<file> form.
3182 for (const auto *A : Args.filtered(OPT_fmodule_file)) {
3183 StringRef Val = A->getValue();
3184 if (Val.contains('=')) {
3185 auto Split = Val.split('=');
3186 Opts.PrebuiltModuleFiles.insert_or_assign(
3187 std::string(Split.first), std::string(Split.second));
3190 for (const auto *A : Args.filtered(OPT_fprebuilt_module_path))
3191 Opts.AddPrebuiltModulePath(A->getValue());
3193 for (const auto *A : Args.filtered(OPT_fmodules_ignore_macro)) {
3194 StringRef MacroDef = A->getValue();
3195 Opts.ModulesIgnoreMacros.insert(
3196 llvm::CachedHashString(MacroDef.split('=').first));
3199 // Add -I..., -F..., and -index-header-map options in order.
3200 bool IsIndexHeaderMap = false;
3201 bool IsSysrootSpecified =
3202 Args.hasArg(OPT__sysroot_EQ) || Args.hasArg(OPT_isysroot);
3203 for (const auto *A : Args.filtered(OPT_I, OPT_F, OPT_index_header_map)) {
3204 if (A->getOption().matches(OPT_index_header_map)) {
3205 // -index-header-map applies to the next -I or -F.
3206 IsIndexHeaderMap = true;
3207 continue;
3210 frontend::IncludeDirGroup Group =
3211 IsIndexHeaderMap ? frontend::IndexHeaderMap : frontend::Angled;
3213 bool IsFramework = A->getOption().matches(OPT_F);
3214 std::string Path = A->getValue();
3216 if (IsSysrootSpecified && !IsFramework && A->getValue()[0] == '=') {
3217 SmallString<32> Buffer;
3218 llvm::sys::path::append(Buffer, Opts.Sysroot,
3219 llvm::StringRef(A->getValue()).substr(1));
3220 Path = std::string(Buffer.str());
3223 Opts.AddPath(Path, Group, IsFramework,
3224 /*IgnoreSysroot*/ true);
3225 IsIndexHeaderMap = false;
3228 // Add -iprefix/-iwithprefix/-iwithprefixbefore options.
3229 StringRef Prefix = ""; // FIXME: This isn't the correct default prefix.
3230 for (const auto *A :
3231 Args.filtered(OPT_iprefix, OPT_iwithprefix, OPT_iwithprefixbefore)) {
3232 if (A->getOption().matches(OPT_iprefix))
3233 Prefix = A->getValue();
3234 else if (A->getOption().matches(OPT_iwithprefix))
3235 Opts.AddPath(Prefix.str() + A->getValue(), frontend::After, false, true);
3236 else
3237 Opts.AddPath(Prefix.str() + A->getValue(), frontend::Angled, false, true);
3240 for (const auto *A : Args.filtered(OPT_idirafter))
3241 Opts.AddPath(A->getValue(), frontend::After, false, true);
3242 for (const auto *A : Args.filtered(OPT_iquote))
3243 Opts.AddPath(A->getValue(), frontend::Quoted, false, true);
3244 for (const auto *A : Args.filtered(OPT_isystem, OPT_iwithsysroot))
3245 Opts.AddPath(A->getValue(), frontend::System, false,
3246 !A->getOption().matches(OPT_iwithsysroot));
3247 for (const auto *A : Args.filtered(OPT_iframework))
3248 Opts.AddPath(A->getValue(), frontend::System, true, true);
3249 for (const auto *A : Args.filtered(OPT_iframeworkwithsysroot))
3250 Opts.AddPath(A->getValue(), frontend::System, /*IsFramework=*/true,
3251 /*IgnoreSysRoot=*/false);
3253 // Add the paths for the various language specific isystem flags.
3254 for (const auto *A : Args.filtered(OPT_c_isystem))
3255 Opts.AddPath(A->getValue(), frontend::CSystem, false, true);
3256 for (const auto *A : Args.filtered(OPT_cxx_isystem))
3257 Opts.AddPath(A->getValue(), frontend::CXXSystem, false, true);
3258 for (const auto *A : Args.filtered(OPT_objc_isystem))
3259 Opts.AddPath(A->getValue(), frontend::ObjCSystem, false,true);
3260 for (const auto *A : Args.filtered(OPT_objcxx_isystem))
3261 Opts.AddPath(A->getValue(), frontend::ObjCXXSystem, false, true);
3263 // Add the internal paths from a driver that detects standard include paths.
3264 for (const auto *A :
3265 Args.filtered(OPT_internal_isystem, OPT_internal_externc_isystem)) {
3266 frontend::IncludeDirGroup Group = frontend::System;
3267 if (A->getOption().matches(OPT_internal_externc_isystem))
3268 Group = frontend::ExternCSystem;
3269 Opts.AddPath(A->getValue(), Group, false, true);
3272 // Add the path prefixes which are implicitly treated as being system headers.
3273 for (const auto *A :
3274 Args.filtered(OPT_system_header_prefix, OPT_no_system_header_prefix))
3275 Opts.AddSystemHeaderPrefix(
3276 A->getValue(), A->getOption().matches(OPT_system_header_prefix));
3278 for (const auto *A : Args.filtered(OPT_ivfsoverlay, OPT_vfsoverlay))
3279 Opts.AddVFSOverlayFile(A->getValue());
3281 return Diags.getNumErrors() == NumErrorsBefore;
3284 static void GenerateAPINotesArgs(const APINotesOptions &Opts,
3285 ArgumentConsumer Consumer) {
3286 if (!Opts.SwiftVersion.empty())
3287 GenerateArg(Consumer, OPT_fapinotes_swift_version,
3288 Opts.SwiftVersion.getAsString());
3290 for (const auto &Path : Opts.ModuleSearchPaths)
3291 GenerateArg(Consumer, OPT_iapinotes_modules, Path);
3294 static void ParseAPINotesArgs(APINotesOptions &Opts, ArgList &Args,
3295 DiagnosticsEngine &diags) {
3296 if (const Arg *A = Args.getLastArg(OPT_fapinotes_swift_version)) {
3297 if (Opts.SwiftVersion.tryParse(A->getValue()))
3298 diags.Report(diag::err_drv_invalid_value)
3299 << A->getAsString(Args) << A->getValue();
3301 for (const Arg *A : Args.filtered(OPT_iapinotes_modules))
3302 Opts.ModuleSearchPaths.push_back(A->getValue());
3305 /// Check if input file kind and language standard are compatible.
3306 static bool IsInputCompatibleWithStandard(InputKind IK,
3307 const LangStandard &S) {
3308 switch (IK.getLanguage()) {
3309 case Language::Unknown:
3310 case Language::LLVM_IR:
3311 llvm_unreachable("should not parse language flags for this input");
3313 case Language::C:
3314 case Language::ObjC:
3315 case Language::RenderScript:
3316 return S.getLanguage() == Language::C;
3318 case Language::OpenCL:
3319 return S.getLanguage() == Language::OpenCL ||
3320 S.getLanguage() == Language::OpenCLCXX;
3322 case Language::OpenCLCXX:
3323 return S.getLanguage() == Language::OpenCLCXX;
3325 case Language::CXX:
3326 case Language::ObjCXX:
3327 return S.getLanguage() == Language::CXX;
3329 case Language::CUDA:
3330 // FIXME: What -std= values should be permitted for CUDA compilations?
3331 return S.getLanguage() == Language::CUDA ||
3332 S.getLanguage() == Language::CXX;
3334 case Language::HIP:
3335 return S.getLanguage() == Language::CXX || S.getLanguage() == Language::HIP;
3337 case Language::Asm:
3338 // Accept (and ignore) all -std= values.
3339 // FIXME: The -std= value is not ignored; it affects the tokenization
3340 // and preprocessing rules if we're preprocessing this asm input.
3341 return true;
3343 case Language::HLSL:
3344 return S.getLanguage() == Language::HLSL;
3347 llvm_unreachable("unexpected input language");
3350 /// Get language name for given input kind.
3351 static StringRef GetInputKindName(InputKind IK) {
3352 switch (IK.getLanguage()) {
3353 case Language::C:
3354 return "C";
3355 case Language::ObjC:
3356 return "Objective-C";
3357 case Language::CXX:
3358 return "C++";
3359 case Language::ObjCXX:
3360 return "Objective-C++";
3361 case Language::OpenCL:
3362 return "OpenCL";
3363 case Language::OpenCLCXX:
3364 return "C++ for OpenCL";
3365 case Language::CUDA:
3366 return "CUDA";
3367 case Language::RenderScript:
3368 return "RenderScript";
3369 case Language::HIP:
3370 return "HIP";
3372 case Language::Asm:
3373 return "Asm";
3374 case Language::LLVM_IR:
3375 return "LLVM IR";
3377 case Language::HLSL:
3378 return "HLSL";
3380 case Language::Unknown:
3381 break;
3383 llvm_unreachable("unknown input language");
3386 void CompilerInvocationBase::GenerateLangArgs(const LangOptions &Opts,
3387 ArgumentConsumer Consumer,
3388 const llvm::Triple &T,
3389 InputKind IK) {
3390 if (IK.getFormat() == InputKind::Precompiled ||
3391 IK.getLanguage() == Language::LLVM_IR) {
3392 if (Opts.ObjCAutoRefCount)
3393 GenerateArg(Consumer, OPT_fobjc_arc);
3394 if (Opts.PICLevel != 0)
3395 GenerateArg(Consumer, OPT_pic_level, Twine(Opts.PICLevel));
3396 if (Opts.PIE)
3397 GenerateArg(Consumer, OPT_pic_is_pie);
3398 for (StringRef Sanitizer : serializeSanitizerKinds(Opts.Sanitize))
3399 GenerateArg(Consumer, OPT_fsanitize_EQ, Sanitizer);
3401 return;
3404 OptSpecifier StdOpt;
3405 switch (Opts.LangStd) {
3406 case LangStandard::lang_opencl10:
3407 case LangStandard::lang_opencl11:
3408 case LangStandard::lang_opencl12:
3409 case LangStandard::lang_opencl20:
3410 case LangStandard::lang_opencl30:
3411 case LangStandard::lang_openclcpp10:
3412 case LangStandard::lang_openclcpp2021:
3413 StdOpt = OPT_cl_std_EQ;
3414 break;
3415 default:
3416 StdOpt = OPT_std_EQ;
3417 break;
3420 auto LangStandard = LangStandard::getLangStandardForKind(Opts.LangStd);
3421 GenerateArg(Consumer, StdOpt, LangStandard.getName());
3423 if (Opts.IncludeDefaultHeader)
3424 GenerateArg(Consumer, OPT_finclude_default_header);
3425 if (Opts.DeclareOpenCLBuiltins)
3426 GenerateArg(Consumer, OPT_fdeclare_opencl_builtins);
3428 const LangOptions *LangOpts = &Opts;
3430 #define LANG_OPTION_WITH_MARSHALLING(...) \
3431 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
3432 #include "clang/Driver/Options.inc"
3433 #undef LANG_OPTION_WITH_MARSHALLING
3435 // The '-fcf-protection=' option is generated by CodeGenOpts generator.
3437 if (Opts.ObjC) {
3438 GenerateArg(Consumer, OPT_fobjc_runtime_EQ, Opts.ObjCRuntime.getAsString());
3440 if (Opts.GC == LangOptions::GCOnly)
3441 GenerateArg(Consumer, OPT_fobjc_gc_only);
3442 else if (Opts.GC == LangOptions::HybridGC)
3443 GenerateArg(Consumer, OPT_fobjc_gc);
3444 else if (Opts.ObjCAutoRefCount == 1)
3445 GenerateArg(Consumer, OPT_fobjc_arc);
3447 if (Opts.ObjCWeakRuntime)
3448 GenerateArg(Consumer, OPT_fobjc_runtime_has_weak);
3450 if (Opts.ObjCWeak)
3451 GenerateArg(Consumer, OPT_fobjc_weak);
3453 if (Opts.ObjCSubscriptingLegacyRuntime)
3454 GenerateArg(Consumer, OPT_fobjc_subscripting_legacy_runtime);
3457 if (Opts.GNUCVersion != 0) {
3458 unsigned Major = Opts.GNUCVersion / 100 / 100;
3459 unsigned Minor = (Opts.GNUCVersion / 100) % 100;
3460 unsigned Patch = Opts.GNUCVersion % 100;
3461 GenerateArg(Consumer, OPT_fgnuc_version_EQ,
3462 Twine(Major) + "." + Twine(Minor) + "." + Twine(Patch));
3465 if (Opts.IgnoreXCOFFVisibility)
3466 GenerateArg(Consumer, OPT_mignore_xcoff_visibility);
3468 if (Opts.SignedOverflowBehavior == LangOptions::SOB_Trapping) {
3469 GenerateArg(Consumer, OPT_ftrapv);
3470 GenerateArg(Consumer, OPT_ftrapv_handler, Opts.OverflowHandler);
3471 } else if (Opts.SignedOverflowBehavior == LangOptions::SOB_Defined) {
3472 GenerateArg(Consumer, OPT_fwrapv);
3475 if (Opts.MSCompatibilityVersion != 0) {
3476 unsigned Major = Opts.MSCompatibilityVersion / 10000000;
3477 unsigned Minor = (Opts.MSCompatibilityVersion / 100000) % 100;
3478 unsigned Subminor = Opts.MSCompatibilityVersion % 100000;
3479 GenerateArg(Consumer, OPT_fms_compatibility_version,
3480 Twine(Major) + "." + Twine(Minor) + "." + Twine(Subminor));
3483 if ((!Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus17) || T.isOSzOS()) {
3484 if (!Opts.Trigraphs)
3485 GenerateArg(Consumer, OPT_fno_trigraphs);
3486 } else {
3487 if (Opts.Trigraphs)
3488 GenerateArg(Consumer, OPT_ftrigraphs);
3491 if (Opts.Blocks && !(Opts.OpenCL && Opts.OpenCLVersion == 200))
3492 GenerateArg(Consumer, OPT_fblocks);
3494 if (Opts.ConvergentFunctions &&
3495 !(Opts.OpenCL || (Opts.CUDA && Opts.CUDAIsDevice) || Opts.SYCLIsDevice))
3496 GenerateArg(Consumer, OPT_fconvergent_functions);
3498 if (Opts.NoBuiltin && !Opts.Freestanding)
3499 GenerateArg(Consumer, OPT_fno_builtin);
3501 if (!Opts.NoBuiltin)
3502 for (const auto &Func : Opts.NoBuiltinFuncs)
3503 GenerateArg(Consumer, OPT_fno_builtin_, Func);
3505 if (Opts.LongDoubleSize == 128)
3506 GenerateArg(Consumer, OPT_mlong_double_128);
3507 else if (Opts.LongDoubleSize == 64)
3508 GenerateArg(Consumer, OPT_mlong_double_64);
3509 else if (Opts.LongDoubleSize == 80)
3510 GenerateArg(Consumer, OPT_mlong_double_80);
3512 // Not generating '-mrtd', it's just an alias for '-fdefault-calling-conv='.
3514 // OpenMP was requested via '-fopenmp', not implied by '-fopenmp-simd' or
3515 // '-fopenmp-targets='.
3516 if (Opts.OpenMP && !Opts.OpenMPSimd) {
3517 GenerateArg(Consumer, OPT_fopenmp);
3519 if (Opts.OpenMP != 51)
3520 GenerateArg(Consumer, OPT_fopenmp_version_EQ, Twine(Opts.OpenMP));
3522 if (!Opts.OpenMPUseTLS)
3523 GenerateArg(Consumer, OPT_fnoopenmp_use_tls);
3525 if (Opts.OpenMPIsTargetDevice)
3526 GenerateArg(Consumer, OPT_fopenmp_is_target_device);
3528 if (Opts.OpenMPIRBuilder)
3529 GenerateArg(Consumer, OPT_fopenmp_enable_irbuilder);
3532 if (Opts.OpenMPSimd) {
3533 GenerateArg(Consumer, OPT_fopenmp_simd);
3535 if (Opts.OpenMP != 51)
3536 GenerateArg(Consumer, OPT_fopenmp_version_EQ, Twine(Opts.OpenMP));
3539 if (Opts.OpenMPThreadSubscription)
3540 GenerateArg(Consumer, OPT_fopenmp_assume_threads_oversubscription);
3542 if (Opts.OpenMPTeamSubscription)
3543 GenerateArg(Consumer, OPT_fopenmp_assume_teams_oversubscription);
3545 if (Opts.OpenMPTargetDebug != 0)
3546 GenerateArg(Consumer, OPT_fopenmp_target_debug_EQ,
3547 Twine(Opts.OpenMPTargetDebug));
3549 if (Opts.OpenMPCUDANumSMs != 0)
3550 GenerateArg(Consumer, OPT_fopenmp_cuda_number_of_sm_EQ,
3551 Twine(Opts.OpenMPCUDANumSMs));
3553 if (Opts.OpenMPCUDABlocksPerSM != 0)
3554 GenerateArg(Consumer, OPT_fopenmp_cuda_blocks_per_sm_EQ,
3555 Twine(Opts.OpenMPCUDABlocksPerSM));
3557 if (Opts.OpenMPCUDAReductionBufNum != 1024)
3558 GenerateArg(Consumer, OPT_fopenmp_cuda_teams_reduction_recs_num_EQ,
3559 Twine(Opts.OpenMPCUDAReductionBufNum));
3561 if (!Opts.OMPTargetTriples.empty()) {
3562 std::string Targets;
3563 llvm::raw_string_ostream OS(Targets);
3564 llvm::interleave(
3565 Opts.OMPTargetTriples, OS,
3566 [&OS](const llvm::Triple &T) { OS << T.str(); }, ",");
3567 GenerateArg(Consumer, OPT_fopenmp_targets_EQ, OS.str());
3570 if (!Opts.OMPHostIRFile.empty())
3571 GenerateArg(Consumer, OPT_fopenmp_host_ir_file_path, Opts.OMPHostIRFile);
3573 if (Opts.OpenMPCUDAMode)
3574 GenerateArg(Consumer, OPT_fopenmp_cuda_mode);
3576 if (Opts.OpenACC) {
3577 GenerateArg(Consumer, OPT_fopenacc);
3578 if (!Opts.OpenACCMacroOverride.empty())
3579 GenerateArg(Consumer, OPT_openacc_macro_override,
3580 Opts.OpenACCMacroOverride);
3583 // The arguments used to set Optimize, OptimizeSize and NoInlineDefine are
3584 // generated from CodeGenOptions.
3586 if (Opts.DefaultFPContractMode == LangOptions::FPM_Fast)
3587 GenerateArg(Consumer, OPT_ffp_contract, "fast");
3588 else if (Opts.DefaultFPContractMode == LangOptions::FPM_On)
3589 GenerateArg(Consumer, OPT_ffp_contract, "on");
3590 else if (Opts.DefaultFPContractMode == LangOptions::FPM_Off)
3591 GenerateArg(Consumer, OPT_ffp_contract, "off");
3592 else if (Opts.DefaultFPContractMode == LangOptions::FPM_FastHonorPragmas)
3593 GenerateArg(Consumer, OPT_ffp_contract, "fast-honor-pragmas");
3595 for (StringRef Sanitizer : serializeSanitizerKinds(Opts.Sanitize))
3596 GenerateArg(Consumer, OPT_fsanitize_EQ, Sanitizer);
3598 // Conflating '-fsanitize-system-ignorelist' and '-fsanitize-ignorelist'.
3599 for (const std::string &F : Opts.NoSanitizeFiles)
3600 GenerateArg(Consumer, OPT_fsanitize_ignorelist_EQ, F);
3602 switch (Opts.getClangABICompat()) {
3603 case LangOptions::ClangABI::Ver3_8:
3604 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "3.8");
3605 break;
3606 case LangOptions::ClangABI::Ver4:
3607 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "4.0");
3608 break;
3609 case LangOptions::ClangABI::Ver6:
3610 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "6.0");
3611 break;
3612 case LangOptions::ClangABI::Ver7:
3613 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "7.0");
3614 break;
3615 case LangOptions::ClangABI::Ver9:
3616 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "9.0");
3617 break;
3618 case LangOptions::ClangABI::Ver11:
3619 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "11.0");
3620 break;
3621 case LangOptions::ClangABI::Ver12:
3622 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "12.0");
3623 break;
3624 case LangOptions::ClangABI::Ver14:
3625 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "14.0");
3626 break;
3627 case LangOptions::ClangABI::Ver15:
3628 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "15.0");
3629 break;
3630 case LangOptions::ClangABI::Ver17:
3631 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, "17.0");
3632 break;
3633 case LangOptions::ClangABI::Latest:
3634 break;
3637 if (Opts.getSignReturnAddressScope() ==
3638 LangOptions::SignReturnAddressScopeKind::All)
3639 GenerateArg(Consumer, OPT_msign_return_address_EQ, "all");
3640 else if (Opts.getSignReturnAddressScope() ==
3641 LangOptions::SignReturnAddressScopeKind::NonLeaf)
3642 GenerateArg(Consumer, OPT_msign_return_address_EQ, "non-leaf");
3644 if (Opts.getSignReturnAddressKey() ==
3645 LangOptions::SignReturnAddressKeyKind::BKey)
3646 GenerateArg(Consumer, OPT_msign_return_address_key_EQ, "b_key");
3648 if (Opts.CXXABI)
3649 GenerateArg(Consumer, OPT_fcxx_abi_EQ,
3650 TargetCXXABI::getSpelling(*Opts.CXXABI));
3652 if (Opts.RelativeCXXABIVTables)
3653 GenerateArg(Consumer, OPT_fexperimental_relative_cxx_abi_vtables);
3654 else
3655 GenerateArg(Consumer, OPT_fno_experimental_relative_cxx_abi_vtables);
3657 if (Opts.UseTargetPathSeparator)
3658 GenerateArg(Consumer, OPT_ffile_reproducible);
3659 else
3660 GenerateArg(Consumer, OPT_fno_file_reproducible);
3662 for (const auto &MP : Opts.MacroPrefixMap)
3663 GenerateArg(Consumer, OPT_fmacro_prefix_map_EQ, MP.first + "=" + MP.second);
3665 if (!Opts.RandstructSeed.empty())
3666 GenerateArg(Consumer, OPT_frandomize_layout_seed_EQ, Opts.RandstructSeed);
3669 bool CompilerInvocation::ParseLangArgs(LangOptions &Opts, ArgList &Args,
3670 InputKind IK, const llvm::Triple &T,
3671 std::vector<std::string> &Includes,
3672 DiagnosticsEngine &Diags) {
3673 unsigned NumErrorsBefore = Diags.getNumErrors();
3675 if (IK.getFormat() == InputKind::Precompiled ||
3676 IK.getLanguage() == Language::LLVM_IR) {
3677 // ObjCAAutoRefCount and Sanitize LangOpts are used to setup the
3678 // PassManager in BackendUtil.cpp. They need to be initialized no matter
3679 // what the input type is.
3680 if (Args.hasArg(OPT_fobjc_arc))
3681 Opts.ObjCAutoRefCount = 1;
3682 // PICLevel and PIELevel are needed during code generation and this should
3683 // be set regardless of the input type.
3684 Opts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
3685 Opts.PIE = Args.hasArg(OPT_pic_is_pie);
3686 parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
3687 Diags, Opts.Sanitize);
3689 return Diags.getNumErrors() == NumErrorsBefore;
3692 // Other LangOpts are only initialized when the input is not AST or LLVM IR.
3693 // FIXME: Should we really be parsing this for an Language::Asm input?
3695 // FIXME: Cleanup per-file based stuff.
3696 LangStandard::Kind LangStd = LangStandard::lang_unspecified;
3697 if (const Arg *A = Args.getLastArg(OPT_std_EQ)) {
3698 LangStd = LangStandard::getLangKind(A->getValue());
3699 if (LangStd == LangStandard::lang_unspecified) {
3700 Diags.Report(diag::err_drv_invalid_value)
3701 << A->getAsString(Args) << A->getValue();
3702 // Report supported standards with short description.
3703 for (unsigned KindValue = 0;
3704 KindValue != LangStandard::lang_unspecified;
3705 ++KindValue) {
3706 const LangStandard &Std = LangStandard::getLangStandardForKind(
3707 static_cast<LangStandard::Kind>(KindValue));
3708 if (IsInputCompatibleWithStandard(IK, Std)) {
3709 auto Diag = Diags.Report(diag::note_drv_use_standard);
3710 Diag << Std.getName() << Std.getDescription();
3711 unsigned NumAliases = 0;
3712 #define LANGSTANDARD(id, name, lang, desc, features)
3713 #define LANGSTANDARD_ALIAS(id, alias) \
3714 if (KindValue == LangStandard::lang_##id) ++NumAliases;
3715 #define LANGSTANDARD_ALIAS_DEPR(id, alias)
3716 #include "clang/Basic/LangStandards.def"
3717 Diag << NumAliases;
3718 #define LANGSTANDARD(id, name, lang, desc, features)
3719 #define LANGSTANDARD_ALIAS(id, alias) \
3720 if (KindValue == LangStandard::lang_##id) Diag << alias;
3721 #define LANGSTANDARD_ALIAS_DEPR(id, alias)
3722 #include "clang/Basic/LangStandards.def"
3725 } else {
3726 // Valid standard, check to make sure language and standard are
3727 // compatible.
3728 const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
3729 if (!IsInputCompatibleWithStandard(IK, Std)) {
3730 Diags.Report(diag::err_drv_argument_not_allowed_with)
3731 << A->getAsString(Args) << GetInputKindName(IK);
3736 // -cl-std only applies for OpenCL language standards.
3737 // Override the -std option in this case.
3738 if (const Arg *A = Args.getLastArg(OPT_cl_std_EQ)) {
3739 LangStandard::Kind OpenCLLangStd
3740 = llvm::StringSwitch<LangStandard::Kind>(A->getValue())
3741 .Cases("cl", "CL", LangStandard::lang_opencl10)
3742 .Cases("cl1.0", "CL1.0", LangStandard::lang_opencl10)
3743 .Cases("cl1.1", "CL1.1", LangStandard::lang_opencl11)
3744 .Cases("cl1.2", "CL1.2", LangStandard::lang_opencl12)
3745 .Cases("cl2.0", "CL2.0", LangStandard::lang_opencl20)
3746 .Cases("cl3.0", "CL3.0", LangStandard::lang_opencl30)
3747 .Cases("clc++", "CLC++", LangStandard::lang_openclcpp10)
3748 .Cases("clc++1.0", "CLC++1.0", LangStandard::lang_openclcpp10)
3749 .Cases("clc++2021", "CLC++2021", LangStandard::lang_openclcpp2021)
3750 .Default(LangStandard::lang_unspecified);
3752 if (OpenCLLangStd == LangStandard::lang_unspecified) {
3753 Diags.Report(diag::err_drv_invalid_value)
3754 << A->getAsString(Args) << A->getValue();
3756 else
3757 LangStd = OpenCLLangStd;
3760 // These need to be parsed now. They are used to set OpenCL defaults.
3761 Opts.IncludeDefaultHeader = Args.hasArg(OPT_finclude_default_header);
3762 Opts.DeclareOpenCLBuiltins = Args.hasArg(OPT_fdeclare_opencl_builtins);
3764 LangOptions::setLangDefaults(Opts, IK.getLanguage(), T, Includes, LangStd);
3766 // The key paths of codegen options defined in Options.td start with
3767 // "LangOpts->". Let's provide the expected variable name and type.
3768 LangOptions *LangOpts = &Opts;
3770 #define LANG_OPTION_WITH_MARSHALLING(...) \
3771 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
3772 #include "clang/Driver/Options.inc"
3773 #undef LANG_OPTION_WITH_MARSHALLING
3775 if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
3776 StringRef Name = A->getValue();
3777 if (Name == "full" || Name == "branch") {
3778 Opts.CFProtectionBranch = 1;
3782 if ((Args.hasArg(OPT_fsycl_is_device) || Args.hasArg(OPT_fsycl_is_host)) &&
3783 !Args.hasArg(OPT_sycl_std_EQ)) {
3784 // If the user supplied -fsycl-is-device or -fsycl-is-host, but failed to
3785 // provide -sycl-std=, we want to default it to whatever the default SYCL
3786 // version is. I could not find a way to express this with the options
3787 // tablegen because we still want this value to be SYCL_None when the user
3788 // is not in device or host mode.
3789 Opts.setSYCLVersion(LangOptions::SYCL_Default);
3792 if (Opts.ObjC) {
3793 if (Arg *arg = Args.getLastArg(OPT_fobjc_runtime_EQ)) {
3794 StringRef value = arg->getValue();
3795 if (Opts.ObjCRuntime.tryParse(value))
3796 Diags.Report(diag::err_drv_unknown_objc_runtime) << value;
3799 if (Args.hasArg(OPT_fobjc_gc_only))
3800 Opts.setGC(LangOptions::GCOnly);
3801 else if (Args.hasArg(OPT_fobjc_gc))
3802 Opts.setGC(LangOptions::HybridGC);
3803 else if (Args.hasArg(OPT_fobjc_arc)) {
3804 Opts.ObjCAutoRefCount = 1;
3805 if (!Opts.ObjCRuntime.allowsARC())
3806 Diags.Report(diag::err_arc_unsupported_on_runtime);
3809 // ObjCWeakRuntime tracks whether the runtime supports __weak, not
3810 // whether the feature is actually enabled. This is predominantly
3811 // determined by -fobjc-runtime, but we allow it to be overridden
3812 // from the command line for testing purposes.
3813 if (Args.hasArg(OPT_fobjc_runtime_has_weak))
3814 Opts.ObjCWeakRuntime = 1;
3815 else
3816 Opts.ObjCWeakRuntime = Opts.ObjCRuntime.allowsWeak();
3818 // ObjCWeak determines whether __weak is actually enabled.
3819 // Note that we allow -fno-objc-weak to disable this even in ARC mode.
3820 if (auto weakArg = Args.getLastArg(OPT_fobjc_weak, OPT_fno_objc_weak)) {
3821 if (!weakArg->getOption().matches(OPT_fobjc_weak)) {
3822 assert(!Opts.ObjCWeak);
3823 } else if (Opts.getGC() != LangOptions::NonGC) {
3824 Diags.Report(diag::err_objc_weak_with_gc);
3825 } else if (!Opts.ObjCWeakRuntime) {
3826 Diags.Report(diag::err_objc_weak_unsupported);
3827 } else {
3828 Opts.ObjCWeak = 1;
3830 } else if (Opts.ObjCAutoRefCount) {
3831 Opts.ObjCWeak = Opts.ObjCWeakRuntime;
3834 if (Args.hasArg(OPT_fobjc_subscripting_legacy_runtime))
3835 Opts.ObjCSubscriptingLegacyRuntime =
3836 (Opts.ObjCRuntime.getKind() == ObjCRuntime::FragileMacOSX);
3839 if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) {
3840 // Check that the version has 1 to 3 components and the minor and patch
3841 // versions fit in two decimal digits.
3842 VersionTuple GNUCVer;
3843 bool Invalid = GNUCVer.tryParse(A->getValue());
3844 unsigned Major = GNUCVer.getMajor();
3845 unsigned Minor = GNUCVer.getMinor().value_or(0);
3846 unsigned Patch = GNUCVer.getSubminor().value_or(0);
3847 if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
3848 Diags.Report(diag::err_drv_invalid_value)
3849 << A->getAsString(Args) << A->getValue();
3851 Opts.GNUCVersion = Major * 100 * 100 + Minor * 100 + Patch;
3854 if (T.isOSAIX() && (Args.hasArg(OPT_mignore_xcoff_visibility)))
3855 Opts.IgnoreXCOFFVisibility = 1;
3857 if (Args.hasArg(OPT_ftrapv)) {
3858 Opts.setSignedOverflowBehavior(LangOptions::SOB_Trapping);
3859 // Set the handler, if one is specified.
3860 Opts.OverflowHandler =
3861 std::string(Args.getLastArgValue(OPT_ftrapv_handler));
3863 else if (Args.hasArg(OPT_fwrapv))
3864 Opts.setSignedOverflowBehavior(LangOptions::SOB_Defined);
3866 Opts.MSCompatibilityVersion = 0;
3867 if (const Arg *A = Args.getLastArg(OPT_fms_compatibility_version)) {
3868 VersionTuple VT;
3869 if (VT.tryParse(A->getValue()))
3870 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
3871 << A->getValue();
3872 Opts.MSCompatibilityVersion = VT.getMajor() * 10000000 +
3873 VT.getMinor().value_or(0) * 100000 +
3874 VT.getSubminor().value_or(0);
3877 // Mimicking gcc's behavior, trigraphs are only enabled if -trigraphs
3878 // is specified, or -std is set to a conforming mode.
3879 // Trigraphs are disabled by default in c++1z onwards.
3880 // For z/OS, trigraphs are enabled by default (without regard to the above).
3881 Opts.Trigraphs =
3882 (!Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus17) || T.isOSzOS();
3883 Opts.Trigraphs =
3884 Args.hasFlag(OPT_ftrigraphs, OPT_fno_trigraphs, Opts.Trigraphs);
3886 Opts.Blocks = Args.hasArg(OPT_fblocks) || (Opts.OpenCL
3887 && Opts.OpenCLVersion == 200);
3889 Opts.ConvergentFunctions = Args.hasArg(OPT_fconvergent_functions) ||
3890 Opts.OpenCL || (Opts.CUDA && Opts.CUDAIsDevice) ||
3891 Opts.SYCLIsDevice;
3893 Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding;
3894 if (!Opts.NoBuiltin)
3895 getAllNoBuiltinFuncValues(Args, Opts.NoBuiltinFuncs);
3896 if (Arg *A = Args.getLastArg(options::OPT_LongDouble_Group)) {
3897 if (A->getOption().matches(options::OPT_mlong_double_64))
3898 Opts.LongDoubleSize = 64;
3899 else if (A->getOption().matches(options::OPT_mlong_double_80))
3900 Opts.LongDoubleSize = 80;
3901 else if (A->getOption().matches(options::OPT_mlong_double_128))
3902 Opts.LongDoubleSize = 128;
3903 else
3904 Opts.LongDoubleSize = 0;
3906 if (Opts.FastRelaxedMath || Opts.CLUnsafeMath)
3907 Opts.setDefaultFPContractMode(LangOptions::FPM_Fast);
3909 llvm::sort(Opts.ModuleFeatures);
3911 // -mrtd option
3912 if (Arg *A = Args.getLastArg(OPT_mrtd)) {
3913 if (Opts.getDefaultCallingConv() != LangOptions::DCC_None)
3914 Diags.Report(diag::err_drv_argument_not_allowed_with)
3915 << A->getSpelling() << "-fdefault-calling-conv";
3916 else {
3917 switch (T.getArch()) {
3918 case llvm::Triple::x86:
3919 Opts.setDefaultCallingConv(LangOptions::DCC_StdCall);
3920 break;
3921 case llvm::Triple::m68k:
3922 Opts.setDefaultCallingConv(LangOptions::DCC_RtdCall);
3923 break;
3924 default:
3925 Diags.Report(diag::err_drv_argument_not_allowed_with)
3926 << A->getSpelling() << T.getTriple();
3931 // Check if -fopenmp is specified and set default version to 5.0.
3932 Opts.OpenMP = Args.hasArg(OPT_fopenmp) ? 51 : 0;
3933 // Check if -fopenmp-simd is specified.
3934 bool IsSimdSpecified =
3935 Args.hasFlag(options::OPT_fopenmp_simd, options::OPT_fno_openmp_simd,
3936 /*Default=*/false);
3937 Opts.OpenMPSimd = !Opts.OpenMP && IsSimdSpecified;
3938 Opts.OpenMPUseTLS =
3939 Opts.OpenMP && !Args.hasArg(options::OPT_fnoopenmp_use_tls);
3940 Opts.OpenMPIsTargetDevice =
3941 Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_is_target_device);
3942 Opts.OpenMPIRBuilder =
3943 Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_enable_irbuilder);
3944 bool IsTargetSpecified =
3945 Opts.OpenMPIsTargetDevice || Args.hasArg(options::OPT_fopenmp_targets_EQ);
3947 Opts.ConvergentFunctions =
3948 Opts.ConvergentFunctions || Opts.OpenMPIsTargetDevice;
3950 if (Opts.OpenMP || Opts.OpenMPSimd) {
3951 if (int Version = getLastArgIntValue(
3952 Args, OPT_fopenmp_version_EQ,
3953 (IsSimdSpecified || IsTargetSpecified) ? 51 : Opts.OpenMP, Diags))
3954 Opts.OpenMP = Version;
3955 // Provide diagnostic when a given target is not expected to be an OpenMP
3956 // device or host.
3957 if (!Opts.OpenMPIsTargetDevice) {
3958 switch (T.getArch()) {
3959 default:
3960 break;
3961 // Add unsupported host targets here:
3962 case llvm::Triple::nvptx:
3963 case llvm::Triple::nvptx64:
3964 Diags.Report(diag::err_drv_omp_host_target_not_supported) << T.str();
3965 break;
3970 // Set the flag to prevent the implementation from emitting device exception
3971 // handling code for those requiring so.
3972 if ((Opts.OpenMPIsTargetDevice && (T.isNVPTX() || T.isAMDGCN())) ||
3973 Opts.OpenCLCPlusPlus) {
3975 Opts.Exceptions = 0;
3976 Opts.CXXExceptions = 0;
3978 if (Opts.OpenMPIsTargetDevice && T.isNVPTX()) {
3979 Opts.OpenMPCUDANumSMs =
3980 getLastArgIntValue(Args, options::OPT_fopenmp_cuda_number_of_sm_EQ,
3981 Opts.OpenMPCUDANumSMs, Diags);
3982 Opts.OpenMPCUDABlocksPerSM =
3983 getLastArgIntValue(Args, options::OPT_fopenmp_cuda_blocks_per_sm_EQ,
3984 Opts.OpenMPCUDABlocksPerSM, Diags);
3985 Opts.OpenMPCUDAReductionBufNum = getLastArgIntValue(
3986 Args, options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ,
3987 Opts.OpenMPCUDAReductionBufNum, Diags);
3990 // Set the value of the debugging flag used in the new offloading device RTL.
3991 // Set either by a specific value or to a default if not specified.
3992 if (Opts.OpenMPIsTargetDevice && (Args.hasArg(OPT_fopenmp_target_debug) ||
3993 Args.hasArg(OPT_fopenmp_target_debug_EQ))) {
3994 Opts.OpenMPTargetDebug = getLastArgIntValue(
3995 Args, OPT_fopenmp_target_debug_EQ, Opts.OpenMPTargetDebug, Diags);
3996 if (!Opts.OpenMPTargetDebug && Args.hasArg(OPT_fopenmp_target_debug))
3997 Opts.OpenMPTargetDebug = 1;
4000 if (Opts.OpenMPIsTargetDevice) {
4001 if (Args.hasArg(OPT_fopenmp_assume_teams_oversubscription))
4002 Opts.OpenMPTeamSubscription = true;
4003 if (Args.hasArg(OPT_fopenmp_assume_threads_oversubscription))
4004 Opts.OpenMPThreadSubscription = true;
4007 // Get the OpenMP target triples if any.
4008 if (Arg *A = Args.getLastArg(options::OPT_fopenmp_targets_EQ)) {
4009 enum ArchPtrSize { Arch16Bit, Arch32Bit, Arch64Bit };
4010 auto getArchPtrSize = [](const llvm::Triple &T) {
4011 if (T.isArch16Bit())
4012 return Arch16Bit;
4013 if (T.isArch32Bit())
4014 return Arch32Bit;
4015 assert(T.isArch64Bit() && "Expected 64-bit architecture");
4016 return Arch64Bit;
4019 for (unsigned i = 0; i < A->getNumValues(); ++i) {
4020 llvm::Triple TT(A->getValue(i));
4022 if (TT.getArch() == llvm::Triple::UnknownArch ||
4023 !(TT.getArch() == llvm::Triple::aarch64 || TT.isPPC() ||
4024 TT.getArch() == llvm::Triple::nvptx ||
4025 TT.getArch() == llvm::Triple::nvptx64 ||
4026 TT.getArch() == llvm::Triple::amdgcn ||
4027 TT.getArch() == llvm::Triple::x86 ||
4028 TT.getArch() == llvm::Triple::x86_64))
4029 Diags.Report(diag::err_drv_invalid_omp_target) << A->getValue(i);
4030 else if (getArchPtrSize(T) != getArchPtrSize(TT))
4031 Diags.Report(diag::err_drv_incompatible_omp_arch)
4032 << A->getValue(i) << T.str();
4033 else
4034 Opts.OMPTargetTriples.push_back(TT);
4038 // Get OpenMP host file path if any and report if a non existent file is
4039 // found
4040 if (Arg *A = Args.getLastArg(options::OPT_fopenmp_host_ir_file_path)) {
4041 Opts.OMPHostIRFile = A->getValue();
4042 if (!llvm::sys::fs::exists(Opts.OMPHostIRFile))
4043 Diags.Report(diag::err_drv_omp_host_ir_file_not_found)
4044 << Opts.OMPHostIRFile;
4047 // Set CUDA mode for OpenMP target NVPTX/AMDGCN if specified in options
4048 Opts.OpenMPCUDAMode = Opts.OpenMPIsTargetDevice &&
4049 (T.isNVPTX() || T.isAMDGCN()) &&
4050 Args.hasArg(options::OPT_fopenmp_cuda_mode);
4052 // OpenACC Configuration.
4053 if (Args.hasArg(options::OPT_fopenacc)) {
4054 Opts.OpenACC = true;
4056 if (Arg *A = Args.getLastArg(options::OPT_openacc_macro_override))
4057 Opts.OpenACCMacroOverride = A->getValue();
4060 // FIXME: Eliminate this dependency.
4061 unsigned Opt = getOptimizationLevel(Args, IK, Diags),
4062 OptSize = getOptimizationLevelSize(Args);
4063 Opts.Optimize = Opt != 0;
4064 Opts.OptimizeSize = OptSize != 0;
4066 // This is the __NO_INLINE__ define, which just depends on things like the
4067 // optimization level and -fno-inline, not actually whether the backend has
4068 // inlining enabled.
4069 Opts.NoInlineDefine = !Opts.Optimize;
4070 if (Arg *InlineArg = Args.getLastArg(
4071 options::OPT_finline_functions, options::OPT_finline_hint_functions,
4072 options::OPT_fno_inline_functions, options::OPT_fno_inline))
4073 if (InlineArg->getOption().matches(options::OPT_fno_inline))
4074 Opts.NoInlineDefine = true;
4076 if (Arg *A = Args.getLastArg(OPT_ffp_contract)) {
4077 StringRef Val = A->getValue();
4078 if (Val == "fast")
4079 Opts.setDefaultFPContractMode(LangOptions::FPM_Fast);
4080 else if (Val == "on")
4081 Opts.setDefaultFPContractMode(LangOptions::FPM_On);
4082 else if (Val == "off")
4083 Opts.setDefaultFPContractMode(LangOptions::FPM_Off);
4084 else if (Val == "fast-honor-pragmas")
4085 Opts.setDefaultFPContractMode(LangOptions::FPM_FastHonorPragmas);
4086 else
4087 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
4090 // Parse -fsanitize= arguments.
4091 parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
4092 Diags, Opts.Sanitize);
4093 Opts.NoSanitizeFiles = Args.getAllArgValues(OPT_fsanitize_ignorelist_EQ);
4094 std::vector<std::string> systemIgnorelists =
4095 Args.getAllArgValues(OPT_fsanitize_system_ignorelist_EQ);
4096 Opts.NoSanitizeFiles.insert(Opts.NoSanitizeFiles.end(),
4097 systemIgnorelists.begin(),
4098 systemIgnorelists.end());
4100 if (Arg *A = Args.getLastArg(OPT_fclang_abi_compat_EQ)) {
4101 Opts.setClangABICompat(LangOptions::ClangABI::Latest);
4103 StringRef Ver = A->getValue();
4104 std::pair<StringRef, StringRef> VerParts = Ver.split('.');
4105 unsigned Major, Minor = 0;
4107 // Check the version number is valid: either 3.x (0 <= x <= 9) or
4108 // y or y.0 (4 <= y <= current version).
4109 if (!VerParts.first.starts_with("0") &&
4110 !VerParts.first.getAsInteger(10, Major) && 3 <= Major &&
4111 Major <= CLANG_VERSION_MAJOR &&
4112 (Major == 3
4113 ? VerParts.second.size() == 1 &&
4114 !VerParts.second.getAsInteger(10, Minor)
4115 : VerParts.first.size() == Ver.size() || VerParts.second == "0")) {
4116 // Got a valid version number.
4117 if (Major == 3 && Minor <= 8)
4118 Opts.setClangABICompat(LangOptions::ClangABI::Ver3_8);
4119 else if (Major <= 4)
4120 Opts.setClangABICompat(LangOptions::ClangABI::Ver4);
4121 else if (Major <= 6)
4122 Opts.setClangABICompat(LangOptions::ClangABI::Ver6);
4123 else if (Major <= 7)
4124 Opts.setClangABICompat(LangOptions::ClangABI::Ver7);
4125 else if (Major <= 9)
4126 Opts.setClangABICompat(LangOptions::ClangABI::Ver9);
4127 else if (Major <= 11)
4128 Opts.setClangABICompat(LangOptions::ClangABI::Ver11);
4129 else if (Major <= 12)
4130 Opts.setClangABICompat(LangOptions::ClangABI::Ver12);
4131 else if (Major <= 14)
4132 Opts.setClangABICompat(LangOptions::ClangABI::Ver14);
4133 else if (Major <= 15)
4134 Opts.setClangABICompat(LangOptions::ClangABI::Ver15);
4135 else if (Major <= 17)
4136 Opts.setClangABICompat(LangOptions::ClangABI::Ver17);
4137 } else if (Ver != "latest") {
4138 Diags.Report(diag::err_drv_invalid_value)
4139 << A->getAsString(Args) << A->getValue();
4143 if (Arg *A = Args.getLastArg(OPT_msign_return_address_EQ)) {
4144 StringRef SignScope = A->getValue();
4146 if (SignScope.equals_insensitive("none"))
4147 Opts.setSignReturnAddressScope(
4148 LangOptions::SignReturnAddressScopeKind::None);
4149 else if (SignScope.equals_insensitive("all"))
4150 Opts.setSignReturnAddressScope(
4151 LangOptions::SignReturnAddressScopeKind::All);
4152 else if (SignScope.equals_insensitive("non-leaf"))
4153 Opts.setSignReturnAddressScope(
4154 LangOptions::SignReturnAddressScopeKind::NonLeaf);
4155 else
4156 Diags.Report(diag::err_drv_invalid_value)
4157 << A->getAsString(Args) << SignScope;
4159 if (Arg *A = Args.getLastArg(OPT_msign_return_address_key_EQ)) {
4160 StringRef SignKey = A->getValue();
4161 if (!SignScope.empty() && !SignKey.empty()) {
4162 if (SignKey == "a_key")
4163 Opts.setSignReturnAddressKey(
4164 LangOptions::SignReturnAddressKeyKind::AKey);
4165 else if (SignKey == "b_key")
4166 Opts.setSignReturnAddressKey(
4167 LangOptions::SignReturnAddressKeyKind::BKey);
4168 else
4169 Diags.Report(diag::err_drv_invalid_value)
4170 << A->getAsString(Args) << SignKey;
4175 // The value can be empty, which indicates the system default should be used.
4176 StringRef CXXABI = Args.getLastArgValue(OPT_fcxx_abi_EQ);
4177 if (!CXXABI.empty()) {
4178 if (!TargetCXXABI::isABI(CXXABI)) {
4179 Diags.Report(diag::err_invalid_cxx_abi) << CXXABI;
4180 } else {
4181 auto Kind = TargetCXXABI::getKind(CXXABI);
4182 if (!TargetCXXABI::isSupportedCXXABI(T, Kind))
4183 Diags.Report(diag::err_unsupported_cxx_abi) << CXXABI << T.str();
4184 else
4185 Opts.CXXABI = Kind;
4189 Opts.RelativeCXXABIVTables =
4190 Args.hasFlag(options::OPT_fexperimental_relative_cxx_abi_vtables,
4191 options::OPT_fno_experimental_relative_cxx_abi_vtables,
4192 TargetCXXABI::usesRelativeVTables(T));
4194 // RTTI is on by default.
4195 bool HasRTTI = !Args.hasArg(options::OPT_fno_rtti);
4196 Opts.OmitVTableRTTI =
4197 Args.hasFlag(options::OPT_fexperimental_omit_vtable_rtti,
4198 options::OPT_fno_experimental_omit_vtable_rtti, false);
4199 if (Opts.OmitVTableRTTI && HasRTTI)
4200 Diags.Report(diag::err_drv_using_omit_rtti_component_without_no_rtti);
4202 for (const auto &A : Args.getAllArgValues(OPT_fmacro_prefix_map_EQ)) {
4203 auto Split = StringRef(A).split('=');
4204 Opts.MacroPrefixMap.insert(
4205 {std::string(Split.first), std::string(Split.second)});
4208 Opts.UseTargetPathSeparator =
4209 !Args.getLastArg(OPT_fno_file_reproducible) &&
4210 (Args.getLastArg(OPT_ffile_compilation_dir_EQ) ||
4211 Args.getLastArg(OPT_fmacro_prefix_map_EQ) ||
4212 Args.getLastArg(OPT_ffile_reproducible));
4214 // Error if -mvscale-min is unbounded.
4215 if (Arg *A = Args.getLastArg(options::OPT_mvscale_min_EQ)) {
4216 unsigned VScaleMin;
4217 if (StringRef(A->getValue()).getAsInteger(10, VScaleMin) || VScaleMin == 0)
4218 Diags.Report(diag::err_cc1_unbounded_vscale_min);
4221 if (const Arg *A = Args.getLastArg(OPT_frandomize_layout_seed_file_EQ)) {
4222 std::ifstream SeedFile(A->getValue(0));
4224 if (!SeedFile.is_open())
4225 Diags.Report(diag::err_drv_cannot_open_randomize_layout_seed_file)
4226 << A->getValue(0);
4228 std::getline(SeedFile, Opts.RandstructSeed);
4231 if (const Arg *A = Args.getLastArg(OPT_frandomize_layout_seed_EQ))
4232 Opts.RandstructSeed = A->getValue(0);
4234 // Validate options for HLSL
4235 if (Opts.HLSL) {
4236 // TODO: Revisit restricting SPIR-V to logical once we've figured out how to
4237 // handle PhysicalStorageBuffer64 memory model
4238 if (T.isDXIL() || T.isSPIRVLogical()) {
4239 enum { ShaderModel, VulkanEnv, ShaderStage };
4240 enum { OS, Environment };
4242 int ExpectedOS = T.isSPIRVLogical() ? VulkanEnv : ShaderModel;
4244 if (T.getOSName().empty()) {
4245 Diags.Report(diag::err_drv_hlsl_bad_shader_required_in_target)
4246 << ExpectedOS << OS << T.str();
4247 } else if (T.getEnvironmentName().empty()) {
4248 Diags.Report(diag::err_drv_hlsl_bad_shader_required_in_target)
4249 << ShaderStage << Environment << T.str();
4250 } else if (!T.isShaderStageEnvironment()) {
4251 Diags.Report(diag::err_drv_hlsl_bad_shader_unsupported)
4252 << ShaderStage << T.getEnvironmentName() << T.str();
4255 if (T.isDXIL()) {
4256 if (!T.isShaderModelOS() || T.getOSVersion() == VersionTuple(0)) {
4257 Diags.Report(diag::err_drv_hlsl_bad_shader_unsupported)
4258 << ShaderModel << T.getOSName() << T.str();
4260 } else if (T.isSPIRVLogical()) {
4261 if (!T.isVulkanOS() || T.getVulkanVersion() == VersionTuple(0)) {
4262 Diags.Report(diag::err_drv_hlsl_bad_shader_unsupported)
4263 << VulkanEnv << T.getOSName() << T.str();
4265 } else {
4266 llvm_unreachable("expected DXIL or SPIR-V target");
4268 } else
4269 Diags.Report(diag::err_drv_hlsl_unsupported_target) << T.str();
4272 return Diags.getNumErrors() == NumErrorsBefore;
4275 static bool isStrictlyPreprocessorAction(frontend::ActionKind Action) {
4276 switch (Action) {
4277 case frontend::ASTDeclList:
4278 case frontend::ASTDump:
4279 case frontend::ASTPrint:
4280 case frontend::ASTView:
4281 case frontend::EmitAssembly:
4282 case frontend::EmitBC:
4283 case frontend::EmitHTML:
4284 case frontend::EmitLLVM:
4285 case frontend::EmitLLVMOnly:
4286 case frontend::EmitCodeGenOnly:
4287 case frontend::EmitObj:
4288 case frontend::ExtractAPI:
4289 case frontend::FixIt:
4290 case frontend::GenerateModule:
4291 case frontend::GenerateModuleInterface:
4292 case frontend::GenerateHeaderUnit:
4293 case frontend::GeneratePCH:
4294 case frontend::GenerateInterfaceStubs:
4295 case frontend::ParseSyntaxOnly:
4296 case frontend::ModuleFileInfo:
4297 case frontend::VerifyPCH:
4298 case frontend::PluginAction:
4299 case frontend::RewriteObjC:
4300 case frontend::RewriteTest:
4301 case frontend::RunAnalysis:
4302 case frontend::TemplightDump:
4303 case frontend::MigrateSource:
4304 return false;
4306 case frontend::DumpCompilerOptions:
4307 case frontend::DumpRawTokens:
4308 case frontend::DumpTokens:
4309 case frontend::InitOnly:
4310 case frontend::PrintPreamble:
4311 case frontend::PrintPreprocessedInput:
4312 case frontend::RewriteMacros:
4313 case frontend::RunPreprocessorOnly:
4314 case frontend::PrintDependencyDirectivesSourceMinimizerOutput:
4315 return true;
4317 llvm_unreachable("invalid frontend action");
4320 static void GeneratePreprocessorArgs(const PreprocessorOptions &Opts,
4321 ArgumentConsumer Consumer,
4322 const LangOptions &LangOpts,
4323 const FrontendOptions &FrontendOpts,
4324 const CodeGenOptions &CodeGenOpts) {
4325 const PreprocessorOptions *PreprocessorOpts = &Opts;
4327 #define PREPROCESSOR_OPTION_WITH_MARSHALLING(...) \
4328 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
4329 #include "clang/Driver/Options.inc"
4330 #undef PREPROCESSOR_OPTION_WITH_MARSHALLING
4332 if (Opts.PCHWithHdrStop && !Opts.PCHWithHdrStopCreate)
4333 GenerateArg(Consumer, OPT_pch_through_hdrstop_use);
4335 for (const auto &D : Opts.DeserializedPCHDeclsToErrorOn)
4336 GenerateArg(Consumer, OPT_error_on_deserialized_pch_decl, D);
4338 if (Opts.PrecompiledPreambleBytes != std::make_pair(0u, false))
4339 GenerateArg(Consumer, OPT_preamble_bytes_EQ,
4340 Twine(Opts.PrecompiledPreambleBytes.first) + "," +
4341 (Opts.PrecompiledPreambleBytes.second ? "1" : "0"));
4343 for (const auto &M : Opts.Macros) {
4344 // Don't generate __CET__ macro definitions. They are implied by the
4345 // -fcf-protection option that is generated elsewhere.
4346 if (M.first == "__CET__=1" && !M.second &&
4347 !CodeGenOpts.CFProtectionReturn && CodeGenOpts.CFProtectionBranch)
4348 continue;
4349 if (M.first == "__CET__=2" && !M.second && CodeGenOpts.CFProtectionReturn &&
4350 !CodeGenOpts.CFProtectionBranch)
4351 continue;
4352 if (M.first == "__CET__=3" && !M.second && CodeGenOpts.CFProtectionReturn &&
4353 CodeGenOpts.CFProtectionBranch)
4354 continue;
4356 GenerateArg(Consumer, M.second ? OPT_U : OPT_D, M.first);
4359 for (const auto &I : Opts.Includes) {
4360 // Don't generate OpenCL includes. They are implied by other flags that are
4361 // generated elsewhere.
4362 if (LangOpts.OpenCL && LangOpts.IncludeDefaultHeader &&
4363 ((LangOpts.DeclareOpenCLBuiltins && I == "opencl-c-base.h") ||
4364 I == "opencl-c.h"))
4365 continue;
4366 // Don't generate HLSL includes. They are implied by other flags that are
4367 // generated elsewhere.
4368 if (LangOpts.HLSL && I == "hlsl.h")
4369 continue;
4371 GenerateArg(Consumer, OPT_include, I);
4374 for (const auto &CI : Opts.ChainedIncludes)
4375 GenerateArg(Consumer, OPT_chain_include, CI);
4377 for (const auto &RF : Opts.RemappedFiles)
4378 GenerateArg(Consumer, OPT_remap_file, RF.first + ";" + RF.second);
4380 if (Opts.SourceDateEpoch)
4381 GenerateArg(Consumer, OPT_source_date_epoch, Twine(*Opts.SourceDateEpoch));
4383 if (Opts.DefineTargetOSMacros)
4384 GenerateArg(Consumer, OPT_fdefine_target_os_macros);
4386 // Don't handle LexEditorPlaceholders. It is implied by the action that is
4387 // generated elsewhere.
4390 static bool ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args,
4391 DiagnosticsEngine &Diags,
4392 frontend::ActionKind Action,
4393 const FrontendOptions &FrontendOpts) {
4394 unsigned NumErrorsBefore = Diags.getNumErrors();
4396 PreprocessorOptions *PreprocessorOpts = &Opts;
4398 #define PREPROCESSOR_OPTION_WITH_MARSHALLING(...) \
4399 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
4400 #include "clang/Driver/Options.inc"
4401 #undef PREPROCESSOR_OPTION_WITH_MARSHALLING
4403 Opts.PCHWithHdrStop = Args.hasArg(OPT_pch_through_hdrstop_create) ||
4404 Args.hasArg(OPT_pch_through_hdrstop_use);
4406 for (const auto *A : Args.filtered(OPT_error_on_deserialized_pch_decl))
4407 Opts.DeserializedPCHDeclsToErrorOn.insert(A->getValue());
4409 if (const Arg *A = Args.getLastArg(OPT_preamble_bytes_EQ)) {
4410 StringRef Value(A->getValue());
4411 size_t Comma = Value.find(',');
4412 unsigned Bytes = 0;
4413 unsigned EndOfLine = 0;
4415 if (Comma == StringRef::npos ||
4416 Value.substr(0, Comma).getAsInteger(10, Bytes) ||
4417 Value.substr(Comma + 1).getAsInteger(10, EndOfLine))
4418 Diags.Report(diag::err_drv_preamble_format);
4419 else {
4420 Opts.PrecompiledPreambleBytes.first = Bytes;
4421 Opts.PrecompiledPreambleBytes.second = (EndOfLine != 0);
4425 // Add the __CET__ macro if a CFProtection option is set.
4426 if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
4427 StringRef Name = A->getValue();
4428 if (Name == "branch")
4429 Opts.addMacroDef("__CET__=1");
4430 else if (Name == "return")
4431 Opts.addMacroDef("__CET__=2");
4432 else if (Name == "full")
4433 Opts.addMacroDef("__CET__=3");
4436 // Add macros from the command line.
4437 for (const auto *A : Args.filtered(OPT_D, OPT_U)) {
4438 if (A->getOption().matches(OPT_D))
4439 Opts.addMacroDef(A->getValue());
4440 else
4441 Opts.addMacroUndef(A->getValue());
4444 // Add the ordered list of -includes.
4445 for (const auto *A : Args.filtered(OPT_include))
4446 Opts.Includes.emplace_back(A->getValue());
4448 for (const auto *A : Args.filtered(OPT_chain_include))
4449 Opts.ChainedIncludes.emplace_back(A->getValue());
4451 for (const auto *A : Args.filtered(OPT_remap_file)) {
4452 std::pair<StringRef, StringRef> Split = StringRef(A->getValue()).split(';');
4454 if (Split.second.empty()) {
4455 Diags.Report(diag::err_drv_invalid_remap_file) << A->getAsString(Args);
4456 continue;
4459 Opts.addRemappedFile(Split.first, Split.second);
4462 if (const Arg *A = Args.getLastArg(OPT_source_date_epoch)) {
4463 StringRef Epoch = A->getValue();
4464 // SOURCE_DATE_EPOCH, if specified, must be a non-negative decimal integer.
4465 // On time64 systems, pick 253402300799 (the UNIX timestamp of
4466 // 9999-12-31T23:59:59Z) as the upper bound.
4467 const uint64_t MaxTimestamp =
4468 std::min<uint64_t>(std::numeric_limits<time_t>::max(), 253402300799);
4469 uint64_t V;
4470 if (Epoch.getAsInteger(10, V) || V > MaxTimestamp) {
4471 Diags.Report(diag::err_fe_invalid_source_date_epoch)
4472 << Epoch << MaxTimestamp;
4473 } else {
4474 Opts.SourceDateEpoch = V;
4478 // Always avoid lexing editor placeholders when we're just running the
4479 // preprocessor as we never want to emit the
4480 // "editor placeholder in source file" error in PP only mode.
4481 if (isStrictlyPreprocessorAction(Action))
4482 Opts.LexEditorPlaceholders = false;
4484 Opts.DefineTargetOSMacros =
4485 Args.hasFlag(OPT_fdefine_target_os_macros,
4486 OPT_fno_define_target_os_macros, Opts.DefineTargetOSMacros);
4488 return Diags.getNumErrors() == NumErrorsBefore;
4491 static void
4492 GeneratePreprocessorOutputArgs(const PreprocessorOutputOptions &Opts,
4493 ArgumentConsumer Consumer,
4494 frontend::ActionKind Action) {
4495 const PreprocessorOutputOptions &PreprocessorOutputOpts = Opts;
4497 #define PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING(...) \
4498 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
4499 #include "clang/Driver/Options.inc"
4500 #undef PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING
4502 bool Generate_dM = isStrictlyPreprocessorAction(Action) && !Opts.ShowCPP;
4503 if (Generate_dM)
4504 GenerateArg(Consumer, OPT_dM);
4505 if (!Generate_dM && Opts.ShowMacros)
4506 GenerateArg(Consumer, OPT_dD);
4507 if (Opts.DirectivesOnly)
4508 GenerateArg(Consumer, OPT_fdirectives_only);
4511 static bool ParsePreprocessorOutputArgs(PreprocessorOutputOptions &Opts,
4512 ArgList &Args, DiagnosticsEngine &Diags,
4513 frontend::ActionKind Action) {
4514 unsigned NumErrorsBefore = Diags.getNumErrors();
4516 PreprocessorOutputOptions &PreprocessorOutputOpts = Opts;
4518 #define PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING(...) \
4519 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
4520 #include "clang/Driver/Options.inc"
4521 #undef PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING
4523 Opts.ShowCPP = isStrictlyPreprocessorAction(Action) && !Args.hasArg(OPT_dM);
4524 Opts.ShowMacros = Args.hasArg(OPT_dM) || Args.hasArg(OPT_dD);
4525 Opts.DirectivesOnly = Args.hasArg(OPT_fdirectives_only);
4527 return Diags.getNumErrors() == NumErrorsBefore;
4530 static void GenerateTargetArgs(const TargetOptions &Opts,
4531 ArgumentConsumer Consumer) {
4532 const TargetOptions *TargetOpts = &Opts;
4533 #define TARGET_OPTION_WITH_MARSHALLING(...) \
4534 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
4535 #include "clang/Driver/Options.inc"
4536 #undef TARGET_OPTION_WITH_MARSHALLING
4538 if (!Opts.SDKVersion.empty())
4539 GenerateArg(Consumer, OPT_target_sdk_version_EQ,
4540 Opts.SDKVersion.getAsString());
4541 if (!Opts.DarwinTargetVariantSDKVersion.empty())
4542 GenerateArg(Consumer, OPT_darwin_target_variant_sdk_version_EQ,
4543 Opts.DarwinTargetVariantSDKVersion.getAsString());
4546 static bool ParseTargetArgs(TargetOptions &Opts, ArgList &Args,
4547 DiagnosticsEngine &Diags) {
4548 unsigned NumErrorsBefore = Diags.getNumErrors();
4550 TargetOptions *TargetOpts = &Opts;
4552 #define TARGET_OPTION_WITH_MARSHALLING(...) \
4553 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
4554 #include "clang/Driver/Options.inc"
4555 #undef TARGET_OPTION_WITH_MARSHALLING
4557 if (Arg *A = Args.getLastArg(options::OPT_target_sdk_version_EQ)) {
4558 llvm::VersionTuple Version;
4559 if (Version.tryParse(A->getValue()))
4560 Diags.Report(diag::err_drv_invalid_value)
4561 << A->getAsString(Args) << A->getValue();
4562 else
4563 Opts.SDKVersion = Version;
4565 if (Arg *A =
4566 Args.getLastArg(options::OPT_darwin_target_variant_sdk_version_EQ)) {
4567 llvm::VersionTuple Version;
4568 if (Version.tryParse(A->getValue()))
4569 Diags.Report(diag::err_drv_invalid_value)
4570 << A->getAsString(Args) << A->getValue();
4571 else
4572 Opts.DarwinTargetVariantSDKVersion = Version;
4575 return Diags.getNumErrors() == NumErrorsBefore;
4578 bool CompilerInvocation::CreateFromArgsImpl(
4579 CompilerInvocation &Res, ArrayRef<const char *> CommandLineArgs,
4580 DiagnosticsEngine &Diags, const char *Argv0) {
4581 unsigned NumErrorsBefore = Diags.getNumErrors();
4583 // Parse the arguments.
4584 const OptTable &Opts = getDriverOptTable();
4585 llvm::opt::Visibility VisibilityMask(options::CC1Option);
4586 unsigned MissingArgIndex, MissingArgCount;
4587 InputArgList Args = Opts.ParseArgs(CommandLineArgs, MissingArgIndex,
4588 MissingArgCount, VisibilityMask);
4589 LangOptions &LangOpts = Res.getLangOpts();
4591 // Check for missing argument error.
4592 if (MissingArgCount)
4593 Diags.Report(diag::err_drv_missing_argument)
4594 << Args.getArgString(MissingArgIndex) << MissingArgCount;
4596 // Issue errors on unknown arguments.
4597 for (const auto *A : Args.filtered(OPT_UNKNOWN)) {
4598 auto ArgString = A->getAsString(Args);
4599 std::string Nearest;
4600 if (Opts.findNearest(ArgString, Nearest, VisibilityMask) > 1)
4601 Diags.Report(diag::err_drv_unknown_argument) << ArgString;
4602 else
4603 Diags.Report(diag::err_drv_unknown_argument_with_suggestion)
4604 << ArgString << Nearest;
4607 ParseFileSystemArgs(Res.getFileSystemOpts(), Args, Diags);
4608 ParseMigratorArgs(Res.getMigratorOpts(), Args, Diags);
4609 ParseAnalyzerArgs(Res.getAnalyzerOpts(), Args, Diags);
4610 ParseDiagnosticArgs(Res.getDiagnosticOpts(), Args, &Diags,
4611 /*DefaultDiagColor=*/false);
4612 ParseFrontendArgs(Res.getFrontendOpts(), Args, Diags, LangOpts.IsHeaderFile);
4613 // FIXME: We shouldn't have to pass the DashX option around here
4614 InputKind DashX = Res.getFrontendOpts().DashX;
4615 ParseTargetArgs(Res.getTargetOpts(), Args, Diags);
4616 llvm::Triple T(Res.getTargetOpts().Triple);
4617 ParseHeaderSearchArgs(Res.getHeaderSearchOpts(), Args, Diags,
4618 Res.getFileSystemOpts().WorkingDir);
4619 ParseAPINotesArgs(Res.getAPINotesOpts(), Args, Diags);
4621 ParseLangArgs(LangOpts, Args, DashX, T, Res.getPreprocessorOpts().Includes,
4622 Diags);
4623 if (Res.getFrontendOpts().ProgramAction == frontend::RewriteObjC)
4624 LangOpts.ObjCExceptions = 1;
4626 for (auto Warning : Res.getDiagnosticOpts().Warnings) {
4627 if (Warning == "misexpect" &&
4628 !Diags.isIgnored(diag::warn_profile_data_misexpect, SourceLocation())) {
4629 Res.getCodeGenOpts().MisExpect = true;
4633 if (LangOpts.CUDA) {
4634 // During CUDA device-side compilation, the aux triple is the
4635 // triple used for host compilation.
4636 if (LangOpts.CUDAIsDevice)
4637 Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple;
4640 // Set the triple of the host for OpenMP device compile.
4641 if (LangOpts.OpenMPIsTargetDevice)
4642 Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple;
4644 ParseCodeGenArgs(Res.getCodeGenOpts(), Args, DashX, Diags, T,
4645 Res.getFrontendOpts().OutputFile, LangOpts);
4647 // FIXME: Override value name discarding when asan or msan is used because the
4648 // backend passes depend on the name of the alloca in order to print out
4649 // names.
4650 Res.getCodeGenOpts().DiscardValueNames &=
4651 !LangOpts.Sanitize.has(SanitizerKind::Address) &&
4652 !LangOpts.Sanitize.has(SanitizerKind::KernelAddress) &&
4653 !LangOpts.Sanitize.has(SanitizerKind::Memory) &&
4654 !LangOpts.Sanitize.has(SanitizerKind::KernelMemory);
4656 ParsePreprocessorArgs(Res.getPreprocessorOpts(), Args, Diags,
4657 Res.getFrontendOpts().ProgramAction,
4658 Res.getFrontendOpts());
4659 ParsePreprocessorOutputArgs(Res.getPreprocessorOutputOpts(), Args, Diags,
4660 Res.getFrontendOpts().ProgramAction);
4662 ParseDependencyOutputArgs(Res.getDependencyOutputOpts(), Args, Diags,
4663 Res.getFrontendOpts().ProgramAction,
4664 Res.getPreprocessorOutputOpts().ShowLineMarkers);
4665 if (!Res.getDependencyOutputOpts().OutputFile.empty() &&
4666 Res.getDependencyOutputOpts().Targets.empty())
4667 Diags.Report(diag::err_fe_dependency_file_requires_MT);
4669 // If sanitizer is enabled, disable OPT_ffine_grained_bitfield_accesses.
4670 if (Res.getCodeGenOpts().FineGrainedBitfieldAccesses &&
4671 !Res.getLangOpts().Sanitize.empty()) {
4672 Res.getCodeGenOpts().FineGrainedBitfieldAccesses = false;
4673 Diags.Report(diag::warn_drv_fine_grained_bitfield_accesses_ignored);
4676 // Store the command-line for using in the CodeView backend.
4677 if (Res.getCodeGenOpts().CodeViewCommandLine) {
4678 Res.getCodeGenOpts().Argv0 = Argv0;
4679 append_range(Res.getCodeGenOpts().CommandLineArgs, CommandLineArgs);
4682 // Set PGOOptions. Need to create a temporary VFS to read the profile
4683 // to determine the PGO type.
4684 if (!Res.getCodeGenOpts().ProfileInstrumentUsePath.empty()) {
4685 auto FS =
4686 createVFSFromOverlayFiles(Res.getHeaderSearchOpts().VFSOverlayFiles,
4687 Diags, llvm::vfs::getRealFileSystem());
4688 setPGOUseInstrumentor(Res.getCodeGenOpts(),
4689 Res.getCodeGenOpts().ProfileInstrumentUsePath, *FS,
4690 Diags);
4693 FixupInvocation(Res, Diags, Args, DashX);
4695 return Diags.getNumErrors() == NumErrorsBefore;
4698 bool CompilerInvocation::CreateFromArgs(CompilerInvocation &Invocation,
4699 ArrayRef<const char *> CommandLineArgs,
4700 DiagnosticsEngine &Diags,
4701 const char *Argv0) {
4702 CompilerInvocation DummyInvocation;
4704 return RoundTrip(
4705 [](CompilerInvocation &Invocation, ArrayRef<const char *> CommandLineArgs,
4706 DiagnosticsEngine &Diags, const char *Argv0) {
4707 return CreateFromArgsImpl(Invocation, CommandLineArgs, Diags, Argv0);
4709 [](CompilerInvocation &Invocation, SmallVectorImpl<const char *> &Args,
4710 StringAllocator SA) {
4711 Args.push_back("-cc1");
4712 Invocation.generateCC1CommandLine(Args, SA);
4714 Invocation, DummyInvocation, CommandLineArgs, Diags, Argv0);
4717 std::string CompilerInvocation::getModuleHash() const {
4718 // FIXME: Consider using SHA1 instead of MD5.
4719 llvm::HashBuilder<llvm::MD5, llvm::endianness::native> HBuilder;
4721 // Note: For QoI reasons, the things we use as a hash here should all be
4722 // dumped via the -module-info flag.
4724 // Start the signature with the compiler version.
4725 HBuilder.add(getClangFullRepositoryVersion());
4727 // Also include the serialization version, in case LLVM_APPEND_VC_REV is off
4728 // and getClangFullRepositoryVersion() doesn't include git revision.
4729 HBuilder.add(serialization::VERSION_MAJOR, serialization::VERSION_MINOR);
4731 // Extend the signature with the language options
4732 #define LANGOPT(Name, Bits, Default, Description) HBuilder.add(LangOpts->Name);
4733 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4734 HBuilder.add(static_cast<unsigned>(LangOpts->get##Name()));
4735 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
4736 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
4737 #include "clang/Basic/LangOptions.def"
4739 HBuilder.addRange(getLangOpts().ModuleFeatures);
4741 HBuilder.add(getLangOpts().ObjCRuntime);
4742 HBuilder.addRange(getLangOpts().CommentOpts.BlockCommandNames);
4744 // Extend the signature with the target options.
4745 HBuilder.add(getTargetOpts().Triple, getTargetOpts().CPU,
4746 getTargetOpts().TuneCPU, getTargetOpts().ABI);
4747 HBuilder.addRange(getTargetOpts().FeaturesAsWritten);
4749 // Extend the signature with preprocessor options.
4750 const PreprocessorOptions &ppOpts = getPreprocessorOpts();
4751 HBuilder.add(ppOpts.UsePredefines, ppOpts.DetailedRecord);
4753 const HeaderSearchOptions &hsOpts = getHeaderSearchOpts();
4754 for (const auto &Macro : getPreprocessorOpts().Macros) {
4755 // If we're supposed to ignore this macro for the purposes of modules,
4756 // don't put it into the hash.
4757 if (!hsOpts.ModulesIgnoreMacros.empty()) {
4758 // Check whether we're ignoring this macro.
4759 StringRef MacroDef = Macro.first;
4760 if (hsOpts.ModulesIgnoreMacros.count(
4761 llvm::CachedHashString(MacroDef.split('=').first)))
4762 continue;
4765 HBuilder.add(Macro);
4768 // Extend the signature with the sysroot and other header search options.
4769 HBuilder.add(hsOpts.Sysroot, hsOpts.ModuleFormat, hsOpts.UseDebugInfo,
4770 hsOpts.UseBuiltinIncludes, hsOpts.UseStandardSystemIncludes,
4771 hsOpts.UseStandardCXXIncludes, hsOpts.UseLibcxx,
4772 hsOpts.ModulesValidateDiagnosticOptions);
4773 HBuilder.add(hsOpts.ResourceDir);
4775 if (hsOpts.ModulesStrictContextHash) {
4776 HBuilder.addRange(hsOpts.SystemHeaderPrefixes);
4777 HBuilder.addRange(hsOpts.UserEntries);
4779 const DiagnosticOptions &diagOpts = getDiagnosticOpts();
4780 #define DIAGOPT(Name, Bits, Default) HBuilder.add(diagOpts.Name);
4781 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
4782 HBuilder.add(diagOpts.get##Name());
4783 #include "clang/Basic/DiagnosticOptions.def"
4784 #undef DIAGOPT
4785 #undef ENUM_DIAGOPT
4788 // Extend the signature with the user build path.
4789 HBuilder.add(hsOpts.ModuleUserBuildPath);
4791 // Extend the signature with the module file extensions.
4792 for (const auto &ext : getFrontendOpts().ModuleFileExtensions)
4793 ext->hashExtension(HBuilder);
4795 // Extend the signature with the Swift version for API notes.
4796 const APINotesOptions &APINotesOpts = getAPINotesOpts();
4797 if (!APINotesOpts.SwiftVersion.empty()) {
4798 HBuilder.add(APINotesOpts.SwiftVersion.getMajor());
4799 if (auto Minor = APINotesOpts.SwiftVersion.getMinor())
4800 HBuilder.add(*Minor);
4801 if (auto Subminor = APINotesOpts.SwiftVersion.getSubminor())
4802 HBuilder.add(*Subminor);
4803 if (auto Build = APINotesOpts.SwiftVersion.getBuild())
4804 HBuilder.add(*Build);
4807 // When compiling with -gmodules, also hash -fdebug-prefix-map as it
4808 // affects the debug info in the PCM.
4809 if (getCodeGenOpts().DebugTypeExtRefs)
4810 HBuilder.addRange(getCodeGenOpts().DebugPrefixMap);
4812 // Extend the signature with the affecting debug options.
4813 if (getHeaderSearchOpts().ModuleFormat == "obj") {
4814 #define DEBUGOPT(Name, Bits, Default) HBuilder.add(CodeGenOpts->Name);
4815 #define VALUE_DEBUGOPT(Name, Bits, Default) HBuilder.add(CodeGenOpts->Name);
4816 #define ENUM_DEBUGOPT(Name, Type, Bits, Default) \
4817 HBuilder.add(static_cast<unsigned>(CodeGenOpts->get##Name()));
4818 #define BENIGN_DEBUGOPT(Name, Bits, Default)
4819 #define BENIGN_VALUE_DEBUGOPT(Name, Bits, Default)
4820 #define BENIGN_ENUM_DEBUGOPT(Name, Type, Bits, Default)
4821 #include "clang/Basic/DebugOptions.def"
4824 // Extend the signature with the enabled sanitizers, if at least one is
4825 // enabled. Sanitizers which cannot affect AST generation aren't hashed.
4826 SanitizerSet SanHash = getLangOpts().Sanitize;
4827 SanHash.clear(getPPTransparentSanitizers());
4828 if (!SanHash.empty())
4829 HBuilder.add(SanHash.Mask);
4831 llvm::MD5::MD5Result Result;
4832 HBuilder.getHasher().final(Result);
4833 uint64_t Hash = Result.high() ^ Result.low();
4834 return toString(llvm::APInt(64, Hash), 36, /*Signed=*/false);
4837 void CompilerInvocationBase::generateCC1CommandLine(
4838 ArgumentConsumer Consumer) const {
4839 llvm::Triple T(getTargetOpts().Triple);
4841 GenerateFileSystemArgs(getFileSystemOpts(), Consumer);
4842 GenerateMigratorArgs(getMigratorOpts(), Consumer);
4843 GenerateAnalyzerArgs(getAnalyzerOpts(), Consumer);
4844 GenerateDiagnosticArgs(getDiagnosticOpts(), Consumer,
4845 /*DefaultDiagColor=*/false);
4846 GenerateFrontendArgs(getFrontendOpts(), Consumer, getLangOpts().IsHeaderFile);
4847 GenerateTargetArgs(getTargetOpts(), Consumer);
4848 GenerateHeaderSearchArgs(getHeaderSearchOpts(), Consumer);
4849 GenerateAPINotesArgs(getAPINotesOpts(), Consumer);
4850 GenerateLangArgs(getLangOpts(), Consumer, T, getFrontendOpts().DashX);
4851 GenerateCodeGenArgs(getCodeGenOpts(), Consumer, T,
4852 getFrontendOpts().OutputFile, &getLangOpts());
4853 GeneratePreprocessorArgs(getPreprocessorOpts(), Consumer, getLangOpts(),
4854 getFrontendOpts(), getCodeGenOpts());
4855 GeneratePreprocessorOutputArgs(getPreprocessorOutputOpts(), Consumer,
4856 getFrontendOpts().ProgramAction);
4857 GenerateDependencyOutputArgs(getDependencyOutputOpts(), Consumer);
4860 std::vector<std::string> CompilerInvocationBase::getCC1CommandLine() const {
4861 std::vector<std::string> Args{"-cc1"};
4862 generateCC1CommandLine(
4863 [&Args](const Twine &Arg) { Args.push_back(Arg.str()); });
4864 return Args;
4867 void CompilerInvocation::resetNonModularOptions() {
4868 getLangOpts().resetNonModularOptions();
4869 getPreprocessorOpts().resetNonModularOptions();
4870 getCodeGenOpts().resetNonModularOptions(getHeaderSearchOpts().ModuleFormat);
4873 void CompilerInvocation::clearImplicitModuleBuildOptions() {
4874 getLangOpts().ImplicitModules = false;
4875 getHeaderSearchOpts().ImplicitModuleMaps = false;
4876 getHeaderSearchOpts().ModuleCachePath.clear();
4877 getHeaderSearchOpts().ModulesValidateOncePerBuildSession = false;
4878 getHeaderSearchOpts().BuildSessionTimestamp = 0;
4879 // The specific values we canonicalize to for pruning don't affect behaviour,
4880 /// so use the default values so they may be dropped from the command-line.
4881 getHeaderSearchOpts().ModuleCachePruneInterval = 7 * 24 * 60 * 60;
4882 getHeaderSearchOpts().ModuleCachePruneAfter = 31 * 24 * 60 * 60;
4885 IntrusiveRefCntPtr<llvm::vfs::FileSystem>
4886 clang::createVFSFromCompilerInvocation(const CompilerInvocation &CI,
4887 DiagnosticsEngine &Diags) {
4888 return createVFSFromCompilerInvocation(CI, Diags,
4889 llvm::vfs::getRealFileSystem());
4892 IntrusiveRefCntPtr<llvm::vfs::FileSystem>
4893 clang::createVFSFromCompilerInvocation(
4894 const CompilerInvocation &CI, DiagnosticsEngine &Diags,
4895 IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS) {
4896 return createVFSFromOverlayFiles(CI.getHeaderSearchOpts().VFSOverlayFiles,
4897 Diags, std::move(BaseFS));
4900 IntrusiveRefCntPtr<llvm::vfs::FileSystem> clang::createVFSFromOverlayFiles(
4901 ArrayRef<std::string> VFSOverlayFiles, DiagnosticsEngine &Diags,
4902 IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS) {
4903 if (VFSOverlayFiles.empty())
4904 return BaseFS;
4906 IntrusiveRefCntPtr<llvm::vfs::FileSystem> Result = BaseFS;
4907 // earlier vfs files are on the bottom
4908 for (const auto &File : VFSOverlayFiles) {
4909 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
4910 Result->getBufferForFile(File);
4911 if (!Buffer) {
4912 Diags.Report(diag::err_missing_vfs_overlay_file) << File;
4913 continue;
4916 IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS = llvm::vfs::getVFSFromYAML(
4917 std::move(Buffer.get()), /*DiagHandler*/ nullptr, File,
4918 /*DiagContext*/ nullptr, Result);
4919 if (!FS) {
4920 Diags.Report(diag::err_invalid_vfs_overlay) << File;
4921 continue;
4924 Result = FS;
4926 return Result;