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