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