1//===- CompilerInvocation.cpp ---------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "clang/Frontend/CompilerInvocation.h"
10#include "TestModuleFileExtension.h"
11#include "clang/Basic/Builtins.h"
12#include "clang/Basic/CharInfo.h"
13#include "clang/Basic/CodeGenOptions.h"
14#include "clang/Basic/CommentOptions.h"
15#include "clang/Basic/Diagnostic.h"
16#include "clang/Basic/DiagnosticDriver.h"
17#include "clang/Basic/DiagnosticFrontend.h"
18#include "clang/Basic/DiagnosticOptions.h"
19#include "clang/Basic/FileSystemOptions.h"
20#include "clang/Basic/LLVM.h"
21#include "clang/Basic/LangOptions.h"
22#include "clang/Basic/LangStandard.h"
23#include "clang/Basic/ObjCRuntime.h"
24#include "clang/Basic/Sanitizers.h"
25#include "clang/Basic/SourceLocation.h"
26#include "clang/Basic/TargetOptions.h"
27#include "clang/Basic/Version.h"
28#include "clang/Basic/XRayInstr.h"
29#include "clang/Config/config.h"
30#include "clang/Frontend/CommandLineSourceLoc.h"
31#include "clang/Frontend/DependencyOutputOptions.h"
32#include "clang/Frontend/FrontendOptions.h"
33#include "clang/Frontend/MigratorOptions.h"
34#include "clang/Frontend/PreprocessorOutputOptions.h"
35#include "clang/Frontend/TextDiagnosticBuffer.h"
36#include "clang/Frontend/Utils.h"
37#include "clang/Lex/HeaderSearchOptions.h"
38#include "clang/Lex/PreprocessorOptions.h"
39#include "clang/Options/Options.h"
40#include "clang/Serialization/ASTBitCodes.h"
41#include "clang/Serialization/ModuleFileExtension.h"
42#include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
43#include "llvm/ADT/APInt.h"
44#include "llvm/ADT/ArrayRef.h"
45#include "llvm/ADT/CachedHashString.h"
46#include "llvm/ADT/FloatingPointMode.h"
47#include "llvm/ADT/STLExtras.h"
48#include "llvm/ADT/SmallVector.h"
49#include "llvm/ADT/StringRef.h"
50#include "llvm/ADT/StringSwitch.h"
51#include "llvm/ADT/Twine.h"
52#include "llvm/Config/llvm-config.h"
53#include "llvm/Frontend/Debug/Options.h"
54#include "llvm/IR/DebugInfoMetadata.h"
55#include "llvm/Linker/Linker.h"
56#include "llvm/MC/MCTargetOptions.h"
57#include "llvm/Option/Arg.h"
58#include "llvm/Option/ArgList.h"
59#include "llvm/Option/OptSpecifier.h"
60#include "llvm/Option/OptTable.h"
61#include "llvm/Option/Option.h"
62#include "llvm/ProfileData/InstrProfReader.h"
63#include "llvm/Remarks/HotnessThresholdParser.h"
64#include "llvm/Support/CodeGen.h"
65#include "llvm/Support/Compiler.h"
66#include "llvm/Support/Error.h"
67#include "llvm/Support/ErrorHandling.h"
68#include "llvm/Support/ErrorOr.h"
69#include "llvm/Support/FileSystem.h"
70#include "llvm/Support/HashBuilder.h"
71#include "llvm/Support/MathExtras.h"
72#include "llvm/Support/MemoryBuffer.h"
73#include "llvm/Support/Path.h"
74#include "llvm/Support/Process.h"
75#include "llvm/Support/Regex.h"
76#include "llvm/Support/VersionTuple.h"
77#include "llvm/Support/VirtualFileSystem.h"
78#include "llvm/Support/raw_ostream.h"
79#include "llvm/Target/TargetOptions.h"
80#include "llvm/TargetParser/Host.h"
81#include "llvm/TargetParser/Triple.h"
82#include <algorithm>
83#include <cassert>
84#include <cstddef>
85#include <cstring>
86#include <ctime>
87#include <fstream>
88#include <limits>
89#include <memory>
90#include <optional>
91#include <string>
92#include <tuple>
93#include <type_traits>
94#include <utility>
95#include <vector>
96
97using namespace clang;
98using namespace options;
99using namespace llvm::opt;
100
101//===----------------------------------------------------------------------===//
102// Helpers.
103//===----------------------------------------------------------------------===//
104
105// Parse misexpect tolerance argument value.
106// Valid option values are integers in the range [0, 100)
107static Expected<std::optional<uint32_t>> parseToleranceOption(StringRef Arg) {
108 uint32_t Val;
109 if (Arg.getAsInteger(Radix: 10, Result&: Val))
110 return llvm::createStringError(EC: llvm::inconvertibleErrorCode(),
111 Fmt: "Not an integer: %s", Vals: Arg.data());
112 return Val;
113}
114
115//===----------------------------------------------------------------------===//
116// Initialization.
117//===----------------------------------------------------------------------===//
118
119template <class T> std::shared_ptr<T> make_shared_copy(const T &X) {
120 return std::make_shared<T>(X);
121}
122
123CompilerInvocationBase::CompilerInvocationBase()
124 : LangOpts(std::make_shared<LangOptions>()),
125 TargetOpts(std::make_shared<TargetOptions>()),
126 DiagnosticOpts(std::make_shared<DiagnosticOptions>()),
127 HSOpts(std::make_shared<HeaderSearchOptions>()),
128 PPOpts(std::make_shared<PreprocessorOptions>()),
129 AnalyzerOpts(std::make_shared<AnalyzerOptions>()),
130 MigratorOpts(std::make_shared<MigratorOptions>()),
131 APINotesOpts(std::make_shared<APINotesOptions>()),
132 CodeGenOpts(std::make_shared<CodeGenOptions>()),
133 FSOpts(std::make_shared<FileSystemOptions>()),
134 FrontendOpts(std::make_shared<FrontendOptions>()),
135 DependencyOutputOpts(std::make_shared<DependencyOutputOptions>()),
136 PreprocessorOutputOpts(std::make_shared<PreprocessorOutputOptions>()) {}
137
138CompilerInvocationBase &
139CompilerInvocationBase::deep_copy_assign(const CompilerInvocationBase &X) {
140 if (this != &X) {
141 LangOpts = make_shared_copy(X: X.getLangOpts());
142 TargetOpts = make_shared_copy(X: X.getTargetOpts());
143 DiagnosticOpts = make_shared_copy(X: X.getDiagnosticOpts());
144 HSOpts = make_shared_copy(X: X.getHeaderSearchOpts());
145 PPOpts = make_shared_copy(X: X.getPreprocessorOpts());
146 AnalyzerOpts = make_shared_copy(X: X.getAnalyzerOpts());
147 MigratorOpts = make_shared_copy(X: X.getMigratorOpts());
148 APINotesOpts = make_shared_copy(X: X.getAPINotesOpts());
149 CodeGenOpts = make_shared_copy(X: X.getCodeGenOpts());
150 FSOpts = make_shared_copy(X: X.getFileSystemOpts());
151 FrontendOpts = make_shared_copy(X: X.getFrontendOpts());
152 DependencyOutputOpts = make_shared_copy(X: X.getDependencyOutputOpts());
153 PreprocessorOutputOpts = make_shared_copy(X: X.getPreprocessorOutputOpts());
154 }
155 return *this;
156}
157
158CompilerInvocationBase &
159CompilerInvocationBase::shallow_copy_assign(const CompilerInvocationBase &X) {
160 if (this != &X) {
161 LangOpts = X.LangOpts;
162 TargetOpts = X.TargetOpts;
163 DiagnosticOpts = X.DiagnosticOpts;
164 HSOpts = X.HSOpts;
165 PPOpts = X.PPOpts;
166 AnalyzerOpts = X.AnalyzerOpts;
167 MigratorOpts = X.MigratorOpts;
168 APINotesOpts = X.APINotesOpts;
169 CodeGenOpts = X.CodeGenOpts;
170 FSOpts = X.FSOpts;
171 FrontendOpts = X.FrontendOpts;
172 DependencyOutputOpts = X.DependencyOutputOpts;
173 PreprocessorOutputOpts = X.PreprocessorOutputOpts;
174 }
175 return *this;
176}
177
178CompilerInvocation::CompilerInvocation(const CowCompilerInvocation &X)
179 : CompilerInvocationBase(EmptyConstructor{}) {
180 CompilerInvocationBase::deep_copy_assign(X);
181}
182
183CompilerInvocation &
184CompilerInvocation::operator=(const CowCompilerInvocation &X) {
185 CompilerInvocationBase::deep_copy_assign(X);
186 return *this;
187}
188
189template <typename T>
190T &ensureOwned(std::shared_ptr<T> &Storage) {
191 if (Storage.use_count() > 1)
192 Storage = std::make_shared<T>(*Storage);
193 return *Storage;
194}
195
196LangOptions &CowCompilerInvocation::getMutLangOpts() {
197 return ensureOwned(Storage&: LangOpts);
198}
199
200TargetOptions &CowCompilerInvocation::getMutTargetOpts() {
201 return ensureOwned(Storage&: TargetOpts);
202}
203
204DiagnosticOptions &CowCompilerInvocation::getMutDiagnosticOpts() {
205 return ensureOwned(Storage&: DiagnosticOpts);
206}
207
208HeaderSearchOptions &CowCompilerInvocation::getMutHeaderSearchOpts() {
209 return ensureOwned(Storage&: HSOpts);
210}
211
212PreprocessorOptions &CowCompilerInvocation::getMutPreprocessorOpts() {
213 return ensureOwned(Storage&: PPOpts);
214}
215
216AnalyzerOptions &CowCompilerInvocation::getMutAnalyzerOpts() {
217 return ensureOwned(Storage&: AnalyzerOpts);
218}
219
220MigratorOptions &CowCompilerInvocation::getMutMigratorOpts() {
221 return ensureOwned(Storage&: MigratorOpts);
222}
223
224APINotesOptions &CowCompilerInvocation::getMutAPINotesOpts() {
225 return ensureOwned(Storage&: APINotesOpts);
226}
227
228CodeGenOptions &CowCompilerInvocation::getMutCodeGenOpts() {
229 return ensureOwned(Storage&: CodeGenOpts);
230}
231
232FileSystemOptions &CowCompilerInvocation::getMutFileSystemOpts() {
233 return ensureOwned(Storage&: FSOpts);
234}
235
236FrontendOptions &CowCompilerInvocation::getMutFrontendOpts() {
237 return ensureOwned(Storage&: FrontendOpts);
238}
239
240DependencyOutputOptions &CowCompilerInvocation::getMutDependencyOutputOpts() {
241 return ensureOwned(Storage&: DependencyOutputOpts);
242}
243
244PreprocessorOutputOptions &
245CowCompilerInvocation::getMutPreprocessorOutputOpts() {
246 return ensureOwned(Storage&: PreprocessorOutputOpts);
247}
248
249//===----------------------------------------------------------------------===//
250// Normalizers
251//===----------------------------------------------------------------------===//
252
253using ArgumentConsumer = CompilerInvocation::ArgumentConsumer;
254
255#define OPTTABLE_STR_TABLE_CODE
256#include "clang/Options/Options.inc"
257#undef OPTTABLE_STR_TABLE_CODE
258
259static llvm::StringRef lookupStrInTable(unsigned Offset) {
260 return OptionStrTable[Offset];
261}
262
263#define SIMPLE_ENUM_VALUE_TABLE
264#include "clang/Options/Options.inc"
265#undef SIMPLE_ENUM_VALUE_TABLE
266
267static std::optional<bool> normalizeSimpleFlag(OptSpecifier Opt,
268 unsigned TableIndex,
269 const ArgList &Args,
270 DiagnosticsEngine &Diags) {
271 if (Args.hasArg(Ids: Opt))
272 return true;
273 return std::nullopt;
274}
275
276static std::optional<bool> normalizeSimpleNegativeFlag(OptSpecifier Opt,
277 unsigned,
278 const ArgList &Args,
279 DiagnosticsEngine &) {
280 if (Args.hasArg(Ids: Opt))
281 return false;
282 return std::nullopt;
283}
284
285/// The tblgen-erated code passes in a fifth parameter of an arbitrary type, but
286/// denormalizeSimpleFlags never looks at it. Avoid bloating compile-time with
287/// unnecessary template instantiations and just ignore it with a variadic
288/// argument.
289static void denormalizeSimpleFlag(ArgumentConsumer Consumer,
290 unsigned SpellingOffset, Option::OptionClass,
291 unsigned, /*T*/...) {
292 Consumer(lookupStrInTable(Offset: SpellingOffset));
293}
294static void denormalizeSimpleFlag(ArgumentConsumer Consumer,
295 const Twine &Spelling, Option::OptionClass,
296 unsigned, /*T*/...) {
297 Consumer(Spelling);
298}
299
300template <typename T> static constexpr bool is_uint64_t_convertible() {
301 return !std::is_same_v<T, uint64_t> && llvm::is_integral_or_enum<T>::value;
302}
303
304template <typename T,
305 std::enable_if_t<!is_uint64_t_convertible<T>(), bool> = false>
306static auto makeFlagToValueNormalizer(T Value) {
307 return [Value](OptSpecifier Opt, unsigned, const ArgList &Args,
308 DiagnosticsEngine &) -> std::optional<T> {
309 if (Args.hasArg(Ids: Opt))
310 return Value;
311 return std::nullopt;
312 };
313}
314
315template <typename T,
316 std::enable_if_t<is_uint64_t_convertible<T>(), bool> = false>
317static auto makeFlagToValueNormalizer(T Value) {
318 return makeFlagToValueNormalizer(Value: uint64_t(Value));
319}
320
321static auto makeBooleanOptionNormalizer(bool Value, bool OtherValue,
322 OptSpecifier OtherOpt) {
323 return [Value, OtherValue,
324 OtherOpt](OptSpecifier Opt, unsigned, const ArgList &Args,
325 DiagnosticsEngine &) -> std::optional<bool> {
326 if (const Arg *A = Args.getLastArg(Ids: Opt, Ids: OtherOpt)) {
327 return A->getOption().matches(ID: Opt) ? Value : OtherValue;
328 }
329 return std::nullopt;
330 };
331}
332
333static auto makeBooleanOptionDenormalizer(bool Value) {
334 return [Value](ArgumentConsumer Consumer, unsigned SpellingOffset,
335 Option::OptionClass, unsigned, bool KeyPath) {
336 if (KeyPath == Value)
337 Consumer(lookupStrInTable(Offset: SpellingOffset));
338 };
339}
340
341static void denormalizeStringImpl(ArgumentConsumer Consumer,
342 const Twine &Spelling,
343 Option::OptionClass OptClass, unsigned,
344 const Twine &Value) {
345 switch (OptClass) {
346 case Option::SeparateClass:
347 case Option::JoinedOrSeparateClass:
348 case Option::JoinedAndSeparateClass:
349 Consumer(Spelling);
350 Consumer(Value);
351 break;
352 case Option::JoinedClass:
353 case Option::CommaJoinedClass:
354 Consumer(Spelling + Value);
355 break;
356 default:
357 llvm_unreachable("Cannot denormalize an option with option class "
358 "incompatible with string denormalization.");
359 }
360}
361
362template <typename T>
363static void
364denormalizeString(ArgumentConsumer Consumer, unsigned SpellingOffset,
365 Option::OptionClass OptClass, unsigned TableIndex, T Value) {
366 denormalizeStringImpl(Consumer, Spelling: lookupStrInTable(Offset: SpellingOffset), OptClass,
367 TableIndex, Value: Twine(Value));
368}
369
370template <typename T>
371static void denormalizeString(ArgumentConsumer Consumer, const Twine &Spelling,
372 Option::OptionClass OptClass, unsigned TableIndex,
373 T Value) {
374 denormalizeStringImpl(Consumer, Spelling, OptClass, TableIndex, Value: Twine(Value));
375}
376
377static std::optional<SimpleEnumValue>
378findValueTableByName(const SimpleEnumValueTable &Table, StringRef Name) {
379 for (int I = 0, E = Table.Size; I != E; ++I)
380 if (Name == Table.Table[I].Name)
381 return Table.Table[I];
382
383 return std::nullopt;
384}
385
386static std::optional<SimpleEnumValue>
387findValueTableByValue(const SimpleEnumValueTable &Table, unsigned Value) {
388 for (int I = 0, E = Table.Size; I != E; ++I)
389 if (Value == Table.Table[I].Value)
390 return Table.Table[I];
391
392 return std::nullopt;
393}
394
395static std::optional<unsigned> normalizeSimpleEnum(OptSpecifier Opt,
396 unsigned TableIndex,
397 const ArgList &Args,
398 DiagnosticsEngine &Diags) {
399 assert(TableIndex < SimpleEnumValueTablesSize);
400 const SimpleEnumValueTable &Table = SimpleEnumValueTables[TableIndex];
401
402 auto *Arg = Args.getLastArg(Ids: Opt);
403 if (!Arg)
404 return std::nullopt;
405
406 StringRef ArgValue = Arg->getValue();
407 if (auto MaybeEnumVal = findValueTableByName(Table, Name: ArgValue))
408 return MaybeEnumVal->Value;
409
410 Diags.Report(DiagID: diag::err_drv_invalid_value)
411 << Arg->getAsString(Args) << ArgValue;
412 return std::nullopt;
413}
414
415static void denormalizeSimpleEnumImpl(ArgumentConsumer Consumer,
416 unsigned SpellingOffset,
417 Option::OptionClass OptClass,
418 unsigned TableIndex, unsigned Value) {
419 assert(TableIndex < SimpleEnumValueTablesSize);
420 const SimpleEnumValueTable &Table = SimpleEnumValueTables[TableIndex];
421 if (auto MaybeEnumVal = findValueTableByValue(Table, Value)) {
422 denormalizeString(Consumer, Spelling: lookupStrInTable(Offset: SpellingOffset), OptClass,
423 TableIndex, Value: MaybeEnumVal->Name);
424 } else {
425 llvm_unreachable("The simple enum value was not correctly defined in "
426 "the tablegen option description");
427 }
428}
429
430template <typename T>
431static void denormalizeSimpleEnum(ArgumentConsumer Consumer,
432 unsigned SpellingOffset,
433 Option::OptionClass OptClass,
434 unsigned TableIndex, T Value) {
435 return denormalizeSimpleEnumImpl(Consumer, SpellingOffset, OptClass,
436 TableIndex, Value: static_cast<unsigned>(Value));
437}
438
439static std::optional<std::string> normalizeString(OptSpecifier Opt,
440 int TableIndex,
441 const ArgList &Args,
442 DiagnosticsEngine &Diags) {
443 auto *Arg = Args.getLastArg(Ids: Opt);
444 if (!Arg)
445 return std::nullopt;
446 return std::string(Arg->getValue());
447}
448
449template <typename IntTy>
450static std::optional<IntTy> normalizeStringIntegral(OptSpecifier Opt, int,
451 const ArgList &Args,
452 DiagnosticsEngine &Diags) {
453 auto *Arg = Args.getLastArg(Ids: Opt);
454 if (!Arg)
455 return std::nullopt;
456 IntTy Res;
457 if (StringRef(Arg->getValue()).getAsInteger(0, Res)) {
458 Diags.Report(DiagID: diag::err_drv_invalid_int_value)
459 << Arg->getAsString(Args) << Arg->getValue();
460 return std::nullopt;
461 }
462 return Res;
463}
464
465static std::optional<std::vector<std::string>>
466normalizeStringVector(OptSpecifier Opt, int, const ArgList &Args,
467 DiagnosticsEngine &) {
468 return Args.getAllArgValues(Id: Opt);
469}
470
471static void denormalizeStringVector(ArgumentConsumer Consumer,
472 unsigned SpellingOffset,
473 Option::OptionClass OptClass,
474 unsigned TableIndex,
475 const std::vector<std::string> &Values) {
476 switch (OptClass) {
477 case Option::CommaJoinedClass: {
478 std::string CommaJoinedValue;
479 if (!Values.empty()) {
480 CommaJoinedValue.append(str: Values.front());
481 for (const std::string &Value : llvm::drop_begin(RangeOrContainer: Values, N: 1)) {
482 CommaJoinedValue.append(s: ",");
483 CommaJoinedValue.append(str: Value);
484 }
485 }
486 denormalizeString(Consumer, SpellingOffset,
487 OptClass: Option::OptionClass::JoinedClass, TableIndex,
488 Value: CommaJoinedValue);
489 break;
490 }
491 case Option::JoinedClass:
492 case Option::SeparateClass:
493 case Option::JoinedOrSeparateClass:
494 for (const std::string &Value : Values)
495 denormalizeString(Consumer, SpellingOffset, OptClass, TableIndex, Value);
496 break;
497 default:
498 llvm_unreachable("Cannot denormalize an option with option class "
499 "incompatible with string vector denormalization.");
500 }
501}
502
503static std::optional<std::string> normalizeTriple(OptSpecifier Opt,
504 int TableIndex,
505 const ArgList &Args,
506 DiagnosticsEngine &Diags) {
507 auto *Arg = Args.getLastArg(Ids: Opt);
508 if (!Arg)
509 return std::nullopt;
510 return llvm::Triple::normalize(Str: Arg->getValue());
511}
512
513template <typename T, typename U>
514static T mergeForwardValue(T KeyPath, U Value) {
515 return static_cast<T>(Value);
516}
517
518template <typename T, typename U> static T mergeMaskValue(T KeyPath, U Value) {
519 return KeyPath | Value;
520}
521
522template <typename T> static T extractForwardValue(T KeyPath) {
523 return KeyPath;
524}
525
526template <typename T, typename U, U Value>
527static T extractMaskValue(T KeyPath) {
528 return ((KeyPath & Value) == Value) ? static_cast<T>(Value) : T();
529}
530
531#define PARSE_OPTION_WITH_MARSHALLING( \
532 ARGS, DIAGS, PREFIX_TYPE, SPELLING_OFFSET, ID, KIND, GROUP, ALIAS, \
533 ALIASARGS, FLAGS, VISIBILITY, PARAM, HELPTEXT, HELPTEXTSFORVARIANTS, \
534 METAVAR, VALUES, SUBCOMMANDIDS_OFFSET, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
535 DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
536 MERGER, EXTRACTOR, TABLE_INDEX) \
537 if ((VISIBILITY) & options::CC1Option) { \
538 KEYPATH = MERGER(KEYPATH, DEFAULT_VALUE); \
539 if (IMPLIED_CHECK) \
540 KEYPATH = MERGER(KEYPATH, IMPLIED_VALUE); \
541 if (SHOULD_PARSE) \
542 if (auto MaybeValue = NORMALIZER(OPT_##ID, TABLE_INDEX, ARGS, DIAGS)) \
543 KEYPATH = \
544 MERGER(KEYPATH, static_cast<decltype(KEYPATH)>(*MaybeValue)); \
545 }
546
547// Capture the extracted value as a lambda argument to avoid potential issues
548// with lifetime extension of the reference.
549#define GENERATE_OPTION_WITH_MARSHALLING( \
550 CONSUMER, PREFIX_TYPE, SPELLING_OFFSET, ID, KIND, GROUP, ALIAS, ALIASARGS, \
551 FLAGS, VISIBILITY, PARAM, HELPTEXT, HELPTEXTSFORVARIANTS, METAVAR, VALUES, \
552 SUBCOMMANDIDS_OFFSET, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
553 IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, MERGER, EXTRACTOR, \
554 TABLE_INDEX) \
555 if ((VISIBILITY) & options::CC1Option) { \
556 [&](const auto &Extracted) { \
557 if (ALWAYS_EMIT || \
558 (Extracted != \
559 static_cast<decltype(KEYPATH)>((IMPLIED_CHECK) ? (IMPLIED_VALUE) \
560 : (DEFAULT_VALUE)))) \
561 DENORMALIZER(CONSUMER, SPELLING_OFFSET, Option::KIND##Class, \
562 TABLE_INDEX, Extracted); \
563 }(EXTRACTOR(KEYPATH)); \
564 }
565
566static StringRef GetInputKindName(InputKind IK);
567
568static bool FixupInvocation(CompilerInvocation &Invocation,
569 DiagnosticsEngine &Diags, const ArgList &Args,
570 InputKind IK) {
571 unsigned NumErrorsBefore = Diags.getNumErrors();
572
573 LangOptions &LangOpts = Invocation.getLangOpts();
574 CodeGenOptions &CodeGenOpts = Invocation.getCodeGenOpts();
575 TargetOptions &TargetOpts = Invocation.getTargetOpts();
576 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
577 CodeGenOpts.XRayInstrumentFunctions = LangOpts.XRayInstrument;
578 CodeGenOpts.XRayAlwaysEmitCustomEvents = LangOpts.XRayAlwaysEmitCustomEvents;
579 CodeGenOpts.XRayAlwaysEmitTypedEvents = LangOpts.XRayAlwaysEmitTypedEvents;
580 CodeGenOpts.DisableFree = FrontendOpts.DisableFree;
581 FrontendOpts.GenerateGlobalModuleIndex = FrontendOpts.UseGlobalModuleIndex;
582 if (FrontendOpts.ShowStats)
583 CodeGenOpts.ClearASTBeforeBackend = false;
584 LangOpts.SanitizeCoverage = CodeGenOpts.hasSanitizeCoverage();
585 LangOpts.ForceEmitVTables = CodeGenOpts.ForceEmitVTables;
586 LangOpts.SpeculativeLoadHardening = CodeGenOpts.SpeculativeLoadHardening;
587 LangOpts.CurrentModule = LangOpts.ModuleName;
588
589 llvm::Triple T(TargetOpts.Triple);
590 llvm::Triple::ArchType Arch = T.getArch();
591
592 CodeGenOpts.CodeModel = TargetOpts.CodeModel;
593 CodeGenOpts.LargeDataThreshold = TargetOpts.LargeDataThreshold;
594
595 if (CodeGenOpts.getExceptionHandling() !=
596 CodeGenOptions::ExceptionHandlingKind::None &&
597 T.isWindowsMSVCEnvironment())
598 Diags.Report(DiagID: diag::err_fe_invalid_exception_model)
599 << static_cast<unsigned>(CodeGenOpts.getExceptionHandling()) << T.str();
600
601 if (LangOpts.AppleKext && !LangOpts.CPlusPlus)
602 Diags.Report(DiagID: diag::warn_c_kext);
603
604 if (LangOpts.NewAlignOverride &&
605 !llvm::isPowerOf2_32(Value: LangOpts.NewAlignOverride)) {
606 Arg *A = Args.getLastArg(Ids: OPT_fnew_alignment_EQ);
607 Diags.Report(DiagID: diag::err_fe_invalid_alignment)
608 << A->getAsString(Args) << A->getValue();
609 LangOpts.NewAlignOverride = 0;
610 }
611
612 // The -f[no-]raw-string-literals option is only valid in C and in C++
613 // standards before C++11.
614 if (LangOpts.CPlusPlus11) {
615 if (Args.hasArg(Ids: OPT_fraw_string_literals, Ids: OPT_fno_raw_string_literals)) {
616 Args.claimAllArgs(Ids: OPT_fraw_string_literals, Ids: OPT_fno_raw_string_literals);
617 Diags.Report(DiagID: diag::warn_drv_fraw_string_literals_in_cxx11)
618 << bool(LangOpts.RawStringLiterals);
619 }
620
621 // Do not allow disabling raw string literals in C++11 or later.
622 LangOpts.RawStringLiterals = true;
623 }
624
625 if (Args.hasArg(Ids: OPT_freflection) && !LangOpts.CPlusPlus26) {
626 Diags.Report(DiagID: diag::err_drv_reflection_requires_cxx26)
627 << Args.getLastArg(Ids: options::OPT_freflection)->getAsString(Args);
628 }
629
630 LangOpts.NamedLoops =
631 Args.hasFlag(Pos: OPT_fnamed_loops, Neg: OPT_fno_named_loops, Default: LangOpts.C2y);
632
633 // Prevent the user from specifying both -fsycl-is-device and -fsycl-is-host.
634 if (LangOpts.SYCLIsDevice && LangOpts.SYCLIsHost)
635 Diags.Report(DiagID: diag::err_drv_argument_not_allowed_with) << "-fsycl-is-device"
636 << "-fsycl-is-host";
637
638 if (Args.hasArg(Ids: OPT_fgnu89_inline) && LangOpts.CPlusPlus)
639 Diags.Report(DiagID: diag::err_drv_argument_not_allowed_with)
640 << "-fgnu89-inline" << GetInputKindName(IK);
641
642 if (Args.hasArg(Ids: OPT_hlsl_entrypoint) && !LangOpts.HLSL)
643 Diags.Report(DiagID: diag::err_drv_argument_not_allowed_with)
644 << "-hlsl-entry" << GetInputKindName(IK);
645
646 if (Args.hasArg(Ids: OPT_fdx_rootsignature_version) && !LangOpts.HLSL)
647 Diags.Report(DiagID: diag::err_drv_argument_not_allowed_with)
648 << "-fdx-rootsignature-version" << GetInputKindName(IK);
649
650 if (Args.hasArg(Ids: OPT_fdx_rootsignature_define) && !LangOpts.HLSL)
651 Diags.Report(DiagID: diag::err_drv_argument_not_allowed_with)
652 << "-fdx-rootsignature-define" << GetInputKindName(IK);
653
654 if (Args.hasArg(Ids: OPT_fgpu_allow_device_init) && !LangOpts.HIP)
655 Diags.Report(DiagID: diag::warn_ignored_hip_only_option)
656 << Args.getLastArg(Ids: OPT_fgpu_allow_device_init)->getAsString(Args);
657
658 if (Args.hasArg(Ids: OPT_gpu_max_threads_per_block_EQ) && !LangOpts.HIP)
659 Diags.Report(DiagID: diag::warn_ignored_hip_only_option)
660 << Args.getLastArg(Ids: OPT_gpu_max_threads_per_block_EQ)->getAsString(Args);
661
662 // HLSL invocations should always have -Wconversion, -Wvector-conversion, and
663 // -Wmatrix-conversion by default.
664 if (LangOpts.HLSL) {
665 auto &Warnings = Invocation.getDiagnosticOpts().Warnings;
666 if (!llvm::is_contained(Range&: Warnings, Element: "conversion"))
667 Warnings.insert(position: Warnings.begin(), x: "conversion");
668 if (!llvm::is_contained(Range&: Warnings, Element: "vector-conversion"))
669 Warnings.insert(position: Warnings.begin(), x: "vector-conversion");
670 if (!llvm::is_contained(Range&: Warnings, Element: "matrix-conversion"))
671 Warnings.insert(position: Warnings.begin(), x: "matrix-conversion");
672 }
673
674 // When these options are used, the compiler is allowed to apply
675 // optimizations that may affect the final result. For example
676 // (x+y)+z is transformed to x+(y+z) but may not give the same
677 // final result; it's not value safe.
678 // Another example can be to simplify x/x to 1.0 but x could be 0.0, INF
679 // or NaN. Final result may then differ. An error is issued when the eval
680 // method is set with one of these options.
681 if (Args.hasArg(Ids: OPT_ffp_eval_method_EQ)) {
682 if (LangOpts.ApproxFunc)
683 Diags.Report(DiagID: diag::err_incompatible_fp_eval_method_options) << 0;
684 if (LangOpts.AllowFPReassoc)
685 Diags.Report(DiagID: diag::err_incompatible_fp_eval_method_options) << 1;
686 if (LangOpts.AllowRecip)
687 Diags.Report(DiagID: diag::err_incompatible_fp_eval_method_options) << 2;
688 }
689
690 // -cl-strict-aliasing needs to emit diagnostic in the case where CL > 1.0.
691 // This option should be deprecated for CL > 1.0 because
692 // this option was added for compatibility with OpenCL 1.0.
693 if (Args.getLastArg(Ids: OPT_cl_strict_aliasing) &&
694 (LangOpts.getOpenCLCompatibleVersion() > 100))
695 Diags.Report(DiagID: diag::warn_option_invalid_ocl_version)
696 << LangOpts.getOpenCLVersionString()
697 << Args.getLastArg(Ids: OPT_cl_strict_aliasing)->getAsString(Args);
698
699 if (Arg *A = Args.getLastArg(Ids: OPT_fdefault_calling_conv_EQ)) {
700 auto DefaultCC = LangOpts.getDefaultCallingConv();
701
702 bool emitError = (DefaultCC == LangOptions::DCC_FastCall ||
703 DefaultCC == LangOptions::DCC_StdCall) &&
704 Arch != llvm::Triple::x86;
705 emitError |= (DefaultCC == LangOptions::DCC_VectorCall ||
706 DefaultCC == LangOptions::DCC_RegCall) &&
707 !T.isX86();
708 emitError |= DefaultCC == LangOptions::DCC_RtdCall && Arch != llvm::Triple::m68k;
709 if (emitError)
710 Diags.Report(DiagID: diag::err_drv_argument_not_allowed_with)
711 << A->getSpelling() << T.getTriple();
712 }
713
714 return Diags.getNumErrors() == NumErrorsBefore;
715}
716
717//===----------------------------------------------------------------------===//
718// Deserialization (from args)
719//===----------------------------------------------------------------------===//
720
721static void GenerateArg(ArgumentConsumer Consumer,
722 llvm::opt::OptSpecifier OptSpecifier) {
723 Option Opt = getDriverOptTable().getOption(Opt: OptSpecifier);
724 denormalizeSimpleFlag(Consumer, Spelling: Opt.getPrefixedName(),
725 Option::OptionClass::FlagClass, 0);
726}
727
728static void GenerateArg(ArgumentConsumer Consumer,
729 llvm::opt::OptSpecifier OptSpecifier,
730 const Twine &Value) {
731 Option Opt = getDriverOptTable().getOption(Opt: OptSpecifier);
732 denormalizeString(Consumer, Spelling: Opt.getPrefixedName(), OptClass: Opt.getKind(), TableIndex: 0, Value);
733}
734
735// Parse command line arguments into CompilerInvocation.
736using ParseFn =
737 llvm::function_ref<bool(CompilerInvocation &, ArrayRef<const char *>,
738 DiagnosticsEngine &, const char *)>;
739
740// Generate command line arguments from CompilerInvocation.
741using GenerateFn = llvm::function_ref<void(
742 CompilerInvocation &, SmallVectorImpl<const char *> &,
743 CompilerInvocation::StringAllocator)>;
744
745/// May perform round-trip of command line arguments. By default, the round-trip
746/// is enabled in assert builds. This can be overwritten at run-time via the
747/// "-round-trip-args" and "-no-round-trip-args" command line flags, or via the
748/// ForceRoundTrip parameter.
749///
750/// During round-trip, the command line arguments are parsed into a dummy
751/// CompilerInvocation, which is used to generate the command line arguments
752/// again. The real CompilerInvocation is then created by parsing the generated
753/// arguments, not the original ones. This (in combination with tests covering
754/// argument behavior) ensures the generated command line is complete (doesn't
755/// drop/mangle any arguments).
756///
757/// Finally, we check the command line that was used to create the real
758/// CompilerInvocation instance. By default, we compare it to the command line
759/// the real CompilerInvocation generates. This checks whether the generator is
760/// deterministic. If \p CheckAgainstOriginalInvocation is enabled, we instead
761/// compare it to the original command line to verify the original command-line
762/// was canonical and can round-trip exactly.
763static bool RoundTrip(ParseFn Parse, GenerateFn Generate,
764 CompilerInvocation &RealInvocation,
765 CompilerInvocation &DummyInvocation,
766 ArrayRef<const char *> CommandLineArgs,
767 DiagnosticsEngine &Diags, const char *Argv0,
768 bool CheckAgainstOriginalInvocation = false,
769 bool ForceRoundTrip = false) {
770#ifndef NDEBUG
771 bool DoRoundTripDefault = true;
772#else
773 bool DoRoundTripDefault = false;
774#endif
775
776 bool DoRoundTrip = DoRoundTripDefault;
777 if (ForceRoundTrip) {
778 DoRoundTrip = true;
779 } else {
780 for (const auto *Arg : CommandLineArgs) {
781 if (Arg == StringRef("-round-trip-args"))
782 DoRoundTrip = true;
783 if (Arg == StringRef("-no-round-trip-args"))
784 DoRoundTrip = false;
785 }
786 }
787
788 // If round-trip was not requested, simply run the parser with the real
789 // invocation diagnostics.
790 if (!DoRoundTrip)
791 return Parse(RealInvocation, CommandLineArgs, Diags, Argv0);
792
793 // Serializes quoted (and potentially escaped) arguments.
794 auto SerializeArgs = [](ArrayRef<const char *> Args) {
795 std::string Buffer;
796 llvm::raw_string_ostream OS(Buffer);
797 for (const char *Arg : Args) {
798 llvm::sys::printArg(OS, Arg, /*Quote=*/true);
799 OS << ' ';
800 }
801 return Buffer;
802 };
803
804 // Setup a dummy DiagnosticsEngine.
805 DiagnosticOptions DummyDiagOpts;
806 DiagnosticsEngine DummyDiags(DiagnosticIDs::create(), DummyDiagOpts);
807 DummyDiags.setClient(client: new TextDiagnosticBuffer());
808
809 // Run the first parse on the original arguments with the dummy invocation and
810 // diagnostics.
811 if (!Parse(DummyInvocation, CommandLineArgs, DummyDiags, Argv0) ||
812 DummyDiags.getNumWarnings() != 0) {
813 // If the first parse did not succeed, it must be user mistake (invalid
814 // command line arguments). We won't be able to generate arguments that
815 // would reproduce the same result. Let's fail again with the real
816 // invocation and diagnostics, so all side-effects of parsing are visible.
817 unsigned NumWarningsBefore = Diags.getNumWarnings();
818 auto Success = Parse(RealInvocation, CommandLineArgs, Diags, Argv0);
819 if (!Success || Diags.getNumWarnings() != NumWarningsBefore)
820 return Success;
821
822 // Parse with original options and diagnostics succeeded even though it
823 // shouldn't have. Something is off.
824 Diags.Report(DiagID: diag::err_cc1_round_trip_fail_then_ok);
825 Diags.Report(DiagID: diag::note_cc1_round_trip_original)
826 << SerializeArgs(CommandLineArgs);
827 return false;
828 }
829
830 // Setup string allocator.
831 llvm::BumpPtrAllocator Alloc;
832 llvm::StringSaver StringPool(Alloc);
833 auto SA = [&StringPool](const Twine &Arg) {
834 return StringPool.save(S: Arg).data();
835 };
836
837 // Generate arguments from the dummy invocation. If Generate is the
838 // inverse of Parse, the newly generated arguments must have the same
839 // semantics as the original.
840 SmallVector<const char *> GeneratedArgs;
841 Generate(DummyInvocation, GeneratedArgs, SA);
842
843 // Run the second parse, now on the generated arguments, and with the real
844 // invocation and diagnostics. The result is what we will end up using for the
845 // rest of compilation, so if Generate is not inverse of Parse, something down
846 // the line will break.
847 bool Success2 = Parse(RealInvocation, GeneratedArgs, Diags, Argv0);
848
849 // The first parse on original arguments succeeded, but second parse of
850 // generated arguments failed. Something must be wrong with the generator.
851 if (!Success2) {
852 Diags.Report(DiagID: diag::err_cc1_round_trip_ok_then_fail);
853 Diags.Report(DiagID: diag::note_cc1_round_trip_generated)
854 << 1 << SerializeArgs(GeneratedArgs);
855 return false;
856 }
857
858 SmallVector<const char *> ComparisonArgs;
859 if (CheckAgainstOriginalInvocation)
860 // Compare against original arguments.
861 ComparisonArgs.assign(in_start: CommandLineArgs.begin(), in_end: CommandLineArgs.end());
862 else
863 // Generate arguments again, this time from the options we will end up using
864 // for the rest of the compilation.
865 Generate(RealInvocation, ComparisonArgs, SA);
866
867 // Compares two lists of arguments.
868 auto Equal = [](const ArrayRef<const char *> A,
869 const ArrayRef<const char *> B) {
870 return llvm::equal(LRange: A, RRange: B, P: [](const char *AElem, const char *BElem) {
871 return StringRef(AElem) == StringRef(BElem);
872 });
873 };
874
875 // If we generated different arguments from what we assume are two
876 // semantically equivalent CompilerInvocations, the Generate function may
877 // be non-deterministic.
878 if (!Equal(GeneratedArgs, ComparisonArgs)) {
879 Diags.Report(DiagID: diag::err_cc1_round_trip_mismatch);
880 Diags.Report(DiagID: diag::note_cc1_round_trip_generated)
881 << 1 << SerializeArgs(GeneratedArgs);
882 Diags.Report(DiagID: diag::note_cc1_round_trip_generated)
883 << 2 << SerializeArgs(ComparisonArgs);
884 return false;
885 }
886
887 Diags.Report(DiagID: diag::remark_cc1_round_trip_generated)
888 << 1 << SerializeArgs(GeneratedArgs);
889 Diags.Report(DiagID: diag::remark_cc1_round_trip_generated)
890 << 2 << SerializeArgs(ComparisonArgs);
891
892 return Success2;
893}
894
895bool CompilerInvocation::checkCC1RoundTrip(ArrayRef<const char *> Args,
896 DiagnosticsEngine &Diags,
897 const char *Argv0) {
898 CompilerInvocation DummyInvocation1, DummyInvocation2;
899 return RoundTrip(
900 Parse: [](CompilerInvocation &Invocation, ArrayRef<const char *> CommandLineArgs,
901 DiagnosticsEngine &Diags, const char *Argv0) {
902 return CreateFromArgsImpl(Res&: Invocation, CommandLineArgs, Diags, Argv0);
903 },
904 Generate: [](CompilerInvocation &Invocation, SmallVectorImpl<const char *> &Args,
905 StringAllocator SA) {
906 Args.push_back(Elt: "-cc1");
907 Invocation.generateCC1CommandLine(Args, SA);
908 },
909 RealInvocation&: DummyInvocation1, DummyInvocation&: DummyInvocation2, CommandLineArgs: Args, Diags, Argv0,
910 /*CheckAgainstOriginalInvocation=*/true, /*ForceRoundTrip=*/true);
911}
912
913static void addDiagnosticArgs(ArgList &Args, OptSpecifier Group,
914 OptSpecifier GroupWithValue,
915 std::vector<std::string> &Diagnostics) {
916 for (auto *A : Args.filtered(Ids: Group)) {
917 if (A->getOption().getKind() == Option::FlagClass) {
918 // The argument is a pure flag (such as OPT_Wall or OPT_Wdeprecated). Add
919 // its name (minus the "W" or "R" at the beginning) to the diagnostics.
920 Diagnostics.push_back(
921 x: std::string(A->getOption().getName().drop_front(N: 1)));
922 } else if (A->getOption().matches(ID: GroupWithValue)) {
923 // This is -Wfoo= or -Rfoo=, where foo is the name of the diagnostic
924 // group. Add only the group name to the diagnostics.
925 Diagnostics.push_back(
926 x: std::string(A->getOption().getName().drop_front(N: 1).rtrim(Chars: "=-")));
927 } else {
928 // Otherwise, add its value (for OPT_W_Joined and similar).
929 Diagnostics.push_back(x: A->getValue());
930 }
931 }
932}
933
934// Parse the Static Analyzer configuration. If \p Diags is set to nullptr,
935// it won't verify the input.
936static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts,
937 DiagnosticsEngine *Diags);
938
939static void getAllNoBuiltinFuncValues(ArgList &Args,
940 std::vector<std::string> &Funcs) {
941 std::vector<std::string> Values = Args.getAllArgValues(Id: OPT_fno_builtin_);
942 auto BuiltinEnd = llvm::partition(Range&: Values, P: Builtin::Context::isBuiltinFunc);
943 Funcs.insert(position: Funcs.end(), first: Values.begin(), last: BuiltinEnd);
944}
945
946static void GenerateAnalyzerArgs(const AnalyzerOptions &Opts,
947 ArgumentConsumer Consumer) {
948 const AnalyzerOptions *AnalyzerOpts = &Opts;
949
950#define ANALYZER_OPTION_WITH_MARSHALLING(...) \
951 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
952#include "clang/Options/Options.inc"
953#undef ANALYZER_OPTION_WITH_MARSHALLING
954
955 if (Opts.AnalysisConstraintsOpt != RangeConstraintsModel) {
956 switch (Opts.AnalysisConstraintsOpt) {
957#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \
958 case NAME##Model: \
959 GenerateArg(Consumer, OPT_analyzer_constraints, CMDFLAG); \
960 break;
961#include "clang/StaticAnalyzer/Core/Analyses.def"
962 default:
963 llvm_unreachable("Tried to generate unknown analysis constraint.");
964 }
965 }
966
967 if (Opts.AnalysisDiagOpt != PD_HTML) {
968 switch (Opts.AnalysisDiagOpt) {
969#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \
970 case PD_##NAME: \
971 GenerateArg(Consumer, OPT_analyzer_output, CMDFLAG); \
972 break;
973#include "clang/StaticAnalyzer/Core/Analyses.def"
974 default:
975 llvm_unreachable("Tried to generate unknown analysis diagnostic client.");
976 }
977 }
978
979 if (Opts.AnalysisPurgeOpt != PurgeStmt) {
980 switch (Opts.AnalysisPurgeOpt) {
981#define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \
982 case NAME: \
983 GenerateArg(Consumer, OPT_analyzer_purge, CMDFLAG); \
984 break;
985#include "clang/StaticAnalyzer/Core/Analyses.def"
986 default:
987 llvm_unreachable("Tried to generate unknown analysis purge mode.");
988 }
989 }
990
991 if (Opts.InliningMode != NoRedundancy) {
992 switch (Opts.InliningMode) {
993#define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \
994 case NAME: \
995 GenerateArg(Consumer, OPT_analyzer_inlining_mode, CMDFLAG); \
996 break;
997#include "clang/StaticAnalyzer/Core/Analyses.def"
998 default:
999 llvm_unreachable("Tried to generate unknown analysis inlining mode.");
1000 }
1001 }
1002
1003 for (const auto &CP : Opts.CheckersAndPackages) {
1004 OptSpecifier Opt =
1005 CP.second ? OPT_analyzer_checker : OPT_analyzer_disable_checker;
1006 GenerateArg(Consumer, OptSpecifier: Opt, Value: CP.first);
1007 }
1008
1009 AnalyzerOptions ConfigOpts;
1010 parseAnalyzerConfigs(AnOpts&: ConfigOpts, Diags: nullptr);
1011
1012 // Sort options by key to avoid relying on StringMap iteration order.
1013 SmallVector<std::pair<StringRef, StringRef>, 4> SortedConfigOpts;
1014 for (const auto &C : Opts.Config)
1015 SortedConfigOpts.emplace_back(Args: C.getKey(), Args: C.getValue());
1016 llvm::sort(C&: SortedConfigOpts, Comp: llvm::less_first());
1017
1018 for (const auto &[Key, Value] : SortedConfigOpts) {
1019 // Don't generate anything that came from parseAnalyzerConfigs. It would be
1020 // redundant and may not be valid on the command line.
1021 auto Entry = ConfigOpts.Config.find(Key);
1022 if (Entry != ConfigOpts.Config.end() && Entry->getValue() == Value)
1023 continue;
1024
1025 GenerateArg(Consumer, OptSpecifier: OPT_analyzer_config, Value: Key + "=" + Value);
1026 }
1027
1028 // Nothing to generate for FullCompilerInvocation.
1029}
1030
1031static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args,
1032 DiagnosticsEngine &Diags) {
1033 unsigned NumErrorsBefore = Diags.getNumErrors();
1034
1035 AnalyzerOptions *AnalyzerOpts = &Opts;
1036
1037#define ANALYZER_OPTION_WITH_MARSHALLING(...) \
1038 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
1039#include "clang/Options/Options.inc"
1040#undef ANALYZER_OPTION_WITH_MARSHALLING
1041
1042 if (Arg *A = Args.getLastArg(Ids: OPT_analyzer_constraints)) {
1043 StringRef Name = A->getValue();
1044 AnalysisConstraints Value = llvm::StringSwitch<AnalysisConstraints>(Name)
1045#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \
1046 .Case(CMDFLAG, NAME##Model)
1047#include "clang/StaticAnalyzer/Core/Analyses.def"
1048 .Default(Value: NumConstraints);
1049 if (Value == NumConstraints) {
1050 Diags.Report(DiagID: diag::err_drv_invalid_value)
1051 << A->getAsString(Args) << Name;
1052 } else {
1053#ifndef LLVM_WITH_Z3
1054 if (Value == AnalysisConstraints::Z3ConstraintsModel) {
1055 Diags.Report(DiagID: diag::err_analyzer_not_built_with_z3);
1056 }
1057#endif // LLVM_WITH_Z3
1058 Opts.AnalysisConstraintsOpt = Value;
1059 }
1060 }
1061
1062 if (Arg *A = Args.getLastArg(Ids: OPT_analyzer_output)) {
1063 StringRef Name = A->getValue();
1064 AnalysisDiagClients Value = llvm::StringSwitch<AnalysisDiagClients>(Name)
1065#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \
1066 .Case(CMDFLAG, PD_##NAME)
1067#include "clang/StaticAnalyzer/Core/Analyses.def"
1068 .Default(Value: NUM_ANALYSIS_DIAG_CLIENTS);
1069 if (Value == NUM_ANALYSIS_DIAG_CLIENTS) {
1070 Diags.Report(DiagID: diag::err_drv_invalid_value)
1071 << A->getAsString(Args) << Name;
1072 } else {
1073 Opts.AnalysisDiagOpt = Value;
1074 }
1075 }
1076
1077 if (Arg *A = Args.getLastArg(Ids: OPT_analyzer_purge)) {
1078 StringRef Name = A->getValue();
1079 AnalysisPurgeMode Value = llvm::StringSwitch<AnalysisPurgeMode>(Name)
1080#define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \
1081 .Case(CMDFLAG, NAME)
1082#include "clang/StaticAnalyzer/Core/Analyses.def"
1083 .Default(Value: NumPurgeModes);
1084 if (Value == NumPurgeModes) {
1085 Diags.Report(DiagID: diag::err_drv_invalid_value)
1086 << A->getAsString(Args) << Name;
1087 } else {
1088 Opts.AnalysisPurgeOpt = Value;
1089 }
1090 }
1091
1092 if (Arg *A = Args.getLastArg(Ids: OPT_analyzer_inlining_mode)) {
1093 StringRef Name = A->getValue();
1094 AnalysisInliningMode Value = llvm::StringSwitch<AnalysisInliningMode>(Name)
1095#define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \
1096 .Case(CMDFLAG, NAME)
1097#include "clang/StaticAnalyzer/Core/Analyses.def"
1098 .Default(Value: NumInliningModes);
1099 if (Value == NumInliningModes) {
1100 Diags.Report(DiagID: diag::err_drv_invalid_value)
1101 << A->getAsString(Args) << Name;
1102 } else {
1103 Opts.InliningMode = Value;
1104 }
1105 }
1106
1107 Opts.CheckersAndPackages.clear();
1108 for (const Arg *A :
1109 Args.filtered(Ids: OPT_analyzer_checker, Ids: OPT_analyzer_disable_checker)) {
1110 A->claim();
1111 bool IsEnabled = A->getOption().getID() == OPT_analyzer_checker;
1112 // We can have a list of comma separated checker names, e.g:
1113 // '-analyzer-checker=cocoa,unix'
1114 StringRef CheckerAndPackageList = A->getValue();
1115 SmallVector<StringRef, 16> CheckersAndPackages;
1116 CheckerAndPackageList.split(A&: CheckersAndPackages, Separator: ",");
1117 for (const StringRef &CheckerOrPackage : CheckersAndPackages)
1118 Opts.CheckersAndPackages.emplace_back(args: std::string(CheckerOrPackage),
1119 args&: IsEnabled);
1120 }
1121
1122 // Go through the analyzer configuration options.
1123 for (const auto *A : Args.filtered(Ids: OPT_analyzer_config)) {
1124
1125 // We can have a list of comma separated config names, e.g:
1126 // '-analyzer-config key1=val1,key2=val2'
1127 StringRef configList = A->getValue();
1128 SmallVector<StringRef, 4> configVals;
1129 configList.split(A&: configVals, Separator: ",");
1130 for (const auto &configVal : configVals) {
1131 StringRef key, val;
1132 std::tie(args&: key, args&: val) = configVal.split(Separator: "=");
1133 if (val.empty()) {
1134 Diags.Report(Loc: SourceLocation(),
1135 DiagID: diag::err_analyzer_config_no_value) << configVal;
1136 break;
1137 }
1138 if (val.contains(C: '=')) {
1139 Diags.Report(Loc: SourceLocation(),
1140 DiagID: diag::err_analyzer_config_multiple_values)
1141 << configVal;
1142 break;
1143 }
1144
1145 // TODO: Check checker options too, possibly in CheckerRegistry.
1146 // Leave unknown non-checker configs unclaimed.
1147 if (!key.contains(Other: ":") && Opts.isUnknownAnalyzerConfig(Name: key)) {
1148 if (Opts.ShouldEmitErrorsOnInvalidConfigValue)
1149 Diags.Report(DiagID: diag::err_analyzer_config_unknown) << key;
1150 continue;
1151 }
1152
1153 A->claim();
1154 Opts.Config[key] = std::string(val);
1155 }
1156 }
1157
1158 if (Opts.ShouldEmitErrorsOnInvalidConfigValue)
1159 parseAnalyzerConfigs(AnOpts&: Opts, Diags: &Diags);
1160 else
1161 parseAnalyzerConfigs(AnOpts&: Opts, Diags: nullptr);
1162
1163 llvm::raw_string_ostream os(Opts.FullCompilerInvocation);
1164 for (unsigned i = 0; i < Args.getNumInputArgStrings(); ++i) {
1165 if (i != 0)
1166 os << " ";
1167 os << Args.getArgString(Index: i);
1168 }
1169
1170 return Diags.getNumErrors() == NumErrorsBefore;
1171}
1172
1173static StringRef getStringOption(AnalyzerOptions::ConfigTable &Config,
1174 StringRef OptionName, StringRef DefaultVal) {
1175 return Config.insert(KV: {OptionName, std::string(DefaultVal)}).first->second;
1176}
1177
1178static void initOption(AnalyzerOptions::ConfigTable &Config,
1179 DiagnosticsEngine *Diags,
1180 StringRef &OptionField, StringRef Name,
1181 StringRef DefaultVal) {
1182 // String options may be known to invalid (e.g. if the expected string is a
1183 // file name, but the file does not exist), those will have to be checked in
1184 // parseConfigs.
1185 OptionField = getStringOption(Config, OptionName: Name, DefaultVal);
1186}
1187
1188static void initOption(AnalyzerOptions::ConfigTable &Config,
1189 DiagnosticsEngine *Diags,
1190 bool &OptionField, StringRef Name, bool DefaultVal) {
1191 auto PossiblyInvalidVal =
1192 llvm::StringSwitch<std::optional<bool>>(
1193 getStringOption(Config, OptionName: Name, DefaultVal: (DefaultVal ? "true" : "false")))
1194 .Case(S: "true", Value: true)
1195 .Case(S: "false", Value: false)
1196 .Default(Value: std::nullopt);
1197
1198 if (!PossiblyInvalidVal) {
1199 if (Diags)
1200 Diags->Report(DiagID: diag::err_analyzer_config_invalid_input)
1201 << Name << "a boolean";
1202 else
1203 OptionField = DefaultVal;
1204 } else
1205 OptionField = *PossiblyInvalidVal;
1206}
1207
1208static void initOption(AnalyzerOptions::ConfigTable &Config,
1209 DiagnosticsEngine *Diags,
1210 unsigned &OptionField, StringRef Name,
1211 unsigned DefaultVal) {
1212
1213 OptionField = DefaultVal;
1214 bool HasFailed = getStringOption(Config, OptionName: Name, DefaultVal: std::to_string(val: DefaultVal))
1215 .getAsInteger(Radix: 0, Result&: OptionField);
1216 if (Diags && HasFailed)
1217 Diags->Report(DiagID: diag::err_analyzer_config_invalid_input)
1218 << Name << "an unsigned";
1219}
1220
1221static void initOption(AnalyzerOptions::ConfigTable &Config,
1222 DiagnosticsEngine *Diags,
1223 PositiveAnalyzerOption &OptionField, StringRef Name,
1224 unsigned DefaultVal) {
1225 auto Parsed = PositiveAnalyzerOption::create(
1226 Str: getStringOption(Config, OptionName: Name, DefaultVal: std::to_string(val: DefaultVal)));
1227 if (Parsed.has_value()) {
1228 OptionField = Parsed.value();
1229 return;
1230 }
1231 if (Diags && !Parsed.has_value())
1232 Diags->Report(DiagID: diag::err_analyzer_config_invalid_input)
1233 << Name << "a positive";
1234
1235 OptionField = DefaultVal;
1236}
1237
1238static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts,
1239 DiagnosticsEngine *Diags) {
1240 // TODO: There's no need to store the entire configtable, it'd be plenty
1241 // enough to store checker options.
1242
1243#define ANALYZER_OPTION(TYPE, NAME, CMDFLAG, DESC, DEFAULT_VAL) \
1244 initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, DEFAULT_VAL);
1245#define ANALYZER_OPTION_DEPENDS_ON_USER_MODE(...)
1246#include "clang/StaticAnalyzer/Core/AnalyzerOptions.def"
1247
1248 assert(AnOpts.UserMode == "shallow" || AnOpts.UserMode == "deep");
1249 const bool InShallowMode = AnOpts.UserMode == "shallow";
1250
1251#define ANALYZER_OPTION(...)
1252#define ANALYZER_OPTION_DEPENDS_ON_USER_MODE(TYPE, NAME, CMDFLAG, DESC, \
1253 SHALLOW_VAL, DEEP_VAL) \
1254 initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, \
1255 InShallowMode ? SHALLOW_VAL : DEEP_VAL);
1256#include "clang/StaticAnalyzer/Core/AnalyzerOptions.def"
1257
1258 // At this point, AnalyzerOptions is configured. Let's validate some options.
1259
1260 // FIXME: Here we try to validate the silenced checkers or packages are valid.
1261 // The current approach only validates the registered checkers which does not
1262 // contain the runtime enabled checkers and optimally we would validate both.
1263 if (!AnOpts.RawSilencedCheckersAndPackages.empty()) {
1264 std::vector<StringRef> Checkers =
1265 AnOpts.getRegisteredCheckers(/*IncludeExperimental=*/true);
1266 std::vector<StringRef> Packages =
1267 AnOpts.getRegisteredPackages(/*IncludeExperimental=*/true);
1268
1269 SmallVector<StringRef, 16> CheckersAndPackages;
1270 AnOpts.RawSilencedCheckersAndPackages.split(A&: CheckersAndPackages, Separator: ";");
1271
1272 for (const StringRef &CheckerOrPackage : CheckersAndPackages) {
1273 if (Diags) {
1274 bool IsChecker = CheckerOrPackage.contains(C: '.');
1275 bool IsValidName = IsChecker
1276 ? llvm::is_contained(Range&: Checkers, Element: CheckerOrPackage)
1277 : llvm::is_contained(Range&: Packages, Element: CheckerOrPackage);
1278
1279 if (!IsValidName)
1280 Diags->Report(DiagID: diag::err_unknown_analyzer_checker_or_package)
1281 << CheckerOrPackage;
1282 }
1283
1284 AnOpts.SilencedCheckersAndPackages.emplace_back(args: CheckerOrPackage);
1285 }
1286 }
1287
1288 if (!Diags)
1289 return;
1290
1291 if (AnOpts.ShouldTrackConditionsDebug && !AnOpts.ShouldTrackConditions)
1292 Diags->Report(DiagID: diag::err_analyzer_config_invalid_input)
1293 << "track-conditions-debug" << "'track-conditions' to also be enabled";
1294}
1295
1296/// Generate a remark argument. This is an inverse of `ParseOptimizationRemark`.
1297static void
1298GenerateOptimizationRemark(ArgumentConsumer Consumer, OptSpecifier OptEQ,
1299 StringRef Name,
1300 const CodeGenOptions::OptRemark &Remark) {
1301 if (Remark.hasValidPattern()) {
1302 GenerateArg(Consumer, OptSpecifier: OptEQ, Value: Remark.Pattern);
1303 } else if (Remark.Kind == CodeGenOptions::RK_Enabled) {
1304 GenerateArg(Consumer, OptSpecifier: OPT_R_Joined, Value: Name);
1305 } else if (Remark.Kind == CodeGenOptions::RK_Disabled) {
1306 GenerateArg(Consumer, OptSpecifier: OPT_R_Joined, Value: StringRef("no-") + Name);
1307 }
1308}
1309
1310/// Parse a remark command line argument. It may be missing, disabled/enabled by
1311/// '-R[no-]group' or specified with a regular expression by '-Rgroup=regexp'.
1312/// On top of that, it can be disabled/enabled globally by '-R[no-]everything'.
1313static CodeGenOptions::OptRemark
1314ParseOptimizationRemark(DiagnosticsEngine &Diags, ArgList &Args,
1315 OptSpecifier OptEQ, StringRef Name) {
1316 CodeGenOptions::OptRemark Result;
1317
1318 auto InitializeResultPattern = [&Diags, &Args, &Result](const Arg *A,
1319 StringRef Pattern) {
1320 Result.Pattern = Pattern.str();
1321
1322 std::string RegexError;
1323 Result.Regex = std::make_shared<llvm::Regex>(args&: Result.Pattern);
1324 if (!Result.Regex->isValid(Error&: RegexError)) {
1325 Diags.Report(DiagID: diag::err_drv_optimization_remark_pattern)
1326 << RegexError << A->getAsString(Args);
1327 return false;
1328 }
1329
1330 return true;
1331 };
1332
1333 for (Arg *A : Args) {
1334 if (A->getOption().matches(ID: OPT_R_Joined)) {
1335 StringRef Value = A->getValue();
1336
1337 if (Value == Name)
1338 Result.Kind = CodeGenOptions::RK_Enabled;
1339 else if (Value == "everything")
1340 Result.Kind = CodeGenOptions::RK_EnabledEverything;
1341 else if (Value.split(Separator: '-') == std::make_pair(x: StringRef("no"), y&: Name))
1342 Result.Kind = CodeGenOptions::RK_Disabled;
1343 else if (Value == "no-everything")
1344 Result.Kind = CodeGenOptions::RK_DisabledEverything;
1345 else
1346 continue;
1347
1348 if (Result.Kind == CodeGenOptions::RK_Disabled ||
1349 Result.Kind == CodeGenOptions::RK_DisabledEverything) {
1350 Result.Pattern = "";
1351 Result.Regex = nullptr;
1352 } else {
1353 InitializeResultPattern(A, ".*");
1354 }
1355 } else if (A->getOption().matches(ID: OptEQ)) {
1356 Result.Kind = CodeGenOptions::RK_WithPattern;
1357 if (!InitializeResultPattern(A, A->getValue()))
1358 return CodeGenOptions::OptRemark();
1359 }
1360 }
1361
1362 return Result;
1363}
1364
1365static bool parseDiagnosticLevelMask(StringRef FlagName,
1366 const std::vector<std::string> &Levels,
1367 DiagnosticsEngine &Diags,
1368 DiagnosticLevelMask &M) {
1369 bool Success = true;
1370 for (const auto &Level : Levels) {
1371 DiagnosticLevelMask const PM =
1372 llvm::StringSwitch<DiagnosticLevelMask>(Level)
1373 .Case(S: "note", Value: DiagnosticLevelMask::Note)
1374 .Case(S: "remark", Value: DiagnosticLevelMask::Remark)
1375 .Case(S: "warning", Value: DiagnosticLevelMask::Warning)
1376 .Case(S: "error", Value: DiagnosticLevelMask::Error)
1377 .Default(Value: DiagnosticLevelMask::None);
1378 if (PM == DiagnosticLevelMask::None) {
1379 Success = false;
1380 Diags.Report(DiagID: diag::err_drv_invalid_value) << FlagName << Level;
1381 }
1382 M = M | PM;
1383 }
1384 return Success;
1385}
1386
1387static void parseSanitizerKinds(StringRef FlagName,
1388 const std::vector<std::string> &Sanitizers,
1389 DiagnosticsEngine &Diags, SanitizerSet &S) {
1390 for (const auto &Sanitizer : Sanitizers) {
1391 SanitizerMask K = parseSanitizerValue(Value: Sanitizer, /*AllowGroups=*/false);
1392 if (K == SanitizerMask())
1393 Diags.Report(DiagID: diag::err_drv_invalid_value) << FlagName << Sanitizer;
1394 else
1395 S.set(K, Value: true);
1396 }
1397}
1398
1399static SmallVector<StringRef, 4> serializeSanitizerKinds(SanitizerSet S) {
1400 SmallVector<StringRef, 4> Values;
1401 serializeSanitizerSet(Set: S, Values);
1402 return Values;
1403}
1404
1405static SanitizerMaskCutoffs
1406parseSanitizerWeightedKinds(StringRef FlagName,
1407 const std::vector<std::string> &Sanitizers,
1408 DiagnosticsEngine &Diags) {
1409 SanitizerMaskCutoffs Cutoffs;
1410 for (const auto &Sanitizer : Sanitizers) {
1411 if (!parseSanitizerWeightedValue(Value: Sanitizer, /*AllowGroups=*/false, Cutoffs))
1412 Diags.Report(DiagID: diag::err_drv_invalid_value) << FlagName << Sanitizer;
1413 }
1414 return Cutoffs;
1415}
1416
1417static void parseXRayInstrumentationBundle(StringRef FlagName, StringRef Bundle,
1418 ArgList &Args, DiagnosticsEngine &D,
1419 XRayInstrSet &S) {
1420 llvm::SmallVector<StringRef, 2> BundleParts;
1421 llvm::SplitString(Source: Bundle, OutFragments&: BundleParts, Delimiters: ",");
1422 for (const auto &B : BundleParts) {
1423 auto Mask = parseXRayInstrValue(Value: B);
1424 if (Mask == XRayInstrKind::None)
1425 if (B != "none")
1426 D.Report(DiagID: diag::err_drv_invalid_value) << FlagName << Bundle;
1427 else
1428 S.Mask = Mask;
1429 else if (Mask == XRayInstrKind::All)
1430 S.Mask = Mask;
1431 else
1432 S.set(K: Mask, Value: true);
1433 }
1434}
1435
1436static std::string serializeXRayInstrumentationBundle(const XRayInstrSet &S) {
1437 llvm::SmallVector<StringRef, 2> BundleParts;
1438 serializeXRayInstrValue(Set: S, Values&: BundleParts);
1439 std::string Buffer;
1440 llvm::raw_string_ostream OS(Buffer);
1441 llvm::interleave(c: BundleParts, os&: OS, each_fn: [&OS](StringRef Part) { OS << Part; }, separator: ",");
1442 return Buffer;
1443}
1444
1445void CompilerInvocation::setDefaultPointerAuthOptions(
1446 PointerAuthOptions &Opts, const LangOptions &LangOpts,
1447 const llvm::Triple &Triple) {
1448 assert(Triple.getArch() == llvm::Triple::aarch64);
1449 if (LangOpts.PointerAuthCalls) {
1450 using Key = PointerAuthSchema::ARM8_3Key;
1451 using Discrimination = PointerAuthSchema::Discrimination;
1452 // If you change anything here, be sure to update <ptrauth.h>.
1453 Opts.FunctionPointers = PointerAuthSchema(
1454 Key::ASIA, false,
1455 LangOpts.PointerAuthFunctionTypeDiscrimination ? Discrimination::Type
1456 : Discrimination::None);
1457
1458 Opts.CXXVTablePointers = PointerAuthSchema(
1459 Key::ASDA, LangOpts.PointerAuthVTPtrAddressDiscrimination,
1460 LangOpts.PointerAuthVTPtrTypeDiscrimination ? Discrimination::Type
1461 : Discrimination::None);
1462
1463 if (LangOpts.PointerAuthTypeInfoVTPtrDiscrimination)
1464 Opts.CXXTypeInfoVTablePointer =
1465 PointerAuthSchema(Key::ASDA, true, Discrimination::Constant,
1466 StdTypeInfoVTablePointerConstantDiscrimination);
1467 else
1468 Opts.CXXTypeInfoVTablePointer =
1469 PointerAuthSchema(Key::ASDA, false, Discrimination::None);
1470
1471 Opts.CXXVTTVTablePointers =
1472 PointerAuthSchema(Key::ASDA, false, Discrimination::None);
1473 Opts.CXXVirtualFunctionPointers = Opts.CXXVirtualVariadicFunctionPointers =
1474 PointerAuthSchema(Key::ASIA, true, Discrimination::Decl);
1475 Opts.CXXMemberFunctionPointers =
1476 PointerAuthSchema(Key::ASIA, false, Discrimination::Type);
1477
1478 if (LangOpts.PointerAuthInitFini) {
1479 Opts.InitFiniPointers = PointerAuthSchema(
1480 Key::ASIA, LangOpts.PointerAuthInitFiniAddressDiscrimination,
1481 Discrimination::Constant, InitFiniPointerConstantDiscriminator);
1482 }
1483
1484 Opts.BlockInvocationFunctionPointers =
1485 PointerAuthSchema(Key::ASIA, true, Discrimination::None);
1486 Opts.BlockHelperFunctionPointers =
1487 PointerAuthSchema(Key::ASIA, true, Discrimination::None);
1488 Opts.BlockByrefHelperFunctionPointers =
1489 PointerAuthSchema(Key::ASIA, true, Discrimination::None);
1490 if (LangOpts.PointerAuthBlockDescriptorPointers)
1491 Opts.BlockDescriptorPointers =
1492 PointerAuthSchema(Key::ASDA, true, Discrimination::Constant,
1493 BlockDescriptorConstantDiscriminator);
1494
1495 Opts.ObjCMethodListFunctionPointers =
1496 PointerAuthSchema(Key::ASIA, true, Discrimination::None);
1497 Opts.ObjCMethodListPointer =
1498 PointerAuthSchema(Key::ASDA, true, Discrimination::Constant,
1499 MethodListPointerConstantDiscriminator);
1500 if (LangOpts.PointerAuthObjcIsa) {
1501 Opts.ObjCIsaPointers =
1502 PointerAuthSchema(Key::ASDA, true, Discrimination::Constant,
1503 IsaPointerConstantDiscriminator);
1504 Opts.ObjCSuperPointers =
1505 PointerAuthSchema(Key::ASDA, true, Discrimination::Constant,
1506 SuperPointerConstantDiscriminator);
1507 }
1508
1509 if (LangOpts.PointerAuthObjcClassROPointers)
1510 Opts.ObjCClassROPointers =
1511 PointerAuthSchema(Key::ASDA, true, Discrimination::Constant,
1512 ClassROConstantDiscriminator);
1513 }
1514 Opts.ReturnAddresses = LangOpts.PointerAuthReturns;
1515 Opts.AuthTraps = LangOpts.PointerAuthAuthTraps;
1516 Opts.IndirectGotos = LangOpts.PointerAuthIndirectGotos;
1517 Opts.AArch64JumpTableHardening = LangOpts.AArch64JumpTableHardening;
1518}
1519
1520static void parsePointerAuthOptions(PointerAuthOptions &Opts,
1521 const LangOptions &LangOpts,
1522 const llvm::Triple &Triple,
1523 DiagnosticsEngine &Diags) {
1524 if (!LangOpts.PointerAuthCalls && !LangOpts.PointerAuthReturns &&
1525 !LangOpts.PointerAuthAuthTraps && !LangOpts.PointerAuthIndirectGotos &&
1526 !LangOpts.AArch64JumpTableHardening)
1527 return;
1528
1529 CompilerInvocation::setDefaultPointerAuthOptions(Opts, LangOpts, Triple);
1530}
1531
1532void CompilerInvocationBase::GenerateCodeGenArgs(const CodeGenOptions &Opts,
1533 ArgumentConsumer Consumer,
1534 const llvm::Triple &T,
1535 const std::string &OutputFile,
1536 const LangOptions *LangOpts) {
1537 const CodeGenOptions &CodeGenOpts = Opts;
1538
1539 if (Opts.OptimizationLevel == 0)
1540 GenerateArg(Consumer, OptSpecifier: OPT_O0);
1541 else
1542 GenerateArg(Consumer, OptSpecifier: OPT_O, Value: Twine(Opts.OptimizationLevel));
1543
1544#define CODEGEN_OPTION_WITH_MARSHALLING(...) \
1545 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
1546#include "clang/Options/Options.inc"
1547#undef CODEGEN_OPTION_WITH_MARSHALLING
1548
1549 if (Opts.OptimizationLevel > 0) {
1550 if (Opts.Inlining == CodeGenOptions::NormalInlining)
1551 GenerateArg(Consumer, OptSpecifier: OPT_finline_functions);
1552 else if (Opts.Inlining == CodeGenOptions::OnlyHintInlining)
1553 GenerateArg(Consumer, OptSpecifier: OPT_finline_hint_functions);
1554 else if (Opts.Inlining == CodeGenOptions::OnlyAlwaysInlining)
1555 GenerateArg(Consumer, OptSpecifier: OPT_fno_inline);
1556 }
1557
1558 if (Opts.DirectAccessExternalData && LangOpts->PICLevel != 0)
1559 GenerateArg(Consumer, OptSpecifier: OPT_fdirect_access_external_data);
1560 else if (!Opts.DirectAccessExternalData && LangOpts->PICLevel == 0)
1561 GenerateArg(Consumer, OptSpecifier: OPT_fno_direct_access_external_data);
1562
1563 std::optional<StringRef> DebugInfoVal;
1564 switch (Opts.DebugInfo) {
1565 case llvm::codegenoptions::DebugLineTablesOnly:
1566 DebugInfoVal = "line-tables-only";
1567 break;
1568 case llvm::codegenoptions::DebugDirectivesOnly:
1569 DebugInfoVal = "line-directives-only";
1570 break;
1571 case llvm::codegenoptions::DebugInfoConstructor:
1572 DebugInfoVal = "constructor";
1573 break;
1574 case llvm::codegenoptions::LimitedDebugInfo:
1575 DebugInfoVal = "limited";
1576 break;
1577 case llvm::codegenoptions::FullDebugInfo:
1578 DebugInfoVal = "standalone";
1579 break;
1580 case llvm::codegenoptions::UnusedTypeInfo:
1581 DebugInfoVal = "unused-types";
1582 break;
1583 case llvm::codegenoptions::NoDebugInfo: // default value
1584 DebugInfoVal = std::nullopt;
1585 break;
1586 case llvm::codegenoptions::LocTrackingOnly: // implied value
1587 DebugInfoVal = std::nullopt;
1588 break;
1589 }
1590 if (DebugInfoVal)
1591 GenerateArg(Consumer, OptSpecifier: OPT_debug_info_kind_EQ, Value: *DebugInfoVal);
1592
1593 for (const auto &Prefix : Opts.DebugPrefixMap)
1594 GenerateArg(Consumer, OptSpecifier: OPT_fdebug_prefix_map_EQ,
1595 Value: Prefix.first + "=" + Prefix.second);
1596
1597 for (const auto &Prefix : Opts.CoveragePrefixMap)
1598 GenerateArg(Consumer, OptSpecifier: OPT_fcoverage_prefix_map_EQ,
1599 Value: Prefix.first + "=" + Prefix.second);
1600
1601 if (Opts.NewStructPathTBAA)
1602 GenerateArg(Consumer, OptSpecifier: OPT_new_struct_path_tbaa);
1603
1604 if (Opts.OptimizeSize == 1)
1605 GenerateArg(Consumer, OptSpecifier: OPT_O, Value: "s");
1606 else if (Opts.OptimizeSize == 2)
1607 GenerateArg(Consumer, OptSpecifier: OPT_O, Value: "z");
1608
1609 // SimplifyLibCalls is set only in the absence of -fno-builtin and
1610 // -ffreestanding. We'll consider that when generating them.
1611
1612 // NoBuiltinFuncs are generated by LangOptions.
1613
1614 if (Opts.UnrollLoops && Opts.OptimizationLevel <= 1)
1615 GenerateArg(Consumer, OptSpecifier: OPT_funroll_loops);
1616 else if (!Opts.UnrollLoops && Opts.OptimizationLevel > 1)
1617 GenerateArg(Consumer, OptSpecifier: OPT_fno_unroll_loops);
1618
1619 if (Opts.InterchangeLoops)
1620 GenerateArg(Consumer, OptSpecifier: OPT_floop_interchange);
1621 else
1622 GenerateArg(Consumer, OptSpecifier: OPT_fno_loop_interchange);
1623
1624 if (Opts.FuseLoops)
1625 GenerateArg(Consumer, OptSpecifier: OPT_fexperimental_loop_fusion);
1626
1627 if (!Opts.BinutilsVersion.empty())
1628 GenerateArg(Consumer, OptSpecifier: OPT_fbinutils_version_EQ, Value: Opts.BinutilsVersion);
1629
1630 if (Opts.DebugNameTable ==
1631 static_cast<unsigned>(llvm::DICompileUnit::DebugNameTableKind::GNU))
1632 GenerateArg(Consumer, OptSpecifier: OPT_ggnu_pubnames);
1633 else if (Opts.DebugNameTable ==
1634 static_cast<unsigned>(
1635 llvm::DICompileUnit::DebugNameTableKind::Default))
1636 GenerateArg(Consumer, OptSpecifier: OPT_gpubnames);
1637
1638 if (Opts.DebugTemplateAlias)
1639 GenerateArg(Consumer, OptSpecifier: OPT_gtemplate_alias);
1640
1641 auto TNK = Opts.getDebugSimpleTemplateNames();
1642 if (TNK != llvm::codegenoptions::DebugTemplateNamesKind::Full) {
1643 if (TNK == llvm::codegenoptions::DebugTemplateNamesKind::Simple)
1644 GenerateArg(Consumer, OptSpecifier: OPT_gsimple_template_names_EQ, Value: "simple");
1645 else if (TNK == llvm::codegenoptions::DebugTemplateNamesKind::Mangled)
1646 GenerateArg(Consumer, OptSpecifier: OPT_gsimple_template_names_EQ, Value: "mangled");
1647 }
1648 // ProfileInstrumentUsePath is marshalled automatically, no need to generate
1649 // it or PGOUseInstrumentor.
1650
1651 if (Opts.TimePasses) {
1652 if (Opts.TimePassesPerRun)
1653 GenerateArg(Consumer, OptSpecifier: OPT_ftime_report_EQ, Value: "per-pass-run");
1654 else
1655 GenerateArg(Consumer, OptSpecifier: OPT_ftime_report);
1656
1657 if (Opts.TimePassesJson)
1658 GenerateArg(Consumer, OptSpecifier: OPT_ftime_report_json);
1659 }
1660
1661 if (Opts.PrepareForLTO && !Opts.PrepareForThinLTO)
1662 GenerateArg(Consumer, OptSpecifier: OPT_flto_EQ, Value: "full");
1663
1664 if (Opts.PrepareForThinLTO)
1665 GenerateArg(Consumer, OptSpecifier: OPT_flto_EQ, Value: "thin");
1666
1667 if (!Opts.ThinLTOIndexFile.empty())
1668 GenerateArg(Consumer, OptSpecifier: OPT_fthinlto_index_EQ, Value: Opts.ThinLTOIndexFile);
1669
1670 if (Opts.SaveTempsFilePrefix == OutputFile)
1671 GenerateArg(Consumer, OptSpecifier: OPT_save_temps_EQ, Value: "obj");
1672
1673 StringRef MemProfileBasename("memprof.profraw");
1674 if (!Opts.MemoryProfileOutput.empty()) {
1675 if (Opts.MemoryProfileOutput == MemProfileBasename) {
1676 GenerateArg(Consumer, OptSpecifier: OPT_fmemory_profile);
1677 } else {
1678 size_t ArgLength =
1679 Opts.MemoryProfileOutput.size() - MemProfileBasename.size();
1680 GenerateArg(Consumer, OptSpecifier: OPT_fmemory_profile_EQ,
1681 Value: Opts.MemoryProfileOutput.substr(pos: 0, n: ArgLength));
1682 }
1683 }
1684
1685 if (memcmp(s1: Opts.CoverageVersion, s2: "0000", n: 4))
1686 GenerateArg(Consumer, OptSpecifier: OPT_coverage_version_EQ,
1687 Value: StringRef(Opts.CoverageVersion, 4));
1688
1689 // TODO: Check if we need to generate arguments stored in CmdArgs. (Namely
1690 // '-fembed_bitcode', which does not map to any CompilerInvocation field and
1691 // won't be generated.)
1692
1693 if (Opts.XRayInstrumentationBundle.Mask != XRayInstrKind::All) {
1694 std::string InstrBundle =
1695 serializeXRayInstrumentationBundle(S: Opts.XRayInstrumentationBundle);
1696 if (!InstrBundle.empty())
1697 GenerateArg(Consumer, OptSpecifier: OPT_fxray_instrumentation_bundle, Value: InstrBundle);
1698 }
1699
1700 if (Opts.CFProtectionReturn && Opts.CFProtectionBranch)
1701 GenerateArg(Consumer, OptSpecifier: OPT_fcf_protection_EQ, Value: "full");
1702 else if (Opts.CFProtectionReturn)
1703 GenerateArg(Consumer, OptSpecifier: OPT_fcf_protection_EQ, Value: "return");
1704 else if (Opts.CFProtectionBranch)
1705 GenerateArg(Consumer, OptSpecifier: OPT_fcf_protection_EQ, Value: "branch");
1706
1707 if (Opts.CFProtectionBranch) {
1708 switch (Opts.getCFBranchLabelScheme()) {
1709 case CFBranchLabelSchemeKind::Default:
1710 break;
1711#define CF_BRANCH_LABEL_SCHEME(Kind, FlagVal) \
1712 case CFBranchLabelSchemeKind::Kind: \
1713 GenerateArg(Consumer, OPT_mcf_branch_label_scheme_EQ, #FlagVal); \
1714 break;
1715#include "clang/Basic/CFProtectionOptions.def"
1716 }
1717 }
1718
1719 if (Opts.FunctionReturnThunks)
1720 GenerateArg(Consumer, OptSpecifier: OPT_mfunction_return_EQ, Value: "thunk-extern");
1721
1722 for (const auto &F : Opts.LinkBitcodeFiles) {
1723 bool Builtint = F.LinkFlags == llvm::Linker::Flags::LinkOnlyNeeded &&
1724 F.PropagateAttrs && F.Internalize;
1725 GenerateArg(Consumer,
1726 OptSpecifier: Builtint ? OPT_mlink_builtin_bitcode : OPT_mlink_bitcode_file,
1727 Value: F.Filename);
1728 }
1729
1730 if (Opts.EmulatedTLS)
1731 GenerateArg(Consumer, OptSpecifier: OPT_femulated_tls);
1732
1733 if (Opts.FPDenormalMode != llvm::DenormalMode::getIEEE())
1734 GenerateArg(Consumer, OptSpecifier: OPT_fdenormal_fp_math_EQ, Value: Opts.FPDenormalMode.str());
1735
1736 if ((Opts.FPDenormalMode != Opts.FP32DenormalMode) ||
1737 (Opts.FP32DenormalMode != llvm::DenormalMode::getIEEE()))
1738 GenerateArg(Consumer, OptSpecifier: OPT_fdenormal_fp_math_f32_EQ,
1739 Value: Opts.FP32DenormalMode.str());
1740
1741 if (Opts.StructReturnConvention == CodeGenOptions::SRCK_OnStack) {
1742 OptSpecifier Opt =
1743 T.isPPC32() ? OPT_maix_struct_return : OPT_fpcc_struct_return;
1744 GenerateArg(Consumer, OptSpecifier: Opt);
1745 } else if (Opts.StructReturnConvention == CodeGenOptions::SRCK_InRegs) {
1746 OptSpecifier Opt =
1747 T.isPPC32() ? OPT_msvr4_struct_return : OPT_freg_struct_return;
1748 GenerateArg(Consumer, OptSpecifier: Opt);
1749 }
1750
1751 if (Opts.EnableAIXExtendedAltivecABI)
1752 GenerateArg(Consumer, OptSpecifier: OPT_mabi_EQ_vec_extabi);
1753
1754 if (Opts.XCOFFReadOnlyPointers)
1755 GenerateArg(Consumer, OptSpecifier: OPT_mxcoff_roptr);
1756
1757 if (!Opts.OptRecordPasses.empty())
1758 GenerateArg(Consumer, OptSpecifier: OPT_opt_record_passes, Value: Opts.OptRecordPasses);
1759
1760 if (!Opts.OptRecordFormat.empty())
1761 GenerateArg(Consumer, OptSpecifier: OPT_opt_record_format, Value: Opts.OptRecordFormat);
1762
1763 GenerateOptimizationRemark(Consumer, OptEQ: OPT_Rpass_EQ, Name: "pass",
1764 Remark: Opts.OptimizationRemark);
1765
1766 GenerateOptimizationRemark(Consumer, OptEQ: OPT_Rpass_missed_EQ, Name: "pass-missed",
1767 Remark: Opts.OptimizationRemarkMissed);
1768
1769 GenerateOptimizationRemark(Consumer, OptEQ: OPT_Rpass_analysis_EQ, Name: "pass-analysis",
1770 Remark: Opts.OptimizationRemarkAnalysis);
1771
1772 GenerateArg(Consumer, OptSpecifier: OPT_fdiagnostics_hotness_threshold_EQ,
1773 Value: Opts.DiagnosticsHotnessThreshold
1774 ? Twine(*Opts.DiagnosticsHotnessThreshold)
1775 : "auto");
1776
1777 GenerateArg(Consumer, OptSpecifier: OPT_fdiagnostics_misexpect_tolerance_EQ,
1778 Value: Twine(*Opts.DiagnosticsMisExpectTolerance));
1779
1780 for (StringRef Sanitizer : serializeSanitizerKinds(S: Opts.SanitizeRecover))
1781 GenerateArg(Consumer, OptSpecifier: OPT_fsanitize_recover_EQ, Value: Sanitizer);
1782
1783 for (StringRef Sanitizer : serializeSanitizerKinds(S: Opts.SanitizeTrap))
1784 GenerateArg(Consumer, OptSpecifier: OPT_fsanitize_trap_EQ, Value: Sanitizer);
1785
1786 for (StringRef Sanitizer :
1787 serializeSanitizerKinds(S: Opts.SanitizeMergeHandlers))
1788 GenerateArg(Consumer, OptSpecifier: OPT_fsanitize_merge_handlers_EQ, Value: Sanitizer);
1789
1790 SmallVector<std::string, 4> Values;
1791 serializeSanitizerMaskCutoffs(Cutoffs: Opts.SanitizeSkipHotCutoffs, Values);
1792 for (std::string Sanitizer : Values)
1793 GenerateArg(Consumer, OptSpecifier: OPT_fsanitize_skip_hot_cutoff_EQ, Value: Sanitizer);
1794
1795 if (Opts.AllowRuntimeCheckSkipHotCutoff) {
1796 GenerateArg(Consumer, OptSpecifier: OPT_fallow_runtime_check_skip_hot_cutoff_EQ,
1797 Value: std::to_string(val: *Opts.AllowRuntimeCheckSkipHotCutoff));
1798 }
1799
1800 for (StringRef Sanitizer :
1801 serializeSanitizerKinds(S: Opts.SanitizeAnnotateDebugInfo))
1802 GenerateArg(Consumer, OptSpecifier: OPT_fsanitize_annotate_debug_info_EQ, Value: Sanitizer);
1803
1804 if (!Opts.EmitVersionIdentMetadata)
1805 GenerateArg(Consumer, OptSpecifier: OPT_Qn);
1806
1807 switch (Opts.FiniteLoops) {
1808 case CodeGenOptions::FiniteLoopsKind::Language:
1809 break;
1810 case CodeGenOptions::FiniteLoopsKind::Always:
1811 GenerateArg(Consumer, OptSpecifier: OPT_ffinite_loops);
1812 break;
1813 case CodeGenOptions::FiniteLoopsKind::Never:
1814 GenerateArg(Consumer, OptSpecifier: OPT_fno_finite_loops);
1815 break;
1816 }
1817
1818 if (Opts.StaticClosure)
1819 GenerateArg(Consumer, OptSpecifier: OPT_static_libclosure);
1820}
1821
1822bool CompilerInvocation::ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args,
1823 InputKind IK,
1824 DiagnosticsEngine &Diags,
1825 const llvm::Triple &T,
1826 const std::string &OutputFile,
1827 const LangOptions &LangOptsRef) {
1828 unsigned NumErrorsBefore = Diags.getNumErrors();
1829
1830 Opts.OptimizationLevel = getOptimizationLevel(Args, IK, Diags);
1831
1832 // The key paths of codegen options defined in Options.td start with
1833 // "CodeGenOpts.". Let's provide the expected variable name and type.
1834 CodeGenOptions &CodeGenOpts = Opts;
1835 // Some codegen options depend on language options. Let's provide the expected
1836 // variable name and type.
1837 const LangOptions *LangOpts = &LangOptsRef;
1838
1839#define CODEGEN_OPTION_WITH_MARSHALLING(...) \
1840 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
1841#include "clang/Options/Options.inc"
1842#undef CODEGEN_OPTION_WITH_MARSHALLING
1843
1844 // At O0 we want to fully disable inlining outside of cases marked with
1845 // 'alwaysinline' that are required for correctness.
1846 if (Opts.OptimizationLevel == 0) {
1847 Opts.setInlining(CodeGenOptions::OnlyAlwaysInlining);
1848 } else if (const Arg *A = Args.getLastArg(Ids: options::OPT_finline_functions,
1849 Ids: options::OPT_finline_hint_functions,
1850 Ids: options::OPT_fno_inline_functions,
1851 Ids: options::OPT_fno_inline)) {
1852 // Explicit inlining flags can disable some or all inlining even at
1853 // optimization levels above zero.
1854 if (A->getOption().matches(ID: options::OPT_finline_functions))
1855 Opts.setInlining(CodeGenOptions::NormalInlining);
1856 else if (A->getOption().matches(ID: options::OPT_finline_hint_functions))
1857 Opts.setInlining(CodeGenOptions::OnlyHintInlining);
1858 else
1859 Opts.setInlining(CodeGenOptions::OnlyAlwaysInlining);
1860 } else {
1861 Opts.setInlining(CodeGenOptions::NormalInlining);
1862 }
1863
1864 // PIC defaults to -fno-direct-access-external-data while non-PIC defaults to
1865 // -fdirect-access-external-data.
1866 Opts.DirectAccessExternalData =
1867 Args.hasArg(Ids: OPT_fdirect_access_external_data) ||
1868 (!Args.hasArg(Ids: OPT_fno_direct_access_external_data) &&
1869 LangOpts->PICLevel == 0);
1870
1871 if (Arg *A = Args.getLastArg(Ids: OPT_debug_info_kind_EQ)) {
1872 unsigned Val =
1873 llvm::StringSwitch<unsigned>(A->getValue())
1874 .Case(S: "line-tables-only", Value: llvm::codegenoptions::DebugLineTablesOnly)
1875 .Case(S: "line-directives-only",
1876 Value: llvm::codegenoptions::DebugDirectivesOnly)
1877 .Case(S: "constructor", Value: llvm::codegenoptions::DebugInfoConstructor)
1878 .Case(S: "limited", Value: llvm::codegenoptions::LimitedDebugInfo)
1879 .Case(S: "standalone", Value: llvm::codegenoptions::FullDebugInfo)
1880 .Case(S: "unused-types", Value: llvm::codegenoptions::UnusedTypeInfo)
1881 .Default(Value: ~0U);
1882 if (Val == ~0U)
1883 Diags.Report(DiagID: diag::err_drv_invalid_value) << A->getAsString(Args)
1884 << A->getValue();
1885 else
1886 Opts.setDebugInfo(static_cast<llvm::codegenoptions::DebugInfoKind>(Val));
1887 }
1888
1889 // If -fuse-ctor-homing is set and limited debug info is already on, then use
1890 // constructor homing, and vice versa for -fno-use-ctor-homing.
1891 if (const Arg *A =
1892 Args.getLastArg(Ids: OPT_fuse_ctor_homing, Ids: OPT_fno_use_ctor_homing)) {
1893 if (A->getOption().matches(ID: OPT_fuse_ctor_homing) &&
1894 Opts.getDebugInfo() == llvm::codegenoptions::LimitedDebugInfo)
1895 Opts.setDebugInfo(llvm::codegenoptions::DebugInfoConstructor);
1896 if (A->getOption().matches(ID: OPT_fno_use_ctor_homing) &&
1897 Opts.getDebugInfo() == llvm::codegenoptions::DebugInfoConstructor)
1898 Opts.setDebugInfo(llvm::codegenoptions::LimitedDebugInfo);
1899 }
1900
1901 for (const auto &Arg : Args.getAllArgValues(Id: OPT_fdebug_prefix_map_EQ)) {
1902 auto Split = StringRef(Arg).split(Separator: '=');
1903 Opts.DebugPrefixMap.emplace_back(Args&: Split.first, Args&: Split.second);
1904 }
1905
1906 for (const auto &Arg : Args.getAllArgValues(Id: OPT_fcoverage_prefix_map_EQ)) {
1907 auto Split = StringRef(Arg).split(Separator: '=');
1908 Opts.CoveragePrefixMap.emplace_back(Args&: Split.first, Args&: Split.second);
1909 }
1910
1911 const llvm::Triple::ArchType DebugEntryValueArchs[] = {
1912 llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::aarch64,
1913 llvm::Triple::arm, llvm::Triple::armeb, llvm::Triple::mips,
1914 llvm::Triple::mipsel, llvm::Triple::mips64, llvm::Triple::mips64el,
1915 llvm::Triple::riscv32, llvm::Triple::riscv64};
1916
1917 if (Opts.OptimizationLevel > 0 && Opts.hasReducedDebugInfo() &&
1918 llvm::is_contained(Range: DebugEntryValueArchs, Element: T.getArch()))
1919 Opts.EmitCallSiteInfo = true;
1920
1921 if (!Opts.EnableDIPreservationVerify && Opts.DIBugsReportFilePath.size()) {
1922 Diags.Report(DiagID: diag::warn_ignoring_verify_debuginfo_preserve_export)
1923 << Opts.DIBugsReportFilePath;
1924 Opts.DIBugsReportFilePath = "";
1925 }
1926
1927 Opts.NewStructPathTBAA = !Args.hasArg(Ids: OPT_no_struct_path_tbaa) &&
1928 Args.hasArg(Ids: OPT_new_struct_path_tbaa);
1929 Opts.OptimizeSize = getOptimizationLevelSize(Args);
1930 Opts.SimplifyLibCalls = !LangOpts->NoBuiltin;
1931 if (Opts.SimplifyLibCalls)
1932 Opts.NoBuiltinFuncs = LangOpts->NoBuiltinFuncs;
1933 Opts.UnrollLoops =
1934 Args.hasFlag(Pos: OPT_funroll_loops, Neg: OPT_fno_unroll_loops,
1935 Default: (Opts.OptimizationLevel > 1));
1936 Opts.InterchangeLoops =
1937 Args.hasFlag(Pos: OPT_floop_interchange, Neg: OPT_fno_loop_interchange, Default: false);
1938 Opts.FuseLoops = Args.hasFlag(Pos: OPT_fexperimental_loop_fusion,
1939 Neg: OPT_fno_experimental_loop_fusion, Default: false);
1940 Opts.BinutilsVersion =
1941 std::string(Args.getLastArgValue(Id: OPT_fbinutils_version_EQ));
1942
1943 Opts.DebugTemplateAlias = Args.hasArg(Ids: OPT_gtemplate_alias);
1944
1945 Opts.DebugNameTable = static_cast<unsigned>(
1946 Args.hasArg(Ids: OPT_ggnu_pubnames)
1947 ? llvm::DICompileUnit::DebugNameTableKind::GNU
1948 : Args.hasArg(Ids: OPT_gpubnames)
1949 ? llvm::DICompileUnit::DebugNameTableKind::Default
1950 : llvm::DICompileUnit::DebugNameTableKind::None);
1951 if (const Arg *A = Args.getLastArg(Ids: OPT_gsimple_template_names_EQ)) {
1952 StringRef Value = A->getValue();
1953 if (Value != "simple" && Value != "mangled")
1954 Diags.Report(DiagID: diag::err_drv_unsupported_option_argument)
1955 << A->getSpelling() << A->getValue();
1956 Opts.setDebugSimpleTemplateNames(
1957 StringRef(A->getValue()) == "simple"
1958 ? llvm::codegenoptions::DebugTemplateNamesKind::Simple
1959 : llvm::codegenoptions::DebugTemplateNamesKind::Mangled);
1960 }
1961
1962 if (Args.hasArg(Ids: OPT_ftime_report, Ids: OPT_ftime_report_EQ, Ids: OPT_ftime_report_json,
1963 Ids: OPT_stats_file_timers)) {
1964 Opts.TimePasses = true;
1965
1966 // -ftime-report= is only for new pass manager.
1967 if (const Arg *EQ = Args.getLastArg(Ids: OPT_ftime_report_EQ)) {
1968 StringRef Val = EQ->getValue();
1969 if (Val == "per-pass")
1970 Opts.TimePassesPerRun = false;
1971 else if (Val == "per-pass-run")
1972 Opts.TimePassesPerRun = true;
1973 else
1974 Diags.Report(DiagID: diag::err_drv_invalid_value)
1975 << EQ->getAsString(Args) << EQ->getValue();
1976 }
1977
1978 if (Args.getLastArg(Ids: OPT_ftime_report_json))
1979 Opts.TimePassesJson = true;
1980 }
1981
1982 Opts.PrepareForLTO = false;
1983 Opts.PrepareForThinLTO = false;
1984 if (Arg *A = Args.getLastArg(Ids: OPT_flto_EQ)) {
1985 Opts.PrepareForLTO = true;
1986 StringRef S = A->getValue();
1987 if (S == "thin")
1988 Opts.PrepareForThinLTO = true;
1989 else if (S != "full")
1990 Diags.Report(DiagID: diag::err_drv_invalid_value) << A->getAsString(Args) << S;
1991 if (Args.hasArg(Ids: OPT_funified_lto))
1992 Opts.PrepareForThinLTO = true;
1993 }
1994 if (Arg *A = Args.getLastArg(Ids: OPT_fthinlto_index_EQ)) {
1995 if (IK.getLanguage() != Language::LLVM_IR)
1996 Diags.Report(DiagID: diag::err_drv_argument_only_allowed_with)
1997 << A->getAsString(Args) << "-x ir";
1998 Opts.ThinLTOIndexFile =
1999 std::string(Args.getLastArgValue(Id: OPT_fthinlto_index_EQ));
2000 }
2001 if (Arg *A = Args.getLastArg(Ids: OPT_save_temps_EQ))
2002 Opts.SaveTempsFilePrefix =
2003 llvm::StringSwitch<std::string>(A->getValue())
2004 .Case(S: "obj", Value: OutputFile)
2005 .Default(Value: llvm::sys::path::filename(path: OutputFile).str());
2006
2007 // The memory profile runtime appends the pid to make this name more unique.
2008 const char *MemProfileBasename = "memprof.profraw";
2009 if (Args.hasArg(Ids: OPT_fmemory_profile_EQ)) {
2010 SmallString<128> Path(Args.getLastArgValue(Id: OPT_fmemory_profile_EQ));
2011 llvm::sys::path::append(path&: Path, a: MemProfileBasename);
2012 Opts.MemoryProfileOutput = std::string(Path);
2013 } else if (Args.hasArg(Ids: OPT_fmemory_profile))
2014 Opts.MemoryProfileOutput = MemProfileBasename;
2015
2016 if (Opts.CoverageNotesFile.size() || Opts.CoverageDataFile.size()) {
2017 if (Args.hasArg(Ids: OPT_coverage_version_EQ)) {
2018 StringRef CoverageVersion = Args.getLastArgValue(Id: OPT_coverage_version_EQ);
2019 if (CoverageVersion.size() != 4) {
2020 Diags.Report(DiagID: diag::err_drv_invalid_value)
2021 << Args.getLastArg(Ids: OPT_coverage_version_EQ)->getAsString(Args)
2022 << CoverageVersion;
2023 } else {
2024 memcpy(dest: Opts.CoverageVersion, src: CoverageVersion.data(), n: 4);
2025 }
2026 }
2027 }
2028 // FIXME: For backend options that are not yet recorded as function
2029 // attributes in the IR, keep track of them so we can embed them in a
2030 // separate data section and use them when building the bitcode.
2031 for (const auto &A : Args) {
2032 // Do not encode output and input.
2033 if (A->getOption().getID() == options::OPT_o ||
2034 A->getOption().getID() == options::OPT_INPUT ||
2035 A->getOption().getID() == options::OPT_x ||
2036 A->getOption().getID() == options::OPT_fembed_bitcode ||
2037 A->getOption().matches(ID: options::OPT_W_Group))
2038 continue;
2039 ArgStringList ASL;
2040 A->render(Args, Output&: ASL);
2041 for (const auto &arg : ASL) {
2042 StringRef ArgStr(arg);
2043 llvm::append_range(C&: Opts.CmdArgs, R&: ArgStr);
2044 // using \00 to separate each commandline options.
2045 Opts.CmdArgs.push_back(x: '\0');
2046 }
2047 }
2048
2049 auto XRayInstrBundles =
2050 Args.getAllArgValues(Id: OPT_fxray_instrumentation_bundle);
2051 if (XRayInstrBundles.empty())
2052 Opts.XRayInstrumentationBundle.Mask = XRayInstrKind::All;
2053 else
2054 for (const auto &A : XRayInstrBundles)
2055 parseXRayInstrumentationBundle(FlagName: "-fxray-instrumentation-bundle=", Bundle: A, Args,
2056 D&: Diags, S&: Opts.XRayInstrumentationBundle);
2057
2058 if (const Arg *A = Args.getLastArg(Ids: OPT_fcf_protection_EQ)) {
2059 StringRef Name = A->getValue();
2060 if (Name == "full") {
2061 Opts.CFProtectionReturn = 1;
2062 Opts.CFProtectionBranch = 1;
2063 } else if (Name == "return")
2064 Opts.CFProtectionReturn = 1;
2065 else if (Name == "branch")
2066 Opts.CFProtectionBranch = 1;
2067 else if (Name != "none")
2068 Diags.Report(DiagID: diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
2069 }
2070
2071 if (Opts.CFProtectionBranch && T.isRISCV()) {
2072 if (const Arg *A = Args.getLastArg(Ids: OPT_mcf_branch_label_scheme_EQ)) {
2073 const auto Scheme =
2074 llvm::StringSwitch<CFBranchLabelSchemeKind>(A->getValue())
2075#define CF_BRANCH_LABEL_SCHEME(Kind, FlagVal) \
2076 .Case(#FlagVal, CFBranchLabelSchemeKind::Kind)
2077#include "clang/Basic/CFProtectionOptions.def"
2078 .Default(Value: CFBranchLabelSchemeKind::Default);
2079 if (Scheme != CFBranchLabelSchemeKind::Default)
2080 Opts.setCFBranchLabelScheme(Scheme);
2081 else
2082 Diags.Report(DiagID: diag::err_drv_invalid_value)
2083 << A->getAsString(Args) << A->getValue();
2084 }
2085 }
2086
2087 if (const Arg *A = Args.getLastArg(Ids: OPT_mfunction_return_EQ)) {
2088 auto Val = llvm::StringSwitch<llvm::FunctionReturnThunksKind>(A->getValue())
2089 .Case(S: "keep", Value: llvm::FunctionReturnThunksKind::Keep)
2090 .Case(S: "thunk-extern", Value: llvm::FunctionReturnThunksKind::Extern)
2091 .Default(Value: llvm::FunctionReturnThunksKind::Invalid);
2092 // SystemZ might want to add support for "expolines."
2093 if (!T.isX86())
2094 Diags.Report(DiagID: diag::err_drv_argument_not_allowed_with)
2095 << A->getSpelling() << T.getTriple();
2096 else if (Val == llvm::FunctionReturnThunksKind::Invalid)
2097 Diags.Report(DiagID: diag::err_drv_invalid_value)
2098 << A->getAsString(Args) << A->getValue();
2099 else if (Val == llvm::FunctionReturnThunksKind::Extern &&
2100 Args.getLastArgValue(Id: OPT_mcmodel_EQ) == "large")
2101 Diags.Report(DiagID: diag::err_drv_argument_not_allowed_with)
2102 << A->getAsString(Args)
2103 << Args.getLastArg(Ids: OPT_mcmodel_EQ)->getAsString(Args);
2104 else
2105 Opts.FunctionReturnThunks = static_cast<unsigned>(Val);
2106 }
2107
2108 for (auto *A :
2109 Args.filtered(Ids: OPT_mlink_bitcode_file, Ids: OPT_mlink_builtin_bitcode)) {
2110 CodeGenOptions::BitcodeFileToLink F;
2111 F.Filename = A->getValue();
2112 if (A->getOption().matches(ID: OPT_mlink_builtin_bitcode)) {
2113 F.LinkFlags = llvm::Linker::Flags::LinkOnlyNeeded;
2114 // When linking CUDA bitcode, propagate function attributes so that
2115 // e.g. libdevice gets fast-math attrs if we're building with fast-math.
2116 F.PropagateAttrs = true;
2117 F.Internalize = true;
2118 }
2119 Opts.LinkBitcodeFiles.push_back(x: F);
2120 }
2121
2122 if (Arg *A = Args.getLastArg(Ids: OPT_fdenormal_fp_math_EQ)) {
2123 StringRef Val = A->getValue();
2124 Opts.FPDenormalMode = llvm::parseDenormalFPAttribute(Str: Val);
2125 Opts.FP32DenormalMode = Opts.FPDenormalMode;
2126 if (!Opts.FPDenormalMode.isValid())
2127 Diags.Report(DiagID: diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
2128 }
2129
2130 if (Arg *A = Args.getLastArg(Ids: OPT_fdenormal_fp_math_f32_EQ)) {
2131 StringRef Val = A->getValue();
2132 Opts.FP32DenormalMode = llvm::parseDenormalFPAttribute(Str: Val);
2133 if (!Opts.FP32DenormalMode.isValid())
2134 Diags.Report(DiagID: diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
2135 }
2136
2137 // X86_32 has -fppc-struct-return and -freg-struct-return.
2138 // PPC32 has -maix-struct-return and -msvr4-struct-return.
2139 if (Arg *A =
2140 Args.getLastArg(Ids: OPT_fpcc_struct_return, Ids: OPT_freg_struct_return,
2141 Ids: OPT_maix_struct_return, Ids: OPT_msvr4_struct_return)) {
2142 // TODO: We might want to consider enabling these options on AIX in the
2143 // future.
2144 if (T.isOSAIX())
2145 Diags.Report(DiagID: diag::err_drv_unsupported_opt_for_target)
2146 << A->getSpelling() << T.str();
2147
2148 const Option &O = A->getOption();
2149 if (O.matches(ID: OPT_fpcc_struct_return) ||
2150 O.matches(ID: OPT_maix_struct_return)) {
2151 Opts.setStructReturnConvention(CodeGenOptions::SRCK_OnStack);
2152 } else {
2153 assert(O.matches(OPT_freg_struct_return) ||
2154 O.matches(OPT_msvr4_struct_return));
2155 Opts.setStructReturnConvention(CodeGenOptions::SRCK_InRegs);
2156 }
2157 }
2158
2159 if (Arg *A = Args.getLastArg(Ids: OPT_mxcoff_roptr)) {
2160 if (!T.isOSAIX())
2161 Diags.Report(DiagID: diag::err_drv_unsupported_opt_for_target)
2162 << A->getSpelling() << T.str();
2163
2164 // Since the storage mapping class is specified per csect,
2165 // without using data sections, it is less effective to use read-only
2166 // pointers. Using read-only pointers may cause other RO variables in the
2167 // same csect to become RW when the linker acts upon `-bforceimprw`;
2168 // therefore, we require that separate data sections
2169 // are used when `-mxcoff-roptr` is in effect. We respect the setting of
2170 // data-sections since we have not found reasons to do otherwise that
2171 // overcome the user surprise of not respecting the setting.
2172 if (!Args.hasFlag(Pos: OPT_fdata_sections, Neg: OPT_fno_data_sections, Default: false))
2173 Diags.Report(DiagID: diag::err_roptr_requires_data_sections);
2174
2175 Opts.XCOFFReadOnlyPointers = true;
2176 }
2177
2178 if (Arg *A = Args.getLastArg(Ids: OPT_mabi_EQ_quadword_atomics)) {
2179 if (!T.isOSAIX() || T.isPPC32())
2180 Diags.Report(DiagID: diag::err_drv_unsupported_opt_for_target)
2181 << A->getSpelling() << T.str();
2182 }
2183
2184 bool NeedLocTracking = false;
2185
2186 if (!Opts.OptRecordFile.empty())
2187 NeedLocTracking = true;
2188
2189 if (Arg *A = Args.getLastArg(Ids: OPT_opt_record_passes)) {
2190 Opts.OptRecordPasses = A->getValue();
2191 NeedLocTracking = true;
2192 }
2193
2194 if (Arg *A = Args.getLastArg(Ids: OPT_opt_record_format)) {
2195 Opts.OptRecordFormat = A->getValue();
2196 NeedLocTracking = true;
2197 }
2198
2199 Opts.OptimizationRemark =
2200 ParseOptimizationRemark(Diags, Args, OptEQ: OPT_Rpass_EQ, Name: "pass");
2201
2202 Opts.OptimizationRemarkMissed =
2203 ParseOptimizationRemark(Diags, Args, OptEQ: OPT_Rpass_missed_EQ, Name: "pass-missed");
2204
2205 Opts.OptimizationRemarkAnalysis = ParseOptimizationRemark(
2206 Diags, Args, OptEQ: OPT_Rpass_analysis_EQ, Name: "pass-analysis");
2207
2208 NeedLocTracking |= Opts.OptimizationRemark.hasValidPattern() ||
2209 Opts.OptimizationRemarkMissed.hasValidPattern() ||
2210 Opts.OptimizationRemarkAnalysis.hasValidPattern();
2211
2212 bool UsingSampleProfile = !Opts.SampleProfileFile.empty();
2213 bool UsingProfile =
2214 UsingSampleProfile || !Opts.ProfileInstrumentUsePath.empty();
2215
2216 if (Opts.DiagnosticsWithHotness && !UsingProfile &&
2217 // An IR file will contain PGO as metadata
2218 IK.getLanguage() != Language::LLVM_IR)
2219 Diags.Report(DiagID: diag::warn_drv_diagnostics_hotness_requires_pgo)
2220 << "-fdiagnostics-show-hotness";
2221
2222 // Parse remarks hotness threshold. Valid value is either integer or 'auto'.
2223 if (auto *arg =
2224 Args.getLastArg(Ids: options::OPT_fdiagnostics_hotness_threshold_EQ)) {
2225 auto ResultOrErr =
2226 llvm::remarks::parseHotnessThresholdOption(Arg: arg->getValue());
2227
2228 if (!ResultOrErr) {
2229 Diags.Report(DiagID: diag::err_drv_invalid_diagnotics_hotness_threshold)
2230 << "-fdiagnostics-hotness-threshold=";
2231 } else {
2232 Opts.DiagnosticsHotnessThreshold = *ResultOrErr;
2233 if ((!Opts.DiagnosticsHotnessThreshold ||
2234 *Opts.DiagnosticsHotnessThreshold > 0) &&
2235 !UsingProfile)
2236 Diags.Report(DiagID: diag::warn_drv_diagnostics_hotness_requires_pgo)
2237 << "-fdiagnostics-hotness-threshold=";
2238 }
2239 }
2240
2241 if (auto *arg =
2242 Args.getLastArg(Ids: options::OPT_fdiagnostics_misexpect_tolerance_EQ)) {
2243 auto ResultOrErr = parseToleranceOption(Arg: arg->getValue());
2244
2245 if (!ResultOrErr) {
2246 Diags.Report(DiagID: diag::err_drv_invalid_diagnotics_misexpect_tolerance)
2247 << "-fdiagnostics-misexpect-tolerance=";
2248 } else {
2249 Opts.DiagnosticsMisExpectTolerance = *ResultOrErr;
2250 if ((!Opts.DiagnosticsMisExpectTolerance ||
2251 *Opts.DiagnosticsMisExpectTolerance > 0) &&
2252 !UsingProfile)
2253 Diags.Report(DiagID: diag::warn_drv_diagnostics_misexpect_requires_pgo)
2254 << "-fdiagnostics-misexpect-tolerance=";
2255 }
2256 }
2257
2258 // If the user requested to use a sample profile for PGO, then the
2259 // backend will need to track source location information so the profile
2260 // can be incorporated into the IR.
2261 if (UsingSampleProfile)
2262 NeedLocTracking = true;
2263
2264 if (!Opts.StackUsageFile.empty())
2265 NeedLocTracking = true;
2266
2267 // If the user requested a flag that requires source locations available in
2268 // the backend, make sure that the backend tracks source location information.
2269 if (NeedLocTracking &&
2270 Opts.getDebugInfo() == llvm::codegenoptions::NoDebugInfo)
2271 Opts.setDebugInfo(llvm::codegenoptions::LocTrackingOnly);
2272
2273 // Parse -fsanitize-recover= arguments.
2274 // FIXME: Report unrecoverable sanitizers incorrectly specified here.
2275 parseSanitizerKinds(FlagName: "-fsanitize-recover=",
2276 Sanitizers: Args.getAllArgValues(Id: OPT_fsanitize_recover_EQ), Diags,
2277 S&: Opts.SanitizeRecover);
2278 parseSanitizerKinds(FlagName: "-fsanitize-trap=",
2279 Sanitizers: Args.getAllArgValues(Id: OPT_fsanitize_trap_EQ), Diags,
2280 S&: Opts.SanitizeTrap);
2281 parseSanitizerKinds(FlagName: "-fsanitize-merge=",
2282 Sanitizers: Args.getAllArgValues(Id: OPT_fsanitize_merge_handlers_EQ),
2283 Diags, S&: Opts.SanitizeMergeHandlers);
2284
2285 // Parse -fsanitize-skip-hot-cutoff= arguments.
2286 Opts.SanitizeSkipHotCutoffs = parseSanitizerWeightedKinds(
2287 FlagName: "-fsanitize-skip-hot-cutoff=",
2288 Sanitizers: Args.getAllArgValues(Id: OPT_fsanitize_skip_hot_cutoff_EQ), Diags);
2289
2290 parseSanitizerKinds(
2291 FlagName: "-fsanitize-annotate-debug-info=",
2292 Sanitizers: Args.getAllArgValues(Id: OPT_fsanitize_annotate_debug_info_EQ), Diags,
2293 S&: Opts.SanitizeAnnotateDebugInfo);
2294
2295 if (StringRef V =
2296 Args.getLastArgValue(Id: OPT_fallow_runtime_check_skip_hot_cutoff_EQ);
2297 !V.empty()) {
2298 double A;
2299 if (V.getAsDouble(Result&: A) || A < 0.0 || A > 1.0) {
2300 Diags.Report(DiagID: diag::err_drv_invalid_value)
2301 << "-fallow-runtime-check-skip-hot-cutoff=" << V;
2302 } else {
2303 Opts.AllowRuntimeCheckSkipHotCutoff = A;
2304 }
2305 }
2306
2307 Opts.EmitVersionIdentMetadata = Args.hasFlag(Pos: OPT_Qy, Neg: OPT_Qn, Default: true);
2308
2309 if (!LangOpts->CUDAIsDevice)
2310 parsePointerAuthOptions(Opts&: Opts.PointerAuth, LangOpts: *LangOpts, Triple: T, Diags);
2311
2312 if (Args.hasArg(Ids: options::OPT_ffinite_loops))
2313 Opts.FiniteLoops = CodeGenOptions::FiniteLoopsKind::Always;
2314 else if (Args.hasArg(Ids: options::OPT_fno_finite_loops))
2315 Opts.FiniteLoops = CodeGenOptions::FiniteLoopsKind::Never;
2316
2317 Opts.EmitIEEENaNCompliantInsts = Args.hasFlag(
2318 Pos: options::OPT_mamdgpu_ieee, Neg: options::OPT_mno_amdgpu_ieee, Default: true);
2319 if (!Opts.EmitIEEENaNCompliantInsts && !LangOptsRef.NoHonorNaNs)
2320 Diags.Report(DiagID: diag::err_drv_amdgpu_ieee_without_no_honor_nans);
2321
2322 Opts.StaticClosure = Args.hasArg(Ids: options::OPT_static_libclosure);
2323
2324 return Diags.getNumErrors() == NumErrorsBefore;
2325}
2326
2327static void GenerateDependencyOutputArgs(const DependencyOutputOptions &Opts,
2328 ArgumentConsumer Consumer) {
2329 const DependencyOutputOptions &DependencyOutputOpts = Opts;
2330#define DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING(...) \
2331 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
2332#include "clang/Options/Options.inc"
2333#undef DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING
2334
2335 if (Opts.ShowIncludesDest != ShowIncludesDestination::None)
2336 GenerateArg(Consumer, OptSpecifier: OPT_show_includes);
2337
2338 for (const auto &Dep : Opts.ExtraDeps) {
2339 switch (Dep.second) {
2340 case EDK_SanitizeIgnorelist:
2341 // Sanitizer ignorelist arguments are generated from LanguageOptions.
2342 continue;
2343 case EDK_ModuleFile:
2344 // Module file arguments are generated from FrontendOptions and
2345 // HeaderSearchOptions.
2346 continue;
2347 case EDK_ProfileList:
2348 // Profile list arguments are generated from LanguageOptions via the
2349 // marshalling infrastructure.
2350 continue;
2351 case EDK_DepFileEntry:
2352 GenerateArg(Consumer, OptSpecifier: OPT_fdepfile_entry, Value: Dep.first);
2353 break;
2354 }
2355 }
2356}
2357
2358static bool ParseDependencyOutputArgs(DependencyOutputOptions &Opts,
2359 ArgList &Args, DiagnosticsEngine &Diags,
2360 frontend::ActionKind Action,
2361 bool ShowLineMarkers) {
2362 unsigned NumErrorsBefore = Diags.getNumErrors();
2363
2364 DependencyOutputOptions &DependencyOutputOpts = Opts;
2365#define DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING(...) \
2366 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
2367#include "clang/Options/Options.inc"
2368#undef DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING
2369
2370 if (Args.hasArg(Ids: OPT_show_includes)) {
2371 // Writing both /showIncludes and preprocessor output to stdout
2372 // would produce interleaved output, so use stderr for /showIncludes.
2373 // This behaves the same as cl.exe, when /E, /EP or /P are passed.
2374 if (Action == frontend::PrintPreprocessedInput || !ShowLineMarkers)
2375 Opts.ShowIncludesDest = ShowIncludesDestination::Stderr;
2376 else
2377 Opts.ShowIncludesDest = ShowIncludesDestination::Stdout;
2378 } else {
2379 Opts.ShowIncludesDest = ShowIncludesDestination::None;
2380 }
2381
2382 // Add sanitizer ignorelists as extra dependencies.
2383 // They won't be discovered by the regular preprocessor, so
2384 // we let make / ninja to know about this implicit dependency.
2385 if (!Args.hasArg(Ids: OPT_fno_sanitize_ignorelist)) {
2386 for (const auto *A : Args.filtered(Ids: OPT_fsanitize_ignorelist_EQ)) {
2387 StringRef Val = A->getValue();
2388 if (!Val.contains(C: '='))
2389 Opts.ExtraDeps.emplace_back(args: std::string(Val), args: EDK_SanitizeIgnorelist);
2390 }
2391 if (Opts.IncludeSystemHeaders) {
2392 for (const auto *A : Args.filtered(Ids: OPT_fsanitize_system_ignorelist_EQ)) {
2393 StringRef Val = A->getValue();
2394 if (!Val.contains(C: '='))
2395 Opts.ExtraDeps.emplace_back(args: std::string(Val), args: EDK_SanitizeIgnorelist);
2396 }
2397 }
2398 }
2399
2400 // -fprofile-list= dependencies.
2401 for (const auto &Filename : Args.getAllArgValues(Id: OPT_fprofile_list_EQ))
2402 Opts.ExtraDeps.emplace_back(args: Filename, args: EDK_ProfileList);
2403
2404 // Propagate the extra dependencies.
2405 for (const auto *A : Args.filtered(Ids: OPT_fdepfile_entry))
2406 Opts.ExtraDeps.emplace_back(args: A->getValue(), args: EDK_DepFileEntry);
2407
2408 // Only the -fmodule-file=<file> form.
2409 for (const auto *A : Args.filtered(Ids: OPT_fmodule_file)) {
2410 StringRef Val = A->getValue();
2411 if (!Val.contains(C: '='))
2412 Opts.ExtraDeps.emplace_back(args: std::string(Val), args: EDK_ModuleFile);
2413 }
2414
2415 // Check for invalid combinations of header-include-format
2416 // and header-include-filtering.
2417 if (Opts.HeaderIncludeFormat == HIFMT_Textual &&
2418 Opts.HeaderIncludeFiltering != HIFIL_None) {
2419 if (Args.hasArg(Ids: OPT_header_include_format_EQ))
2420 Diags.Report(DiagID: diag::err_drv_print_header_cc1_invalid_combination)
2421 << headerIncludeFormatKindToString(K: Opts.HeaderIncludeFormat)
2422 << headerIncludeFilteringKindToString(K: Opts.HeaderIncludeFiltering);
2423 else
2424 Diags.Report(DiagID: diag::err_drv_print_header_cc1_invalid_filtering)
2425 << headerIncludeFilteringKindToString(K: Opts.HeaderIncludeFiltering);
2426 } else if (Opts.HeaderIncludeFormat == HIFMT_JSON &&
2427 Opts.HeaderIncludeFiltering == HIFIL_None) {
2428 if (Args.hasArg(Ids: OPT_header_include_filtering_EQ))
2429 Diags.Report(DiagID: diag::err_drv_print_header_cc1_invalid_combination)
2430 << headerIncludeFormatKindToString(K: Opts.HeaderIncludeFormat)
2431 << headerIncludeFilteringKindToString(K: Opts.HeaderIncludeFiltering);
2432 else
2433 Diags.Report(DiagID: diag::err_drv_print_header_cc1_invalid_format)
2434 << headerIncludeFormatKindToString(K: Opts.HeaderIncludeFormat);
2435 }
2436
2437 return Diags.getNumErrors() == NumErrorsBefore;
2438}
2439
2440static bool parseShowColorsArgs(const ArgList &Args, bool DefaultColor) {
2441 // Color diagnostics default to auto ("on" if terminal supports) in the driver
2442 // but default to off in cc1, needing an explicit OPT_fdiagnostics_color.
2443 // Support both clang's -f[no-]color-diagnostics and gcc's
2444 // -f[no-]diagnostics-colors[=never|always|auto].
2445 enum {
2446 Colors_On,
2447 Colors_Off,
2448 Colors_Auto
2449 } ShowColors = DefaultColor ? Colors_Auto : Colors_Off;
2450 for (auto *A : Args) {
2451 const Option &O = A->getOption();
2452 if (O.matches(ID: options::OPT_fcolor_diagnostics)) {
2453 ShowColors = Colors_On;
2454 } else if (O.matches(ID: options::OPT_fno_color_diagnostics)) {
2455 ShowColors = Colors_Off;
2456 } else if (O.matches(ID: options::OPT_fdiagnostics_color_EQ)) {
2457 StringRef Value(A->getValue());
2458 if (Value == "always")
2459 ShowColors = Colors_On;
2460 else if (Value == "never")
2461 ShowColors = Colors_Off;
2462 else if (Value == "auto")
2463 ShowColors = Colors_Auto;
2464 }
2465 }
2466 return ShowColors == Colors_On ||
2467 (ShowColors == Colors_Auto &&
2468 llvm::sys::Process::StandardErrHasColors());
2469}
2470
2471static bool checkVerifyPrefixes(const std::vector<std::string> &VerifyPrefixes,
2472 DiagnosticsEngine &Diags) {
2473 bool Success = true;
2474 for (const auto &Prefix : VerifyPrefixes) {
2475 // Every prefix must start with a letter and contain only alphanumeric
2476 // characters, hyphens, and underscores.
2477 auto BadChar = llvm::find_if(Range: Prefix, P: [](char C) {
2478 return !isAlphanumeric(c: C) && C != '-' && C != '_';
2479 });
2480 if (BadChar != Prefix.end() || !isLetter(c: Prefix[0])) {
2481 Success = false;
2482 Diags.Report(DiagID: diag::err_drv_invalid_value) << "-verify=" << Prefix;
2483 Diags.Report(DiagID: diag::note_drv_verify_prefix_spelling);
2484 }
2485 }
2486 return Success;
2487}
2488
2489static void GenerateFileSystemArgs(const FileSystemOptions &Opts,
2490 ArgumentConsumer Consumer) {
2491 const FileSystemOptions &FileSystemOpts = Opts;
2492
2493#define FILE_SYSTEM_OPTION_WITH_MARSHALLING(...) \
2494 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
2495#include "clang/Options/Options.inc"
2496#undef FILE_SYSTEM_OPTION_WITH_MARSHALLING
2497}
2498
2499static bool ParseFileSystemArgs(FileSystemOptions &Opts, const ArgList &Args,
2500 DiagnosticsEngine &Diags) {
2501 unsigned NumErrorsBefore = Diags.getNumErrors();
2502
2503 FileSystemOptions &FileSystemOpts = Opts;
2504
2505#define FILE_SYSTEM_OPTION_WITH_MARSHALLING(...) \
2506 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
2507#include "clang/Options/Options.inc"
2508#undef FILE_SYSTEM_OPTION_WITH_MARSHALLING
2509
2510 return Diags.getNumErrors() == NumErrorsBefore;
2511}
2512
2513static void GenerateMigratorArgs(const MigratorOptions &Opts,
2514 ArgumentConsumer Consumer) {
2515 const MigratorOptions &MigratorOpts = Opts;
2516#define MIGRATOR_OPTION_WITH_MARSHALLING(...) \
2517 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
2518#include "clang/Options/Options.inc"
2519#undef MIGRATOR_OPTION_WITH_MARSHALLING
2520}
2521
2522static bool ParseMigratorArgs(MigratorOptions &Opts, const ArgList &Args,
2523 DiagnosticsEngine &Diags) {
2524 unsigned NumErrorsBefore = Diags.getNumErrors();
2525
2526 MigratorOptions &MigratorOpts = Opts;
2527
2528#define MIGRATOR_OPTION_WITH_MARSHALLING(...) \
2529 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
2530#include "clang/Options/Options.inc"
2531#undef MIGRATOR_OPTION_WITH_MARSHALLING
2532
2533 return Diags.getNumErrors() == NumErrorsBefore;
2534}
2535
2536void CompilerInvocationBase::GenerateDiagnosticArgs(
2537 const DiagnosticOptions &Opts, ArgumentConsumer Consumer,
2538 bool DefaultDiagColor) {
2539 const DiagnosticOptions *DiagnosticOpts = &Opts;
2540#define DIAG_OPTION_WITH_MARSHALLING(...) \
2541 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
2542#include "clang/Options/Options.inc"
2543#undef DIAG_OPTION_WITH_MARSHALLING
2544
2545 if (!Opts.DiagnosticSerializationFile.empty())
2546 GenerateArg(Consumer, OptSpecifier: OPT_diagnostic_serialized_file,
2547 Value: Opts.DiagnosticSerializationFile);
2548
2549 if (Opts.ShowColors)
2550 GenerateArg(Consumer, OptSpecifier: OPT_fcolor_diagnostics);
2551
2552 if (Opts.VerifyDiagnostics &&
2553 llvm::is_contained(Range: Opts.VerifyPrefixes, Element: "expected"))
2554 GenerateArg(Consumer, OptSpecifier: OPT_verify);
2555
2556 for (const auto &Prefix : Opts.VerifyPrefixes)
2557 if (Prefix != "expected")
2558 GenerateArg(Consumer, OptSpecifier: OPT_verify_EQ, Value: Prefix);
2559
2560 if (Opts.VerifyDirectives) {
2561 GenerateArg(Consumer, OptSpecifier: OPT_verify_directives);
2562 }
2563
2564 DiagnosticLevelMask VIU = Opts.getVerifyIgnoreUnexpected();
2565 if (VIU == DiagnosticLevelMask::None) {
2566 // This is the default, don't generate anything.
2567 } else if (VIU == DiagnosticLevelMask::All) {
2568 GenerateArg(Consumer, OptSpecifier: OPT_verify_ignore_unexpected);
2569 } else {
2570 if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Note) != 0)
2571 GenerateArg(Consumer, OptSpecifier: OPT_verify_ignore_unexpected_EQ, Value: "note");
2572 if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Remark) != 0)
2573 GenerateArg(Consumer, OptSpecifier: OPT_verify_ignore_unexpected_EQ, Value: "remark");
2574 if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Warning) != 0)
2575 GenerateArg(Consumer, OptSpecifier: OPT_verify_ignore_unexpected_EQ, Value: "warning");
2576 if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Error) != 0)
2577 GenerateArg(Consumer, OptSpecifier: OPT_verify_ignore_unexpected_EQ, Value: "error");
2578 }
2579
2580 for (const auto &Warning : Opts.Warnings) {
2581 // This option is automatically generated from UndefPrefixes.
2582 if (Warning == "undef-prefix")
2583 continue;
2584 // This option is automatically generated from CheckConstexprFunctionBodies.
2585 if (Warning == "invalid-constexpr" || Warning == "no-invalid-constexpr")
2586 continue;
2587 Consumer(StringRef("-W") + Warning);
2588 }
2589
2590 for (const auto &Remark : Opts.Remarks) {
2591 // These arguments are generated from OptimizationRemark fields of
2592 // CodeGenOptions.
2593 StringRef IgnoredRemarks[] = {"pass", "no-pass",
2594 "pass-analysis", "no-pass-analysis",
2595 "pass-missed", "no-pass-missed"};
2596 if (llvm::is_contained(Range&: IgnoredRemarks, Element: Remark))
2597 continue;
2598
2599 Consumer(StringRef("-R") + Remark);
2600 }
2601
2602 if (!Opts.DiagnosticSuppressionMappingsFile.empty()) {
2603 GenerateArg(Consumer, OptSpecifier: OPT_warning_suppression_mappings_EQ,
2604 Value: Opts.DiagnosticSuppressionMappingsFile);
2605 }
2606}
2607
2608std::unique_ptr<DiagnosticOptions>
2609clang::CreateAndPopulateDiagOpts(ArrayRef<const char *> Argv) {
2610 auto DiagOpts = std::make_unique<DiagnosticOptions>();
2611 unsigned MissingArgIndex, MissingArgCount;
2612 InputArgList Args = getDriverOptTable().ParseArgs(
2613 Args: Argv.slice(N: 1), MissingArgIndex, MissingArgCount);
2614
2615 bool ShowColors = true;
2616 if (std::optional<std::string> NoColor =
2617 llvm::sys::Process::GetEnv(name: "NO_COLOR");
2618 NoColor && !NoColor->empty()) {
2619 // If the user set the NO_COLOR environment variable, we'll honor that
2620 // unless the command line overrides it.
2621 ShowColors = false;
2622 }
2623
2624 // We ignore MissingArgCount and the return value of ParseDiagnosticArgs.
2625 // Any errors that would be diagnosed here will also be diagnosed later,
2626 // when the DiagnosticsEngine actually exists.
2627 (void)ParseDiagnosticArgs(Opts&: *DiagOpts, Args, /*Diags=*/nullptr, DefaultDiagColor: ShowColors);
2628 return DiagOpts;
2629}
2630
2631bool clang::ParseDiagnosticArgs(DiagnosticOptions &Opts, ArgList &Args,
2632 DiagnosticsEngine *Diags,
2633 bool DefaultDiagColor) {
2634 std::optional<DiagnosticOptions> IgnoringDiagOpts;
2635 std::optional<DiagnosticsEngine> IgnoringDiags;
2636 if (!Diags) {
2637 IgnoringDiagOpts.emplace();
2638 IgnoringDiags.emplace(args: DiagnosticIDs::create(), args&: *IgnoringDiagOpts,
2639 args: new IgnoringDiagConsumer());
2640 Diags = &*IgnoringDiags;
2641 }
2642
2643 unsigned NumErrorsBefore = Diags->getNumErrors();
2644
2645 // The key paths of diagnostic options defined in Options.td start with
2646 // "DiagnosticOpts->". Let's provide the expected variable name and type.
2647 DiagnosticOptions *DiagnosticOpts = &Opts;
2648
2649#define DIAG_OPTION_WITH_MARSHALLING(...) \
2650 PARSE_OPTION_WITH_MARSHALLING(Args, *Diags, __VA_ARGS__)
2651#include "clang/Options/Options.inc"
2652#undef DIAG_OPTION_WITH_MARSHALLING
2653
2654 llvm::sys::Process::UseANSIEscapeCodes(enable: Opts.UseANSIEscapeCodes);
2655
2656 if (Arg *A =
2657 Args.getLastArg(Ids: OPT_diagnostic_serialized_file, Ids: OPT__serialize_diags))
2658 Opts.DiagnosticSerializationFile = A->getValue();
2659 Opts.ShowColors = parseShowColorsArgs(Args, DefaultColor: DefaultDiagColor);
2660
2661 Opts.VerifyDiagnostics = Args.hasArg(Ids: OPT_verify) || Args.hasArg(Ids: OPT_verify_EQ);
2662 Opts.VerifyDirectives = Args.hasArg(Ids: OPT_verify_directives);
2663 Opts.VerifyPrefixes = Args.getAllArgValues(Id: OPT_verify_EQ);
2664 if (Args.hasArg(Ids: OPT_verify))
2665 Opts.VerifyPrefixes.push_back(x: "expected");
2666 // Keep VerifyPrefixes in its original order for the sake of diagnostics, and
2667 // then sort it to prepare for fast lookup using std::binary_search.
2668 if (!checkVerifyPrefixes(VerifyPrefixes: Opts.VerifyPrefixes, Diags&: *Diags))
2669 Opts.VerifyDiagnostics = false;
2670 else
2671 llvm::sort(C&: Opts.VerifyPrefixes);
2672 DiagnosticLevelMask DiagMask = DiagnosticLevelMask::None;
2673 parseDiagnosticLevelMask(
2674 FlagName: "-verify-ignore-unexpected=",
2675 Levels: Args.getAllArgValues(Id: OPT_verify_ignore_unexpected_EQ), Diags&: *Diags, M&: DiagMask);
2676 if (Args.hasArg(Ids: OPT_verify_ignore_unexpected))
2677 DiagMask = DiagnosticLevelMask::All;
2678 Opts.setVerifyIgnoreUnexpected(DiagMask);
2679 if (Opts.TabStop == 0 || Opts.TabStop > DiagnosticOptions::MaxTabStop) {
2680 Diags->Report(DiagID: diag::warn_ignoring_ftabstop_value)
2681 << Opts.TabStop << DiagnosticOptions::DefaultTabStop;
2682 Opts.TabStop = DiagnosticOptions::DefaultTabStop;
2683 }
2684
2685 if (const Arg *A = Args.getLastArg(Ids: OPT_warning_suppression_mappings_EQ))
2686 Opts.DiagnosticSuppressionMappingsFile = A->getValue();
2687
2688 addDiagnosticArgs(Args, Group: OPT_W_Group, GroupWithValue: OPT_W_value_Group, Diagnostics&: Opts.Warnings);
2689 addDiagnosticArgs(Args, Group: OPT_R_Group, GroupWithValue: OPT_R_value_Group, Diagnostics&: Opts.Remarks);
2690
2691 return Diags->getNumErrors() == NumErrorsBefore;
2692}
2693
2694unsigned clang::getOptimizationLevel(const ArgList &Args, InputKind IK,
2695 DiagnosticsEngine &Diags) {
2696 unsigned DefaultOpt = 0;
2697 if ((IK.getLanguage() == Language::OpenCL ||
2698 IK.getLanguage() == Language::OpenCLCXX) &&
2699 !Args.hasArg(Ids: OPT_cl_opt_disable))
2700 DefaultOpt = 2;
2701
2702 if (Arg *A = Args.getLastArg(Ids: options::OPT_O_Group)) {
2703 if (A->getOption().matches(ID: options::OPT_O0))
2704 return 0;
2705
2706 if (A->getOption().matches(ID: options::OPT_Ofast))
2707 return 3;
2708
2709 assert(A->getOption().matches(options::OPT_O));
2710
2711 StringRef S(A->getValue());
2712 if (S == "s" || S == "z")
2713 return 2;
2714
2715 if (S == "g")
2716 return 1;
2717
2718 DefaultOpt = getLastArgIntValue(Args, Id: OPT_O, Default: DefaultOpt, Diags);
2719 }
2720
2721 unsigned MaxOptLevel = 3;
2722 if (DefaultOpt > MaxOptLevel) {
2723 // If the optimization level is not supported, fall back on the default
2724 // optimization
2725 Diags.Report(DiagID: diag::warn_drv_optimization_value)
2726 << Args.getLastArg(Ids: OPT_O)->getAsString(Args) << "-O" << MaxOptLevel;
2727 DefaultOpt = MaxOptLevel;
2728 }
2729
2730 return DefaultOpt;
2731}
2732
2733unsigned clang::getOptimizationLevelSize(const ArgList &Args) {
2734 if (Arg *A = Args.getLastArg(Ids: options::OPT_O_Group)) {
2735 if (A->getOption().matches(ID: options::OPT_O)) {
2736 switch (A->getValue()[0]) {
2737 default:
2738 return 0;
2739 case 's':
2740 return 1;
2741 case 'z':
2742 return 2;
2743 }
2744 }
2745 }
2746 return 0;
2747}
2748
2749/// Parse the argument to the -ftest-module-file-extension
2750/// command-line argument.
2751///
2752/// \returns true on error, false on success.
2753static bool parseTestModuleFileExtensionArg(StringRef Arg,
2754 std::string &BlockName,
2755 unsigned &MajorVersion,
2756 unsigned &MinorVersion,
2757 bool &Hashed,
2758 std::string &UserInfo) {
2759 SmallVector<StringRef, 5> Args;
2760 Arg.split(A&: Args, Separator: ':', MaxSplit: 5);
2761 if (Args.size() < 5)
2762 return true;
2763
2764 BlockName = std::string(Args[0]);
2765 if (Args[1].getAsInteger(Radix: 10, Result&: MajorVersion)) return true;
2766 if (Args[2].getAsInteger(Radix: 10, Result&: MinorVersion)) return true;
2767 if (Args[3].getAsInteger(Radix: 2, Result&: Hashed)) return true;
2768 if (Args.size() > 4)
2769 UserInfo = std::string(Args[4]);
2770 return false;
2771}
2772
2773/// Return a table that associates command line option specifiers with the
2774/// frontend action. Note: The pair {frontend::PluginAction, OPT_plugin} is
2775/// intentionally missing, as this case is handled separately from other
2776/// frontend options.
2777static const auto &getFrontendActionTable() {
2778 static const std::pair<frontend::ActionKind, unsigned> Table[] = {
2779 {frontend::ASTDeclList, OPT_ast_list},
2780
2781 {frontend::ASTDump, OPT_ast_dump_all_EQ},
2782 {frontend::ASTDump, OPT_ast_dump_all},
2783 {frontend::ASTDump, OPT_ast_dump_EQ},
2784 {frontend::ASTDump, OPT_ast_dump},
2785 {frontend::ASTDump, OPT_ast_dump_lookups},
2786 {frontend::ASTDump, OPT_ast_dump_decl_types},
2787
2788 {frontend::ASTPrint, OPT_ast_print},
2789 {frontend::ASTView, OPT_ast_view},
2790 {frontend::DumpCompilerOptions, OPT_compiler_options_dump},
2791 {frontend::DumpRawTokens, OPT_dump_raw_tokens},
2792 {frontend::DumpTokens, OPT_dump_tokens},
2793 {frontend::EmitAssembly, OPT_S},
2794 {frontend::EmitBC, OPT_emit_llvm_bc},
2795 {frontend::EmitCIR, OPT_emit_cir},
2796 {frontend::EmitHTML, OPT_emit_html},
2797 {frontend::EmitLLVM, OPT_emit_llvm},
2798 {frontend::EmitLLVMOnly, OPT_emit_llvm_only},
2799 {frontend::EmitCodeGenOnly, OPT_emit_codegen_only},
2800 {frontend::EmitObj, OPT_emit_obj},
2801 {frontend::ExtractAPI, OPT_extract_api},
2802
2803 {frontend::FixIt, OPT_fixit_EQ},
2804 {frontend::FixIt, OPT_fixit},
2805
2806 {frontend::GenerateModule, OPT_emit_module},
2807 {frontend::GenerateModuleInterface, OPT_emit_module_interface},
2808 {frontend::GenerateReducedModuleInterface,
2809 OPT_emit_reduced_module_interface},
2810 {frontend::GenerateHeaderUnit, OPT_emit_header_unit},
2811 {frontend::GeneratePCH, OPT_emit_pch},
2812 {frontend::GenerateInterfaceStubs, OPT_emit_interface_stubs},
2813 {frontend::InitOnly, OPT_init_only},
2814 {frontend::ParseSyntaxOnly, OPT_fsyntax_only},
2815 {frontend::ModuleFileInfo, OPT_module_file_info},
2816 {frontend::VerifyPCH, OPT_verify_pch},
2817 {frontend::PrintPreamble, OPT_print_preamble},
2818 {frontend::PrintPreprocessedInput, OPT_E},
2819 {frontend::TemplightDump, OPT_templight_dump},
2820 {frontend::RewriteMacros, OPT_rewrite_macros},
2821 {frontend::RewriteObjC, OPT_rewrite_objc},
2822 {frontend::RewriteTest, OPT_rewrite_test},
2823 {frontend::RunAnalysis, OPT_analyze},
2824 {frontend::RunPreprocessorOnly, OPT_Eonly},
2825 {frontend::PrintDependencyDirectivesSourceMinimizerOutput,
2826 OPT_print_dependency_directives_minimized_source},
2827 };
2828
2829 return Table;
2830}
2831
2832/// Maps command line option to frontend action.
2833static std::optional<frontend::ActionKind>
2834getFrontendAction(OptSpecifier &Opt) {
2835 for (const auto &ActionOpt : getFrontendActionTable())
2836 if (ActionOpt.second == Opt.getID())
2837 return ActionOpt.first;
2838
2839 return std::nullopt;
2840}
2841
2842/// Maps frontend action to command line option.
2843static std::optional<OptSpecifier>
2844getProgramActionOpt(frontend::ActionKind ProgramAction) {
2845 for (const auto &ActionOpt : getFrontendActionTable())
2846 if (ActionOpt.first == ProgramAction)
2847 return OptSpecifier(ActionOpt.second);
2848
2849 return std::nullopt;
2850}
2851
2852static void GenerateFrontendArgs(const FrontendOptions &Opts,
2853 ArgumentConsumer Consumer, bool IsHeader) {
2854 const FrontendOptions &FrontendOpts = Opts;
2855#define FRONTEND_OPTION_WITH_MARSHALLING(...) \
2856 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
2857#include "clang/Options/Options.inc"
2858#undef FRONTEND_OPTION_WITH_MARSHALLING
2859
2860 std::optional<OptSpecifier> ProgramActionOpt =
2861 getProgramActionOpt(ProgramAction: Opts.ProgramAction);
2862
2863 // Generating a simple flag covers most frontend actions.
2864 std::function<void()> GenerateProgramAction = [&]() {
2865 GenerateArg(Consumer, OptSpecifier: *ProgramActionOpt);
2866 };
2867
2868 if (!ProgramActionOpt) {
2869 // PluginAction is the only program action handled separately.
2870 assert(Opts.ProgramAction == frontend::PluginAction &&
2871 "Frontend action without option.");
2872 GenerateProgramAction = [&]() {
2873 GenerateArg(Consumer, OptSpecifier: OPT_plugin, Value: Opts.ActionName);
2874 };
2875 }
2876
2877 // FIXME: Simplify the complex 'AST dump' command line.
2878 if (Opts.ProgramAction == frontend::ASTDump) {
2879 GenerateProgramAction = [&]() {
2880 // ASTDumpLookups, ASTDumpDeclTypes and ASTDumpFilter are generated via
2881 // marshalling infrastructure.
2882
2883 if (Opts.ASTDumpFormat != ADOF_Default) {
2884 StringRef Format;
2885 switch (Opts.ASTDumpFormat) {
2886 case ADOF_Default:
2887 llvm_unreachable("Default AST dump format.");
2888 case ADOF_JSON:
2889 Format = "json";
2890 break;
2891 }
2892
2893 if (Opts.ASTDumpAll)
2894 GenerateArg(Consumer, OptSpecifier: OPT_ast_dump_all_EQ, Value: Format);
2895 if (Opts.ASTDumpDecls)
2896 GenerateArg(Consumer, OptSpecifier: OPT_ast_dump_EQ, Value: Format);
2897 } else {
2898 if (Opts.ASTDumpAll)
2899 GenerateArg(Consumer, OptSpecifier: OPT_ast_dump_all);
2900 if (Opts.ASTDumpDecls)
2901 GenerateArg(Consumer, OptSpecifier: OPT_ast_dump);
2902 }
2903 };
2904 }
2905
2906 if (Opts.ProgramAction == frontend::FixIt && !Opts.FixItSuffix.empty()) {
2907 GenerateProgramAction = [&]() {
2908 GenerateArg(Consumer, OptSpecifier: OPT_fixit_EQ, Value: Opts.FixItSuffix);
2909 };
2910 }
2911
2912 GenerateProgramAction();
2913
2914 for (const auto &PluginArgs : Opts.PluginArgs) {
2915 Option Opt = getDriverOptTable().getOption(Opt: OPT_plugin_arg);
2916 for (const auto &PluginArg : PluginArgs.second)
2917 denormalizeString(Consumer,
2918 Spelling: Opt.getPrefix() + Opt.getName() + PluginArgs.first,
2919 OptClass: Opt.getKind(), TableIndex: 0, Value: PluginArg);
2920 }
2921
2922 for (const auto &Ext : Opts.ModuleFileExtensions)
2923 if (auto *TestExt = dyn_cast_or_null<TestModuleFileExtension>(Val: Ext.get()))
2924 GenerateArg(Consumer, OptSpecifier: OPT_ftest_module_file_extension_EQ, Value: TestExt->str());
2925
2926 if (!Opts.CodeCompletionAt.FileName.empty())
2927 GenerateArg(Consumer, OptSpecifier: OPT_code_completion_at,
2928 Value: Opts.CodeCompletionAt.ToString());
2929
2930 for (const auto &Plugin : Opts.Plugins)
2931 GenerateArg(Consumer, OptSpecifier: OPT_load, Value: Plugin);
2932
2933 // ASTDumpDecls and ASTDumpAll already handled with ProgramAction.
2934
2935 for (const auto &ModuleFile : Opts.ModuleFiles)
2936 GenerateArg(Consumer, OptSpecifier: OPT_fmodule_file, Value: ModuleFile);
2937
2938 if (Opts.AuxTargetCPU)
2939 GenerateArg(Consumer, OptSpecifier: OPT_aux_target_cpu, Value: *Opts.AuxTargetCPU);
2940
2941 if (Opts.AuxTargetFeatures)
2942 for (const auto &Feature : *Opts.AuxTargetFeatures)
2943 GenerateArg(Consumer, OptSpecifier: OPT_aux_target_feature, Value: Feature);
2944
2945 {
2946 StringRef Preprocessed = Opts.DashX.isPreprocessed() ? "-cpp-output" : "";
2947 StringRef ModuleMap =
2948 Opts.DashX.getFormat() == InputKind::ModuleMap ? "-module-map" : "";
2949 StringRef HeaderUnit = "";
2950 switch (Opts.DashX.getHeaderUnitKind()) {
2951 case InputKind::HeaderUnit_None:
2952 break;
2953 case InputKind::HeaderUnit_User:
2954 HeaderUnit = "-user";
2955 break;
2956 case InputKind::HeaderUnit_System:
2957 HeaderUnit = "-system";
2958 break;
2959 case InputKind::HeaderUnit_Abs:
2960 HeaderUnit = "-header-unit";
2961 break;
2962 }
2963 StringRef Header = IsHeader ? "-header" : "";
2964
2965 StringRef Lang;
2966 switch (Opts.DashX.getLanguage()) {
2967 case Language::C:
2968 Lang = "c";
2969 break;
2970 case Language::OpenCL:
2971 Lang = "cl";
2972 break;
2973 case Language::OpenCLCXX:
2974 Lang = "clcpp";
2975 break;
2976 case Language::CUDA:
2977 Lang = "cuda";
2978 break;
2979 case Language::HIP:
2980 Lang = "hip";
2981 break;
2982 case Language::CXX:
2983 Lang = "c++";
2984 break;
2985 case Language::ObjC:
2986 Lang = "objective-c";
2987 break;
2988 case Language::ObjCXX:
2989 Lang = "objective-c++";
2990 break;
2991 case Language::Asm:
2992 Lang = "assembler-with-cpp";
2993 break;
2994 case Language::Unknown:
2995 assert(Opts.DashX.getFormat() == InputKind::Precompiled &&
2996 "Generating -x argument for unknown language (not precompiled).");
2997 Lang = "ast";
2998 break;
2999 case Language::LLVM_IR:
3000 Lang = "ir";
3001 break;
3002 case Language::HLSL:
3003 Lang = "hlsl";
3004 break;
3005 case Language::CIR:
3006 Lang = "cir";
3007 break;
3008 }
3009
3010 GenerateArg(Consumer, OptSpecifier: OPT_x,
3011 Value: Lang + HeaderUnit + Header + ModuleMap + Preprocessed);
3012 }
3013
3014 // OPT_INPUT has a unique class, generate it directly.
3015 for (const auto &Input : Opts.Inputs)
3016 Consumer(Input.getFile());
3017}
3018
3019static bool ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args,
3020 DiagnosticsEngine &Diags, bool &IsHeaderFile) {
3021 unsigned NumErrorsBefore = Diags.getNumErrors();
3022
3023 FrontendOptions &FrontendOpts = Opts;
3024
3025#define FRONTEND_OPTION_WITH_MARSHALLING(...) \
3026 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
3027#include "clang/Options/Options.inc"
3028#undef FRONTEND_OPTION_WITH_MARSHALLING
3029
3030 Opts.ProgramAction = frontend::ParseSyntaxOnly;
3031 if (const Arg *A = Args.getLastArg(Ids: OPT_Action_Group)) {
3032 OptSpecifier Opt = OptSpecifier(A->getOption().getID());
3033 std::optional<frontend::ActionKind> ProgramAction = getFrontendAction(Opt);
3034 assert(ProgramAction && "Option specifier not in Action_Group.");
3035
3036 if (ProgramAction == frontend::ASTDump &&
3037 (Opt == OPT_ast_dump_all_EQ || Opt == OPT_ast_dump_EQ)) {
3038 unsigned Val = llvm::StringSwitch<unsigned>(A->getValue())
3039 .CaseLower(S: "default", Value: ADOF_Default)
3040 .CaseLower(S: "json", Value: ADOF_JSON)
3041 .Default(Value: std::numeric_limits<unsigned>::max());
3042
3043 if (Val != std::numeric_limits<unsigned>::max())
3044 Opts.ASTDumpFormat = static_cast<ASTDumpOutputFormat>(Val);
3045 else {
3046 Diags.Report(DiagID: diag::err_drv_invalid_value)
3047 << A->getAsString(Args) << A->getValue();
3048 Opts.ASTDumpFormat = ADOF_Default;
3049 }
3050 }
3051
3052 if (ProgramAction == frontend::FixIt && Opt == OPT_fixit_EQ)
3053 Opts.FixItSuffix = A->getValue();
3054
3055 if (ProgramAction == frontend::GenerateInterfaceStubs) {
3056 StringRef ArgStr =
3057 Args.hasArg(Ids: OPT_interface_stub_version_EQ)
3058 ? Args.getLastArgValue(Id: OPT_interface_stub_version_EQ)
3059 : "ifs-v1";
3060 if (ArgStr == "experimental-yaml-elf-v1" ||
3061 ArgStr == "experimental-ifs-v1" || ArgStr == "experimental-ifs-v2" ||
3062 ArgStr == "experimental-tapi-elf-v1") {
3063 std::string ErrorMessage =
3064 "Invalid interface stub format: " + ArgStr.str() +
3065 " is deprecated.";
3066 Diags.Report(DiagID: diag::err_drv_invalid_value)
3067 << "Must specify a valid interface stub format type, ie: "
3068 "-interface-stub-version=ifs-v1"
3069 << ErrorMessage;
3070 ProgramAction = frontend::ParseSyntaxOnly;
3071 } else if (!ArgStr.starts_with(Prefix: "ifs-")) {
3072 std::string ErrorMessage =
3073 "Invalid interface stub format: " + ArgStr.str() + ".";
3074 Diags.Report(DiagID: diag::err_drv_invalid_value)
3075 << "Must specify a valid interface stub format type, ie: "
3076 "-interface-stub-version=ifs-v1"
3077 << ErrorMessage;
3078 ProgramAction = frontend::ParseSyntaxOnly;
3079 }
3080 }
3081
3082 Opts.ProgramAction = *ProgramAction;
3083
3084 // Catch common mistakes when multiple actions are specified for cc1 (e.g.
3085 // -S -emit-llvm means -emit-llvm while -emit-llvm -S means -S). However, to
3086 // support driver `-c -Xclang ACTION` (-cc1 -emit-llvm file -main-file-name
3087 // X ACTION), we suppress the error when the two actions are separated by
3088 // -main-file-name.
3089 //
3090 // As an exception, accept composable -ast-dump*.
3091 if (!A->getSpelling().starts_with(Prefix: "-ast-dump")) {
3092 const Arg *SavedAction = nullptr;
3093 for (const Arg *AA :
3094 Args.filtered(Ids: OPT_Action_Group, Ids: OPT_main_file_name)) {
3095 if (AA->getOption().matches(ID: OPT_main_file_name)) {
3096 SavedAction = nullptr;
3097 } else if (!SavedAction) {
3098 SavedAction = AA;
3099 } else {
3100 if (!A->getOption().matches(ID: OPT_ast_dump_EQ))
3101 Diags.Report(DiagID: diag::err_fe_invalid_multiple_actions)
3102 << SavedAction->getSpelling() << A->getSpelling();
3103 break;
3104 }
3105 }
3106 }
3107 }
3108
3109 if (const Arg* A = Args.getLastArg(Ids: OPT_plugin)) {
3110 Opts.Plugins.emplace_back(args: A->getValue(N: 0));
3111 Opts.ProgramAction = frontend::PluginAction;
3112 Opts.ActionName = A->getValue();
3113 }
3114 for (const auto *AA : Args.filtered(Ids: OPT_plugin_arg))
3115 Opts.PluginArgs[AA->getValue(N: 0)].emplace_back(args: AA->getValue(N: 1));
3116
3117 for (const std::string &Arg :
3118 Args.getAllArgValues(Id: OPT_ftest_module_file_extension_EQ)) {
3119 std::string BlockName;
3120 unsigned MajorVersion;
3121 unsigned MinorVersion;
3122 bool Hashed;
3123 std::string UserInfo;
3124 if (parseTestModuleFileExtensionArg(Arg, BlockName, MajorVersion,
3125 MinorVersion, Hashed, UserInfo)) {
3126 Diags.Report(DiagID: diag::err_test_module_file_extension_format) << Arg;
3127
3128 continue;
3129 }
3130
3131 // Add the testing module file extension.
3132 Opts.ModuleFileExtensions.push_back(
3133 x: std::make_shared<TestModuleFileExtension>(
3134 args&: BlockName, args&: MajorVersion, args&: MinorVersion, args&: Hashed, args&: UserInfo));
3135 }
3136
3137 if (const Arg *A = Args.getLastArg(Ids: OPT_code_completion_at)) {
3138 Opts.CodeCompletionAt =
3139 ParsedSourceLocation::FromString(Str: A->getValue());
3140 if (Opts.CodeCompletionAt.FileName.empty()) {
3141 Diags.Report(DiagID: diag::err_drv_invalid_value)
3142 << A->getAsString(Args) << A->getValue();
3143 Diags.Report(DiagID: diag::note_command_line_code_loc_requirement);
3144 }
3145 }
3146
3147 Opts.Plugins = Args.getAllArgValues(Id: OPT_load);
3148 Opts.ASTDumpDecls = Args.hasArg(Ids: OPT_ast_dump, Ids: OPT_ast_dump_EQ);
3149 Opts.ASTDumpAll = Args.hasArg(Ids: OPT_ast_dump_all, Ids: OPT_ast_dump_all_EQ);
3150 // Only the -fmodule-file=<file> form.
3151 for (const auto *A : Args.filtered(Ids: OPT_fmodule_file)) {
3152 StringRef Val = A->getValue();
3153 if (!Val.contains(C: '='))
3154 Opts.ModuleFiles.push_back(x: std::string(Val));
3155 }
3156
3157 if (Opts.ProgramAction != frontend::GenerateModule && Opts.IsSystemModule)
3158 Diags.Report(DiagID: diag::err_drv_argument_only_allowed_with) << "-fsystem-module"
3159 << "-emit-module";
3160 if (Args.hasArg(Ids: OPT_fclangir) || Args.hasArg(Ids: OPT_emit_cir))
3161 Opts.UseClangIRPipeline = true;
3162
3163#if CLANG_ENABLE_CIR
3164 if (Args.hasArg(OPT_clangir_disable_passes))
3165 Opts.ClangIRDisablePasses = true;
3166
3167 if (Args.hasArg(OPT_clangir_disable_verifier))
3168 Opts.ClangIRDisableCIRVerifier = true;
3169#endif // CLANG_ENABLE_CIR
3170
3171 if (Args.hasArg(Ids: OPT_aux_target_cpu))
3172 Opts.AuxTargetCPU = std::string(Args.getLastArgValue(Id: OPT_aux_target_cpu));
3173 if (Args.hasArg(Ids: OPT_aux_target_feature))
3174 Opts.AuxTargetFeatures = Args.getAllArgValues(Id: OPT_aux_target_feature);
3175
3176 InputKind DashX(Language::Unknown);
3177 if (const Arg *A = Args.getLastArg(Ids: OPT_x)) {
3178 StringRef XValue = A->getValue();
3179
3180 // Parse suffixes:
3181 // '<lang>(-[{header-unit,user,system}-]header|[-module-map][-cpp-output])'.
3182 // FIXME: Supporting '<lang>-header-cpp-output' would be useful.
3183 bool Preprocessed = XValue.consume_back(Suffix: "-cpp-output");
3184 bool ModuleMap = XValue.consume_back(Suffix: "-module-map");
3185 // Detect and consume the header indicator.
3186 bool IsHeader =
3187 XValue != "precompiled-header" && XValue.consume_back(Suffix: "-header");
3188
3189 // If we have c++-{user,system}-header, that indicates a header unit input
3190 // likewise, if the user put -fmodule-header together with a header with an
3191 // absolute path (header-unit-header).
3192 InputKind::HeaderUnitKind HUK = InputKind::HeaderUnit_None;
3193 if (IsHeader || Preprocessed) {
3194 if (XValue.consume_back(Suffix: "-header-unit"))
3195 HUK = InputKind::HeaderUnit_Abs;
3196 else if (XValue.consume_back(Suffix: "-system"))
3197 HUK = InputKind::HeaderUnit_System;
3198 else if (XValue.consume_back(Suffix: "-user"))
3199 HUK = InputKind::HeaderUnit_User;
3200 }
3201
3202 // The value set by this processing is an un-preprocessed source which is
3203 // not intended to be a module map or header unit.
3204 IsHeaderFile = IsHeader && !Preprocessed && !ModuleMap &&
3205 HUK == InputKind::HeaderUnit_None;
3206
3207 // Principal languages.
3208 DashX = llvm::StringSwitch<InputKind>(XValue)
3209 .Case(S: "c", Value: Language::C)
3210 .Case(S: "cl", Value: Language::OpenCL)
3211 .Case(S: "clcpp", Value: Language::OpenCLCXX)
3212 .Case(S: "cuda", Value: Language::CUDA)
3213 .Case(S: "hip", Value: Language::HIP)
3214 .Case(S: "c++", Value: Language::CXX)
3215 .Case(S: "objective-c", Value: Language::ObjC)
3216 .Case(S: "objective-c++", Value: Language::ObjCXX)
3217 .Case(S: "hlsl", Value: Language::HLSL)
3218 .Default(Value: Language::Unknown);
3219
3220 // "objc[++]-cpp-output" is an acceptable synonym for
3221 // "objective-c[++]-cpp-output".
3222 if (DashX.isUnknown() && Preprocessed && !IsHeaderFile && !ModuleMap &&
3223 HUK == InputKind::HeaderUnit_None)
3224 DashX = llvm::StringSwitch<InputKind>(XValue)
3225 .Case(S: "objc", Value: Language::ObjC)
3226 .Case(S: "objc++", Value: Language::ObjCXX)
3227 .Default(Value: Language::Unknown);
3228
3229 // Some special cases cannot be combined with suffixes.
3230 if (DashX.isUnknown() && !Preprocessed && !IsHeaderFile && !ModuleMap &&
3231 HUK == InputKind::HeaderUnit_None)
3232 DashX = llvm::StringSwitch<InputKind>(XValue)
3233 .Case(S: "cpp-output", Value: InputKind(Language::C).getPreprocessed())
3234 .Case(S: "assembler-with-cpp", Value: Language::Asm)
3235 .Cases(CaseStrings: {"ast", "pcm", "precompiled-header"},
3236 Value: InputKind(Language::Unknown, InputKind::Precompiled))
3237 .Case(S: "ir", Value: Language::LLVM_IR)
3238 .Case(S: "cir", Value: Language::CIR)
3239 .Default(Value: Language::Unknown);
3240
3241 if (DashX.isUnknown())
3242 Diags.Report(DiagID: diag::err_drv_invalid_value)
3243 << A->getAsString(Args) << A->getValue();
3244
3245 if (Preprocessed)
3246 DashX = DashX.getPreprocessed();
3247 // A regular header is considered mutually exclusive with a header unit.
3248 if (HUK != InputKind::HeaderUnit_None) {
3249 DashX = DashX.withHeaderUnit(HU: HUK);
3250 IsHeaderFile = true;
3251 } else if (IsHeaderFile)
3252 DashX = DashX.getHeader();
3253 if (ModuleMap)
3254 DashX = DashX.withFormat(F: InputKind::ModuleMap);
3255 }
3256
3257 // '-' is the default input if none is given.
3258 std::vector<std::string> Inputs = Args.getAllArgValues(Id: OPT_INPUT);
3259 Opts.Inputs.clear();
3260 if (Inputs.empty())
3261 Inputs.push_back(x: "-");
3262
3263 if (DashX.getHeaderUnitKind() != InputKind::HeaderUnit_None &&
3264 Inputs.size() > 1)
3265 Diags.Report(DiagID: diag::err_drv_header_unit_extra_inputs) << Inputs[1];
3266
3267 for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
3268 InputKind IK = DashX;
3269 if (IK.isUnknown()) {
3270 IK = FrontendOptions::getInputKindForExtension(
3271 Extension: StringRef(Inputs[i]).rsplit(Separator: '.').second);
3272 // FIXME: Warn on this?
3273 if (IK.isUnknown())
3274 IK = Language::C;
3275 // FIXME: Remove this hack.
3276 if (i == 0)
3277 DashX = IK;
3278 }
3279
3280 bool IsSystem = false;
3281
3282 // The -emit-module action implicitly takes a module map.
3283 if (Opts.ProgramAction == frontend::GenerateModule &&
3284 IK.getFormat() == InputKind::Source) {
3285 IK = IK.withFormat(F: InputKind::ModuleMap);
3286 IsSystem = Opts.IsSystemModule;
3287 }
3288
3289 Opts.Inputs.emplace_back(Args: std::move(Inputs[i]), Args&: IK, Args&: IsSystem);
3290 }
3291
3292 Opts.DashX = DashX;
3293
3294 return Diags.getNumErrors() == NumErrorsBefore;
3295}
3296
3297static void GenerateHeaderSearchArgs(const HeaderSearchOptions &Opts,
3298 ArgumentConsumer Consumer) {
3299 const HeaderSearchOptions *HeaderSearchOpts = &Opts;
3300#define HEADER_SEARCH_OPTION_WITH_MARSHALLING(...) \
3301 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
3302#include "clang/Options/Options.inc"
3303#undef HEADER_SEARCH_OPTION_WITH_MARSHALLING
3304
3305 if (Opts.UseLibcxx)
3306 GenerateArg(Consumer, OptSpecifier: OPT_stdlib_EQ, Value: "libc++");
3307
3308 for (const auto &File : Opts.PrebuiltModuleFiles)
3309 GenerateArg(Consumer, OptSpecifier: OPT_fmodule_file, Value: File.first + "=" + File.second);
3310
3311 for (const auto &Path : Opts.PrebuiltModulePaths)
3312 GenerateArg(Consumer, OptSpecifier: OPT_fprebuilt_module_path, Value: Path);
3313
3314 for (const auto &Macro : Opts.ModulesIgnoreMacros)
3315 GenerateArg(Consumer, OptSpecifier: OPT_fmodules_ignore_macro, Value: Macro.val());
3316
3317 auto Matches = [](const HeaderSearchOptions::Entry &Entry,
3318 llvm::ArrayRef<frontend::IncludeDirGroup> Groups,
3319 std::optional<bool> IsFramework,
3320 std::optional<bool> IgnoreSysRoot) {
3321 return llvm::is_contained(Range&: Groups, Element: Entry.Group) &&
3322 (!IsFramework || (Entry.IsFramework == *IsFramework)) &&
3323 (!IgnoreSysRoot || (Entry.IgnoreSysRoot == *IgnoreSysRoot));
3324 };
3325
3326 auto It = Opts.UserEntries.begin();
3327 auto End = Opts.UserEntries.end();
3328
3329 // Add -I... and -F... options in order.
3330 for (; It < End && Matches(*It, {frontend::Angled}, std::nullopt, true);
3331 ++It) {
3332 OptSpecifier Opt = [It, Matches]() {
3333 if (Matches(*It, frontend::Angled, true, true))
3334 return OPT_F;
3335 if (Matches(*It, frontend::Angled, false, true))
3336 return OPT_I;
3337 llvm_unreachable("Unexpected HeaderSearchOptions::Entry.");
3338 }();
3339
3340 GenerateArg(Consumer, OptSpecifier: Opt, Value: It->Path);
3341 }
3342
3343 // Note: some paths that came from "[-iprefix=xx] -iwithprefixbefore=yy" may
3344 // have already been generated as "-I[xx]yy". If that's the case, their
3345 // position on command line was such that this has no semantic impact on
3346 // include paths.
3347 for (; It < End &&
3348 Matches(*It, {frontend::After, frontend::Angled}, false, true);
3349 ++It) {
3350 OptSpecifier Opt =
3351 It->Group == frontend::After ? OPT_iwithprefix : OPT_iwithprefixbefore;
3352 GenerateArg(Consumer, OptSpecifier: Opt, Value: It->Path);
3353 }
3354
3355 // Note: Some paths that came from "-idirafter=xxyy" may have already been
3356 // generated as "-iwithprefix=xxyy". If that's the case, their position on
3357 // command line was such that this has no semantic impact on include paths.
3358 for (; It < End && Matches(*It, {frontend::After}, false, true); ++It)
3359 GenerateArg(Consumer, OptSpecifier: OPT_idirafter, Value: It->Path);
3360 for (; It < End && Matches(*It, {frontend::Quoted}, false, true); ++It)
3361 GenerateArg(Consumer, OptSpecifier: OPT_iquote, Value: It->Path);
3362 for (; It < End && Matches(*It, {frontend::System}, false, std::nullopt);
3363 ++It)
3364 GenerateArg(Consumer, OptSpecifier: It->IgnoreSysRoot ? OPT_isystem : OPT_iwithsysroot,
3365 Value: It->Path);
3366 for (; It < End && Matches(*It, {frontend::System}, true, true); ++It)
3367 GenerateArg(Consumer, OptSpecifier: OPT_iframework, Value: It->Path);
3368 for (; It < End && Matches(*It, {frontend::System}, true, false); ++It)
3369 GenerateArg(Consumer, OptSpecifier: OPT_iframeworkwithsysroot, Value: It->Path);
3370
3371 // Add the paths for the various language specific isystem flags.
3372 for (; It < End && Matches(*It, {frontend::CSystem}, false, true); ++It)
3373 GenerateArg(Consumer, OptSpecifier: OPT_c_isystem, Value: It->Path);
3374 for (; It < End && Matches(*It, {frontend::CXXSystem}, false, true); ++It)
3375 GenerateArg(Consumer, OptSpecifier: OPT_cxx_isystem, Value: It->Path);
3376 for (; It < End && Matches(*It, {frontend::ObjCSystem}, false, true); ++It)
3377 GenerateArg(Consumer, OptSpecifier: OPT_objc_isystem, Value: It->Path);
3378 for (; It < End && Matches(*It, {frontend::ObjCXXSystem}, false, true); ++It)
3379 GenerateArg(Consumer, OptSpecifier: OPT_objcxx_isystem, Value: It->Path);
3380
3381 // Add the internal paths from a driver that detects standard include paths.
3382 // Note: Some paths that came from "-internal-isystem" arguments may have
3383 // already been generated as "-isystem". If that's the case, their position on
3384 // command line was such that this has no semantic impact on include paths.
3385 for (; It < End &&
3386 Matches(*It, {frontend::System, frontend::ExternCSystem}, false, true);
3387 ++It) {
3388 OptSpecifier Opt = It->Group == frontend::System
3389 ? OPT_internal_isystem
3390 : OPT_internal_externc_isystem;
3391 GenerateArg(Consumer, OptSpecifier: Opt, Value: It->Path);
3392 }
3393 for (; It < End && Matches(*It, {frontend::System}, true, true); ++It)
3394 GenerateArg(Consumer, OptSpecifier: OPT_internal_iframework, Value: It->Path);
3395
3396 assert(It == End && "Unhandled HeaderSearchOption::Entry.");
3397
3398 // Add the path prefixes which are implicitly treated as being system headers.
3399 for (const auto &P : Opts.SystemHeaderPrefixes) {
3400 OptSpecifier Opt = P.IsSystemHeader ? OPT_system_header_prefix
3401 : OPT_no_system_header_prefix;
3402 GenerateArg(Consumer, OptSpecifier: Opt, Value: P.Prefix);
3403 }
3404
3405 for (const std::string &F : Opts.VFSOverlayFiles)
3406 GenerateArg(Consumer, OptSpecifier: OPT_ivfsoverlay, Value: F);
3407}
3408
3409static bool ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args,
3410 DiagnosticsEngine &Diags) {
3411 unsigned NumErrorsBefore = Diags.getNumErrors();
3412
3413 HeaderSearchOptions *HeaderSearchOpts = &Opts;
3414
3415#define HEADER_SEARCH_OPTION_WITH_MARSHALLING(...) \
3416 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
3417#include "clang/Options/Options.inc"
3418#undef HEADER_SEARCH_OPTION_WITH_MARSHALLING
3419
3420 if (const Arg *A = Args.getLastArg(Ids: OPT_stdlib_EQ))
3421 Opts.UseLibcxx = (strcmp(s1: A->getValue(), s2: "libc++") == 0);
3422
3423 // Only the -fmodule-file=<name>=<file> form.
3424 for (const auto *A : Args.filtered(Ids: OPT_fmodule_file)) {
3425 StringRef Val = A->getValue();
3426 if (Val.contains(C: '=')) {
3427 auto Split = Val.split(Separator: '=');
3428 Opts.PrebuiltModuleFiles.insert_or_assign(
3429 k: std::string(Split.first), obj: std::string(Split.second));
3430 }
3431 }
3432 for (const auto *A : Args.filtered(Ids: OPT_fprebuilt_module_path))
3433 Opts.AddPrebuiltModulePath(Name: A->getValue());
3434
3435 for (const auto *A : Args.filtered(Ids: OPT_fmodules_ignore_macro)) {
3436 StringRef MacroDef = A->getValue();
3437 Opts.ModulesIgnoreMacros.insert(
3438 X: llvm::CachedHashString(MacroDef.split(Separator: '=').first));
3439 }
3440
3441 // Add -I... and -F... options in order.
3442 bool IsSysrootSpecified =
3443 Args.hasArg(Ids: OPT__sysroot_EQ) || Args.hasArg(Ids: OPT_isysroot);
3444
3445 // Expand a leading `=` to the sysroot if one was passed (and it's not a
3446 // framework flag).
3447 auto PrefixHeaderPath = [IsSysrootSpecified,
3448 &Opts](const llvm::opt::Arg *A,
3449 bool IsFramework = false) -> std::string {
3450 assert(A->getNumValues() && "Unexpected empty search path flag!");
3451 if (IsSysrootSpecified && !IsFramework && A->getValue()[0] == '=') {
3452 SmallString<32> Buffer;
3453 llvm::sys::path::append(path&: Buffer, a: Opts.Sysroot,
3454 b: llvm::StringRef(A->getValue()).substr(Start: 1));
3455 return std::string(Buffer);
3456 }
3457 return A->getValue();
3458 };
3459
3460 for (const auto *A : Args.filtered(Ids: OPT_I, Ids: OPT_F)) {
3461 bool IsFramework = A->getOption().matches(ID: OPT_F);
3462 Opts.AddPath(Path: PrefixHeaderPath(A, IsFramework), Group: frontend::Angled,
3463 IsFramework, /*IgnoreSysroot=*/IgnoreSysRoot: true);
3464 }
3465
3466 // Add -iprefix/-iwithprefix/-iwithprefixbefore options.
3467 StringRef Prefix = ""; // FIXME: This isn't the correct default prefix.
3468 for (const auto *A :
3469 Args.filtered(Ids: OPT_iprefix, Ids: OPT_iwithprefix, Ids: OPT_iwithprefixbefore)) {
3470 if (A->getOption().matches(ID: OPT_iprefix))
3471 Prefix = A->getValue();
3472 else if (A->getOption().matches(ID: OPT_iwithprefix))
3473 Opts.AddPath(Path: Prefix.str() + A->getValue(), Group: frontend::After, IsFramework: false, IgnoreSysRoot: true);
3474 else
3475 Opts.AddPath(Path: Prefix.str() + A->getValue(), Group: frontend::Angled, IsFramework: false, IgnoreSysRoot: true);
3476 }
3477
3478 for (const auto *A : Args.filtered(Ids: OPT_idirafter))
3479 Opts.AddPath(Path: PrefixHeaderPath(A), Group: frontend::After, IsFramework: false, IgnoreSysRoot: true);
3480 for (const auto *A : Args.filtered(Ids: OPT_iquote))
3481 Opts.AddPath(Path: PrefixHeaderPath(A), Group: frontend::Quoted, IsFramework: false, IgnoreSysRoot: true);
3482
3483 for (const auto *A : Args.filtered(Ids: OPT_isystem, Ids: OPT_iwithsysroot)) {
3484 if (A->getOption().matches(ID: OPT_iwithsysroot)) {
3485 Opts.AddPath(Path: A->getValue(), Group: frontend::System, IsFramework: false,
3486 /*IgnoreSysRoot=*/false);
3487 continue;
3488 }
3489 Opts.AddPath(Path: PrefixHeaderPath(A), Group: frontend::System, IsFramework: false, IgnoreSysRoot: true);
3490 }
3491 for (const auto *A : Args.filtered(Ids: OPT_iframework))
3492 Opts.AddPath(Path: A->getValue(), Group: frontend::System, IsFramework: true, IgnoreSysRoot: true);
3493 for (const auto *A : Args.filtered(Ids: OPT_iframeworkwithsysroot))
3494 Opts.AddPath(Path: A->getValue(), Group: frontend::System, /*IsFramework=*/true,
3495 /*IgnoreSysRoot=*/false);
3496
3497 // Add the paths for the various language specific isystem flags.
3498 for (const auto *A : Args.filtered(Ids: OPT_c_isystem))
3499 Opts.AddPath(Path: A->getValue(), Group: frontend::CSystem, IsFramework: false, IgnoreSysRoot: true);
3500 for (const auto *A : Args.filtered(Ids: OPT_cxx_isystem))
3501 Opts.AddPath(Path: A->getValue(), Group: frontend::CXXSystem, IsFramework: false, IgnoreSysRoot: true);
3502 for (const auto *A : Args.filtered(Ids: OPT_objc_isystem))
3503 Opts.AddPath(Path: A->getValue(), Group: frontend::ObjCSystem, IsFramework: false,IgnoreSysRoot: true);
3504 for (const auto *A : Args.filtered(Ids: OPT_objcxx_isystem))
3505 Opts.AddPath(Path: A->getValue(), Group: frontend::ObjCXXSystem, IsFramework: false, IgnoreSysRoot: true);
3506
3507 // Add the internal paths from a driver that detects standard include paths.
3508 for (const auto *A :
3509 Args.filtered(Ids: OPT_internal_isystem, Ids: OPT_internal_externc_isystem)) {
3510 frontend::IncludeDirGroup Group = frontend::System;
3511 if (A->getOption().matches(ID: OPT_internal_externc_isystem))
3512 Group = frontend::ExternCSystem;
3513 Opts.AddPath(Path: A->getValue(), Group, IsFramework: false, IgnoreSysRoot: true);
3514 }
3515 for (const auto *A : Args.filtered(Ids: OPT_internal_iframework))
3516 Opts.AddPath(Path: A->getValue(), Group: frontend::System, IsFramework: true, IgnoreSysRoot: true);
3517
3518 // Add the path prefixes which are implicitly treated as being system headers.
3519 for (const auto *A :
3520 Args.filtered(Ids: OPT_system_header_prefix, Ids: OPT_no_system_header_prefix))
3521 Opts.AddSystemHeaderPrefix(
3522 Prefix: A->getValue(), IsSystemHeader: A->getOption().matches(ID: OPT_system_header_prefix));
3523
3524 for (const auto *A : Args.filtered(Ids: OPT_ivfsoverlay, Ids: OPT_vfsoverlay))
3525 Opts.AddVFSOverlayFile(Name: A->getValue());
3526
3527 return Diags.getNumErrors() == NumErrorsBefore;
3528}
3529
3530static void GenerateAPINotesArgs(const APINotesOptions &Opts,
3531 ArgumentConsumer Consumer) {
3532 if (!Opts.SwiftVersion.empty())
3533 GenerateArg(Consumer, OptSpecifier: OPT_fapinotes_swift_version,
3534 Value: Opts.SwiftVersion.getAsString());
3535
3536 for (const auto &Path : Opts.ModuleSearchPaths)
3537 GenerateArg(Consumer, OptSpecifier: OPT_iapinotes_modules, Value: Path);
3538}
3539
3540static void ParseAPINotesArgs(APINotesOptions &Opts, ArgList &Args,
3541 DiagnosticsEngine &diags) {
3542 if (const Arg *A = Args.getLastArg(Ids: OPT_fapinotes_swift_version)) {
3543 if (Opts.SwiftVersion.tryParse(string: A->getValue()))
3544 diags.Report(DiagID: diag::err_drv_invalid_value)
3545 << A->getAsString(Args) << A->getValue();
3546 }
3547 for (const Arg *A : Args.filtered(Ids: OPT_iapinotes_modules))
3548 Opts.ModuleSearchPaths.push_back(x: A->getValue());
3549}
3550
3551static void GeneratePointerAuthArgs(const LangOptions &Opts,
3552 ArgumentConsumer Consumer) {
3553 if (Opts.PointerAuthIntrinsics)
3554 GenerateArg(Consumer, OptSpecifier: OPT_fptrauth_intrinsics);
3555 if (Opts.PointerAuthCalls)
3556 GenerateArg(Consumer, OptSpecifier: OPT_fptrauth_calls);
3557 if (Opts.PointerAuthReturns)
3558 GenerateArg(Consumer, OptSpecifier: OPT_fptrauth_returns);
3559 if (Opts.PointerAuthIndirectGotos)
3560 GenerateArg(Consumer, OptSpecifier: OPT_fptrauth_indirect_gotos);
3561 if (Opts.PointerAuthAuthTraps)
3562 GenerateArg(Consumer, OptSpecifier: OPT_fptrauth_auth_traps);
3563 if (Opts.PointerAuthVTPtrAddressDiscrimination)
3564 GenerateArg(Consumer, OptSpecifier: OPT_fptrauth_vtable_pointer_address_discrimination);
3565 if (Opts.PointerAuthVTPtrTypeDiscrimination)
3566 GenerateArg(Consumer, OptSpecifier: OPT_fptrauth_vtable_pointer_type_discrimination);
3567 if (Opts.PointerAuthTypeInfoVTPtrDiscrimination)
3568 GenerateArg(Consumer, OptSpecifier: OPT_fptrauth_type_info_vtable_pointer_discrimination);
3569 if (Opts.PointerAuthFunctionTypeDiscrimination)
3570 GenerateArg(Consumer, OptSpecifier: OPT_fptrauth_function_pointer_type_discrimination);
3571 if (Opts.PointerAuthInitFini)
3572 GenerateArg(Consumer, OptSpecifier: OPT_fptrauth_init_fini);
3573 if (Opts.PointerAuthInitFiniAddressDiscrimination)
3574 GenerateArg(Consumer, OptSpecifier: OPT_fptrauth_init_fini_address_discrimination);
3575 if (Opts.PointerAuthELFGOT)
3576 GenerateArg(Consumer, OptSpecifier: OPT_fptrauth_elf_got);
3577 if (Opts.AArch64JumpTableHardening)
3578 GenerateArg(Consumer, OptSpecifier: OPT_faarch64_jump_table_hardening);
3579 if (Opts.PointerAuthObjcIsa)
3580 GenerateArg(Consumer, OptSpecifier: OPT_fptrauth_objc_isa);
3581 if (Opts.PointerAuthObjcInterfaceSel)
3582 GenerateArg(Consumer, OptSpecifier: OPT_fptrauth_objc_interface_sel);
3583 if (Opts.PointerAuthObjcClassROPointers)
3584 GenerateArg(Consumer, OptSpecifier: OPT_fptrauth_objc_class_ro);
3585 if (Opts.PointerAuthBlockDescriptorPointers)
3586 GenerateArg(Consumer, OptSpecifier: OPT_fptrauth_block_descriptor_pointers);
3587}
3588
3589static void ParsePointerAuthArgs(LangOptions &Opts, ArgList &Args,
3590 DiagnosticsEngine &Diags) {
3591 Opts.PointerAuthIntrinsics = Args.hasArg(Ids: OPT_fptrauth_intrinsics);
3592 Opts.PointerAuthCalls = Args.hasArg(Ids: OPT_fptrauth_calls);
3593 Opts.PointerAuthReturns = Args.hasArg(Ids: OPT_fptrauth_returns);
3594 Opts.PointerAuthIndirectGotos = Args.hasArg(Ids: OPT_fptrauth_indirect_gotos);
3595 Opts.PointerAuthAuthTraps = Args.hasArg(Ids: OPT_fptrauth_auth_traps);
3596 Opts.PointerAuthVTPtrAddressDiscrimination =
3597 Args.hasArg(Ids: OPT_fptrauth_vtable_pointer_address_discrimination);
3598 Opts.PointerAuthVTPtrTypeDiscrimination =
3599 Args.hasArg(Ids: OPT_fptrauth_vtable_pointer_type_discrimination);
3600 Opts.PointerAuthTypeInfoVTPtrDiscrimination =
3601 Args.hasArg(Ids: OPT_fptrauth_type_info_vtable_pointer_discrimination);
3602 Opts.PointerAuthFunctionTypeDiscrimination =
3603 Args.hasArg(Ids: OPT_fptrauth_function_pointer_type_discrimination);
3604 Opts.PointerAuthInitFini = Args.hasArg(Ids: OPT_fptrauth_init_fini);
3605 Opts.PointerAuthInitFiniAddressDiscrimination =
3606 Args.hasArg(Ids: OPT_fptrauth_init_fini_address_discrimination);
3607 Opts.PointerAuthELFGOT = Args.hasArg(Ids: OPT_fptrauth_elf_got);
3608 Opts.AArch64JumpTableHardening =
3609 Args.hasArg(Ids: OPT_faarch64_jump_table_hardening);
3610 Opts.PointerAuthBlockDescriptorPointers =
3611 Args.hasArg(Ids: OPT_fptrauth_block_descriptor_pointers);
3612 Opts.PointerAuthObjcIsa = Args.hasArg(Ids: OPT_fptrauth_objc_isa);
3613 Opts.PointerAuthObjcClassROPointers = Args.hasArg(Ids: OPT_fptrauth_objc_class_ro);
3614 Opts.PointerAuthObjcInterfaceSel =
3615 Args.hasArg(Ids: OPT_fptrauth_objc_interface_sel);
3616
3617 if (Opts.PointerAuthObjcInterfaceSel)
3618 Opts.PointerAuthObjcInterfaceSelKey =
3619 static_cast<unsigned>(PointerAuthSchema::ARM8_3Key::ASDB);
3620}
3621
3622/// Check if input file kind and language standard are compatible.
3623static bool IsInputCompatibleWithStandard(InputKind IK,
3624 const LangStandard &S) {
3625 switch (IK.getLanguage()) {
3626 case Language::Unknown:
3627 case Language::LLVM_IR:
3628 case Language::CIR:
3629 llvm_unreachable("should not parse language flags for this input");
3630
3631 case Language::C:
3632 case Language::ObjC:
3633 return S.getLanguage() == Language::C;
3634
3635 case Language::OpenCL:
3636 return S.getLanguage() == Language::OpenCL ||
3637 S.getLanguage() == Language::OpenCLCXX;
3638
3639 case Language::OpenCLCXX:
3640 return S.getLanguage() == Language::OpenCLCXX;
3641
3642 case Language::CXX:
3643 case Language::ObjCXX:
3644 return S.getLanguage() == Language::CXX;
3645
3646 case Language::CUDA:
3647 // FIXME: What -std= values should be permitted for CUDA compilations?
3648 return S.getLanguage() == Language::CUDA ||
3649 S.getLanguage() == Language::CXX;
3650
3651 case Language::HIP:
3652 return S.getLanguage() == Language::CXX || S.getLanguage() == Language::HIP;
3653
3654 case Language::Asm:
3655 // Accept (and ignore) all -std= values.
3656 // FIXME: The -std= value is not ignored; it affects the tokenization
3657 // and preprocessing rules if we're preprocessing this asm input.
3658 return true;
3659
3660 case Language::HLSL:
3661 return S.getLanguage() == Language::HLSL;
3662 }
3663
3664 llvm_unreachable("unexpected input language");
3665}
3666
3667/// Get language name for given input kind.
3668static StringRef GetInputKindName(InputKind IK) {
3669 switch (IK.getLanguage()) {
3670 case Language::C:
3671 return "C";
3672 case Language::ObjC:
3673 return "Objective-C";
3674 case Language::CXX:
3675 return "C++";
3676 case Language::ObjCXX:
3677 return "Objective-C++";
3678 case Language::OpenCL:
3679 return "OpenCL";
3680 case Language::OpenCLCXX:
3681 return "C++ for OpenCL";
3682 case Language::CUDA:
3683 return "CUDA";
3684 case Language::HIP:
3685 return "HIP";
3686
3687 case Language::Asm:
3688 return "Asm";
3689 case Language::LLVM_IR:
3690 return "LLVM IR";
3691 case Language::CIR:
3692 return "Clang IR";
3693
3694 case Language::HLSL:
3695 return "HLSL";
3696
3697 case Language::Unknown:
3698 break;
3699 }
3700 llvm_unreachable("unknown input language");
3701}
3702
3703void CompilerInvocationBase::GenerateLangArgs(const LangOptions &Opts,
3704 ArgumentConsumer Consumer,
3705 const llvm::Triple &T,
3706 InputKind IK) {
3707 if (IK.getFormat() == InputKind::Precompiled ||
3708 IK.getLanguage() == Language::LLVM_IR ||
3709 IK.getLanguage() == Language::CIR) {
3710 if (Opts.ObjCAutoRefCount)
3711 GenerateArg(Consumer, OptSpecifier: OPT_fobjc_arc);
3712 if (Opts.PICLevel != 0)
3713 GenerateArg(Consumer, OptSpecifier: OPT_pic_level, Value: Twine(Opts.PICLevel));
3714 if (Opts.PIE)
3715 GenerateArg(Consumer, OptSpecifier: OPT_pic_is_pie);
3716 for (StringRef Sanitizer : serializeSanitizerKinds(S: Opts.Sanitize))
3717 GenerateArg(Consumer, OptSpecifier: OPT_fsanitize_EQ, Value: Sanitizer);
3718 for (StringRef Sanitizer :
3719 serializeSanitizerKinds(S: Opts.UBSanFeatureIgnoredSanitize))
3720 GenerateArg(Consumer, OptSpecifier: OPT_fsanitize_ignore_for_ubsan_feature_EQ,
3721 Value: Sanitizer);
3722
3723 return;
3724 }
3725
3726 OptSpecifier StdOpt;
3727 switch (Opts.LangStd) {
3728 case LangStandard::lang_opencl10:
3729 case LangStandard::lang_opencl11:
3730 case LangStandard::lang_opencl12:
3731 case LangStandard::lang_opencl20:
3732 case LangStandard::lang_opencl30:
3733 case LangStandard::lang_openclcpp10:
3734 case LangStandard::lang_openclcpp2021:
3735 StdOpt = OPT_cl_std_EQ;
3736 break;
3737 default:
3738 StdOpt = OPT_std_EQ;
3739 break;
3740 }
3741
3742 auto LangStandard = LangStandard::getLangStandardForKind(K: Opts.LangStd);
3743 GenerateArg(Consumer, OptSpecifier: StdOpt, Value: LangStandard.getName());
3744
3745 if (Opts.IncludeDefaultHeader)
3746 GenerateArg(Consumer, OptSpecifier: OPT_finclude_default_header);
3747 if (Opts.DeclareOpenCLBuiltins)
3748 GenerateArg(Consumer, OptSpecifier: OPT_fdeclare_opencl_builtins);
3749
3750 const LangOptions *LangOpts = &Opts;
3751
3752#define LANG_OPTION_WITH_MARSHALLING(...) \
3753 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
3754#include "clang/Options/Options.inc"
3755#undef LANG_OPTION_WITH_MARSHALLING
3756
3757 // The '-fcf-protection=' option is generated by CodeGenOpts generator.
3758
3759 if (Opts.ObjC) {
3760 GenerateArg(Consumer, OptSpecifier: OPT_fobjc_runtime_EQ, Value: Opts.ObjCRuntime.getAsString());
3761
3762 if (Opts.GC == LangOptions::GCOnly)
3763 GenerateArg(Consumer, OptSpecifier: OPT_fobjc_gc_only);
3764 else if (Opts.GC == LangOptions::HybridGC)
3765 GenerateArg(Consumer, OptSpecifier: OPT_fobjc_gc);
3766 else if (Opts.ObjCAutoRefCount == 1)
3767 GenerateArg(Consumer, OptSpecifier: OPT_fobjc_arc);
3768
3769 if (Opts.ObjCWeakRuntime)
3770 GenerateArg(Consumer, OptSpecifier: OPT_fobjc_runtime_has_weak);
3771
3772 if (Opts.ObjCWeak)
3773 GenerateArg(Consumer, OptSpecifier: OPT_fobjc_weak);
3774
3775 if (Opts.ObjCSubscriptingLegacyRuntime)
3776 GenerateArg(Consumer, OptSpecifier: OPT_fobjc_subscripting_legacy_runtime);
3777 }
3778
3779 if (Opts.GNUCVersion != 0) {
3780 unsigned Major = Opts.GNUCVersion / 100 / 100;
3781 unsigned Minor = (Opts.GNUCVersion / 100) % 100;
3782 unsigned Patch = Opts.GNUCVersion % 100;
3783 GenerateArg(Consumer, OptSpecifier: OPT_fgnuc_version_EQ,
3784 Value: Twine(Major) + "." + Twine(Minor) + "." + Twine(Patch));
3785 }
3786
3787 if (Opts.IgnoreXCOFFVisibility)
3788 GenerateArg(Consumer, OptSpecifier: OPT_mignore_xcoff_visibility);
3789
3790 if (Opts.SignedOverflowBehavior == LangOptions::SOB_Trapping) {
3791 GenerateArg(Consumer, OptSpecifier: OPT_ftrapv);
3792 GenerateArg(Consumer, OptSpecifier: OPT_ftrapv_handler, Value: Opts.OverflowHandler);
3793 } else if (Opts.SignedOverflowBehavior == LangOptions::SOB_Defined) {
3794 GenerateArg(Consumer, OptSpecifier: OPT_fwrapv);
3795 }
3796 if (Opts.PointerOverflowDefined)
3797 GenerateArg(Consumer, OptSpecifier: OPT_fwrapv_pointer);
3798
3799 if (Opts.MSCompatibilityVersion != 0) {
3800 unsigned Major = Opts.MSCompatibilityVersion / 10000000;
3801 unsigned Minor = (Opts.MSCompatibilityVersion / 100000) % 100;
3802 unsigned Subminor = Opts.MSCompatibilityVersion % 100000;
3803 GenerateArg(Consumer, OptSpecifier: OPT_fms_compatibility_version,
3804 Value: Twine(Major) + "." + Twine(Minor) + "." + Twine(Subminor));
3805 }
3806
3807 if ((!Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus17 && !Opts.C23) ||
3808 T.isOSzOS()) {
3809 if (!Opts.Trigraphs)
3810 GenerateArg(Consumer, OptSpecifier: OPT_fno_trigraphs);
3811 } else {
3812 if (Opts.Trigraphs)
3813 GenerateArg(Consumer, OptSpecifier: OPT_ftrigraphs);
3814 }
3815
3816 if (T.isOSzOS() && !Opts.ZOSExt)
3817 GenerateArg(Consumer, OptSpecifier: OPT_fno_zos_extensions);
3818 else if (Opts.ZOSExt)
3819 GenerateArg(Consumer, OptSpecifier: OPT_fzos_extensions);
3820
3821 if (Opts.Blocks && !(Opts.OpenCL && Opts.OpenCLVersion == 200))
3822 GenerateArg(Consumer, OptSpecifier: OPT_fblocks);
3823
3824 if (Opts.ConvergentFunctions)
3825 GenerateArg(Consumer, OptSpecifier: OPT_fconvergent_functions);
3826 else
3827 GenerateArg(Consumer, OptSpecifier: OPT_fno_convergent_functions);
3828
3829 if (Opts.NoBuiltin && !Opts.Freestanding)
3830 GenerateArg(Consumer, OptSpecifier: OPT_fno_builtin);
3831
3832 if (!Opts.NoBuiltin)
3833 for (const auto &Func : Opts.NoBuiltinFuncs)
3834 GenerateArg(Consumer, OptSpecifier: OPT_fno_builtin_, Value: Func);
3835
3836 if (Opts.LongDoubleSize == 128)
3837 GenerateArg(Consumer, OptSpecifier: OPT_mlong_double_128);
3838 else if (Opts.LongDoubleSize == 64)
3839 GenerateArg(Consumer, OptSpecifier: OPT_mlong_double_64);
3840 else if (Opts.LongDoubleSize == 80)
3841 GenerateArg(Consumer, OptSpecifier: OPT_mlong_double_80);
3842
3843 // Not generating '-mrtd', it's just an alias for '-fdefault-calling-conv='.
3844
3845 // OpenMP was requested via '-fopenmp', not implied by '-fopenmp-simd' or
3846 // '-fopenmp-targets='.
3847 if (Opts.OpenMP && !Opts.OpenMPSimd) {
3848 GenerateArg(Consumer, OptSpecifier: OPT_fopenmp);
3849
3850 if (Opts.OpenMP != 51)
3851 GenerateArg(Consumer, OptSpecifier: OPT_fopenmp_version_EQ, Value: Twine(Opts.OpenMP));
3852
3853 if (!Opts.OpenMPUseTLS)
3854 GenerateArg(Consumer, OptSpecifier: OPT_fnoopenmp_use_tls);
3855
3856 if (Opts.OpenMPIsTargetDevice)
3857 GenerateArg(Consumer, OptSpecifier: OPT_fopenmp_is_target_device);
3858
3859 if (Opts.OpenMPIRBuilder)
3860 GenerateArg(Consumer, OptSpecifier: OPT_fopenmp_enable_irbuilder);
3861 }
3862
3863 if (Opts.OpenMPSimd) {
3864 GenerateArg(Consumer, OptSpecifier: OPT_fopenmp_simd);
3865
3866 if (Opts.OpenMP != 51)
3867 GenerateArg(Consumer, OptSpecifier: OPT_fopenmp_version_EQ, Value: Twine(Opts.OpenMP));
3868 }
3869
3870 if (Opts.OpenMPThreadSubscription)
3871 GenerateArg(Consumer, OptSpecifier: OPT_fopenmp_assume_threads_oversubscription);
3872
3873 if (Opts.OpenMPTeamSubscription)
3874 GenerateArg(Consumer, OptSpecifier: OPT_fopenmp_assume_teams_oversubscription);
3875
3876 if (Opts.OpenMPTargetDebug != 0)
3877 GenerateArg(Consumer, OptSpecifier: OPT_fopenmp_target_debug_EQ,
3878 Value: Twine(Opts.OpenMPTargetDebug));
3879
3880 if (Opts.OpenMPCUDANumSMs != 0)
3881 GenerateArg(Consumer, OptSpecifier: OPT_fopenmp_cuda_number_of_sm_EQ,
3882 Value: Twine(Opts.OpenMPCUDANumSMs));
3883
3884 if (Opts.OpenMPCUDABlocksPerSM != 0)
3885 GenerateArg(Consumer, OptSpecifier: OPT_fopenmp_cuda_blocks_per_sm_EQ,
3886 Value: Twine(Opts.OpenMPCUDABlocksPerSM));
3887
3888 if (Opts.OpenMPCUDAReductionBufNum != 1024)
3889 GenerateArg(Consumer, OptSpecifier: OPT_fopenmp_cuda_teams_reduction_recs_num_EQ,
3890 Value: Twine(Opts.OpenMPCUDAReductionBufNum));
3891
3892 if (!Opts.OMPTargetTriples.empty()) {
3893 std::string Targets;
3894 llvm::raw_string_ostream OS(Targets);
3895 llvm::interleave(
3896 c: Opts.OMPTargetTriples, os&: OS,
3897 each_fn: [&OS](const llvm::Triple &T) { OS << T.str(); }, separator: ",");
3898 GenerateArg(Consumer, OptSpecifier: OPT_offload_targets_EQ, Value: Targets);
3899 }
3900
3901 if (Opts.OpenMPCUDAMode)
3902 GenerateArg(Consumer, OptSpecifier: OPT_fopenmp_cuda_mode);
3903
3904 if (Opts.OpenACC)
3905 GenerateArg(Consumer, OptSpecifier: OPT_fopenacc);
3906
3907 // The arguments used to set Optimize, OptimizeSize and NoInlineDefine are
3908 // generated from CodeGenOptions.
3909
3910 if (Opts.DefaultFPContractMode == LangOptions::FPM_Fast)
3911 GenerateArg(Consumer, OptSpecifier: OPT_ffp_contract, Value: "fast");
3912 else if (Opts.DefaultFPContractMode == LangOptions::FPM_On)
3913 GenerateArg(Consumer, OptSpecifier: OPT_ffp_contract, Value: "on");
3914 else if (Opts.DefaultFPContractMode == LangOptions::FPM_Off)
3915 GenerateArg(Consumer, OptSpecifier: OPT_ffp_contract, Value: "off");
3916 else if (Opts.DefaultFPContractMode == LangOptions::FPM_FastHonorPragmas)
3917 GenerateArg(Consumer, OptSpecifier: OPT_ffp_contract, Value: "fast-honor-pragmas");
3918
3919 for (StringRef Sanitizer : serializeSanitizerKinds(S: Opts.Sanitize))
3920 GenerateArg(Consumer, OptSpecifier: OPT_fsanitize_EQ, Value: Sanitizer);
3921 for (StringRef Sanitizer :
3922 serializeSanitizerKinds(S: Opts.UBSanFeatureIgnoredSanitize))
3923 GenerateArg(Consumer, OptSpecifier: OPT_fsanitize_ignore_for_ubsan_feature_EQ, Value: Sanitizer);
3924
3925 // Conflating '-fsanitize-system-ignorelist' and '-fsanitize-ignorelist'.
3926 for (const std::string &F : Opts.NoSanitizeFiles)
3927 GenerateArg(Consumer, OptSpecifier: OPT_fsanitize_ignorelist_EQ, Value: F);
3928
3929 switch (Opts.getClangABICompat()) {
3930#define ABI_VER_MAJOR_MINOR(Major, Minor) \
3931 case LangOptions::ClangABI::Ver##Major##_##Minor: \
3932 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, #Major "." #Minor); \
3933 break;
3934#define ABI_VER_MAJOR(Major) \
3935 case LangOptions::ClangABI::Ver##Major: \
3936 GenerateArg(Consumer, OPT_fclang_abi_compat_EQ, #Major ".0"); \
3937 break;
3938#define ABI_VER_LATEST(Latest) \
3939 case LangOptions::ClangABI::Latest: \
3940 break;
3941#include "clang/Basic/ABIVersions.def"
3942 }
3943
3944 if (Opts.getSignReturnAddressScope() ==
3945 LangOptions::SignReturnAddressScopeKind::All)
3946 GenerateArg(Consumer, OptSpecifier: OPT_msign_return_address_EQ, Value: "all");
3947 else if (Opts.getSignReturnAddressScope() ==
3948 LangOptions::SignReturnAddressScopeKind::NonLeaf)
3949 GenerateArg(Consumer, OptSpecifier: OPT_msign_return_address_EQ, Value: "non-leaf");
3950
3951 if (Opts.getSignReturnAddressKey() ==
3952 LangOptions::SignReturnAddressKeyKind::BKey)
3953 GenerateArg(Consumer, OptSpecifier: OPT_msign_return_address_key_EQ, Value: "b_key");
3954
3955 if (Opts.CXXABI)
3956 GenerateArg(Consumer, OptSpecifier: OPT_fcxx_abi_EQ,
3957 Value: TargetCXXABI::getSpelling(ABIKind: *Opts.CXXABI));
3958
3959 if (Opts.RelativeCXXABIVTables)
3960 GenerateArg(Consumer, OptSpecifier: OPT_fexperimental_relative_cxx_abi_vtables);
3961 else
3962 GenerateArg(Consumer, OptSpecifier: OPT_fno_experimental_relative_cxx_abi_vtables);
3963
3964 if (Opts.UseTargetPathSeparator)
3965 GenerateArg(Consumer, OptSpecifier: OPT_ffile_reproducible);
3966 else
3967 GenerateArg(Consumer, OptSpecifier: OPT_fno_file_reproducible);
3968
3969 for (const auto &MP : Opts.MacroPrefixMap)
3970 GenerateArg(Consumer, OptSpecifier: OPT_fmacro_prefix_map_EQ, Value: MP.first + "=" + MP.second);
3971
3972 if (!Opts.RandstructSeed.empty())
3973 GenerateArg(Consumer, OptSpecifier: OPT_frandomize_layout_seed_EQ, Value: Opts.RandstructSeed);
3974
3975 if (Opts.AllocTokenMax)
3976 GenerateArg(Consumer, OptSpecifier: OPT_falloc_token_max_EQ,
3977 Value: std::to_string(val: *Opts.AllocTokenMax));
3978
3979 if (Opts.AllocTokenMode) {
3980 StringRef S = llvm::getAllocTokenModeAsString(Mode: *Opts.AllocTokenMode);
3981 GenerateArg(Consumer, OptSpecifier: OPT_falloc_token_mode_EQ, Value: S);
3982 }
3983 // Generate args for matrix types.
3984 if (Opts.MatrixTypes) {
3985 if (Opts.getDefaultMatrixMemoryLayout() ==
3986 LangOptions::MatrixMemoryLayout::MatrixColMajor)
3987 GenerateArg(Consumer, OptSpecifier: OPT_fmatrix_memory_layout_EQ, Value: "column-major");
3988 if (Opts.getDefaultMatrixMemoryLayout() ==
3989 LangOptions::MatrixMemoryLayout::MatrixRowMajor)
3990 GenerateArg(Consumer, OptSpecifier: OPT_fmatrix_memory_layout_EQ, Value: "row-major");
3991 }
3992}
3993
3994bool CompilerInvocation::ParseLangArgs(LangOptions &Opts, ArgList &Args,
3995 InputKind IK, const llvm::Triple &T,
3996 std::vector<std::string> &Includes,
3997 DiagnosticsEngine &Diags) {
3998 unsigned NumErrorsBefore = Diags.getNumErrors();
3999
4000 if (IK.getFormat() == InputKind::Precompiled ||
4001 IK.getLanguage() == Language::LLVM_IR ||
4002 IK.getLanguage() == Language::CIR) {
4003 // ObjCAAutoRefCount and Sanitize LangOpts are used to setup the
4004 // PassManager in BackendUtil.cpp. They need to be initialized no matter
4005 // what the input type is.
4006 if (Args.hasArg(Ids: OPT_fobjc_arc))
4007 Opts.ObjCAutoRefCount = 1;
4008 // PICLevel and PIELevel are needed during code generation and this should
4009 // be set regardless of the input type.
4010 Opts.PICLevel = getLastArgIntValue(Args, Id: OPT_pic_level, Default: 0, Diags);
4011 Opts.PIE = Args.hasArg(Ids: OPT_pic_is_pie);
4012 parseSanitizerKinds(FlagName: "-fsanitize=", Sanitizers: Args.getAllArgValues(Id: OPT_fsanitize_EQ),
4013 Diags, S&: Opts.Sanitize);
4014 parseSanitizerKinds(
4015 FlagName: "-fsanitize-ignore-for-ubsan-feature=",
4016 Sanitizers: Args.getAllArgValues(Id: OPT_fsanitize_ignore_for_ubsan_feature_EQ), Diags,
4017 S&: Opts.UBSanFeatureIgnoredSanitize);
4018
4019 return Diags.getNumErrors() == NumErrorsBefore;
4020 }
4021
4022 // Other LangOpts are only initialized when the input is not AST or LLVM IR.
4023 // FIXME: Should we really be parsing this for an Language::Asm input?
4024
4025 // FIXME: Cleanup per-file based stuff.
4026 LangStandard::Kind LangStd = LangStandard::lang_unspecified;
4027 if (const Arg *A = Args.getLastArg(Ids: OPT_std_EQ)) {
4028 LangStd = LangStandard::getLangKind(Name: A->getValue());
4029 if (LangStd == LangStandard::lang_unspecified) {
4030 Diags.Report(DiagID: diag::err_drv_invalid_value)
4031 << A->getAsString(Args) << A->getValue();
4032 // Report supported standards with short description.
4033 for (unsigned KindValue = 0;
4034 KindValue != LangStandard::lang_unspecified;
4035 ++KindValue) {
4036 const LangStandard &Std = LangStandard::getLangStandardForKind(
4037 K: static_cast<LangStandard::Kind>(KindValue));
4038 if (IsInputCompatibleWithStandard(IK, S: Std)) {
4039 auto Diag = Diags.Report(DiagID: diag::note_drv_use_standard);
4040 Diag << Std.getName() << Std.getDescription();
4041 unsigned NumAliases = 0;
4042#define LANGSTANDARD(id, name, lang, desc, features, version)
4043#define LANGSTANDARD_ALIAS(id, alias) \
4044 if (KindValue == LangStandard::lang_##id) ++NumAliases;
4045#define LANGSTANDARD_ALIAS_DEPR(id, alias)
4046#include "clang/Basic/LangStandards.def"
4047 Diag << NumAliases;
4048#define LANGSTANDARD(id, name, lang, desc, features, version)
4049#define LANGSTANDARD_ALIAS(id, alias) \
4050 if (KindValue == LangStandard::lang_##id) Diag << alias;
4051#define LANGSTANDARD_ALIAS_DEPR(id, alias)
4052#include "clang/Basic/LangStandards.def"
4053 }
4054 }
4055 } else {
4056 // Valid standard, check to make sure language and standard are
4057 // compatible.
4058 const LangStandard &Std = LangStandard::getLangStandardForKind(K: LangStd);
4059 if (!IsInputCompatibleWithStandard(IK, S: Std)) {
4060 Diags.Report(DiagID: diag::err_drv_argument_not_allowed_with)
4061 << A->getAsString(Args) << GetInputKindName(IK);
4062 }
4063 }
4064 }
4065
4066 // -cl-std only applies for OpenCL language standards.
4067 // Override the -std option in this case.
4068 if (const Arg *A = Args.getLastArg(Ids: OPT_cl_std_EQ)) {
4069 LangStandard::Kind OpenCLLangStd =
4070 llvm::StringSwitch<LangStandard::Kind>(A->getValue())
4071 .Cases(CaseStrings: {"cl", "CL"}, Value: LangStandard::lang_opencl10)
4072 .Cases(CaseStrings: {"cl1.0", "CL1.0"}, Value: LangStandard::lang_opencl10)
4073 .Cases(CaseStrings: {"cl1.1", "CL1.1"}, Value: LangStandard::lang_opencl11)
4074 .Cases(CaseStrings: {"cl1.2", "CL1.2"}, Value: LangStandard::lang_opencl12)
4075 .Cases(CaseStrings: {"cl2.0", "CL2.0"}, Value: LangStandard::lang_opencl20)
4076 .Cases(CaseStrings: {"cl3.0", "CL3.0"}, Value: LangStandard::lang_opencl30)
4077 .Cases(CaseStrings: {"clc++", "CLC++"}, Value: LangStandard::lang_openclcpp10)
4078 .Cases(CaseStrings: {"clc++1.0", "CLC++1.0"}, Value: LangStandard::lang_openclcpp10)
4079 .Cases(CaseStrings: {"clc++2021", "CLC++2021"}, Value: LangStandard::lang_openclcpp2021)
4080 .Default(Value: LangStandard::lang_unspecified);
4081
4082 if (OpenCLLangStd == LangStandard::lang_unspecified) {
4083 Diags.Report(DiagID: diag::err_drv_invalid_value)
4084 << A->getAsString(Args) << A->getValue();
4085 }
4086 else
4087 LangStd = OpenCLLangStd;
4088 }
4089
4090 // These need to be parsed now. They are used to set OpenCL defaults.
4091 Opts.IncludeDefaultHeader = Args.hasArg(Ids: OPT_finclude_default_header);
4092 Opts.DeclareOpenCLBuiltins = Args.hasArg(Ids: OPT_fdeclare_opencl_builtins);
4093
4094 LangOptions::setLangDefaults(Opts, Lang: IK.getLanguage(), T, Includes, LangStd);
4095
4096 // The key paths of codegen options defined in Options.td start with
4097 // "LangOpts->". Let's provide the expected variable name and type.
4098 LangOptions *LangOpts = &Opts;
4099
4100#define LANG_OPTION_WITH_MARSHALLING(...) \
4101 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
4102#include "clang/Options/Options.inc"
4103#undef LANG_OPTION_WITH_MARSHALLING
4104
4105 if (const Arg *A = Args.getLastArg(Ids: OPT_fcf_protection_EQ)) {
4106 StringRef Name = A->getValue();
4107 if (Name == "full") {
4108 Opts.CFProtectionBranch = 1;
4109 Opts.CFProtectionReturn = 1;
4110 } else if (Name == "branch") {
4111 Opts.CFProtectionBranch = 1;
4112 } else if (Name == "return") {
4113 Opts.CFProtectionReturn = 1;
4114 }
4115 }
4116
4117 if (Opts.CFProtectionBranch) {
4118 if (const Arg *A = Args.getLastArg(Ids: OPT_mcf_branch_label_scheme_EQ)) {
4119 const auto Scheme =
4120 llvm::StringSwitch<CFBranchLabelSchemeKind>(A->getValue())
4121#define CF_BRANCH_LABEL_SCHEME(Kind, FlagVal) \
4122 .Case(#FlagVal, CFBranchLabelSchemeKind::Kind)
4123#include "clang/Basic/CFProtectionOptions.def"
4124 .Default(Value: CFBranchLabelSchemeKind::Default);
4125 Opts.setCFBranchLabelScheme(Scheme);
4126 }
4127 }
4128
4129 if ((Args.hasArg(Ids: OPT_fsycl_is_device) || Args.hasArg(Ids: OPT_fsycl_is_host)) &&
4130 !Args.hasArg(Ids: OPT_sycl_std_EQ)) {
4131 // If the user supplied -fsycl-is-device or -fsycl-is-host, but failed to
4132 // provide -sycl-std=, we want to default it to whatever the default SYCL
4133 // version is. I could not find a way to express this with the options
4134 // tablegen because we still want this value to be SYCL_None when the user
4135 // is not in device or host mode.
4136 Opts.setSYCLVersion(LangOptions::SYCL_Default);
4137 }
4138
4139 if (Opts.ObjC) {
4140 if (Arg *arg = Args.getLastArg(Ids: OPT_fobjc_runtime_EQ)) {
4141 StringRef value = arg->getValue();
4142 if (Opts.ObjCRuntime.tryParse(input: value))
4143 Diags.Report(DiagID: diag::err_drv_unknown_objc_runtime) << value;
4144 }
4145
4146 if (Args.hasArg(Ids: OPT_fobjc_gc_only))
4147 Opts.setGC(LangOptions::GCOnly);
4148 else if (Args.hasArg(Ids: OPT_fobjc_gc))
4149 Opts.setGC(LangOptions::HybridGC);
4150 else if (Args.hasArg(Ids: OPT_fobjc_arc)) {
4151 Opts.ObjCAutoRefCount = 1;
4152 if (!Opts.ObjCRuntime.allowsARC())
4153 Diags.Report(DiagID: diag::err_arc_unsupported_on_runtime);
4154 }
4155
4156 // ObjCWeakRuntime tracks whether the runtime supports __weak, not
4157 // whether the feature is actually enabled. This is predominantly
4158 // determined by -fobjc-runtime, but we allow it to be overridden
4159 // from the command line for testing purposes.
4160 if (Args.hasArg(Ids: OPT_fobjc_runtime_has_weak))
4161 Opts.ObjCWeakRuntime = 1;
4162 else
4163 Opts.ObjCWeakRuntime = Opts.ObjCRuntime.allowsWeak();
4164
4165 // ObjCWeak determines whether __weak is actually enabled.
4166 // Note that we allow -fno-objc-weak to disable this even in ARC mode.
4167 if (auto weakArg = Args.getLastArg(Ids: OPT_fobjc_weak, Ids: OPT_fno_objc_weak)) {
4168 if (!weakArg->getOption().matches(ID: OPT_fobjc_weak)) {
4169 assert(!Opts.ObjCWeak);
4170 } else if (Opts.getGC() != LangOptions::NonGC) {
4171 Diags.Report(DiagID: diag::err_objc_weak_with_gc);
4172 } else if (!Opts.ObjCWeakRuntime) {
4173 Diags.Report(DiagID: diag::err_objc_weak_unsupported);
4174 } else {
4175 Opts.ObjCWeak = 1;
4176 }
4177 } else if (Opts.ObjCAutoRefCount) {
4178 Opts.ObjCWeak = Opts.ObjCWeakRuntime;
4179 }
4180
4181 if (Args.hasArg(Ids: OPT_fobjc_subscripting_legacy_runtime))
4182 Opts.ObjCSubscriptingLegacyRuntime =
4183 (Opts.ObjCRuntime.getKind() == ObjCRuntime::FragileMacOSX);
4184 }
4185
4186 if (Arg *A = Args.getLastArg(Ids: options::OPT_fgnuc_version_EQ)) {
4187 // Check that the version has 1 to 3 components and the minor and patch
4188 // versions fit in two decimal digits.
4189 VersionTuple GNUCVer;
4190 bool Invalid = GNUCVer.tryParse(string: A->getValue());
4191 unsigned Major = GNUCVer.getMajor();
4192 unsigned Minor = GNUCVer.getMinor().value_or(u: 0);
4193 unsigned Patch = GNUCVer.getSubminor().value_or(u: 0);
4194 if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
4195 Diags.Report(DiagID: diag::err_drv_invalid_value)
4196 << A->getAsString(Args) << A->getValue();
4197 }
4198 Opts.GNUCVersion = Major * 100 * 100 + Minor * 100 + Patch;
4199 }
4200
4201 if (T.isOSAIX() && (Args.hasArg(Ids: OPT_mignore_xcoff_visibility)))
4202 Opts.IgnoreXCOFFVisibility = 1;
4203
4204 if (Args.hasArg(Ids: OPT_ftrapv)) {
4205 Opts.setSignedOverflowBehavior(LangOptions::SOB_Trapping);
4206 // Set the handler, if one is specified.
4207 Opts.OverflowHandler =
4208 std::string(Args.getLastArgValue(Id: OPT_ftrapv_handler));
4209 }
4210 else if (Args.hasArg(Ids: OPT_fwrapv))
4211 Opts.setSignedOverflowBehavior(LangOptions::SOB_Defined);
4212 if (Args.hasArg(Ids: OPT_fwrapv_pointer))
4213 Opts.PointerOverflowDefined = true;
4214
4215 Opts.MSCompatibilityVersion = 0;
4216 if (const Arg *A = Args.getLastArg(Ids: OPT_fms_compatibility_version)) {
4217 VersionTuple VT;
4218 if (VT.tryParse(string: A->getValue()))
4219 Diags.Report(DiagID: diag::err_drv_invalid_value) << A->getAsString(Args)
4220 << A->getValue();
4221 Opts.MSCompatibilityVersion = VT.getMajor() * 10000000 +
4222 VT.getMinor().value_or(u: 0) * 100000 +
4223 VT.getSubminor().value_or(u: 0);
4224 }
4225
4226 // Mimicking gcc's behavior, trigraphs are only enabled if -trigraphs
4227 // is specified, or -std is set to a conforming mode.
4228 // Trigraphs are disabled by default in C++17 and C23 onwards.
4229 // For z/OS, trigraphs are enabled by default (without regard to the above).
4230 Opts.Trigraphs =
4231 (!Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus17 && !Opts.C23) ||
4232 T.isOSzOS();
4233 Opts.Trigraphs =
4234 Args.hasFlag(Pos: OPT_ftrigraphs, Neg: OPT_fno_trigraphs, Default: Opts.Trigraphs);
4235
4236 Opts.ZOSExt =
4237 Args.hasFlag(Pos: OPT_fzos_extensions, Neg: OPT_fno_zos_extensions, Default: T.isOSzOS());
4238
4239 Opts.Blocks = Args.hasArg(Ids: OPT_fblocks) || (Opts.OpenCL
4240 && Opts.OpenCLVersion == 200);
4241
4242 bool HasConvergentOperations = Opts.isTargetDevice() || Opts.OpenCL ||
4243 Opts.HLSL || T.isAMDGPU() || T.isNVPTX();
4244 Opts.ConvergentFunctions =
4245 Args.hasFlag(Pos: OPT_fconvergent_functions, Neg: OPT_fno_convergent_functions,
4246 Default: HasConvergentOperations);
4247
4248 Opts.NoBuiltin = Args.hasArg(Ids: OPT_fno_builtin) || Opts.Freestanding;
4249 if (!Opts.NoBuiltin)
4250 getAllNoBuiltinFuncValues(Args, Funcs&: Opts.NoBuiltinFuncs);
4251 if (Arg *A = Args.getLastArg(Ids: options::OPT_LongDouble_Group)) {
4252 if (A->getOption().matches(ID: options::OPT_mlong_double_64))
4253 Opts.LongDoubleSize = 64;
4254 else if (A->getOption().matches(ID: options::OPT_mlong_double_80))
4255 Opts.LongDoubleSize = 80;
4256 else if (A->getOption().matches(ID: options::OPT_mlong_double_128))
4257 Opts.LongDoubleSize = 128;
4258 else
4259 Opts.LongDoubleSize = 0;
4260 }
4261 if (Opts.FastRelaxedMath || Opts.CLUnsafeMath)
4262 Opts.setDefaultFPContractMode(LangOptions::FPM_Fast);
4263
4264 llvm::sort(C&: Opts.ModuleFeatures);
4265
4266 // -mrtd option
4267 if (Arg *A = Args.getLastArg(Ids: OPT_mrtd)) {
4268 if (Opts.getDefaultCallingConv() != LangOptions::DCC_None)
4269 Diags.Report(DiagID: diag::err_drv_argument_not_allowed_with)
4270 << A->getSpelling() << "-fdefault-calling-conv";
4271 else {
4272 switch (T.getArch()) {
4273 case llvm::Triple::x86:
4274 Opts.setDefaultCallingConv(LangOptions::DCC_StdCall);
4275 break;
4276 case llvm::Triple::m68k:
4277 Opts.setDefaultCallingConv(LangOptions::DCC_RtdCall);
4278 break;
4279 default:
4280 Diags.Report(DiagID: diag::err_drv_argument_not_allowed_with)
4281 << A->getSpelling() << T.getTriple();
4282 }
4283 }
4284 }
4285
4286 // Check if -fopenmp is specified and set default version to 5.1.
4287 Opts.OpenMP = Args.hasArg(Ids: OPT_fopenmp) ? 51 : 0;
4288 // Check if -fopenmp-simd is specified.
4289 bool IsSimdSpecified =
4290 Args.hasFlag(Pos: options::OPT_fopenmp_simd, Neg: options::OPT_fno_openmp_simd,
4291 /*Default=*/false);
4292 Opts.OpenMPSimd = !Opts.OpenMP && IsSimdSpecified;
4293 Opts.OpenMPUseTLS =
4294 Opts.OpenMP && !Args.hasArg(Ids: options::OPT_fnoopenmp_use_tls);
4295 Opts.OpenMPIsTargetDevice =
4296 Opts.OpenMP && Args.hasArg(Ids: options::OPT_fopenmp_is_target_device);
4297 Opts.OpenMPIRBuilder =
4298 Opts.OpenMP && Args.hasArg(Ids: options::OPT_fopenmp_enable_irbuilder);
4299 bool IsTargetSpecified =
4300 Opts.OpenMPIsTargetDevice || Args.hasArg(Ids: options::OPT_offload_targets_EQ);
4301
4302 if (Opts.OpenMP || Opts.OpenMPSimd) {
4303 if (int Version = getLastArgIntValue(
4304 Args, Id: OPT_fopenmp_version_EQ,
4305 Default: (IsSimdSpecified || IsTargetSpecified) ? 51 : Opts.OpenMP, Diags))
4306 Opts.OpenMP = Version;
4307 // Provide diagnostic when a given target is not expected to be an OpenMP
4308 // device or host.
4309 if (!Opts.OpenMPIsTargetDevice) {
4310 switch (T.getArch()) {
4311 default:
4312 break;
4313 // Add unsupported host targets here:
4314 case llvm::Triple::nvptx:
4315 case llvm::Triple::nvptx64:
4316 Diags.Report(DiagID: diag::err_drv_omp_host_target_not_supported) << T.str();
4317 break;
4318 }
4319 }
4320 }
4321
4322 // Set the flag to prevent the implementation from emitting device exception
4323 // handling code for those requiring so.
4324 if ((Opts.OpenMPIsTargetDevice && T.isGPU()) || Opts.OpenCLCPlusPlus) {
4325
4326 Opts.Exceptions = 0;
4327 Opts.CXXExceptions = 0;
4328 }
4329 if (Opts.OpenMPIsTargetDevice && T.isNVPTX()) {
4330 Opts.OpenMPCUDANumSMs =
4331 getLastArgIntValue(Args, Id: options::OPT_fopenmp_cuda_number_of_sm_EQ,
4332 Default: Opts.OpenMPCUDANumSMs, Diags);
4333 Opts.OpenMPCUDABlocksPerSM =
4334 getLastArgIntValue(Args, Id: options::OPT_fopenmp_cuda_blocks_per_sm_EQ,
4335 Default: Opts.OpenMPCUDABlocksPerSM, Diags);
4336 Opts.OpenMPCUDAReductionBufNum = getLastArgIntValue(
4337 Args, Id: options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ,
4338 Default: Opts.OpenMPCUDAReductionBufNum, Diags);
4339 }
4340
4341 // Set the value of the debugging flag used in the new offloading device RTL.
4342 // Set either by a specific value or to a default if not specified.
4343 if (Opts.OpenMPIsTargetDevice && (Args.hasArg(Ids: OPT_fopenmp_target_debug) ||
4344 Args.hasArg(Ids: OPT_fopenmp_target_debug_EQ))) {
4345 Opts.OpenMPTargetDebug = getLastArgIntValue(
4346 Args, Id: OPT_fopenmp_target_debug_EQ, Default: Opts.OpenMPTargetDebug, Diags);
4347 if (!Opts.OpenMPTargetDebug && Args.hasArg(Ids: OPT_fopenmp_target_debug))
4348 Opts.OpenMPTargetDebug = 1;
4349 }
4350
4351 if (Opts.OpenMPIsTargetDevice) {
4352 if (Args.hasArg(Ids: OPT_fopenmp_assume_teams_oversubscription))
4353 Opts.OpenMPTeamSubscription = true;
4354 if (Args.hasArg(Ids: OPT_fopenmp_assume_threads_oversubscription))
4355 Opts.OpenMPThreadSubscription = true;
4356 }
4357
4358 // Get the OpenMP target triples if any.
4359 if (Arg *A = Args.getLastArg(Ids: options::OPT_offload_targets_EQ)) {
4360 enum ArchPtrSize { Arch16Bit, Arch32Bit, Arch64Bit };
4361 auto getArchPtrSize = [](const llvm::Triple &T) {
4362 if (T.isArch16Bit())
4363 return Arch16Bit;
4364 if (T.isArch32Bit())
4365 return Arch32Bit;
4366 assert(T.isArch64Bit() && "Expected 64-bit architecture");
4367 return Arch64Bit;
4368 };
4369
4370 for (unsigned i = 0; i < A->getNumValues(); ++i) {
4371 llvm::Triple TT(A->getValue(N: i));
4372
4373 if (TT.getArch() == llvm::Triple::UnknownArch ||
4374 !(TT.getArch() == llvm::Triple::aarch64 || TT.isPPC() ||
4375 TT.getArch() == llvm::Triple::spirv64 ||
4376 TT.getArch() == llvm::Triple::systemz ||
4377 TT.getArch() == llvm::Triple::loongarch64 ||
4378 TT.getArch() == llvm::Triple::nvptx ||
4379 TT.getArch() == llvm::Triple::nvptx64 || TT.isAMDGCN() ||
4380 TT.getArch() == llvm::Triple::x86 ||
4381 TT.getArch() == llvm::Triple::x86_64))
4382 Diags.Report(DiagID: diag::err_drv_invalid_omp_target) << A->getValue(N: i);
4383 else if (getArchPtrSize(T) != getArchPtrSize(TT))
4384 Diags.Report(DiagID: diag::err_drv_incompatible_omp_arch)
4385 << A->getValue(N: i) << T.str();
4386 else
4387 Opts.OMPTargetTriples.push_back(x: TT);
4388 }
4389 }
4390
4391 // Set CUDA mode for OpenMP target NVPTX/AMDGCN if specified in options
4392 Opts.OpenMPCUDAMode = Opts.OpenMPIsTargetDevice &&
4393 (T.isNVPTX() || T.isAMDGCN()) &&
4394 Args.hasArg(Ids: options::OPT_fopenmp_cuda_mode);
4395
4396 // OpenACC Configuration.
4397 if (Args.hasArg(Ids: options::OPT_fopenacc))
4398 Opts.OpenACC = true;
4399
4400 if (Arg *A = Args.getLastArg(Ids: OPT_ffp_contract)) {
4401 StringRef Val = A->getValue();
4402 if (Val == "fast")
4403 Opts.setDefaultFPContractMode(LangOptions::FPM_Fast);
4404 else if (Val == "on")
4405 Opts.setDefaultFPContractMode(LangOptions::FPM_On);
4406 else if (Val == "off")
4407 Opts.setDefaultFPContractMode(LangOptions::FPM_Off);
4408 else if (Val == "fast-honor-pragmas")
4409 Opts.setDefaultFPContractMode(LangOptions::FPM_FastHonorPragmas);
4410 else
4411 Diags.Report(DiagID: diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
4412 }
4413
4414 if (auto *A =
4415 Args.getLastArg(Ids: OPT_fsanitize_undefined_ignore_overflow_pattern_EQ)) {
4416 for (int i = 0, n = A->getNumValues(); i != n; ++i) {
4417 Opts.OverflowPatternExclusionMask |=
4418 llvm::StringSwitch<unsigned>(A->getValue(N: i))
4419 .Case(S: "none", Value: LangOptionsBase::None)
4420 .Case(S: "all", Value: LangOptionsBase::All)
4421 .Case(S: "add-unsigned-overflow-test",
4422 Value: LangOptionsBase::AddUnsignedOverflowTest)
4423 .Case(S: "add-signed-overflow-test",
4424 Value: LangOptionsBase::AddSignedOverflowTest)
4425 .Case(S: "negated-unsigned-const", Value: LangOptionsBase::NegUnsignedConst)
4426 .Case(S: "unsigned-post-decr-while",
4427 Value: LangOptionsBase::PostDecrInWhile)
4428 .Default(Value: 0);
4429 }
4430 }
4431
4432 // Parse -fsanitize= arguments.
4433 parseSanitizerKinds(FlagName: "-fsanitize=", Sanitizers: Args.getAllArgValues(Id: OPT_fsanitize_EQ),
4434 Diags, S&: Opts.Sanitize);
4435 parseSanitizerKinds(
4436 FlagName: "-fsanitize-ignore-for-ubsan-feature=",
4437 Sanitizers: Args.getAllArgValues(Id: OPT_fsanitize_ignore_for_ubsan_feature_EQ), Diags,
4438 S&: Opts.UBSanFeatureIgnoredSanitize);
4439 Opts.NoSanitizeFiles = Args.getAllArgValues(Id: OPT_fsanitize_ignorelist_EQ);
4440 std::vector<std::string> systemIgnorelists =
4441 Args.getAllArgValues(Id: OPT_fsanitize_system_ignorelist_EQ);
4442 Opts.NoSanitizeFiles.insert(position: Opts.NoSanitizeFiles.end(),
4443 first: systemIgnorelists.begin(),
4444 last: systemIgnorelists.end());
4445
4446 if (Arg *A = Args.getLastArg(Ids: OPT_fclang_abi_compat_EQ)) {
4447 Opts.setClangABICompat(LangOptions::ClangABI::Latest);
4448
4449 StringRef Ver = A->getValue();
4450 std::pair<StringRef, StringRef> VerParts = Ver.split(Separator: '.');
4451 int Major, Minor = 0;
4452
4453 // Check the version number is valid: either 3.x (0 <= x <= 9) or
4454 // y or y.0 (4 <= y <= current version).
4455 if (!VerParts.first.starts_with(Prefix: "0") &&
4456 !VerParts.first.getAsInteger(Radix: 10, Result&: Major) && 3 <= Major &&
4457 Major <= MAX_CLANG_ABI_COMPAT_VERSION &&
4458 (Major == 3
4459 ? VerParts.second.size() == 1 &&
4460 !VerParts.second.getAsInteger(Radix: 10, Result&: Minor)
4461 : VerParts.first.size() == Ver.size() || VerParts.second == "0")) {
4462 // Got a valid version number.
4463#define ABI_VER_MAJOR_MINOR(Major_, Minor_) \
4464 if (std::tuple(Major, Minor) <= std::tuple(Major_, Minor_)) \
4465 Opts.setClangABICompat(LangOptions::ClangABI::Ver##Major_##_##Minor_); \
4466 else
4467#define ABI_VER_MAJOR(Major_) \
4468 if (Major <= Major_) \
4469 Opts.setClangABICompat(LangOptions::ClangABI::Ver##Major_); \
4470 else
4471#define ABI_VER_LATEST(Latest) \
4472 { /* Equivalent to latest version - do nothing */ \
4473 }
4474#include "clang/Basic/ABIVersions.def"
4475 } else if (Ver != "latest") {
4476 Diags.Report(DiagID: diag::err_drv_invalid_value)
4477 << A->getAsString(Args) << A->getValue();
4478 }
4479 }
4480
4481 if (Arg *A = Args.getLastArg(Ids: OPT_msign_return_address_EQ)) {
4482 StringRef SignScope = A->getValue();
4483
4484 if (SignScope.equals_insensitive(RHS: "none"))
4485 Opts.setSignReturnAddressScope(
4486 LangOptions::SignReturnAddressScopeKind::None);
4487 else if (SignScope.equals_insensitive(RHS: "all"))
4488 Opts.setSignReturnAddressScope(
4489 LangOptions::SignReturnAddressScopeKind::All);
4490 else if (SignScope.equals_insensitive(RHS: "non-leaf"))
4491 Opts.setSignReturnAddressScope(
4492 LangOptions::SignReturnAddressScopeKind::NonLeaf);
4493 else
4494 Diags.Report(DiagID: diag::err_drv_invalid_value)
4495 << A->getAsString(Args) << SignScope;
4496
4497 if (Arg *A = Args.getLastArg(Ids: OPT_msign_return_address_key_EQ)) {
4498 StringRef SignKey = A->getValue();
4499 if (!SignScope.empty() && !SignKey.empty()) {
4500 if (SignKey == "a_key")
4501 Opts.setSignReturnAddressKey(
4502 LangOptions::SignReturnAddressKeyKind::AKey);
4503 else if (SignKey == "b_key")
4504 Opts.setSignReturnAddressKey(
4505 LangOptions::SignReturnAddressKeyKind::BKey);
4506 else
4507 Diags.Report(DiagID: diag::err_drv_invalid_value)
4508 << A->getAsString(Args) << SignKey;
4509 }
4510 }
4511 }
4512
4513 // The value can be empty, which indicates the system default should be used.
4514 StringRef CXXABI = Args.getLastArgValue(Id: OPT_fcxx_abi_EQ);
4515 if (!CXXABI.empty()) {
4516 if (!TargetCXXABI::isABI(Name: CXXABI)) {
4517 Diags.Report(DiagID: diag::err_invalid_cxx_abi) << CXXABI;
4518 } else {
4519 auto Kind = TargetCXXABI::getKind(Name: CXXABI);
4520 if (!TargetCXXABI::isSupportedCXXABI(T, Kind))
4521 Diags.Report(DiagID: diag::err_unsupported_cxx_abi) << CXXABI << T.str();
4522 else
4523 Opts.CXXABI = Kind;
4524 }
4525 }
4526
4527 Opts.RelativeCXXABIVTables =
4528 Args.hasFlag(Pos: options::OPT_fexperimental_relative_cxx_abi_vtables,
4529 Neg: options::OPT_fno_experimental_relative_cxx_abi_vtables,
4530 Default: TargetCXXABI::usesRelativeVTables(T));
4531
4532 // RTTI is on by default.
4533 bool HasRTTI = !Args.hasArg(Ids: options::OPT_fno_rtti);
4534 Opts.OmitVTableRTTI =
4535 Args.hasFlag(Pos: options::OPT_fexperimental_omit_vtable_rtti,
4536 Neg: options::OPT_fno_experimental_omit_vtable_rtti, Default: false);
4537 if (Opts.OmitVTableRTTI && HasRTTI)
4538 Diags.Report(DiagID: diag::err_drv_using_omit_rtti_component_without_no_rtti);
4539
4540 for (const auto &A : Args.getAllArgValues(Id: OPT_fmacro_prefix_map_EQ)) {
4541 auto Split = StringRef(A).split(Separator: '=');
4542 Opts.MacroPrefixMap.insert(
4543 x: {std::string(Split.first), std::string(Split.second)});
4544 }
4545
4546 Opts.UseTargetPathSeparator =
4547 !Args.getLastArg(Ids: OPT_fno_file_reproducible) &&
4548 (Args.getLastArg(Ids: OPT_ffile_compilation_dir_EQ) ||
4549 Args.getLastArg(Ids: OPT_fmacro_prefix_map_EQ) ||
4550 Args.getLastArg(Ids: OPT_ffile_reproducible));
4551
4552 // Error if -mvscale-min is unbounded.
4553 if (Arg *A = Args.getLastArg(Ids: options::OPT_mvscale_min_EQ)) {
4554 unsigned VScaleMin;
4555 if (StringRef(A->getValue()).getAsInteger(Radix: 10, Result&: VScaleMin) || VScaleMin == 0)
4556 Diags.Report(DiagID: diag::err_cc1_unbounded_vscale_min);
4557 }
4558 if (Arg *A = Args.getLastArg(Ids: options::OPT_mvscale_streaming_min_EQ)) {
4559 unsigned VScaleMin;
4560 if (StringRef(A->getValue()).getAsInteger(Radix: 10, Result&: VScaleMin) || VScaleMin == 0)
4561 Diags.Report(DiagID: diag::err_cc1_unbounded_vscale_min);
4562 }
4563
4564 if (const Arg *A = Args.getLastArg(Ids: OPT_frandomize_layout_seed_file_EQ)) {
4565 std::ifstream SeedFile(A->getValue(N: 0));
4566
4567 if (!SeedFile.is_open())
4568 Diags.Report(DiagID: diag::err_drv_cannot_open_randomize_layout_seed_file)
4569 << A->getValue(N: 0);
4570
4571 std::getline(is&: SeedFile, str&: Opts.RandstructSeed);
4572 }
4573
4574 if (const Arg *A = Args.getLastArg(Ids: OPT_frandomize_layout_seed_EQ))
4575 Opts.RandstructSeed = A->getValue(N: 0);
4576
4577 if (const auto *Arg = Args.getLastArg(Ids: options::OPT_falloc_token_max_EQ)) {
4578 StringRef S = Arg->getValue();
4579 uint64_t Value = 0;
4580 if (S.getAsInteger(Radix: 0, Result&: Value))
4581 Diags.Report(DiagID: diag::err_drv_invalid_value) << Arg->getAsString(Args) << S;
4582 else
4583 Opts.AllocTokenMax = Value;
4584 }
4585
4586 if (const auto *Arg = Args.getLastArg(Ids: options::OPT_falloc_token_mode_EQ)) {
4587 StringRef S = Arg->getValue();
4588 if (auto Mode = getAllocTokenModeFromString(Name: S))
4589 Opts.AllocTokenMode = Mode;
4590 else
4591 Diags.Report(DiagID: diag::err_drv_invalid_value) << Arg->getAsString(Args) << S;
4592 }
4593
4594 // Enable options for matrix types.
4595 if (Opts.MatrixTypes) {
4596 if (const Arg *A = Args.getLastArg(Ids: OPT_fmatrix_memory_layout_EQ)) {
4597 StringRef ClangValue = A->getValue();
4598 if (ClangValue == "row-major")
4599 Opts.setDefaultMatrixMemoryLayout(
4600 LangOptions::MatrixMemoryLayout::MatrixRowMajor);
4601 else
4602 Opts.setDefaultMatrixMemoryLayout(
4603 LangOptions::MatrixMemoryLayout::MatrixColMajor);
4604
4605 for (Arg *A : Args.filtered(Ids: options::OPT_mllvm)) {
4606 StringRef OptValue = A->getValue();
4607 if (OptValue.consume_front(Prefix: "-matrix-default-layout=") &&
4608 ClangValue != OptValue)
4609 Diags.Report(DiagID: diag::err_conflicting_matrix_layout_flags)
4610 << ClangValue << OptValue;
4611 }
4612 }
4613 }
4614
4615 // Validate options for HLSL
4616 if (Opts.HLSL) {
4617 // TODO: Revisit restricting SPIR-V to logical once we've figured out how to
4618 // handle PhysicalStorageBuffer64 memory model
4619 if (T.isDXIL() || T.isSPIRVLogical()) {
4620 enum { ShaderModel, VulkanEnv, ShaderStage };
4621 enum { OS, Environment };
4622
4623 int ExpectedOS = T.isSPIRVLogical() ? VulkanEnv : ShaderModel;
4624
4625 if (T.getOSName().empty()) {
4626 Diags.Report(DiagID: diag::err_drv_hlsl_bad_shader_required_in_target)
4627 << ExpectedOS << OS << T.str();
4628 } else if (T.getEnvironmentName().empty()) {
4629 Diags.Report(DiagID: diag::err_drv_hlsl_bad_shader_required_in_target)
4630 << ShaderStage << Environment << T.str();
4631 } else if (!T.isShaderStageEnvironment()) {
4632 Diags.Report(DiagID: diag::err_drv_hlsl_bad_shader_unsupported)
4633 << ShaderStage << T.getEnvironmentName() << T.str();
4634 }
4635
4636 if (T.isDXIL()) {
4637 if (!T.isShaderModelOS() || T.getOSVersion() == VersionTuple(0)) {
4638 Diags.Report(DiagID: diag::err_drv_hlsl_bad_shader_unsupported)
4639 << ShaderModel << T.getOSName() << T.str();
4640 }
4641 // Validate that if fnative-half-type is given, that
4642 // the language standard is at least hlsl2018, and that
4643 // the target shader model is at least 6.2.
4644 if (Args.getLastArg(Ids: OPT_fnative_half_type) ||
4645 Args.getLastArg(Ids: OPT_fnative_int16_type)) {
4646 const LangStandard &Std =
4647 LangStandard::getLangStandardForKind(K: Opts.LangStd);
4648 if (!(Opts.LangStd >= LangStandard::lang_hlsl2018 &&
4649 T.getOSVersion() >= VersionTuple(6, 2)))
4650 Diags.Report(DiagID: diag::err_drv_hlsl_16bit_types_unsupported)
4651 << "-enable-16bit-types" << true << Std.getName()
4652 << T.getOSVersion().getAsString();
4653 }
4654 } else if (T.isSPIRVLogical()) {
4655 if (!T.isVulkanOS() || T.getVulkanVersion() == VersionTuple(0)) {
4656 Diags.Report(DiagID: diag::err_drv_hlsl_bad_shader_unsupported)
4657 << VulkanEnv << T.getOSName() << T.str();
4658 }
4659 if (Args.getLastArg(Ids: OPT_fnative_half_type) ||
4660 Args.getLastArg(Ids: OPT_fnative_int16_type)) {
4661 const char *Str = Args.getLastArg(Ids: OPT_fnative_half_type)
4662 ? "-fnative-half-type"
4663 : "-fnative-int16-type";
4664 const LangStandard &Std =
4665 LangStandard::getLangStandardForKind(K: Opts.LangStd);
4666 if (!(Opts.LangStd >= LangStandard::lang_hlsl2018))
4667 Diags.Report(DiagID: diag::err_drv_hlsl_16bit_types_unsupported)
4668 << Str << false << Std.getName();
4669 }
4670 } else {
4671 llvm_unreachable("expected DXIL or SPIR-V target");
4672 }
4673 } else
4674 Diags.Report(DiagID: diag::err_drv_hlsl_unsupported_target) << T.str();
4675
4676 if (Opts.LangStd < LangStandard::lang_hlsl202x) {
4677 const LangStandard &Requested =
4678 LangStandard::getLangStandardForKind(K: Opts.LangStd);
4679 const LangStandard &Recommended =
4680 LangStandard::getLangStandardForKind(K: LangStandard::lang_hlsl202x);
4681 Diags.Report(DiagID: diag::warn_hlsl_langstd_minimal)
4682 << Requested.getName() << Recommended.getName();
4683 }
4684 }
4685
4686 return Diags.getNumErrors() == NumErrorsBefore;
4687}
4688
4689static bool isStrictlyPreprocessorAction(frontend::ActionKind Action) {
4690 switch (Action) {
4691 case frontend::ASTDeclList:
4692 case frontend::ASTDump:
4693 case frontend::ASTPrint:
4694 case frontend::ASTView:
4695 case frontend::EmitAssembly:
4696 case frontend::EmitBC:
4697 case frontend::EmitCIR:
4698 case frontend::EmitHTML:
4699 case frontend::EmitLLVM:
4700 case frontend::EmitLLVMOnly:
4701 case frontend::EmitCodeGenOnly:
4702 case frontend::EmitObj:
4703 case frontend::ExtractAPI:
4704 case frontend::FixIt:
4705 case frontend::GenerateModule:
4706 case frontend::GenerateModuleInterface:
4707 case frontend::GenerateReducedModuleInterface:
4708 case frontend::GenerateHeaderUnit:
4709 case frontend::GeneratePCH:
4710 case frontend::GenerateInterfaceStubs:
4711 case frontend::ParseSyntaxOnly:
4712 case frontend::ModuleFileInfo:
4713 case frontend::VerifyPCH:
4714 case frontend::PluginAction:
4715 case frontend::RewriteObjC:
4716 case frontend::RewriteTest:
4717 case frontend::RunAnalysis:
4718 case frontend::TemplightDump:
4719 return false;
4720
4721 case frontend::DumpCompilerOptions:
4722 case frontend::DumpRawTokens:
4723 case frontend::DumpTokens:
4724 case frontend::InitOnly:
4725 case frontend::PrintPreamble:
4726 case frontend::PrintPreprocessedInput:
4727 case frontend::RewriteMacros:
4728 case frontend::RunPreprocessorOnly:
4729 case frontend::PrintDependencyDirectivesSourceMinimizerOutput:
4730 return true;
4731 }
4732 llvm_unreachable("invalid frontend action");
4733}
4734
4735static bool isCodeGenAction(frontend::ActionKind Action) {
4736 switch (Action) {
4737 case frontend::EmitAssembly:
4738 case frontend::EmitBC:
4739 case frontend::EmitCIR:
4740 case frontend::EmitHTML:
4741 case frontend::EmitLLVM:
4742 case frontend::EmitLLVMOnly:
4743 case frontend::EmitCodeGenOnly:
4744 case frontend::EmitObj:
4745 case frontend::GenerateModule:
4746 case frontend::GenerateModuleInterface:
4747 case frontend::GenerateReducedModuleInterface:
4748 case frontend::GenerateHeaderUnit:
4749 case frontend::GeneratePCH:
4750 case frontend::GenerateInterfaceStubs:
4751 return true;
4752 case frontend::ASTDeclList:
4753 case frontend::ASTDump:
4754 case frontend::ASTPrint:
4755 case frontend::ASTView:
4756 case frontend::ExtractAPI:
4757 case frontend::FixIt:
4758 case frontend::ParseSyntaxOnly:
4759 case frontend::ModuleFileInfo:
4760 case frontend::VerifyPCH:
4761 case frontend::PluginAction:
4762 case frontend::RewriteObjC:
4763 case frontend::RewriteTest:
4764 case frontend::RunAnalysis:
4765 case frontend::TemplightDump:
4766 case frontend::DumpCompilerOptions:
4767 case frontend::DumpRawTokens:
4768 case frontend::DumpTokens:
4769 case frontend::InitOnly:
4770 case frontend::PrintPreamble:
4771 case frontend::PrintPreprocessedInput:
4772 case frontend::RewriteMacros:
4773 case frontend::RunPreprocessorOnly:
4774 case frontend::PrintDependencyDirectivesSourceMinimizerOutput:
4775 return false;
4776 }
4777 llvm_unreachable("invalid frontend action");
4778}
4779
4780static void GeneratePreprocessorArgs(const PreprocessorOptions &Opts,
4781 ArgumentConsumer Consumer,
4782 const LangOptions &LangOpts,
4783 const FrontendOptions &FrontendOpts,
4784 const CodeGenOptions &CodeGenOpts) {
4785 const PreprocessorOptions *PreprocessorOpts = &Opts;
4786
4787#define PREPROCESSOR_OPTION_WITH_MARSHALLING(...) \
4788 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
4789#include "clang/Options/Options.inc"
4790#undef PREPROCESSOR_OPTION_WITH_MARSHALLING
4791
4792 if (Opts.PCHWithHdrStop && !Opts.PCHWithHdrStopCreate)
4793 GenerateArg(Consumer, OptSpecifier: OPT_pch_through_hdrstop_use);
4794
4795 for (const auto &D : Opts.DeserializedPCHDeclsToErrorOn)
4796 GenerateArg(Consumer, OptSpecifier: OPT_error_on_deserialized_pch_decl, Value: D);
4797
4798 if (Opts.PrecompiledPreambleBytes != std::make_pair(x: 0u, y: false))
4799 GenerateArg(Consumer, OptSpecifier: OPT_preamble_bytes_EQ,
4800 Value: Twine(Opts.PrecompiledPreambleBytes.first) + "," +
4801 (Opts.PrecompiledPreambleBytes.second ? "1" : "0"));
4802
4803 for (const auto &M : Opts.Macros) {
4804 // Don't generate __CET__ macro definitions. They are implied by the
4805 // -fcf-protection option that is generated elsewhere.
4806 if (M.first == "__CET__=1" && !M.second &&
4807 !CodeGenOpts.CFProtectionReturn && CodeGenOpts.CFProtectionBranch)
4808 continue;
4809 if (M.first == "__CET__=2" && !M.second && CodeGenOpts.CFProtectionReturn &&
4810 !CodeGenOpts.CFProtectionBranch)
4811 continue;
4812 if (M.first == "__CET__=3" && !M.second && CodeGenOpts.CFProtectionReturn &&
4813 CodeGenOpts.CFProtectionBranch)
4814 continue;
4815
4816 GenerateArg(Consumer, OptSpecifier: M.second ? OPT_U : OPT_D, Value: M.first);
4817 }
4818
4819 for (const auto &I : Opts.Includes) {
4820 // Don't generate OpenCL includes. They are implied by other flags that are
4821 // generated elsewhere.
4822 if (LangOpts.OpenCL && LangOpts.IncludeDefaultHeader &&
4823 ((LangOpts.DeclareOpenCLBuiltins && I == "opencl-c-base.h") ||
4824 I == "opencl-c.h"))
4825 continue;
4826 // Don't generate HLSL includes. They are implied by other flags that are
4827 // generated elsewhere.
4828 if (LangOpts.HLSL && I == "hlsl.h")
4829 continue;
4830
4831 GenerateArg(Consumer, OptSpecifier: OPT_include, Value: I);
4832 }
4833
4834 for (const auto &CI : Opts.ChainedIncludes)
4835 GenerateArg(Consumer, OptSpecifier: OPT_chain_include, Value: CI);
4836
4837 for (const auto &RF : Opts.RemappedFiles)
4838 GenerateArg(Consumer, OptSpecifier: OPT_remap_file, Value: RF.first + ";" + RF.second);
4839
4840 if (Opts.SourceDateEpoch)
4841 GenerateArg(Consumer, OptSpecifier: OPT_source_date_epoch, Value: Twine(*Opts.SourceDateEpoch));
4842
4843 if (Opts.DefineTargetOSMacros)
4844 GenerateArg(Consumer, OptSpecifier: OPT_fdefine_target_os_macros);
4845
4846 for (const auto &EmbedEntry : Opts.EmbedEntries)
4847 GenerateArg(Consumer, OptSpecifier: OPT_embed_dir_EQ, Value: EmbedEntry);
4848
4849 // Don't handle LexEditorPlaceholders. It is implied by the action that is
4850 // generated elsewhere.
4851}
4852
4853static bool ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args,
4854 DiagnosticsEngine &Diags,
4855 frontend::ActionKind Action,
4856 const FrontendOptions &FrontendOpts) {
4857 unsigned NumErrorsBefore = Diags.getNumErrors();
4858
4859 PreprocessorOptions *PreprocessorOpts = &Opts;
4860
4861#define PREPROCESSOR_OPTION_WITH_MARSHALLING(...) \
4862 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
4863#include "clang/Options/Options.inc"
4864#undef PREPROCESSOR_OPTION_WITH_MARSHALLING
4865
4866 Opts.PCHWithHdrStop = Args.hasArg(Ids: OPT_pch_through_hdrstop_create) ||
4867 Args.hasArg(Ids: OPT_pch_through_hdrstop_use);
4868
4869 for (const auto *A : Args.filtered(Ids: OPT_error_on_deserialized_pch_decl))
4870 Opts.DeserializedPCHDeclsToErrorOn.insert(x: A->getValue());
4871
4872 if (const Arg *A = Args.getLastArg(Ids: OPT_preamble_bytes_EQ)) {
4873 StringRef Value(A->getValue());
4874 size_t Comma = Value.find(C: ',');
4875 unsigned Bytes = 0;
4876 unsigned EndOfLine = 0;
4877
4878 if (Comma == StringRef::npos ||
4879 Value.substr(Start: 0, N: Comma).getAsInteger(Radix: 10, Result&: Bytes) ||
4880 Value.substr(Start: Comma + 1).getAsInteger(Radix: 10, Result&: EndOfLine))
4881 Diags.Report(DiagID: diag::err_drv_preamble_format);
4882 else {
4883 Opts.PrecompiledPreambleBytes.first = Bytes;
4884 Opts.PrecompiledPreambleBytes.second = (EndOfLine != 0);
4885 }
4886 }
4887
4888 // Add macros from the command line.
4889 for (const auto *A : Args.filtered(Ids: OPT_D, Ids: OPT_U)) {
4890 if (A->getOption().matches(ID: OPT_D))
4891 Opts.addMacroDef(Name: A->getValue());
4892 else
4893 Opts.addMacroUndef(Name: A->getValue());
4894 }
4895
4896 // Add the ordered list of -includes.
4897 for (const auto *A : Args.filtered(Ids: OPT_include))
4898 Opts.Includes.emplace_back(args: A->getValue());
4899
4900 for (const auto *A : Args.filtered(Ids: OPT_chain_include))
4901 Opts.ChainedIncludes.emplace_back(args: A->getValue());
4902
4903 for (const auto *A : Args.filtered(Ids: OPT_remap_file)) {
4904 std::pair<StringRef, StringRef> Split = StringRef(A->getValue()).split(Separator: ';');
4905
4906 if (Split.second.empty()) {
4907 Diags.Report(DiagID: diag::err_drv_invalid_remap_file) << A->getAsString(Args);
4908 continue;
4909 }
4910
4911 Opts.addRemappedFile(From: Split.first, To: Split.second);
4912 }
4913
4914 if (const Arg *A = Args.getLastArg(Ids: OPT_source_date_epoch)) {
4915 StringRef Epoch = A->getValue();
4916 // SOURCE_DATE_EPOCH, if specified, must be a non-negative decimal integer.
4917 // On time64 systems, pick 253402300799 (the UNIX timestamp of
4918 // 9999-12-31T23:59:59Z) as the upper bound.
4919 const uint64_t MaxTimestamp =
4920 std::min<uint64_t>(a: std::numeric_limits<time_t>::max(), b: 253402300799);
4921 uint64_t V;
4922 if (Epoch.getAsInteger(Radix: 10, Result&: V) || V > MaxTimestamp) {
4923 Diags.Report(DiagID: diag::err_fe_invalid_source_date_epoch)
4924 << Epoch << MaxTimestamp;
4925 } else {
4926 Opts.SourceDateEpoch = V;
4927 }
4928 }
4929
4930 for (const auto *A : Args.filtered(Ids: OPT_embed_dir_EQ)) {
4931 StringRef Val = A->getValue();
4932 Opts.EmbedEntries.push_back(x: std::string(Val));
4933 }
4934
4935 // Always avoid lexing editor placeholders when we're just running the
4936 // preprocessor as we never want to emit the
4937 // "editor placeholder in source file" error in PP only mode.
4938 if (isStrictlyPreprocessorAction(Action))
4939 Opts.LexEditorPlaceholders = false;
4940
4941 Opts.DefineTargetOSMacros =
4942 Args.hasFlag(Pos: OPT_fdefine_target_os_macros,
4943 Neg: OPT_fno_define_target_os_macros, Default: Opts.DefineTargetOSMacros);
4944
4945 return Diags.getNumErrors() == NumErrorsBefore;
4946}
4947
4948static void
4949GeneratePreprocessorOutputArgs(const PreprocessorOutputOptions &Opts,
4950 ArgumentConsumer Consumer,
4951 frontend::ActionKind Action) {
4952 const PreprocessorOutputOptions &PreprocessorOutputOpts = Opts;
4953
4954#define PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING(...) \
4955 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
4956#include "clang/Options/Options.inc"
4957#undef PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING
4958
4959 bool Generate_dM = isStrictlyPreprocessorAction(Action) && !Opts.ShowCPP;
4960 if (Generate_dM)
4961 GenerateArg(Consumer, OptSpecifier: OPT_dM);
4962 if (!Generate_dM && Opts.ShowMacros)
4963 GenerateArg(Consumer, OptSpecifier: OPT_dD);
4964 if (Opts.DirectivesOnly)
4965 GenerateArg(Consumer, OptSpecifier: OPT_fdirectives_only);
4966}
4967
4968static bool ParsePreprocessorOutputArgs(PreprocessorOutputOptions &Opts,
4969 ArgList &Args, DiagnosticsEngine &Diags,
4970 frontend::ActionKind Action) {
4971 unsigned NumErrorsBefore = Diags.getNumErrors();
4972
4973 PreprocessorOutputOptions &PreprocessorOutputOpts = Opts;
4974
4975#define PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING(...) \
4976 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
4977#include "clang/Options/Options.inc"
4978#undef PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING
4979
4980 Opts.ShowCPP = isStrictlyPreprocessorAction(Action) && !Args.hasArg(Ids: OPT_dM);
4981 Opts.ShowMacros = Args.hasArg(Ids: OPT_dM) || Args.hasArg(Ids: OPT_dD);
4982 Opts.DirectivesOnly = Args.hasArg(Ids: OPT_fdirectives_only);
4983
4984 return Diags.getNumErrors() == NumErrorsBefore;
4985}
4986
4987static void GenerateTargetArgs(const TargetOptions &Opts,
4988 ArgumentConsumer Consumer) {
4989 const TargetOptions *TargetOpts = &Opts;
4990#define TARGET_OPTION_WITH_MARSHALLING(...) \
4991 GENERATE_OPTION_WITH_MARSHALLING(Consumer, __VA_ARGS__)
4992#include "clang/Options/Options.inc"
4993#undef TARGET_OPTION_WITH_MARSHALLING
4994
4995 if (!Opts.SDKVersion.empty())
4996 GenerateArg(Consumer, OptSpecifier: OPT_target_sdk_version_EQ,
4997 Value: Opts.SDKVersion.getAsString());
4998 if (!Opts.DarwinTargetVariantSDKVersion.empty())
4999 GenerateArg(Consumer, OptSpecifier: OPT_darwin_target_variant_sdk_version_EQ,
5000 Value: Opts.DarwinTargetVariantSDKVersion.getAsString());
5001}
5002
5003static bool ParseTargetArgs(TargetOptions &Opts, ArgList &Args,
5004 DiagnosticsEngine &Diags) {
5005 unsigned NumErrorsBefore = Diags.getNumErrors();
5006
5007 TargetOptions *TargetOpts = &Opts;
5008
5009#define TARGET_OPTION_WITH_MARSHALLING(...) \
5010 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, __VA_ARGS__)
5011#include "clang/Options/Options.inc"
5012#undef TARGET_OPTION_WITH_MARSHALLING
5013
5014 if (Arg *A = Args.getLastArg(Ids: options::OPT_target_sdk_version_EQ)) {
5015 llvm::VersionTuple Version;
5016 if (Version.tryParse(string: A->getValue()))
5017 Diags.Report(DiagID: diag::err_drv_invalid_value)
5018 << A->getAsString(Args) << A->getValue();
5019 else
5020 Opts.SDKVersion = Version;
5021 }
5022 if (Arg *A =
5023 Args.getLastArg(Ids: options::OPT_darwin_target_variant_sdk_version_EQ)) {
5024 llvm::VersionTuple Version;
5025 if (Version.tryParse(string: A->getValue()))
5026 Diags.Report(DiagID: diag::err_drv_invalid_value)
5027 << A->getAsString(Args) << A->getValue();
5028 else
5029 Opts.DarwinTargetVariantSDKVersion = Version;
5030 }
5031
5032 return Diags.getNumErrors() == NumErrorsBefore;
5033}
5034
5035bool CompilerInvocation::CreateFromArgsImpl(
5036 CompilerInvocation &Res, ArrayRef<const char *> CommandLineArgs,
5037 DiagnosticsEngine &Diags, const char *Argv0) {
5038 unsigned NumErrorsBefore = Diags.getNumErrors();
5039
5040 // Parse the arguments.
5041 const OptTable &Opts = getDriverOptTable();
5042 llvm::opt::Visibility VisibilityMask(options::CC1Option);
5043 unsigned MissingArgIndex, MissingArgCount;
5044 InputArgList Args = Opts.ParseArgs(Args: CommandLineArgs, MissingArgIndex,
5045 MissingArgCount, VisibilityMask);
5046 LangOptions &LangOpts = Res.getLangOpts();
5047
5048 // Check for missing argument error.
5049 if (MissingArgCount)
5050 Diags.Report(DiagID: diag::err_drv_missing_argument)
5051 << Args.getArgString(Index: MissingArgIndex) << MissingArgCount;
5052
5053 // Issue errors on unknown arguments.
5054 for (const auto *A : Args.filtered(Ids: OPT_UNKNOWN)) {
5055 auto ArgString = A->getAsString(Args);
5056 std::string Nearest;
5057 if (Opts.findNearest(Option: ArgString, NearestString&: Nearest, VisibilityMask) > 1)
5058 Diags.Report(DiagID: diag::err_drv_unknown_argument) << ArgString;
5059 else
5060 Diags.Report(DiagID: diag::err_drv_unknown_argument_with_suggestion)
5061 << ArgString << Nearest;
5062 }
5063
5064 ParseFileSystemArgs(Opts&: Res.getFileSystemOpts(), Args, Diags);
5065 ParseMigratorArgs(Opts&: Res.getMigratorOpts(), Args, Diags);
5066 ParseAnalyzerArgs(Opts&: Res.getAnalyzerOpts(), Args, Diags);
5067 ParseDiagnosticArgs(Opts&: Res.getDiagnosticOpts(), Args, Diags: &Diags,
5068 /*DefaultDiagColor=*/false);
5069 ParseFrontendArgs(Opts&: Res.getFrontendOpts(), Args, Diags, IsHeaderFile&: LangOpts.IsHeaderFile);
5070 // FIXME: We shouldn't have to pass the DashX option around here
5071 InputKind DashX = Res.getFrontendOpts().DashX;
5072 ParseTargetArgs(Opts&: Res.getTargetOpts(), Args, Diags);
5073 llvm::Triple T(Res.getTargetOpts().Triple);
5074 ParseHeaderSearchArgs(Opts&: Res.getHeaderSearchOpts(), Args, Diags);
5075 if (Res.getFrontendOpts().GenReducedBMI ||
5076 Res.getFrontendOpts().ProgramAction ==
5077 frontend::GenerateReducedModuleInterface ||
5078 Res.getFrontendOpts().ProgramAction ==
5079 frontend::GenerateModuleInterface) {
5080 Res.getHeaderSearchOpts().ModulesSkipDiagnosticOptions = true;
5081 Res.getHeaderSearchOpts().ModulesSkipHeaderSearchPaths = true;
5082 }
5083 ParseAPINotesArgs(Opts&: Res.getAPINotesOpts(), Args, diags&: Diags);
5084
5085 ParsePointerAuthArgs(Opts&: LangOpts, Args, Diags);
5086
5087 ParseLangArgs(Opts&: LangOpts, Args, IK: DashX, T, Includes&: Res.getPreprocessorOpts().Includes,
5088 Diags);
5089 if (Res.getFrontendOpts().ProgramAction == frontend::RewriteObjC)
5090 LangOpts.ObjCExceptions = 1;
5091
5092 for (auto Warning : Res.getDiagnosticOpts().Warnings) {
5093 if (Warning == "misexpect" &&
5094 !Diags.isIgnored(DiagID: diag::warn_profile_data_misexpect, Loc: SourceLocation())) {
5095 Res.getCodeGenOpts().MisExpect = true;
5096 }
5097 }
5098
5099 if (LangOpts.CUDA) {
5100 // During CUDA device-side compilation, the aux triple is the
5101 // triple used for host compilation.
5102 if (LangOpts.CUDAIsDevice)
5103 Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple;
5104 }
5105
5106 if (LangOpts.OpenACC && !Res.getFrontendOpts().UseClangIRPipeline &&
5107 isCodeGenAction(Action: Res.getFrontendOpts().ProgramAction))
5108 Diags.Report(DiagID: diag::warn_drv_openacc_without_cir);
5109
5110 // Set the triple of the host for OpenMP device compile.
5111 if (LangOpts.OpenMPIsTargetDevice)
5112 Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple;
5113
5114 ParseCodeGenArgs(Opts&: Res.getCodeGenOpts(), Args, IK: DashX, Diags, T,
5115 OutputFile: Res.getFrontendOpts().OutputFile, LangOptsRef: LangOpts);
5116
5117 // FIXME: Override value name discarding when asan or msan is used because the
5118 // backend passes depend on the name of the alloca in order to print out
5119 // names.
5120 Res.getCodeGenOpts().DiscardValueNames &=
5121 !LangOpts.Sanitize.has(K: SanitizerKind::Address) &&
5122 !LangOpts.Sanitize.has(K: SanitizerKind::KernelAddress) &&
5123 !LangOpts.Sanitize.has(K: SanitizerKind::Memory) &&
5124 !LangOpts.Sanitize.has(K: SanitizerKind::KernelMemory);
5125
5126 ParsePreprocessorArgs(Opts&: Res.getPreprocessorOpts(), Args, Diags,
5127 Action: Res.getFrontendOpts().ProgramAction,
5128 FrontendOpts: Res.getFrontendOpts());
5129 ParsePreprocessorOutputArgs(Opts&: Res.getPreprocessorOutputOpts(), Args, Diags,
5130 Action: Res.getFrontendOpts().ProgramAction);
5131
5132 ParseDependencyOutputArgs(Opts&: Res.getDependencyOutputOpts(), Args, Diags,
5133 Action: Res.getFrontendOpts().ProgramAction,
5134 ShowLineMarkers: Res.getPreprocessorOutputOpts().ShowLineMarkers);
5135 if (!Res.getDependencyOutputOpts().OutputFile.empty() &&
5136 Res.getDependencyOutputOpts().Targets.empty())
5137 Diags.Report(DiagID: diag::err_fe_dependency_file_requires_MT);
5138
5139 // If sanitizer is enabled, disable OPT_ffine_grained_bitfield_accesses.
5140 if (Res.getCodeGenOpts().FineGrainedBitfieldAccesses &&
5141 !Res.getLangOpts().Sanitize.empty()) {
5142 Res.getCodeGenOpts().FineGrainedBitfieldAccesses = false;
5143 Diags.Report(DiagID: diag::warn_drv_fine_grained_bitfield_accesses_ignored);
5144 }
5145
5146 // Store the command-line for using in the CodeView backend.
5147 if (Res.getCodeGenOpts().CodeViewCommandLine) {
5148 Res.getCodeGenOpts().Argv0 = Argv0;
5149 append_range(C&: Res.getCodeGenOpts().CommandLineArgs, R&: CommandLineArgs);
5150 }
5151
5152 if (!Res.getCodeGenOpts().ProfileInstrumentUsePath.empty() &&
5153 Res.getCodeGenOpts().getProfileUse() ==
5154 llvm::driver::ProfileInstrKind::ProfileNone)
5155 Diags.Report(DiagID: diag::err_drv_profile_instrument_use_path_with_no_kind);
5156
5157 FixupInvocation(Invocation&: Res, Diags, Args, IK: DashX);
5158
5159 return Diags.getNumErrors() == NumErrorsBefore;
5160}
5161
5162bool CompilerInvocation::CreateFromArgs(CompilerInvocation &Invocation,
5163 ArrayRef<const char *> CommandLineArgs,
5164 DiagnosticsEngine &Diags,
5165 const char *Argv0) {
5166 CompilerInvocation DummyInvocation;
5167
5168 return RoundTrip(
5169 Parse: [](CompilerInvocation &Invocation, ArrayRef<const char *> CommandLineArgs,
5170 DiagnosticsEngine &Diags, const char *Argv0) {
5171 return CreateFromArgsImpl(Res&: Invocation, CommandLineArgs, Diags, Argv0);
5172 },
5173 Generate: [](CompilerInvocation &Invocation, SmallVectorImpl<const char *> &Args,
5174 StringAllocator SA) {
5175 Args.push_back(Elt: "-cc1");
5176 Invocation.generateCC1CommandLine(Args, SA);
5177 },
5178 RealInvocation&: Invocation, DummyInvocation, CommandLineArgs, Diags, Argv0);
5179}
5180
5181std::string CompilerInvocation::computeContextHash() const {
5182 // FIXME: Consider using SHA1 instead of MD5.
5183 llvm::HashBuilder<llvm::MD5, llvm::endianness::native> HBuilder;
5184
5185 // Note: For QoI reasons, the things we use as a hash here should all be
5186 // dumped via the -module-info flag.
5187
5188 // Start the signature with the compiler version.
5189 HBuilder.add(Value: getClangFullRepositoryVersion());
5190
5191 // Also include the serialization version, in case LLVM_APPEND_VC_REV is off
5192 // and getClangFullRepositoryVersion() doesn't include git revision.
5193 HBuilder.add(Args: serialization::VERSION_MAJOR, Args: serialization::VERSION_MINOR);
5194
5195 // Extend the signature with the language options
5196 // FIXME: Replace with C++20 `using enum LangOptions::CompatibilityKind`.
5197 using CK = LangOptions::CompatibilityKind;
5198#define LANGOPT(Name, Bits, Default, Compatibility, Description) \
5199 if constexpr (CK::Compatibility != CK::Benign) \
5200 HBuilder.add(LangOpts->Name);
5201#define ENUM_LANGOPT(Name, Type, Bits, Default, Compatibility, Description) \
5202 if constexpr (CK::Compatibility != CK::Benign) \
5203 HBuilder.add(static_cast<unsigned>(LangOpts->get##Name()));
5204#include "clang/Basic/LangOptions.def"
5205
5206 HBuilder.addRange(Range: getLangOpts().ModuleFeatures);
5207
5208 HBuilder.add(Value: getLangOpts().ObjCRuntime);
5209 HBuilder.addRange(Range: getLangOpts().CommentOpts.BlockCommandNames);
5210
5211 // Extend the signature with the target options.
5212 HBuilder.add(Args: getTargetOpts().Triple, Args: getTargetOpts().CPU,
5213 Args: getTargetOpts().TuneCPU, Args: getTargetOpts().ABI);
5214 HBuilder.addRange(Range: getTargetOpts().FeaturesAsWritten);
5215
5216 // Extend the signature with preprocessor options.
5217 const PreprocessorOptions &ppOpts = getPreprocessorOpts();
5218 HBuilder.add(Args: ppOpts.UsePredefines, Args: ppOpts.DetailedRecord);
5219
5220 const HeaderSearchOptions &hsOpts = getHeaderSearchOpts();
5221 for (const auto &Macro : getPreprocessorOpts().Macros) {
5222 // If we're supposed to ignore this macro for the purposes of modules,
5223 // don't put it into the hash.
5224 if (!hsOpts.ModulesIgnoreMacros.empty()) {
5225 // Check whether we're ignoring this macro.
5226 StringRef MacroDef = Macro.first;
5227 if (hsOpts.ModulesIgnoreMacros.count(
5228 key: llvm::CachedHashString(MacroDef.split(Separator: '=').first)))
5229 continue;
5230 }
5231
5232 HBuilder.add(Value: Macro);
5233 }
5234
5235 // Extend the signature with the sysroot and other header search options.
5236 HBuilder.add(Args: hsOpts.Sysroot, Args: hsOpts.ModuleFormat, Args: hsOpts.UseDebugInfo,
5237 Args: hsOpts.UseBuiltinIncludes, Args: hsOpts.UseStandardSystemIncludes,
5238 Args: hsOpts.UseStandardCXXIncludes, Args: hsOpts.UseLibcxx,
5239 Args: hsOpts.ModulesValidateDiagnosticOptions);
5240 HBuilder.add(Value: hsOpts.ResourceDir);
5241
5242 if (hsOpts.ModulesStrictContextHash) {
5243 HBuilder.addRange(Range: hsOpts.SystemHeaderPrefixes);
5244 HBuilder.addRange(Range: hsOpts.UserEntries);
5245 HBuilder.addRange(Range: hsOpts.VFSOverlayFiles);
5246
5247 const DiagnosticOptions &diagOpts = getDiagnosticOpts();
5248#define DIAGOPT(Name, Bits, Default) HBuilder.add(diagOpts.Name);
5249#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
5250 HBuilder.add(diagOpts.get##Name());
5251#include "clang/Basic/DiagnosticOptions.def"
5252#undef DIAGOPT
5253#undef ENUM_DIAGOPT
5254 }
5255
5256 // Extend the signature with the user build path.
5257 HBuilder.add(Value: hsOpts.ModuleUserBuildPath);
5258
5259 // Extend the signature with the module file extensions.
5260 for (const auto &ext : getFrontendOpts().ModuleFileExtensions)
5261 ext->hashExtension(HBuilder);
5262
5263 // Extend the signature with the Swift version for API notes.
5264 const APINotesOptions &APINotesOpts = getAPINotesOpts();
5265 if (!APINotesOpts.SwiftVersion.empty()) {
5266 HBuilder.add(Value: APINotesOpts.SwiftVersion.getMajor());
5267 if (auto Minor = APINotesOpts.SwiftVersion.getMinor())
5268 HBuilder.add(Value: *Minor);
5269 if (auto Subminor = APINotesOpts.SwiftVersion.getSubminor())
5270 HBuilder.add(Value: *Subminor);
5271 if (auto Build = APINotesOpts.SwiftVersion.getBuild())
5272 HBuilder.add(Value: *Build);
5273 }
5274
5275 // Extend the signature with affecting codegen options.
5276 {
5277 using CK = CodeGenOptions::CompatibilityKind;
5278#define CODEGENOPT(Name, Bits, Default, Compatibility) \
5279 if constexpr (CK::Compatibility != CK::Benign) \
5280 HBuilder.add(CodeGenOpts->Name);
5281#define ENUM_CODEGENOPT(Name, Type, Bits, Default, Compatibility) \
5282 if constexpr (CK::Compatibility != CK::Benign) \
5283 HBuilder.add(static_cast<unsigned>(CodeGenOpts->get##Name()));
5284#define DEBUGOPT(Name, Bits, Default, Compatibility)
5285#define VALUE_DEBUGOPT(Name, Bits, Default, Compatibility)
5286#define ENUM_DEBUGOPT(Name, Type, Bits, Default, Compatibility)
5287#include "clang/Basic/CodeGenOptions.def"
5288 }
5289
5290 // When compiling with -gmodules, also hash -fdebug-prefix-map as it
5291 // affects the debug info in the PCM.
5292 if (getCodeGenOpts().DebugTypeExtRefs)
5293 HBuilder.addRange(Range: getCodeGenOpts().DebugPrefixMap);
5294
5295 // Extend the signature with the affecting debug options.
5296 if (getHeaderSearchOpts().ModuleFormat == "obj") {
5297 // FIXME: Replace with C++20 `using enum CodeGenOptions::CompatibilityKind`.
5298 using CK = CodeGenOptions::CompatibilityKind;
5299#define DEBUGOPT(Name, Bits, Default, Compatibility) \
5300 if constexpr (CK::Compatibility != CK::Benign) \
5301 HBuilder.add(CodeGenOpts->Name);
5302#define VALUE_DEBUGOPT(Name, Bits, Default, Compatibility) \
5303 if constexpr (CK::Compatibility != CK::Benign) \
5304 HBuilder.add(CodeGenOpts->Name);
5305#define ENUM_DEBUGOPT(Name, Type, Bits, Default, Compatibility) \
5306 if constexpr (CK::Compatibility != CK::Benign) \
5307 HBuilder.add(static_cast<unsigned>(CodeGenOpts->get##Name()));
5308#include "clang/Basic/DebugOptions.def"
5309 }
5310
5311 // Extend the signature with the enabled sanitizers, if at least one is
5312 // enabled. Sanitizers which cannot affect AST generation aren't hashed.
5313 SanitizerSet SanHash = getLangOpts().Sanitize;
5314 SanHash.clear(K: getPPTransparentSanitizers());
5315 if (!SanHash.empty())
5316 HBuilder.add(Value: SanHash.Mask);
5317
5318 llvm::MD5::MD5Result Result;
5319 HBuilder.getHasher().final(Result);
5320 uint64_t Hash = Result.high() ^ Result.low();
5321 return toString(I: llvm::APInt(64, Hash), Radix: 36, /*Signed=*/false);
5322}
5323
5324void CompilerInvocationBase::visitPathsImpl(
5325 llvm::function_ref<bool(std::string &)> Predicate) {
5326#define RETURN_IF(PATH) \
5327 do { \
5328 if (Predicate(PATH)) \
5329 return; \
5330 } while (0)
5331
5332#define RETURN_IF_MANY(PATHS) \
5333 do { \
5334 if (llvm::any_of(PATHS, Predicate)) \
5335 return; \
5336 } while (0)
5337
5338 auto &HeaderSearchOpts = *this->HSOpts;
5339 // Header search paths.
5340 RETURN_IF(HeaderSearchOpts.Sysroot);
5341 for (auto &Entry : HeaderSearchOpts.UserEntries)
5342 if (Entry.IgnoreSysRoot)
5343 RETURN_IF(Entry.Path);
5344 RETURN_IF(HeaderSearchOpts.ResourceDir);
5345 RETURN_IF(HeaderSearchOpts.ModuleCachePath);
5346 RETURN_IF(HeaderSearchOpts.ModuleUserBuildPath);
5347 for (auto &[Name, File] : HeaderSearchOpts.PrebuiltModuleFiles)
5348 RETURN_IF(File);
5349 RETURN_IF_MANY(HeaderSearchOpts.PrebuiltModulePaths);
5350 RETURN_IF_MANY(HeaderSearchOpts.VFSOverlayFiles);
5351
5352 // Preprocessor options.
5353 auto &PPOpts = *this->PPOpts;
5354 RETURN_IF_MANY(PPOpts.MacroIncludes);
5355 RETURN_IF_MANY(PPOpts.Includes);
5356 RETURN_IF(PPOpts.ImplicitPCHInclude);
5357
5358 // Frontend options.
5359 auto &FrontendOpts = *this->FrontendOpts;
5360 for (auto &Input : FrontendOpts.Inputs) {
5361 if (Input.isBuffer())
5362 continue;
5363
5364 RETURN_IF(Input.File);
5365 }
5366 // TODO: Also report output files such as FrontendOpts.OutputFile;
5367 RETURN_IF(FrontendOpts.CodeCompletionAt.FileName);
5368 RETURN_IF_MANY(FrontendOpts.ModuleMapFiles);
5369 RETURN_IF_MANY(FrontendOpts.ModuleFiles);
5370 RETURN_IF_MANY(FrontendOpts.ModulesEmbedFiles);
5371 RETURN_IF_MANY(FrontendOpts.ASTMergeFiles);
5372 RETURN_IF(FrontendOpts.OverrideRecordLayoutsFile);
5373 RETURN_IF(FrontendOpts.StatsFile);
5374
5375 // Filesystem options.
5376 auto &FileSystemOpts = *this->FSOpts;
5377 RETURN_IF(FileSystemOpts.WorkingDir);
5378
5379 // Codegen options.
5380 auto &CodeGenOpts = *this->CodeGenOpts;
5381 RETURN_IF(CodeGenOpts.DebugCompilationDir);
5382 RETURN_IF(CodeGenOpts.CoverageCompilationDir);
5383
5384 // Sanitizer options.
5385 RETURN_IF_MANY(LangOpts->NoSanitizeFiles);
5386
5387 // Coverage mappings.
5388 RETURN_IF(CodeGenOpts.ProfileInstrumentUsePath);
5389 RETURN_IF(CodeGenOpts.SampleProfileFile);
5390 RETURN_IF(CodeGenOpts.ProfileRemappingFile);
5391
5392 // Dependency output options.
5393 for (auto &ExtraDep : DependencyOutputOpts->ExtraDeps)
5394 RETURN_IF(ExtraDep.first);
5395}
5396
5397void CompilerInvocationBase::visitPaths(
5398 llvm::function_ref<bool(StringRef)> Callback) const {
5399 // The const_cast here is OK, because visitPathsImpl() itself doesn't modify
5400 // the invocation, and our callback takes immutable StringRefs.
5401 return const_cast<CompilerInvocationBase *>(this)->visitPathsImpl(
5402 Predicate: [&Callback](std::string &Path) { return Callback(StringRef(Path)); });
5403}
5404
5405void CompilerInvocationBase::generateCC1CommandLine(
5406 ArgumentConsumer Consumer) const {
5407 llvm::Triple T(getTargetOpts().Triple);
5408
5409 GenerateFileSystemArgs(Opts: getFileSystemOpts(), Consumer);
5410 GenerateMigratorArgs(Opts: getMigratorOpts(), Consumer);
5411 GenerateAnalyzerArgs(Opts: getAnalyzerOpts(), Consumer);
5412 GenerateDiagnosticArgs(Opts: getDiagnosticOpts(), Consumer,
5413 /*DefaultDiagColor=*/false);
5414 GenerateFrontendArgs(Opts: getFrontendOpts(), Consumer, IsHeader: getLangOpts().IsHeaderFile);
5415 GenerateTargetArgs(Opts: getTargetOpts(), Consumer);
5416 GenerateHeaderSearchArgs(Opts: getHeaderSearchOpts(), Consumer);
5417 GenerateAPINotesArgs(Opts: getAPINotesOpts(), Consumer);
5418 GeneratePointerAuthArgs(Opts: getLangOpts(), Consumer);
5419 GenerateLangArgs(Opts: getLangOpts(), Consumer, T, IK: getFrontendOpts().DashX);
5420 GenerateCodeGenArgs(Opts: getCodeGenOpts(), Consumer, T,
5421 OutputFile: getFrontendOpts().OutputFile, LangOpts: &getLangOpts());
5422 GeneratePreprocessorArgs(Opts: getPreprocessorOpts(), Consumer, LangOpts: getLangOpts(),
5423 FrontendOpts: getFrontendOpts(), CodeGenOpts: getCodeGenOpts());
5424 GeneratePreprocessorOutputArgs(Opts: getPreprocessorOutputOpts(), Consumer,
5425 Action: getFrontendOpts().ProgramAction);
5426 GenerateDependencyOutputArgs(Opts: getDependencyOutputOpts(), Consumer);
5427}
5428
5429std::vector<std::string> CompilerInvocationBase::getCC1CommandLine() const {
5430 std::vector<std::string> Args{"-cc1"};
5431 generateCC1CommandLine(
5432 Consumer: [&Args](const Twine &Arg) { Args.push_back(x: Arg.str()); });
5433 return Args;
5434}
5435
5436void CompilerInvocation::resetNonModularOptions() {
5437 getLangOpts().resetNonModularOptions();
5438 getPreprocessorOpts().resetNonModularOptions();
5439 getCodeGenOpts().resetNonModularOptions(ModuleFormat: getHeaderSearchOpts().ModuleFormat);
5440}
5441
5442void CompilerInvocation::clearImplicitModuleBuildOptions() {
5443 getLangOpts().ImplicitModules = false;
5444 getHeaderSearchOpts().ImplicitModuleMaps = false;
5445 getHeaderSearchOpts().ModuleCachePath.clear();
5446 getHeaderSearchOpts().ModulesValidateOncePerBuildSession = false;
5447 getHeaderSearchOpts().BuildSessionTimestamp = 0;
5448 // The specific values we canonicalize to for pruning don't affect behaviour,
5449 /// so use the default values so they may be dropped from the command-line.
5450 getHeaderSearchOpts().ModuleCachePruneInterval = 7 * 24 * 60 * 60;
5451 getHeaderSearchOpts().ModuleCachePruneAfter = 31 * 24 * 60 * 60;
5452}
5453
5454IntrusiveRefCntPtr<llvm::vfs::FileSystem>
5455clang::createVFSFromCompilerInvocation(const CompilerInvocation &CI,
5456 DiagnosticsEngine &Diags) {
5457 return createVFSFromCompilerInvocation(CI, Diags,
5458 BaseFS: llvm::vfs::getRealFileSystem());
5459}
5460
5461IntrusiveRefCntPtr<llvm::vfs::FileSystem>
5462clang::createVFSFromCompilerInvocation(
5463 const CompilerInvocation &CI, DiagnosticsEngine &Diags,
5464 IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS) {
5465 return createVFSFromOverlayFiles(VFSOverlayFiles: CI.getHeaderSearchOpts().VFSOverlayFiles,
5466 Diags, BaseFS: std::move(BaseFS));
5467}
5468
5469IntrusiveRefCntPtr<llvm::vfs::FileSystem> clang::createVFSFromOverlayFiles(
5470 ArrayRef<std::string> VFSOverlayFiles, DiagnosticsEngine &Diags,
5471 IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS) {
5472 if (VFSOverlayFiles.empty())
5473 return BaseFS;
5474
5475 IntrusiveRefCntPtr<llvm::vfs::FileSystem> Result = BaseFS;
5476 // earlier vfs files are on the bottom
5477 for (const auto &File : VFSOverlayFiles) {
5478 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
5479 Result->getBufferForFile(Name: File);
5480 if (!Buffer) {
5481 Diags.Report(DiagID: diag::err_missing_vfs_overlay_file) << File;
5482 continue;
5483 }
5484
5485 IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS = llvm::vfs::getVFSFromYAML(
5486 Buffer: std::move(Buffer.get()), /*DiagHandler*/ nullptr, YAMLFilePath: File,
5487 /*DiagContext*/ nullptr, ExternalFS: Result);
5488 if (!FS) {
5489 Diags.Report(DiagID: diag::err_invalid_vfs_overlay) << File;
5490 continue;
5491 }
5492
5493 Result = FS;
5494 }
5495 return Result;
5496}
5497