xref: /llvm-project/clang/lib/Frontend/CompilerInvocation.cpp (revision 70410a264949101ced3ce3458f37dd4cc2f5af85)
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/Utils.h"
42 #include "clang/Lex/HeaderSearchOptions.h"
43 #include "clang/Lex/PreprocessorOptions.h"
44 #include "clang/Sema/CodeCompleteOptions.h"
45 #include "clang/Serialization/ASTBitCodes.h"
46 #include "clang/Serialization/ModuleFileExtension.h"
47 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
48 #include "llvm/ADT/APInt.h"
49 #include "llvm/ADT/ArrayRef.h"
50 #include "llvm/ADT/CachedHashString.h"
51 #include "llvm/ADT/FloatingPointMode.h"
52 #include "llvm/ADT/Hashing.h"
53 #include "llvm/ADT/None.h"
54 #include "llvm/ADT/Optional.h"
55 #include "llvm/ADT/SmallString.h"
56 #include "llvm/ADT/SmallVector.h"
57 #include "llvm/ADT/StringRef.h"
58 #include "llvm/ADT/StringSwitch.h"
59 #include "llvm/ADT/Triple.h"
60 #include "llvm/ADT/Twine.h"
61 #include "llvm/Config/llvm-config.h"
62 #include "llvm/IR/DebugInfoMetadata.h"
63 #include "llvm/Linker/Linker.h"
64 #include "llvm/MC/MCTargetOptions.h"
65 #include "llvm/Option/Arg.h"
66 #include "llvm/Option/ArgList.h"
67 #include "llvm/Option/OptSpecifier.h"
68 #include "llvm/Option/OptTable.h"
69 #include "llvm/Option/Option.h"
70 #include "llvm/ProfileData/InstrProfReader.h"
71 #include "llvm/Remarks/HotnessThresholdParser.h"
72 #include "llvm/Support/CodeGen.h"
73 #include "llvm/Support/Compiler.h"
74 #include "llvm/Support/Error.h"
75 #include "llvm/Support/ErrorHandling.h"
76 #include "llvm/Support/ErrorOr.h"
77 #include "llvm/Support/FileSystem.h"
78 #include "llvm/Support/Host.h"
79 #include "llvm/Support/MathExtras.h"
80 #include "llvm/Support/MemoryBuffer.h"
81 #include "llvm/Support/Path.h"
82 #include "llvm/Support/Process.h"
83 #include "llvm/Support/Regex.h"
84 #include "llvm/Support/VersionTuple.h"
85 #include "llvm/Support/VirtualFileSystem.h"
86 #include "llvm/Support/raw_ostream.h"
87 #include "llvm/Target/TargetOptions.h"
88 #include <algorithm>
89 #include <atomic>
90 #include <cassert>
91 #include <cstddef>
92 #include <cstring>
93 #include <memory>
94 #include <string>
95 #include <tuple>
96 #include <type_traits>
97 #include <utility>
98 #include <vector>
99 
100 using namespace clang;
101 using namespace driver;
102 using namespace options;
103 using namespace llvm::opt;
104 
105 //===----------------------------------------------------------------------===//
106 // Initialization.
107 //===----------------------------------------------------------------------===//
108 
109 CompilerInvocationBase::CompilerInvocationBase()
110     : LangOpts(new LangOptions()), TargetOpts(new TargetOptions()),
111       DiagnosticOpts(new DiagnosticOptions()),
112       HeaderSearchOpts(new HeaderSearchOptions()),
113       PreprocessorOpts(new PreprocessorOptions()) {}
114 
115 CompilerInvocationBase::CompilerInvocationBase(const CompilerInvocationBase &X)
116     : LangOpts(new LangOptions(*X.getLangOpts())),
117       TargetOpts(new TargetOptions(X.getTargetOpts())),
118       DiagnosticOpts(new DiagnosticOptions(X.getDiagnosticOpts())),
119       HeaderSearchOpts(new HeaderSearchOptions(X.getHeaderSearchOpts())),
120       PreprocessorOpts(new PreprocessorOptions(X.getPreprocessorOpts())) {}
121 
122 CompilerInvocationBase::~CompilerInvocationBase() = default;
123 
124 //===----------------------------------------------------------------------===//
125 // Normalizers
126 //===----------------------------------------------------------------------===//
127 
128 #define SIMPLE_ENUM_VALUE_TABLE
129 #include "clang/Driver/Options.inc"
130 #undef SIMPLE_ENUM_VALUE_TABLE
131 
132 static llvm::Optional<bool> normalizeSimpleFlag(OptSpecifier Opt,
133                                                 unsigned TableIndex,
134                                                 const ArgList &Args,
135                                                 DiagnosticsEngine &Diags) {
136   if (Args.hasArg(Opt))
137     return true;
138   return None;
139 }
140 
141 static Optional<bool> normalizeSimpleNegativeFlag(OptSpecifier Opt, unsigned,
142                                                   const ArgList &Args,
143                                                   DiagnosticsEngine &) {
144   if (Args.hasArg(Opt))
145     return false;
146   return None;
147 }
148 
149 /// The tblgen-erated code passes in a fifth parameter of an arbitrary type, but
150 /// denormalizeSimpleFlags never looks at it. Avoid bloating compile-time with
151 /// unnecessary template instantiations and just ignore it with a variadic
152 /// argument.
153 static void denormalizeSimpleFlag(SmallVectorImpl<const char *> &Args,
154                                   const char *Spelling,
155                                   CompilerInvocation::StringAllocator,
156                                   Option::OptionClass, unsigned, /*T*/...) {
157   Args.push_back(Spelling);
158 }
159 
160 namespace {
161 template <typename T> struct FlagToValueNormalizer {
162   T Value;
163 
164   Optional<T> operator()(OptSpecifier Opt, unsigned, const ArgList &Args,
165                          DiagnosticsEngine &) {
166     if (Args.hasArg(Opt))
167       return Value;
168     return None;
169   }
170 };
171 } // namespace
172 
173 template <typename T> static constexpr bool is_int_convertible() {
174   return sizeof(T) <= sizeof(uint64_t) &&
175          std::is_trivially_constructible<T, uint64_t>::value &&
176          std::is_trivially_constructible<uint64_t, T>::value;
177 }
178 
179 template <typename T, std::enable_if_t<is_int_convertible<T>(), bool> = false>
180 static FlagToValueNormalizer<uint64_t> makeFlagToValueNormalizer(T Value) {
181   return FlagToValueNormalizer<uint64_t>{Value};
182 }
183 
184 template <typename T, std::enable_if_t<!is_int_convertible<T>(), bool> = false>
185 static FlagToValueNormalizer<T> makeFlagToValueNormalizer(T Value) {
186   return FlagToValueNormalizer<T>{std::move(Value)};
187 }
188 
189 static auto makeBooleanOptionNormalizer(bool Value, bool OtherValue,
190                                         OptSpecifier OtherOpt) {
191   return [Value, OtherValue, OtherOpt](OptSpecifier Opt, unsigned,
192                                        const ArgList &Args,
193                                        DiagnosticsEngine &) -> Optional<bool> {
194     if (const Arg *A = Args.getLastArg(Opt, OtherOpt)) {
195       return A->getOption().matches(Opt) ? Value : OtherValue;
196     }
197     return None;
198   };
199 }
200 
201 static auto makeBooleanOptionDenormalizer(bool Value) {
202   return [Value](SmallVectorImpl<const char *> &Args, const char *Spelling,
203                  CompilerInvocation::StringAllocator, Option::OptionClass,
204                  unsigned, bool KeyPath) {
205     if (KeyPath == Value)
206       Args.push_back(Spelling);
207   };
208 }
209 
210 static void denormalizeStringImpl(SmallVectorImpl<const char *> &Args,
211                                   const char *Spelling,
212                                   CompilerInvocation::StringAllocator SA,
213                                   Option::OptionClass OptClass, unsigned,
214                                   Twine Value) {
215   switch (OptClass) {
216   case Option::SeparateClass:
217   case Option::JoinedOrSeparateClass:
218     Args.push_back(Spelling);
219     Args.push_back(SA(Value));
220     break;
221   case Option::JoinedClass:
222     Args.push_back(SA(Twine(Spelling) + Value));
223     break;
224   default:
225     llvm_unreachable("Cannot denormalize an option with option class "
226                      "incompatible with string denormalization.");
227   }
228 }
229 
230 template <typename T>
231 static void
232 denormalizeString(SmallVectorImpl<const char *> &Args, const char *Spelling,
233                   CompilerInvocation::StringAllocator SA,
234                   Option::OptionClass OptClass, unsigned TableIndex, T Value) {
235   denormalizeStringImpl(Args, Spelling, SA, OptClass, TableIndex, Twine(Value));
236 }
237 
238 static Optional<SimpleEnumValue>
239 findValueTableByName(const SimpleEnumValueTable &Table, StringRef Name) {
240   for (int I = 0, E = Table.Size; I != E; ++I)
241     if (Name == Table.Table[I].Name)
242       return Table.Table[I];
243 
244   return None;
245 }
246 
247 static Optional<SimpleEnumValue>
248 findValueTableByValue(const SimpleEnumValueTable &Table, unsigned Value) {
249   for (int I = 0, E = Table.Size; I != E; ++I)
250     if (Value == Table.Table[I].Value)
251       return Table.Table[I];
252 
253   return None;
254 }
255 
256 static llvm::Optional<unsigned> normalizeSimpleEnum(OptSpecifier Opt,
257                                                     unsigned TableIndex,
258                                                     const ArgList &Args,
259                                                     DiagnosticsEngine &Diags) {
260   assert(TableIndex < SimpleEnumValueTablesSize);
261   const SimpleEnumValueTable &Table = SimpleEnumValueTables[TableIndex];
262 
263   auto *Arg = Args.getLastArg(Opt);
264   if (!Arg)
265     return None;
266 
267   StringRef ArgValue = Arg->getValue();
268   if (auto MaybeEnumVal = findValueTableByName(Table, ArgValue))
269     return MaybeEnumVal->Value;
270 
271   Diags.Report(diag::err_drv_invalid_value)
272       << Arg->getAsString(Args) << ArgValue;
273   return None;
274 }
275 
276 static void denormalizeSimpleEnumImpl(SmallVectorImpl<const char *> &Args,
277                                       const char *Spelling,
278                                       CompilerInvocation::StringAllocator SA,
279                                       Option::OptionClass OptClass,
280                                       unsigned TableIndex, unsigned Value) {
281   assert(TableIndex < SimpleEnumValueTablesSize);
282   const SimpleEnumValueTable &Table = SimpleEnumValueTables[TableIndex];
283   if (auto MaybeEnumVal = findValueTableByValue(Table, Value)) {
284     denormalizeString(Args, Spelling, SA, OptClass, TableIndex,
285                       MaybeEnumVal->Name);
286   } else {
287     llvm_unreachable("The simple enum value was not correctly defined in "
288                      "the tablegen option description");
289   }
290 }
291 
292 template <typename T>
293 static void denormalizeSimpleEnum(SmallVectorImpl<const char *> &Args,
294                                   const char *Spelling,
295                                   CompilerInvocation::StringAllocator SA,
296                                   Option::OptionClass OptClass,
297                                   unsigned TableIndex, T Value) {
298   return denormalizeSimpleEnumImpl(Args, Spelling, SA, OptClass, TableIndex,
299                                    static_cast<unsigned>(Value));
300 }
301 
302 static Optional<std::string> normalizeString(OptSpecifier Opt, int TableIndex,
303                                              const ArgList &Args,
304                                              DiagnosticsEngine &Diags) {
305   auto *Arg = Args.getLastArg(Opt);
306   if (!Arg)
307     return None;
308   return std::string(Arg->getValue());
309 }
310 
311 template <typename IntTy>
312 static Optional<IntTy> normalizeStringIntegral(OptSpecifier Opt, int,
313                                                const ArgList &Args,
314                                                DiagnosticsEngine &Diags) {
315   auto *Arg = Args.getLastArg(Opt);
316   if (!Arg)
317     return None;
318   IntTy Res;
319   if (StringRef(Arg->getValue()).getAsInteger(0, Res)) {
320     Diags.Report(diag::err_drv_invalid_int_value)
321         << Arg->getAsString(Args) << Arg->getValue();
322   }
323   return Res;
324 }
325 
326 static Optional<std::string> normalizeTriple(OptSpecifier Opt, int TableIndex,
327                                              const ArgList &Args,
328                                              DiagnosticsEngine &Diags) {
329   auto *Arg = Args.getLastArg(Opt);
330   if (!Arg)
331     return None;
332   return llvm::Triple::normalize(Arg->getValue());
333 }
334 
335 template <typename T, typename U>
336 static T mergeForwardValue(T KeyPath, U Value) {
337   return static_cast<T>(Value);
338 }
339 
340 template <typename T, typename U> static T mergeMaskValue(T KeyPath, U Value) {
341   return KeyPath | Value;
342 }
343 
344 template <typename T> static T extractForwardValue(T KeyPath) {
345   return KeyPath;
346 }
347 
348 template <typename T, typename U, U Value>
349 static T extractMaskValue(T KeyPath) {
350   return KeyPath & Value;
351 }
352 
353 static void FixupInvocation(CompilerInvocation &Invocation,
354                             DiagnosticsEngine &Diags,
355                             const InputArgList &Args) {
356   LangOptions &LangOpts = *Invocation.getLangOpts();
357   DiagnosticOptions &DiagOpts = Invocation.getDiagnosticOpts();
358   CodeGenOptions &CodeGenOpts = Invocation.getCodeGenOpts();
359   TargetOptions &TargetOpts = Invocation.getTargetOpts();
360   FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
361   CodeGenOpts.XRayInstrumentFunctions = LangOpts.XRayInstrument;
362   CodeGenOpts.XRayAlwaysEmitCustomEvents = LangOpts.XRayAlwaysEmitCustomEvents;
363   CodeGenOpts.XRayAlwaysEmitTypedEvents = LangOpts.XRayAlwaysEmitTypedEvents;
364   CodeGenOpts.DisableFree = FrontendOpts.DisableFree;
365   FrontendOpts.GenerateGlobalModuleIndex = FrontendOpts.UseGlobalModuleIndex;
366 
367   LangOpts.ForceEmitVTables = CodeGenOpts.ForceEmitVTables;
368   LangOpts.SpeculativeLoadHardening = CodeGenOpts.SpeculativeLoadHardening;
369   LangOpts.CurrentModule = LangOpts.ModuleName;
370 
371   llvm::sys::Process::UseANSIEscapeCodes(DiagOpts.UseANSIEscapeCodes);
372 
373   llvm::Triple T(TargetOpts.Triple);
374   llvm::Triple::ArchType Arch = T.getArch();
375 
376   if (LangOpts.getExceptionHandling() != llvm::ExceptionHandling::None &&
377       T.isWindowsMSVCEnvironment())
378     Diags.Report(diag::err_fe_invalid_exception_model)
379         << static_cast<unsigned>(LangOpts.getExceptionHandling()) << T.str();
380 
381   if (LangOpts.AppleKext && !LangOpts.CPlusPlus)
382     Diags.Report(diag::warn_c_kext);
383 
384   if (LangOpts.NewAlignOverride &&
385       !llvm::isPowerOf2_32(LangOpts.NewAlignOverride)) {
386     Arg *A = Args.getLastArg(OPT_fnew_alignment_EQ);
387     Diags.Report(diag::err_fe_invalid_alignment)
388         << A->getAsString(Args) << A->getValue();
389     LangOpts.NewAlignOverride = 0;
390   }
391 
392   if (Arg *A = Args.getLastArg(OPT_fdefault_calling_conv_EQ)) {
393     auto DefaultCC = LangOpts.getDefaultCallingConv();
394 
395     bool emitError = (DefaultCC == LangOptions::DCC_FastCall ||
396                       DefaultCC == LangOptions::DCC_StdCall) &&
397                      Arch != llvm::Triple::x86;
398     emitError |= (DefaultCC == LangOptions::DCC_VectorCall ||
399                   DefaultCC == LangOptions::DCC_RegCall) &&
400                  !T.isX86();
401     if (emitError)
402       Diags.Report(diag::err_drv_argument_not_allowed_with)
403           << A->getSpelling() << T.getTriple();
404   }
405 
406   if (!CodeGenOpts.ProfileRemappingFile.empty() && CodeGenOpts.LegacyPassManager)
407     Diags.Report(diag::err_drv_argument_only_allowed_with)
408         << Args.getLastArg(OPT_fprofile_remapping_file_EQ)->getAsString(Args)
409         << "-fno-legacy-pass-manager";
410 }
411 
412 //===----------------------------------------------------------------------===//
413 // Deserialization (from args)
414 //===----------------------------------------------------------------------===//
415 
416 static unsigned getOptimizationLevel(ArgList &Args, InputKind IK,
417                                      DiagnosticsEngine &Diags) {
418   unsigned DefaultOpt = llvm::CodeGenOpt::None;
419   if (IK.getLanguage() == Language::OpenCL && !Args.hasArg(OPT_cl_opt_disable))
420     DefaultOpt = llvm::CodeGenOpt::Default;
421 
422   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
423     if (A->getOption().matches(options::OPT_O0))
424       return llvm::CodeGenOpt::None;
425 
426     if (A->getOption().matches(options::OPT_Ofast))
427       return llvm::CodeGenOpt::Aggressive;
428 
429     assert(A->getOption().matches(options::OPT_O));
430 
431     StringRef S(A->getValue());
432     if (S == "s" || S == "z")
433       return llvm::CodeGenOpt::Default;
434 
435     if (S == "g")
436       return llvm::CodeGenOpt::Less;
437 
438     return getLastArgIntValue(Args, OPT_O, DefaultOpt, Diags);
439   }
440 
441   return DefaultOpt;
442 }
443 
444 static unsigned getOptimizationLevelSize(ArgList &Args) {
445   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
446     if (A->getOption().matches(options::OPT_O)) {
447       switch (A->getValue()[0]) {
448       default:
449         return 0;
450       case 's':
451         return 1;
452       case 'z':
453         return 2;
454       }
455     }
456   }
457   return 0;
458 }
459 
460 static void addDiagnosticArgs(ArgList &Args, OptSpecifier Group,
461                               OptSpecifier GroupWithValue,
462                               std::vector<std::string> &Diagnostics) {
463   for (auto *A : Args.filtered(Group)) {
464     if (A->getOption().getKind() == Option::FlagClass) {
465       // The argument is a pure flag (such as OPT_Wall or OPT_Wdeprecated). Add
466       // its name (minus the "W" or "R" at the beginning) to the warning list.
467       Diagnostics.push_back(
468           std::string(A->getOption().getName().drop_front(1)));
469     } else if (A->getOption().matches(GroupWithValue)) {
470       // This is -Wfoo= or -Rfoo=, where foo is the name of the diagnostic group.
471       Diagnostics.push_back(
472           std::string(A->getOption().getName().drop_front(1).rtrim("=-")));
473     } else {
474       // Otherwise, add its value (for OPT_W_Joined and similar).
475       for (const auto *Arg : A->getValues())
476         Diagnostics.emplace_back(Arg);
477     }
478   }
479 }
480 
481 // Parse the Static Analyzer configuration. If \p Diags is set to nullptr,
482 // it won't verify the input.
483 static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts,
484                                  DiagnosticsEngine *Diags);
485 
486 static void getAllNoBuiltinFuncValues(ArgList &Args,
487                                       std::vector<std::string> &Funcs) {
488   SmallVector<const char *, 8> Values;
489   for (const auto &Arg : Args) {
490     const Option &O = Arg->getOption();
491     if (O.matches(options::OPT_fno_builtin_)) {
492       const char *FuncName = Arg->getValue();
493       if (Builtin::Context::isBuiltinFunc(FuncName))
494         Values.push_back(FuncName);
495     }
496   }
497   Funcs.insert(Funcs.end(), Values.begin(), Values.end());
498 }
499 
500 static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args,
501                               DiagnosticsEngine &Diags) {
502   bool Success = true;
503   if (Arg *A = Args.getLastArg(OPT_analyzer_store)) {
504     StringRef Name = A->getValue();
505     AnalysisStores Value = llvm::StringSwitch<AnalysisStores>(Name)
506 #define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN) \
507       .Case(CMDFLAG, NAME##Model)
508 #include "clang/StaticAnalyzer/Core/Analyses.def"
509       .Default(NumStores);
510     if (Value == NumStores) {
511       Diags.Report(diag::err_drv_invalid_value)
512         << A->getAsString(Args) << Name;
513       Success = false;
514     } else {
515       Opts.AnalysisStoreOpt = Value;
516     }
517   }
518 
519   if (Arg *A = Args.getLastArg(OPT_analyzer_constraints)) {
520     StringRef Name = A->getValue();
521     AnalysisConstraints Value = llvm::StringSwitch<AnalysisConstraints>(Name)
522 #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \
523       .Case(CMDFLAG, NAME##Model)
524 #include "clang/StaticAnalyzer/Core/Analyses.def"
525       .Default(NumConstraints);
526     if (Value == NumConstraints) {
527       Diags.Report(diag::err_drv_invalid_value)
528         << A->getAsString(Args) << Name;
529       Success = false;
530     } else {
531       Opts.AnalysisConstraintsOpt = Value;
532     }
533   }
534 
535   if (Arg *A = Args.getLastArg(OPT_analyzer_output)) {
536     StringRef Name = A->getValue();
537     AnalysisDiagClients Value = llvm::StringSwitch<AnalysisDiagClients>(Name)
538 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \
539       .Case(CMDFLAG, PD_##NAME)
540 #include "clang/StaticAnalyzer/Core/Analyses.def"
541       .Default(NUM_ANALYSIS_DIAG_CLIENTS);
542     if (Value == NUM_ANALYSIS_DIAG_CLIENTS) {
543       Diags.Report(diag::err_drv_invalid_value)
544         << A->getAsString(Args) << Name;
545       Success = false;
546     } else {
547       Opts.AnalysisDiagOpt = Value;
548     }
549   }
550 
551   if (Arg *A = Args.getLastArg(OPT_analyzer_purge)) {
552     StringRef Name = A->getValue();
553     AnalysisPurgeMode Value = llvm::StringSwitch<AnalysisPurgeMode>(Name)
554 #define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \
555       .Case(CMDFLAG, NAME)
556 #include "clang/StaticAnalyzer/Core/Analyses.def"
557       .Default(NumPurgeModes);
558     if (Value == NumPurgeModes) {
559       Diags.Report(diag::err_drv_invalid_value)
560         << A->getAsString(Args) << Name;
561       Success = false;
562     } else {
563       Opts.AnalysisPurgeOpt = Value;
564     }
565   }
566 
567   if (Arg *A = Args.getLastArg(OPT_analyzer_inlining_mode)) {
568     StringRef Name = A->getValue();
569     AnalysisInliningMode Value = llvm::StringSwitch<AnalysisInliningMode>(Name)
570 #define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \
571       .Case(CMDFLAG, NAME)
572 #include "clang/StaticAnalyzer/Core/Analyses.def"
573       .Default(NumInliningModes);
574     if (Value == NumInliningModes) {
575       Diags.Report(diag::err_drv_invalid_value)
576         << A->getAsString(Args) << Name;
577       Success = false;
578     } else {
579       Opts.InliningMode = Value;
580     }
581   }
582 
583   Opts.ShouldEmitErrorsOnInvalidConfigValue =
584       /* negated */!llvm::StringSwitch<bool>(
585                    Args.getLastArgValue(OPT_analyzer_config_compatibility_mode))
586         .Case("true", true)
587         .Case("false", false)
588         .Default(false);
589 
590   Opts.CheckersAndPackages.clear();
591   for (const Arg *A :
592        Args.filtered(OPT_analyzer_checker, OPT_analyzer_disable_checker)) {
593     A->claim();
594     bool IsEnabled = A->getOption().getID() == OPT_analyzer_checker;
595     // We can have a list of comma separated checker names, e.g:
596     // '-analyzer-checker=cocoa,unix'
597     StringRef CheckerAndPackageList = A->getValue();
598     SmallVector<StringRef, 16> CheckersAndPackages;
599     CheckerAndPackageList.split(CheckersAndPackages, ",");
600     for (const StringRef &CheckerOrPackage : CheckersAndPackages)
601       Opts.CheckersAndPackages.emplace_back(std::string(CheckerOrPackage),
602                                             IsEnabled);
603   }
604 
605   // Go through the analyzer configuration options.
606   for (const auto *A : Args.filtered(OPT_analyzer_config)) {
607 
608     // We can have a list of comma separated config names, e.g:
609     // '-analyzer-config key1=val1,key2=val2'
610     StringRef configList = A->getValue();
611     SmallVector<StringRef, 4> configVals;
612     configList.split(configVals, ",");
613     for (const auto &configVal : configVals) {
614       StringRef key, val;
615       std::tie(key, val) = configVal.split("=");
616       if (val.empty()) {
617         Diags.Report(SourceLocation(),
618                      diag::err_analyzer_config_no_value) << configVal;
619         Success = false;
620         break;
621       }
622       if (val.find('=') != StringRef::npos) {
623         Diags.Report(SourceLocation(),
624                      diag::err_analyzer_config_multiple_values)
625           << configVal;
626         Success = false;
627         break;
628       }
629 
630       // TODO: Check checker options too, possibly in CheckerRegistry.
631       // Leave unknown non-checker configs unclaimed.
632       if (!key.contains(":") && Opts.isUnknownAnalyzerConfig(key)) {
633         if (Opts.ShouldEmitErrorsOnInvalidConfigValue)
634           Diags.Report(diag::err_analyzer_config_unknown) << key;
635         continue;
636       }
637 
638       A->claim();
639       Opts.Config[key] = std::string(val);
640     }
641   }
642 
643   if (Opts.ShouldEmitErrorsOnInvalidConfigValue)
644     parseAnalyzerConfigs(Opts, &Diags);
645   else
646     parseAnalyzerConfigs(Opts, nullptr);
647 
648   llvm::raw_string_ostream os(Opts.FullCompilerInvocation);
649   for (unsigned i = 0; i < Args.getNumInputArgStrings(); ++i) {
650     if (i != 0)
651       os << " ";
652     os << Args.getArgString(i);
653   }
654   os.flush();
655 
656   return Success;
657 }
658 
659 static StringRef getStringOption(AnalyzerOptions::ConfigTable &Config,
660                                  StringRef OptionName, StringRef DefaultVal) {
661   return Config.insert({OptionName, std::string(DefaultVal)}).first->second;
662 }
663 
664 static void initOption(AnalyzerOptions::ConfigTable &Config,
665                        DiagnosticsEngine *Diags,
666                        StringRef &OptionField, StringRef Name,
667                        StringRef DefaultVal) {
668   // String options may be known to invalid (e.g. if the expected string is a
669   // file name, but the file does not exist), those will have to be checked in
670   // parseConfigs.
671   OptionField = getStringOption(Config, Name, DefaultVal);
672 }
673 
674 static void initOption(AnalyzerOptions::ConfigTable &Config,
675                        DiagnosticsEngine *Diags,
676                        bool &OptionField, StringRef Name, bool DefaultVal) {
677   auto PossiblyInvalidVal = llvm::StringSwitch<Optional<bool>>(
678                  getStringOption(Config, Name, (DefaultVal ? "true" : "false")))
679       .Case("true", true)
680       .Case("false", false)
681       .Default(None);
682 
683   if (!PossiblyInvalidVal) {
684     if (Diags)
685       Diags->Report(diag::err_analyzer_config_invalid_input)
686         << Name << "a boolean";
687     else
688       OptionField = DefaultVal;
689   } else
690     OptionField = PossiblyInvalidVal.getValue();
691 }
692 
693 static void initOption(AnalyzerOptions::ConfigTable &Config,
694                        DiagnosticsEngine *Diags,
695                        unsigned &OptionField, StringRef Name,
696                        unsigned DefaultVal) {
697 
698   OptionField = DefaultVal;
699   bool HasFailed = getStringOption(Config, Name, std::to_string(DefaultVal))
700                      .getAsInteger(0, OptionField);
701   if (Diags && HasFailed)
702     Diags->Report(diag::err_analyzer_config_invalid_input)
703       << Name << "an unsigned";
704 }
705 
706 static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts,
707                                  DiagnosticsEngine *Diags) {
708   // TODO: There's no need to store the entire configtable, it'd be plenty
709   // enough tostore checker options.
710 
711 #define ANALYZER_OPTION(TYPE, NAME, CMDFLAG, DESC, DEFAULT_VAL)                \
712   initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, DEFAULT_VAL);
713 
714 #define ANALYZER_OPTION_DEPENDS_ON_USER_MODE(TYPE, NAME, CMDFLAG, DESC,        \
715                                            SHALLOW_VAL, DEEP_VAL)              \
716   switch (AnOpts.getUserMode()) {                                              \
717   case UMK_Shallow:                                                            \
718     initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, SHALLOW_VAL);       \
719     break;                                                                     \
720   case UMK_Deep:                                                               \
721     initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, DEEP_VAL);          \
722     break;                                                                     \
723   }                                                                            \
724 
725 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.def"
726 #undef ANALYZER_OPTION
727 #undef ANALYZER_OPTION_DEPENDS_ON_USER_MODE
728 
729   // At this point, AnalyzerOptions is configured. Let's validate some options.
730 
731   // FIXME: Here we try to validate the silenced checkers or packages are valid.
732   // The current approach only validates the registered checkers which does not
733   // contain the runtime enabled checkers and optimally we would validate both.
734   if (!AnOpts.RawSilencedCheckersAndPackages.empty()) {
735     std::vector<StringRef> Checkers =
736         AnOpts.getRegisteredCheckers(/*IncludeExperimental=*/true);
737     std::vector<StringRef> Packages =
738         AnOpts.getRegisteredPackages(/*IncludeExperimental=*/true);
739 
740     SmallVector<StringRef, 16> CheckersAndPackages;
741     AnOpts.RawSilencedCheckersAndPackages.split(CheckersAndPackages, ";");
742 
743     for (const StringRef &CheckerOrPackage : CheckersAndPackages) {
744       if (Diags) {
745         bool IsChecker = CheckerOrPackage.contains('.');
746         bool IsValidName =
747             IsChecker
748                 ? llvm::find(Checkers, CheckerOrPackage) != Checkers.end()
749                 : llvm::find(Packages, CheckerOrPackage) != Packages.end();
750 
751         if (!IsValidName)
752           Diags->Report(diag::err_unknown_analyzer_checker_or_package)
753               << CheckerOrPackage;
754       }
755 
756       AnOpts.SilencedCheckersAndPackages.emplace_back(CheckerOrPackage);
757     }
758   }
759 
760   if (!Diags)
761     return;
762 
763   if (AnOpts.ShouldTrackConditionsDebug && !AnOpts.ShouldTrackConditions)
764     Diags->Report(diag::err_analyzer_config_invalid_input)
765         << "track-conditions-debug" << "'track-conditions' to also be enabled";
766 
767   if (!AnOpts.CTUDir.empty() && !llvm::sys::fs::is_directory(AnOpts.CTUDir))
768     Diags->Report(diag::err_analyzer_config_invalid_input) << "ctu-dir"
769                                                            << "a filename";
770 
771   if (!AnOpts.ModelPath.empty() &&
772       !llvm::sys::fs::is_directory(AnOpts.ModelPath))
773     Diags->Report(diag::err_analyzer_config_invalid_input) << "model-path"
774                                                            << "a filename";
775 }
776 
777 static void ParseCommentArgs(CommentOptions &Opts, ArgList &Args) {
778   Opts.BlockCommandNames = Args.getAllArgValues(OPT_fcomment_block_commands);
779   Opts.ParseAllComments = Args.hasArg(OPT_fparse_all_comments);
780 }
781 
782 /// Create a new Regex instance out of the string value in \p RpassArg.
783 /// It returns a pointer to the newly generated Regex instance.
784 static std::shared_ptr<llvm::Regex>
785 GenerateOptimizationRemarkRegex(DiagnosticsEngine &Diags, ArgList &Args,
786                                 Arg *RpassArg) {
787   StringRef Val = RpassArg->getValue();
788   std::string RegexError;
789   std::shared_ptr<llvm::Regex> Pattern = std::make_shared<llvm::Regex>(Val);
790   if (!Pattern->isValid(RegexError)) {
791     Diags.Report(diag::err_drv_optimization_remark_pattern)
792         << RegexError << RpassArg->getAsString(Args);
793     Pattern.reset();
794   }
795   return Pattern;
796 }
797 
798 static bool parseDiagnosticLevelMask(StringRef FlagName,
799                                      const std::vector<std::string> &Levels,
800                                      DiagnosticsEngine *Diags,
801                                      DiagnosticLevelMask &M) {
802   bool Success = true;
803   for (const auto &Level : Levels) {
804     DiagnosticLevelMask const PM =
805       llvm::StringSwitch<DiagnosticLevelMask>(Level)
806         .Case("note",    DiagnosticLevelMask::Note)
807         .Case("remark",  DiagnosticLevelMask::Remark)
808         .Case("warning", DiagnosticLevelMask::Warning)
809         .Case("error",   DiagnosticLevelMask::Error)
810         .Default(DiagnosticLevelMask::None);
811     if (PM == DiagnosticLevelMask::None) {
812       Success = false;
813       if (Diags)
814         Diags->Report(diag::err_drv_invalid_value) << FlagName << Level;
815     }
816     M = M | PM;
817   }
818   return Success;
819 }
820 
821 static void parseSanitizerKinds(StringRef FlagName,
822                                 const std::vector<std::string> &Sanitizers,
823                                 DiagnosticsEngine &Diags, SanitizerSet &S) {
824   for (const auto &Sanitizer : Sanitizers) {
825     SanitizerMask K = parseSanitizerValue(Sanitizer, /*AllowGroups=*/false);
826     if (K == SanitizerMask())
827       Diags.Report(diag::err_drv_invalid_value) << FlagName << Sanitizer;
828     else
829       S.set(K, true);
830   }
831 }
832 
833 static void parseXRayInstrumentationBundle(StringRef FlagName, StringRef Bundle,
834                                            ArgList &Args, DiagnosticsEngine &D,
835                                            XRayInstrSet &S) {
836   llvm::SmallVector<StringRef, 2> BundleParts;
837   llvm::SplitString(Bundle, BundleParts, ",");
838   for (const auto &B : BundleParts) {
839     auto Mask = parseXRayInstrValue(B);
840     if (Mask == XRayInstrKind::None)
841       if (B != "none")
842         D.Report(diag::err_drv_invalid_value) << FlagName << Bundle;
843       else
844         S.Mask = Mask;
845     else if (Mask == XRayInstrKind::All)
846       S.Mask = Mask;
847     else
848       S.set(Mask, true);
849   }
850 }
851 
852 // Set the profile kind using fprofile-instrument-use-path.
853 static void setPGOUseInstrumentor(CodeGenOptions &Opts,
854                                   const Twine &ProfileName) {
855   auto ReaderOrErr = llvm::IndexedInstrProfReader::create(ProfileName);
856   // In error, return silently and let Clang PGOUse report the error message.
857   if (auto E = ReaderOrErr.takeError()) {
858     llvm::consumeError(std::move(E));
859     Opts.setProfileUse(CodeGenOptions::ProfileClangInstr);
860     return;
861   }
862   std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader =
863     std::move(ReaderOrErr.get());
864   if (PGOReader->isIRLevelProfile()) {
865     if (PGOReader->hasCSIRLevelProfile())
866       Opts.setProfileUse(CodeGenOptions::ProfileCSIRInstr);
867     else
868       Opts.setProfileUse(CodeGenOptions::ProfileIRInstr);
869   } else
870     Opts.setProfileUse(CodeGenOptions::ProfileClangInstr);
871 }
872 
873 static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK,
874                              DiagnosticsEngine &Diags,
875                              const TargetOptions &TargetOpts,
876                              const FrontendOptions &FrontendOpts) {
877   bool Success = true;
878   llvm::Triple Triple = llvm::Triple(TargetOpts.Triple);
879 
880   unsigned OptimizationLevel = getOptimizationLevel(Args, IK, Diags);
881   // TODO: This could be done in Driver
882   unsigned MaxOptLevel = 3;
883   if (OptimizationLevel > MaxOptLevel) {
884     // If the optimization level is not supported, fall back on the default
885     // optimization
886     Diags.Report(diag::warn_drv_optimization_value)
887         << Args.getLastArg(OPT_O)->getAsString(Args) << "-O" << MaxOptLevel;
888     OptimizationLevel = MaxOptLevel;
889   }
890   Opts.OptimizationLevel = OptimizationLevel;
891 
892   // At O0 we want to fully disable inlining outside of cases marked with
893   // 'alwaysinline' that are required for correctness.
894   Opts.setInlining((Opts.OptimizationLevel == 0)
895                        ? CodeGenOptions::OnlyAlwaysInlining
896                        : CodeGenOptions::NormalInlining);
897   // Explicit inlining flags can disable some or all inlining even at
898   // optimization levels above zero.
899   if (Arg *InlineArg = Args.getLastArg(
900           options::OPT_finline_functions, options::OPT_finline_hint_functions,
901           options::OPT_fno_inline_functions, options::OPT_fno_inline)) {
902     if (Opts.OptimizationLevel > 0) {
903       const Option &InlineOpt = InlineArg->getOption();
904       if (InlineOpt.matches(options::OPT_finline_functions))
905         Opts.setInlining(CodeGenOptions::NormalInlining);
906       else if (InlineOpt.matches(options::OPT_finline_hint_functions))
907         Opts.setInlining(CodeGenOptions::OnlyHintInlining);
908       else
909         Opts.setInlining(CodeGenOptions::OnlyAlwaysInlining);
910     }
911   }
912 
913   // If -fuse-ctor-homing is set and limited debug info is already on, then use
914   // constructor homing.
915   if (Args.getLastArg(OPT_fuse_ctor_homing))
916     if (Opts.getDebugInfo() == codegenoptions::LimitedDebugInfo)
917       Opts.setDebugInfo(codegenoptions::DebugInfoConstructor);
918 
919   for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ)) {
920     auto Split = StringRef(Arg).split('=');
921     Opts.DebugPrefixMap.insert(
922         {std::string(Split.first), std::string(Split.second)});
923   }
924 
925   const llvm::Triple::ArchType DebugEntryValueArchs[] = {
926       llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::aarch64,
927       llvm::Triple::arm, llvm::Triple::armeb, llvm::Triple::mips,
928       llvm::Triple::mipsel, llvm::Triple::mips64, llvm::Triple::mips64el};
929 
930   llvm::Triple T(TargetOpts.Triple);
931   if (Opts.OptimizationLevel > 0 && Opts.hasReducedDebugInfo() &&
932       llvm::is_contained(DebugEntryValueArchs, T.getArch()))
933     Opts.EmitCallSiteInfo = true;
934 
935   Opts.NewStructPathTBAA = !Args.hasArg(OPT_no_struct_path_tbaa) &&
936                            Args.hasArg(OPT_new_struct_path_tbaa);
937   Opts.OptimizeSize = getOptimizationLevelSize(Args);
938   Opts.SimplifyLibCalls = !(Args.hasArg(OPT_fno_builtin) ||
939                             Args.hasArg(OPT_ffreestanding));
940   if (Opts.SimplifyLibCalls)
941     getAllNoBuiltinFuncValues(Args, Opts.NoBuiltinFuncs);
942   Opts.UnrollLoops =
943       Args.hasFlag(OPT_funroll_loops, OPT_fno_unroll_loops,
944                    (Opts.OptimizationLevel > 1));
945 
946   Opts.DebugNameTable = static_cast<unsigned>(
947       Args.hasArg(OPT_ggnu_pubnames)
948           ? llvm::DICompileUnit::DebugNameTableKind::GNU
949           : Args.hasArg(OPT_gpubnames)
950                 ? llvm::DICompileUnit::DebugNameTableKind::Default
951                 : llvm::DICompileUnit::DebugNameTableKind::None);
952 
953   if (!Opts.ProfileInstrumentUsePath.empty())
954     setPGOUseInstrumentor(Opts, Opts.ProfileInstrumentUsePath);
955 
956   Opts.CodeModel = TargetOpts.CodeModel;
957 
958   if (const Arg *A = Args.getLastArg(OPT_ftime_report, OPT_ftime_report_EQ)) {
959     Opts.TimePasses = true;
960 
961     // -ftime-report= is only for new pass manager.
962     if (A->getOption().getID() == OPT_ftime_report_EQ) {
963       if (Opts.LegacyPassManager)
964         Diags.Report(diag::err_drv_argument_only_allowed_with)
965             << A->getAsString(Args) << "-fno-legacy-pass-manager";
966 
967       StringRef Val = A->getValue();
968       if (Val == "per-pass")
969         Opts.TimePassesPerRun = false;
970       else if (Val == "per-pass-run")
971         Opts.TimePassesPerRun = true;
972       else
973         Diags.Report(diag::err_drv_invalid_value)
974             << A->getAsString(Args) << A->getValue();
975     }
976   }
977 
978   Opts.Reciprocals = Args.getAllArgValues(OPT_mrecip_EQ);
979 
980   // Basic Block Sections implies Function Sections.
981   Opts.FunctionSections =
982       Args.hasArg(OPT_ffunction_sections) ||
983       (Opts.BBSections != "none" && Opts.BBSections != "labels");
984 
985   Opts.PrepareForLTO = Args.hasArg(OPT_flto, OPT_flto_EQ);
986   Opts.PrepareForThinLTO = false;
987   if (Arg *A = Args.getLastArg(OPT_flto_EQ)) {
988     StringRef S = A->getValue();
989     if (S == "thin")
990       Opts.PrepareForThinLTO = true;
991     else if (S != "full")
992       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << S;
993   }
994   if (Arg *A = Args.getLastArg(OPT_fthinlto_index_EQ)) {
995     if (IK.getLanguage() != Language::LLVM_IR)
996       Diags.Report(diag::err_drv_argument_only_allowed_with)
997           << A->getAsString(Args) << "-x ir";
998     Opts.ThinLTOIndexFile =
999         std::string(Args.getLastArgValue(OPT_fthinlto_index_EQ));
1000   }
1001   if (Arg *A = Args.getLastArg(OPT_save_temps_EQ))
1002     Opts.SaveTempsFilePrefix =
1003         llvm::StringSwitch<std::string>(A->getValue())
1004             .Case("obj", FrontendOpts.OutputFile)
1005             .Default(llvm::sys::path::filename(FrontendOpts.OutputFile).str());
1006 
1007   // The memory profile runtime appends the pid to make this name more unique.
1008   const char *MemProfileBasename = "memprof.profraw";
1009   if (Args.hasArg(OPT_fmemory_profile_EQ)) {
1010     SmallString<128> Path(
1011         std::string(Args.getLastArgValue(OPT_fmemory_profile_EQ)));
1012     llvm::sys::path::append(Path, MemProfileBasename);
1013     Opts.MemoryProfileOutput = std::string(Path);
1014   } else if (Args.hasArg(OPT_fmemory_profile))
1015     Opts.MemoryProfileOutput = MemProfileBasename;
1016 
1017   if (Opts.EmitGcovArcs || Opts.EmitGcovNotes) {
1018     Opts.CoverageDataFile =
1019         std::string(Args.getLastArgValue(OPT_coverage_data_file));
1020     Opts.CoverageNotesFile =
1021         std::string(Args.getLastArgValue(OPT_coverage_notes_file));
1022     Opts.ProfileFilterFiles =
1023         std::string(Args.getLastArgValue(OPT_fprofile_filter_files_EQ));
1024     Opts.ProfileExcludeFiles =
1025         std::string(Args.getLastArgValue(OPT_fprofile_exclude_files_EQ));
1026     if (Args.hasArg(OPT_coverage_version_EQ)) {
1027       StringRef CoverageVersion = Args.getLastArgValue(OPT_coverage_version_EQ);
1028       if (CoverageVersion.size() != 4) {
1029         Diags.Report(diag::err_drv_invalid_value)
1030             << Args.getLastArg(OPT_coverage_version_EQ)->getAsString(Args)
1031             << CoverageVersion;
1032       } else {
1033         memcpy(Opts.CoverageVersion, CoverageVersion.data(), 4);
1034       }
1035     }
1036   }
1037   // FIXME: For backend options that are not yet recorded as function
1038   // attributes in the IR, keep track of them so we can embed them in a
1039   // separate data section and use them when building the bitcode.
1040   for (const auto &A : Args) {
1041     // Do not encode output and input.
1042     if (A->getOption().getID() == options::OPT_o ||
1043         A->getOption().getID() == options::OPT_INPUT ||
1044         A->getOption().getID() == options::OPT_x ||
1045         A->getOption().getID() == options::OPT_fembed_bitcode ||
1046         A->getOption().matches(options::OPT_W_Group))
1047       continue;
1048     ArgStringList ASL;
1049     A->render(Args, ASL);
1050     for (const auto &arg : ASL) {
1051       StringRef ArgStr(arg);
1052       Opts.CmdArgs.insert(Opts.CmdArgs.end(), ArgStr.begin(), ArgStr.end());
1053       // using \00 to separate each commandline options.
1054       Opts.CmdArgs.push_back('\0');
1055     }
1056   }
1057 
1058   Opts.XRayTotalFunctionGroups =
1059       getLastArgIntValue(Args, OPT_fxray_function_groups, 1, Diags);
1060   Opts.XRaySelectedFunctionGroup =
1061       getLastArgIntValue(Args, OPT_fxray_selected_function_group, 0, Diags);
1062 
1063   auto XRayInstrBundles =
1064       Args.getAllArgValues(OPT_fxray_instrumentation_bundle);
1065   if (XRayInstrBundles.empty())
1066     Opts.XRayInstrumentationBundle.Mask = XRayInstrKind::All;
1067   else
1068     for (const auto &A : XRayInstrBundles)
1069       parseXRayInstrumentationBundle("-fxray-instrumentation-bundle=", A, Args,
1070                                      Diags, Opts.XRayInstrumentationBundle);
1071 
1072   if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
1073     StringRef Name = A->getValue();
1074     if (Name == "full") {
1075       Opts.CFProtectionReturn = 1;
1076       Opts.CFProtectionBranch = 1;
1077     } else if (Name == "return")
1078       Opts.CFProtectionReturn = 1;
1079     else if (Name == "branch")
1080       Opts.CFProtectionBranch = 1;
1081     else if (Name != "none") {
1082       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
1083       Success = false;
1084     }
1085   }
1086 
1087   if (const Arg *A = Args.getLastArg(OPT_compress_debug_sections_EQ)) {
1088     auto DCT = llvm::StringSwitch<llvm::DebugCompressionType>(A->getValue())
1089                    .Case("none", llvm::DebugCompressionType::None)
1090                    .Case("zlib", llvm::DebugCompressionType::Z)
1091                    .Case("zlib-gnu", llvm::DebugCompressionType::GNU)
1092                    .Default(llvm::DebugCompressionType::None);
1093     Opts.setCompressDebugSections(DCT);
1094   }
1095 
1096   for (auto *A :
1097        Args.filtered(OPT_mlink_bitcode_file, OPT_mlink_builtin_bitcode)) {
1098     CodeGenOptions::BitcodeFileToLink F;
1099     F.Filename = A->getValue();
1100     if (A->getOption().matches(OPT_mlink_builtin_bitcode)) {
1101       F.LinkFlags = llvm::Linker::Flags::LinkOnlyNeeded;
1102       // When linking CUDA bitcode, propagate function attributes so that
1103       // e.g. libdevice gets fast-math attrs if we're building with fast-math.
1104       F.PropagateAttrs = true;
1105       F.Internalize = true;
1106     }
1107     Opts.LinkBitcodeFiles.push_back(F);
1108   }
1109   Opts.SanitizeCoverageAllowlistFiles =
1110       Args.getAllArgValues(OPT_fsanitize_coverage_allowlist);
1111   Opts.SanitizeCoverageBlocklistFiles =
1112       Args.getAllArgValues(OPT_fsanitize_coverage_blocklist);
1113   Opts.SSPBufferSize =
1114       getLastArgIntValue(Args, OPT_stack_protector_buffer_size, 8, Diags);
1115 
1116   Opts.StackProtectorGuard =
1117       std::string(Args.getLastArgValue(OPT_mstack_protector_guard_EQ));
1118 
1119   if (Arg *A = Args.getLastArg(OPT_mstack_protector_guard_offset_EQ)) {
1120     StringRef Val = A->getValue();
1121     unsigned Offset = Opts.StackProtectorGuardOffset;
1122     Val.getAsInteger(10, Offset);
1123     Opts.StackProtectorGuardOffset = Offset;
1124   }
1125 
1126   Opts.StackProtectorGuardReg =
1127       std::string(Args.getLastArgValue(OPT_mstack_protector_guard_reg_EQ,
1128                                        "none"));
1129 
1130 
1131   if (Args.getLastArg(OPT_femulated_tls) ||
1132       Args.getLastArg(OPT_fno_emulated_tls)) {
1133     Opts.ExplicitEmulatedTLS = true;
1134     Opts.EmulatedTLS =
1135         Args.hasFlag(OPT_femulated_tls, OPT_fno_emulated_tls, false);
1136   }
1137 
1138   if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_EQ)) {
1139     StringRef Val = A->getValue();
1140     Opts.FPDenormalMode = llvm::parseDenormalFPAttribute(Val);
1141     if (!Opts.FPDenormalMode.isValid())
1142       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
1143   }
1144 
1145   if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_f32_EQ)) {
1146     StringRef Val = A->getValue();
1147     Opts.FP32DenormalMode = llvm::parseDenormalFPAttribute(Val);
1148     if (!Opts.FP32DenormalMode.isValid())
1149       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
1150   }
1151 
1152   // X86_32 has -fppc-struct-return and -freg-struct-return.
1153   // PPC32 has -maix-struct-return and -msvr4-struct-return.
1154   if (Arg *A =
1155           Args.getLastArg(OPT_fpcc_struct_return, OPT_freg_struct_return,
1156                           OPT_maix_struct_return, OPT_msvr4_struct_return)) {
1157     // TODO: We might want to consider enabling these options on AIX in the
1158     // future.
1159     if (T.isOSAIX())
1160       Diags.Report(diag::err_drv_unsupported_opt_for_target)
1161           << A->getSpelling() << T.str();
1162 
1163     const Option &O = A->getOption();
1164     if (O.matches(OPT_fpcc_struct_return) ||
1165         O.matches(OPT_maix_struct_return)) {
1166       Opts.setStructReturnConvention(CodeGenOptions::SRCK_OnStack);
1167     } else {
1168       assert(O.matches(OPT_freg_struct_return) ||
1169              O.matches(OPT_msvr4_struct_return));
1170       Opts.setStructReturnConvention(CodeGenOptions::SRCK_InRegs);
1171     }
1172   }
1173 
1174   if (T.isOSAIX() && (Args.hasArg(OPT_mignore_xcoff_visibility) ||
1175                       !Args.hasArg(OPT_fvisibility)))
1176     Opts.IgnoreXCOFFVisibility = 1;
1177 
1178   if (Arg *A =
1179           Args.getLastArg(OPT_mabi_EQ_vec_default, OPT_mabi_EQ_vec_extabi)) {
1180     if (!T.isOSAIX())
1181       Diags.Report(diag::err_drv_unsupported_opt_for_target)
1182           << A->getSpelling() << T.str();
1183 
1184     const Option &O = A->getOption();
1185     if (O.matches(OPT_mabi_EQ_vec_default))
1186       Diags.Report(diag::err_aix_default_altivec_abi)
1187           << A->getSpelling() << T.str();
1188     else {
1189       assert(O.matches(OPT_mabi_EQ_vec_extabi));
1190       Opts.EnableAIXExtendedAltivecABI = 1;
1191     }
1192   }
1193 
1194   Opts.DependentLibraries = Args.getAllArgValues(OPT_dependent_lib);
1195   Opts.LinkerOptions = Args.getAllArgValues(OPT_linker_option);
1196   bool NeedLocTracking = false;
1197 
1198   if (!Opts.OptRecordFile.empty())
1199     NeedLocTracking = true;
1200 
1201   if (Arg *A = Args.getLastArg(OPT_opt_record_passes)) {
1202     Opts.OptRecordPasses = A->getValue();
1203     NeedLocTracking = true;
1204   }
1205 
1206   if (Arg *A = Args.getLastArg(OPT_opt_record_format)) {
1207     Opts.OptRecordFormat = A->getValue();
1208     NeedLocTracking = true;
1209   }
1210 
1211   if (Arg *A = Args.getLastArg(OPT_Rpass_EQ)) {
1212     Opts.OptimizationRemarkPattern =
1213         GenerateOptimizationRemarkRegex(Diags, Args, A);
1214     NeedLocTracking = true;
1215   }
1216 
1217   if (Arg *A = Args.getLastArg(OPT_Rpass_missed_EQ)) {
1218     Opts.OptimizationRemarkMissedPattern =
1219         GenerateOptimizationRemarkRegex(Diags, Args, A);
1220     NeedLocTracking = true;
1221   }
1222 
1223   if (Arg *A = Args.getLastArg(OPT_Rpass_analysis_EQ)) {
1224     Opts.OptimizationRemarkAnalysisPattern =
1225         GenerateOptimizationRemarkRegex(Diags, Args, A);
1226     NeedLocTracking = true;
1227   }
1228 
1229   bool UsingSampleProfile = !Opts.SampleProfileFile.empty();
1230   bool UsingProfile = UsingSampleProfile ||
1231       (Opts.getProfileUse() != CodeGenOptions::ProfileNone);
1232 
1233   if (Opts.DiagnosticsWithHotness && !UsingProfile &&
1234       // An IR file will contain PGO as metadata
1235       IK.getLanguage() != Language::LLVM_IR)
1236     Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
1237         << "-fdiagnostics-show-hotness";
1238 
1239   // Parse remarks hotness threshold. Valid value is either integer or 'auto'.
1240   if (auto *arg =
1241           Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
1242     auto ResultOrErr =
1243         llvm::remarks::parseHotnessThresholdOption(arg->getValue());
1244 
1245     if (!ResultOrErr) {
1246       Diags.Report(diag::err_drv_invalid_diagnotics_hotness_threshold)
1247           << "-fdiagnostics-hotness-threshold=";
1248     } else {
1249       Opts.DiagnosticsHotnessThreshold = *ResultOrErr;
1250       if ((!Opts.DiagnosticsHotnessThreshold.hasValue() ||
1251            Opts.DiagnosticsHotnessThreshold.getValue() > 0) &&
1252           !UsingProfile)
1253         Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
1254             << "-fdiagnostics-hotness-threshold=";
1255     }
1256   }
1257 
1258   // If the user requested to use a sample profile for PGO, then the
1259   // backend will need to track source location information so the profile
1260   // can be incorporated into the IR.
1261   if (UsingSampleProfile)
1262     NeedLocTracking = true;
1263 
1264   // If the user requested a flag that requires source locations available in
1265   // the backend, make sure that the backend tracks source location information.
1266   if (NeedLocTracking && Opts.getDebugInfo() == codegenoptions::NoDebugInfo)
1267     Opts.setDebugInfo(codegenoptions::LocTrackingOnly);
1268 
1269   Opts.RewriteMapFiles = Args.getAllArgValues(OPT_frewrite_map_file);
1270 
1271   // Parse -fsanitize-recover= arguments.
1272   // FIXME: Report unrecoverable sanitizers incorrectly specified here.
1273   parseSanitizerKinds("-fsanitize-recover=",
1274                       Args.getAllArgValues(OPT_fsanitize_recover_EQ), Diags,
1275                       Opts.SanitizeRecover);
1276   parseSanitizerKinds("-fsanitize-trap=",
1277                       Args.getAllArgValues(OPT_fsanitize_trap_EQ), Diags,
1278                       Opts.SanitizeTrap);
1279 
1280   Opts.EmitVersionIdentMetadata = Args.hasFlag(OPT_Qy, OPT_Qn, true);
1281 
1282   Opts.DefaultFunctionAttrs = Args.getAllArgValues(OPT_default_function_attr);
1283 
1284   Opts.PassPlugins = Args.getAllArgValues(OPT_fpass_plugin_EQ);
1285 
1286   return Success;
1287 }
1288 
1289 static void ParseDependencyOutputArgs(DependencyOutputOptions &Opts,
1290                                       ArgList &Args) {
1291   Opts.Targets = Args.getAllArgValues(OPT_MT);
1292   if (Args.hasArg(OPT_show_includes)) {
1293     // Writing both /showIncludes and preprocessor output to stdout
1294     // would produce interleaved output, so use stderr for /showIncludes.
1295     // This behaves the same as cl.exe, when /E, /EP or /P are passed.
1296     if (Args.hasArg(options::OPT_E) || Args.hasArg(options::OPT_P))
1297       Opts.ShowIncludesDest = ShowIncludesDestination::Stderr;
1298     else
1299       Opts.ShowIncludesDest = ShowIncludesDestination::Stdout;
1300   } else {
1301     Opts.ShowIncludesDest = ShowIncludesDestination::None;
1302   }
1303   // Add sanitizer blacklists as extra dependencies.
1304   // They won't be discovered by the regular preprocessor, so
1305   // we let make / ninja to know about this implicit dependency.
1306   if (!Args.hasArg(OPT_fno_sanitize_blacklist)) {
1307     for (const auto *A : Args.filtered(OPT_fsanitize_blacklist)) {
1308       StringRef Val = A->getValue();
1309       if (Val.find('=') == StringRef::npos)
1310         Opts.ExtraDeps.push_back(std::string(Val));
1311     }
1312     if (Opts.IncludeSystemHeaders) {
1313       for (const auto *A : Args.filtered(OPT_fsanitize_system_blacklist)) {
1314         StringRef Val = A->getValue();
1315         if (Val.find('=') == StringRef::npos)
1316           Opts.ExtraDeps.push_back(std::string(Val));
1317       }
1318     }
1319   }
1320 
1321   // Propagate the extra dependencies.
1322   for (const auto *A : Args.filtered(OPT_fdepfile_entry)) {
1323     Opts.ExtraDeps.push_back(A->getValue());
1324   }
1325 
1326   // Only the -fmodule-file=<file> form.
1327   for (const auto *A : Args.filtered(OPT_fmodule_file)) {
1328     StringRef Val = A->getValue();
1329     if (Val.find('=') == StringRef::npos)
1330       Opts.ExtraDeps.push_back(std::string(Val));
1331   }
1332 }
1333 
1334 static bool parseShowColorsArgs(const ArgList &Args, bool DefaultColor) {
1335   // Color diagnostics default to auto ("on" if terminal supports) in the driver
1336   // but default to off in cc1, needing an explicit OPT_fdiagnostics_color.
1337   // Support both clang's -f[no-]color-diagnostics and gcc's
1338   // -f[no-]diagnostics-colors[=never|always|auto].
1339   enum {
1340     Colors_On,
1341     Colors_Off,
1342     Colors_Auto
1343   } ShowColors = DefaultColor ? Colors_Auto : Colors_Off;
1344   for (auto *A : Args) {
1345     const Option &O = A->getOption();
1346     if (O.matches(options::OPT_fcolor_diagnostics) ||
1347         O.matches(options::OPT_fdiagnostics_color)) {
1348       ShowColors = Colors_On;
1349     } else if (O.matches(options::OPT_fno_color_diagnostics) ||
1350                O.matches(options::OPT_fno_diagnostics_color)) {
1351       ShowColors = Colors_Off;
1352     } else if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
1353       StringRef Value(A->getValue());
1354       if (Value == "always")
1355         ShowColors = Colors_On;
1356       else if (Value == "never")
1357         ShowColors = Colors_Off;
1358       else if (Value == "auto")
1359         ShowColors = Colors_Auto;
1360     }
1361   }
1362   return ShowColors == Colors_On ||
1363          (ShowColors == Colors_Auto &&
1364           llvm::sys::Process::StandardErrHasColors());
1365 }
1366 
1367 static bool checkVerifyPrefixes(const std::vector<std::string> &VerifyPrefixes,
1368                                 DiagnosticsEngine *Diags) {
1369   bool Success = true;
1370   for (const auto &Prefix : VerifyPrefixes) {
1371     // Every prefix must start with a letter and contain only alphanumeric
1372     // characters, hyphens, and underscores.
1373     auto BadChar = llvm::find_if(Prefix, [](char C) {
1374       return !isAlphanumeric(C) && C != '-' && C != '_';
1375     });
1376     if (BadChar != Prefix.end() || !isLetter(Prefix[0])) {
1377       Success = false;
1378       if (Diags) {
1379         Diags->Report(diag::err_drv_invalid_value) << "-verify=" << Prefix;
1380         Diags->Report(diag::note_drv_verify_prefix_spelling);
1381       }
1382     }
1383   }
1384   return Success;
1385 }
1386 
1387 bool clang::ParseDiagnosticArgs(DiagnosticOptions &Opts, ArgList &Args,
1388                                 DiagnosticsEngine *Diags,
1389                                 bool DefaultDiagColor) {
1390   bool Success = true;
1391 
1392   Opts.DiagnosticLogFile =
1393       std::string(Args.getLastArgValue(OPT_diagnostic_log_file));
1394   if (Arg *A =
1395           Args.getLastArg(OPT_diagnostic_serialized_file, OPT__serialize_diags))
1396     Opts.DiagnosticSerializationFile = A->getValue();
1397   Opts.IgnoreWarnings = Args.hasArg(OPT_w);
1398   Opts.NoRewriteMacros = Args.hasArg(OPT_Wno_rewrite_macros);
1399   Opts.Pedantic = Args.hasArg(OPT_pedantic);
1400   Opts.PedanticErrors = Args.hasArg(OPT_pedantic_errors);
1401   Opts.ShowCarets = !Args.hasArg(OPT_fno_caret_diagnostics);
1402   Opts.ShowColors = parseShowColorsArgs(Args, DefaultDiagColor);
1403   Opts.ShowColumn = !Args.hasArg(OPT_fno_show_column);
1404   Opts.ShowFixits = !Args.hasArg(OPT_fno_diagnostics_fixit_info);
1405   Opts.ShowLocation = !Args.hasArg(OPT_fno_show_source_location);
1406   Opts.AbsolutePath = Args.hasArg(OPT_fdiagnostics_absolute_paths);
1407   Opts.ShowOptionNames = !Args.hasArg(OPT_fno_diagnostics_show_option);
1408 
1409   // Default behavior is to not to show note include stacks.
1410   Opts.ShowNoteIncludeStack = false;
1411   if (Arg *A = Args.getLastArg(OPT_fdiagnostics_show_note_include_stack,
1412                                OPT_fno_diagnostics_show_note_include_stack))
1413     if (A->getOption().matches(OPT_fdiagnostics_show_note_include_stack))
1414       Opts.ShowNoteIncludeStack = true;
1415 
1416   StringRef ShowOverloads =
1417     Args.getLastArgValue(OPT_fshow_overloads_EQ, "all");
1418   if (ShowOverloads == "best")
1419     Opts.setShowOverloads(Ovl_Best);
1420   else if (ShowOverloads == "all")
1421     Opts.setShowOverloads(Ovl_All);
1422   else {
1423     Success = false;
1424     if (Diags)
1425       Diags->Report(diag::err_drv_invalid_value)
1426       << Args.getLastArg(OPT_fshow_overloads_EQ)->getAsString(Args)
1427       << ShowOverloads;
1428   }
1429 
1430   StringRef ShowCategory =
1431     Args.getLastArgValue(OPT_fdiagnostics_show_category, "none");
1432   if (ShowCategory == "none")
1433     Opts.ShowCategories = 0;
1434   else if (ShowCategory == "id")
1435     Opts.ShowCategories = 1;
1436   else if (ShowCategory == "name")
1437     Opts.ShowCategories = 2;
1438   else {
1439     Success = false;
1440     if (Diags)
1441       Diags->Report(diag::err_drv_invalid_value)
1442       << Args.getLastArg(OPT_fdiagnostics_show_category)->getAsString(Args)
1443       << ShowCategory;
1444   }
1445 
1446   StringRef Format =
1447     Args.getLastArgValue(OPT_fdiagnostics_format, "clang");
1448   if (Format == "clang")
1449     Opts.setFormat(DiagnosticOptions::Clang);
1450   else if (Format == "msvc")
1451     Opts.setFormat(DiagnosticOptions::MSVC);
1452   else if (Format == "msvc-fallback") {
1453     Opts.setFormat(DiagnosticOptions::MSVC);
1454     Opts.CLFallbackMode = true;
1455   } else if (Format == "vi")
1456     Opts.setFormat(DiagnosticOptions::Vi);
1457   else {
1458     Success = false;
1459     if (Diags)
1460       Diags->Report(diag::err_drv_invalid_value)
1461       << Args.getLastArg(OPT_fdiagnostics_format)->getAsString(Args)
1462       << Format;
1463   }
1464 
1465   Opts.ShowSourceRanges = Args.hasArg(OPT_fdiagnostics_print_source_range_info);
1466   Opts.ShowParseableFixits = Args.hasArg(OPT_fdiagnostics_parseable_fixits);
1467   Opts.ShowPresumedLoc = !Args.hasArg(OPT_fno_diagnostics_use_presumed_location);
1468   Opts.VerifyDiagnostics = Args.hasArg(OPT_verify) || Args.hasArg(OPT_verify_EQ);
1469   Opts.VerifyPrefixes = Args.getAllArgValues(OPT_verify_EQ);
1470   if (Args.hasArg(OPT_verify))
1471     Opts.VerifyPrefixes.push_back("expected");
1472   // Keep VerifyPrefixes in its original order for the sake of diagnostics, and
1473   // then sort it to prepare for fast lookup using std::binary_search.
1474   if (!checkVerifyPrefixes(Opts.VerifyPrefixes, Diags)) {
1475     Opts.VerifyDiagnostics = false;
1476     Success = false;
1477   }
1478   else
1479     llvm::sort(Opts.VerifyPrefixes);
1480   DiagnosticLevelMask DiagMask = DiagnosticLevelMask::None;
1481   Success &= parseDiagnosticLevelMask("-verify-ignore-unexpected=",
1482     Args.getAllArgValues(OPT_verify_ignore_unexpected_EQ),
1483     Diags, DiagMask);
1484   if (Args.hasArg(OPT_verify_ignore_unexpected))
1485     DiagMask = DiagnosticLevelMask::All;
1486   Opts.setVerifyIgnoreUnexpected(DiagMask);
1487   Opts.ElideType = !Args.hasArg(OPT_fno_elide_type);
1488   Opts.ShowTemplateTree = Args.hasArg(OPT_fdiagnostics_show_template_tree);
1489   Opts.ErrorLimit = getLastArgIntValue(Args, OPT_ferror_limit, 0, Diags);
1490   Opts.MacroBacktraceLimit =
1491       getLastArgIntValue(Args, OPT_fmacro_backtrace_limit,
1492                          DiagnosticOptions::DefaultMacroBacktraceLimit, Diags);
1493   Opts.TemplateBacktraceLimit = getLastArgIntValue(
1494       Args, OPT_ftemplate_backtrace_limit,
1495       DiagnosticOptions::DefaultTemplateBacktraceLimit, Diags);
1496   Opts.ConstexprBacktraceLimit = getLastArgIntValue(
1497       Args, OPT_fconstexpr_backtrace_limit,
1498       DiagnosticOptions::DefaultConstexprBacktraceLimit, Diags);
1499   Opts.SpellCheckingLimit = getLastArgIntValue(
1500       Args, OPT_fspell_checking_limit,
1501       DiagnosticOptions::DefaultSpellCheckingLimit, Diags);
1502   Opts.SnippetLineLimit = getLastArgIntValue(
1503       Args, OPT_fcaret_diagnostics_max_lines,
1504       DiagnosticOptions::DefaultSnippetLineLimit, Diags);
1505   Opts.TabStop = getLastArgIntValue(Args, OPT_ftabstop,
1506                                     DiagnosticOptions::DefaultTabStop, Diags);
1507   if (Opts.TabStop == 0 || Opts.TabStop > DiagnosticOptions::MaxTabStop) {
1508     Opts.TabStop = DiagnosticOptions::DefaultTabStop;
1509     if (Diags)
1510       Diags->Report(diag::warn_ignoring_ftabstop_value)
1511       << Opts.TabStop << DiagnosticOptions::DefaultTabStop;
1512   }
1513   Opts.MessageLength =
1514       getLastArgIntValue(Args, OPT_fmessage_length_EQ, 0, Diags);
1515 
1516   Opts.UndefPrefixes = Args.getAllArgValues(OPT_Wundef_prefix_EQ);
1517 
1518   addDiagnosticArgs(Args, OPT_W_Group, OPT_W_value_Group, Opts.Warnings);
1519   addDiagnosticArgs(Args, OPT_R_Group, OPT_R_value_Group, Opts.Remarks);
1520 
1521   return Success;
1522 }
1523 
1524 /// Parse the argument to the -ftest-module-file-extension
1525 /// command-line argument.
1526 ///
1527 /// \returns true on error, false on success.
1528 static bool parseTestModuleFileExtensionArg(StringRef Arg,
1529                                             std::string &BlockName,
1530                                             unsigned &MajorVersion,
1531                                             unsigned &MinorVersion,
1532                                             bool &Hashed,
1533                                             std::string &UserInfo) {
1534   SmallVector<StringRef, 5> Args;
1535   Arg.split(Args, ':', 5);
1536   if (Args.size() < 5)
1537     return true;
1538 
1539   BlockName = std::string(Args[0]);
1540   if (Args[1].getAsInteger(10, MajorVersion)) return true;
1541   if (Args[2].getAsInteger(10, MinorVersion)) return true;
1542   if (Args[3].getAsInteger(2, Hashed)) return true;
1543   if (Args.size() > 4)
1544     UserInfo = std::string(Args[4]);
1545   return false;
1546 }
1547 
1548 static InputKind ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args,
1549                                    DiagnosticsEngine &Diags,
1550                                    bool &IsHeaderFile) {
1551   Opts.ProgramAction = frontend::ParseSyntaxOnly;
1552   if (const Arg *A = Args.getLastArg(OPT_Action_Group)) {
1553     switch (A->getOption().getID()) {
1554     default:
1555       llvm_unreachable("Invalid option in group!");
1556     case OPT_ast_list:
1557       Opts.ProgramAction = frontend::ASTDeclList; break;
1558     case OPT_ast_dump_all_EQ:
1559     case OPT_ast_dump_EQ: {
1560       unsigned Val = llvm::StringSwitch<unsigned>(A->getValue())
1561                          .CaseLower("default", ADOF_Default)
1562                          .CaseLower("json", ADOF_JSON)
1563                          .Default(std::numeric_limits<unsigned>::max());
1564 
1565       if (Val != std::numeric_limits<unsigned>::max())
1566         Opts.ASTDumpFormat = static_cast<ASTDumpOutputFormat>(Val);
1567       else {
1568         Diags.Report(diag::err_drv_invalid_value)
1569             << A->getAsString(Args) << A->getValue();
1570         Opts.ASTDumpFormat = ADOF_Default;
1571       }
1572       LLVM_FALLTHROUGH;
1573     }
1574     case OPT_ast_dump:
1575     case OPT_ast_dump_all:
1576     case OPT_ast_dump_lookups:
1577     case OPT_ast_dump_decl_types:
1578       Opts.ProgramAction = frontend::ASTDump; break;
1579     case OPT_ast_print:
1580       Opts.ProgramAction = frontend::ASTPrint; break;
1581     case OPT_ast_view:
1582       Opts.ProgramAction = frontend::ASTView; break;
1583     case OPT_compiler_options_dump:
1584       Opts.ProgramAction = frontend::DumpCompilerOptions; break;
1585     case OPT_dump_raw_tokens:
1586       Opts.ProgramAction = frontend::DumpRawTokens; break;
1587     case OPT_dump_tokens:
1588       Opts.ProgramAction = frontend::DumpTokens; break;
1589     case OPT_S:
1590       Opts.ProgramAction = frontend::EmitAssembly; break;
1591     case OPT_emit_llvm_bc:
1592       Opts.ProgramAction = frontend::EmitBC; break;
1593     case OPT_emit_html:
1594       Opts.ProgramAction = frontend::EmitHTML; break;
1595     case OPT_emit_llvm:
1596       Opts.ProgramAction = frontend::EmitLLVM; break;
1597     case OPT_emit_llvm_only:
1598       Opts.ProgramAction = frontend::EmitLLVMOnly; break;
1599     case OPT_emit_codegen_only:
1600       Opts.ProgramAction = frontend::EmitCodeGenOnly; break;
1601     case OPT_emit_obj:
1602       Opts.ProgramAction = frontend::EmitObj; break;
1603     case OPT_fixit_EQ:
1604       Opts.FixItSuffix = A->getValue();
1605       LLVM_FALLTHROUGH;
1606     case OPT_fixit:
1607       Opts.ProgramAction = frontend::FixIt; break;
1608     case OPT_emit_module:
1609       Opts.ProgramAction = frontend::GenerateModule; break;
1610     case OPT_emit_module_interface:
1611       Opts.ProgramAction = frontend::GenerateModuleInterface; break;
1612     case OPT_emit_header_module:
1613       Opts.ProgramAction = frontend::GenerateHeaderModule; break;
1614     case OPT_emit_pch:
1615       Opts.ProgramAction = frontend::GeneratePCH; break;
1616     case OPT_emit_interface_stubs: {
1617       StringRef ArgStr =
1618           Args.hasArg(OPT_interface_stub_version_EQ)
1619               ? Args.getLastArgValue(OPT_interface_stub_version_EQ)
1620               : "experimental-ifs-v2";
1621       if (ArgStr == "experimental-yaml-elf-v1" ||
1622           ArgStr == "experimental-ifs-v1" ||
1623           ArgStr == "experimental-tapi-elf-v1") {
1624         std::string ErrorMessage =
1625             "Invalid interface stub format: " + ArgStr.str() +
1626             " is deprecated.";
1627         Diags.Report(diag::err_drv_invalid_value)
1628             << "Must specify a valid interface stub format type, ie: "
1629                "-interface-stub-version=experimental-ifs-v2"
1630             << ErrorMessage;
1631       } else if (!ArgStr.startswith("experimental-ifs-")) {
1632         std::string ErrorMessage =
1633             "Invalid interface stub format: " + ArgStr.str() + ".";
1634         Diags.Report(diag::err_drv_invalid_value)
1635             << "Must specify a valid interface stub format type, ie: "
1636                "-interface-stub-version=experimental-ifs-v2"
1637             << ErrorMessage;
1638       } else {
1639         Opts.ProgramAction = frontend::GenerateInterfaceStubs;
1640       }
1641       break;
1642     }
1643     case OPT_init_only:
1644       Opts.ProgramAction = frontend::InitOnly; break;
1645     case OPT_fsyntax_only:
1646       Opts.ProgramAction = frontend::ParseSyntaxOnly; break;
1647     case OPT_module_file_info:
1648       Opts.ProgramAction = frontend::ModuleFileInfo; break;
1649     case OPT_verify_pch:
1650       Opts.ProgramAction = frontend::VerifyPCH; break;
1651     case OPT_print_preamble:
1652       Opts.ProgramAction = frontend::PrintPreamble; break;
1653     case OPT_E:
1654       Opts.ProgramAction = frontend::PrintPreprocessedInput; break;
1655     case OPT_templight_dump:
1656       Opts.ProgramAction = frontend::TemplightDump; break;
1657     case OPT_rewrite_macros:
1658       Opts.ProgramAction = frontend::RewriteMacros; break;
1659     case OPT_rewrite_objc:
1660       Opts.ProgramAction = frontend::RewriteObjC; break;
1661     case OPT_rewrite_test:
1662       Opts.ProgramAction = frontend::RewriteTest; break;
1663     case OPT_analyze:
1664       Opts.ProgramAction = frontend::RunAnalysis; break;
1665     case OPT_migrate:
1666       Opts.ProgramAction = frontend::MigrateSource; break;
1667     case OPT_Eonly:
1668       Opts.ProgramAction = frontend::RunPreprocessorOnly; break;
1669     case OPT_print_dependency_directives_minimized_source:
1670       Opts.ProgramAction =
1671           frontend::PrintDependencyDirectivesSourceMinimizerOutput;
1672       break;
1673     }
1674   }
1675 
1676   if (const Arg* A = Args.getLastArg(OPT_plugin)) {
1677     Opts.Plugins.emplace_back(A->getValue(0));
1678     Opts.ProgramAction = frontend::PluginAction;
1679     Opts.ActionName = A->getValue();
1680   }
1681   Opts.AddPluginActions = Args.getAllArgValues(OPT_add_plugin);
1682   for (const auto *AA : Args.filtered(OPT_plugin_arg))
1683     Opts.PluginArgs[AA->getValue(0)].emplace_back(AA->getValue(1));
1684 
1685   for (const std::string &Arg :
1686          Args.getAllArgValues(OPT_ftest_module_file_extension_EQ)) {
1687     std::string BlockName;
1688     unsigned MajorVersion;
1689     unsigned MinorVersion;
1690     bool Hashed;
1691     std::string UserInfo;
1692     if (parseTestModuleFileExtensionArg(Arg, BlockName, MajorVersion,
1693                                         MinorVersion, Hashed, UserInfo)) {
1694       Diags.Report(diag::err_test_module_file_extension_format) << Arg;
1695 
1696       continue;
1697     }
1698 
1699     // Add the testing module file extension.
1700     Opts.ModuleFileExtensions.push_back(
1701         std::make_shared<TestModuleFileExtension>(
1702             BlockName, MajorVersion, MinorVersion, Hashed, UserInfo));
1703   }
1704 
1705   if (const Arg *A = Args.getLastArg(OPT_code_completion_at)) {
1706     Opts.CodeCompletionAt =
1707       ParsedSourceLocation::FromString(A->getValue());
1708     if (Opts.CodeCompletionAt.FileName.empty())
1709       Diags.Report(diag::err_drv_invalid_value)
1710         << A->getAsString(Args) << A->getValue();
1711   }
1712 
1713   Opts.Plugins = Args.getAllArgValues(OPT_load);
1714   Opts.ASTMergeFiles = Args.getAllArgValues(OPT_ast_merge);
1715   Opts.LLVMArgs = Args.getAllArgValues(OPT_mllvm);
1716   Opts.ASTDumpDecls = Args.hasArg(OPT_ast_dump, OPT_ast_dump_EQ);
1717   Opts.ASTDumpAll = Args.hasArg(OPT_ast_dump_all, OPT_ast_dump_all_EQ);
1718   Opts.ModuleMapFiles = Args.getAllArgValues(OPT_fmodule_map_file);
1719   // Only the -fmodule-file=<file> form.
1720   for (const auto *A : Args.filtered(OPT_fmodule_file)) {
1721     StringRef Val = A->getValue();
1722     if (Val.find('=') == StringRef::npos)
1723       Opts.ModuleFiles.push_back(std::string(Val));
1724   }
1725   Opts.ModulesEmbedFiles = Args.getAllArgValues(OPT_fmodules_embed_file_EQ);
1726   Opts.AllowPCMWithCompilerErrors = Args.hasArg(OPT_fallow_pcm_with_errors);
1727 
1728   if (Opts.ProgramAction != frontend::GenerateModule && Opts.IsSystemModule)
1729     Diags.Report(diag::err_drv_argument_only_allowed_with) << "-fsystem-module"
1730                                                            << "-emit-module";
1731 
1732   if (Args.hasArg(OPT_aux_target_cpu))
1733     Opts.AuxTargetCPU = std::string(Args.getLastArgValue(OPT_aux_target_cpu));
1734   if (Args.hasArg(OPT_aux_target_feature))
1735     Opts.AuxTargetFeatures = Args.getAllArgValues(OPT_aux_target_feature);
1736 
1737   if (Opts.ARCMTAction != FrontendOptions::ARCMT_None &&
1738       Opts.ObjCMTAction != FrontendOptions::ObjCMT_None) {
1739     Diags.Report(diag::err_drv_argument_not_allowed_with)
1740       << "ARC migration" << "ObjC migration";
1741   }
1742 
1743   InputKind DashX(Language::Unknown);
1744   if (const Arg *A = Args.getLastArg(OPT_x)) {
1745     StringRef XValue = A->getValue();
1746 
1747     // Parse suffixes: '<lang>(-header|[-module-map][-cpp-output])'.
1748     // FIXME: Supporting '<lang>-header-cpp-output' would be useful.
1749     bool Preprocessed = XValue.consume_back("-cpp-output");
1750     bool ModuleMap = XValue.consume_back("-module-map");
1751     IsHeaderFile = !Preprocessed && !ModuleMap &&
1752                    XValue != "precompiled-header" &&
1753                    XValue.consume_back("-header");
1754 
1755     // Principal languages.
1756     DashX = llvm::StringSwitch<InputKind>(XValue)
1757                 .Case("c", Language::C)
1758                 .Case("cl", Language::OpenCL)
1759                 .Case("cuda", Language::CUDA)
1760                 .Case("hip", Language::HIP)
1761                 .Case("c++", Language::CXX)
1762                 .Case("objective-c", Language::ObjC)
1763                 .Case("objective-c++", Language::ObjCXX)
1764                 .Case("renderscript", Language::RenderScript)
1765                 .Default(Language::Unknown);
1766 
1767     // "objc[++]-cpp-output" is an acceptable synonym for
1768     // "objective-c[++]-cpp-output".
1769     if (DashX.isUnknown() && Preprocessed && !IsHeaderFile && !ModuleMap)
1770       DashX = llvm::StringSwitch<InputKind>(XValue)
1771                   .Case("objc", Language::ObjC)
1772                   .Case("objc++", Language::ObjCXX)
1773                   .Default(Language::Unknown);
1774 
1775     // Some special cases cannot be combined with suffixes.
1776     if (DashX.isUnknown() && !Preprocessed && !ModuleMap && !IsHeaderFile)
1777       DashX = llvm::StringSwitch<InputKind>(XValue)
1778                   .Case("cpp-output", InputKind(Language::C).getPreprocessed())
1779                   .Case("assembler-with-cpp", Language::Asm)
1780                   .Cases("ast", "pcm", "precompiled-header",
1781                          InputKind(Language::Unknown, InputKind::Precompiled))
1782                   .Case("ir", Language::LLVM_IR)
1783                   .Default(Language::Unknown);
1784 
1785     if (DashX.isUnknown())
1786       Diags.Report(diag::err_drv_invalid_value)
1787         << A->getAsString(Args) << A->getValue();
1788 
1789     if (Preprocessed)
1790       DashX = DashX.getPreprocessed();
1791     if (ModuleMap)
1792       DashX = DashX.withFormat(InputKind::ModuleMap);
1793   }
1794 
1795   // '-' is the default input if none is given.
1796   std::vector<std::string> Inputs = Args.getAllArgValues(OPT_INPUT);
1797   Opts.Inputs.clear();
1798   if (Inputs.empty())
1799     Inputs.push_back("-");
1800   for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
1801     InputKind IK = DashX;
1802     if (IK.isUnknown()) {
1803       IK = FrontendOptions::getInputKindForExtension(
1804         StringRef(Inputs[i]).rsplit('.').second);
1805       // FIXME: Warn on this?
1806       if (IK.isUnknown())
1807         IK = Language::C;
1808       // FIXME: Remove this hack.
1809       if (i == 0)
1810         DashX = IK;
1811     }
1812 
1813     bool IsSystem = false;
1814 
1815     // The -emit-module action implicitly takes a module map.
1816     if (Opts.ProgramAction == frontend::GenerateModule &&
1817         IK.getFormat() == InputKind::Source) {
1818       IK = IK.withFormat(InputKind::ModuleMap);
1819       IsSystem = Opts.IsSystemModule;
1820     }
1821 
1822     Opts.Inputs.emplace_back(std::move(Inputs[i]), IK, IsSystem);
1823   }
1824 
1825   return DashX;
1826 }
1827 
1828 std::string CompilerInvocation::GetResourcesPath(const char *Argv0,
1829                                                  void *MainAddr) {
1830   std::string ClangExecutable =
1831       llvm::sys::fs::getMainExecutable(Argv0, MainAddr);
1832   return Driver::GetResourcesPath(ClangExecutable, CLANG_RESOURCE_DIR);
1833 }
1834 
1835 static void ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args,
1836                                   const std::string &WorkingDir) {
1837   if (const Arg *A = Args.getLastArg(OPT_stdlib_EQ))
1838     Opts.UseLibcxx = (strcmp(A->getValue(), "libc++") == 0);
1839 
1840   // Canonicalize -fmodules-cache-path before storing it.
1841   SmallString<128> P(Args.getLastArgValue(OPT_fmodules_cache_path));
1842   if (!(P.empty() || llvm::sys::path::is_absolute(P))) {
1843     if (WorkingDir.empty())
1844       llvm::sys::fs::make_absolute(P);
1845     else
1846       llvm::sys::fs::make_absolute(WorkingDir, P);
1847   }
1848   llvm::sys::path::remove_dots(P);
1849   Opts.ModuleCachePath = std::string(P.str());
1850 
1851   // Only the -fmodule-file=<name>=<file> form.
1852   for (const auto *A : Args.filtered(OPT_fmodule_file)) {
1853     StringRef Val = A->getValue();
1854     if (Val.find('=') != StringRef::npos){
1855       auto Split = Val.split('=');
1856       Opts.PrebuiltModuleFiles.insert(
1857           {std::string(Split.first), std::string(Split.second)});
1858     }
1859   }
1860   for (const auto *A : Args.filtered(OPT_fprebuilt_module_path))
1861     Opts.AddPrebuiltModulePath(A->getValue());
1862 
1863   for (const auto *A : Args.filtered(OPT_fmodules_ignore_macro)) {
1864     StringRef MacroDef = A->getValue();
1865     Opts.ModulesIgnoreMacros.insert(
1866         llvm::CachedHashString(MacroDef.split('=').first));
1867   }
1868 
1869   // Add -I..., -F..., and -index-header-map options in order.
1870   bool IsIndexHeaderMap = false;
1871   bool IsSysrootSpecified =
1872       Args.hasArg(OPT__sysroot_EQ) || Args.hasArg(OPT_isysroot);
1873   for (const auto *A : Args.filtered(OPT_I, OPT_F, OPT_index_header_map)) {
1874     if (A->getOption().matches(OPT_index_header_map)) {
1875       // -index-header-map applies to the next -I or -F.
1876       IsIndexHeaderMap = true;
1877       continue;
1878     }
1879 
1880     frontend::IncludeDirGroup Group =
1881         IsIndexHeaderMap ? frontend::IndexHeaderMap : frontend::Angled;
1882 
1883     bool IsFramework = A->getOption().matches(OPT_F);
1884     std::string Path = A->getValue();
1885 
1886     if (IsSysrootSpecified && !IsFramework && A->getValue()[0] == '=') {
1887       SmallString<32> Buffer;
1888       llvm::sys::path::append(Buffer, Opts.Sysroot,
1889                               llvm::StringRef(A->getValue()).substr(1));
1890       Path = std::string(Buffer.str());
1891     }
1892 
1893     Opts.AddPath(Path, Group, IsFramework,
1894                  /*IgnoreSysroot*/ true);
1895     IsIndexHeaderMap = false;
1896   }
1897 
1898   // Add -iprefix/-iwithprefix/-iwithprefixbefore options.
1899   StringRef Prefix = ""; // FIXME: This isn't the correct default prefix.
1900   for (const auto *A :
1901        Args.filtered(OPT_iprefix, OPT_iwithprefix, OPT_iwithprefixbefore)) {
1902     if (A->getOption().matches(OPT_iprefix))
1903       Prefix = A->getValue();
1904     else if (A->getOption().matches(OPT_iwithprefix))
1905       Opts.AddPath(Prefix.str() + A->getValue(), frontend::After, false, true);
1906     else
1907       Opts.AddPath(Prefix.str() + A->getValue(), frontend::Angled, false, true);
1908   }
1909 
1910   for (const auto *A : Args.filtered(OPT_idirafter))
1911     Opts.AddPath(A->getValue(), frontend::After, false, true);
1912   for (const auto *A : Args.filtered(OPT_iquote))
1913     Opts.AddPath(A->getValue(), frontend::Quoted, false, true);
1914   for (const auto *A : Args.filtered(OPT_isystem, OPT_iwithsysroot))
1915     Opts.AddPath(A->getValue(), frontend::System, false,
1916                  !A->getOption().matches(OPT_iwithsysroot));
1917   for (const auto *A : Args.filtered(OPT_iframework))
1918     Opts.AddPath(A->getValue(), frontend::System, true, true);
1919   for (const auto *A : Args.filtered(OPT_iframeworkwithsysroot))
1920     Opts.AddPath(A->getValue(), frontend::System, /*IsFramework=*/true,
1921                  /*IgnoreSysRoot=*/false);
1922 
1923   // Add the paths for the various language specific isystem flags.
1924   for (const auto *A : Args.filtered(OPT_c_isystem))
1925     Opts.AddPath(A->getValue(), frontend::CSystem, false, true);
1926   for (const auto *A : Args.filtered(OPT_cxx_isystem))
1927     Opts.AddPath(A->getValue(), frontend::CXXSystem, false, true);
1928   for (const auto *A : Args.filtered(OPT_objc_isystem))
1929     Opts.AddPath(A->getValue(), frontend::ObjCSystem, false,true);
1930   for (const auto *A : Args.filtered(OPT_objcxx_isystem))
1931     Opts.AddPath(A->getValue(), frontend::ObjCXXSystem, false, true);
1932 
1933   // Add the internal paths from a driver that detects standard include paths.
1934   for (const auto *A :
1935        Args.filtered(OPT_internal_isystem, OPT_internal_externc_isystem)) {
1936     frontend::IncludeDirGroup Group = frontend::System;
1937     if (A->getOption().matches(OPT_internal_externc_isystem))
1938       Group = frontend::ExternCSystem;
1939     Opts.AddPath(A->getValue(), Group, false, true);
1940   }
1941 
1942   // Add the path prefixes which are implicitly treated as being system headers.
1943   for (const auto *A :
1944        Args.filtered(OPT_system_header_prefix, OPT_no_system_header_prefix))
1945     Opts.AddSystemHeaderPrefix(
1946         A->getValue(), A->getOption().matches(OPT_system_header_prefix));
1947 
1948   for (const auto *A : Args.filtered(OPT_ivfsoverlay))
1949     Opts.AddVFSOverlayFile(A->getValue());
1950 }
1951 
1952 void CompilerInvocation::setLangDefaults(LangOptions &Opts, InputKind IK,
1953                                          const llvm::Triple &T,
1954                                          PreprocessorOptions &PPOpts,
1955                                          LangStandard::Kind LangStd) {
1956   // Set some properties which depend solely on the input kind; it would be nice
1957   // to move these to the language standard, and have the driver resolve the
1958   // input kind + language standard.
1959   //
1960   // FIXME: Perhaps a better model would be for a single source file to have
1961   // multiple language standards (C / C++ std, ObjC std, OpenCL std, OpenMP std)
1962   // simultaneously active?
1963   if (IK.getLanguage() == Language::Asm) {
1964     Opts.AsmPreprocessor = 1;
1965   } else if (IK.isObjectiveC()) {
1966     Opts.ObjC = 1;
1967   }
1968 
1969   if (LangStd == LangStandard::lang_unspecified) {
1970     // Based on the base language, pick one.
1971     switch (IK.getLanguage()) {
1972     case Language::Unknown:
1973     case Language::LLVM_IR:
1974       llvm_unreachable("Invalid input kind!");
1975     case Language::OpenCL:
1976       LangStd = LangStandard::lang_opencl10;
1977       break;
1978     case Language::CUDA:
1979       LangStd = LangStandard::lang_cuda;
1980       break;
1981     case Language::Asm:
1982     case Language::C:
1983 #if defined(CLANG_DEFAULT_STD_C)
1984       LangStd = CLANG_DEFAULT_STD_C;
1985 #else
1986       // The PS4 uses C99 as the default C standard.
1987       if (T.isPS4())
1988         LangStd = LangStandard::lang_gnu99;
1989       else
1990         LangStd = LangStandard::lang_gnu17;
1991 #endif
1992       break;
1993     case Language::ObjC:
1994 #if defined(CLANG_DEFAULT_STD_C)
1995       LangStd = CLANG_DEFAULT_STD_C;
1996 #else
1997       LangStd = LangStandard::lang_gnu11;
1998 #endif
1999       break;
2000     case Language::CXX:
2001     case Language::ObjCXX:
2002 #if defined(CLANG_DEFAULT_STD_CXX)
2003       LangStd = CLANG_DEFAULT_STD_CXX;
2004 #else
2005       LangStd = LangStandard::lang_gnucxx14;
2006 #endif
2007       break;
2008     case Language::RenderScript:
2009       LangStd = LangStandard::lang_c99;
2010       break;
2011     case Language::HIP:
2012       LangStd = LangStandard::lang_hip;
2013       break;
2014     }
2015   }
2016 
2017   const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
2018   Opts.LineComment = Std.hasLineComments();
2019   Opts.C99 = Std.isC99();
2020   Opts.C11 = Std.isC11();
2021   Opts.C17 = Std.isC17();
2022   Opts.C2x = Std.isC2x();
2023   Opts.CPlusPlus = Std.isCPlusPlus();
2024   Opts.CPlusPlus11 = Std.isCPlusPlus11();
2025   Opts.CPlusPlus14 = Std.isCPlusPlus14();
2026   Opts.CPlusPlus17 = Std.isCPlusPlus17();
2027   Opts.CPlusPlus20 = Std.isCPlusPlus20();
2028   Opts.CPlusPlus2b = Std.isCPlusPlus2b();
2029   Opts.Digraphs = Std.hasDigraphs();
2030   Opts.GNUMode = Std.isGNUMode();
2031   Opts.GNUInline = !Opts.C99 && !Opts.CPlusPlus;
2032   Opts.GNUCVersion = 0;
2033   Opts.HexFloats = Std.hasHexFloats();
2034   Opts.ImplicitInt = Std.hasImplicitInt();
2035 
2036   // Set OpenCL Version.
2037   Opts.OpenCL = Std.isOpenCL();
2038   if (LangStd == LangStandard::lang_opencl10)
2039     Opts.OpenCLVersion = 100;
2040   else if (LangStd == LangStandard::lang_opencl11)
2041     Opts.OpenCLVersion = 110;
2042   else if (LangStd == LangStandard::lang_opencl12)
2043     Opts.OpenCLVersion = 120;
2044   else if (LangStd == LangStandard::lang_opencl20)
2045     Opts.OpenCLVersion = 200;
2046   else if (LangStd == LangStandard::lang_opencl30)
2047     Opts.OpenCLVersion = 300;
2048   else if (LangStd == LangStandard::lang_openclcpp)
2049     Opts.OpenCLCPlusPlusVersion = 100;
2050 
2051   // OpenCL has some additional defaults.
2052   if (Opts.OpenCL) {
2053     Opts.AltiVec = 0;
2054     Opts.ZVector = 0;
2055     Opts.setLaxVectorConversions(LangOptions::LaxVectorConversionKind::None);
2056     Opts.setDefaultFPContractMode(LangOptions::FPM_On);
2057     Opts.NativeHalfType = 1;
2058     Opts.NativeHalfArgsAndReturns = 1;
2059     Opts.OpenCLCPlusPlus = Opts.CPlusPlus;
2060 
2061     // Include default header file for OpenCL.
2062     if (Opts.IncludeDefaultHeader) {
2063       if (Opts.DeclareOpenCLBuiltins) {
2064         // Only include base header file for builtin types and constants.
2065         PPOpts.Includes.push_back("opencl-c-base.h");
2066       } else {
2067         PPOpts.Includes.push_back("opencl-c.h");
2068       }
2069     }
2070   }
2071 
2072   Opts.HIP = IK.getLanguage() == Language::HIP;
2073   Opts.CUDA = IK.getLanguage() == Language::CUDA || Opts.HIP;
2074   if (Opts.HIP) {
2075     // HIP toolchain does not support 'Fast' FPOpFusion in backends since it
2076     // fuses multiplication/addition instructions without contract flag from
2077     // device library functions in LLVM bitcode, which causes accuracy loss in
2078     // certain math functions, e.g. tan(-1e20) becomes -0.933 instead of 0.8446.
2079     // For device library functions in bitcode to work, 'Strict' or 'Standard'
2080     // FPOpFusion options in backends is needed. Therefore 'fast-honor-pragmas'
2081     // FP contract option is used to allow fuse across statements in frontend
2082     // whereas respecting contract flag in backend.
2083     Opts.setDefaultFPContractMode(LangOptions::FPM_FastHonorPragmas);
2084   } else if (Opts.CUDA) {
2085     // Allow fuse across statements disregarding pragmas.
2086     Opts.setDefaultFPContractMode(LangOptions::FPM_Fast);
2087   }
2088 
2089   Opts.RenderScript = IK.getLanguage() == Language::RenderScript;
2090   if (Opts.RenderScript) {
2091     Opts.NativeHalfType = 1;
2092     Opts.NativeHalfArgsAndReturns = 1;
2093   }
2094 
2095   // OpenCL and C++ both have bool, true, false keywords.
2096   Opts.Bool = Opts.OpenCL || Opts.CPlusPlus;
2097 
2098   // OpenCL has half keyword
2099   Opts.Half = Opts.OpenCL;
2100 
2101   // C++ has wchar_t keyword.
2102   Opts.WChar = Opts.CPlusPlus;
2103 
2104   Opts.GNUKeywords = Opts.GNUMode;
2105   Opts.CXXOperatorNames = Opts.CPlusPlus;
2106 
2107   Opts.AlignedAllocation = Opts.CPlusPlus17;
2108 
2109   Opts.DollarIdents = !Opts.AsmPreprocessor;
2110 
2111   // Enable [[]] attributes in C++11 and C2x by default.
2112   Opts.DoubleSquareBracketAttributes = Opts.CPlusPlus11 || Opts.C2x;
2113 }
2114 
2115 /// Attempt to parse a visibility value out of the given argument.
2116 static Visibility parseVisibility(Arg *arg, ArgList &args,
2117                                   DiagnosticsEngine &diags) {
2118   StringRef value = arg->getValue();
2119   if (value == "default") {
2120     return DefaultVisibility;
2121   } else if (value == "hidden" || value == "internal") {
2122     return HiddenVisibility;
2123   } else if (value == "protected") {
2124     // FIXME: diagnose if target does not support protected visibility
2125     return ProtectedVisibility;
2126   }
2127 
2128   diags.Report(diag::err_drv_invalid_value)
2129     << arg->getAsString(args) << value;
2130   return DefaultVisibility;
2131 }
2132 
2133 /// Check if input file kind and language standard are compatible.
2134 static bool IsInputCompatibleWithStandard(InputKind IK,
2135                                           const LangStandard &S) {
2136   switch (IK.getLanguage()) {
2137   case Language::Unknown:
2138   case Language::LLVM_IR:
2139     llvm_unreachable("should not parse language flags for this input");
2140 
2141   case Language::C:
2142   case Language::ObjC:
2143   case Language::RenderScript:
2144     return S.getLanguage() == Language::C;
2145 
2146   case Language::OpenCL:
2147     return S.getLanguage() == Language::OpenCL;
2148 
2149   case Language::CXX:
2150   case Language::ObjCXX:
2151     return S.getLanguage() == Language::CXX;
2152 
2153   case Language::CUDA:
2154     // FIXME: What -std= values should be permitted for CUDA compilations?
2155     return S.getLanguage() == Language::CUDA ||
2156            S.getLanguage() == Language::CXX;
2157 
2158   case Language::HIP:
2159     return S.getLanguage() == Language::CXX || S.getLanguage() == Language::HIP;
2160 
2161   case Language::Asm:
2162     // Accept (and ignore) all -std= values.
2163     // FIXME: The -std= value is not ignored; it affects the tokenization
2164     // and preprocessing rules if we're preprocessing this asm input.
2165     return true;
2166   }
2167 
2168   llvm_unreachable("unexpected input language");
2169 }
2170 
2171 /// Get language name for given input kind.
2172 static const StringRef GetInputKindName(InputKind IK) {
2173   switch (IK.getLanguage()) {
2174   case Language::C:
2175     return "C";
2176   case Language::ObjC:
2177     return "Objective-C";
2178   case Language::CXX:
2179     return "C++";
2180   case Language::ObjCXX:
2181     return "Objective-C++";
2182   case Language::OpenCL:
2183     return "OpenCL";
2184   case Language::CUDA:
2185     return "CUDA";
2186   case Language::RenderScript:
2187     return "RenderScript";
2188   case Language::HIP:
2189     return "HIP";
2190 
2191   case Language::Asm:
2192     return "Asm";
2193   case Language::LLVM_IR:
2194     return "LLVM IR";
2195 
2196   case Language::Unknown:
2197     break;
2198   }
2199   llvm_unreachable("unknown input language");
2200 }
2201 
2202 static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK,
2203                           const TargetOptions &TargetOpts,
2204                           PreprocessorOptions &PPOpts,
2205                           DiagnosticsEngine &Diags) {
2206   // FIXME: Cleanup per-file based stuff.
2207   LangStandard::Kind LangStd = LangStandard::lang_unspecified;
2208   if (const Arg *A = Args.getLastArg(OPT_std_EQ)) {
2209     LangStd = LangStandard::getLangKind(A->getValue());
2210     if (LangStd == LangStandard::lang_unspecified) {
2211       Diags.Report(diag::err_drv_invalid_value)
2212         << A->getAsString(Args) << A->getValue();
2213       // Report supported standards with short description.
2214       for (unsigned KindValue = 0;
2215            KindValue != LangStandard::lang_unspecified;
2216            ++KindValue) {
2217         const LangStandard &Std = LangStandard::getLangStandardForKind(
2218           static_cast<LangStandard::Kind>(KindValue));
2219         if (IsInputCompatibleWithStandard(IK, Std)) {
2220           auto Diag = Diags.Report(diag::note_drv_use_standard);
2221           Diag << Std.getName() << Std.getDescription();
2222           unsigned NumAliases = 0;
2223 #define LANGSTANDARD(id, name, lang, desc, features)
2224 #define LANGSTANDARD_ALIAS(id, alias) \
2225           if (KindValue == LangStandard::lang_##id) ++NumAliases;
2226 #define LANGSTANDARD_ALIAS_DEPR(id, alias)
2227 #include "clang/Basic/LangStandards.def"
2228           Diag << NumAliases;
2229 #define LANGSTANDARD(id, name, lang, desc, features)
2230 #define LANGSTANDARD_ALIAS(id, alias) \
2231           if (KindValue == LangStandard::lang_##id) Diag << alias;
2232 #define LANGSTANDARD_ALIAS_DEPR(id, alias)
2233 #include "clang/Basic/LangStandards.def"
2234         }
2235       }
2236     } else {
2237       // Valid standard, check to make sure language and standard are
2238       // compatible.
2239       const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
2240       if (!IsInputCompatibleWithStandard(IK, Std)) {
2241         Diags.Report(diag::err_drv_argument_not_allowed_with)
2242           << A->getAsString(Args) << GetInputKindName(IK);
2243       }
2244     }
2245   }
2246 
2247   if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
2248     StringRef Name = A->getValue();
2249     if (Name == "full" || Name == "branch") {
2250       Opts.CFProtectionBranch = 1;
2251     }
2252   }
2253   // -cl-std only applies for OpenCL language standards.
2254   // Override the -std option in this case.
2255   if (const Arg *A = Args.getLastArg(OPT_cl_std_EQ)) {
2256     LangStandard::Kind OpenCLLangStd
2257       = llvm::StringSwitch<LangStandard::Kind>(A->getValue())
2258         .Cases("cl", "CL", LangStandard::lang_opencl10)
2259         .Cases("cl1.0", "CL1.0", LangStandard::lang_opencl10)
2260         .Cases("cl1.1", "CL1.1", LangStandard::lang_opencl11)
2261         .Cases("cl1.2", "CL1.2", LangStandard::lang_opencl12)
2262         .Cases("cl2.0", "CL2.0", LangStandard::lang_opencl20)
2263         .Cases("cl3.0", "CL3.0", LangStandard::lang_opencl30)
2264         .Cases("clc++", "CLC++", LangStandard::lang_openclcpp)
2265         .Default(LangStandard::lang_unspecified);
2266 
2267     if (OpenCLLangStd == LangStandard::lang_unspecified) {
2268       Diags.Report(diag::err_drv_invalid_value)
2269         << A->getAsString(Args) << A->getValue();
2270     }
2271     else
2272       LangStd = OpenCLLangStd;
2273   }
2274 
2275   Opts.SYCLIsDevice = Opts.SYCL && Args.hasArg(options::OPT_fsycl_is_device);
2276   if (Opts.SYCL) {
2277     // -sycl-std applies to any SYCL source, not only those containing kernels,
2278     // but also those using the SYCL API
2279     if (const Arg *A = Args.getLastArg(OPT_sycl_std_EQ)) {
2280       Opts.SYCLVersion = llvm::StringSwitch<unsigned>(A->getValue())
2281                              .Cases("2017", "1.2.1", "121", "sycl-1.2.1", 2017)
2282                              .Default(0U);
2283 
2284       if (Opts.SYCLVersion == 0U) {
2285         // User has passed an invalid value to the flag, this is an error
2286         Diags.Report(diag::err_drv_invalid_value)
2287             << A->getAsString(Args) << A->getValue();
2288       }
2289     }
2290   }
2291 
2292   llvm::Triple T(TargetOpts.Triple);
2293   CompilerInvocation::setLangDefaults(Opts, IK, T, PPOpts, LangStd);
2294 
2295   // -cl-strict-aliasing needs to emit diagnostic in the case where CL > 1.0.
2296   // This option should be deprecated for CL > 1.0 because
2297   // this option was added for compatibility with OpenCL 1.0.
2298   if (Args.getLastArg(OPT_cl_strict_aliasing)
2299        && Opts.OpenCLVersion > 100) {
2300     Diags.Report(diag::warn_option_invalid_ocl_version)
2301         << Opts.getOpenCLVersionTuple().getAsString()
2302         << Args.getLastArg(OPT_cl_strict_aliasing)->getAsString(Args);
2303   }
2304 
2305   // We abuse '-f[no-]gnu-keywords' to force overriding all GNU-extension
2306   // keywords. This behavior is provided by GCC's poorly named '-fasm' flag,
2307   // while a subset (the non-C++ GNU keywords) is provided by GCC's
2308   // '-fgnu-keywords'. Clang conflates the two for simplicity under the single
2309   // name, as it doesn't seem a useful distinction.
2310   Opts.GNUKeywords = Args.hasFlag(OPT_fgnu_keywords, OPT_fno_gnu_keywords,
2311                                   Opts.GNUKeywords);
2312 
2313   Opts.Digraphs = Args.hasFlag(OPT_fdigraphs, OPT_fno_digraphs, Opts.Digraphs);
2314 
2315   if (Args.hasArg(OPT_fno_operator_names))
2316     Opts.CXXOperatorNames = 0;
2317 
2318   if (Opts.CUDAIsDevice && Args.hasArg(OPT_fcuda_approx_transcendentals))
2319     Opts.CUDADeviceApproxTranscendentals = 1;
2320 
2321   if (Args.hasArg(OPT_fgpu_allow_device_init)) {
2322     if (Opts.HIP)
2323       Opts.GPUAllowDeviceInit = 1;
2324     else
2325       Diags.Report(diag::warn_ignored_hip_only_option)
2326           << Args.getLastArg(OPT_fgpu_allow_device_init)->getAsString(Args);
2327   }
2328   if (Opts.HIP)
2329     Opts.GPUMaxThreadsPerBlock = getLastArgIntValue(
2330         Args, OPT_gpu_max_threads_per_block_EQ, Opts.GPUMaxThreadsPerBlock);
2331   else if (Args.hasArg(OPT_gpu_max_threads_per_block_EQ))
2332     Diags.Report(diag::warn_ignored_hip_only_option)
2333         << Args.getLastArg(OPT_gpu_max_threads_per_block_EQ)->getAsString(Args);
2334 
2335   if (Opts.ObjC) {
2336     if (Arg *arg = Args.getLastArg(OPT_fobjc_runtime_EQ)) {
2337       StringRef value = arg->getValue();
2338       if (Opts.ObjCRuntime.tryParse(value))
2339         Diags.Report(diag::err_drv_unknown_objc_runtime) << value;
2340     }
2341 
2342     if (Args.hasArg(OPT_fobjc_gc_only))
2343       Opts.setGC(LangOptions::GCOnly);
2344     else if (Args.hasArg(OPT_fobjc_gc))
2345       Opts.setGC(LangOptions::HybridGC);
2346     else if (Args.hasArg(OPT_fobjc_arc)) {
2347       Opts.ObjCAutoRefCount = 1;
2348       if (!Opts.ObjCRuntime.allowsARC())
2349         Diags.Report(diag::err_arc_unsupported_on_runtime);
2350     }
2351 
2352     // ObjCWeakRuntime tracks whether the runtime supports __weak, not
2353     // whether the feature is actually enabled.  This is predominantly
2354     // determined by -fobjc-runtime, but we allow it to be overridden
2355     // from the command line for testing purposes.
2356     if (Args.hasArg(OPT_fobjc_runtime_has_weak))
2357       Opts.ObjCWeakRuntime = 1;
2358     else
2359       Opts.ObjCWeakRuntime = Opts.ObjCRuntime.allowsWeak();
2360 
2361     // ObjCWeak determines whether __weak is actually enabled.
2362     // Note that we allow -fno-objc-weak to disable this even in ARC mode.
2363     if (auto weakArg = Args.getLastArg(OPT_fobjc_weak, OPT_fno_objc_weak)) {
2364       if (!weakArg->getOption().matches(OPT_fobjc_weak)) {
2365         assert(!Opts.ObjCWeak);
2366       } else if (Opts.getGC() != LangOptions::NonGC) {
2367         Diags.Report(diag::err_objc_weak_with_gc);
2368       } else if (!Opts.ObjCWeakRuntime) {
2369         Diags.Report(diag::err_objc_weak_unsupported);
2370       } else {
2371         Opts.ObjCWeak = 1;
2372       }
2373     } else if (Opts.ObjCAutoRefCount) {
2374       Opts.ObjCWeak = Opts.ObjCWeakRuntime;
2375     }
2376 
2377     if (Args.hasArg(OPT_fobjc_subscripting_legacy_runtime))
2378       Opts.ObjCSubscriptingLegacyRuntime =
2379         (Opts.ObjCRuntime.getKind() == ObjCRuntime::FragileMacOSX);
2380   }
2381 
2382   if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) {
2383     // Check that the version has 1 to 3 components and the minor and patch
2384     // versions fit in two decimal digits.
2385     VersionTuple GNUCVer;
2386     bool Invalid = GNUCVer.tryParse(A->getValue());
2387     unsigned Major = GNUCVer.getMajor();
2388     unsigned Minor = GNUCVer.getMinor().getValueOr(0);
2389     unsigned Patch = GNUCVer.getSubminor().getValueOr(0);
2390     if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
2391       Diags.Report(diag::err_drv_invalid_value)
2392           << A->getAsString(Args) << A->getValue();
2393     }
2394     Opts.GNUCVersion = Major * 100 * 100 + Minor * 100 + Patch;
2395   }
2396 
2397   if (Args.hasArg(OPT_fgnu89_inline)) {
2398     if (Opts.CPlusPlus)
2399       Diags.Report(diag::err_drv_argument_not_allowed_with)
2400         << "-fgnu89-inline" << GetInputKindName(IK);
2401     else
2402       Opts.GNUInline = 1;
2403   }
2404 
2405   // The type-visibility mode defaults to the value-visibility mode.
2406   if (Arg *typeVisOpt = Args.getLastArg(OPT_ftype_visibility)) {
2407     Opts.setTypeVisibilityMode(parseVisibility(typeVisOpt, Args, Diags));
2408   } else {
2409     Opts.setTypeVisibilityMode(Opts.getValueVisibilityMode());
2410   }
2411 
2412   if (Args.hasArg(OPT_fvisibility_from_dllstorageclass)) {
2413     Opts.VisibilityFromDLLStorageClass = 1;
2414 
2415     // Translate dllexport defintions to default visibility, by default.
2416     if (Arg *O = Args.getLastArg(OPT_fvisibility_dllexport_EQ))
2417       Opts.setDLLExportVisibility(parseVisibility(O, Args, Diags));
2418     else
2419       Opts.setDLLExportVisibility(DefaultVisibility);
2420 
2421     // Translate defintions without an explict DLL storage class to hidden
2422     // visibility, by default.
2423     if (Arg *O = Args.getLastArg(OPT_fvisibility_nodllstorageclass_EQ))
2424       Opts.setNoDLLStorageClassVisibility(parseVisibility(O, Args, Diags));
2425     else
2426       Opts.setNoDLLStorageClassVisibility(HiddenVisibility);
2427 
2428     // Translate dllimport external declarations to default visibility, by
2429     // default.
2430     if (Arg *O = Args.getLastArg(OPT_fvisibility_externs_dllimport_EQ))
2431       Opts.setExternDeclDLLImportVisibility(parseVisibility(O, Args, Diags));
2432     else
2433       Opts.setExternDeclDLLImportVisibility(DefaultVisibility);
2434 
2435     // Translate external declarations without an explicit DLL storage class
2436     // to hidden visibility, by default.
2437     if (Arg *O = Args.getLastArg(OPT_fvisibility_externs_nodllstorageclass_EQ))
2438       Opts.setExternDeclNoDLLStorageClassVisibility(
2439           parseVisibility(O, Args, Diags));
2440     else
2441       Opts.setExternDeclNoDLLStorageClassVisibility(HiddenVisibility);
2442   }
2443 
2444   if (Args.hasArg(OPT_ftrapv)) {
2445     Opts.setSignedOverflowBehavior(LangOptions::SOB_Trapping);
2446     // Set the handler, if one is specified.
2447     Opts.OverflowHandler =
2448         std::string(Args.getLastArgValue(OPT_ftrapv_handler));
2449   }
2450   else if (Args.hasArg(OPT_fwrapv))
2451     Opts.setSignedOverflowBehavior(LangOptions::SOB_Defined);
2452 
2453   Opts.MicrosoftExt = Opts.MSVCCompat || Args.hasArg(OPT_fms_extensions);
2454   Opts.AsmBlocks = Args.hasArg(OPT_fasm_blocks) || Opts.MicrosoftExt;
2455   Opts.MSCompatibilityVersion = 0;
2456   if (const Arg *A = Args.getLastArg(OPT_fms_compatibility_version)) {
2457     VersionTuple VT;
2458     if (VT.tryParse(A->getValue()))
2459       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
2460                                                 << A->getValue();
2461     Opts.MSCompatibilityVersion = VT.getMajor() * 10000000 +
2462                                   VT.getMinor().getValueOr(0) * 100000 +
2463                                   VT.getSubminor().getValueOr(0);
2464   }
2465 
2466   // Mimicking gcc's behavior, trigraphs are only enabled if -trigraphs
2467   // is specified, or -std is set to a conforming mode.
2468   // Trigraphs are disabled by default in c++1z onwards.
2469   // For z/OS, trigraphs are enabled by default (without regard to the above).
2470   Opts.Trigraphs =
2471       (!Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus17) || T.isOSzOS();
2472   Opts.Trigraphs =
2473       Args.hasFlag(OPT_ftrigraphs, OPT_fno_trigraphs, Opts.Trigraphs);
2474 
2475   Opts.DollarIdents = Args.hasFlag(OPT_fdollars_in_identifiers,
2476                                    OPT_fno_dollars_in_identifiers,
2477                                    Opts.DollarIdents);
2478 
2479   // -ffixed-point
2480   Opts.FixedPoint =
2481       Args.hasFlag(OPT_ffixed_point, OPT_fno_fixed_point, /*Default=*/false) &&
2482       !Opts.CPlusPlus;
2483   Opts.PaddingOnUnsignedFixedPoint =
2484       Args.hasFlag(OPT_fpadding_on_unsigned_fixed_point,
2485                    OPT_fno_padding_on_unsigned_fixed_point,
2486                    /*Default=*/false) &&
2487       Opts.FixedPoint;
2488 
2489   Opts.RTTI = Opts.CPlusPlus && !Args.hasArg(OPT_fno_rtti);
2490   Opts.RTTIData = Opts.RTTI && !Args.hasArg(OPT_fno_rtti_data);
2491   Opts.Blocks = Args.hasArg(OPT_fblocks) || (Opts.OpenCL
2492     && Opts.OpenCLVersion == 200);
2493   Opts.Coroutines = Opts.CPlusPlus20 || Args.hasArg(OPT_fcoroutines_ts);
2494 
2495   Opts.ConvergentFunctions = Opts.OpenCL || (Opts.CUDA && Opts.CUDAIsDevice) ||
2496                              Opts.SYCLIsDevice ||
2497                              Args.hasArg(OPT_fconvergent_functions);
2498 
2499   Opts.DoubleSquareBracketAttributes =
2500       Args.hasFlag(OPT_fdouble_square_bracket_attributes,
2501                    OPT_fno_double_square_bracket_attributes,
2502                    Opts.DoubleSquareBracketAttributes);
2503 
2504   Opts.CPlusPlusModules = Opts.CPlusPlus20;
2505   Opts.Modules =
2506       Args.hasArg(OPT_fmodules) || Opts.ModulesTS || Opts.CPlusPlusModules;
2507   Opts.ModulesDeclUse =
2508       Args.hasArg(OPT_fmodules_decluse) || Opts.ModulesStrictDeclUse;
2509   // FIXME: We only need this in C++ modules / Modules TS if we might textually
2510   // enter a different module (eg, when building a header unit).
2511   Opts.ModulesLocalVisibility =
2512       Args.hasArg(OPT_fmodules_local_submodule_visibility) || Opts.ModulesTS ||
2513       Opts.CPlusPlusModules;
2514   Opts.ModulesSearchAll = Opts.Modules &&
2515     !Args.hasArg(OPT_fno_modules_search_all) &&
2516     Args.hasArg(OPT_fmodules_search_all);
2517   Opts.CharIsSigned = Opts.OpenCL || !Args.hasArg(OPT_fno_signed_char);
2518   Opts.WChar = Opts.CPlusPlus && !Args.hasArg(OPT_fno_wchar);
2519   Opts.Char8 = Args.hasFlag(OPT_fchar8__t, OPT_fno_char8__t, Opts.CPlusPlus20);
2520   Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding;
2521   if (!Opts.NoBuiltin)
2522     getAllNoBuiltinFuncValues(Args, Opts.NoBuiltinFuncs);
2523   Opts.AlignedAllocation =
2524       Args.hasFlag(OPT_faligned_allocation, OPT_fno_aligned_allocation,
2525                    Opts.AlignedAllocation);
2526   Opts.AlignedAllocationUnavailable =
2527       Opts.AlignedAllocation && Args.hasArg(OPT_aligned_alloc_unavailable);
2528   if (Args.hasArg(OPT_fconcepts_ts))
2529     Diags.Report(diag::warn_fe_concepts_ts_flag);
2530   Opts.MathErrno = !Opts.OpenCL && Args.hasArg(OPT_fmath_errno);
2531   Opts.LongDoubleSize = Args.hasArg(OPT_mlong_double_128)
2532                             ? 128
2533                             : Args.hasArg(OPT_mlong_double_64) ? 64 : 0;
2534   Opts.EnableAIXExtendedAltivecABI = Args.hasArg(OPT_mabi_EQ_vec_extabi);
2535   Opts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
2536   Opts.DumpRecordLayouts = Opts.DumpRecordLayoutsSimple
2537                         || Args.hasArg(OPT_fdump_record_layouts);
2538   if (Opts.FastRelaxedMath)
2539     Opts.setDefaultFPContractMode(LangOptions::FPM_Fast);
2540   Opts.ModuleFeatures = Args.getAllArgValues(OPT_fmodule_feature);
2541   llvm::sort(Opts.ModuleFeatures);
2542   Opts.NativeHalfType |= Args.hasArg(OPT_fnative_half_type);
2543   Opts.NativeHalfArgsAndReturns |= Args.hasArg(OPT_fnative_half_arguments_and_returns);
2544   // Enable HalfArgsAndReturns if present in Args or if NativeHalfArgsAndReturns
2545   // is enabled.
2546   Opts.HalfArgsAndReturns = Args.hasArg(OPT_fallow_half_arguments_and_returns)
2547                             | Opts.NativeHalfArgsAndReturns;
2548 
2549   Opts.ArmSveVectorBits =
2550       getLastArgIntValue(Args, options::OPT_msve_vector_bits_EQ, 0, Diags);
2551 
2552   // __declspec is enabled by default for the PS4 by the driver, and also
2553   // enabled for Microsoft Extensions or Borland Extensions, here.
2554   //
2555   // FIXME: __declspec is also currently enabled for CUDA, but isn't really a
2556   // CUDA extension. However, it is required for supporting
2557   // __clang_cuda_builtin_vars.h, which uses __declspec(property). Once that has
2558   // been rewritten in terms of something more generic, remove the Opts.CUDA
2559   // term here.
2560   Opts.DeclSpecKeyword =
2561       Args.hasFlag(OPT_fdeclspec, OPT_fno_declspec,
2562                    (Opts.MicrosoftExt || Opts.Borland || Opts.CUDA));
2563 
2564   // -mrtd option
2565   if (Arg *A = Args.getLastArg(OPT_mrtd)) {
2566     if (Opts.getDefaultCallingConv() != LangOptions::DCC_None)
2567       Diags.Report(diag::err_drv_argument_not_allowed_with)
2568           << A->getSpelling() << "-fdefault-calling-conv";
2569     else {
2570       llvm::Triple T(TargetOpts.Triple);
2571       if (T.getArch() != llvm::Triple::x86)
2572         Diags.Report(diag::err_drv_argument_not_allowed_with)
2573             << A->getSpelling() << T.getTriple();
2574       else
2575         Opts.setDefaultCallingConv(LangOptions::DCC_StdCall);
2576     }
2577   }
2578 
2579   // Check if -fopenmp-simd is specified.
2580   bool IsSimdSpecified =
2581       Args.hasFlag(options::OPT_fopenmp_simd, options::OPT_fno_openmp_simd,
2582                    /*Default=*/false);
2583   Opts.OpenMPSimd = !Opts.OpenMP && IsSimdSpecified;
2584   Opts.OpenMPUseTLS =
2585       Opts.OpenMP && !Args.hasArg(options::OPT_fnoopenmp_use_tls);
2586   Opts.OpenMPIsDevice =
2587       Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_is_device);
2588   Opts.OpenMPIRBuilder =
2589       Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_enable_irbuilder);
2590   bool IsTargetSpecified =
2591       Opts.OpenMPIsDevice || Args.hasArg(options::OPT_fopenmp_targets_EQ);
2592 
2593   if (Opts.OpenMP || Opts.OpenMPSimd) {
2594     if (int Version = getLastArgIntValue(
2595             Args, OPT_fopenmp_version_EQ,
2596             (IsSimdSpecified || IsTargetSpecified) ? 50 : Opts.OpenMP, Diags))
2597       Opts.OpenMP = Version;
2598     // Provide diagnostic when a given target is not expected to be an OpenMP
2599     // device or host.
2600     if (!Opts.OpenMPIsDevice) {
2601       switch (T.getArch()) {
2602       default:
2603         break;
2604       // Add unsupported host targets here:
2605       case llvm::Triple::nvptx:
2606       case llvm::Triple::nvptx64:
2607         Diags.Report(diag::err_drv_omp_host_target_not_supported)
2608             << TargetOpts.Triple;
2609         break;
2610       }
2611     }
2612   }
2613 
2614   // Set the flag to prevent the implementation from emitting device exception
2615   // handling code for those requiring so.
2616   if ((Opts.OpenMPIsDevice && (T.isNVPTX() || T.isAMDGCN())) ||
2617       Opts.OpenCLCPlusPlus) {
2618     Opts.Exceptions = 0;
2619     Opts.CXXExceptions = 0;
2620   }
2621   if (Opts.OpenMPIsDevice && T.isNVPTX()) {
2622     Opts.OpenMPCUDANumSMs =
2623         getLastArgIntValue(Args, options::OPT_fopenmp_cuda_number_of_sm_EQ,
2624                            Opts.OpenMPCUDANumSMs, Diags);
2625     Opts.OpenMPCUDABlocksPerSM =
2626         getLastArgIntValue(Args, options::OPT_fopenmp_cuda_blocks_per_sm_EQ,
2627                            Opts.OpenMPCUDABlocksPerSM, Diags);
2628     Opts.OpenMPCUDAReductionBufNum = getLastArgIntValue(
2629         Args, options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ,
2630         Opts.OpenMPCUDAReductionBufNum, Diags);
2631   }
2632 
2633   // Get the OpenMP target triples if any.
2634   if (Arg *A = Args.getLastArg(options::OPT_fopenmp_targets_EQ)) {
2635     enum ArchPtrSize { Arch16Bit, Arch32Bit, Arch64Bit };
2636     auto getArchPtrSize = [](const llvm::Triple &T) {
2637       if (T.isArch16Bit())
2638         return Arch16Bit;
2639       if (T.isArch32Bit())
2640         return Arch32Bit;
2641       assert(T.isArch64Bit() && "Expected 64-bit architecture");
2642       return Arch64Bit;
2643     };
2644 
2645     for (unsigned i = 0; i < A->getNumValues(); ++i) {
2646       llvm::Triple TT(A->getValue(i));
2647 
2648       if (TT.getArch() == llvm::Triple::UnknownArch ||
2649           !(TT.getArch() == llvm::Triple::aarch64 ||
2650             TT.getArch() == llvm::Triple::ppc ||
2651             TT.getArch() == llvm::Triple::ppc64 ||
2652             TT.getArch() == llvm::Triple::ppc64le ||
2653             TT.getArch() == llvm::Triple::nvptx ||
2654             TT.getArch() == llvm::Triple::nvptx64 ||
2655             TT.getArch() == llvm::Triple::amdgcn ||
2656             TT.getArch() == llvm::Triple::x86 ||
2657             TT.getArch() == llvm::Triple::x86_64))
2658         Diags.Report(diag::err_drv_invalid_omp_target) << A->getValue(i);
2659       else if (getArchPtrSize(T) != getArchPtrSize(TT))
2660         Diags.Report(diag::err_drv_incompatible_omp_arch)
2661             << A->getValue(i) << T.str();
2662       else
2663         Opts.OMPTargetTriples.push_back(TT);
2664     }
2665   }
2666 
2667   // Get OpenMP host file path if any and report if a non existent file is
2668   // found
2669   if (Arg *A = Args.getLastArg(options::OPT_fopenmp_host_ir_file_path)) {
2670     Opts.OMPHostIRFile = A->getValue();
2671     if (!llvm::sys::fs::exists(Opts.OMPHostIRFile))
2672       Diags.Report(diag::err_drv_omp_host_ir_file_not_found)
2673           << Opts.OMPHostIRFile;
2674   }
2675 
2676   // Set CUDA mode for OpenMP target NVPTX/AMDGCN if specified in options
2677   Opts.OpenMPCUDAMode = Opts.OpenMPIsDevice && (T.isNVPTX() || T.isAMDGCN()) &&
2678                         Args.hasArg(options::OPT_fopenmp_cuda_mode);
2679 
2680   // Set CUDA support for parallel execution of target regions for OpenMP target
2681   // NVPTX/AMDGCN if specified in options.
2682   Opts.OpenMPCUDATargetParallel =
2683       Opts.OpenMPIsDevice && (T.isNVPTX() || T.isAMDGCN()) &&
2684       Args.hasArg(options::OPT_fopenmp_cuda_parallel_target_regions);
2685 
2686   // Set CUDA mode for OpenMP target NVPTX/AMDGCN if specified in options
2687   Opts.OpenMPCUDAForceFullRuntime =
2688       Opts.OpenMPIsDevice && (T.isNVPTX() || T.isAMDGCN()) &&
2689       Args.hasArg(options::OPT_fopenmp_cuda_force_full_runtime);
2690 
2691   // Record whether the __DEPRECATED define was requested.
2692   Opts.Deprecated = Args.hasFlag(OPT_fdeprecated_macro,
2693                                  OPT_fno_deprecated_macro,
2694                                  Opts.Deprecated);
2695 
2696   // FIXME: Eliminate this dependency.
2697   unsigned Opt = getOptimizationLevel(Args, IK, Diags),
2698        OptSize = getOptimizationLevelSize(Args);
2699   Opts.Optimize = Opt != 0;
2700   Opts.OptimizeSize = OptSize != 0;
2701 
2702   // This is the __NO_INLINE__ define, which just depends on things like the
2703   // optimization level and -fno-inline, not actually whether the backend has
2704   // inlining enabled.
2705   Opts.NoInlineDefine = !Opts.Optimize;
2706   if (Arg *InlineArg = Args.getLastArg(
2707           options::OPT_finline_functions, options::OPT_finline_hint_functions,
2708           options::OPT_fno_inline_functions, options::OPT_fno_inline))
2709     if (InlineArg->getOption().matches(options::OPT_fno_inline))
2710       Opts.NoInlineDefine = true;
2711 
2712   if (Arg *A = Args.getLastArg(OPT_ffp_contract)) {
2713     StringRef Val = A->getValue();
2714     if (Val == "fast")
2715       Opts.setDefaultFPContractMode(LangOptions::FPM_Fast);
2716     else if (Val == "on")
2717       Opts.setDefaultFPContractMode(LangOptions::FPM_On);
2718     else if (Val == "off")
2719       Opts.setDefaultFPContractMode(LangOptions::FPM_Off);
2720     else if (Val == "fast-honor-pragmas")
2721       Opts.setDefaultFPContractMode(LangOptions::FPM_FastHonorPragmas);
2722     else
2723       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
2724   }
2725 
2726   if (Args.hasArg(OPT_ftrapping_math)) {
2727     Opts.setFPExceptionMode(LangOptions::FPE_Strict);
2728   }
2729 
2730   if (Args.hasArg(OPT_fno_trapping_math)) {
2731     Opts.setFPExceptionMode(LangOptions::FPE_Ignore);
2732   }
2733 
2734   LangOptions::FPExceptionModeKind FPEB = LangOptions::FPE_Ignore;
2735   if (Arg *A = Args.getLastArg(OPT_ffp_exception_behavior_EQ)) {
2736     StringRef Val = A->getValue();
2737     if (Val.equals("ignore"))
2738       FPEB = LangOptions::FPE_Ignore;
2739     else if (Val.equals("maytrap"))
2740       FPEB = LangOptions::FPE_MayTrap;
2741     else if (Val.equals("strict"))
2742       FPEB = LangOptions::FPE_Strict;
2743     else
2744       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
2745   }
2746   Opts.setFPExceptionMode(FPEB);
2747 
2748   // Parse -fsanitize= arguments.
2749   parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
2750                       Diags, Opts.Sanitize);
2751   Opts.SanitizerBlacklistFiles = Args.getAllArgValues(OPT_fsanitize_blacklist);
2752   std::vector<std::string> systemBlacklists =
2753       Args.getAllArgValues(OPT_fsanitize_system_blacklist);
2754   Opts.SanitizerBlacklistFiles.insert(Opts.SanitizerBlacklistFiles.end(),
2755                                       systemBlacklists.begin(),
2756                                       systemBlacklists.end());
2757 
2758   // -fxray-{always,never}-instrument= filenames.
2759   Opts.XRayAlwaysInstrumentFiles =
2760       Args.getAllArgValues(OPT_fxray_always_instrument);
2761   Opts.XRayNeverInstrumentFiles =
2762       Args.getAllArgValues(OPT_fxray_never_instrument);
2763   Opts.XRayAttrListFiles = Args.getAllArgValues(OPT_fxray_attr_list);
2764 
2765   if (Arg *A = Args.getLastArg(OPT_fclang_abi_compat_EQ)) {
2766     Opts.setClangABICompat(LangOptions::ClangABI::Latest);
2767 
2768     StringRef Ver = A->getValue();
2769     std::pair<StringRef, StringRef> VerParts = Ver.split('.');
2770     unsigned Major, Minor = 0;
2771 
2772     // Check the version number is valid: either 3.x (0 <= x <= 9) or
2773     // y or y.0 (4 <= y <= current version).
2774     if (!VerParts.first.startswith("0") &&
2775         !VerParts.first.getAsInteger(10, Major) &&
2776         3 <= Major && Major <= CLANG_VERSION_MAJOR &&
2777         (Major == 3 ? VerParts.second.size() == 1 &&
2778                       !VerParts.second.getAsInteger(10, Minor)
2779                     : VerParts.first.size() == Ver.size() ||
2780                       VerParts.second == "0")) {
2781       // Got a valid version number.
2782       if (Major == 3 && Minor <= 8)
2783         Opts.setClangABICompat(LangOptions::ClangABI::Ver3_8);
2784       else if (Major <= 4)
2785         Opts.setClangABICompat(LangOptions::ClangABI::Ver4);
2786       else if (Major <= 6)
2787         Opts.setClangABICompat(LangOptions::ClangABI::Ver6);
2788       else if (Major <= 7)
2789         Opts.setClangABICompat(LangOptions::ClangABI::Ver7);
2790       else if (Major <= 9)
2791         Opts.setClangABICompat(LangOptions::ClangABI::Ver9);
2792       else if (Major <= 11)
2793         Opts.setClangABICompat(LangOptions::ClangABI::Ver11);
2794     } else if (Ver != "latest") {
2795       Diags.Report(diag::err_drv_invalid_value)
2796           << A->getAsString(Args) << A->getValue();
2797     }
2798   }
2799 
2800   if (Arg *A = Args.getLastArg(OPT_msign_return_address_EQ)) {
2801     StringRef SignScope = A->getValue();
2802 
2803     if (SignScope.equals_lower("none"))
2804       Opts.setSignReturnAddressScope(
2805           LangOptions::SignReturnAddressScopeKind::None);
2806     else if (SignScope.equals_lower("all"))
2807       Opts.setSignReturnAddressScope(
2808           LangOptions::SignReturnAddressScopeKind::All);
2809     else if (SignScope.equals_lower("non-leaf"))
2810       Opts.setSignReturnAddressScope(
2811           LangOptions::SignReturnAddressScopeKind::NonLeaf);
2812     else
2813       Diags.Report(diag::err_drv_invalid_value)
2814           << A->getAsString(Args) << SignScope;
2815 
2816     if (Arg *A = Args.getLastArg(OPT_msign_return_address_key_EQ)) {
2817       StringRef SignKey = A->getValue();
2818       if (!SignScope.empty() && !SignKey.empty()) {
2819         if (SignKey.equals_lower("a_key"))
2820           Opts.setSignReturnAddressKey(
2821               LangOptions::SignReturnAddressKeyKind::AKey);
2822         else if (SignKey.equals_lower("b_key"))
2823           Opts.setSignReturnAddressKey(
2824               LangOptions::SignReturnAddressKeyKind::BKey);
2825         else
2826           Diags.Report(diag::err_drv_invalid_value)
2827               << A->getAsString(Args) << SignKey;
2828       }
2829     }
2830   }
2831 
2832   std::string ThreadModel =
2833       std::string(Args.getLastArgValue(OPT_mthread_model, "posix"));
2834   if (ThreadModel != "posix" && ThreadModel != "single")
2835     Diags.Report(diag::err_drv_invalid_value)
2836         << Args.getLastArg(OPT_mthread_model)->getAsString(Args) << ThreadModel;
2837   Opts.setThreadModel(
2838       llvm::StringSwitch<LangOptions::ThreadModelKind>(ThreadModel)
2839           .Case("posix", LangOptions::ThreadModelKind::POSIX)
2840           .Case("single", LangOptions::ThreadModelKind::Single));
2841 }
2842 
2843 static bool isStrictlyPreprocessorAction(frontend::ActionKind Action) {
2844   switch (Action) {
2845   case frontend::ASTDeclList:
2846   case frontend::ASTDump:
2847   case frontend::ASTPrint:
2848   case frontend::ASTView:
2849   case frontend::EmitAssembly:
2850   case frontend::EmitBC:
2851   case frontend::EmitHTML:
2852   case frontend::EmitLLVM:
2853   case frontend::EmitLLVMOnly:
2854   case frontend::EmitCodeGenOnly:
2855   case frontend::EmitObj:
2856   case frontend::FixIt:
2857   case frontend::GenerateModule:
2858   case frontend::GenerateModuleInterface:
2859   case frontend::GenerateHeaderModule:
2860   case frontend::GeneratePCH:
2861   case frontend::GenerateInterfaceStubs:
2862   case frontend::ParseSyntaxOnly:
2863   case frontend::ModuleFileInfo:
2864   case frontend::VerifyPCH:
2865   case frontend::PluginAction:
2866   case frontend::RewriteObjC:
2867   case frontend::RewriteTest:
2868   case frontend::RunAnalysis:
2869   case frontend::TemplightDump:
2870   case frontend::MigrateSource:
2871     return false;
2872 
2873   case frontend::DumpCompilerOptions:
2874   case frontend::DumpRawTokens:
2875   case frontend::DumpTokens:
2876   case frontend::InitOnly:
2877   case frontend::PrintPreamble:
2878   case frontend::PrintPreprocessedInput:
2879   case frontend::RewriteMacros:
2880   case frontend::RunPreprocessorOnly:
2881   case frontend::PrintDependencyDirectivesSourceMinimizerOutput:
2882     return true;
2883   }
2884   llvm_unreachable("invalid frontend action");
2885 }
2886 
2887 static void ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args,
2888                                   DiagnosticsEngine &Diags,
2889                                   frontend::ActionKind Action) {
2890   Opts.PCHWithHdrStop = Args.hasArg(OPT_pch_through_hdrstop_create) ||
2891                         Args.hasArg(OPT_pch_through_hdrstop_use);
2892   Opts.AllowPCHWithCompilerErrors =
2893       Args.hasArg(OPT_fallow_pch_with_errors, OPT_fallow_pcm_with_errors);
2894 
2895   for (const auto *A : Args.filtered(OPT_error_on_deserialized_pch_decl))
2896     Opts.DeserializedPCHDeclsToErrorOn.insert(A->getValue());
2897 
2898   for (const auto &A : Args.getAllArgValues(OPT_fmacro_prefix_map_EQ)) {
2899     auto Split = StringRef(A).split('=');
2900     Opts.MacroPrefixMap.insert(
2901         {std::string(Split.first), std::string(Split.second)});
2902   }
2903 
2904   if (const Arg *A = Args.getLastArg(OPT_preamble_bytes_EQ)) {
2905     StringRef Value(A->getValue());
2906     size_t Comma = Value.find(',');
2907     unsigned Bytes = 0;
2908     unsigned EndOfLine = 0;
2909 
2910     if (Comma == StringRef::npos ||
2911         Value.substr(0, Comma).getAsInteger(10, Bytes) ||
2912         Value.substr(Comma + 1).getAsInteger(10, EndOfLine))
2913       Diags.Report(diag::err_drv_preamble_format);
2914     else {
2915       Opts.PrecompiledPreambleBytes.first = Bytes;
2916       Opts.PrecompiledPreambleBytes.second = (EndOfLine != 0);
2917     }
2918   }
2919 
2920   // Add the __CET__ macro if a CFProtection option is set.
2921   if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
2922     StringRef Name = A->getValue();
2923     if (Name == "branch")
2924       Opts.addMacroDef("__CET__=1");
2925     else if (Name == "return")
2926       Opts.addMacroDef("__CET__=2");
2927     else if (Name == "full")
2928       Opts.addMacroDef("__CET__=3");
2929   }
2930 
2931   // Add macros from the command line.
2932   for (const auto *A : Args.filtered(OPT_D, OPT_U)) {
2933     if (A->getOption().matches(OPT_D))
2934       Opts.addMacroDef(A->getValue());
2935     else
2936       Opts.addMacroUndef(A->getValue());
2937   }
2938 
2939   Opts.MacroIncludes = Args.getAllArgValues(OPT_imacros);
2940 
2941   // Add the ordered list of -includes.
2942   for (const auto *A : Args.filtered(OPT_include))
2943     Opts.Includes.emplace_back(A->getValue());
2944 
2945   for (const auto *A : Args.filtered(OPT_chain_include))
2946     Opts.ChainedIncludes.emplace_back(A->getValue());
2947 
2948   for (const auto *A : Args.filtered(OPT_remap_file)) {
2949     std::pair<StringRef, StringRef> Split = StringRef(A->getValue()).split(';');
2950 
2951     if (Split.second.empty()) {
2952       Diags.Report(diag::err_drv_invalid_remap_file) << A->getAsString(Args);
2953       continue;
2954     }
2955 
2956     Opts.addRemappedFile(Split.first, Split.second);
2957   }
2958 
2959   // Always avoid lexing editor placeholders when we're just running the
2960   // preprocessor as we never want to emit the
2961   // "editor placeholder in source file" error in PP only mode.
2962   if (isStrictlyPreprocessorAction(Action))
2963     Opts.LexEditorPlaceholders = false;
2964 }
2965 
2966 static void ParsePreprocessorOutputArgs(PreprocessorOutputOptions &Opts,
2967                                         ArgList &Args,
2968                                         frontend::ActionKind Action) {
2969   if (isStrictlyPreprocessorAction(Action))
2970     Opts.ShowCPP = !Args.hasArg(OPT_dM);
2971   else
2972     Opts.ShowCPP = 0;
2973 
2974   Opts.ShowMacros = Args.hasArg(OPT_dM) || Args.hasArg(OPT_dD);
2975 }
2976 
2977 static void ParseTargetArgs(TargetOptions &Opts, ArgList &Args,
2978                             DiagnosticsEngine &Diags) {
2979   Opts.FeaturesAsWritten = Args.getAllArgValues(OPT_target_feature);
2980   Opts.OpenCLExtensionsAsWritten = Args.getAllArgValues(OPT_cl_ext_EQ);
2981   Opts.AllowAMDGPUUnsafeFPAtomics =
2982       Args.hasFlag(options::OPT_munsafe_fp_atomics,
2983                    options::OPT_mno_unsafe_fp_atomics, false);
2984   if (Arg *A = Args.getLastArg(options::OPT_target_sdk_version_EQ)) {
2985     llvm::VersionTuple Version;
2986     if (Version.tryParse(A->getValue()))
2987       Diags.Report(diag::err_drv_invalid_value)
2988           << A->getAsString(Args) << A->getValue();
2989     else
2990       Opts.SDKVersion = Version;
2991   }
2992 }
2993 
2994 bool CompilerInvocation::parseSimpleArgs(const ArgList &Args,
2995                                          DiagnosticsEngine &Diags) {
2996 #define OPTION_WITH_MARSHALLING(                                               \
2997     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
2998     HELPTEXT, METAVAR, VALUES, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,  \
2999     IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, MERGER, EXTRACTOR, \
3000     TABLE_INDEX)                                                               \
3001   if ((FLAGS)&options::CC1Option) {                                            \
3002     this->KEYPATH = MERGER(this->KEYPATH, DEFAULT_VALUE);                      \
3003     if (IMPLIED_CHECK)                                                         \
3004       this->KEYPATH = MERGER(this->KEYPATH, IMPLIED_VALUE);                    \
3005     if (auto MaybeValue = NORMALIZER(OPT_##ID, TABLE_INDEX, Args, Diags))      \
3006       this->KEYPATH = MERGER(                                                  \
3007           this->KEYPATH, static_cast<decltype(this->KEYPATH)>(*MaybeValue));   \
3008   }
3009 
3010 #include "clang/Driver/Options.inc"
3011 #undef OPTION_WITH_MARSHALLING
3012   return true;
3013 }
3014 
3015 bool CompilerInvocation::CreateFromArgs(CompilerInvocation &Res,
3016                                         ArrayRef<const char *> CommandLineArgs,
3017                                         DiagnosticsEngine &Diags,
3018                                         const char *Argv0) {
3019   bool Success = true;
3020 
3021   // Parse the arguments.
3022   const OptTable &Opts = getDriverOptTable();
3023   const unsigned IncludedFlagsBitmask = options::CC1Option;
3024   unsigned MissingArgIndex, MissingArgCount;
3025   InputArgList Args = Opts.ParseArgs(CommandLineArgs, MissingArgIndex,
3026                                      MissingArgCount, IncludedFlagsBitmask);
3027   LangOptions &LangOpts = *Res.getLangOpts();
3028 
3029   // Check for missing argument error.
3030   if (MissingArgCount) {
3031     Diags.Report(diag::err_drv_missing_argument)
3032         << Args.getArgString(MissingArgIndex) << MissingArgCount;
3033     Success = false;
3034   }
3035 
3036   // Issue errors on unknown arguments.
3037   for (const auto *A : Args.filtered(OPT_UNKNOWN)) {
3038     auto ArgString = A->getAsString(Args);
3039     std::string Nearest;
3040     if (Opts.findNearest(ArgString, Nearest, IncludedFlagsBitmask) > 1)
3041       Diags.Report(diag::err_drv_unknown_argument) << ArgString;
3042     else
3043       Diags.Report(diag::err_drv_unknown_argument_with_suggestion)
3044           << ArgString << Nearest;
3045     Success = false;
3046   }
3047 
3048   Success &= Res.parseSimpleArgs(Args, Diags);
3049 
3050   Success &= ParseAnalyzerArgs(*Res.getAnalyzerOpts(), Args, Diags);
3051   ParseDependencyOutputArgs(Res.getDependencyOutputOpts(), Args);
3052   if (!Res.getDependencyOutputOpts().OutputFile.empty() &&
3053       Res.getDependencyOutputOpts().Targets.empty()) {
3054     Diags.Report(diag::err_fe_dependency_file_requires_MT);
3055     Success = false;
3056   }
3057   Success &= ParseDiagnosticArgs(Res.getDiagnosticOpts(), Args, &Diags,
3058                                  /*DefaultDiagColor=*/false);
3059   ParseCommentArgs(LangOpts.CommentOpts, Args);
3060   // FIXME: We shouldn't have to pass the DashX option around here
3061   InputKind DashX = ParseFrontendArgs(Res.getFrontendOpts(), Args, Diags,
3062                                       LangOpts.IsHeaderFile);
3063   ParseTargetArgs(Res.getTargetOpts(), Args, Diags);
3064   Success &= ParseCodeGenArgs(Res.getCodeGenOpts(), Args, DashX, Diags,
3065                               Res.getTargetOpts(), Res.getFrontendOpts());
3066   ParseHeaderSearchArgs(Res.getHeaderSearchOpts(), Args,
3067                         Res.getFileSystemOpts().WorkingDir);
3068   llvm::Triple T(Res.getTargetOpts().Triple);
3069   if (DashX.getFormat() == InputKind::Precompiled ||
3070       DashX.getLanguage() == Language::LLVM_IR) {
3071     // ObjCAAutoRefCount and Sanitize LangOpts are used to setup the
3072     // PassManager in BackendUtil.cpp. They need to be initializd no matter
3073     // what the input type is.
3074     if (Args.hasArg(OPT_fobjc_arc))
3075       LangOpts.ObjCAutoRefCount = 1;
3076     // PIClevel and PIELevel are needed during code generation and this should be
3077     // set regardless of the input type.
3078     LangOpts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
3079     parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
3080                         Diags, LangOpts.Sanitize);
3081   } else {
3082     // Other LangOpts are only initialized when the input is not AST or LLVM IR.
3083     // FIXME: Should we really be calling this for an Language::Asm input?
3084     ParseLangArgs(LangOpts, Args, DashX, Res.getTargetOpts(),
3085                   Res.getPreprocessorOpts(), Diags);
3086     if (Res.getFrontendOpts().ProgramAction == frontend::RewriteObjC)
3087       LangOpts.ObjCExceptions = 1;
3088     if (T.isOSDarwin() && DashX.isPreprocessed()) {
3089       // Supress the darwin-specific 'stdlibcxx-not-found' diagnostic for
3090       // preprocessed input as we don't expect it to be used with -std=libc++
3091       // anyway.
3092       Res.getDiagnosticOpts().Warnings.push_back("no-stdlibcxx-not-found");
3093     }
3094   }
3095 
3096   if (LangOpts.CUDA) {
3097     // During CUDA device-side compilation, the aux triple is the
3098     // triple used for host compilation.
3099     if (LangOpts.CUDAIsDevice)
3100       Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple;
3101   }
3102 
3103   // Set the triple of the host for OpenMP device compile.
3104   if (LangOpts.OpenMPIsDevice)
3105     Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple;
3106 
3107   // FIXME: Override value name discarding when asan or msan is used because the
3108   // backend passes depend on the name of the alloca in order to print out
3109   // names.
3110   Res.getCodeGenOpts().DiscardValueNames &=
3111       !LangOpts.Sanitize.has(SanitizerKind::Address) &&
3112       !LangOpts.Sanitize.has(SanitizerKind::KernelAddress) &&
3113       !LangOpts.Sanitize.has(SanitizerKind::Memory) &&
3114       !LangOpts.Sanitize.has(SanitizerKind::KernelMemory);
3115 
3116   ParsePreprocessorArgs(Res.getPreprocessorOpts(), Args, Diags,
3117                         Res.getFrontendOpts().ProgramAction);
3118   ParsePreprocessorOutputArgs(Res.getPreprocessorOutputOpts(), Args,
3119                               Res.getFrontendOpts().ProgramAction);
3120 
3121   // Turn on -Wspir-compat for SPIR target.
3122   if (T.isSPIR())
3123     Res.getDiagnosticOpts().Warnings.push_back("spir-compat");
3124 
3125   // If sanitizer is enabled, disable OPT_ffine_grained_bitfield_accesses.
3126   if (Res.getCodeGenOpts().FineGrainedBitfieldAccesses &&
3127       !Res.getLangOpts()->Sanitize.empty()) {
3128     Res.getCodeGenOpts().FineGrainedBitfieldAccesses = false;
3129     Diags.Report(diag::warn_drv_fine_grained_bitfield_accesses_ignored);
3130   }
3131 
3132   // Store the command-line for using in the CodeView backend.
3133   Res.getCodeGenOpts().Argv0 = Argv0;
3134   Res.getCodeGenOpts().CommandLineArgs = CommandLineArgs;
3135 
3136   FixupInvocation(Res, Diags, Args);
3137 
3138   return Success;
3139 }
3140 
3141 std::string CompilerInvocation::getModuleHash() const {
3142   // Note: For QoI reasons, the things we use as a hash here should all be
3143   // dumped via the -module-info flag.
3144   using llvm::hash_code;
3145   using llvm::hash_value;
3146   using llvm::hash_combine;
3147   using llvm::hash_combine_range;
3148 
3149   // Start the signature with the compiler version.
3150   // FIXME: We'd rather use something more cryptographically sound than
3151   // CityHash, but this will do for now.
3152   hash_code code = hash_value(getClangFullRepositoryVersion());
3153 
3154   // Also include the serialization version, in case LLVM_APPEND_VC_REV is off
3155   // and getClangFullRepositoryVersion() doesn't include git revision.
3156   code = hash_combine(code, serialization::VERSION_MAJOR,
3157                       serialization::VERSION_MINOR);
3158 
3159   // Extend the signature with the language options
3160 #define LANGOPT(Name, Bits, Default, Description) \
3161    code = hash_combine(code, LangOpts->Name);
3162 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
3163   code = hash_combine(code, static_cast<unsigned>(LangOpts->get##Name()));
3164 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
3165 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
3166 #include "clang/Basic/LangOptions.def"
3167 
3168   for (StringRef Feature : LangOpts->ModuleFeatures)
3169     code = hash_combine(code, Feature);
3170 
3171   code = hash_combine(code, LangOpts->ObjCRuntime);
3172   const auto &BCN = LangOpts->CommentOpts.BlockCommandNames;
3173   code = hash_combine(code, hash_combine_range(BCN.begin(), BCN.end()));
3174 
3175   // Extend the signature with the target options.
3176   code = hash_combine(code, TargetOpts->Triple, TargetOpts->CPU,
3177                       TargetOpts->TuneCPU, TargetOpts->ABI);
3178   for (const auto &FeatureAsWritten : TargetOpts->FeaturesAsWritten)
3179     code = hash_combine(code, FeatureAsWritten);
3180 
3181   // Extend the signature with preprocessor options.
3182   const PreprocessorOptions &ppOpts = getPreprocessorOpts();
3183   const HeaderSearchOptions &hsOpts = getHeaderSearchOpts();
3184   code = hash_combine(code, ppOpts.UsePredefines, ppOpts.DetailedRecord);
3185 
3186   for (const auto &I : getPreprocessorOpts().Macros) {
3187     // If we're supposed to ignore this macro for the purposes of modules,
3188     // don't put it into the hash.
3189     if (!hsOpts.ModulesIgnoreMacros.empty()) {
3190       // Check whether we're ignoring this macro.
3191       StringRef MacroDef = I.first;
3192       if (hsOpts.ModulesIgnoreMacros.count(
3193               llvm::CachedHashString(MacroDef.split('=').first)))
3194         continue;
3195     }
3196 
3197     code = hash_combine(code, I.first, I.second);
3198   }
3199 
3200   // Extend the signature with the sysroot and other header search options.
3201   code = hash_combine(code, hsOpts.Sysroot,
3202                       hsOpts.ModuleFormat,
3203                       hsOpts.UseDebugInfo,
3204                       hsOpts.UseBuiltinIncludes,
3205                       hsOpts.UseStandardSystemIncludes,
3206                       hsOpts.UseStandardCXXIncludes,
3207                       hsOpts.UseLibcxx,
3208                       hsOpts.ModulesValidateDiagnosticOptions);
3209   code = hash_combine(code, hsOpts.ResourceDir);
3210 
3211   if (hsOpts.ModulesStrictContextHash) {
3212     hash_code SHPC = hash_combine_range(hsOpts.SystemHeaderPrefixes.begin(),
3213                                         hsOpts.SystemHeaderPrefixes.end());
3214     hash_code UEC = hash_combine_range(hsOpts.UserEntries.begin(),
3215                                        hsOpts.UserEntries.end());
3216     code = hash_combine(code, hsOpts.SystemHeaderPrefixes.size(), SHPC,
3217                         hsOpts.UserEntries.size(), UEC);
3218 
3219     const DiagnosticOptions &diagOpts = getDiagnosticOpts();
3220     #define DIAGOPT(Name, Bits, Default) \
3221       code = hash_combine(code, diagOpts.Name);
3222     #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
3223       code = hash_combine(code, diagOpts.get##Name());
3224     #include "clang/Basic/DiagnosticOptions.def"
3225     #undef DIAGOPT
3226     #undef ENUM_DIAGOPT
3227   }
3228 
3229   // Extend the signature with the user build path.
3230   code = hash_combine(code, hsOpts.ModuleUserBuildPath);
3231 
3232   // Extend the signature with the module file extensions.
3233   const FrontendOptions &frontendOpts = getFrontendOpts();
3234   for (const auto &ext : frontendOpts.ModuleFileExtensions) {
3235     code = ext->hashExtension(code);
3236   }
3237 
3238   // When compiling with -gmodules, also hash -fdebug-prefix-map as it
3239   // affects the debug info in the PCM.
3240   if (getCodeGenOpts().DebugTypeExtRefs)
3241     for (const auto &KeyValue : getCodeGenOpts().DebugPrefixMap)
3242       code = hash_combine(code, KeyValue.first, KeyValue.second);
3243 
3244   // Extend the signature with the enabled sanitizers, if at least one is
3245   // enabled. Sanitizers which cannot affect AST generation aren't hashed.
3246   SanitizerSet SanHash = LangOpts->Sanitize;
3247   SanHash.clear(getPPTransparentSanitizers());
3248   if (!SanHash.empty())
3249     code = hash_combine(code, SanHash.Mask);
3250 
3251   return llvm::APInt(64, code).toString(36, /*Signed=*/false);
3252 }
3253 
3254 void CompilerInvocation::generateCC1CommandLine(
3255     SmallVectorImpl<const char *> &Args, StringAllocator SA) const {
3256   // Capture the extracted value as a lambda argument to avoid potential issues
3257   // with lifetime extension of the reference.
3258 #define OPTION_WITH_MARSHALLING(                                               \
3259     PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
3260     HELPTEXT, METAVAR, VALUES, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,  \
3261     IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, MERGER, EXTRACTOR, \
3262     TABLE_INDEX)                                                               \
3263   if ((FLAGS)&options::CC1Option) {                                            \
3264     [&](const auto &Extracted) {                                               \
3265       if (ALWAYS_EMIT ||                                                       \
3266           (Extracted !=                                                        \
3267            static_cast<decltype(this->KEYPATH)>(                               \
3268                (IMPLIED_CHECK) ? (IMPLIED_VALUE) : (DEFAULT_VALUE))))          \
3269         DENORMALIZER(Args, SPELLING, SA, Option::KIND##Class, TABLE_INDEX,     \
3270                      Extracted);                                               \
3271     }(EXTRACTOR(this->KEYPATH));                                               \
3272   }
3273 
3274 #include "clang/Driver/Options.inc"
3275 #undef OPTION_WITH_MARSHALLING
3276 }
3277 
3278 IntrusiveRefCntPtr<llvm::vfs::FileSystem>
3279 clang::createVFSFromCompilerInvocation(const CompilerInvocation &CI,
3280                                        DiagnosticsEngine &Diags) {
3281   return createVFSFromCompilerInvocation(CI, Diags,
3282                                          llvm::vfs::getRealFileSystem());
3283 }
3284 
3285 IntrusiveRefCntPtr<llvm::vfs::FileSystem>
3286 clang::createVFSFromCompilerInvocation(
3287     const CompilerInvocation &CI, DiagnosticsEngine &Diags,
3288     IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS) {
3289   if (CI.getHeaderSearchOpts().VFSOverlayFiles.empty())
3290     return BaseFS;
3291 
3292   IntrusiveRefCntPtr<llvm::vfs::FileSystem> Result = BaseFS;
3293   // earlier vfs files are on the bottom
3294   for (const auto &File : CI.getHeaderSearchOpts().VFSOverlayFiles) {
3295     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
3296         Result->getBufferForFile(File);
3297     if (!Buffer) {
3298       Diags.Report(diag::err_missing_vfs_overlay_file) << File;
3299       continue;
3300     }
3301 
3302     IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS = llvm::vfs::getVFSFromYAML(
3303         std::move(Buffer.get()), /*DiagHandler*/ nullptr, File,
3304         /*DiagContext*/ nullptr, Result);
3305     if (!FS) {
3306       Diags.Report(diag::err_invalid_vfs_overlay) << File;
3307       continue;
3308     }
3309 
3310     Result = FS;
3311   }
3312   return Result;
3313 }
3314