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