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