Coverage Report

Created: 2020-10-24 06:27

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