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