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