Coverage Report

Created: 2019-07-24 05:18

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