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