blob: 7d1b1965f93a444aebc51d14e3c585a0a969c5ed [file] [log] [blame]
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001//===- CompilerInvocation.cpp ---------------------------------------------===//
Daniel Dunbar629f6bb2009-11-17 06:02:29 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Daniel Dunbar629f6bb2009-11-17 06:02:29 +00006//
7//===----------------------------------------------------------------------===//
8
Mehdi Amini9670f842016-07-18 19:02:11 +00009#include "clang/Frontend/CompilerInvocation.h"
Douglas Gregor6623e1f2015-11-03 18:33:07 +000010#include "TestModuleFileExtension.h"
Chad Rosier7dbc9cf2016-01-06 14:35:46 +000011#include "clang/Basic/Builtins.h"
Eugene Zelenko44357ee2018-03-26 21:45:04 +000012#include "clang/Basic/CharInfo.h"
Richard Trieu63688182018-12-11 03:18:39 +000013#include "clang/Basic/CodeGenOptions.h"
Eugene Zelenko44357ee2018-03-26 21:45:04 +000014#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"
Rainer Orth09d890d2019-08-05 13:59:26 +000021#include "clang/Basic/LangStandard.h"
Eugene Zelenko44357ee2018-03-26 21:45:04 +000022#include "clang/Basic/ObjCRuntime.h"
23#include "clang/Basic/Sanitizers.h"
24#include "clang/Basic/SourceLocation.h"
25#include "clang/Basic/TargetOptions.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Basic/Version.h"
Eugene Zelenko44357ee2018-03-26 21:45:04 +000027#include "clang/Basic/Visibility.h"
Dean Michael Berris488f7c22018-04-13 02:31:58 +000028#include "clang/Basic/XRayInstr.h"
Chandler Carruthfd3cc702014-12-29 12:09:08 +000029#include "clang/Config/config.h"
Nico Weber0abcafd2019-01-31 22:15:32 +000030#include "clang/Driver/Driver.h"
Daniel Dunbarc70c3932009-12-01 03:16:53 +000031#include "clang/Driver/DriverDiagnostic.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "clang/Driver/Options.h"
Eugene Zelenko44357ee2018-03-26 21:45:04 +000033#include "clang/Frontend/CommandLineSourceLoc.h"
34#include "clang/Frontend/DependencyOutputOptions.h"
Ben Langmuir8832c062014-04-15 18:16:25 +000035#include "clang/Frontend/FrontendDiagnostic.h"
Eugene Zelenko44357ee2018-03-26 21:45:04 +000036#include "clang/Frontend/FrontendOptions.h"
Nico Weberca27a2b02019-01-03 18:26:06 +000037#include "clang/Frontend/FrontendPluginRegistry.h"
Eugene Zelenko44357ee2018-03-26 21:45:04 +000038#include "clang/Frontend/MigratorOptions.h"
39#include "clang/Frontend/PreprocessorOutputOptions.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000040#include "clang/Frontend/Utils.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000041#include "clang/Lex/HeaderSearchOptions.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000042#include "clang/Lex/PreprocessorOptions.h"
Eugene Zelenko44357ee2018-03-26 21:45:04 +000043#include "clang/Sema/CodeCompleteOptions.h"
Douglas Gregor6623e1f2015-11-03 18:33:07 +000044#include "clang/Serialization/ModuleFileExtension.h"
Eugene Zelenko44357ee2018-03-26 21:45:04 +000045#include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
46#include "llvm/ADT/APInt.h"
47#include "llvm/ADT/ArrayRef.h"
48#include "llvm/ADT/CachedHashString.h"
Douglas Gregor7fd08492012-11-05 19:45:09 +000049#include "llvm/ADT/Hashing.h"
Eugene Zelenko44357ee2018-03-26 21:45:04 +000050#include "llvm/ADT/None.h"
51#include "llvm/ADT/Optional.h"
52#include "llvm/ADT/SmallString.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000053#include "llvm/ADT/SmallVector.h"
Eugene Zelenko44357ee2018-03-26 21:45:04 +000054#include "llvm/ADT/StringRef.h"
Daniel Dunbarc70c3932009-12-01 03:16:53 +000055#include "llvm/ADT/StringSwitch.h"
Duncan Sandsf610b5b2010-08-30 09:42:39 +000056#include "llvm/ADT/Triple.h"
Eugene Zelenko44357ee2018-03-26 21:45:04 +000057#include "llvm/ADT/Twine.h"
David Blaikie65864522018-08-20 20:14:08 +000058#include "llvm/IR/DebugInfoMetadata.h"
Artem Belevich5d40ae32015-10-27 17:56:59 +000059#include "llvm/Linker/Linker.h"
Eugene Zelenko44357ee2018-03-26 21:45:04 +000060#include "llvm/MC/MCTargetOptions.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000061#include "llvm/Option/Arg.h"
62#include "llvm/Option/ArgList.h"
Eugene Zelenko44357ee2018-03-26 21:45:04 +000063#include "llvm/Option/OptSpecifier.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000064#include "llvm/Option/OptTable.h"
65#include "llvm/Option/Option.h"
Rong Xu9c6f1532016-03-02 20:59:36 +000066#include "llvm/ProfileData/InstrProfReader.h"
Saleem Abdulrasool62849c62014-05-08 02:28:32 +000067#include "llvm/Support/CodeGen.h"
Eugene Zelenko44357ee2018-03-26 21:45:04 +000068#include "llvm/Support/Compiler.h"
69#include "llvm/Support/Error.h"
Daniel Dunbar629f6bb2009-11-17 06:02:29 +000070#include "llvm/Support/ErrorHandling.h"
Eugene Zelenko44357ee2018-03-26 21:45:04 +000071#include "llvm/Support/ErrorOr.h"
Rafael Espindola9678d272013-06-26 05:03:40 +000072#include "llvm/Support/FileSystem.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000073#include "llvm/Support/Host.h"
Eugene Zelenko44357ee2018-03-26 21:45:04 +000074#include "llvm/Support/MathExtras.h"
75#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000076#include "llvm/Support/Path.h"
Nico Rieck7857d462013-09-11 00:38:02 +000077#include "llvm/Support/Process.h"
Eugene Zelenko44357ee2018-03-26 21:45:04 +000078#include "llvm/Support/Regex.h"
Pavel Labathd8c62902018-06-11 10:28:04 +000079#include "llvm/Support/VersionTuple.h"
Jonas Devliegherefc514902018-10-10 13:27:25 +000080#include "llvm/Support/VirtualFileSystem.h"
Eugene Zelenko44357ee2018-03-26 21:45:04 +000081#include "llvm/Support/raw_ostream.h"
Renato Golin4854d802015-11-09 12:40:41 +000082#include "llvm/Target/TargetOptions.h"
Eugene Zelenko44357ee2018-03-26 21:45:04 +000083#include <algorithm>
Benjamin Kramer4527fb22014-03-02 17:08:31 +000084#include <atomic>
Eugene Zelenko44357ee2018-03-26 21:45:04 +000085#include <cassert>
86#include <cstddef>
87#include <cstring>
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000088#include <memory>
Eugene Zelenko44357ee2018-03-26 21:45:04 +000089#include <string>
90#include <tuple>
91#include <utility>
92#include <vector>
93
Daniel Dunbar629f6bb2009-11-17 06:02:29 +000094using namespace clang;
Eugene Zelenko44357ee2018-03-26 21:45:04 +000095using namespace driver;
96using namespace options;
97using namespace llvm::opt;
Daniel Dunbar629f6bb2009-11-17 06:02:29 +000098
Ted Kremenek8cf47df2011-11-17 23:01:24 +000099//===----------------------------------------------------------------------===//
100// Initialization.
101//===----------------------------------------------------------------------===//
102
Ted Kremenek2acedbd2011-11-18 04:32:13 +0000103CompilerInvocationBase::CompilerInvocationBase()
Eugene Zelenko44357ee2018-03-26 21:45:04 +0000104 : LangOpts(new LangOptions()), TargetOpts(new TargetOptions()),
105 DiagnosticOpts(new DiagnosticOptions()),
106 HeaderSearchOpts(new HeaderSearchOptions()),
107 PreprocessorOpts(new PreprocessorOptions()) {}
Ted Kremenek8cf47df2011-11-17 23:01:24 +0000108
Ted Kremenek2acedbd2011-11-18 04:32:13 +0000109CompilerInvocationBase::CompilerInvocationBase(const CompilerInvocationBase &X)
David Blaikieea4395e2017-01-06 19:49:01 +0000110 : LangOpts(new LangOptions(*X.getLangOpts())),
111 TargetOpts(new TargetOptions(X.getTargetOpts())),
112 DiagnosticOpts(new DiagnosticOptions(X.getDiagnosticOpts())),
113 HeaderSearchOpts(new HeaderSearchOptions(X.getHeaderSearchOpts())),
114 PreprocessorOpts(new PreprocessorOptions(X.getPreprocessorOpts())) {}
Ted Kremenek8cf47df2011-11-17 23:01:24 +0000115
Eugene Zelenko44357ee2018-03-26 21:45:04 +0000116CompilerInvocationBase::~CompilerInvocationBase() = default;
Alp Tokerc7dc0622014-05-11 22:10:52 +0000117
Ted Kremenek8cf47df2011-11-17 23:01:24 +0000118//===----------------------------------------------------------------------===//
Richard Smith33fd5512012-11-01 03:48:49 +0000119// Deserialization (from args)
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000120//===----------------------------------------------------------------------===//
121
Peter Collingbourneb8e5dd42010-12-04 01:50:36 +0000122static unsigned getOptimizationLevel(ArgList &Args, InputKind IK,
David Blaikie9c902b52011-09-25 23:23:43 +0000123 DiagnosticsEngine &Diags) {
Sam Parker000fbab2018-11-26 17:26:49 +0000124 unsigned DefaultOpt = llvm::CodeGenOpt::None;
Rainer Orth09d890d2019-08-05 13:59:26 +0000125 if (IK.getLanguage() == Language::OpenCL && !Args.hasArg(OPT_cl_opt_disable))
Sam Parker000fbab2018-11-26 17:26:49 +0000126 DefaultOpt = llvm::CodeGenOpt::Default;
James Molloya3c85b82012-05-01 14:57:16 +0000127
128 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
129 if (A->getOption().matches(options::OPT_O0))
Sam Parker000fbab2018-11-26 17:26:49 +0000130 return llvm::CodeGenOpt::None;
James Molloya3c85b82012-05-01 14:57:16 +0000131
Chad Rosier153d7c62013-04-10 21:26:02 +0000132 if (A->getOption().matches(options::OPT_Ofast))
Sam Parker000fbab2018-11-26 17:26:49 +0000133 return llvm::CodeGenOpt::Aggressive;
Chad Rosier153d7c62013-04-10 21:26:02 +0000134
Eugene Zelenko44357ee2018-03-26 21:45:04 +0000135 assert(A->getOption().matches(options::OPT_O));
James Molloya3c85b82012-05-01 14:57:16 +0000136
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000137 StringRef S(A->getValue());
James Molloya3c85b82012-05-01 14:57:16 +0000138 if (S == "s" || S == "z" || S.empty())
Sam Parker000fbab2018-11-26 17:26:49 +0000139 return llvm::CodeGenOpt::Default;
James Molloya3c85b82012-05-01 14:57:16 +0000140
Sylvestre Ledrud340ccc2016-11-11 17:29:56 +0000141 if (S == "g")
Sam Parker000fbab2018-11-26 17:26:49 +0000142 return llvm::CodeGenOpt::Less;
Sylvestre Ledrud340ccc2016-11-11 17:29:56 +0000143
Reid Kleckner898229a2013-06-14 17:17:23 +0000144 return getLastArgIntValue(Args, OPT_O, DefaultOpt, Diags);
James Molloya3c85b82012-05-01 14:57:16 +0000145 }
146
147 return DefaultOpt;
148}
149
Chad Rosierf2d39642013-04-10 21:30:03 +0000150static unsigned getOptimizationLevelSize(ArgList &Args) {
James Molloya3c85b82012-05-01 14:57:16 +0000151 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
152 if (A->getOption().matches(options::OPT_O)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000153 switch (A->getValue()[0]) {
James Molloya3c85b82012-05-01 14:57:16 +0000154 default:
155 return 0;
156 case 's':
157 return 1;
158 case 'z':
159 return 2;
160 }
161 }
162 }
163 return 0;
164}
165
Richard Smith3be1cb22014-08-07 00:24:21 +0000166static void addDiagnosticArgs(ArgList &Args, OptSpecifier Group,
167 OptSpecifier GroupWithValue,
168 std::vector<std::string> &Diagnostics) {
Eugene Zelenko44357ee2018-03-26 21:45:04 +0000169 for (auto *A : Args.filtered(Group)) {
James Molloya3c85b82012-05-01 14:57:16 +0000170 if (A->getOption().getKind() == Option::FlagClass) {
Richard Smith3be1cb22014-08-07 00:24:21 +0000171 // The argument is a pure flag (such as OPT_Wall or OPT_Wdeprecated). Add
172 // its name (minus the "W" or "R" at the beginning) to the warning list.
173 Diagnostics.push_back(A->getOption().getName().drop_front(1));
174 } else if (A->getOption().matches(GroupWithValue)) {
175 // This is -Wfoo= or -Rfoo=, where foo is the name of the diagnostic group.
176 Diagnostics.push_back(A->getOption().getName().drop_front(1).rtrim("=-"));
James Molloya3c85b82012-05-01 14:57:16 +0000177 } else {
Richard Smith3be1cb22014-08-07 00:24:21 +0000178 // Otherwise, add its value (for OPT_W_Joined and similar).
Eugene Zelenko44357ee2018-03-26 21:45:04 +0000179 for (const auto *Arg : A->getValues())
Benjamin Kramer3204b152015-05-29 19:42:19 +0000180 Diagnostics.emplace_back(Arg);
James Molloya3c85b82012-05-01 14:57:16 +0000181 }
182 }
Peter Collingbourneb8e5dd42010-12-04 01:50:36 +0000183}
184
Kristof Umannd1a4b062018-11-30 21:24:31 +0000185// Parse the Static Analyzer configuration. If \p Diags is set to nullptr,
186// it won't verify the input.
Kristof Umann549f9cd2018-11-30 20:44:00 +0000187static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts,
Kristof Umannd1a4b062018-11-30 21:24:31 +0000188 DiagnosticsEngine *Diags);
Kristof Umann549f9cd2018-11-30 20:44:00 +0000189
Chad Rosier7dbc9cf2016-01-06 14:35:46 +0000190static void getAllNoBuiltinFuncValues(ArgList &Args,
191 std::vector<std::string> &Funcs) {
192 SmallVector<const char *, 8> Values;
193 for (const auto &Arg : Args) {
194 const Option &O = Arg->getOption();
195 if (O.matches(options::OPT_fno_builtin_)) {
196 const char *FuncName = Arg->getValue();
197 if (Builtin::Context::isBuiltinFunc(FuncName))
198 Values.push_back(FuncName);
199 }
200 }
201 Funcs.insert(Funcs.end(), Values.begin(), Values.end());
202}
203
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000204static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args,
David Blaikie9c902b52011-09-25 23:23:43 +0000205 DiagnosticsEngine &Diags) {
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000206 bool Success = true;
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000207 if (Arg *A = Args.getLastArg(OPT_analyzer_store)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000208 StringRef Name = A->getValue();
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000209 AnalysisStores Value = llvm::StringSwitch<AnalysisStores>(Name)
210#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN) \
211 .Case(CMDFLAG, NAME##Model)
Ted Kremeneka5770cd2012-08-31 04:35:58 +0000212#include "clang/StaticAnalyzer/Core/Analyses.def"
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000213 .Default(NumStores);
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000214 if (Value == NumStores) {
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000215 Diags.Report(diag::err_drv_invalid_value)
Daniel Dunbar0bcb62d2010-06-09 22:30:54 +0000216 << A->getAsString(Args) << Name;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000217 Success = false;
218 } else {
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000219 Opts.AnalysisStoreOpt = Value;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000220 }
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000221 }
222
223 if (Arg *A = Args.getLastArg(OPT_analyzer_constraints)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000224 StringRef Name = A->getValue();
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000225 AnalysisConstraints Value = llvm::StringSwitch<AnalysisConstraints>(Name)
226#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \
227 .Case(CMDFLAG, NAME##Model)
Ted Kremeneka5770cd2012-08-31 04:35:58 +0000228#include "clang/StaticAnalyzer/Core/Analyses.def"
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000229 .Default(NumConstraints);
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000230 if (Value == NumConstraints) {
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000231 Diags.Report(diag::err_drv_invalid_value)
Daniel Dunbar0bcb62d2010-06-09 22:30:54 +0000232 << A->getAsString(Args) << Name;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000233 Success = false;
234 } else {
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000235 Opts.AnalysisConstraintsOpt = Value;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000236 }
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000237 }
238
239 if (Arg *A = Args.getLastArg(OPT_analyzer_output)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000240 StringRef Name = A->getValue();
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000241 AnalysisDiagClients Value = llvm::StringSwitch<AnalysisDiagClients>(Name)
Jordan Rose367843a2013-08-16 01:06:30 +0000242#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000243 .Case(CMDFLAG, PD_##NAME)
Ted Kremeneka5770cd2012-08-31 04:35:58 +0000244#include "clang/StaticAnalyzer/Core/Analyses.def"
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000245 .Default(NUM_ANALYSIS_DIAG_CLIENTS);
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000246 if (Value == NUM_ANALYSIS_DIAG_CLIENTS) {
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000247 Diags.Report(diag::err_drv_invalid_value)
Daniel Dunbar0bcb62d2010-06-09 22:30:54 +0000248 << A->getAsString(Args) << Name;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000249 Success = false;
250 } else {
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000251 Opts.AnalysisDiagOpt = Value;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000252 }
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000253 }
254
Anna Zaks8d4c8e12011-09-30 02:03:00 +0000255 if (Arg *A = Args.getLastArg(OPT_analyzer_purge)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000256 StringRef Name = A->getValue();
Anna Zaks8d4c8e12011-09-30 02:03:00 +0000257 AnalysisPurgeMode Value = llvm::StringSwitch<AnalysisPurgeMode>(Name)
258#define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \
259 .Case(CMDFLAG, NAME)
Ted Kremeneka5770cd2012-08-31 04:35:58 +0000260#include "clang/StaticAnalyzer/Core/Analyses.def"
Anna Zaks8d4c8e12011-09-30 02:03:00 +0000261 .Default(NumPurgeModes);
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000262 if (Value == NumPurgeModes) {
Anna Zaks8d4c8e12011-09-30 02:03:00 +0000263 Diags.Report(diag::err_drv_invalid_value)
264 << A->getAsString(Args) << Name;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000265 Success = false;
266 } else {
Anna Zaks8d4c8e12011-09-30 02:03:00 +0000267 Opts.AnalysisPurgeOpt = Value;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000268 }
Anna Zaks8d4c8e12011-09-30 02:03:00 +0000269 }
270
Anna Zaks0af3e062012-03-08 23:16:35 +0000271 if (Arg *A = Args.getLastArg(OPT_analyzer_inlining_mode)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000272 StringRef Name = A->getValue();
Anna Zaks0af3e062012-03-08 23:16:35 +0000273 AnalysisInliningMode Value = llvm::StringSwitch<AnalysisInliningMode>(Name)
274#define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \
275 .Case(CMDFLAG, NAME)
Ted Kremeneka5770cd2012-08-31 04:35:58 +0000276#include "clang/StaticAnalyzer/Core/Analyses.def"
Anna Zaks0af3e062012-03-08 23:16:35 +0000277 .Default(NumInliningModes);
278 if (Value == NumInliningModes) {
279 Diags.Report(diag::err_drv_invalid_value)
280 << A->getAsString(Args) << Name;
281 Success = false;
282 } else {
283 Opts.InliningMode = Value;
284 }
285 }
286
Argyrios Kyrtzidis17bee3e2011-02-25 00:09:51 +0000287 Opts.ShowCheckerHelp = Args.hasArg(OPT_analyzer_checker_help);
Kristof Umann5bc40d92019-05-23 21:46:51 +0000288 Opts.ShowCheckerHelpAlpha = Args.hasArg(OPT_analyzer_checker_help_alpha);
289 Opts.ShowCheckerHelpDeveloper =
290 Args.hasArg(OPT_analyzer_checker_help_developer);
Kristof Umannac95c862019-05-23 22:52:09 +0000291
Kristof Umanne8df27d2019-05-23 20:47:28 +0000292 Opts.ShowCheckerOptionList = Args.hasArg(OPT_analyzer_checker_option_help);
Kristof Umannac95c862019-05-23 22:52:09 +0000293 Opts.ShowCheckerOptionAlphaList =
294 Args.hasArg(OPT_analyzer_checker_option_help_alpha);
Kristof Umann7e55ed82019-05-23 22:07:16 +0000295 Opts.ShowCheckerOptionDeveloperList =
296 Args.hasArg(OPT_analyzer_checker_option_help_developer);
Kristof Umannac95c862019-05-23 22:52:09 +0000297
Kristof Umannf1f351c2018-11-02 15:59:37 +0000298 Opts.ShowConfigOptionsList = Args.hasArg(OPT_analyzer_config_help);
Gabor Horvathc4309902016-08-08 13:41:04 +0000299 Opts.ShowEnabledCheckerList = Args.hasArg(OPT_analyzer_list_enabled_checkers);
Kristof Umannd1a4b062018-11-30 21:24:31 +0000300 Opts.ShouldEmitErrorsOnInvalidConfigValue =
301 /* negated */!llvm::StringSwitch<bool>(
302 Args.getLastArgValue(OPT_analyzer_config_compatibility_mode))
303 .Case("true", true)
304 .Case("false", false)
305 .Default(false);
Anna Zaksd5478fd2014-08-29 20:01:38 +0000306 Opts.DisableAllChecks = Args.hasArg(OPT_analyzer_disable_all_checks);
307
Ted Kremenekb8f8b352012-08-30 19:26:53 +0000308 Opts.visualizeExplodedGraphWithGraphViz =
309 Args.hasArg(OPT_analyzer_viz_egraph_graphviz);
George Karpenkovc704f4f2018-09-28 18:49:21 +0000310 Opts.DumpExplodedGraphTo = Args.getLastArgValue(OPT_analyzer_dump_egraph);
Anna Zaks72eee392012-03-28 19:59:16 +0000311 Opts.NoRetryExhausted = Args.hasArg(OPT_analyzer_disable_retry_exhausted);
Keno Fischer6f48c072019-06-07 23:34:00 +0000312 Opts.AnalyzerWerror = Args.hasArg(OPT_analyzer_werror);
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000313 Opts.AnalyzeAll = Args.hasArg(OPT_analyzer_opt_analyze_headers);
314 Opts.AnalyzerDisplayProgress = Args.hasArg(OPT_analyzer_display_progress);
Ted Kremenek68189912009-12-07 22:06:12 +0000315 Opts.AnalyzeNestedBlocks =
316 Args.hasArg(OPT_analyzer_opt_analyze_nested_blocks);
Daniel Dunbar37300482010-05-20 16:54:55 +0000317 Opts.AnalyzeSpecificFunction = Args.getLastArgValue(OPT_analyze_function);
Ted Kremenek4a2b2372010-08-03 00:09:51 +0000318 Opts.UnoptimizedCFG = Args.hasArg(OPT_analysis_UnoptimizedCFG);
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000319 Opts.TrimGraph = Args.hasArg(OPT_trim_egraph);
Reid Kleckner898229a2013-06-14 17:17:23 +0000320 Opts.maxBlockVisitOnPath =
321 getLastArgIntValue(Args, OPT_analyzer_max_loop, 4, Diags);
Anna Zaksb0286542012-02-27 21:33:16 +0000322 Opts.PrintStats = Args.hasArg(OPT_analyzer_stats);
Anna Zaks26508772012-03-02 19:05:03 +0000323 Opts.InlineMaxStackDepth =
Reid Kleckner898229a2013-06-14 17:17:23 +0000324 getLastArgIntValue(Args, OPT_analyzer_inline_max_stack_depth,
325 Opts.InlineMaxStackDepth, Diags);
Argyrios Kyrtzidis556c45e2011-02-14 18:13:31 +0000326
327 Opts.CheckersControlList.clear();
Sean Silva14facf32015-06-09 01:57:17 +0000328 for (const Arg *A :
329 Args.filtered(OPT_analyzer_checker, OPT_analyzer_disable_checker)) {
Argyrios Kyrtzidis556c45e2011-02-14 18:13:31 +0000330 A->claim();
331 bool enable = (A->getOption().getID() == OPT_analyzer_checker);
Argyrios Kyrtzidisc08d89e2011-02-24 08:42:20 +0000332 // We can have a list of comma separated checker names, e.g:
333 // '-analyzer-checker=cocoa,unix'
Richard Smithbd55daf2012-11-01 04:30:05 +0000334 StringRef checkerList = A->getValue();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000335 SmallVector<StringRef, 4> checkers;
Argyrios Kyrtzidisc08d89e2011-02-24 08:42:20 +0000336 checkerList.split(checkers, ",");
Eugene Zelenko44357ee2018-03-26 21:45:04 +0000337 for (auto checker : checkers)
Benjamin Kramer3204b152015-05-29 19:42:19 +0000338 Opts.CheckersControlList.emplace_back(checker, enable);
Argyrios Kyrtzidis556c45e2011-02-14 18:13:31 +0000339 }
Jacques Pienaara50178c2015-02-24 21:45:33 +0000340
Ted Kremenekfb5351e2012-08-29 05:55:00 +0000341 // Go through the analyzer configuration options.
Eugene Zelenko44357ee2018-03-26 21:45:04 +0000342 for (const auto *A : Args.filtered(OPT_analyzer_config)) {
Kristof Umannd1a4b062018-11-30 21:24:31 +0000343
Ted Kremenekfb5351e2012-08-29 05:55:00 +0000344 // We can have a list of comma separated config names, e.g:
Ted Kremenek53f3e7d2012-08-30 05:49:16 +0000345 // '-analyzer-config key1=val1,key2=val2'
Richard Smithbd55daf2012-11-01 04:30:05 +0000346 StringRef configList = A->getValue();
Ted Kremenekfb5351e2012-08-29 05:55:00 +0000347 SmallVector<StringRef, 4> configVals;
348 configList.split(configVals, ",");
Eugene Zelenko44357ee2018-03-26 21:45:04 +0000349 for (const auto &configVal : configVals) {
Ted Kremenekfb5351e2012-08-29 05:55:00 +0000350 StringRef key, val;
Eugene Zelenko44357ee2018-03-26 21:45:04 +0000351 std::tie(key, val) = configVal.split("=");
Ted Kremenekfb5351e2012-08-29 05:55:00 +0000352 if (val.empty()) {
353 Diags.Report(SourceLocation(),
Eugene Zelenko44357ee2018-03-26 21:45:04 +0000354 diag::err_analyzer_config_no_value) << configVal;
Ted Kremenekfb5351e2012-08-29 05:55:00 +0000355 Success = false;
356 break;
357 }
Ted Kremenek53f3e7d2012-08-30 05:49:16 +0000358 if (val.find('=') != StringRef::npos) {
Ted Kremenekfb5351e2012-08-29 05:55:00 +0000359 Diags.Report(SourceLocation(),
360 diag::err_analyzer_config_multiple_values)
Eugene Zelenko44357ee2018-03-26 21:45:04 +0000361 << configVal;
Ted Kremenekfb5351e2012-08-29 05:55:00 +0000362 Success = false;
363 break;
364 }
Kristof Umannd1a4b062018-11-30 21:24:31 +0000365
366 // TODO: Check checker options too, possibly in CheckerRegistry.
367 // Leave unknown non-checker configs unclaimed.
368 if (!key.contains(":") && Opts.isUnknownAnalyzerConfig(key)) {
369 if (Opts.ShouldEmitErrorsOnInvalidConfigValue)
370 Diags.Report(diag::err_analyzer_config_unknown) << key;
371 continue;
372 }
373
374 A->claim();
Ted Kremenekfb5351e2012-08-29 05:55:00 +0000375 Opts.Config[key] = val;
376 }
377 }
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000378
Kristof Umannd1a4b062018-11-30 21:24:31 +0000379 if (Opts.ShouldEmitErrorsOnInvalidConfigValue)
380 parseAnalyzerConfigs(Opts, &Diags);
381 else
382 parseAnalyzerConfigs(Opts, nullptr);
Kristof Umann549f9cd2018-11-30 20:44:00 +0000383
George Karpenkov4a190fe2018-01-23 19:28:52 +0000384 llvm::raw_string_ostream os(Opts.FullCompilerInvocation);
Eugene Zelenko44357ee2018-03-26 21:45:04 +0000385 for (unsigned i = 0; i < Args.getNumInputArgStrings(); ++i) {
George Karpenkov4a190fe2018-01-23 19:28:52 +0000386 if (i != 0)
387 os << " ";
388 os << Args.getArgString(i);
389 }
390 os.flush();
391
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000392 return Success;
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000393}
394
Kristof Umann549f9cd2018-11-30 20:44:00 +0000395static StringRef getStringOption(AnalyzerOptions::ConfigTable &Config,
396 StringRef OptionName, StringRef DefaultVal) {
397 return Config.insert({OptionName, DefaultVal}).first->second;
398}
399
400static void initOption(AnalyzerOptions::ConfigTable &Config,
Kristof Umannd1a4b062018-11-30 21:24:31 +0000401 DiagnosticsEngine *Diags,
Kristof Umann549f9cd2018-11-30 20:44:00 +0000402 StringRef &OptionField, StringRef Name,
403 StringRef DefaultVal) {
Kristof Umannd1a4b062018-11-30 21:24:31 +0000404 // String options may be known to invalid (e.g. if the expected string is a
405 // file name, but the file does not exist), those will have to be checked in
406 // parseConfigs.
Kristof Umann549f9cd2018-11-30 20:44:00 +0000407 OptionField = getStringOption(Config, Name, DefaultVal);
408}
409
410static void initOption(AnalyzerOptions::ConfigTable &Config,
Kristof Umannd1a4b062018-11-30 21:24:31 +0000411 DiagnosticsEngine *Diags,
Kristof Umann549f9cd2018-11-30 20:44:00 +0000412 bool &OptionField, StringRef Name, bool DefaultVal) {
Kristof Umannd1a4b062018-11-30 21:24:31 +0000413 auto PossiblyInvalidVal = llvm::StringSwitch<Optional<bool>>(
414 getStringOption(Config, Name, (DefaultVal ? "true" : "false")))
Kristof Umann549f9cd2018-11-30 20:44:00 +0000415 .Case("true", true)
416 .Case("false", false)
Kristof Umannd1a4b062018-11-30 21:24:31 +0000417 .Default(None);
418
419 if (!PossiblyInvalidVal) {
420 if (Diags)
421 Diags->Report(diag::err_analyzer_config_invalid_input)
422 << Name << "a boolean";
423 else
424 OptionField = DefaultVal;
425 } else
426 OptionField = PossiblyInvalidVal.getValue();
Kristof Umann549f9cd2018-11-30 20:44:00 +0000427}
428
429static void initOption(AnalyzerOptions::ConfigTable &Config,
Kristof Umannd1a4b062018-11-30 21:24:31 +0000430 DiagnosticsEngine *Diags,
Kristof Umann549f9cd2018-11-30 20:44:00 +0000431 unsigned &OptionField, StringRef Name,
432 unsigned DefaultVal) {
Kristof Umannd1a4b062018-11-30 21:24:31 +0000433
Kristof Umann549f9cd2018-11-30 20:44:00 +0000434 OptionField = DefaultVal;
435 bool HasFailed = getStringOption(Config, Name, std::to_string(DefaultVal))
Kristof Umannb4788b22019-04-19 12:32:10 +0000436 .getAsInteger(0, OptionField);
Kristof Umannd1a4b062018-11-30 21:24:31 +0000437 if (Diags && HasFailed)
438 Diags->Report(diag::err_analyzer_config_invalid_input)
439 << Name << "an unsigned";
Kristof Umann549f9cd2018-11-30 20:44:00 +0000440}
441
442static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts,
Kristof Umannd1a4b062018-11-30 21:24:31 +0000443 DiagnosticsEngine *Diags) {
Kristof Umann549f9cd2018-11-30 20:44:00 +0000444 // TODO: There's no need to store the entire configtable, it'd be plenty
445 // enough tostore checker options.
446
447#define ANALYZER_OPTION(TYPE, NAME, CMDFLAG, DESC, DEFAULT_VAL) \
Kristof Umannd1a4b062018-11-30 21:24:31 +0000448 initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, DEFAULT_VAL);
Kristof Umann549f9cd2018-11-30 20:44:00 +0000449
450#define ANALYZER_OPTION_DEPENDS_ON_USER_MODE(TYPE, NAME, CMDFLAG, DESC, \
451 SHALLOW_VAL, DEEP_VAL) \
452 switch (AnOpts.getUserMode()) { \
453 case UMK_Shallow: \
Kristof Umannd1a4b062018-11-30 21:24:31 +0000454 initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, SHALLOW_VAL); \
Kristof Umann549f9cd2018-11-30 20:44:00 +0000455 break; \
456 case UMK_Deep: \
Kristof Umannd1a4b062018-11-30 21:24:31 +0000457 initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, DEEP_VAL); \
Kristof Umann549f9cd2018-11-30 20:44:00 +0000458 break; \
459 } \
460
461#include "clang/StaticAnalyzer/Core/AnalyzerOptions.def"
462#undef ANALYZER_OPTION
463#undef ANALYZER_OPTION_DEPENDS_ON_USER_MODE
Kristof Umannd1a4b062018-11-30 21:24:31 +0000464
465 // At this point, AnalyzerOptions is configured. Let's validate some options.
466
467 if (!Diags)
468 return;
469
Kristof Umannb5574562019-07-05 14:00:08 +0000470 if (AnOpts.ShouldTrackConditionsDebug && !AnOpts.ShouldTrackConditions)
471 Diags->Report(diag::err_analyzer_config_invalid_input)
472 << "track-conditions-debug" << "'track-conditions' to also be enabled";
473
Kristof Umannd1a4b062018-11-30 21:24:31 +0000474 if (!AnOpts.CTUDir.empty() && !llvm::sys::fs::is_directory(AnOpts.CTUDir))
Ilya Biryukovdbc99412018-12-03 11:34:08 +0000475 Diags->Report(diag::err_analyzer_config_invalid_input) << "ctu-dir"
476 << "a filename";
Kristof Umannd1a4b062018-11-30 21:24:31 +0000477
Ilya Biryukovdbc99412018-12-03 11:34:08 +0000478 if (!AnOpts.ModelPath.empty() &&
479 !llvm::sys::fs::is_directory(AnOpts.ModelPath))
480 Diags->Report(diag::err_analyzer_config_invalid_input) << "model-path"
481 << "a filename";
Kristof Umann549f9cd2018-11-30 20:44:00 +0000482}
483
Fariborz Jahanianaa7b9aa2012-01-25 00:20:29 +0000484static bool ParseMigratorArgs(MigratorOptions &Opts, ArgList &Args) {
485 Opts.NoNSAllocReallocError = Args.hasArg(OPT_migrator_no_nsalloc_error);
Fariborz Jahanian48fd81b2012-01-26 20:57:58 +0000486 Opts.NoFinalizeRemoval = Args.hasArg(OPT_migrator_no_finalize_removal);
Fariborz Jahanianaa7b9aa2012-01-25 00:20:29 +0000487 return true;
488}
489
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000490static void ParseCommentArgs(CommentOptions &Opts, ArgList &Args) {
491 Opts.BlockCommandNames = Args.getAllArgValues(OPT_fcomment_block_commands);
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +0000492 Opts.ParseAllComments = Args.hasArg(OPT_fparse_all_comments);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000493}
494
Saleem Abdulrasool62849c62014-05-08 02:28:32 +0000495static StringRef getCodeModel(ArgList &Args, DiagnosticsEngine &Diags) {
496 if (Arg *A = Args.getLastArg(OPT_mcode_model)) {
497 StringRef Value = A->getValue();
498 if (Value == "small" || Value == "kernel" || Value == "medium" ||
David Greenecc69872018-08-22 11:34:28 +0000499 Value == "large" || Value == "tiny")
Saleem Abdulrasool62849c62014-05-08 02:28:32 +0000500 return Value;
501 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Value;
502 }
503 return "default";
504}
505
Rafael Espindolae1d70532018-01-18 00:20:03 +0000506static llvm::Reloc::Model getRelocModel(ArgList &Args,
507 DiagnosticsEngine &Diags) {
Davide Italiano1a3665bb2017-04-01 21:07:07 +0000508 if (Arg *A = Args.getLastArg(OPT_mrelocation_model)) {
509 StringRef Value = A->getValue();
Rafael Espindolae1d70532018-01-18 00:20:03 +0000510 auto RM = llvm::StringSwitch<llvm::Optional<llvm::Reloc::Model>>(Value)
511 .Case("static", llvm::Reloc::Static)
512 .Case("pic", llvm::Reloc::PIC_)
513 .Case("ropi", llvm::Reloc::ROPI)
514 .Case("rwpi", llvm::Reloc::RWPI)
515 .Case("ropi-rwpi", llvm::Reloc::ROPI_RWPI)
516 .Case("dynamic-no-pic", llvm::Reloc::DynamicNoPIC)
517 .Default(None);
518 if (RM.hasValue())
519 return *RM;
Davide Italiano1a3665bb2017-04-01 21:07:07 +0000520 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Value;
521 }
Rafael Espindolae1d70532018-01-18 00:20:03 +0000522 return llvm::Reloc::PIC_;
Davide Italiano1a3665bb2017-04-01 21:07:07 +0000523}
524
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000525/// Create a new Regex instance out of the string value in \p RpassArg.
Diego Novillod23ec942014-05-29 19:55:06 +0000526/// It returns a pointer to the newly generated Regex instance.
527static std::shared_ptr<llvm::Regex>
528GenerateOptimizationRemarkRegex(DiagnosticsEngine &Diags, ArgList &Args,
529 Arg *RpassArg) {
530 StringRef Val = RpassArg->getValue();
531 std::string RegexError;
532 std::shared_ptr<llvm::Regex> Pattern = std::make_shared<llvm::Regex>(Val);
533 if (!Pattern->isValid(RegexError)) {
534 Diags.Report(diag::err_drv_optimization_remark_pattern)
535 << RegexError << RpassArg->getAsString(Args);
536 Pattern.reset();
537 }
538 return Pattern;
539}
540
Eric Fiselier098e6de2015-06-13 07:11:40 +0000541static bool parseDiagnosticLevelMask(StringRef FlagName,
542 const std::vector<std::string> &Levels,
543 DiagnosticsEngine *Diags,
544 DiagnosticLevelMask &M) {
545 bool Success = true;
546 for (const auto &Level : Levels) {
547 DiagnosticLevelMask const PM =
548 llvm::StringSwitch<DiagnosticLevelMask>(Level)
549 .Case("note", DiagnosticLevelMask::Note)
550 .Case("remark", DiagnosticLevelMask::Remark)
551 .Case("warning", DiagnosticLevelMask::Warning)
552 .Case("error", DiagnosticLevelMask::Error)
553 .Default(DiagnosticLevelMask::None);
554 if (PM == DiagnosticLevelMask::None) {
555 Success = false;
556 if (Diags)
557 Diags->Report(diag::err_drv_invalid_value) << FlagName << Level;
558 }
559 M = M | PM;
560 }
561 return Success;
562}
563
Alexey Samsonov88459522015-01-12 22:39:12 +0000564static void parseSanitizerKinds(StringRef FlagName,
565 const std::vector<std::string> &Sanitizers,
566 DiagnosticsEngine &Diags, SanitizerSet &S) {
567 for (const auto &Sanitizer : Sanitizers) {
Peter Collingbournebf59c342015-05-11 21:39:20 +0000568 SanitizerMask K = parseSanitizerValue(Sanitizer, /*AllowGroups=*/false);
Pierre Gousseauae5303d2019-03-01 10:05:15 +0000569 if (K == SanitizerMask())
Alexey Samsonov88459522015-01-12 22:39:12 +0000570 Diags.Report(diag::err_drv_invalid_value) << FlagName << Sanitizer;
571 else
572 S.set(K, true);
573 }
574}
575
Dean Michael Berris488f7c22018-04-13 02:31:58 +0000576static void parseXRayInstrumentationBundle(StringRef FlagName, StringRef Bundle,
577 ArgList &Args, DiagnosticsEngine &D,
578 XRayInstrSet &S) {
579 llvm::SmallVector<StringRef, 2> BundleParts;
580 llvm::SplitString(Bundle, BundleParts, ",");
581 for (const auto B : BundleParts) {
582 auto Mask = parseXRayInstrValue(B);
583 if (Mask == XRayInstrKind::None)
584 if (B != "none")
585 D.Report(diag::err_drv_invalid_value) << FlagName << Bundle;
586 else
587 S.Mask = Mask;
588 else if (Mask == XRayInstrKind::All)
589 S.Mask = Mask;
590 else
591 S.set(Mask, true);
592 }
593}
594
Rong Xu9c6f1532016-03-02 20:59:36 +0000595// Set the profile kind for fprofile-instrument.
596static void setPGOInstrumentor(CodeGenOptions &Opts, ArgList &Args,
597 DiagnosticsEngine &Diags) {
598 Arg *A = Args.getLastArg(OPT_fprofile_instrument_EQ);
599 if (A == nullptr)
600 return;
601 StringRef S = A->getValue();
602 unsigned I = llvm::StringSwitch<unsigned>(S)
603 .Case("none", CodeGenOptions::ProfileNone)
604 .Case("clang", CodeGenOptions::ProfileClangInstr)
605 .Case("llvm", CodeGenOptions::ProfileIRInstr)
Rong Xua4a09b22019-03-04 20:21:31 +0000606 .Case("csllvm", CodeGenOptions::ProfileCSIRInstr)
Rong Xu9c6f1532016-03-02 20:59:36 +0000607 .Default(~0U);
608 if (I == ~0U) {
609 Diags.Report(diag::err_drv_invalid_pgo_instrumentor) << A->getAsString(Args)
610 << S;
611 return;
612 }
Eugene Zelenko44357ee2018-03-26 21:45:04 +0000613 auto Instrumentor = static_cast<CodeGenOptions::ProfileInstrKind>(I);
Rong Xu9c6f1532016-03-02 20:59:36 +0000614 Opts.setProfileInstr(Instrumentor);
615}
616
617// Set the profile kind using fprofile-instrument-use-path.
618static void setPGOUseInstrumentor(CodeGenOptions &Opts,
Benjamin Kramer442b9a92016-05-29 11:04:56 +0000619 const Twine &ProfileName) {
Rong Xu9c6f1532016-03-02 20:59:36 +0000620 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(ProfileName);
621 // In error, return silently and let Clang PGOUse report the error message.
Vedant Kumarfa2d5952016-05-19 03:54:54 +0000622 if (auto E = ReaderOrErr.takeError()) {
623 llvm::consumeError(std::move(E));
Rong Xu9c6f1532016-03-02 20:59:36 +0000624 Opts.setProfileUse(CodeGenOptions::ProfileClangInstr);
625 return;
626 }
627 std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader =
628 std::move(ReaderOrErr.get());
Rong Xua4a09b22019-03-04 20:21:31 +0000629 if (PGOReader->isIRLevelProfile()) {
630 if (PGOReader->hasCSIRLevelProfile())
631 Opts.setProfileUse(CodeGenOptions::ProfileCSIRInstr);
632 else
633 Opts.setProfileUse(CodeGenOptions::ProfileIRInstr);
634 } else
Rong Xu9c6f1532016-03-02 20:59:36 +0000635 Opts.setProfileUse(CodeGenOptions::ProfileClangInstr);
636}
637
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000638static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK,
Adrian Prantla7634472014-01-07 01:19:08 +0000639 DiagnosticsEngine &Diags,
Teresa Johnson9e4321c2018-04-17 16:39:25 +0000640 const TargetOptions &TargetOpts,
641 const FrontendOptions &FrontendOpts) {
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000642 bool Success = true;
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000643 llvm::Triple Triple = llvm::Triple(TargetOpts.Triple);
Peter Collingbourneb8e5dd42010-12-04 01:50:36 +0000644
Rafael Espindolafd8de1c2014-12-16 21:57:03 +0000645 unsigned OptimizationLevel = getOptimizationLevel(Args, IK, Diags);
Sylvestre Ledru5abf2ec2013-11-18 13:23:07 +0000646 // TODO: This could be done in Driver
647 unsigned MaxOptLevel = 3;
Rafael Espindolafd8de1c2014-12-16 21:57:03 +0000648 if (OptimizationLevel > MaxOptLevel) {
649 // If the optimization level is not supported, fall back on the default
650 // optimization
Sylvestre Ledru5abf2ec2013-11-18 13:23:07 +0000651 Diags.Report(diag::warn_drv_optimization_value)
652 << Args.getLastArg(OPT_O)->getAsString(Args) << "-O" << MaxOptLevel;
Rafael Espindolafd8de1c2014-12-16 21:57:03 +0000653 OptimizationLevel = MaxOptLevel;
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000654 }
Rafael Espindolafd8de1c2014-12-16 21:57:03 +0000655 Opts.OptimizationLevel = OptimizationLevel;
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000656
Chandler Carruthfcd33142016-12-23 01:24:49 +0000657 // At O0 we want to fully disable inlining outside of cases marked with
658 // 'alwaysinline' that are required for correctness.
659 Opts.setInlining((Opts.OptimizationLevel == 0)
660 ? CodeGenOptions::OnlyAlwaysInlining
661 : CodeGenOptions::NormalInlining);
662 // Explicit inlining flags can disable some or all inlining even at
663 // optimization levels above zero.
664 if (Arg *InlineArg = Args.getLastArg(
665 options::OPT_finline_functions, options::OPT_finline_hint_functions,
666 options::OPT_fno_inline_functions, options::OPT_fno_inline)) {
667 if (Opts.OptimizationLevel > 0) {
668 const Option &InlineOpt = InlineArg->getOption();
669 if (InlineOpt.matches(options::OPT_finline_functions))
670 Opts.setInlining(CodeGenOptions::NormalInlining);
671 else if (InlineOpt.matches(options::OPT_finline_hint_functions))
672 Opts.setInlining(CodeGenOptions::OnlyHintInlining);
673 else
674 Opts.setInlining(CodeGenOptions::OnlyAlwaysInlining);
675 }
Hans Wennborg7a008882016-05-24 20:40:51 +0000676 }
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000677
Chandler Carruth50f9e892016-12-23 20:44:01 +0000678 Opts.ExperimentalNewPassManager = Args.hasFlag(
679 OPT_fexperimental_new_pass_manager, OPT_fno_experimental_new_pass_manager,
Petr Hosekc3aa97a2018-04-06 00:53:00 +0000680 /* Default */ ENABLE_EXPERIMENTAL_NEW_PASS_MANAGER);
Chandler Carruth50f9e892016-12-23 20:44:01 +0000681
Tim Shenb13eebe2017-06-29 23:10:13 +0000682 Opts.DebugPassManager =
683 Args.hasFlag(OPT_fdebug_pass_manager, OPT_fno_debug_pass_manager,
684 /* Default */ false);
685
Michael Zolotukhinc888dd02015-03-17 20:03:11 +0000686 if (Arg *A = Args.getLastArg(OPT_fveclib)) {
687 StringRef Name = A->getValue();
688 if (Name == "Accelerate")
689 Opts.setVecLib(CodeGenOptions::Accelerate);
Nemanja Ivanovic6321c682019-06-05 01:57:57 +0000690 else if (Name == "MASSV")
691 Opts.setVecLib(CodeGenOptions::MASSV);
Matt Masten6731dea2016-07-29 16:44:24 +0000692 else if (Name == "SVML")
693 Opts.setVecLib(CodeGenOptions::SVML);
Michael Zolotukhinc888dd02015-03-17 20:03:11 +0000694 else if (Name == "none")
695 Opts.setVecLib(CodeGenOptions::NoLibrary);
696 else
697 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
698 }
699
Douglas Katzman3459ce22015-10-08 04:24:12 +0000700 if (Arg *A = Args.getLastArg(OPT_debug_info_kind_EQ)) {
Douglas Katzmana2ef81f2016-01-06 01:37:57 +0000701 unsigned Val =
702 llvm::StringSwitch<unsigned>(A->getValue())
Benjamin Kramer8c305922016-02-02 11:06:51 +0000703 .Case("line-tables-only", codegenoptions::DebugLineTablesOnly)
Alexey Bataev80e1b5e2018-08-31 13:56:14 +0000704 .Case("line-directives-only", codegenoptions::DebugDirectivesOnly)
Benjamin Kramer8c305922016-02-02 11:06:51 +0000705 .Case("limited", codegenoptions::LimitedDebugInfo)
706 .Case("standalone", codegenoptions::FullDebugInfo)
Douglas Katzmana2ef81f2016-01-06 01:37:57 +0000707 .Default(~0U);
708 if (Val == ~0U)
709 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
710 << A->getValue();
711 else
Benjamin Kramer8c305922016-02-02 11:06:51 +0000712 Opts.setDebugInfo(static_cast<codegenoptions::DebugInfoKind>(Val));
Alexey Samsonov486e1fe2012-04-27 07:24:20 +0000713 }
Paul Robinson45784a72015-12-19 02:24:10 +0000714 if (Arg *A = Args.getLastArg(OPT_debugger_tuning_EQ)) {
Douglas Katzmana2ef81f2016-01-06 01:37:57 +0000715 unsigned Val = llvm::StringSwitch<unsigned>(A->getValue())
Paul Robinson9ef13db2016-02-05 23:23:25 +0000716 .Case("gdb", unsigned(llvm::DebuggerKind::GDB))
717 .Case("lldb", unsigned(llvm::DebuggerKind::LLDB))
718 .Case("sce", unsigned(llvm::DebuggerKind::SCE))
Douglas Katzmana2ef81f2016-01-06 01:37:57 +0000719 .Default(~0U);
720 if (Val == ~0U)
721 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
722 << A->getValue();
723 else
Paul Robinson9ef13db2016-02-05 23:23:25 +0000724 Opts.setDebuggerTuning(static_cast<llvm::DebuggerKind>(Val));
Paul Robinson45784a72015-12-19 02:24:10 +0000725 }
Douglas Katzman3459ce22015-10-08 04:24:12 +0000726 Opts.DwarfVersion = getLastArgIntValue(Args, OPT_dwarf_version_EQ, 0, Diags);
Eric Christophera2f7eb72012-10-18 21:52:18 +0000727 Opts.DebugColumnInfo = Args.hasArg(OPT_dwarf_column_info);
Douglas Katzman3459ce22015-10-08 04:24:12 +0000728 Opts.EmitCodeView = Args.hasArg(OPT_gcodeview);
Reid Kleckner75557712018-11-16 18:47:41 +0000729 Opts.CodeViewGHash = Args.hasArg(OPT_gcodeview_ghash);
Amjad Aboud546bc112017-02-09 22:07:24 +0000730 Opts.MacroDebugInfo = Args.hasArg(OPT_debug_info_macro);
Peter Collingbournefb532b92016-02-24 20:46:36 +0000731 Opts.WholeProgramVTables = Args.hasArg(OPT_fwhole_program_vtables);
Peter Collingbourne3afb2662016-04-28 17:09:37 +0000732 Opts.LTOVisibilityPublicStd = Args.hasArg(OPT_flto_visibility_public_std);
Aaron Pucherte1dc4952019-06-15 15:38:51 +0000733 Opts.SplitDwarfFile = Args.getLastArgValue(OPT_split_dwarf_file);
Aaron Puchert922759a2019-06-15 14:07:43 +0000734 Opts.SplitDwarfOutput = Args.getLastArgValue(OPT_split_dwarf_output);
David Blaikiea45c31a2016-08-24 18:29:58 +0000735 Opts.SplitDwarfInlining = !Args.hasArg(OPT_fno_split_dwarf_inlining);
Adrian Prantl6b21ab22015-08-27 19:46:20 +0000736 Opts.DebugTypeExtRefs = Args.hasArg(OPT_dwarf_ext_refs);
Paul Robinsona8280812017-09-29 21:25:07 +0000737 Opts.DebugExplicitImport = Args.hasArg(OPT_dwarf_explicit_import);
Paul Robinson1787f812017-09-28 18:37:02 +0000738 Opts.DebugFwdTemplateParams = Args.hasArg(OPT_debug_forward_template_params);
Scott Lindera2fbcef2018-02-26 17:32:31 +0000739 Opts.EmbedSource = Args.hasArg(OPT_gembed_source);
Alexey Samsonov486e1fe2012-04-27 07:24:20 +0000740
Saleem Abdulrasool436256a2015-10-12 20:21:08 +0000741 for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ))
742 Opts.DebugPrefixMap.insert(StringRef(Arg).split('='));
743
Duncan P. N. Exon Smithbb618252015-04-15 01:16:18 +0000744 if (const Arg *A =
745 Args.getLastArg(OPT_emit_llvm_uselists, OPT_no_emit_llvm_uselists))
746 Opts.EmitLLVMUseLists = A->getOption().getID() == OPT_emit_llvm_uselists;
747
Steven Wu546a1962015-07-17 20:09:56 +0000748 Opts.DisableLLVMPasses = Args.hasArg(OPT_disable_llvm_passes);
Mehdi Amini7f873072017-01-06 23:18:09 +0000749 Opts.DisableLifetimeMarkers = Args.hasArg(OPT_disable_lifetimemarkers);
Djordje Todorovic639d36b2019-06-26 09:38:09 +0000750
751 llvm::Triple T(TargetOpts.Triple);
752 llvm::Triple::ArchType Arch = T.getArch();
753 if (Opts.OptimizationLevel > 0 &&
754 (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64))
755 Opts.EnableDebugEntryValues = Args.hasArg(OPT_femit_debug_entry_values);
756
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +0000757 Opts.DisableO0ImplyOptNone = Args.hasArg(OPT_disable_O0_optnone);
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000758 Opts.DisableRedZone = Args.hasArg(OPT_disable_red_zone);
Kristina Brooks7f569b72018-10-18 14:07:02 +0000759 Opts.IndirectTlsSegRefs = Args.hasArg(OPT_mno_tls_direct_seg_refs);
John McCall7ef5cb32011-03-18 02:56:14 +0000760 Opts.ForbidGuardVariables = Args.hasArg(OPT_fforbid_guard_variables);
Daniel Dunbard3f3d932011-06-21 18:54:46 +0000761 Opts.UseRegisterSizedBitfieldAccess = Args.hasArg(
762 OPT_fuse_register_sized_bitfield_access);
Chad Rosierb71f6aa2013-04-24 18:09:54 +0000763 Opts.RelaxedAliasing = Args.hasArg(OPT_relaxed_aliasing);
Manman Renf5d9d342013-10-11 20:48:38 +0000764 Opts.StructPathTBAA = !Args.hasArg(OPT_no_struct_path_tbaa);
Ivan A. Kosarevfa03a6a2017-11-20 11:16:16 +0000765 Opts.NewStructPathTBAA = !Args.hasArg(OPT_no_struct_path_tbaa) &&
766 Args.hasArg(OPT_new_struct_path_tbaa);
Wei Mi9b3d6272017-10-16 16:50:27 +0000767 Opts.FineGrainedBitfieldAccesses =
768 Args.hasFlag(OPT_ffine_grained_bitfield_accesses,
769 OPT_fno_fine_grained_bitfield_accesses, false);
Daniel Dunbar37300482010-05-20 16:54:55 +0000770 Opts.DwarfDebugFlags = Args.getLastArgValue(OPT_dwarf_debug_flags);
Scott Linderde6beb02018-12-14 15:38:15 +0000771 Opts.RecordCommandLine = Args.getLastArgValue(OPT_record_command_line);
Manoj Gupta4b3eefa2018-04-05 15:29:52 +0000772 Opts.MergeAllConstants = Args.hasArg(OPT_fmerge_all_constants);
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000773 Opts.NoCommon = Args.hasArg(OPT_fno_common);
774 Opts.NoImplicitFloat = Args.hasArg(OPT_no_implicit_float);
Chad Rosierf2d39642013-04-10 21:30:03 +0000775 Opts.OptimizeSize = getOptimizationLevelSize(Args);
Daniel Dunbar6d5824f2010-06-07 23:19:17 +0000776 Opts.SimplifyLibCalls = !(Args.hasArg(OPT_fno_builtin) ||
777 Args.hasArg(OPT_ffreestanding));
Chad Rosier7dbc9cf2016-01-06 14:35:46 +0000778 if (Opts.SimplifyLibCalls)
779 getAllNoBuiltinFuncValues(Args, Opts.NoBuiltinFuncs);
Chandler Carruth54c29102013-08-08 08:34:35 +0000780 Opts.UnrollLoops =
781 Args.hasFlag(OPT_funroll_loops, OPT_fno_unroll_loops,
Marianne Mailhot-Sarrasin21ac3bf2016-05-04 15:26:28 +0000782 (Opts.OptimizationLevel > 1));
Hal Finkelce0697f2013-11-17 16:03:29 +0000783 Opts.RerollLoops = Args.hasArg(OPT_freroll_loops);
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000784
Saleem Abdulrasoolcfeb90d2014-02-23 00:40:30 +0000785 Opts.DisableIntegratedAS = Args.hasArg(OPT_fno_integrated_as);
Daniel Dunbare246fbe2013-04-16 18:21:19 +0000786 Opts.Autolink = !Args.hasArg(OPT_fno_autolink);
Diego Novillo5c297052013-11-13 12:22:39 +0000787 Opts.SampleProfileFile = Args.getLastArgValue(OPT_fprofile_sample_use_EQ);
Dehao Chenb3a70de2017-01-19 00:44:21 +0000788 Opts.DebugInfoForProfiling = Args.hasFlag(
789 OPT_fdebug_info_for_profiling, OPT_fno_debug_info_for_profiling, false);
David Blaikie65864522018-08-20 20:14:08 +0000790 Opts.DebugNameTable = static_cast<unsigned>(
791 Args.hasArg(OPT_ggnu_pubnames)
792 ? llvm::DICompileUnit::DebugNameTableKind::GNU
793 : Args.hasArg(OPT_gpubnames)
794 ? llvm::DICompileUnit::DebugNameTableKind::Default
795 : llvm::DICompileUnit::DebugNameTableKind::None);
David Blaikie27692de2018-11-13 20:08:13 +0000796 Opts.DebugRangesBaseAddress = Args.hasArg(OPT_fdebug_ranges_base_address);
Rong Xu9837ef52016-02-04 18:39:09 +0000797
Rong Xu9c6f1532016-03-02 20:59:36 +0000798 setPGOInstrumentor(Opts, Args, Diags);
799 Opts.InstrProfileOutput =
800 Args.getLastArgValue(OPT_fprofile_instrument_path_EQ);
801 Opts.ProfileInstrumentUsePath =
802 Args.getLastArgValue(OPT_fprofile_instrument_use_path_EQ);
803 if (!Opts.ProfileInstrumentUsePath.empty())
804 setPGOUseInstrumentor(Opts, Opts.ProfileInstrumentUsePath);
Richard Smith8654ae52018-10-10 23:13:35 +0000805 Opts.ProfileRemappingFile =
806 Args.getLastArgValue(OPT_fprofile_remapping_file_EQ);
807 if (!Opts.ProfileRemappingFile.empty() && !Opts.ExperimentalNewPassManager) {
808 Diags.Report(diag::err_drv_argument_only_allowed_with)
809 << Args.getLastArg(OPT_fprofile_remapping_file_EQ)->getAsString(Args)
810 << "-fexperimental-new-pass-manager";
811 }
Rong Xu9837ef52016-02-04 18:39:09 +0000812
Diego Novilloc4b94da2015-08-05 23:27:40 +0000813 Opts.CoverageMapping =
814 Args.hasFlag(OPT_fcoverage_mapping, OPT_fno_coverage_mapping, false);
Alex Lorenzf2cf38e2014-08-08 23:41:24 +0000815 Opts.DumpCoverageMapping = Args.hasArg(OPT_dump_coverage_mapping);
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000816 Opts.AsmVerbose = Args.hasArg(OPT_masm_verbose);
Nirav Dave993a1392016-07-27 19:57:40 +0000817 Opts.PreserveAsmComments = !Args.hasArg(OPT_fno_preserve_as_comments);
Richard Smith351241c2016-04-07 21:46:12 +0000818 Opts.AssumeSaneOperatorNew = !Args.hasArg(OPT_fno_assume_sane_operator_new);
John McCall31168b02011-06-15 23:02:42 +0000819 Opts.ObjCAutoRefCountExceptions = Args.hasArg(OPT_fobjc_arc_exceptions);
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000820 Opts.CXAAtExit = !Args.hasArg(OPT_fno_use_cxa_atexit);
Akira Hatanaka617e2612018-04-17 18:41:52 +0000821 Opts.RegisterGlobalDtorsWithAtExit =
822 Args.hasArg(OPT_fregister_global_dtors_with_atexit);
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000823 Opts.CXXCtorDtorAliases = Args.hasArg(OPT_mconstructor_aliases);
Ali Tamurbc1cd922018-10-08 22:25:20 +0000824 Opts.CodeModel = TargetOpts.CodeModel;
Daniel Dunbar37300482010-05-20 16:54:55 +0000825 Opts.DebugPass = Args.getLastArgValue(OPT_mdebug_pass);
Yuanfang Chenff22ec32019-07-20 22:50:50 +0000826
827 // Handle -mframe-pointer option.
828 if (Arg *A = Args.getLastArg(OPT_mframe_pointer_EQ)) {
829 CodeGenOptions::FramePointerKind FP;
830 StringRef Name = A->getValue();
831 bool ValidFP = true;
832 if (Name == "none")
833 FP = CodeGenOptions::FramePointerKind::None;
834 else if (Name == "non-leaf")
835 FP = CodeGenOptions::FramePointerKind::NonLeaf;
836 else if (Name == "all")
837 FP = CodeGenOptions::FramePointerKind::All;
838 else {
839 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
840 Success = false;
841 ValidFP = false;
842 }
843 if (ValidFP)
844 Opts.setFramePointer(FP);
845 }
846
847 // -pg may override -mframe-pointer
848 // TODO: This should be merged into getFramePointerKind in Clang.cpp.
849 if (Args.hasArg(OPT_pg))
850 Opts.setFramePointer(CodeGenOptions::FramePointerKind::All);
851
Nick Lewycky92a6c742013-06-21 21:15:32 +0000852 Opts.DisableFree = Args.hasArg(OPT_disable_free);
Benjamin Kramer12f2de12016-03-14 13:23:58 +0000853 Opts.DiscardValueNames = Args.hasArg(OPT_discard_value_names);
Nick Lewycky1c8c4362012-01-23 08:29:12 +0000854 Opts.DisableTailCalls = Args.hasArg(OPT_mdisable_tail_calls);
Akira Hatanaka627586b2018-03-02 01:53:15 +0000855 Opts.NoEscapingBlockTailCalls =
856 Args.hasArg(OPT_fno_escaping_block_tail_calls);
Daniel Dunbar37300482010-05-20 16:54:55 +0000857 Opts.FloatABI = Args.getLastArgValue(OPT_mfloat_abi);
Egor Churaev45c26ee2017-03-27 10:38:01 +0000858 Opts.LessPreciseFPMAD = Args.hasArg(OPT_cl_mad_enable) ||
859 Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
860 Args.hasArg(OPT_cl_fast_relaxed_math);
Daniel Dunbar37300482010-05-20 16:54:55 +0000861 Opts.LimitFloatPrecision = Args.getLastArgValue(OPT_mlimit_float_precision);
Daniel Dunbar19939cc2011-12-09 23:41:18 +0000862 Opts.NoInfsFPMath = (Args.hasArg(OPT_menable_no_infinities) ||
Pekka Jaaskelainen37014502014-12-10 16:41:14 +0000863 Args.hasArg(OPT_cl_finite_math_only) ||
Daniel Dunbar19939cc2011-12-09 23:41:18 +0000864 Args.hasArg(OPT_cl_fast_relaxed_math));
865 Opts.NoNaNsFPMath = (Args.hasArg(OPT_menable_no_nans) ||
Pekka Jaaskelainen37014502014-12-10 16:41:14 +0000866 Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
867 Args.hasArg(OPT_cl_finite_math_only) ||
Daniel Dunbar19939cc2011-12-09 23:41:18 +0000868 Args.hasArg(OPT_cl_fast_relaxed_math));
Yaxun Liu79c99fb2016-07-08 20:28:29 +0000869 Opts.NoSignedZeros = (Args.hasArg(OPT_fno_signed_zeros) ||
Egor Churaev45c26ee2017-03-27 10:38:01 +0000870 Args.hasArg(OPT_cl_no_signed_zeros) ||
871 Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
872 Args.hasArg(OPT_cl_fast_relaxed_math));
Sanjay Patelcb8c0092017-12-16 16:11:17 +0000873 Opts.Reassociate = Args.hasArg(OPT_mreassociate);
Yaxun Liue1bfbc52018-07-21 02:02:22 +0000874 Opts.FlushDenorm = Args.hasArg(OPT_cl_denorms_are_zero) ||
875 (Args.hasArg(OPT_fcuda_is_device) &&
876 Args.hasArg(OPT_fcuda_flush_denormals_to_zero));
Yaxun Liuffb60902016-08-09 20:10:18 +0000877 Opts.CorrectlyRoundedDivSqrt =
878 Args.hasArg(OPT_cl_fp32_correctly_rounded_divide_sqrt);
Alexey Sotkin20f65922018-02-22 11:54:14 +0000879 Opts.UniformWGSize =
880 Args.hasArg(OPT_cl_uniform_work_group_size);
Craig Topper402b4312017-11-20 17:09:22 +0000881 Opts.Reciprocals = Args.getAllArgValues(OPT_mrecip_EQ);
Sanjay Patel359b1052015-04-09 15:03:23 +0000882 Opts.ReciprocalMath = Args.hasArg(OPT_freciprocal_math);
Sjoerd Meijer0a8d4212016-08-30 08:09:45 +0000883 Opts.NoTrappingMath = Args.hasArg(OPT_fno_trapping_math);
Sanjay Patelc81450e2018-04-30 18:19:03 +0000884 Opts.StrictFloatCastOverflow =
885 !Args.hasArg(OPT_fno_strict_float_cast_overflow);
Sanjay Pateld1754762018-04-27 14:22:48 +0000886
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000887 Opts.NoZeroInitializedInBSS = Args.hasArg(OPT_mno_zero_initialized_in_bss);
Reid Kleckner898229a2013-06-14 17:17:23 +0000888 Opts.NumRegisterParameters = getLastArgIntValue(Args, OPT_mregparm, 0, Diags);
Nick Lewyckyca6b90d2011-06-21 00:14:18 +0000889 Opts.NoExecStack = Args.hasArg(OPT_mno_exec_stack);
Joerg Sonnenbergera43604a2014-08-26 18:40:25 +0000890 Opts.FatalWarnings = Args.hasArg(OPT_massembler_fatal_warnings);
Brian Cain7b953b62019-08-08 19:19:20 +0000891 Opts.NoWarn = Args.hasArg(OPT_massembler_no_warn);
Eric Christopher006208c2013-04-04 06:29:47 +0000892 Opts.EnableSegmentedStacks = Args.hasArg(OPT_split_stacks);
Daniel Dunbarc43b6b22010-05-27 05:39:39 +0000893 Opts.RelaxAll = Args.hasArg(OPT_mrelax_all);
David Majnemer2b9349d2015-12-21 22:09:34 +0000894 Opts.IncrementalLinkerCompatible =
895 Args.hasArg(OPT_mincremental_linker_compatible);
Sriraman Tallam165a8842016-10-19 20:24:06 +0000896 Opts.PIECopyRelocations =
897 Args.hasArg(OPT_mpie_copy_relocations);
Sriraman Tallam5c651482017-11-07 19:37:51 +0000898 Opts.NoPLT = Args.hasArg(OPT_fno_plt);
Daniel Dunbar67919b22011-03-28 22:49:28 +0000899 Opts.SaveTempLabels = Args.hasArg(OPT_msave_temp_labels);
Nick Lewycky1d617ac2011-10-17 23:05:52 +0000900 Opts.NoDwarfDirectoryAsm = Args.hasArg(OPT_fno_dwarf_directory_asm);
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000901 Opts.SoftFloat = Args.hasArg(OPT_msoft_float);
Chandler Carruth8b4140d2012-03-27 23:58:37 +0000902 Opts.StrictEnums = Args.hasArg(OPT_fstrict_enums);
Alex Lorenzc1608f72017-01-04 13:40:34 +0000903 Opts.StrictReturn = !Args.hasArg(OPT_fno_strict_return);
Piotr Padlewski338c9d02015-09-15 21:46:47 +0000904 Opts.StrictVTablePointers = Args.hasArg(OPT_fstrict_vtable_pointers);
Piotr Padlewskie368de32018-06-13 13:55:42 +0000905 Opts.ForceEmitVTables = Args.hasArg(OPT_fforce_emit_vtables);
Chandler Carruth306bd2c2012-01-02 14:19:45 +0000906 Opts.UnsafeFPMath = Args.hasArg(OPT_menable_unsafe_fp_math) ||
907 Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
Peter Collingbourne61d6a752010-12-04 01:51:23 +0000908 Args.hasArg(OPT_cl_fast_relaxed_math);
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000909 Opts.UnwindTables = Args.hasArg(OPT_munwind_tables);
Davide Italiano1a3665bb2017-04-01 21:07:07 +0000910 Opts.RelocationModel = getRelocModel(Args, Diags);
Jonathan Roelofsb140a102014-10-03 21:57:44 +0000911 Opts.ThreadModel = Args.getLastArgValue(OPT_mthread_model, "posix");
912 if (Opts.ThreadModel != "posix" && Opts.ThreadModel != "single")
913 Diags.Report(diag::err_drv_invalid_value)
914 << Args.getLastArg(OPT_mthread_model)->getAsString(Args)
915 << Opts.ThreadModel;
Bob Wilson14adb362012-02-03 06:27:22 +0000916 Opts.TrapFuncName = Args.getLastArgValue(OPT_ftrap_function_EQ);
Rafael Espindola66aa0452012-06-19 01:26:10 +0000917 Opts.UseInitArray = Args.hasArg(OPT_fuse_init_array);
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000918
Nick Lewycky3a410fe2013-10-11 03:35:10 +0000919 Opts.FunctionSections = Args.hasFlag(OPT_ffunction_sections,
920 OPT_fno_function_sections, false);
921 Opts.DataSections = Args.hasFlag(OPT_fdata_sections,
922 OPT_fno_data_sections, false);
Sean Eveson5110d4f2018-01-08 13:42:26 +0000923 Opts.StackSizeSection =
924 Args.hasFlag(OPT_fstack_size_section, OPT_fno_stack_size_section, false);
Rafael Espindola6b07a1c2015-02-20 18:08:57 +0000925 Opts.UniqueSectionNames = Args.hasFlag(OPT_funique_section_names,
926 OPT_fno_unique_section_names, true);
927
Nick Lewyckyf04f2372014-10-24 00:49:29 +0000928 Opts.MergeFunctions = Args.hasArg(OPT_fmerge_functions);
Chris Lattnerdc6040b2010-04-13 00:38:24 +0000929
Nirav Daved2f44d82016-04-05 17:50:43 +0000930 Opts.NoUseJumpTables = Args.hasArg(OPT_fno_jump_tables);
931
Manoj Guptada08f6a2018-07-19 00:44:52 +0000932 Opts.NullPointerIsValid = Args.hasArg(OPT_fno_delete_null_pointer_checks);
933
Dehao Chen5e97f232017-08-24 21:37:33 +0000934 Opts.ProfileSampleAccurate = Args.hasArg(OPT_fprofile_sample_accurate);
935
Teresa Johnson945bc502015-10-15 20:35:53 +0000936 Opts.PrepareForLTO = Args.hasArg(OPT_flto, OPT_flto_EQ);
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000937 Opts.PrepareForThinLTO = false;
Yuka Takahashi50a9dfa2017-06-14 15:37:11 +0000938 if (Arg *A = Args.getLastArg(OPT_flto_EQ)) {
939 StringRef S = A->getValue();
940 if (S == "thin")
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000941 Opts.PrepareForThinLTO = true;
Yuka Takahashi50a9dfa2017-06-14 15:37:11 +0000942 else if (S != "full")
943 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << S;
944 }
Peter Collingbourne1e1475a2017-01-18 23:55:27 +0000945 Opts.LTOUnit = Args.hasFlag(OPT_flto_unit, OPT_fno_lto_unit, false);
Teresa Johnson84cecfc2019-01-11 18:32:07 +0000946 Opts.EnableSplitLTOUnit = Args.hasArg(OPT_fsplit_lto_unit);
Teresa Johnsonaff22322015-12-07 19:21:34 +0000947 if (Arg *A = Args.getLastArg(OPT_fthinlto_index_EQ)) {
Rainer Orth09d890d2019-08-05 13:59:26 +0000948 if (IK.getLanguage() != Language::LLVM_IR)
Teresa Johnsonaff22322015-12-07 19:21:34 +0000949 Diags.Report(diag::err_drv_argument_only_allowed_with)
950 << A->getAsString(Args) << "-x ir";
951 Opts.ThinLTOIndexFile = Args.getLastArgValue(OPT_fthinlto_index_EQ);
952 }
Teresa Johnson9e4321c2018-04-17 16:39:25 +0000953 if (Arg *A = Args.getLastArg(OPT_save_temps_EQ))
954 Opts.SaveTempsFilePrefix =
955 llvm::StringSwitch<std::string>(A->getValue())
956 .Case("obj", FrontendOpts.OutputFile)
957 .Default(llvm::sys::path::filename(FrontendOpts.OutputFile).str());
958
Teresa Johnson488d1dc2017-03-23 19:47:49 +0000959 Opts.ThinLinkBitcodeFile = Args.getLastArgValue(OPT_fthin_link_bitcode_EQ);
Teresa Johnson8749d8042015-07-06 16:23:00 +0000960
David Majnemera5b195a2015-02-14 01:35:12 +0000961 Opts.MSVolatile = Args.hasArg(OPT_fms_volatile);
962
Nick Lewyckyd3f3e4f2013-06-25 01:49:44 +0000963 Opts.VectorizeLoop = Args.hasArg(OPT_vectorize_loops);
964 Opts.VectorizeSLP = Args.hasArg(OPT_vectorize_slp);
965
Craig Topper9a724aa2017-12-11 21:09:19 +0000966 Opts.PreferVectorWidth = Args.getLastArgValue(OPT_mprefer_vector_width_EQ);
967
Daniel Dunbar37300482010-05-20 16:54:55 +0000968 Opts.MainFileName = Args.getLastArgValue(OPT_main_file_name);
John McCallcfcb7752010-02-12 23:47:27 +0000969 Opts.VerifyModule = !Args.hasArg(OPT_disable_llvm_verifier);
Daniel Dunbarfca18c1b42010-04-24 17:56:46 +0000970
Adrian McCarthydb2736d2018-01-09 23:49:30 +0000971 Opts.ControlFlowGuard = Args.hasArg(OPT_cfguard);
972
Nick Lewyckyc02bbb62013-03-20 01:38:16 +0000973 Opts.DisableGCov = Args.hasArg(OPT_test_coverage);
Nick Lewycky207bce32011-04-21 23:44:07 +0000974 Opts.EmitGcovArcs = Args.hasArg(OPT_femit_coverage_data);
975 Opts.EmitGcovNotes = Args.hasArg(OPT_femit_coverage_notes);
Nick Lewycky737a4522013-03-07 08:28:53 +0000976 if (Opts.EmitGcovArcs || Opts.EmitGcovNotes) {
Nick Lewycky97e49ac2016-08-31 23:04:32 +0000977 Opts.CoverageDataFile = Args.getLastArgValue(OPT_coverage_data_file);
978 Opts.CoverageNotesFile = Args.getLastArgValue(OPT_coverage_notes_file);
Nick Lewycky737a4522013-03-07 08:28:53 +0000979 Opts.CoverageExtraChecksum = Args.hasArg(OPT_coverage_cfg_checksum);
Nick Lewycky6f15b2902013-03-20 02:14:38 +0000980 Opts.CoverageNoFunctionNamesInData =
981 Args.hasArg(OPT_coverage_no_function_names_in_data);
Calixte Denizetf4bf6712018-11-17 19:41:39 +0000982 Opts.ProfileFilterFiles =
983 Args.getLastArgValue(OPT_fprofile_filter_files_EQ);
984 Opts.ProfileExcludeFiles =
985 Args.getLastArgValue(OPT_fprofile_exclude_files_EQ);
Justin Bogner4e462372015-03-16 23:52:21 +0000986 Opts.CoverageExitBlockBeforeBody =
987 Args.hasArg(OPT_coverage_exit_block_before_body);
Nick Lewycky737a4522013-03-07 08:28:53 +0000988 if (Args.hasArg(OPT_coverage_version_EQ)) {
989 StringRef CoverageVersion = Args.getLastArgValue(OPT_coverage_version_EQ);
990 if (CoverageVersion.size() != 4) {
991 Diags.Report(diag::err_drv_invalid_value)
992 << Args.getLastArg(OPT_coverage_version_EQ)->getAsString(Args)
993 << CoverageVersion;
994 } else {
Nick Lewyckyc8bf8242013-03-14 05:14:01 +0000995 memcpy(Opts.CoverageVersion, CoverageVersion.data(), 4);
Nick Lewycky737a4522013-03-07 08:28:53 +0000996 }
997 }
998 }
Fangrui Song99337e22018-07-20 08:19:20 +0000999 // Handle -fembed-bitcode option.
Steven Wu27fb5222016-05-11 16:26:03 +00001000 if (Arg *A = Args.getLastArg(OPT_fembed_bitcode_EQ)) {
1001 StringRef Name = A->getValue();
1002 unsigned Model = llvm::StringSwitch<unsigned>(Name)
1003 .Case("off", CodeGenOptions::Embed_Off)
1004 .Case("all", CodeGenOptions::Embed_All)
1005 .Case("bitcode", CodeGenOptions::Embed_Bitcode)
1006 .Case("marker", CodeGenOptions::Embed_Marker)
1007 .Default(~0U);
1008 if (Model == ~0U) {
1009 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
1010 Success = false;
1011 } else
1012 Opts.setEmbedBitcode(
1013 static_cast<CodeGenOptions::EmbedBitcodeKind>(Model));
1014 }
1015 // FIXME: For backend options that are not yet recorded as function
1016 // attributes in the IR, keep track of them so we can embed them in a
1017 // separate data section and use them when building the bitcode.
1018 if (Opts.getEmbedBitcode() == CodeGenOptions::Embed_All) {
1019 for (const auto &A : Args) {
1020 // Do not encode output and input.
1021 if (A->getOption().getID() == options::OPT_o ||
1022 A->getOption().getID() == options::OPT_INPUT ||
1023 A->getOption().getID() == options::OPT_x ||
1024 A->getOption().getID() == options::OPT_fembed_bitcode ||
1025 (A->getOption().getGroup().isValid() &&
1026 A->getOption().getGroup().getID() == options::OPT_W_Group))
1027 continue;
1028 ArgStringList ASL;
1029 A->render(Args, ASL);
1030 for (const auto &arg : ASL) {
1031 StringRef ArgStr(arg);
1032 Opts.CmdArgs.insert(Opts.CmdArgs.end(), ArgStr.begin(), ArgStr.end());
Raphael Isemannb23ccec2018-12-10 12:37:46 +00001033 // using \00 to separate each commandline options.
Steven Wu27fb5222016-05-11 16:26:03 +00001034 Opts.CmdArgs.push_back('\0');
1035 }
1036 }
1037 }
Nick Lewycky737a4522013-03-07 08:28:53 +00001038
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001039 Opts.PreserveVec3Type = Args.hasArg(OPT_fpreserve_vec3_type);
Nick Lewycky737a4522013-03-07 08:28:53 +00001040 Opts.InstrumentFunctions = Args.hasArg(OPT_finstrument_functions);
Hans Wennborg76c26c12017-11-14 21:13:27 +00001041 Opts.InstrumentFunctionsAfterInlining =
1042 Args.hasArg(OPT_finstrument_functions_after_inlining);
Hans Wennborg14e8a5a2017-11-21 17:30:34 +00001043 Opts.InstrumentFunctionEntryBare =
1044 Args.hasArg(OPT_finstrument_function_entry_bare);
Dean Michael Berris488f7c22018-04-13 02:31:58 +00001045
1046 Opts.XRayInstrumentFunctions =
1047 Args.hasArg(OPT_fxray_instrument);
Dean Michael Berris1a5b10d2017-11-30 00:04:54 +00001048 Opts.XRayAlwaysEmitCustomEvents =
1049 Args.hasArg(OPT_fxray_always_emit_customevents);
Keith Wyssf437e352018-04-17 21:32:43 +00001050 Opts.XRayAlwaysEmitTypedEvents =
1051 Args.hasArg(OPT_fxray_always_emit_typedevents);
Aaron Ballman7d2aecb2016-07-13 22:32:15 +00001052 Opts.XRayInstructionThreshold =
Dean Michael Berris504fc222017-03-30 22:46:45 +00001053 getLastArgIntValue(Args, OPT_fxray_instruction_threshold_EQ, 200, Diags);
Dean Michael Berris488f7c22018-04-13 02:31:58 +00001054
1055 auto XRayInstrBundles =
1056 Args.getAllArgValues(OPT_fxray_instrumentation_bundle);
1057 if (XRayInstrBundles.empty())
1058 Opts.XRayInstrumentationBundle.Mask = XRayInstrKind::All;
1059 else
1060 for (const auto &A : XRayInstrBundles)
1061 parseXRayInstrumentationBundle("-fxray-instrumentation-bundle=", A, Args,
1062 Diags, Opts.XRayInstrumentationBundle);
1063
Nick Lewycky737a4522013-03-07 08:28:53 +00001064 Opts.InstrumentForProfiling = Args.hasArg(OPT_pg);
Nirav Dave0c86ccf2017-01-31 17:00:35 +00001065 Opts.CallFEntry = Args.hasArg(OPT_mfentry);
Nick Lewycky737a4522013-03-07 08:28:53 +00001066 Opts.EmitOpenCLArgMetadata = Args.hasArg(OPT_cl_kernel_arg_info);
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00001067
Oren Ben Simhon57cc1a52018-01-09 08:53:59 +00001068 if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
1069 StringRef Name = A->getValue();
1070 if (Name == "full") {
1071 Opts.CFProtectionReturn = 1;
1072 Opts.CFProtectionBranch = 1;
1073 } else if (Name == "return")
1074 Opts.CFProtectionReturn = 1;
1075 else if (Name == "branch")
1076 Opts.CFProtectionBranch = 1;
1077 else if (Name != "none") {
1078 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
1079 Success = false;
1080 }
1081 }
1082
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00001083 if (const Arg *A = Args.getLastArg(OPT_compress_debug_sections,
1084 OPT_compress_debug_sections_EQ)) {
1085 if (A->getOption().getID() == OPT_compress_debug_sections) {
Eric Christopher030b17d2019-05-14 19:40:42 +00001086 // TODO: be more clever about the compression type auto-detection
1087 Opts.setCompressDebugSections(llvm::DebugCompressionType::GNU);
Saleem Abdulrasoold064e912017-06-23 15:34:16 +00001088 } else {
1089 auto DCT = llvm::StringSwitch<llvm::DebugCompressionType>(A->getValue())
1090 .Case("none", llvm::DebugCompressionType::None)
1091 .Case("zlib", llvm::DebugCompressionType::Z)
1092 .Case("zlib-gnu", llvm::DebugCompressionType::GNU)
1093 .Default(llvm::DebugCompressionType::None);
1094 Opts.setCompressDebugSections(DCT);
1095 }
1096 }
1097
Rafael Espindolaf8f01c32016-05-29 02:01:14 +00001098 Opts.RelaxELFRelocations = Args.hasArg(OPT_mrelax_relocations);
Nick Lewyckyba743b72011-10-21 02:32:14 +00001099 Opts.DebugCompilationDir = Args.getLastArgValue(OPT_fdebug_compilation_dir);
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001100 for (auto *A :
Matt Arsenaulta13746b2018-08-20 18:16:48 +00001101 Args.filtered(OPT_mlink_bitcode_file, OPT_mlink_builtin_bitcode)) {
Justin Lebarb080b632017-01-25 21:29:48 +00001102 CodeGenOptions::BitcodeFileToLink F;
1103 F.Filename = A->getValue();
Matt Arsenaulta13746b2018-08-20 18:16:48 +00001104 if (A->getOption().matches(OPT_mlink_builtin_bitcode)) {
Jonas Devlieghere5eb9c812017-03-13 18:08:11 +00001105 F.LinkFlags = llvm::Linker::Flags::LinkOnlyNeeded;
Justin Lebarb080b632017-01-25 21:29:48 +00001106 // When linking CUDA bitcode, propagate function attributes so that
1107 // e.g. libdevice gets fast-math attrs if we're building with fast-math.
1108 F.PropagateAttrs = true;
Jonas Devlieghere5eb9c812017-03-13 18:08:11 +00001109 F.Internalize = true;
Justin Lebarb080b632017-01-25 21:29:48 +00001110 }
1111 Opts.LinkBitcodeFiles.push_back(F);
Artem Belevich5d40ae32015-10-27 17:56:59 +00001112 }
Alexey Samsonov3f3b3ab2015-05-07 18:31:29 +00001113 Opts.SanitizeCoverageType =
1114 getLastArgIntValue(Args, OPT_fsanitize_coverage_type, 0, Diags);
1115 Opts.SanitizeCoverageIndirectCalls =
1116 Args.hasArg(OPT_fsanitize_coverage_indirect_calls);
1117 Opts.SanitizeCoverageTraceBB = Args.hasArg(OPT_fsanitize_coverage_trace_bb);
1118 Opts.SanitizeCoverageTraceCmp = Args.hasArg(OPT_fsanitize_coverage_trace_cmp);
Kostya Serebryany3b419712016-08-30 01:27:03 +00001119 Opts.SanitizeCoverageTraceDiv = Args.hasArg(OPT_fsanitize_coverage_trace_div);
1120 Opts.SanitizeCoverageTraceGep = Args.hasArg(OPT_fsanitize_coverage_trace_gep);
Alexey Samsonov3f3b3ab2015-05-07 18:31:29 +00001121 Opts.SanitizeCoverage8bitCounters =
1122 Args.hasArg(OPT_fsanitize_coverage_8bit_counters);
Kostya Serebryanyd4590c72016-02-17 21:34:43 +00001123 Opts.SanitizeCoverageTracePC = Args.hasArg(OPT_fsanitize_coverage_trace_pc);
Kostya Serebryany60cdd612016-09-14 01:39:49 +00001124 Opts.SanitizeCoverageTracePCGuard =
1125 Args.hasArg(OPT_fsanitize_coverage_trace_pc_guard);
Kostya Serebryany50fb6182017-05-05 23:28:18 +00001126 Opts.SanitizeCoverageNoPrune = Args.hasArg(OPT_fsanitize_coverage_no_prune);
Kostya Serebryany2c2fb882017-06-08 22:58:19 +00001127 Opts.SanitizeCoverageInline8bitCounters =
1128 Args.hasArg(OPT_fsanitize_coverage_inline_8bit_counters);
Kostya Serebryany61457762017-07-28 00:10:10 +00001129 Opts.SanitizeCoveragePCTable = Args.hasArg(OPT_fsanitize_coverage_pc_table);
Matt Morehouse5c7fc762017-08-18 18:43:30 +00001130 Opts.SanitizeCoverageStackDepth =
1131 Args.hasArg(OPT_fsanitize_coverage_stack_depth);
Alexey Samsonov29524a92013-01-20 13:12:12 +00001132 Opts.SanitizeMemoryTrackOrigins =
Evgeniy Stepanov2bfcaab2014-03-20 14:58:36 +00001133 getLastArgIntValue(Args, OPT_fsanitize_memory_track_origins_EQ, 0, Diags);
Evgeniy Stepanov45be9e02015-07-10 20:07:16 +00001134 Opts.SanitizeMemoryUseAfterDtor =
Matt Morehousebb26f862017-09-14 23:14:37 +00001135 Args.hasFlag(OPT_fsanitize_memory_use_after_dtor,
1136 OPT_fno_sanitize_memory_use_after_dtor,
1137 false);
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +00001138 Opts.SanitizeMinimalRuntime = Args.hasArg(OPT_fsanitize_minimal_runtime);
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001139 Opts.SanitizeCfiCrossDso = Args.hasArg(OPT_fsanitize_cfi_cross_dso);
Vlad Tsyrklevich634c6012017-10-31 22:39:44 +00001140 Opts.SanitizeCfiICallGeneralizePointers =
1141 Args.hasArg(OPT_fsanitize_cfi_icall_generalize_pointers);
Peter Collingbournedc134532016-01-16 00:31:22 +00001142 Opts.SanitizeStats = Args.hasArg(OPT_fsanitize_stats);
Filipe Cabecinhas4ba58172018-02-12 11:49:02 +00001143 if (Arg *A = Args.getLastArg(
Filipe Cabecinhas0eb50082018-11-02 17:29:04 +00001144 OPT_fsanitize_address_poison_custom_array_cookie,
1145 OPT_fno_sanitize_address_poison_custom_array_cookie)) {
1146 Opts.SanitizeAddressPoisonCustomArrayCookie =
Filipe Cabecinhas4ba58172018-02-12 11:49:02 +00001147 A->getOption().getID() ==
Filipe Cabecinhas0eb50082018-11-02 17:29:04 +00001148 OPT_fsanitize_address_poison_custom_array_cookie;
Filipe Cabecinhas4ba58172018-02-12 11:49:02 +00001149 }
Vitaly Bukaa77ac1b2016-10-10 21:31:50 +00001150 if (Arg *A = Args.getLastArg(OPT_fsanitize_address_use_after_scope,
1151 OPT_fno_sanitize_address_use_after_scope)) {
1152 Opts.SanitizeAddressUseAfterScope =
1153 A->getOption().getID() == OPT_fsanitize_address_use_after_scope;
1154 }
Evgeniy Stepanovd991cdd2017-05-09 21:57:43 +00001155 Opts.SanitizeAddressGlobalsDeadStripping =
1156 Args.hasArg(OPT_fsanitize_address_globals_dead_stripping);
Vitaly Buka8076c572018-12-05 01:44:31 +00001157 if (Arg *A = Args.getLastArg(OPT_fsanitize_address_use_odr_indicator,
1158 OPT_fno_sanitize_address_use_odr_indicator)) {
1159 Opts.SanitizeAddressUseOdrIndicator =
1160 A->getOption().getID() == OPT_fsanitize_address_use_odr_indicator;
1161 }
Chad Rosierdb3da832012-08-21 16:16:06 +00001162 Opts.SSPBufferSize =
Reid Kleckner898229a2013-06-14 17:17:23 +00001163 getLastArgIntValue(Args, OPT_stack_protector_buffer_size, 8, Diags);
Nick Lewyckyf4d3f7a2011-12-06 03:33:03 +00001164 Opts.StackRealignment = Args.hasArg(OPT_mstackrealign);
Joerg Sonnenbergerdb66ed02011-12-05 23:05:23 +00001165 if (Arg *A = Args.getLastArg(OPT_mstack_alignment)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001166 StringRef Val = A->getValue();
Douglas Gregorb0eea8b2012-10-23 20:05:01 +00001167 unsigned StackAlignment = Opts.StackAlignment;
1168 Val.getAsInteger(10, StackAlignment);
1169 Opts.StackAlignment = StackAlignment;
Joerg Sonnenbergerdb66ed02011-12-05 23:05:23 +00001170 }
Chris Lattner3c77a352010-06-22 00:03:40 +00001171
Hans Wennborg77dc2362015-01-20 19:45:50 +00001172 if (Arg *A = Args.getLastArg(OPT_mstack_probe_size)) {
1173 StringRef Val = A->getValue();
1174 unsigned StackProbeSize = Opts.StackProbeSize;
1175 Val.getAsInteger(0, StackProbeSize);
1176 Opts.StackProbeSize = StackProbeSize;
1177 }
1178
Hans Wennborgd43f40d2018-02-23 13:47:36 +00001179 Opts.NoStackArgProbe = Args.hasArg(OPT_mno_stack_arg_probe);
1180
Daniel Dunbarfca18c1b42010-04-24 17:56:46 +00001181 if (Arg *A = Args.getLastArg(OPT_fobjc_dispatch_method_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001182 StringRef Name = A->getValue();
Daniel Dunbarfca18c1b42010-04-24 17:56:46 +00001183 unsigned Method = llvm::StringSwitch<unsigned>(Name)
1184 .Case("legacy", CodeGenOptions::Legacy)
1185 .Case("non-legacy", CodeGenOptions::NonLegacy)
1186 .Case("mixed", CodeGenOptions::Mixed)
1187 .Default(~0U);
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00001188 if (Method == ~0U) {
Daniel Dunbarfca18c1b42010-04-24 17:56:46 +00001189 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00001190 Success = false;
1191 } else {
Douglas Gregorb0eea8b2012-10-23 20:05:01 +00001192 Opts.setObjCDispatchMethod(
1193 static_cast<CodeGenOptions::ObjCDispatchMethodKind>(Method));
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00001194 }
Daniel Dunbarfca18c1b42010-04-24 17:56:46 +00001195 }
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00001196
Pete Coopere3886802018-12-08 05:13:50 +00001197
1198 if (Args.hasArg(OPT_fno_objc_convert_messages_to_runtime_calls))
1199 Opts.ObjCConvertMessagesToRuntimeCalls = 0;
1200
Chih-Hung Hsiehca552b82018-03-01 22:26:19 +00001201 if (Args.getLastArg(OPT_femulated_tls) ||
1202 Args.getLastArg(OPT_fno_emulated_tls)) {
1203 Opts.ExplicitEmulatedTLS = true;
1204 Opts.EmulatedTLS =
1205 Args.hasFlag(OPT_femulated_tls, OPT_fno_emulated_tls, false);
1206 }
Chih-Hung Hsieh2c656c92015-07-28 16:27:56 +00001207
Hans Wennborgf60f6af2012-06-28 08:01:44 +00001208 if (Arg *A = Args.getLastArg(OPT_ftlsmodel_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001209 StringRef Name = A->getValue();
Hans Wennborgf60f6af2012-06-28 08:01:44 +00001210 unsigned Model = llvm::StringSwitch<unsigned>(Name)
1211 .Case("global-dynamic", CodeGenOptions::GeneralDynamicTLSModel)
1212 .Case("local-dynamic", CodeGenOptions::LocalDynamicTLSModel)
1213 .Case("initial-exec", CodeGenOptions::InitialExecTLSModel)
1214 .Case("local-exec", CodeGenOptions::LocalExecTLSModel)
1215 .Default(~0U);
1216 if (Model == ~0U) {
1217 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
1218 Success = false;
1219 } else {
Douglas Gregorb0eea8b2012-10-23 20:05:01 +00001220 Opts.setDefaultTLSModel(static_cast<CodeGenOptions::TLSModel>(Model));
Hans Wennborgf60f6af2012-06-28 08:01:44 +00001221 }
1222 }
1223
Sjoerd Meijer0a8d4212016-08-30 08:09:45 +00001224 if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_EQ)) {
1225 StringRef Val = A->getValue();
1226 if (Val == "ieee")
1227 Opts.FPDenormalMode = "ieee";
1228 else if (Val == "preserve-sign")
1229 Opts.FPDenormalMode = "preserve-sign";
1230 else if (Val == "positive-zero")
1231 Opts.FPDenormalMode = "positive-zero";
1232 else
1233 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
1234 }
1235
John McCall1fe2a8c2013-06-18 02:46:29 +00001236 if (Arg *A = Args.getLastArg(OPT_fpcc_struct_return, OPT_freg_struct_return)) {
1237 if (A->getOption().matches(OPT_fpcc_struct_return)) {
1238 Opts.setStructReturnConvention(CodeGenOptions::SRCK_OnStack);
1239 } else {
1240 assert(A->getOption().matches(OPT_freg_struct_return));
1241 Opts.setStructReturnConvention(CodeGenOptions::SRCK_InRegs);
1242 }
1243 }
1244
Hans Wennborg75958c42013-08-08 00:17:41 +00001245 Opts.DependentLibraries = Args.getAllArgValues(OPT_dependent_lib);
Peter Collingbournedc134532016-01-16 00:31:22 +00001246 Opts.LinkerOptions = Args.getAllArgValues(OPT_linker_option);
Diego Novillo913690c2014-06-24 17:02:17 +00001247 bool NeedLocTracking = false;
Hans Wennborg75958c42013-08-08 00:17:41 +00001248
Hal Finkel8f96e822016-10-11 00:26:09 +00001249 Opts.OptRecordFile = Args.getLastArgValue(OPT_opt_record_file);
1250 if (!Opts.OptRecordFile.empty())
1251 NeedLocTracking = true;
1252
Francis Visoiu Mistrihdd422362019-03-12 21:22:27 +00001253 if (Arg *A = Args.getLastArg(OPT_opt_record_passes)) {
1254 Opts.OptRecordPasses = A->getValue();
1255 NeedLocTracking = true;
1256 }
1257
Francis Visoiu Mistrih34667512019-06-17 16:06:00 +00001258 if (Arg *A = Args.getLastArg(OPT_opt_record_format)) {
1259 Opts.OptRecordFormat = A->getValue();
1260 NeedLocTracking = true;
1261 }
1262
Diego Novillo913690c2014-06-24 17:02:17 +00001263 if (Arg *A = Args.getLastArg(OPT_Rpass_EQ)) {
Diego Novillod23ec942014-05-29 19:55:06 +00001264 Opts.OptimizationRemarkPattern =
1265 GenerateOptimizationRemarkRegex(Diags, Args, A);
Diego Novillo913690c2014-06-24 17:02:17 +00001266 NeedLocTracking = true;
1267 }
Diego Novillod23ec942014-05-29 19:55:06 +00001268
Diego Novillo913690c2014-06-24 17:02:17 +00001269 if (Arg *A = Args.getLastArg(OPT_Rpass_missed_EQ)) {
Diego Novillod23ec942014-05-29 19:55:06 +00001270 Opts.OptimizationRemarkMissedPattern =
1271 GenerateOptimizationRemarkRegex(Diags, Args, A);
Diego Novillo913690c2014-06-24 17:02:17 +00001272 NeedLocTracking = true;
1273 }
Diego Novillod23ec942014-05-29 19:55:06 +00001274
Diego Novillo913690c2014-06-24 17:02:17 +00001275 if (Arg *A = Args.getLastArg(OPT_Rpass_analysis_EQ)) {
Diego Novillod23ec942014-05-29 19:55:06 +00001276 Opts.OptimizationRemarkAnalysisPattern =
1277 GenerateOptimizationRemarkRegex(Diags, Args, A);
Diego Novillo913690c2014-06-24 17:02:17 +00001278 NeedLocTracking = true;
1279 }
1280
Adam Nemet1eea3e52016-09-13 04:32:40 +00001281 Opts.DiagnosticsWithHotness =
1282 Args.hasArg(options::OPT_fdiagnostics_show_hotness);
Brian Gesiak0ea58882017-06-23 02:38:45 +00001283 bool UsingSampleProfile = !Opts.SampleProfileFile.empty();
Brian Gesiak562eab92017-07-01 05:45:26 +00001284 bool UsingProfile = UsingSampleProfile ||
1285 (Opts.getProfileUse() != CodeGenOptions::ProfileNone);
Brian Gesiak0ea58882017-06-23 02:38:45 +00001286
Teresa Johnson66744f82018-05-05 14:37:29 +00001287 if (Opts.DiagnosticsWithHotness && !UsingProfile &&
1288 // An IR file will contain PGO as metadata
Rainer Orth09d890d2019-08-05 13:59:26 +00001289 IK.getLanguage() != Language::LLVM_IR)
Brian Gesiak562eab92017-07-01 05:45:26 +00001290 Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
1291 << "-fdiagnostics-show-hotness";
1292
1293 Opts.DiagnosticsHotnessThreshold = getLastArgUInt64Value(
1294 Args, options::OPT_fdiagnostics_hotness_threshold_EQ, 0);
1295 if (Opts.DiagnosticsHotnessThreshold > 0 && !UsingProfile)
1296 Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
1297 << "-fdiagnostics-hotness-threshold=";
Adam Nemet1eea3e52016-09-13 04:32:40 +00001298
Diego Novillo795f53b2014-10-22 13:00:05 +00001299 // If the user requested to use a sample profile for PGO, then the
1300 // backend will need to track source location information so the profile
1301 // can be incorporated into the IR.
Brian Gesiak0ea58882017-06-23 02:38:45 +00001302 if (UsingSampleProfile)
Diego Novillo795f53b2014-10-22 13:00:05 +00001303 NeedLocTracking = true;
1304
1305 // If the user requested a flag that requires source locations available in
1306 // the backend, make sure that the backend tracks source location information.
Benjamin Kramer8c305922016-02-02 11:06:51 +00001307 if (NeedLocTracking && Opts.getDebugInfo() == codegenoptions::NoDebugInfo)
1308 Opts.setDebugInfo(codegenoptions::LocTrackingOnly);
Diego Novillod23ec942014-05-29 19:55:06 +00001309
Saleem Abdulrasool76a4b952015-01-09 05:10:20 +00001310 Opts.RewriteMapFiles = Args.getAllArgValues(OPT_frewrite_map_file);
1311
Alexey Samsonov88459522015-01-12 22:39:12 +00001312 // Parse -fsanitize-recover= arguments.
1313 // FIXME: Report unrecoverable sanitizers incorrectly specified here.
1314 parseSanitizerKinds("-fsanitize-recover=",
1315 Args.getAllArgValues(OPT_fsanitize_recover_EQ), Diags,
1316 Opts.SanitizeRecover);
Peter Collingbourne9881b782015-06-18 23:59:22 +00001317 parseSanitizerKinds("-fsanitize-trap=",
1318 Args.getAllArgValues(OPT_fsanitize_trap_EQ), Diags,
1319 Opts.SanitizeTrap);
Alexey Samsonov88459522015-01-12 22:39:12 +00001320
Jonas Hahnfelde7681322018-02-28 17:53:46 +00001321 Opts.CudaGpuBinaryFileName =
1322 Args.getLastArgValue(OPT_fcuda_include_gpubinary);
Artem Belevich52cc4872015-05-07 19:34:16 +00001323
Marcin Koscielnickib31ee6d2016-05-04 23:37:40 +00001324 Opts.Backchain = Args.hasArg(OPT_mbackchain);
1325
Filipe Cabecinhasab731f72016-05-12 16:51:36 +00001326 Opts.EmitCheckPathComponentsToStrip = getLastArgIntValue(
1327 Args, OPT_fsanitize_undefined_strip_path_components_EQ, 0, Diags);
1328
Mikhail Maltsev4a4e7a32018-04-23 10:08:46 +00001329 Opts.EmitVersionIdentMetadata = Args.hasFlag(OPT_Qy, OPT_Qn, true);
1330
Peter Collingbourne14b468b2018-07-18 00:27:07 +00001331 Opts.Addrsig = Args.hasArg(OPT_faddrsig);
1332
Luke Cheesemana8a24aa2018-10-25 15:23:49 +00001333 if (Arg *A = Args.getLastArg(OPT_msign_return_address_EQ)) {
Luke Cheeseman0ac44c12018-08-17 12:55:05 +00001334 StringRef SignScope = A->getValue();
Luke Cheesemana8a24aa2018-10-25 15:23:49 +00001335
Luke Cheeseman0ac44c12018-08-17 12:55:05 +00001336 if (SignScope.equals_lower("none"))
1337 Opts.setSignReturnAddress(CodeGenOptions::SignReturnAddressScope::None);
1338 else if (SignScope.equals_lower("all"))
1339 Opts.setSignReturnAddress(CodeGenOptions::SignReturnAddressScope::All);
1340 else if (SignScope.equals_lower("non-leaf"))
1341 Opts.setSignReturnAddress(
1342 CodeGenOptions::SignReturnAddressScope::NonLeaf);
1343 else
1344 Diags.Report(diag::err_drv_invalid_value)
Luke Cheesemana8a24aa2018-10-25 15:23:49 +00001345 << A->getAsString(Args) << SignScope;
1346
1347 if (Arg *A = Args.getLastArg(OPT_msign_return_address_key_EQ)) {
1348 StringRef SignKey = A->getValue();
1349 if (!SignScope.empty() && !SignKey.empty()) {
1350 if (SignKey.equals_lower("a_key"))
1351 Opts.setSignReturnAddressKey(
1352 CodeGenOptions::SignReturnAddressKeyValue::AKey);
1353 else if (SignKey.equals_lower("b_key"))
1354 Opts.setSignReturnAddressKey(
1355 CodeGenOptions::SignReturnAddressKeyValue::BKey);
1356 else
1357 Diags.Report(diag::err_drv_invalid_value)
1358 << A->getAsString(Args) << SignKey;
1359 }
1360 }
Luke Cheeseman0ac44c12018-08-17 12:55:05 +00001361 }
1362
Luke Cheesemana8a24aa2018-10-25 15:23:49 +00001363 Opts.BranchTargetEnforcement = Args.hasArg(OPT_mbranch_target_enforce);
1364
Elizabeth Andrews6593df22018-08-22 19:05:19 +00001365 Opts.KeepStaticConsts = Args.hasArg(OPT_fkeep_static_consts);
1366
Chandler Carruth664aa862018-09-04 12:38:00 +00001367 Opts.SpeculativeLoadHardening = Args.hasArg(OPT_mspeculative_load_hardening);
1368
Peter Collingbourne87f477b2019-01-04 19:27:04 +00001369 Opts.DefaultFunctionAttrs = Args.getAllArgValues(OPT_default_function_attr);
1370
Philip Pfaffee3f105c2019-02-02 23:19:32 +00001371 Opts.PassPlugins = Args.getAllArgValues(OPT_fpass_plugin_EQ);
1372
Peter Collingbournee08e68d2019-06-07 19:10:08 +00001373 Opts.SymbolPartition = Args.getLastArgValue(OPT_fsymbol_partition_EQ);
1374
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00001375 return Success;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001376}
1377
1378static void ParseDependencyOutputArgs(DependencyOutputOptions &Opts,
1379 ArgList &Args) {
Daniel Dunbar37300482010-05-20 16:54:55 +00001380 Opts.OutputFile = Args.getLastArgValue(OPT_dependency_file);
1381 Opts.Targets = Args.getAllArgValues(OPT_MT);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001382 Opts.IncludeSystemHeaders = Args.hasArg(OPT_sys_header_deps);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00001383 Opts.IncludeModuleFiles = Args.hasArg(OPT_module_file_deps);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001384 Opts.UsePhonyTargets = Args.hasArg(OPT_MP);
Daniel Dunbar27734fd2011-02-02 15:41:17 +00001385 Opts.ShowHeaderIncludes = Args.hasArg(OPT_H);
Daniel Dunbar1af1d27512011-02-02 21:11:31 +00001386 Opts.HeaderIncludeOutputFile = Args.getLastArgValue(OPT_header_include_file);
Peter Collingbourne77b0e7f22011-07-12 19:35:15 +00001387 Opts.AddMissingHeaderDeps = Args.hasArg(OPT_MG);
Erich Keane425f48d2018-05-04 15:58:31 +00001388 if (Args.hasArg(OPT_show_includes)) {
1389 // Writing both /showIncludes and preprocessor output to stdout
1390 // would produce interleaved output, so use stderr for /showIncludes.
1391 // This behaves the same as cl.exe, when /E, /EP or /P are passed.
1392 if (Args.hasArg(options::OPT_E) || Args.hasArg(options::OPT_P))
1393 Opts.ShowIncludesDest = ShowIncludesDestination::Stderr;
1394 else
1395 Opts.ShowIncludesDest = ShowIncludesDestination::Stdout;
1396 } else {
1397 Opts.ShowIncludesDest = ShowIncludesDestination::None;
1398 }
Douglas Gregor2e129652012-02-02 23:45:13 +00001399 Opts.DOTOutputFile = Args.getLastArgValue(OPT_dependency_dot);
Justin Bogner86d12592014-06-19 19:36:03 +00001400 Opts.ModuleDependencyOutputDir =
1401 Args.getLastArgValue(OPT_module_dependency_dir);
Paul Robinsond7214a72015-04-27 18:14:32 +00001402 if (Args.hasArg(OPT_MV))
1403 Opts.OutputFormat = DependencyOutputFormat::NMake;
Ivan Krasin1193f2c2015-08-13 04:04:37 +00001404 // Add sanitizer blacklists as extra dependencies.
1405 // They won't be discovered by the regular preprocessor, so
1406 // we let make / ninja to know about this implicit dependency.
Ivan Krasin4c3f2372015-09-02 20:02:38 +00001407 Opts.ExtraDeps = Args.getAllArgValues(OPT_fdepfile_entry);
Boris Kolpackovd30446f2017-08-31 06:26:43 +00001408 // Only the -fmodule-file=<file> form.
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001409 for (const auto *A : Args.filtered(OPT_fmodule_file)) {
Boris Kolpackovd30446f2017-08-31 06:26:43 +00001410 StringRef Val = A->getValue();
1411 if (Val.find('=') == StringRef::npos)
1412 Opts.ExtraDeps.push_back(Val);
1413 }
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001414}
1415
Bruno Cardoso Lopes681d7172016-05-27 20:43:00 +00001416static bool parseShowColorsArgs(const ArgList &Args, bool DefaultColor) {
1417 // Color diagnostics default to auto ("on" if terminal supports) in the driver
1418 // but default to off in cc1, needing an explicit OPT_fdiagnostics_color.
1419 // Support both clang's -f[no-]color-diagnostics and gcc's
1420 // -f[no-]diagnostics-colors[=never|always|auto].
1421 enum {
1422 Colors_On,
1423 Colors_Off,
1424 Colors_Auto
1425 } ShowColors = DefaultColor ? Colors_Auto : Colors_Off;
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001426 for (auto *A : Args) {
Bruno Cardoso Lopes681d7172016-05-27 20:43:00 +00001427 const Option &O = A->getOption();
Bruno Cardoso Lopes681d7172016-05-27 20:43:00 +00001428 if (O.matches(options::OPT_fcolor_diagnostics) ||
1429 O.matches(options::OPT_fdiagnostics_color)) {
1430 ShowColors = Colors_On;
1431 } else if (O.matches(options::OPT_fno_color_diagnostics) ||
1432 O.matches(options::OPT_fno_diagnostics_color)) {
1433 ShowColors = Colors_Off;
Yaron Keren9181e772016-12-10 14:55:14 +00001434 } else if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
Bruno Cardoso Lopes681d7172016-05-27 20:43:00 +00001435 StringRef Value(A->getValue());
1436 if (Value == "always")
1437 ShowColors = Colors_On;
1438 else if (Value == "never")
1439 ShowColors = Colors_Off;
1440 else if (Value == "auto")
1441 ShowColors = Colors_Auto;
1442 }
1443 }
Yaron Keren9181e772016-12-10 14:55:14 +00001444 return ShowColors == Colors_On ||
1445 (ShowColors == Colors_Auto &&
1446 llvm::sys::Process::StandardErrHasColors());
Bruno Cardoso Lopes681d7172016-05-27 20:43:00 +00001447}
1448
Hal Finkel05e46482017-12-16 02:23:22 +00001449static bool checkVerifyPrefixes(const std::vector<std::string> &VerifyPrefixes,
1450 DiagnosticsEngine *Diags) {
1451 bool Success = true;
1452 for (const auto &Prefix : VerifyPrefixes) {
1453 // Every prefix must start with a letter and contain only alphanumeric
1454 // characters, hyphens, and underscores.
Fangrui Song75e74e02019-03-31 08:48:19 +00001455 auto BadChar = llvm::find_if(Prefix, [](char C) {
1456 return !isAlphanumeric(C) && C != '-' && C != '_';
1457 });
Hal Finkel05e46482017-12-16 02:23:22 +00001458 if (BadChar != Prefix.end() || !isLetter(Prefix[0])) {
1459 Success = false;
1460 if (Diags) {
1461 Diags->Report(diag::err_drv_invalid_value) << "-verify=" << Prefix;
1462 Diags->Report(diag::note_drv_verify_prefix_spelling);
1463 }
1464 }
1465 }
1466 return Success;
1467}
1468
Chad Rosierd6f716a2012-03-13 20:09:56 +00001469bool clang::ParseDiagnosticArgs(DiagnosticOptions &Opts, ArgList &Args,
Bruno Cardoso Lopes681d7172016-05-27 20:43:00 +00001470 DiagnosticsEngine *Diags,
Bruno Cardoso Lopes76952a72016-10-11 18:21:26 +00001471 bool DefaultDiagColor, bool DefaultShowOpt) {
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00001472 bool Success = true;
1473
Daniel Dunbar6b584862011-04-07 18:11:14 +00001474 Opts.DiagnosticLogFile = Args.getLastArgValue(OPT_diagnostic_log_file);
Justin Bogner5a6a2fc2014-10-23 22:20:11 +00001475 if (Arg *A =
1476 Args.getLastArg(OPT_diagnostic_serialized_file, OPT__serialize_diags))
1477 Opts.DiagnosticSerializationFile = A->getValue();
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001478 Opts.IgnoreWarnings = Args.hasArg(OPT_w);
1479 Opts.NoRewriteMacros = Args.hasArg(OPT_Wno_rewrite_macros);
1480 Opts.Pedantic = Args.hasArg(OPT_pedantic);
1481 Opts.PedanticErrors = Args.hasArg(OPT_pedantic_errors);
1482 Opts.ShowCarets = !Args.hasArg(OPT_fno_caret_diagnostics);
Bruno Cardoso Lopes681d7172016-05-27 20:43:00 +00001483 Opts.ShowColors = parseShowColorsArgs(Args, DefaultDiagColor);
Douglas Gregor643c9222011-05-21 17:07:29 +00001484 Opts.ShowColumn = Args.hasFlag(OPT_fshow_column,
1485 OPT_fno_show_column,
1486 /*Default=*/true);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001487 Opts.ShowFixits = !Args.hasArg(OPT_fno_diagnostics_fixit_info);
1488 Opts.ShowLocation = !Args.hasArg(OPT_fno_show_source_location);
Hans Wennborgb30f4372016-08-26 15:45:36 +00001489 Opts.AbsolutePath = Args.hasArg(OPT_fdiagnostics_absolute_paths);
Bruno Cardoso Lopes76952a72016-10-11 18:21:26 +00001490 Opts.ShowOptionNames =
1491 Args.hasFlag(OPT_fdiagnostics_show_option,
1492 OPT_fno_diagnostics_show_option, DefaultShowOpt);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00001493
Nico Rieck7857d462013-09-11 00:38:02 +00001494 llvm::sys::Process::UseANSIEscapeCodes(Args.hasArg(OPT_fansi_escape_codes));
1495
Chandler Carruth24284af2011-03-27 20:00:08 +00001496 // Default behavior is to not to show note include stacks.
1497 Opts.ShowNoteIncludeStack = false;
Chandler Carruthb6766f02011-03-27 01:50:55 +00001498 if (Arg *A = Args.getLastArg(OPT_fdiagnostics_show_note_include_stack,
1499 OPT_fno_diagnostics_show_note_include_stack))
Chandler Carruth24284af2011-03-27 20:00:08 +00001500 if (A->getOption().matches(OPT_fdiagnostics_show_note_include_stack))
1501 Opts.ShowNoteIncludeStack = true;
Chandler Carruthb6766f02011-03-27 01:50:55 +00001502
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001503 StringRef ShowOverloads =
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00001504 Args.getLastArgValue(OPT_fshow_overloads_EQ, "all");
1505 if (ShowOverloads == "best")
Douglas Gregor79591782012-10-23 23:11:23 +00001506 Opts.setShowOverloads(Ovl_Best);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00001507 else if (ShowOverloads == "all")
Douglas Gregor79591782012-10-23 23:11:23 +00001508 Opts.setShowOverloads(Ovl_All);
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00001509 else {
Chad Rosierd6f716a2012-03-13 20:09:56 +00001510 Success = false;
1511 if (Diags)
1512 Diags->Report(diag::err_drv_invalid_value)
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00001513 << Args.getLastArg(OPT_fshow_overloads_EQ)->getAsString(Args)
1514 << ShowOverloads;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00001515 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00001516
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001517 StringRef ShowCategory =
Daniel Dunbar37300482010-05-20 16:54:55 +00001518 Args.getLastArgValue(OPT_fdiagnostics_show_category, "none");
Chris Lattnerbf6fac82010-05-04 21:55:25 +00001519 if (ShowCategory == "none")
1520 Opts.ShowCategories = 0;
1521 else if (ShowCategory == "id")
1522 Opts.ShowCategories = 1;
1523 else if (ShowCategory == "name")
1524 Opts.ShowCategories = 2;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00001525 else {
Chad Rosierd6f716a2012-03-13 20:09:56 +00001526 Success = false;
1527 if (Diags)
1528 Diags->Report(diag::err_drv_invalid_value)
Chris Lattnerbf6fac82010-05-04 21:55:25 +00001529 << Args.getLastArg(OPT_fdiagnostics_show_category)->getAsString(Args)
1530 << ShowCategory;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00001531 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00001532
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001533 StringRef Format =
Douglas Gregor643c9222011-05-21 17:07:29 +00001534 Args.getLastArgValue(OPT_fdiagnostics_format, "clang");
1535 if (Format == "clang")
Douglas Gregor79591782012-10-23 23:11:23 +00001536 Opts.setFormat(DiagnosticOptions::Clang);
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00001537 else if (Format == "msvc")
David Majnemer8ab003a2015-02-02 19:30:52 +00001538 Opts.setFormat(DiagnosticOptions::MSVC);
Hans Wennborgf4aee182013-09-24 00:08:55 +00001539 else if (Format == "msvc-fallback") {
David Majnemer8ab003a2015-02-02 19:30:52 +00001540 Opts.setFormat(DiagnosticOptions::MSVC);
Hans Wennborgf4aee182013-09-24 00:08:55 +00001541 Opts.CLFallbackMode = true;
1542 } else if (Format == "vi")
Douglas Gregor79591782012-10-23 23:11:23 +00001543 Opts.setFormat(DiagnosticOptions::Vi);
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00001544 else {
Chad Rosierd6f716a2012-03-13 20:09:56 +00001545 Success = false;
1546 if (Diags)
1547 Diags->Report(diag::err_drv_invalid_value)
Douglas Gregor643c9222011-05-21 17:07:29 +00001548 << Args.getLastArg(OPT_fdiagnostics_format)->getAsString(Args)
1549 << Format;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00001550 }
Eric Fiselier098e6de2015-06-13 07:11:40 +00001551
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001552 Opts.ShowSourceRanges = Args.hasArg(OPT_fdiagnostics_print_source_range_info);
Douglas Gregoreec975c2010-08-19 20:24:43 +00001553 Opts.ShowParseableFixits = Args.hasArg(OPT_fdiagnostics_parseable_fixits);
Richard Smith0b50cb72012-11-14 23:55:25 +00001554 Opts.ShowPresumedLoc = !Args.hasArg(OPT_fno_diagnostics_use_presumed_location);
Hal Finkel05e46482017-12-16 02:23:22 +00001555 Opts.VerifyDiagnostics = Args.hasArg(OPT_verify) || Args.hasArg(OPT_verify_EQ);
1556 Opts.VerifyPrefixes = Args.getAllArgValues(OPT_verify_EQ);
1557 if (Args.hasArg(OPT_verify))
1558 Opts.VerifyPrefixes.push_back("expected");
1559 // Keep VerifyPrefixes in its original order for the sake of diagnostics, and
1560 // then sort it to prepare for fast lookup using std::binary_search.
1561 if (!checkVerifyPrefixes(Opts.VerifyPrefixes, Diags)) {
1562 Opts.VerifyDiagnostics = false;
1563 Success = false;
1564 }
1565 else
Fangrui Song1d38c132018-09-30 21:41:11 +00001566 llvm::sort(Opts.VerifyPrefixes);
Eric Fiselier098e6de2015-06-13 07:11:40 +00001567 DiagnosticLevelMask DiagMask = DiagnosticLevelMask::None;
1568 Success &= parseDiagnosticLevelMask("-verify-ignore-unexpected=",
1569 Args.getAllArgValues(OPT_verify_ignore_unexpected_EQ),
1570 Diags, DiagMask);
1571 if (Args.hasArg(OPT_verify_ignore_unexpected))
1572 DiagMask = DiagnosticLevelMask::All;
1573 Opts.setVerifyIgnoreUnexpected(DiagMask);
Richard Trieu91844232012-06-26 18:18:47 +00001574 Opts.ElideType = !Args.hasArg(OPT_fno_elide_type);
1575 Opts.ShowTemplateTree = Args.hasArg(OPT_fdiagnostics_show_template_tree);
Reid Kleckner898229a2013-06-14 17:17:23 +00001576 Opts.ErrorLimit = getLastArgIntValue(Args, OPT_ferror_limit, 0, Diags);
1577 Opts.MacroBacktraceLimit =
1578 getLastArgIntValue(Args, OPT_fmacro_backtrace_limit,
Douglas Gregorcd121fb2010-05-04 17:13:42 +00001579 DiagnosticOptions::DefaultMacroBacktraceLimit, Diags);
Reid Kleckner898229a2013-06-14 17:17:23 +00001580 Opts.TemplateBacktraceLimit = getLastArgIntValue(
1581 Args, OPT_ftemplate_backtrace_limit,
1582 DiagnosticOptions::DefaultTemplateBacktraceLimit, Diags);
1583 Opts.ConstexprBacktraceLimit = getLastArgIntValue(
1584 Args, OPT_fconstexpr_backtrace_limit,
1585 DiagnosticOptions::DefaultConstexprBacktraceLimit, Diags);
Nick Lewycky24653262014-12-16 21:39:02 +00001586 Opts.SpellCheckingLimit = getLastArgIntValue(
1587 Args, OPT_fspell_checking_limit,
1588 DiagnosticOptions::DefaultSpellCheckingLimit, Diags);
Richard Smith0c7d4d7e2017-05-22 23:51:40 +00001589 Opts.SnippetLineLimit = getLastArgIntValue(
1590 Args, OPT_fcaret_diagnostics_max_lines,
1591 DiagnosticOptions::DefaultSnippetLineLimit, Diags);
Reid Kleckner898229a2013-06-14 17:17:23 +00001592 Opts.TabStop = getLastArgIntValue(Args, OPT_ftabstop,
Chris Lattner3d756f12010-01-13 03:06:50 +00001593 DiagnosticOptions::DefaultTabStop, Diags);
1594 if (Opts.TabStop == 0 || Opts.TabStop > DiagnosticOptions::MaxTabStop) {
Chris Lattner3d756f12010-01-13 03:06:50 +00001595 Opts.TabStop = DiagnosticOptions::DefaultTabStop;
Chad Rosierd6f716a2012-03-13 20:09:56 +00001596 if (Diags)
1597 Diags->Report(diag::warn_ignoring_ftabstop_value)
1598 << Opts.TabStop << DiagnosticOptions::DefaultTabStop;
Chris Lattner3d756f12010-01-13 03:06:50 +00001599 }
Reid Kleckner898229a2013-06-14 17:17:23 +00001600 Opts.MessageLength = getLastArgIntValue(Args, OPT_fmessage_length, 0, Diags);
Richard Smith3be1cb22014-08-07 00:24:21 +00001601 addDiagnosticArgs(Args, OPT_W_Group, OPT_W_value_Group, Opts.Warnings);
1602 addDiagnosticArgs(Args, OPT_R_Group, OPT_R_value_Group, Opts.Remarks);
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00001603
1604 return Success;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001605}
1606
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +00001607static void ParseFileSystemArgs(FileSystemOptions &Opts, ArgList &Args) {
1608 Opts.WorkingDir = Args.getLastArgValue(OPT_working_directory);
1609}
1610
Douglas Gregor6623e1f2015-11-03 18:33:07 +00001611/// Parse the argument to the -ftest-module-file-extension
1612/// command-line argument.
1613///
1614/// \returns true on error, false on success.
1615static bool parseTestModuleFileExtensionArg(StringRef Arg,
1616 std::string &BlockName,
1617 unsigned &MajorVersion,
1618 unsigned &MinorVersion,
1619 bool &Hashed,
1620 std::string &UserInfo) {
1621 SmallVector<StringRef, 5> Args;
1622 Arg.split(Args, ':', 5);
1623 if (Args.size() < 5)
1624 return true;
1625
1626 BlockName = Args[0];
1627 if (Args[1].getAsInteger(10, MajorVersion)) return true;
1628 if (Args[2].getAsInteger(10, MinorVersion)) return true;
1629 if (Args[3].getAsInteger(2, Hashed)) return true;
1630 if (Args.size() > 4)
1631 UserInfo = Args[4];
1632 return false;
1633}
1634
Daniel Dunbar9b491e72010-06-07 23:22:09 +00001635static InputKind ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args,
Erik Verbruggene0bde752016-10-27 14:17:10 +00001636 DiagnosticsEngine &Diags,
1637 bool &IsHeaderFile) {
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001638 Opts.ProgramAction = frontend::ParseSyntaxOnly;
1639 if (const Arg *A = Args.getLastArg(OPT_Action_Group)) {
1640 switch (A->getOption().getID()) {
1641 default:
David Blaikie83d382b2011-09-23 05:06:16 +00001642 llvm_unreachable("Invalid option in group!");
Alexander Kornienko4de03592012-07-31 09:37:40 +00001643 case OPT_ast_list:
1644 Opts.ProgramAction = frontend::ASTDeclList; break;
Aaron Ballman2ce598a2019-05-13 21:39:55 +00001645 case OPT_ast_dump_all_EQ:
1646 case OPT_ast_dump_EQ: {
1647 unsigned Val = llvm::StringSwitch<unsigned>(A->getValue())
1648 .CaseLower("default", ADOF_Default)
1649 .CaseLower("json", ADOF_JSON)
1650 .Default(std::numeric_limits<unsigned>::max());
1651
1652 if (Val != std::numeric_limits<unsigned>::max())
1653 Opts.ASTDumpFormat = static_cast<ASTDumpOutputFormat>(Val);
1654 else {
1655 Diags.Report(diag::err_drv_invalid_value)
1656 << A->getAsString(Args) << A->getValue();
1657 Opts.ASTDumpFormat = ADOF_Default;
1658 }
1659 LLVM_FALLTHROUGH;
1660 }
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001661 case OPT_ast_dump:
Richard Smith3a36ac12017-03-09 22:00:01 +00001662 case OPT_ast_dump_all:
Richard Smith35f986d2014-08-11 22:11:07 +00001663 case OPT_ast_dump_lookups:
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001664 Opts.ProgramAction = frontend::ASTDump; break;
1665 case OPT_ast_print:
1666 Opts.ProgramAction = frontend::ASTPrint; break;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001667 case OPT_ast_view:
1668 Opts.ProgramAction = frontend::ASTView; break;
Aaron Ballman16ed8dd2018-05-31 13:57:09 +00001669 case OPT_compiler_options_dump:
1670 Opts.ProgramAction = frontend::DumpCompilerOptions; break;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001671 case OPT_dump_raw_tokens:
1672 Opts.ProgramAction = frontend::DumpRawTokens; break;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001673 case OPT_dump_tokens:
1674 Opts.ProgramAction = frontend::DumpTokens; break;
1675 case OPT_S:
1676 Opts.ProgramAction = frontend::EmitAssembly; break;
1677 case OPT_emit_llvm_bc:
1678 Opts.ProgramAction = frontend::EmitBC; break;
1679 case OPT_emit_html:
1680 Opts.ProgramAction = frontend::EmitHTML; break;
1681 case OPT_emit_llvm:
1682 Opts.ProgramAction = frontend::EmitLLVM; break;
1683 case OPT_emit_llvm_only:
1684 Opts.ProgramAction = frontend::EmitLLVMOnly; break;
Daniel Dunbar4c77a642010-05-25 18:41:01 +00001685 case OPT_emit_codegen_only:
1686 Opts.ProgramAction = frontend::EmitCodeGenOnly; break;
Daniel Dunbar92db0fb2010-02-03 01:18:43 +00001687 case OPT_emit_obj:
1688 Opts.ProgramAction = frontend::EmitObj; break;
Nick Lewycky784fad72010-04-24 01:30:46 +00001689 case OPT_fixit_EQ:
Richard Smithbd55daf2012-11-01 04:30:05 +00001690 Opts.FixItSuffix = A->getValue();
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +00001691 LLVM_FALLTHROUGH;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001692 case OPT_fixit:
1693 Opts.ProgramAction = frontend::FixIt; break;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001694 case OPT_emit_module:
1695 Opts.ProgramAction = frontend::GenerateModule; break;
Richard Smithbbcc9f02016-08-26 00:14:38 +00001696 case OPT_emit_module_interface:
1697 Opts.ProgramAction = frontend::GenerateModuleInterface; break;
Richard Smithd6509cf2018-09-15 01:21:15 +00001698 case OPT_emit_header_module:
1699 Opts.ProgramAction = frontend::GenerateHeaderModule; break;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001700 case OPT_emit_pch:
1701 Opts.ProgramAction = frontend::GeneratePCH; break;
Puyan Lotfi68f29da2019-06-20 16:59:48 +00001702 case OPT_emit_iterface_stubs: {
1703 llvm::Optional<frontend::ActionKind> ProgramAction =
1704 llvm::StringSwitch<llvm::Optional<frontend::ActionKind>>(
1705 Args.hasArg(OPT_iterface_stub_version_EQ)
1706 ? Args.getLastArgValue(OPT_iterface_stub_version_EQ)
1707 : "")
1708 .Case("experimental-yaml-elf-v1",
1709 frontend::GenerateInterfaceYAMLExpV1)
1710 .Case("experimental-tapi-elf-v1",
1711 frontend::GenerateInterfaceTBEExpV1)
1712 .Default(llvm::None);
1713 if (!ProgramAction)
1714 Diags.Report(diag::err_drv_invalid_value)
1715 << "Must specify a valid interface stub format type using "
1716 << "-interface-stub-version=<experimental-tapi-elf-v1 | "
1717 "experimental-yaml-elf-v1>";
1718 Opts.ProgramAction = *ProgramAction;
1719 break;
1720 }
Daniel Dunbar1c201fb2010-03-19 19:44:04 +00001721 case OPT_init_only:
1722 Opts.ProgramAction = frontend::InitOnly; break;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001723 case OPT_fsyntax_only:
1724 Opts.ProgramAction = frontend::ParseSyntaxOnly; break;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00001725 case OPT_module_file_info:
1726 Opts.ProgramAction = frontend::ModuleFileInfo; break;
Ben Langmuir2cb4a782014-02-05 22:21:15 +00001727 case OPT_verify_pch:
1728 Opts.ProgramAction = frontend::VerifyPCH; break;
Douglas Gregoraf82e352010-07-20 20:18:03 +00001729 case OPT_print_preamble:
1730 Opts.ProgramAction = frontend::PrintPreamble; break;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001731 case OPT_E:
1732 Opts.ProgramAction = frontend::PrintPreprocessedInput; break;
Gabor Horvath207e7b12018-02-10 14:04:45 +00001733 case OPT_templight_dump:
1734 Opts.ProgramAction = frontend::TemplightDump; break;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001735 case OPT_rewrite_macros:
1736 Opts.ProgramAction = frontend::RewriteMacros; break;
1737 case OPT_rewrite_objc:
1738 Opts.ProgramAction = frontend::RewriteObjC; break;
1739 case OPT_rewrite_test:
1740 Opts.ProgramAction = frontend::RewriteTest; break;
1741 case OPT_analyze:
1742 Opts.ProgramAction = frontend::RunAnalysis; break;
Ted Kremenekf7639e12012-03-06 20:06:33 +00001743 case OPT_migrate:
1744 Opts.ProgramAction = frontend::MigrateSource; break;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001745 case OPT_Eonly:
1746 Opts.ProgramAction = frontend::RunPreprocessorOnly; break;
Alex Lorenz6e2d36b2019-06-03 22:59:17 +00001747 case OPT_print_dependency_directives_minimized_source:
1748 Opts.ProgramAction =
1749 frontend::PrintDependencyDirectivesSourceMinimizerOutput;
1750 break;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001751 }
1752 }
Daniel Dunbar7c995e82010-06-16 16:59:23 +00001753
1754 if (const Arg* A = Args.getLastArg(OPT_plugin)) {
Benjamin Kramer3204b152015-05-29 19:42:19 +00001755 Opts.Plugins.emplace_back(A->getValue(0));
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001756 Opts.ProgramAction = frontend::PluginAction;
Richard Smithbd55daf2012-11-01 04:30:05 +00001757 Opts.ActionName = A->getValue();
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001758 }
Nico Weber9f0c21c2019-01-05 01:10:20 +00001759 Opts.AddPluginActions = Args.getAllArgValues(OPT_add_plugin);
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001760 for (const auto *AA : Args.filtered(OPT_plugin_arg))
John Brawn6c789742016-03-15 12:51:40 +00001761 Opts.PluginArgs[AA->getValue(0)].emplace_back(AA->getValue(1));
Nico Weber2992efa2011-01-25 20:34:14 +00001762
Douglas Gregor6623e1f2015-11-03 18:33:07 +00001763 for (const std::string &Arg :
1764 Args.getAllArgValues(OPT_ftest_module_file_extension_EQ)) {
1765 std::string BlockName;
1766 unsigned MajorVersion;
1767 unsigned MinorVersion;
1768 bool Hashed;
1769 std::string UserInfo;
1770 if (parseTestModuleFileExtensionArg(Arg, BlockName, MajorVersion,
1771 MinorVersion, Hashed, UserInfo)) {
1772 Diags.Report(diag::err_test_module_file_extension_format) << Arg;
1773
1774 continue;
1775 }
1776
1777 // Add the testing module file extension.
1778 Opts.ModuleFileExtensions.push_back(
David Blaikie61137e12017-01-05 18:23:18 +00001779 std::make_shared<TestModuleFileExtension>(
1780 BlockName, MajorVersion, MinorVersion, Hashed, UserInfo));
Douglas Gregor6623e1f2015-11-03 18:33:07 +00001781 }
1782
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001783 if (const Arg *A = Args.getLastArg(OPT_code_completion_at)) {
1784 Opts.CodeCompletionAt =
Richard Smithbd55daf2012-11-01 04:30:05 +00001785 ParsedSourceLocation::FromString(A->getValue());
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001786 if (Opts.CodeCompletionAt.FileName.empty())
1787 Diags.Report(diag::err_drv_invalid_value)
Richard Smithbd55daf2012-11-01 04:30:05 +00001788 << A->getAsString(Args) << A->getValue();
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001789 }
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001790 Opts.DisableFree = Args.hasArg(OPT_disable_free);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001791
Daniel Dunbar37300482010-05-20 16:54:55 +00001792 Opts.OutputFile = Args.getLastArgValue(OPT_o);
1793 Opts.Plugins = Args.getAllArgValues(OPT_load);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001794 Opts.RelocatablePCH = Args.hasArg(OPT_relocatable_pch);
Daniel Dunbar215ca5f2009-12-03 07:01:58 +00001795 Opts.ShowHelp = Args.hasArg(OPT_help);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001796 Opts.ShowStats = Args.hasArg(OPT_print_stats);
1797 Opts.ShowTimers = Args.hasArg(OPT_ftime_report);
Fangrui Song765eba32019-06-29 01:24:36 +00001798 Opts.PrintSupportedCPUs = Args.hasArg(OPT_print_supported_cpus);
Anton Afanasyevd880de22019-03-30 08:42:48 +00001799 Opts.TimeTrace = Args.hasArg(OPT_ftime_trace);
Anton Afanasyev4fdcabf2019-07-24 14:55:40 +00001800 Opts.TimeTraceGranularity = getLastArgIntValue(
1801 Args, OPT_ftime_trace_granularity_EQ, Opts.TimeTraceGranularity, Diags);
Daniel Dunbar215ca5f2009-12-03 07:01:58 +00001802 Opts.ShowVersion = Args.hasArg(OPT_version);
Daniel Dunbar37300482010-05-20 16:54:55 +00001803 Opts.ASTMergeFiles = Args.getAllArgValues(OPT_ast_merge);
1804 Opts.LLVMArgs = Args.getAllArgValues(OPT_mllvm);
Nick Lewycky078a5e22010-08-13 17:31:00 +00001805 Opts.FixWhatYouCan = Args.hasArg(OPT_fix_what_you_can);
Argyrios Kyrtzidis24e9aff2012-01-26 02:40:48 +00001806 Opts.FixOnlyWarnings = Args.hasArg(OPT_fix_only_warnings);
1807 Opts.FixAndRecompile = Args.hasArg(OPT_fixit_recompile);
1808 Opts.FixToTemporaries = Args.hasArg(OPT_fixit_to_temp);
Aaron Ballman2ce598a2019-05-13 21:39:55 +00001809 Opts.ASTDumpDecls = Args.hasArg(OPT_ast_dump, OPT_ast_dump_EQ);
1810 Opts.ASTDumpAll = Args.hasArg(OPT_ast_dump_all, OPT_ast_dump_all_EQ);
Alexander Kornienko3db68ee2012-07-26 16:01:23 +00001811 Opts.ASTDumpFilter = Args.getLastArgValue(OPT_ast_dump_filter);
Richard Smith6ea05822013-06-24 01:45:33 +00001812 Opts.ASTDumpLookups = Args.hasArg(OPT_ast_dump_lookups);
Douglas Gregor137f1b92013-01-28 18:38:02 +00001813 Opts.UseGlobalModuleIndex = !Args.hasArg(OPT_fno_modules_global_index);
Douglas Gregorc1bbec82013-01-25 00:45:27 +00001814 Opts.GenerateGlobalModuleIndex = Opts.UseGlobalModuleIndex;
Richard Smith4a89a062014-12-06 01:13:41 +00001815 Opts.ModuleMapFiles = Args.getAllArgValues(OPT_fmodule_map_file);
Boris Kolpackovd30446f2017-08-31 06:26:43 +00001816 // Only the -fmodule-file=<file> form.
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001817 for (const auto *A : Args.filtered(OPT_fmodule_file)) {
Boris Kolpackovd30446f2017-08-31 06:26:43 +00001818 StringRef Val = A->getValue();
1819 if (Val.find('=') == StringRef::npos)
1820 Opts.ModuleFiles.push_back(Val);
1821 }
Richard Smithfb1e7f72015-08-14 05:02:58 +00001822 Opts.ModulesEmbedFiles = Args.getAllArgValues(OPT_fmodules_embed_file_EQ);
Richard Smith919ce232015-11-24 04:22:21 +00001823 Opts.ModulesEmbedAllFiles = Args.hasArg(OPT_fmodules_embed_all_files);
Pierre Gousseau533a8932016-07-13 14:21:11 +00001824 Opts.IncludeTimestamps = !Args.hasArg(OPT_fno_pch_timestamp);
Richard Smithe842a472014-10-22 02:05:46 +00001825
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001826 Opts.CodeCompleteOpts.IncludeMacros
1827 = Args.hasArg(OPT_code_completion_macros);
1828 Opts.CodeCompleteOpts.IncludeCodePatterns
1829 = Args.hasArg(OPT_code_completion_patterns);
1830 Opts.CodeCompleteOpts.IncludeGlobals
1831 = !Args.hasArg(OPT_no_code_completion_globals);
Eric Liufead6ae2017-12-13 10:26:49 +00001832 Opts.CodeCompleteOpts.IncludeNamespaceLevelDecls
1833 = !Args.hasArg(OPT_no_code_completion_ns_level_decls);
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001834 Opts.CodeCompleteOpts.IncludeBriefComments
1835 = Args.hasArg(OPT_code_completion_brief_comments);
Ivan Donchevskiib4670fc2018-05-25 12:56:26 +00001836 Opts.CodeCompleteOpts.IncludeFixIts
1837 = Args.hasArg(OPT_code_completion_with_fixits);
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001838
Douglas Gregore9fc3772012-01-26 07:55:45 +00001839 Opts.OverrideRecordLayoutsFile
1840 = Args.getLastArgValue(OPT_foverride_record_layout_EQ);
Petr Hosek7b274542018-08-08 22:23:57 +00001841 Opts.AuxTriple = Args.getLastArgValue(OPT_aux_triple);
Matthias Braunabb6eea2016-09-26 18:53:34 +00001842 Opts.StatsFile = Args.getLastArgValue(OPT_stats_file);
Artem Belevichb5bc9232015-09-22 17:23:22 +00001843
John McCalld70fb982011-06-15 23:25:17 +00001844 if (const Arg *A = Args.getLastArg(OPT_arcmt_check,
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +00001845 OPT_arcmt_modify,
1846 OPT_arcmt_migrate)) {
John McCalld70fb982011-06-15 23:25:17 +00001847 switch (A->getOption().getID()) {
1848 default:
1849 llvm_unreachable("missed a case");
1850 case OPT_arcmt_check:
1851 Opts.ARCMTAction = FrontendOptions::ARCMT_Check;
1852 break;
1853 case OPT_arcmt_modify:
1854 Opts.ARCMTAction = FrontendOptions::ARCMT_Modify;
1855 break;
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +00001856 case OPT_arcmt_migrate:
1857 Opts.ARCMTAction = FrontendOptions::ARCMT_Migrate;
1858 break;
John McCalld70fb982011-06-15 23:25:17 +00001859 }
1860 }
Ted Kremenekf7639e12012-03-06 20:06:33 +00001861 Opts.MTMigrateDir = Args.getLastArgValue(OPT_mt_migrate_directory);
Argyrios Kyrtzidisd5713632011-07-19 17:20:03 +00001862 Opts.ARCMTMigrateReportOut
1863 = Args.getLastArgValue(OPT_arcmt_migrate_report_output);
1864 Opts.ARCMTMigrateEmitARCErrors
1865 = Args.hasArg(OPT_arcmt_migrate_emit_arc_errors);
John McCalld70fb982011-06-15 23:25:17 +00001866
Ted Kremenekf7639e12012-03-06 20:06:33 +00001867 if (Args.hasArg(OPT_objcmt_migrate_literals))
1868 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Literals;
1869 if (Args.hasArg(OPT_objcmt_migrate_subscripting))
1870 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Subscripting;
Fariborz Jahaniana6556f72014-10-31 21:19:45 +00001871 if (Args.hasArg(OPT_objcmt_migrate_property_dot_syntax))
1872 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_PropertyDotSyntax;
Fariborz Jahaniand83ef842013-07-09 16:59:14 +00001873 if (Args.hasArg(OPT_objcmt_migrate_property))
1874 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Property;
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +00001875 if (Args.hasArg(OPT_objcmt_migrate_readonly_property))
1876 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_ReadonlyProperty;
Fariborz Jahanianc1213862013-10-02 21:32:39 +00001877 if (Args.hasArg(OPT_objcmt_migrate_readwrite_property))
1878 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_ReadwriteProperty;
Fariborz Jahanian2bfa2b92013-10-02 21:58:13 +00001879 if (Args.hasArg(OPT_objcmt_migrate_annotation))
1880 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Annotation;
Fariborz Jahanian23417072013-11-05 22:28:30 +00001881 if (Args.hasArg(OPT_objcmt_returns_innerpointer_property))
1882 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_ReturnsInnerPointerProperty;
Fariborz Jahanian2bfa2b92013-10-02 21:58:13 +00001883 if (Args.hasArg(OPT_objcmt_migrate_instancetype))
1884 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Instancetype;
1885 if (Args.hasArg(OPT_objcmt_migrate_nsmacros))
1886 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_NsMacros;
1887 if (Args.hasArg(OPT_objcmt_migrate_protocol_conformance))
1888 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_ProtocolConformance;
Fariborz Jahanian20a11242013-10-09 19:06:08 +00001889 if (Args.hasArg(OPT_objcmt_atomic_property))
1890 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_AtomicProperty;
Fariborz Jahanian2e793d62013-11-13 00:08:36 +00001891 if (Args.hasArg(OPT_objcmt_ns_nonatomic_iosonly))
1892 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty;
Argyrios Kyrtzidis4f2ecc62013-12-10 18:36:49 +00001893 if (Args.hasArg(OPT_objcmt_migrate_designated_init))
1894 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_DesignatedInitializer;
Fariborz Jahanianc1213862013-10-02 21:32:39 +00001895 if (Args.hasArg(OPT_objcmt_migrate_all))
1896 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_MigrateDecls;
Ted Kremenekf7639e12012-03-06 20:06:33 +00001897
Argyrios Kyrtzidisd5ba86b2013-12-10 18:36:53 +00001898 Opts.ObjCMTWhiteListPath = Args.getLastArgValue(OPT_objcmt_whitelist_dir_path);
Argyrios Kyrtzidis61f20322013-11-14 16:33:29 +00001899
Ted Kremenekf7639e12012-03-06 20:06:33 +00001900 if (Opts.ARCMTAction != FrontendOptions::ARCMT_None &&
1901 Opts.ObjCMTAction != FrontendOptions::ObjCMT_None) {
1902 Diags.Report(diag::err_drv_argument_not_allowed_with)
1903 << "ARC migration" << "ObjC migration";
1904 }
1905
Rainer Orth09d890d2019-08-05 13:59:26 +00001906 InputKind DashX(Language::Unknown);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001907 if (const Arg *A = Args.getLastArg(OPT_x)) {
Richard Smith40c0efa2017-04-26 18:57:40 +00001908 StringRef XValue = A->getValue();
Richard Smithf74d9462017-04-28 01:49:42 +00001909
1910 // Parse suffixes: '<lang>(-header|[-module-map][-cpp-output])'.
1911 // FIXME: Supporting '<lang>-header-cpp-output' would be useful.
1912 bool Preprocessed = XValue.consume_back("-cpp-output");
1913 bool ModuleMap = XValue.consume_back("-module-map");
1914 IsHeaderFile =
1915 !Preprocessed && !ModuleMap && XValue.consume_back("-header");
1916
1917 // Principal languages.
Richard Smith40c0efa2017-04-26 18:57:40 +00001918 DashX = llvm::StringSwitch<InputKind>(XValue)
Rainer Orth09d890d2019-08-05 13:59:26 +00001919 .Case("c", Language::C)
1920 .Case("cl", Language::OpenCL)
1921 .Case("cuda", Language::CUDA)
1922 .Case("hip", Language::HIP)
1923 .Case("c++", Language::CXX)
1924 .Case("objective-c", Language::ObjC)
1925 .Case("objective-c++", Language::ObjCXX)
1926 .Case("renderscript", Language::RenderScript)
1927 .Default(Language::Unknown);
Richard Smithf74d9462017-04-28 01:49:42 +00001928
1929 // "objc[++]-cpp-output" is an acceptable synonym for
1930 // "objective-c[++]-cpp-output".
1931 if (DashX.isUnknown() && Preprocessed && !IsHeaderFile && !ModuleMap)
1932 DashX = llvm::StringSwitch<InputKind>(XValue)
Rainer Orth09d890d2019-08-05 13:59:26 +00001933 .Case("objc", Language::ObjC)
1934 .Case("objc++", Language::ObjCXX)
1935 .Default(Language::Unknown);
Richard Smithf74d9462017-04-28 01:49:42 +00001936
1937 // Some special cases cannot be combined with suffixes.
1938 if (DashX.isUnknown() && !Preprocessed && !ModuleMap && !IsHeaderFile)
1939 DashX = llvm::StringSwitch<InputKind>(XValue)
Rainer Orth09d890d2019-08-05 13:59:26 +00001940 .Case("cpp-output", InputKind(Language::C).getPreprocessed())
1941 .Case("assembler-with-cpp", Language::Asm)
Richard Smithf74d9462017-04-28 01:49:42 +00001942 .Cases("ast", "pcm",
Rainer Orth09d890d2019-08-05 13:59:26 +00001943 InputKind(Language::Unknown, InputKind::Precompiled))
1944 .Case("ir", Language::LLVM_IR)
1945 .Default(Language::Unknown);
Richard Smithf74d9462017-04-28 01:49:42 +00001946
Richard Smith40c0efa2017-04-26 18:57:40 +00001947 if (DashX.isUnknown())
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001948 Diags.Report(diag::err_drv_invalid_value)
Richard Smithbd55daf2012-11-01 04:30:05 +00001949 << A->getAsString(Args) << A->getValue();
Richard Smith40c0efa2017-04-26 18:57:40 +00001950
Richard Smithf74d9462017-04-28 01:49:42 +00001951 if (Preprocessed)
Richard Smith40c0efa2017-04-26 18:57:40 +00001952 DashX = DashX.getPreprocessed();
Richard Smithf74d9462017-04-28 01:49:42 +00001953 if (ModuleMap)
1954 DashX = DashX.withFormat(InputKind::ModuleMap);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001955 }
1956
1957 // '-' is the default input if none is given.
Daniel Dunbar37300482010-05-20 16:54:55 +00001958 std::vector<std::string> Inputs = Args.getAllArgValues(OPT_INPUT);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001959 Opts.Inputs.clear();
1960 if (Inputs.empty())
1961 Inputs.push_back("-");
1962 for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
Daniel Dunbar9b491e72010-06-07 23:22:09 +00001963 InputKind IK = DashX;
Richard Smith40c0efa2017-04-26 18:57:40 +00001964 if (IK.isUnknown()) {
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001965 IK = FrontendOptions::getInputKindForExtension(
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001966 StringRef(Inputs[i]).rsplit('.').second);
Richard Smith40c0efa2017-04-26 18:57:40 +00001967 // FIXME: Warn on this?
1968 if (IK.isUnknown())
Rainer Orth09d890d2019-08-05 13:59:26 +00001969 IK = Language::C;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001970 // FIXME: Remove this hack.
1971 if (i == 0)
1972 DashX = IK;
1973 }
Richard Smithf74d9462017-04-28 01:49:42 +00001974
1975 // The -emit-module action implicitly takes a module map.
1976 if (Opts.ProgramAction == frontend::GenerateModule &&
1977 IK.getFormat() == InputKind::Source)
1978 IK = IK.withFormat(InputKind::ModuleMap);
1979
Benjamin Kramer3204b152015-05-29 19:42:19 +00001980 Opts.Inputs.emplace_back(std::move(Inputs[i]), IK);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001981 }
1982
1983 return DashX;
1984}
1985
Daniel Dunbara5a166d2009-12-15 00:06:45 +00001986std::string CompilerInvocation::GetResourcesPath(const char *Argv0,
1987 void *MainAddr) {
Alexey Samsonov6465d4f2014-12-29 21:28:15 +00001988 std::string ClangExecutable =
1989 llvm::sys::fs::getMainExecutable(Argv0, MainAddr);
Nico Weber0abcafd2019-01-31 22:15:32 +00001990 return Driver::GetResourcesPath(ClangExecutable, CLANG_RESOURCE_DIR);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001991}
1992
Adrian Prantl0ebdeac2017-03-14 23:07:49 +00001993static void ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args,
1994 const std::string &WorkingDir) {
Daniel Dunbar37300482010-05-20 16:54:55 +00001995 Opts.Sysroot = Args.getLastArgValue(OPT_isysroot, "/");
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001996 Opts.Verbose = Args.hasArg(OPT_v);
Francois Pichet698f0192011-10-10 20:34:10 +00001997 Opts.UseBuiltinIncludes = !Args.hasArg(OPT_nobuiltininc);
Daniel Dunbarb25bfde2011-10-11 18:20:10 +00001998 Opts.UseStandardSystemIncludes = !Args.hasArg(OPT_nostdsysteminc);
Douglas Gregor64b046f2010-03-24 20:13:48 +00001999 Opts.UseStandardCXXIncludes = !Args.hasArg(OPT_nostdincxx);
Bob Wilsonb02ea3d2011-06-21 21:12:29 +00002000 if (const Arg *A = Args.getLastArg(OPT_stdlib_EQ))
Richard Smithbd55daf2012-11-01 04:30:05 +00002001 Opts.UseLibcxx = (strcmp(A->getValue(), "libc++") == 0);
Daniel Dunbar37300482010-05-20 16:54:55 +00002002 Opts.ResourceDir = Args.getLastArgValue(OPT_resource_dir);
Adrian Prantl0ebdeac2017-03-14 23:07:49 +00002003
2004 // Canonicalize -fmodules-cache-path before storing it.
2005 SmallString<128> P(Args.getLastArgValue(OPT_fmodules_cache_path));
2006 if (!(P.empty() || llvm::sys::path::is_absolute(P))) {
2007 if (WorkingDir.empty())
2008 llvm::sys::fs::make_absolute(P);
2009 else
2010 llvm::sys::fs::make_absolute(WorkingDir, P);
2011 }
2012 llvm::sys::path::remove_dots(P);
2013 Opts.ModuleCachePath = P.str();
2014
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00002015 Opts.ModuleUserBuildPath = Args.getLastArgValue(OPT_fmodules_user_build_path);
Boris Kolpackovd30446f2017-08-31 06:26:43 +00002016 // Only the -fmodule-file=<name>=<file> form.
Eugene Zelenko44357ee2018-03-26 21:45:04 +00002017 for (const auto *A : Args.filtered(OPT_fmodule_file)) {
Boris Kolpackovd30446f2017-08-31 06:26:43 +00002018 StringRef Val = A->getValue();
2019 if (Val.find('=') != StringRef::npos)
2020 Opts.PrebuiltModuleFiles.insert(Val.split('='));
2021 }
Eugene Zelenko44357ee2018-03-26 21:45:04 +00002022 for (const auto *A : Args.filtered(OPT_fprebuilt_module_path))
Manman Ren11f2a472016-08-18 17:42:15 +00002023 Opts.AddPrebuiltModulePath(A->getValue());
Douglas Gregor1735f4e2011-09-13 23:15:45 +00002024 Opts.DisableModuleHash = Args.hasArg(OPT_fdisable_module_hash);
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002025 Opts.ModulesHashContent = Args.hasArg(OPT_fmodules_hash_content);
Manman Ren47a44452016-07-26 17:12:17 +00002026 Opts.ModulesValidateDiagnosticOptions =
2027 !Args.hasArg(OPT_fmodules_disable_diagnostic_validation);
Richard Smith47972af2015-06-16 00:08:24 +00002028 Opts.ImplicitModuleMaps = Args.hasArg(OPT_fimplicit_module_maps);
Richard Smith9acb99e32014-12-10 03:09:48 +00002029 Opts.ModuleMapFileHomeIsCwd = Args.hasArg(OPT_fmodule_map_file_home_is_cwd);
Reid Kleckner898229a2013-06-14 17:17:23 +00002030 Opts.ModuleCachePruneInterval =
2031 getLastArgIntValue(Args, OPT_fmodules_prune_interval, 7 * 24 * 60 * 60);
2032 Opts.ModuleCachePruneAfter =
2033 getLastArgIntValue(Args, OPT_fmodules_prune_after, 31 * 24 * 60 * 60);
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002034 Opts.ModulesValidateOncePerBuildSession =
2035 Args.hasArg(OPT_fmodules_validate_once_per_build_session);
2036 Opts.BuildSessionTimestamp =
2037 getLastArgUInt64Value(Args, OPT_fbuild_session_timestamp, 0);
Ben Langmuirdcf73862014-03-12 00:06:17 +00002038 Opts.ModulesValidateSystemHeaders =
2039 Args.hasArg(OPT_fmodules_validate_system_headers);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00002040 if (const Arg *A = Args.getLastArg(OPT_fmodule_format_EQ))
2041 Opts.ModuleFormat = A->getValue();
Ben Langmuirdcf73862014-03-12 00:06:17 +00002042
Eugene Zelenko44357ee2018-03-26 21:45:04 +00002043 for (const auto *A : Args.filtered(OPT_fmodules_ignore_macro)) {
Sean Silva14facf32015-06-09 01:57:17 +00002044 StringRef MacroDef = A->getValue();
Justin Lebar5e83dfe2016-10-21 21:45:01 +00002045 Opts.ModulesIgnoreMacros.insert(
2046 llvm::CachedHashString(MacroDef.split('=').first));
Douglas Gregor5dc38992013-02-07 00:21:12 +00002047 }
2048
Douglas Gregor9f93e382011-07-28 04:45:53 +00002049 // Add -I..., -F..., and -index-header-map options in order.
2050 bool IsIndexHeaderMap = false;
Saleem Abdulrasoolde87e5f2016-05-06 19:13:55 +00002051 bool IsSysrootSpecified =
2052 Args.hasArg(OPT__sysroot_EQ) || Args.hasArg(OPT_isysroot);
Eugene Zelenko44357ee2018-03-26 21:45:04 +00002053 for (const auto *A : Args.filtered(OPT_I, OPT_F, OPT_index_header_map)) {
Sean Silva14facf32015-06-09 01:57:17 +00002054 if (A->getOption().matches(OPT_index_header_map)) {
Douglas Gregor9f93e382011-07-28 04:45:53 +00002055 // -index-header-map applies to the next -I or -F.
2056 IsIndexHeaderMap = true;
2057 continue;
2058 }
Sean Silva14facf32015-06-09 01:57:17 +00002059
2060 frontend::IncludeDirGroup Group =
2061 IsIndexHeaderMap ? frontend::IndexHeaderMap : frontend::Angled;
2062
Saleem Abdulrasoolde87e5f2016-05-06 19:13:55 +00002063 bool IsFramework = A->getOption().matches(OPT_F);
2064 std::string Path = A->getValue();
2065
2066 if (IsSysrootSpecified && !IsFramework && A->getValue()[0] == '=') {
2067 SmallString<32> Buffer;
2068 llvm::sys::path::append(Buffer, Opts.Sysroot,
2069 llvm::StringRef(A->getValue()).substr(1));
2070 Path = Buffer.str();
2071 }
2072
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00002073 Opts.AddPath(Path, Group, IsFramework,
Saleem Abdulrasoolde87e5f2016-05-06 19:13:55 +00002074 /*IgnoreSysroot*/ true);
Douglas Gregor9f93e382011-07-28 04:45:53 +00002075 IsIndexHeaderMap = false;
2076 }
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002077
Daniel Dunbarc9c57e92013-01-25 01:50:34 +00002078 // Add -iprefix/-iwithprefix/-iwithprefixbefore options.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002079 StringRef Prefix = ""; // FIXME: This isn't the correct default prefix.
Eugene Zelenko44357ee2018-03-26 21:45:04 +00002080 for (const auto *A :
Sean Silva14facf32015-06-09 01:57:17 +00002081 Args.filtered(OPT_iprefix, OPT_iwithprefix, OPT_iwithprefixbefore)) {
Daniel Dunbara442fd52010-06-11 22:00:13 +00002082 if (A->getOption().matches(OPT_iprefix))
Richard Smithbd55daf2012-11-01 04:30:05 +00002083 Prefix = A->getValue();
Daniel Dunbara442fd52010-06-11 22:00:13 +00002084 else if (A->getOption().matches(OPT_iwithprefix))
Sean Silva14facf32015-06-09 01:57:17 +00002085 Opts.AddPath(Prefix.str() + A->getValue(), frontend::After, false, true);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002086 else
Sean Silva14facf32015-06-09 01:57:17 +00002087 Opts.AddPath(Prefix.str() + A->getValue(), frontend::Angled, false, true);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002088 }
2089
Eugene Zelenko44357ee2018-03-26 21:45:04 +00002090 for (const auto *A : Args.filtered(OPT_idirafter))
Aaron Ballman29dc5de2017-12-07 23:04:11 +00002091 Opts.AddPath(A->getValue(), frontend::After, false, true);
Eugene Zelenko44357ee2018-03-26 21:45:04 +00002092 for (const auto *A : Args.filtered(OPT_iquote))
Aaron Ballman29dc5de2017-12-07 23:04:11 +00002093 Opts.AddPath(A->getValue(), frontend::Quoted, false, true);
Eugene Zelenko44357ee2018-03-26 21:45:04 +00002094 for (const auto *A : Args.filtered(OPT_isystem, OPT_iwithsysroot))
Aaron Ballman29dc5de2017-12-07 23:04:11 +00002095 Opts.AddPath(A->getValue(), frontend::System, false,
2096 !A->getOption().matches(OPT_iwithsysroot));
Eugene Zelenko44357ee2018-03-26 21:45:04 +00002097 for (const auto *A : Args.filtered(OPT_iframework))
Aaron Ballman29dc5de2017-12-07 23:04:11 +00002098 Opts.AddPath(A->getValue(), frontend::System, true, true);
Eugene Zelenko44357ee2018-03-26 21:45:04 +00002099 for (const auto *A : Args.filtered(OPT_iframeworkwithsysroot))
Aaron Ballman29dc5de2017-12-07 23:04:11 +00002100 Opts.AddPath(A->getValue(), frontend::System, /*IsFramework=*/true,
2101 /*IgnoreSysRoot=*/false);
2102
2103 // Add the paths for the various language specific isystem flags.
Eugene Zelenko44357ee2018-03-26 21:45:04 +00002104 for (const auto *A : Args.filtered(OPT_c_isystem))
Aaron Ballman29dc5de2017-12-07 23:04:11 +00002105 Opts.AddPath(A->getValue(), frontend::CSystem, false, true);
Eugene Zelenko44357ee2018-03-26 21:45:04 +00002106 for (const auto *A : Args.filtered(OPT_cxx_isystem))
Aaron Ballman29dc5de2017-12-07 23:04:11 +00002107 Opts.AddPath(A->getValue(), frontend::CXXSystem, false, true);
Eugene Zelenko44357ee2018-03-26 21:45:04 +00002108 for (const auto *A : Args.filtered(OPT_objc_isystem))
Aaron Ballman29dc5de2017-12-07 23:04:11 +00002109 Opts.AddPath(A->getValue(), frontend::ObjCSystem, false,true);
Eugene Zelenko44357ee2018-03-26 21:45:04 +00002110 for (const auto *A : Args.filtered(OPT_objcxx_isystem))
Aaron Ballman29dc5de2017-12-07 23:04:11 +00002111 Opts.AddPath(A->getValue(), frontend::ObjCXXSystem, false, true);
2112
2113 // Add the internal paths from a driver that detects standard include paths.
Eugene Zelenko44357ee2018-03-26 21:45:04 +00002114 for (const auto *A :
Aaron Ballman29dc5de2017-12-07 23:04:11 +00002115 Args.filtered(OPT_internal_isystem, OPT_internal_externc_isystem)) {
2116 frontend::IncludeDirGroup Group = frontend::System;
2117 if (A->getOption().matches(OPT_internal_externc_isystem))
2118 Group = frontend::ExternCSystem;
2119 Opts.AddPath(A->getValue(), Group, false, true);
2120 }
2121
2122 // Add the path prefixes which are implicitly treated as being system headers.
Eugene Zelenko44357ee2018-03-26 21:45:04 +00002123 for (const auto *A :
Aaron Ballman29dc5de2017-12-07 23:04:11 +00002124 Args.filtered(OPT_system_header_prefix, OPT_no_system_header_prefix))
2125 Opts.AddSystemHeaderPrefix(
2126 A->getValue(), A->getOption().matches(OPT_system_header_prefix));
2127
Eugene Zelenko44357ee2018-03-26 21:45:04 +00002128 for (const auto *A : Args.filtered(OPT_ivfsoverlay))
Aaron Ballman29dc5de2017-12-07 23:04:11 +00002129 Opts.AddVFSOverlayFile(A->getValue());
2130}
2131
2132void CompilerInvocation::setLangDefaults(LangOptions &Opts, InputKind IK,
2133 const llvm::Triple &T,
2134 PreprocessorOptions &PPOpts,
2135 LangStandard::Kind LangStd) {
2136 // Set some properties which depend solely on the input kind; it would be nice
2137 // to move these to the language standard, and have the driver resolve the
2138 // input kind + language standard.
2139 //
2140 // FIXME: Perhaps a better model would be for a single source file to have
2141 // multiple language standards (C / C++ std, ObjC std, OpenCL std, OpenMP std)
2142 // simultaneously active?
Rainer Orth09d890d2019-08-05 13:59:26 +00002143 if (IK.getLanguage() == Language::Asm) {
Aaron Ballman29dc5de2017-12-07 23:04:11 +00002144 Opts.AsmPreprocessor = 1;
2145 } else if (IK.isObjectiveC()) {
Erik Pilkingtonfa983902018-10-30 20:31:30 +00002146 Opts.ObjC = 1;
Aaron Ballman29dc5de2017-12-07 23:04:11 +00002147 }
2148
2149 if (LangStd == LangStandard::lang_unspecified) {
2150 // Based on the base language, pick one.
2151 switch (IK.getLanguage()) {
Rainer Orth09d890d2019-08-05 13:59:26 +00002152 case Language::Unknown:
2153 case Language::LLVM_IR:
Aaron Ballman29dc5de2017-12-07 23:04:11 +00002154 llvm_unreachable("Invalid input kind!");
Rainer Orth09d890d2019-08-05 13:59:26 +00002155 case Language::OpenCL:
Aaron Ballman29dc5de2017-12-07 23:04:11 +00002156 LangStd = LangStandard::lang_opencl10;
2157 break;
Rainer Orth09d890d2019-08-05 13:59:26 +00002158 case Language::CUDA:
Aaron Ballman29dc5de2017-12-07 23:04:11 +00002159 LangStd = LangStandard::lang_cuda;
2160 break;
Rainer Orth09d890d2019-08-05 13:59:26 +00002161 case Language::Asm:
2162 case Language::C:
Michal Gorny4289f4c2018-03-06 21:26:28 +00002163#if defined(CLANG_DEFAULT_STD_C)
2164 LangStd = CLANG_DEFAULT_STD_C;
2165#else
Aaron Ballman29dc5de2017-12-07 23:04:11 +00002166 // The PS4 uses C99 as the default C standard.
2167 if (T.isPS4())
2168 LangStd = LangStandard::lang_gnu99;
2169 else
2170 LangStd = LangStandard::lang_gnu11;
Michal Gorny4289f4c2018-03-06 21:26:28 +00002171#endif
Aaron Ballman29dc5de2017-12-07 23:04:11 +00002172 break;
Rainer Orth09d890d2019-08-05 13:59:26 +00002173 case Language::ObjC:
Michal Gorny4289f4c2018-03-06 21:26:28 +00002174#if defined(CLANG_DEFAULT_STD_C)
2175 LangStd = CLANG_DEFAULT_STD_C;
2176#else
Aaron Ballman29dc5de2017-12-07 23:04:11 +00002177 LangStd = LangStandard::lang_gnu11;
Michal Gorny4289f4c2018-03-06 21:26:28 +00002178#endif
Aaron Ballman29dc5de2017-12-07 23:04:11 +00002179 break;
Rainer Orth09d890d2019-08-05 13:59:26 +00002180 case Language::CXX:
2181 case Language::ObjCXX:
Michal Gorny4289f4c2018-03-06 21:26:28 +00002182#if defined(CLANG_DEFAULT_STD_CXX)
2183 LangStd = CLANG_DEFAULT_STD_CXX;
2184#else
Tim Northover36bb6d52017-12-09 12:09:54 +00002185 LangStd = LangStandard::lang_gnucxx14;
Michal Gorny4289f4c2018-03-06 21:26:28 +00002186#endif
Aaron Ballman29dc5de2017-12-07 23:04:11 +00002187 break;
Rainer Orth09d890d2019-08-05 13:59:26 +00002188 case Language::RenderScript:
Aaron Ballman29dc5de2017-12-07 23:04:11 +00002189 LangStd = LangStandard::lang_c99;
2190 break;
Rainer Orth09d890d2019-08-05 13:59:26 +00002191 case Language::HIP:
Yaxun Liu887c5692018-04-25 01:10:37 +00002192 LangStd = LangStandard::lang_hip;
2193 break;
Aaron Ballman29dc5de2017-12-07 23:04:11 +00002194 }
2195 }
2196
2197 const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
2198 Opts.LineComment = Std.hasLineComments();
2199 Opts.C99 = Std.isC99();
2200 Opts.C11 = Std.isC11();
2201 Opts.C17 = Std.isC17();
Aaron Ballmand06f3912019-05-14 12:09:55 +00002202 Opts.C2x = Std.isC2x();
Aaron Ballman29dc5de2017-12-07 23:04:11 +00002203 Opts.CPlusPlus = Std.isCPlusPlus();
2204 Opts.CPlusPlus11 = Std.isCPlusPlus11();
2205 Opts.CPlusPlus14 = Std.isCPlusPlus14();
2206 Opts.CPlusPlus17 = Std.isCPlusPlus17();
2207 Opts.CPlusPlus2a = Std.isCPlusPlus2a();
2208 Opts.Digraphs = Std.hasDigraphs();
2209 Opts.GNUMode = Std.isGNUMode();
2210 Opts.GNUInline = !Opts.C99 && !Opts.CPlusPlus;
2211 Opts.HexFloats = Std.hasHexFloats();
2212 Opts.ImplicitInt = Std.hasImplicitInt();
2213
2214 // Set OpenCL Version.
2215 Opts.OpenCL = Std.isOpenCL();
2216 if (LangStd == LangStandard::lang_opencl10)
2217 Opts.OpenCLVersion = 100;
2218 else if (LangStd == LangStandard::lang_opencl11)
2219 Opts.OpenCLVersion = 110;
2220 else if (LangStd == LangStandard::lang_opencl12)
2221 Opts.OpenCLVersion = 120;
2222 else if (LangStd == LangStandard::lang_opencl20)
2223 Opts.OpenCLVersion = 200;
Anastasia Stulovac645f612018-04-12 14:17:04 +00002224 else if (LangStd == LangStandard::lang_openclcpp)
2225 Opts.OpenCLCPlusPlusVersion = 100;
Aaron Ballman29dc5de2017-12-07 23:04:11 +00002226
2227 // OpenCL has some additional defaults.
2228 if (Opts.OpenCL) {
2229 Opts.AltiVec = 0;
2230 Opts.ZVector = 0;
2231 Opts.LaxVectorConversions = 0;
2232 Opts.setDefaultFPContractMode(LangOptions::FPC_On);
2233 Opts.NativeHalfType = 1;
2234 Opts.NativeHalfArgsAndReturns = 1;
Sven van Haastregt49ffffb2018-04-23 11:23:47 +00002235 Opts.OpenCLCPlusPlus = Opts.CPlusPlus;
Sven van Haastregtaf1c2302019-06-19 12:48:22 +00002236
Aaron Ballman29dc5de2017-12-07 23:04:11 +00002237 // Include default header file for OpenCL.
Sven van Haastregtaf1c2302019-06-19 12:48:22 +00002238 if (Opts.IncludeDefaultHeader) {
2239 if (Opts.DeclareOpenCLBuiltins) {
2240 // Only include base header file for builtin types and constants.
2241 PPOpts.Includes.push_back("opencl-c-base.h");
2242 } else {
2243 PPOpts.Includes.push_back("opencl-c.h");
2244 }
Aaron Ballman29dc5de2017-12-07 23:04:11 +00002245 }
2246 }
2247
Rainer Orth09d890d2019-08-05 13:59:26 +00002248 Opts.HIP = IK.getLanguage() == Language::HIP;
2249 Opts.CUDA = IK.getLanguage() == Language::CUDA || Opts.HIP;
Aaron Ballman29dc5de2017-12-07 23:04:11 +00002250 if (Opts.CUDA)
2251 // Set default FP_CONTRACT to FAST.
2252 Opts.setDefaultFPContractMode(LangOptions::FPC_Fast);
2253
Rainer Orth09d890d2019-08-05 13:59:26 +00002254 Opts.RenderScript = IK.getLanguage() == Language::RenderScript;
Aaron Ballman29dc5de2017-12-07 23:04:11 +00002255 if (Opts.RenderScript) {
2256 Opts.NativeHalfType = 1;
2257 Opts.NativeHalfArgsAndReturns = 1;
2258 }
2259
2260 // OpenCL and C++ both have bool, true, false keywords.
2261 Opts.Bool = Opts.OpenCL || Opts.CPlusPlus;
2262
2263 // OpenCL has half keyword
2264 Opts.Half = Opts.OpenCL;
2265
2266 // C++ has wchar_t keyword.
2267 Opts.WChar = Opts.CPlusPlus;
2268
2269 Opts.GNUKeywords = Opts.GNUMode;
2270 Opts.CXXOperatorNames = Opts.CPlusPlus;
2271
2272 Opts.AlignedAllocation = Opts.CPlusPlus17;
2273
2274 Opts.DollarIdents = !Opts.AsmPreprocessor;
Aaron Ballmand06f3912019-05-14 12:09:55 +00002275
2276 // Enable [[]] attributes in C++11 and C2x by default.
2277 Opts.DoubleSquareBracketAttributes = Opts.CPlusPlus11 || Opts.C2x;
Aaron Ballman29dc5de2017-12-07 23:04:11 +00002278}
2279
2280/// Attempt to parse a visibility value out of the given argument.
2281static Visibility parseVisibility(Arg *arg, ArgList &args,
2282 DiagnosticsEngine &diags) {
2283 StringRef value = arg->getValue();
2284 if (value == "default") {
2285 return DefaultVisibility;
2286 } else if (value == "hidden" || value == "internal") {
2287 return HiddenVisibility;
2288 } else if (value == "protected") {
2289 // FIXME: diagnose if target does not support protected visibility
2290 return ProtectedVisibility;
2291 }
2292
2293 diags.Report(diag::err_drv_invalid_value)
2294 << arg->getAsString(args) << value;
2295 return DefaultVisibility;
2296}
2297
2298/// Check if input file kind and language standard are compatible.
2299static bool IsInputCompatibleWithStandard(InputKind IK,
2300 const LangStandard &S) {
2301 switch (IK.getLanguage()) {
Rainer Orth09d890d2019-08-05 13:59:26 +00002302 case Language::Unknown:
2303 case Language::LLVM_IR:
Aaron Ballman29dc5de2017-12-07 23:04:11 +00002304 llvm_unreachable("should not parse language flags for this input");
2305
Rainer Orth09d890d2019-08-05 13:59:26 +00002306 case Language::C:
2307 case Language::ObjC:
2308 case Language::RenderScript:
2309 return S.getLanguage() == Language::C;
Aaron Ballman29dc5de2017-12-07 23:04:11 +00002310
Rainer Orth09d890d2019-08-05 13:59:26 +00002311 case Language::OpenCL:
2312 return S.getLanguage() == Language::OpenCL;
Aaron Ballman29dc5de2017-12-07 23:04:11 +00002313
Rainer Orth09d890d2019-08-05 13:59:26 +00002314 case Language::CXX:
2315 case Language::ObjCXX:
2316 return S.getLanguage() == Language::CXX;
Richard Smith40c0efa2017-04-26 18:57:40 +00002317
Rainer Orth09d890d2019-08-05 13:59:26 +00002318 case Language::CUDA:
Richard Smithb0fe7042017-04-26 23:44:33 +00002319 // FIXME: What -std= values should be permitted for CUDA compilations?
Rainer Orth09d890d2019-08-05 13:59:26 +00002320 return S.getLanguage() == Language::CUDA ||
2321 S.getLanguage() == Language::CXX;
Richard Smith40c0efa2017-04-26 18:57:40 +00002322
Rainer Orth09d890d2019-08-05 13:59:26 +00002323 case Language::HIP:
2324 return S.getLanguage() == Language::CXX || S.getLanguage() == Language::HIP;
Yaxun Liu887c5692018-04-25 01:10:37 +00002325
Rainer Orth09d890d2019-08-05 13:59:26 +00002326 case Language::Asm:
Richard Smith40c0efa2017-04-26 18:57:40 +00002327 // Accept (and ignore) all -std= values.
2328 // FIXME: The -std= value is not ignored; it affects the tokenization
2329 // and preprocessing rules if we're preprocessing this asm input.
Richard Smith222b30b2017-02-14 23:41:38 +00002330 return true;
Richard Smithc91daf12017-02-14 22:44:20 +00002331 }
Richard Smith40c0efa2017-04-26 18:57:40 +00002332
2333 llvm_unreachable("unexpected input language");
Richard Smithc91daf12017-02-14 22:44:20 +00002334}
2335
2336/// Get language name for given input kind.
2337static const StringRef GetInputKindName(InputKind IK) {
Richard Smith40c0efa2017-04-26 18:57:40 +00002338 switch (IK.getLanguage()) {
Rainer Orth09d890d2019-08-05 13:59:26 +00002339 case Language::C:
Richard Smithb0fe7042017-04-26 23:44:33 +00002340 return "C";
Rainer Orth09d890d2019-08-05 13:59:26 +00002341 case Language::ObjC:
Richard Smithb0fe7042017-04-26 23:44:33 +00002342 return "Objective-C";
Rainer Orth09d890d2019-08-05 13:59:26 +00002343 case Language::CXX:
Richard Smithb0fe7042017-04-26 23:44:33 +00002344 return "C++";
Rainer Orth09d890d2019-08-05 13:59:26 +00002345 case Language::ObjCXX:
Richard Smithb0fe7042017-04-26 23:44:33 +00002346 return "Objective-C++";
Rainer Orth09d890d2019-08-05 13:59:26 +00002347 case Language::OpenCL:
Richard Smithc91daf12017-02-14 22:44:20 +00002348 return "OpenCL";
Rainer Orth09d890d2019-08-05 13:59:26 +00002349 case Language::CUDA:
Richard Smithc91daf12017-02-14 22:44:20 +00002350 return "CUDA";
Rainer Orth09d890d2019-08-05 13:59:26 +00002351 case Language::RenderScript:
Richard Smithb0fe7042017-04-26 23:44:33 +00002352 return "RenderScript";
Rainer Orth09d890d2019-08-05 13:59:26 +00002353 case Language::HIP:
Yaxun Liu887c5692018-04-25 01:10:37 +00002354 return "HIP";
Richard Smithb0fe7042017-04-26 23:44:33 +00002355
Rainer Orth09d890d2019-08-05 13:59:26 +00002356 case Language::Asm:
Richard Smithb0fe7042017-04-26 23:44:33 +00002357 return "Asm";
Rainer Orth09d890d2019-08-05 13:59:26 +00002358 case Language::LLVM_IR:
Richard Smithb0fe7042017-04-26 23:44:33 +00002359 return "LLVM IR";
2360
Rainer Orth09d890d2019-08-05 13:59:26 +00002361 case Language::Unknown:
Richard Smithb0fe7042017-04-26 23:44:33 +00002362 break;
Richard Smithc91daf12017-02-14 22:44:20 +00002363 }
Richard Smithb0fe7042017-04-26 23:44:33 +00002364 llvm_unreachable("unknown input language");
Richard Smithc91daf12017-02-14 22:44:20 +00002365}
2366
Peter Collingbourneaaeb73b2010-12-04 01:50:27 +00002367static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK,
Samuel Antao45bfe4c2016-02-08 15:59:20 +00002368 const TargetOptions &TargetOpts,
Yaxun Liu143f0832016-06-20 19:26:00 +00002369 PreprocessorOptions &PPOpts,
David Blaikie9c902b52011-09-25 23:23:43 +00002370 DiagnosticsEngine &Diags) {
Peter Collingbourneaaeb73b2010-12-04 01:50:27 +00002371 // FIXME: Cleanup per-file based stuff.
2372 LangStandard::Kind LangStd = LangStandard::lang_unspecified;
2373 if (const Arg *A = Args.getLastArg(OPT_std_EQ)) {
Rainer Orth09d890d2019-08-05 13:59:26 +00002374 LangStd = LangStandard::getLangKind(A->getValue());
Richard Smithc91daf12017-02-14 22:44:20 +00002375 if (LangStd == LangStandard::lang_unspecified) {
Peter Collingbourneaaeb73b2010-12-04 01:50:27 +00002376 Diags.Report(diag::err_drv_invalid_value)
Richard Smithbd55daf2012-11-01 04:30:05 +00002377 << A->getAsString(Args) << A->getValue();
Richard Smithc91daf12017-02-14 22:44:20 +00002378 // Report supported standards with short description.
2379 for (unsigned KindValue = 0;
2380 KindValue != LangStandard::lang_unspecified;
2381 ++KindValue) {
2382 const LangStandard &Std = LangStandard::getLangStandardForKind(
2383 static_cast<LangStandard::Kind>(KindValue));
2384 if (IsInputCompatibleWithStandard(IK, Std)) {
Richard Smith8c8fb802017-04-27 01:17:05 +00002385 auto Diag = Diags.Report(diag::note_drv_use_standard);
2386 Diag << Std.getName() << Std.getDescription();
2387 unsigned NumAliases = 0;
2388#define LANGSTANDARD(id, name, lang, desc, features)
2389#define LANGSTANDARD_ALIAS(id, alias) \
2390 if (KindValue == LangStandard::lang_##id) ++NumAliases;
2391#define LANGSTANDARD_ALIAS_DEPR(id, alias)
Rainer Orth09d890d2019-08-05 13:59:26 +00002392#include "clang/Basic/LangStandards.def"
Richard Smith8c8fb802017-04-27 01:17:05 +00002393 Diag << NumAliases;
2394#define LANGSTANDARD(id, name, lang, desc, features)
2395#define LANGSTANDARD_ALIAS(id, alias) \
2396 if (KindValue == LangStandard::lang_##id) Diag << alias;
2397#define LANGSTANDARD_ALIAS_DEPR(id, alias)
Rainer Orth09d890d2019-08-05 13:59:26 +00002398#include "clang/Basic/LangStandards.def"
Richard Smithc91daf12017-02-14 22:44:20 +00002399 }
2400 }
2401 } else {
Alp Tokerf6a24ce2013-12-05 16:25:25 +00002402 // Valid standard, check to make sure language and standard are
2403 // compatible.
Chad Rosier24874a42011-05-02 19:24:53 +00002404 const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
Richard Smithc91daf12017-02-14 22:44:20 +00002405 if (!IsInputCompatibleWithStandard(IK, Std)) {
2406 Diags.Report(diag::err_drv_argument_not_allowed_with)
2407 << A->getAsString(Args) << GetInputKindName(IK);
Chad Rosier24874a42011-05-02 19:24:53 +00002408 }
2409 }
Peter Collingbourneaaeb73b2010-12-04 01:50:27 +00002410 }
2411
Takuto Ikuta302c6432018-11-03 06:45:00 +00002412 if (Args.hasArg(OPT_fno_dllexport_inlines))
2413 Opts.DllExportInlines = false;
2414
Oren Ben Simhon220671a2018-03-17 13:31:35 +00002415 if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
2416 StringRef Name = A->getValue();
2417 if (Name == "full" || Name == "branch") {
2418 Opts.CFProtectionBranch = 1;
2419 }
2420 }
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00002421 // -cl-std only applies for OpenCL language standards.
2422 // Override the -std option in this case.
Peter Collingbournefafa6652010-12-04 01:51:40 +00002423 if (const Arg *A = Args.getLastArg(OPT_cl_std_EQ)) {
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00002424 LangStandard::Kind OpenCLLangStd
Richard Smithc91daf12017-02-14 22:44:20 +00002425 = llvm::StringSwitch<LangStandard::Kind>(A->getValue())
Richard Smith8c8fb802017-04-27 01:17:05 +00002426 .Cases("cl", "CL", LangStandard::lang_opencl10)
Richard Smithc91daf12017-02-14 22:44:20 +00002427 .Cases("cl1.1", "CL1.1", LangStandard::lang_opencl11)
2428 .Cases("cl1.2", "CL1.2", LangStandard::lang_opencl12)
2429 .Cases("cl2.0", "CL2.0", LangStandard::lang_opencl20)
Anastasia Stulova88ed70e2019-07-25 11:04:29 +00002430 .Cases("clc++", "CLC++", LangStandard::lang_openclcpp)
Richard Smithc91daf12017-02-14 22:44:20 +00002431 .Default(LangStandard::lang_unspecified);
Douglas Katzman31fdbfe2015-08-05 15:08:53 +00002432
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00002433 if (OpenCLLangStd == LangStandard::lang_unspecified) {
Peter Collingbournefafa6652010-12-04 01:51:40 +00002434 Diags.Report(diag::err_drv_invalid_value)
Richard Smithc91daf12017-02-14 22:44:20 +00002435 << A->getAsString(Args) << A->getValue();
Peter Collingbournefafa6652010-12-04 01:51:40 +00002436 }
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00002437 else
2438 LangStd = OpenCLLangStd;
Peter Collingbournefafa6652010-12-04 01:51:40 +00002439 }
Douglas Katzman31fdbfe2015-08-05 15:08:53 +00002440
Yaxun Liu143f0832016-06-20 19:26:00 +00002441 Opts.IncludeDefaultHeader = Args.hasArg(OPT_finclude_default_header);
Sven van Haastregt79a222f2019-06-03 09:39:11 +00002442 Opts.DeclareOpenCLBuiltins = Args.hasArg(OPT_fdeclare_opencl_builtins);
Yaxun Liu143f0832016-06-20 19:26:00 +00002443
Sunil Srivastavabf010802016-04-27 19:53:03 +00002444 llvm::Triple T(TargetOpts.Triple);
Yaxun Liu143f0832016-06-20 19:26:00 +00002445 CompilerInvocation::setLangDefaults(Opts, IK, T, PPOpts, LangStd);
Peter Collingbourneaaeb73b2010-12-04 01:50:27 +00002446
Yaxun Liu02c39792016-07-13 21:21:05 +00002447 // -cl-strict-aliasing needs to emit diagnostic in the case where CL > 1.0.
2448 // This option should be deprecated for CL > 1.0 because
2449 // this option was added for compatibility with OpenCL 1.0.
2450 if (Args.getLastArg(OPT_cl_strict_aliasing)
2451 && Opts.OpenCLVersion > 100) {
Yaxun Liu02c39792016-07-13 21:21:05 +00002452 Diags.Report(diag::warn_option_invalid_ocl_version)
Sven van Haastregt35b61392018-05-08 13:47:43 +00002453 << Opts.getOpenCLVersionTuple().getAsString()
2454 << Args.getLastArg(OPT_cl_strict_aliasing)->getAsString(Args);
Yaxun Liu02c39792016-07-13 21:21:05 +00002455 }
2456
Chandler Carruthe03aa552010-04-17 20:17:31 +00002457 // We abuse '-f[no-]gnu-keywords' to force overriding all GNU-extension
2458 // keywords. This behavior is provided by GCC's poorly named '-fasm' flag,
2459 // while a subset (the non-C++ GNU keywords) is provided by GCC's
2460 // '-fgnu-keywords'. Clang conflates the two for simplicity under the single
2461 // name, as it doesn't seem a useful distinction.
2462 Opts.GNUKeywords = Args.hasFlag(OPT_fgnu_keywords, OPT_fno_gnu_keywords,
Peter Collingbourneaaeb73b2010-12-04 01:50:27 +00002463 Opts.GNUKeywords);
Chandler Carruthe03aa552010-04-17 20:17:31 +00002464
Jacob Bandes-Storch33f3e632018-07-17 04:56:22 +00002465 Opts.Digraphs = Args.hasFlag(OPT_fdigraphs, OPT_fno_digraphs, Opts.Digraphs);
2466
Erich Keaned46083c2017-05-25 16:24:49 +00002467 if (Args.hasArg(OPT_fno_operator_names))
Peter Collingbourneaaeb73b2010-12-04 01:50:27 +00002468 Opts.CXXOperatorNames = 0;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002469
Reid Klecknerbbc01782014-12-03 21:53:36 +00002470 if (Args.hasArg(OPT_fcuda_is_device))
2471 Opts.CUDAIsDevice = 1;
2472
Justin Lebar1eac5942016-01-26 17:47:20 +00002473 if (Args.hasArg(OPT_fcuda_allow_variadic_functions))
2474 Opts.CUDAAllowVariadicFunctions = 1;
2475
Justin Lebarba122ab2016-03-30 23:30:21 +00002476 if (Args.hasArg(OPT_fno_cuda_host_device_constexpr))
2477 Opts.CUDAHostDeviceConstexpr = 0;
2478
Justin Lebar91f6f072016-05-23 20:19:56 +00002479 if (Opts.CUDAIsDevice && Args.hasArg(OPT_fcuda_approx_transcendentals))
2480 Opts.CUDADeviceApproxTranscendentals = 1;
2481
Yaxun Liu97670892018-10-02 17:48:54 +00002482 Opts.GPURelocatableDeviceCode = Args.hasArg(OPT_fgpu_rdc);
Jonas Hahnfeld5379c6d2018-02-12 10:46:45 +00002483
Erik Pilkingtonfa983902018-10-30 20:31:30 +00002484 if (Opts.ObjC) {
John McCall5fb5df92012-06-20 06:18:46 +00002485 if (Arg *arg = Args.getLastArg(OPT_fobjc_runtime_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00002486 StringRef value = arg->getValue();
John McCall5fb5df92012-06-20 06:18:46 +00002487 if (Opts.ObjCRuntime.tryParse(value))
2488 Diags.Report(diag::err_drv_unknown_objc_runtime) << value;
2489 }
2490
John McCall31168b02011-06-15 23:02:42 +00002491 if (Args.hasArg(OPT_fobjc_gc_only))
Douglas Gregor79a91412011-09-13 17:21:33 +00002492 Opts.setGC(LangOptions::GCOnly);
John McCall31168b02011-06-15 23:02:42 +00002493 else if (Args.hasArg(OPT_fobjc_gc))
Douglas Gregor79a91412011-09-13 17:21:33 +00002494 Opts.setGC(LangOptions::HybridGC);
John McCall31168b02011-06-15 23:02:42 +00002495 else if (Args.hasArg(OPT_fobjc_arc)) {
2496 Opts.ObjCAutoRefCount = 1;
John McCall3deb1ad2012-08-21 02:47:43 +00002497 if (!Opts.ObjCRuntime.allowsARC())
2498 Diags.Report(diag::err_arc_unsupported_on_runtime);
John McCall460ce582015-10-22 18:38:17 +00002499 }
John McCall31168b02011-06-15 23:02:42 +00002500
John McCall460ce582015-10-22 18:38:17 +00002501 // ObjCWeakRuntime tracks whether the runtime supports __weak, not
2502 // whether the feature is actually enabled. This is predominantly
2503 // determined by -fobjc-runtime, but we allow it to be overridden
2504 // from the command line for testing purposes.
2505 if (Args.hasArg(OPT_fobjc_runtime_has_weak))
2506 Opts.ObjCWeakRuntime = 1;
2507 else
2508 Opts.ObjCWeakRuntime = Opts.ObjCRuntime.allowsWeak();
2509
2510 // ObjCWeak determines whether __weak is actually enabled.
John McCallfbe5ed72015-11-05 19:19:56 +00002511 // Note that we allow -fno-objc-weak to disable this even in ARC mode.
2512 if (auto weakArg = Args.getLastArg(OPT_fobjc_weak, OPT_fno_objc_weak)) {
2513 if (!weakArg->getOption().matches(OPT_fobjc_weak)) {
2514 assert(!Opts.ObjCWeak);
2515 } else if (Opts.getGC() != LangOptions::NonGC) {
John McCall460ce582015-10-22 18:38:17 +00002516 Diags.Report(diag::err_objc_weak_with_gc);
John McCallfbe5ed72015-11-05 19:19:56 +00002517 } else if (!Opts.ObjCWeakRuntime) {
John McCall460ce582015-10-22 18:38:17 +00002518 Diags.Report(diag::err_objc_weak_unsupported);
John McCallfbe5ed72015-11-05 19:19:56 +00002519 } else {
2520 Opts.ObjCWeak = 1;
John McCall460ce582015-10-22 18:38:17 +00002521 }
John McCallfbe5ed72015-11-05 19:19:56 +00002522 } else if (Opts.ObjCAutoRefCount) {
2523 Opts.ObjCWeak = Opts.ObjCWeakRuntime;
John McCall3deb1ad2012-08-21 02:47:43 +00002524 }
John McCall24fc0de2011-07-06 00:26:06 +00002525
John McCall31168b02011-06-15 23:02:42 +00002526 if (Args.hasArg(OPT_fno_objc_infer_related_result_type))
2527 Opts.ObjCInferRelatedResultType = 0;
Douglas Katzman31fdbfe2015-08-05 15:08:53 +00002528
Fariborz Jahaniane1e33f82013-11-01 21:58:17 +00002529 if (Args.hasArg(OPT_fobjc_subscripting_legacy_runtime))
2530 Opts.ObjCSubscriptingLegacyRuntime =
2531 (Opts.ObjCRuntime.getKind() == ObjCRuntime::FragileMacOSX);
John McCall31168b02011-06-15 23:02:42 +00002532 }
Douglas Katzman31fdbfe2015-08-05 15:08:53 +00002533
Peter Collingbourne470d9422015-05-13 22:07:22 +00002534 if (Args.hasArg(OPT_fgnu89_inline)) {
2535 if (Opts.CPlusPlus)
Richard Smithc91daf12017-02-14 22:44:20 +00002536 Diags.Report(diag::err_drv_argument_not_allowed_with)
2537 << "-fgnu89-inline" << GetInputKindName(IK);
Peter Collingbourne470d9422015-05-13 22:07:22 +00002538 else
2539 Opts.GNUInline = 1;
2540 }
Rafael Espindolafb2af642011-06-02 16:13:27 +00002541
Fariborz Jahanianf7f04452011-02-04 00:01:24 +00002542 if (Args.hasArg(OPT_fapple_kext)) {
2543 if (!Opts.CPlusPlus)
2544 Diags.Report(diag::warn_c_kext);
2545 else
2546 Opts.AppleKext = 1;
2547 }
2548
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002549 if (Args.hasArg(OPT_print_ivar_layout))
2550 Opts.ObjCGCBitmapPrint = 1;
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00002551
Fariborz Jahanian63408e82010-04-22 20:26:39 +00002552 if (Args.hasArg(OPT_fno_constant_cfstrings))
2553 Opts.NoConstantCFStrings = 1;
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00002554 if (const auto *A = Args.getLastArg(OPT_fcf_runtime_abi_EQ))
2555 Opts.CFRuntime =
2556 llvm::StringSwitch<LangOptions::CoreFoundationABI>(A->getValue())
2557 .Cases("unspecified", "standalone", "objc",
2558 LangOptions::CoreFoundationABI::ObjectiveC)
2559 .Cases("swift", "swift-5.0",
2560 LangOptions::CoreFoundationABI::Swift5_0)
2561 .Case("swift-4.2", LangOptions::CoreFoundationABI::Swift4_2)
2562 .Case("swift-4.1", LangOptions::CoreFoundationABI::Swift4_1)
2563 .Default(LangOptions::CoreFoundationABI::ObjectiveC);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002564
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00002565 if (Args.hasArg(OPT_fzvector))
2566 Opts.ZVector = 1;
2567
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002568 if (Args.hasArg(OPT_pthread))
2569 Opts.POSIXThreads = 1;
2570
John McCallb4a99d32013-02-19 01:57:35 +00002571 // The value-visibility mode defaults to "default".
2572 if (Arg *visOpt = Args.getLastArg(OPT_fvisibility)) {
2573 Opts.setValueVisibilityMode(parseVisibility(visOpt, Args, Diags));
2574 } else {
2575 Opts.setValueVisibilityMode(DefaultVisibility);
2576 }
2577
2578 // The type-visibility mode defaults to the value-visibility mode.
2579 if (Arg *typeVisOpt = Args.getLastArg(OPT_ftype_visibility)) {
2580 Opts.setTypeVisibilityMode(parseVisibility(typeVisOpt, Args, Diags));
2581 } else {
2582 Opts.setTypeVisibilityMode(Opts.getValueVisibilityMode());
2583 }
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002584
Douglas Gregor08329632010-06-15 17:05:35 +00002585 if (Args.hasArg(OPT_fvisibility_inlines_hidden))
2586 Opts.InlineVisibilityHidden = 1;
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002587
Petr Hosek821b38f2018-12-04 03:25:25 +00002588 if (Args.hasArg(OPT_fvisibility_global_new_delete_hidden))
2589 Opts.GlobalAllocationFunctionVisibilityHidden = 1;
2590
Scott Linderbef26632019-01-28 17:12:19 +00002591 if (Args.hasArg(OPT_fapply_global_visibility_to_externs))
2592 Opts.SetVisibilityForExternDecls = 1;
2593
David Chisnalldd84ef12010-09-17 18:29:54 +00002594 if (Args.hasArg(OPT_ftrapv)) {
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002595 Opts.setSignedOverflowBehavior(LangOptions::SOB_Trapping);
David Chisnalldd84ef12010-09-17 18:29:54 +00002596 // Set the handler, if one is specified.
2597 Opts.OverflowHandler =
2598 Args.getLastArgValue(OPT_ftrapv_handler);
2599 }
Chris Lattner51924e512010-06-26 21:25:03 +00002600 else if (Args.hasArg(OPT_fwrapv))
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002601 Opts.setSignedOverflowBehavior(LangOptions::SOB_Defined);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002602
Nico Weberb62ba512014-12-22 18:35:03 +00002603 Opts.MSVCCompat = Args.hasArg(OPT_fms_compatibility);
2604 Opts.MicrosoftExt = Opts.MSVCCompat || Args.hasArg(OPT_fms_extensions);
2605 Opts.AsmBlocks = Args.hasArg(OPT_fasm_blocks) || Opts.MicrosoftExt;
David Majnemerc371ff02015-03-22 08:39:22 +00002606 Opts.MSCompatibilityVersion = 0;
2607 if (const Arg *A = Args.getLastArg(OPT_fms_compatibility_version)) {
2608 VersionTuple VT;
2609 if (VT.tryParse(A->getValue()))
2610 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
2611 << A->getValue();
2612 Opts.MSCompatibilityVersion = VT.getMajor() * 10000000 +
2613 VT.getMinor().getValueOr(0) * 100000 +
2614 VT.getSubminor().getValueOr(0);
2615 }
Nico Weberb62ba512014-12-22 18:35:03 +00002616
Raphael Isemannb23ccec2018-12-10 12:37:46 +00002617 // Mimicking gcc's behavior, trigraphs are only enabled if -trigraphs
Nico Weberb62ba512014-12-22 18:35:03 +00002618 // is specified, or -std is set to a conforming mode.
2619 // Trigraphs are disabled by default in c++1z onwards.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00002620 Opts.Trigraphs = !Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus17;
Nico Weber00721502014-12-23 22:32:37 +00002621 Opts.Trigraphs =
2622 Args.hasFlag(OPT_ftrigraphs, OPT_fno_trigraphs, Opts.Trigraphs);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002623
Daniel Dunbar15cef0e2009-12-16 20:10:18 +00002624 Opts.DollarIdents = Args.hasFlag(OPT_fdollars_in_identifiers,
2625 OPT_fno_dollars_in_identifiers,
Peter Collingbourneaaeb73b2010-12-04 01:50:27 +00002626 Opts.DollarIdents);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002627 Opts.PascalStrings = Args.hasArg(OPT_fpascal_strings);
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00002628 Opts.VtorDispMode = getLastArgIntValue(Args, OPT_vtordisp_mode_EQ, 1, Diags);
Dawn Perchik68bb1b42010-09-02 23:59:25 +00002629 Opts.Borland = Args.hasArg(OPT_fborland_extensions);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002630 Opts.WritableStrings = Args.hasArg(OPT_fwritable_strings);
Chandler Carruthb009b142011-04-23 06:30:43 +00002631 Opts.ConstStrings = Args.hasFlag(OPT_fconst_strings, OPT_fno_const_strings,
2632 Opts.ConstStrings);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002633 if (Args.hasArg(OPT_fno_lax_vector_conversions))
Anders Carlssonfcd764a2010-02-06 23:23:06 +00002634 Opts.LaxVectorConversions = 0;
2635 if (Args.hasArg(OPT_fno_threadsafe_statics))
Anders Carlsson5d40c6f2010-02-11 08:02:13 +00002636 Opts.ThreadsafeStatics = 0;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002637 Opts.Exceptions = Args.hasArg(OPT_fexceptions);
Anders Carlsson3320e152011-02-22 01:52:06 +00002638 Opts.ObjCExceptions = Args.hasArg(OPT_fobjc_exceptions);
Anders Carlsson33e56a02011-02-23 03:16:42 +00002639 Opts.CXXExceptions = Args.hasArg(OPT_fcxx_exceptions);
Martell Malonec950c652017-11-29 07:25:12 +00002640
Leonard Chanf921d852018-06-04 16:07:52 +00002641 // -ffixed-point
2642 Opts.FixedPoint =
2643 Args.hasFlag(OPT_ffixed_point, OPT_fno_fixed_point, /*Default=*/false) &&
2644 !Opts.CPlusPlus;
Leonard Chan6e16c602018-06-29 17:08:19 +00002645 Opts.PaddingOnUnsignedFixedPoint =
2646 Args.hasFlag(OPT_fpadding_on_unsigned_fixed_point,
2647 OPT_fno_padding_on_unsigned_fixed_point,
Leonard Chandb01c3a2018-06-20 17:19:40 +00002648 /*Default=*/false) &&
2649 Opts.FixedPoint;
Leonard Chanf921d852018-06-04 16:07:52 +00002650
Martell Malonec950c652017-11-29 07:25:12 +00002651 // Handle exception personalities
2652 Arg *A = Args.getLastArg(options::OPT_fsjlj_exceptions,
2653 options::OPT_fseh_exceptions,
2654 options::OPT_fdwarf_exceptions);
2655 if (A) {
2656 const Option &Opt = A->getOption();
Shoaib Meenaid8d15472018-06-07 22:54:54 +00002657 llvm::Triple T(TargetOpts.Triple);
2658 if (T.isWindowsMSVCEnvironment())
2659 Diags.Report(diag::err_fe_invalid_exception_model)
2660 << Opt.getName() << T.str();
2661
Martell Malonec950c652017-11-29 07:25:12 +00002662 Opts.SjLjExceptions = Opt.matches(options::OPT_fsjlj_exceptions);
2663 Opts.SEHExceptions = Opt.matches(options::OPT_fseh_exceptions);
2664 Opts.DWARFExceptions = Opt.matches(options::OPT_fdwarf_exceptions);
2665 }
2666
David Majnemer960813e2016-02-20 09:23:47 +00002667 Opts.ExternCNoUnwind = Args.hasArg(OPT_fexternc_nounwind);
Daniel Dunbar1057f862011-03-18 21:23:38 +00002668 Opts.TraditionalCPP = Args.hasArg(OPT_traditional_cpp);
Anders Carlsson33e56a02011-02-23 03:16:42 +00002669
Yunzhong Gaobacf7e42016-01-26 20:15:02 +00002670 Opts.RTTI = Opts.CPlusPlus && !Args.hasArg(OPT_fno_rtti);
David Majnemerf6072342014-07-01 22:24:56 +00002671 Opts.RTTIData = Opts.RTTI && !Args.hasArg(OPT_fno_rtti_data);
Yaxun Liu18e3fd32016-06-14 21:43:01 +00002672 Opts.Blocks = Args.hasArg(OPT_fblocks) || (Opts.OpenCL
Anastasia Stulovac645f612018-04-12 14:17:04 +00002673 && Opts.OpenCLVersion == 200);
John McCall7959fee2011-09-09 20:41:01 +00002674 Opts.BlocksRuntimeOptional = Args.hasArg(OPT_fblocks_runtime_optional);
Richard Smith10ab78e2019-02-23 21:06:26 +00002675 Opts.Coroutines = Opts.CPlusPlus2a || Args.hasArg(OPT_fcoroutines_ts);
Aaron Ballman29dc5de2017-12-07 23:04:11 +00002676
Aaron Ballman606093a2017-10-15 15:01:42 +00002677 Opts.DoubleSquareBracketAttributes =
2678 Args.hasFlag(OPT_fdouble_square_bracket_attributes,
Aaron Ballmand06f3912019-05-14 12:09:55 +00002679 OPT_fno_double_square_bracket_attributes,
2680 Opts.DoubleSquareBracketAttributes);
Aaron Ballman606093a2017-10-15 15:01:42 +00002681
Richard Smith8af8b862019-04-11 21:18:23 +00002682 Opts.CPlusPlusModules = Opts.CPlusPlus2a;
Richard Smithc7bf3802016-07-23 02:32:21 +00002683 Opts.ModulesTS = Args.hasArg(OPT_fmodules_ts);
Richard Smith8af8b862019-04-11 21:18:23 +00002684 Opts.Modules =
2685 Args.hasArg(OPT_fmodules) || Opts.ModulesTS || Opts.CPlusPlusModules;
Daniel Jasper962b38e2014-04-11 11:47:45 +00002686 Opts.ModulesStrictDeclUse = Args.hasArg(OPT_fmodules_strict_decluse);
2687 Opts.ModulesDeclUse =
2688 Args.hasArg(OPT_fmodules_decluse) || Opts.ModulesStrictDeclUse;
Richard Smith8af8b862019-04-11 21:18:23 +00002689 // FIXME: We only need this in C++ modules / Modules TS if we might textually
2690 // enter a different module (eg, when building a header unit).
Richard Smithee977932015-05-01 21:22:17 +00002691 Opts.ModulesLocalVisibility =
Richard Smith8af8b862019-04-11 21:18:23 +00002692 Args.hasArg(OPT_fmodules_local_submodule_visibility) || Opts.ModulesTS ||
2693 Opts.CPlusPlusModules;
David Blaikief63556d2017-04-12 20:58:33 +00002694 Opts.ModulesCodegen = Args.hasArg(OPT_fmodules_codegen);
2695 Opts.ModulesDebugInfo = Args.hasArg(OPT_fmodules_debuginfo);
John Thompson2255f2c2014-04-23 12:57:01 +00002696 Opts.ModulesSearchAll = Opts.Modules &&
2697 !Args.hasArg(OPT_fno_modules_search_all) &&
2698 Args.hasArg(OPT_fmodules_search_all);
Richard Smith3d23c422014-05-07 02:25:43 +00002699 Opts.ModulesErrorRecovery = !Args.hasArg(OPT_fno_modules_error_recovery);
Manuel Klimekd2e8b042015-02-20 11:44:41 +00002700 Opts.ImplicitModules = !Args.hasArg(OPT_fno_implicit_modules);
David Tweed2da64382013-09-09 09:17:24 +00002701 Opts.CharIsSigned = Opts.OpenCL || !Args.hasArg(OPT_fno_signed_char);
Abramo Bagnara73bf7f52012-09-05 17:30:57 +00002702 Opts.WChar = Opts.CPlusPlus && !Args.hasArg(OPT_fno_wchar);
Richard Smith28ddb912018-11-14 21:04:34 +00002703 Opts.Char8 = Args.hasFlag(OPT_fchar8__t, OPT_fno_char8__t, Opts.CPlusPlus2a);
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002704 if (const Arg *A = Args.getLastArg(OPT_fwchar_type_EQ)) {
2705 Opts.WCharSize = llvm::StringSwitch<unsigned>(A->getValue())
2706 .Case("char", 1)
2707 .Case("short", 2)
2708 .Case("int", 4)
2709 .Default(0);
2710 if (Opts.WCharSize == 0)
2711 Diags.Report(diag::err_fe_invalid_wchar_type) << A->getValue();
2712 }
2713 Opts.WCharIsSigned = Args.hasFlag(OPT_fsigned_wchar, OPT_fno_signed_wchar, true);
Argyrios Kyrtzidis74825bc2010-10-08 00:25:19 +00002714 Opts.ShortEnums = Args.hasArg(OPT_fshort_enums);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002715 Opts.Freestanding = Args.hasArg(OPT_ffreestanding);
2716 Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding;
Chad Rosier7dbc9cf2016-01-06 14:35:46 +00002717 if (!Opts.NoBuiltin)
2718 getAllNoBuiltinFuncValues(Args, Opts.NoBuiltinFuncs);
Eli Benderskyaefa5e22013-07-23 00:13:01 +00002719 Opts.NoMathBuiltin = Args.hasArg(OPT_fno_math_builtin);
Richard Smith26b86ea2016-12-31 21:41:23 +00002720 Opts.RelaxedTemplateTemplateArgs =
2721 Args.hasArg(OPT_frelaxed_template_template_args);
Reid Kleckner7ffc3fb2015-03-20 00:31:07 +00002722 Opts.SizedDeallocation = Args.hasArg(OPT_fsized_deallocation);
Richard Smith59139022016-09-30 22:41:36 +00002723 Opts.AlignedAllocation =
2724 Args.hasFlag(OPT_faligned_allocation, OPT_fno_aligned_allocation,
2725 Opts.AlignedAllocation);
Akira Hatanakacae83f72017-06-29 18:48:40 +00002726 Opts.AlignedAllocationUnavailable =
2727 Opts.AlignedAllocation && Args.hasArg(OPT_aligned_alloc_unavailable);
Richard Smith59139022016-09-30 22:41:36 +00002728 Opts.NewAlignOverride =
2729 getLastArgIntValue(Args, OPT_fnew_alignment_EQ, 0, Diags);
2730 if (Opts.NewAlignOverride && !llvm::isPowerOf2_32(Opts.NewAlignOverride)) {
2731 Arg *A = Args.getLastArg(OPT_fnew_alignment_EQ);
2732 Diags.Report(diag::err_fe_invalid_alignment) << A->getAsString(Args)
2733 << A->getValue();
2734 Opts.NewAlignOverride = 0;
2735 }
Faisal Vali24d59d12015-05-22 01:11:10 +00002736 Opts.ConceptsTS = Args.hasArg(OPT_fconcepts_ts);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002737 Opts.HeinousExtensions = Args.hasArg(OPT_fheinous_gnu_extensions);
John McCall3155f572010-04-09 19:03:51 +00002738 Opts.AccessControl = !Args.hasArg(OPT_fno_access_control);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002739 Opts.ElideConstructors = !Args.hasArg(OPT_fno_elide_constructors);
David Tweed2da64382013-09-09 09:17:24 +00002740 Opts.MathErrno = !Opts.OpenCL && Args.hasArg(OPT_fmath_errno);
Reid Kleckner898229a2013-06-14 17:17:23 +00002741 Opts.InstantiationDepth =
Richard Smithe55b4732016-08-17 21:41:45 +00002742 getLastArgIntValue(Args, OPT_ftemplate_depth, 1024, Diags);
Richard Smith79c927b2013-11-06 19:31:51 +00002743 Opts.ArrowDepth =
2744 getLastArgIntValue(Args, OPT_foperator_arrow_depth, 256, Diags);
Reid Kleckner898229a2013-06-14 17:17:23 +00002745 Opts.ConstexprCallDepth =
2746 getLastArgIntValue(Args, OPT_fconstexpr_depth, 512, Diags);
2747 Opts.ConstexprStepLimit =
2748 getLastArgIntValue(Args, OPT_fconstexpr_steps, 1048576, Diags);
2749 Opts.BracketDepth = getLastArgIntValue(Args, OPT_fbracket_depth, 256, Diags);
Francois Pichet1c229c02011-04-22 22:18:13 +00002750 Opts.DelayedTemplateParsing = Args.hasArg(OPT_fdelayed_template_parsing);
Reid Kleckner898229a2013-06-14 17:17:23 +00002751 Opts.NumLargeByValueCopy =
2752 getLastArgIntValue(Args, OPT_Wlarge_by_value_copy_EQ, 0, Diags);
Douglas Gregordbe39272011-02-01 15:15:22 +00002753 Opts.MSBitfields = Args.hasArg(OPT_mms_bitfields);
Daniel Dunbar37300482010-05-20 16:54:55 +00002754 Opts.ObjCConstantStringClass =
2755 Args.getLastArgValue(OPT_fconstant_string_class);
Ted Kremenek1d56c9e2010-12-23 21:35:43 +00002756 Opts.ObjCDefaultSynthProperties =
Rafael Espindolaea1ba0a2013-09-27 20:21:48 +00002757 !Args.hasArg(OPT_disable_objc_default_synthesize_properties);
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00002758 Opts.EncodeExtendedBlockSig =
2759 Args.hasArg(OPT_fencode_extended_block_signature);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002760 Opts.EmitAllDecls = Args.hasArg(OPT_femit_all_decls);
Reid Kleckner898229a2013-06-14 17:17:23 +00002761 Opts.PackStruct = getLastArgIntValue(Args, OPT_fpack_struct_EQ, 0, Diags);
Fariborz Jahanianbcd82af2014-08-05 18:37:48 +00002762 Opts.MaxTypeAlign = getLastArgIntValue(Args, OPT_fmax_type_align_EQ, 0, Diags);
Reid Kleckner8195f692016-05-04 02:58:24 +00002763 Opts.AlignDouble = Args.hasArg(OPT_malign_double);
Fangrui Songc46d78d2019-07-12 02:32:15 +00002764 Opts.LongDoubleSize = Args.hasArg(OPT_mlong_double_128)
2765 ? 128
2766 : Args.hasArg(OPT_mlong_double_64) ? 64 : 0;
Fangrui Song6bd02a42019-07-15 07:25:11 +00002767 Opts.PPCIEEELongDouble = Args.hasArg(OPT_mabi_EQ_ieeelongdouble);
Reid Kleckner898229a2013-06-14 17:17:23 +00002768 Opts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
Oliver Stannarde3c8ce82019-02-18 12:39:47 +00002769 Opts.ROPI = Args.hasArg(OPT_fropi);
2770 Opts.RWPI = Args.hasArg(OPT_frwpi);
Rafael Espindolac9d336e2016-06-23 15:07:32 +00002771 Opts.PIE = Args.hasArg(OPT_pic_is_pie);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002772 Opts.Static = Args.hasArg(OPT_static_define);
Douglas Gregore9fc3772012-01-26 07:55:45 +00002773 Opts.DumpRecordLayoutsSimple = Args.hasArg(OPT_fdump_record_layouts_simple);
Douglas Katzman31fdbfe2015-08-05 15:08:53 +00002774 Opts.DumpRecordLayouts = Opts.DumpRecordLayoutsSimple
Douglas Gregore9fc3772012-01-26 07:55:45 +00002775 || Args.hasArg(OPT_fdump_record_layouts);
Anders Carlsson11e51402010-04-17 20:15:18 +00002776 Opts.DumpVTableLayouts = Args.hasArg(OPT_fdump_vtable_layouts);
Douglas Gregor8ed0c0b2010-07-09 17:35:33 +00002777 Opts.SpellChecking = !Args.hasArg(OPT_fno_spell_checking);
Daniel Dunbar9302f602010-04-15 15:06:22 +00002778 Opts.NoBitFieldTypeAlign = Args.hasArg(OPT_fno_bitfield_type_align);
Peter Collingbourne0b69e1a2010-12-04 01:50:56 +00002779 Opts.SinglePrecisionConstants = Args.hasArg(OPT_cl_single_precision_constant);
Peter Collingbourne61d6a752010-12-04 01:51:23 +00002780 Opts.FastRelaxedMath = Args.hasArg(OPT_cl_fast_relaxed_math);
Tony Linthicum76329bf2011-12-12 21:14:55 +00002781 Opts.HexagonQdsp6Compat = Args.hasArg(OPT_mqdsp6_compat);
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00002782 Opts.FakeAddressSpaceMap = Args.hasArg(OPT_ffake_address_space_map);
John McCall39439732011-04-09 22:50:59 +00002783 Opts.ParseUnknownAnytype = Args.hasArg(OPT_funknown_anytype);
John McCall3f4138c2011-07-13 17:56:40 +00002784 Opts.DebuggerSupport = Args.hasArg(OPT_fdebugger_support);
Sean Callanan1ce3a6b2012-02-04 01:29:37 +00002785 Opts.DebuggerCastResultToId = Args.hasArg(OPT_fdebugger_cast_result_to_id);
Ted Kremenekf7639e12012-03-06 20:06:33 +00002786 Opts.DebuggerObjCLiteral = Args.hasArg(OPT_fdebugger_objc_literal);
Eli Friedman055c9702011-11-02 01:53:16 +00002787 Opts.ApplePragmaPack = Args.hasArg(OPT_fapple_pragma_pack);
Bruno Cardoso Lopes970b2812018-03-20 22:36:39 +00002788 Opts.ModuleName = Args.getLastArgValue(OPT_fmodule_name_EQ);
2789 Opts.CurrentModule = Opts.ModuleName;
Bob Wilsonb111ec92015-03-02 19:01:14 +00002790 Opts.AppExt = Args.hasArg(OPT_fapplication_extension);
Ben Langmuir532d2102015-02-02 21:56:15 +00002791 Opts.ModuleFeatures = Args.getAllArgValues(OPT_fmodule_feature);
Fangrui Song1d38c132018-09-30 21:41:11 +00002792 llvm::sort(Opts.ModuleFeatures);
Pirama Arumuga Nainare9bcddd2015-05-14 23:44:18 +00002793 Opts.NativeHalfType |= Args.hasArg(OPT_fnative_half_type);
Pirama Arumuga Nainar8e2e9d62016-03-18 16:58:36 +00002794 Opts.NativeHalfArgsAndReturns |= Args.hasArg(OPT_fnative_half_arguments_and_returns);
2795 // Enable HalfArgsAndReturns if present in Args or if NativeHalfArgsAndReturns
2796 // is enabled.
2797 Opts.HalfArgsAndReturns = Args.hasArg(OPT_fallow_half_arguments_and_returns)
2798 | Opts.NativeHalfArgsAndReturns;
Steven Wucb0d13f2015-01-16 23:05:28 +00002799 Opts.GNUAsm = !Args.hasArg(OPT_fno_gnu_inline_asm);
Javed Absar603a2ba2019-05-21 14:21:26 +00002800 Opts.Cmse = Args.hasArg(OPT_mcmse); // Armv8-M Security Extensions
Ben Langmuirb537a3a2014-07-23 15:30:23 +00002801
Saleem Abdulrasoold170c4b2015-10-04 17:51:05 +00002802 // __declspec is enabled by default for the PS4 by the driver, and also
2803 // enabled for Microsoft Extensions or Borland Extensions, here.
2804 //
2805 // FIXME: __declspec is also currently enabled for CUDA, but isn't really a
Justin Lebar2dfbe9a2016-10-08 22:16:08 +00002806 // CUDA extension. However, it is required for supporting
2807 // __clang_cuda_builtin_vars.h, which uses __declspec(property). Once that has
2808 // been rewritten in terms of something more generic, remove the Opts.CUDA
2809 // term here.
Saleem Abdulrasoold170c4b2015-10-04 17:51:05 +00002810 Opts.DeclSpecKeyword =
2811 Args.hasFlag(OPT_fdeclspec, OPT_fno_declspec,
2812 (Opts.MicrosoftExt || Opts.Borland || Opts.CUDA));
2813
David Tweed31d09b02013-09-13 12:04:22 +00002814 if (Arg *A = Args.getLastArg(OPT_faddress_space_map_mangling_EQ)) {
2815 switch (llvm::StringSwitch<unsigned>(A->getValue())
2816 .Case("target", LangOptions::ASMM_Target)
2817 .Case("no", LangOptions::ASMM_Off)
2818 .Case("yes", LangOptions::ASMM_On)
2819 .Default(255)) {
2820 default:
Douglas Katzman31fdbfe2015-08-05 15:08:53 +00002821 Diags.Report(diag::err_drv_invalid_value)
David Tweed31d09b02013-09-13 12:04:22 +00002822 << "-faddress-space-map-mangling=" << A->getValue();
2823 break;
2824 case LangOptions::ASMM_Target:
2825 Opts.setAddressSpaceMapMangling(LangOptions::ASMM_Target);
2826 break;
2827 case LangOptions::ASMM_On:
2828 Opts.setAddressSpaceMapMangling(LangOptions::ASMM_On);
2829 break;
2830 case LangOptions::ASMM_Off:
2831 Opts.setAddressSpaceMapMangling(LangOptions::ASMM_Off);
2832 break;
2833 }
2834 }
2835
David Majnemer86c318f2014-02-11 21:05:00 +00002836 if (Arg *A = Args.getLastArg(OPT_fms_memptr_rep_EQ)) {
2837 LangOptions::PragmaMSPointersToMembersKind InheritanceModel =
2838 llvm::StringSwitch<LangOptions::PragmaMSPointersToMembersKind>(
2839 A->getValue())
2840 .Case("single",
2841 LangOptions::PPTMK_FullGeneralitySingleInheritance)
2842 .Case("multiple",
2843 LangOptions::PPTMK_FullGeneralityMultipleInheritance)
2844 .Case("virtual",
2845 LangOptions::PPTMK_FullGeneralityVirtualInheritance)
2846 .Default(LangOptions::PPTMK_BestCase);
2847 if (InheritanceModel == LangOptions::PPTMK_BestCase)
2848 Diags.Report(diag::err_drv_invalid_value)
2849 << "-fms-memptr-rep=" << A->getValue();
2850
2851 Opts.setMSPointerToMemberRepresentationMethod(InheritanceModel);
2852 }
2853
Alexey Bataeva7547182016-05-18 09:06:38 +00002854 // Check for MS default calling conventions being specified.
2855 if (Arg *A = Args.getLastArg(OPT_fdefault_calling_conv_EQ)) {
2856 LangOptions::DefaultCallingConvention DefaultCC =
Erich Keanea957ffb2017-11-02 21:08:00 +00002857 llvm::StringSwitch<LangOptions::DefaultCallingConvention>(A->getValue())
Alexey Bataeva7547182016-05-18 09:06:38 +00002858 .Case("cdecl", LangOptions::DCC_CDecl)
2859 .Case("fastcall", LangOptions::DCC_FastCall)
2860 .Case("stdcall", LangOptions::DCC_StdCall)
2861 .Case("vectorcall", LangOptions::DCC_VectorCall)
Erich Keanea957ffb2017-11-02 21:08:00 +00002862 .Case("regcall", LangOptions::DCC_RegCall)
Alexey Bataeva7547182016-05-18 09:06:38 +00002863 .Default(LangOptions::DCC_None);
2864 if (DefaultCC == LangOptions::DCC_None)
2865 Diags.Report(diag::err_drv_invalid_value)
2866 << "-fdefault-calling-conv=" << A->getValue();
2867
2868 llvm::Triple T(TargetOpts.Triple);
2869 llvm::Triple::ArchType Arch = T.getArch();
2870 bool emitError = (DefaultCC == LangOptions::DCC_FastCall ||
Reid Kleckner4b2f3262017-05-31 15:39:28 +00002871 DefaultCC == LangOptions::DCC_StdCall) &&
2872 Arch != llvm::Triple::x86;
Erich Keanea957ffb2017-11-02 21:08:00 +00002873 emitError |= (DefaultCC == LangOptions::DCC_VectorCall ||
2874 DefaultCC == LangOptions::DCC_RegCall) &&
Alexey Bataeva7547182016-05-18 09:06:38 +00002875 !(Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64);
2876 if (emitError)
2877 Diags.Report(diag::err_drv_argument_not_allowed_with)
2878 << A->getSpelling() << T.getTriple();
2879 else
2880 Opts.setDefaultCallingConv(DefaultCC);
2881 }
2882
2883 // -mrtd option
2884 if (Arg *A = Args.getLastArg(OPT_mrtd)) {
2885 if (Opts.getDefaultCallingConv() != LangOptions::DCC_None)
2886 Diags.Report(diag::err_drv_argument_not_allowed_with)
2887 << A->getSpelling() << "-fdefault-calling-conv";
2888 else {
2889 llvm::Triple T(TargetOpts.Triple);
2890 if (T.getArch() != llvm::Triple::x86)
2891 Diags.Report(diag::err_drv_argument_not_allowed_with)
2892 << A->getSpelling() << T.getTriple();
2893 else
2894 Opts.setDefaultCallingConv(LangOptions::DCC_StdCall);
2895 }
2896 }
2897
Alexey Bataeva06155d2019-08-07 14:39:17 +00002898 // Check if -fopenmp is specified and set default version to 4.5.
2899 Opts.OpenMP = Args.hasArg(options::OPT_fopenmp) ? 45 : 0;
Alexey Bataeve927ca72017-12-29 17:36:15 +00002900 // Check if -fopenmp-simd is specified.
Alexey Bataev66f95772018-05-21 16:40:32 +00002901 bool IsSimdSpecified =
2902 Args.hasFlag(options::OPT_fopenmp_simd, options::OPT_fno_openmp_simd,
2903 /*Default=*/false);
2904 Opts.OpenMPSimd = !Opts.OpenMP && IsSimdSpecified;
Samuel Antaof8b50122015-07-13 22:54:53 +00002905 Opts.OpenMPUseTLS =
2906 Opts.OpenMP && !Args.hasArg(options::OPT_fnoopenmp_use_tls);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002907 Opts.OpenMPIsDevice =
2908 Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_is_device);
Alexey Bataev77403de2018-07-26 15:17:38 +00002909 bool IsTargetSpecified =
2910 Opts.OpenMPIsDevice || Args.hasArg(options::OPT_fopenmp_targets_EQ);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002911
Alexey Bataeve927ca72017-12-29 17:36:15 +00002912 if (Opts.OpenMP || Opts.OpenMPSimd) {
Alexey Bataev77403de2018-07-26 15:17:38 +00002913 if (int Version = getLastArgIntValue(
2914 Args, OPT_fopenmp_version_EQ,
2915 (IsSimdSpecified || IsTargetSpecified) ? 45 : Opts.OpenMP, Diags))
Alexey Bataevc6bd8912016-05-26 11:10:11 +00002916 Opts.OpenMP = Version;
Alexey Bataev77403de2018-07-26 15:17:38 +00002917 else if (IsSimdSpecified || IsTargetSpecified)
Alexey Bataeve927ca72017-12-29 17:36:15 +00002918 Opts.OpenMP = 45;
Alexey Bataevc6bd8912016-05-26 11:10:11 +00002919 // Provide diagnostic when a given target is not expected to be an OpenMP
2920 // device or host.
2921 if (!Opts.OpenMPIsDevice) {
2922 switch (T.getArch()) {
2923 default:
2924 break;
2925 // Add unsupported host targets here:
2926 case llvm::Triple::nvptx:
2927 case llvm::Triple::nvptx64:
Eugene Zelenko44357ee2018-03-26 21:45:04 +00002928 Diags.Report(diag::err_drv_omp_host_target_not_supported)
Alexey Bataevc6bd8912016-05-26 11:10:11 +00002929 << TargetOpts.Triple;
2930 break;
2931 }
Samuel Antao45bfe4c2016-02-08 15:59:20 +00002932 }
2933 }
2934
Gheorghe-Teodor Berceae3b0a192017-08-07 20:57:59 +00002935 // Set the flag to prevent the implementation from emitting device exception
2936 // handling code for those requiring so.
Sven van Haastregt2ca6ba12018-05-09 13:16:17 +00002937 if ((Opts.OpenMPIsDevice && T.isNVPTX()) || Opts.OpenCLCPlusPlus) {
Gheorghe-Teodor Berceae3b0a192017-08-07 20:57:59 +00002938 Opts.Exceptions = 0;
2939 Opts.CXXExceptions = 0;
2940 }
Alexey Bataeve4090182018-11-02 14:54:07 +00002941 if (Opts.OpenMPIsDevice && T.isNVPTX()) {
2942 Opts.OpenMPCUDANumSMs =
2943 getLastArgIntValue(Args, options::OPT_fopenmp_cuda_number_of_sm_EQ,
2944 Opts.OpenMPCUDANumSMs, Diags);
2945 Opts.OpenMPCUDABlocksPerSM =
2946 getLastArgIntValue(Args, options::OPT_fopenmp_cuda_blocks_per_sm_EQ,
2947 Opts.OpenMPCUDABlocksPerSM, Diags);
Alexey Bataev8061acd2019-02-20 16:36:22 +00002948 Opts.OpenMPCUDAReductionBufNum = getLastArgIntValue(
2949 Args, options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ,
2950 Opts.OpenMPCUDAReductionBufNum, Diags);
Alexey Bataeve4090182018-11-02 14:54:07 +00002951 }
Gheorghe-Teodor Berceae3b0a192017-08-07 20:57:59 +00002952
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00002953 // Prevent auto-widening the representation of loop counters during an
2954 // OpenMP collapse clause.
2955 Opts.OpenMPOptimisticCollapse =
2956 Args.hasArg(options::OPT_fopenmp_optimistic_collapse) ? 1 : 0;
2957
Samuel Antaoee8fb302016-01-06 13:42:12 +00002958 // Get the OpenMP target triples if any.
Samuel Antao1168d63c2016-06-30 21:22:08 +00002959 if (Arg *A = Args.getLastArg(options::OPT_fopenmp_targets_EQ)) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002960
2961 for (unsigned i = 0; i < A->getNumValues(); ++i) {
2962 llvm::Triple TT(A->getValue(i));
2963
Gheorghe-Teodor Berceaef5e1062017-08-07 21:11:10 +00002964 if (TT.getArch() == llvm::Triple::UnknownArch ||
2965 !(TT.getArch() == llvm::Triple::ppc ||
2966 TT.getArch() == llvm::Triple::ppc64 ||
2967 TT.getArch() == llvm::Triple::ppc64le ||
2968 TT.getArch() == llvm::Triple::nvptx ||
2969 TT.getArch() == llvm::Triple::nvptx64 ||
2970 TT.getArch() == llvm::Triple::x86 ||
2971 TT.getArch() == llvm::Triple::x86_64))
Eugene Zelenko44357ee2018-03-26 21:45:04 +00002972 Diags.Report(diag::err_drv_invalid_omp_target) << A->getValue(i);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002973 else
2974 Opts.OMPTargetTriples.push_back(TT);
2975 }
2976 }
2977
2978 // Get OpenMP host file path if any and report if a non existent file is
2979 // found
Samuel Antao1168d63c2016-06-30 21:22:08 +00002980 if (Arg *A = Args.getLastArg(options::OPT_fopenmp_host_ir_file_path)) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002981 Opts.OMPHostIRFile = A->getValue();
2982 if (!llvm::sys::fs::exists(Opts.OMPHostIRFile))
Eugene Zelenko44357ee2018-03-26 21:45:04 +00002983 Diags.Report(diag::err_drv_omp_host_ir_file_not_found)
Samuel Antaoee8fb302016-01-06 13:42:12 +00002984 << Opts.OMPHostIRFile;
2985 }
Douglas Gregor15171282013-01-15 06:45:29 +00002986
Alexey Bader3f62fa62019-02-25 11:48:48 +00002987 Opts.SYCLIsDevice = Args.hasArg(options::OPT_fsycl_is_device);
2988
Alexey Bataev80a9a612018-08-30 14:45:24 +00002989 // Set CUDA mode for OpenMP target NVPTX if specified in options
Carlo Bertolli79712092018-02-28 20:48:35 +00002990 Opts.OpenMPCUDAMode = Opts.OpenMPIsDevice && T.isNVPTX() &&
2991 Args.hasArg(options::OPT_fopenmp_cuda_mode);
2992
Alexey Bataev80a9a612018-08-30 14:45:24 +00002993 // Set CUDA mode for OpenMP target NVPTX if specified in options
2994 Opts.OpenMPCUDAForceFullRuntime =
2995 Opts.OpenMPIsDevice && T.isNVPTX() &&
2996 Args.hasArg(options::OPT_fopenmp_cuda_force_full_runtime);
2997
Chandler Carruth61fbf622011-04-23 09:27:53 +00002998 // Record whether the __DEPRECATED define was requested.
2999 Opts.Deprecated = Args.hasFlag(OPT_fdeprecated_macro,
3000 OPT_fno_deprecated_macro,
3001 Opts.Deprecated);
3002
Daniel Dunbarc70c3932009-12-01 03:16:53 +00003003 // FIXME: Eliminate this dependency.
Dylan Noblesmith4c004f32012-08-08 16:09:15 +00003004 unsigned Opt = getOptimizationLevel(Args, IK, Diags),
Chad Rosierf2d39642013-04-10 21:30:03 +00003005 OptSize = getOptimizationLevelSize(Args);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00003006 Opts.Optimize = Opt != 0;
Dylan Noblesmith4c004f32012-08-08 16:09:15 +00003007 Opts.OptimizeSize = OptSize != 0;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00003008
3009 // This is the __NO_INLINE__ define, which just depends on things like the
3010 // optimization level and -fno-inline, not actually whether the backend has
3011 // inlining enabled.
Chandler Carruthfcd33142016-12-23 01:24:49 +00003012 Opts.NoInlineDefine = !Opts.Optimize;
3013 if (Arg *InlineArg = Args.getLastArg(
3014 options::OPT_finline_functions, options::OPT_finline_hint_functions,
3015 options::OPT_fno_inline_functions, options::OPT_fno_inline))
3016 if (InlineArg->getOption().matches(options::OPT_fno_inline))
3017 Opts.NoInlineDefine = true;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00003018
Pekka Jaaskelainen37014502014-12-10 16:41:14 +00003019 Opts.FastMath = Args.hasArg(OPT_ffast_math) ||
3020 Args.hasArg(OPT_cl_fast_relaxed_math);
3021 Opts.FiniteMathOnly = Args.hasArg(OPT_ffinite_math_only) ||
3022 Args.hasArg(OPT_cl_finite_math_only) ||
3023 Args.hasArg(OPT_cl_fast_relaxed_math);
Alexandros Lamprineasf5a8e6c2015-10-02 14:56:37 +00003024 Opts.UnsafeFPMath = Args.hasArg(OPT_menable_unsafe_fp_math) ||
3025 Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
3026 Args.hasArg(OPT_cl_fast_relaxed_math);
Chandler Carruth306bd2c2012-01-02 14:19:45 +00003027
Adam Nemet049a31d2017-03-29 21:54:24 +00003028 if (Arg *A = Args.getLastArg(OPT_ffp_contract)) {
3029 StringRef Val = A->getValue();
3030 if (Val == "fast")
3031 Opts.setDefaultFPContractMode(LangOptions::FPC_Fast);
3032 else if (Val == "on")
3033 Opts.setDefaultFPContractMode(LangOptions::FPC_On);
3034 else if (Val == "off")
3035 Opts.setDefaultFPContractMode(LangOptions::FPC_Off);
3036 else
3037 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
3038 }
3039
Ted Kremenekb47e6bc2012-09-13 06:41:18 +00003040 Opts.RetainCommentsFromSystemHeaders =
3041 Args.hasArg(OPT_fretain_comments_from_system_headers);
3042
Reid Kleckner898229a2013-06-14 17:17:23 +00003043 unsigned SSP = getLastArgIntValue(Args, OPT_stack_protector, 0, Diags);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00003044 switch (SSP) {
3045 default:
3046 Diags.Report(diag::err_drv_invalid_value)
3047 << Args.getLastArg(OPT_stack_protector)->getAsString(Args) << SSP;
3048 break;
Douglas Gregor79a91412011-09-13 17:21:33 +00003049 case 0: Opts.setStackProtector(LangOptions::SSPOff); break;
3050 case 1: Opts.setStackProtector(LangOptions::SSPOn); break;
Josh Mageee0fc1a82014-02-11 01:35:14 +00003051 case 2: Opts.setStackProtector(LangOptions::SSPStrong); break;
3052 case 3: Opts.setStackProtector(LangOptions::SSPReq); break;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00003053 }
Richard Smith52be6192012-11-05 22:04:41 +00003054
JF Bastien14daa202018-12-18 05:12:21 +00003055 if (Arg *A = Args.getLastArg(OPT_ftrivial_auto_var_init)) {
3056 StringRef Val = A->getValue();
3057 if (Val == "uninitialized")
3058 Opts.setTrivialAutoVarInit(
3059 LangOptions::TrivialAutoVarInitKind::Uninitialized);
3060 else if (Val == "zero")
3061 Opts.setTrivialAutoVarInit(LangOptions::TrivialAutoVarInitKind::Zero);
3062 else if (Val == "pattern")
3063 Opts.setTrivialAutoVarInit(LangOptions::TrivialAutoVarInitKind::Pattern);
3064 else
3065 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
3066 }
3067
Richard Smith52be6192012-11-05 22:04:41 +00003068 // Parse -fsanitize= arguments.
Alexey Samsonov88459522015-01-12 22:39:12 +00003069 parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
3070 Diags, Opts.Sanitize);
Kostya Serebryanyaed71a82014-10-09 17:53:04 +00003071 // -fsanitize-address-field-padding=N has to be a LangOpt, parse it here.
Alexey Samsonova0416102014-11-11 01:26:14 +00003072 Opts.SanitizeAddressFieldPadding =
Kostya Serebryanyaed71a82014-10-09 17:53:04 +00003073 getLastArgIntValue(Args, OPT_fsanitize_address_field_padding, 0, Diags);
Alexey Samsonova511cdd2015-02-04 17:40:08 +00003074 Opts.SanitizerBlacklistFiles = Args.getAllArgValues(OPT_fsanitize_blacklist);
Dean Michael Berris835832d2017-03-30 00:29:36 +00003075
Dean Michael Berris504fc222017-03-30 22:46:45 +00003076 // -fxray-instrument
Dean Michael Berris835832d2017-03-30 00:29:36 +00003077 Opts.XRayInstrument =
3078 Args.hasFlag(OPT_fxray_instrument, OPT_fnoxray_instrument, false);
Dean Michael Berris504fc222017-03-30 22:46:45 +00003079
Dean Michael Berris1a5b10d2017-11-30 00:04:54 +00003080 // -fxray-always-emit-customevents
3081 Opts.XRayAlwaysEmitCustomEvents =
3082 Args.hasFlag(OPT_fxray_always_emit_customevents,
3083 OPT_fnoxray_always_emit_customevents, false);
3084
Keith Wyssf437e352018-04-17 21:32:43 +00003085 // -fxray-always-emit-typedevents
3086 Opts.XRayAlwaysEmitTypedEvents =
3087 Args.hasFlag(OPT_fxray_always_emit_typedevents,
3088 OPT_fnoxray_always_emit_customevents, false);
3089
Dean Michael Berris504fc222017-03-30 22:46:45 +00003090 // -fxray-{always,never}-instrument= filenames.
Dean Michael Berris835832d2017-03-30 00:29:36 +00003091 Opts.XRayAlwaysInstrumentFiles =
3092 Args.getAllArgValues(OPT_fxray_always_instrument);
3093 Opts.XRayNeverInstrumentFiles =
3094 Args.getAllArgValues(OPT_fxray_never_instrument);
Dean Michael Berris20dc6ef2018-04-09 04:02:09 +00003095 Opts.XRayAttrListFiles = Args.getAllArgValues(OPT_fxray_attr_list);
Alex Lorenz1be800c52017-04-19 08:58:56 +00003096
Piotr Padlewskie368de32018-06-13 13:55:42 +00003097 // -fforce-emit-vtables
3098 Opts.ForceEmitVTables = Args.hasArg(OPT_fforce_emit_vtables);
3099
Alex Lorenz1be800c52017-04-19 08:58:56 +00003100 // -fallow-editor-placeholders
3101 Opts.AllowEditorPlaceholders = Args.hasArg(OPT_fallow_editor_placeholders);
Akira Hatanakafcbe17c2018-03-28 21:13:14 +00003102
Erik Pilkington5a559e62018-08-21 17:24:06 +00003103 Opts.RegisterStaticDestructors = !Args.hasArg(OPT_fno_cxx_static_destructors);
3104
Akira Hatanakafcbe17c2018-03-28 21:13:14 +00003105 if (Arg *A = Args.getLastArg(OPT_fclang_abi_compat_EQ)) {
3106 Opts.setClangABICompat(LangOptions::ClangABI::Latest);
3107
3108 StringRef Ver = A->getValue();
3109 std::pair<StringRef, StringRef> VerParts = Ver.split('.');
3110 unsigned Major, Minor = 0;
3111
3112 // Check the version number is valid: either 3.x (0 <= x <= 9) or
3113 // y or y.0 (4 <= y <= current version).
3114 if (!VerParts.first.startswith("0") &&
3115 !VerParts.first.getAsInteger(10, Major) &&
3116 3 <= Major && Major <= CLANG_VERSION_MAJOR &&
3117 (Major == 3 ? VerParts.second.size() == 1 &&
3118 !VerParts.second.getAsInteger(10, Minor)
3119 : VerParts.first.size() == Ver.size() ||
3120 VerParts.second == "0")) {
3121 // Got a valid version number.
3122 if (Major == 3 && Minor <= 8)
3123 Opts.setClangABICompat(LangOptions::ClangABI::Ver3_8);
3124 else if (Major <= 4)
3125 Opts.setClangABICompat(LangOptions::ClangABI::Ver4);
Richard Smith880057c2018-04-02 18:29:44 +00003126 else if (Major <= 6)
3127 Opts.setClangABICompat(LangOptions::ClangABI::Ver6);
Richard Smith6822bd72018-10-26 19:26:45 +00003128 else if (Major <= 7)
3129 Opts.setClangABICompat(LangOptions::ClangABI::Ver7);
Akira Hatanakafcbe17c2018-03-28 21:13:14 +00003130 } else if (Ver != "latest") {
3131 Diags.Report(diag::err_drv_invalid_value)
3132 << A->getAsString(Args) << A->getValue();
3133 }
3134 }
Peter Collingbourne54d13b42018-05-30 03:40:04 +00003135
3136 Opts.CompleteMemberPointers = Args.hasArg(OPT_fcomplete_member_pointers);
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00003137 Opts.BuildingPCHWithObjectFile = Args.hasArg(OPT_building_pch_with_obj);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00003138}
3139
Alex Lorenzfb7654a2017-06-16 20:13:39 +00003140static bool isStrictlyPreprocessorAction(frontend::ActionKind Action) {
3141 switch (Action) {
3142 case frontend::ASTDeclList:
3143 case frontend::ASTDump:
3144 case frontend::ASTPrint:
3145 case frontend::ASTView:
3146 case frontend::EmitAssembly:
3147 case frontend::EmitBC:
3148 case frontend::EmitHTML:
3149 case frontend::EmitLLVM:
3150 case frontend::EmitLLVMOnly:
3151 case frontend::EmitCodeGenOnly:
3152 case frontend::EmitObj:
3153 case frontend::FixIt:
3154 case frontend::GenerateModule:
3155 case frontend::GenerateModuleInterface:
Richard Smithd6509cf2018-09-15 01:21:15 +00003156 case frontend::GenerateHeaderModule:
Alex Lorenzfb7654a2017-06-16 20:13:39 +00003157 case frontend::GeneratePCH:
Puyan Lotfi68f29da2019-06-20 16:59:48 +00003158 case frontend::GenerateInterfaceYAMLExpV1:
3159 case frontend::GenerateInterfaceTBEExpV1:
Alex Lorenzfb7654a2017-06-16 20:13:39 +00003160 case frontend::ParseSyntaxOnly:
3161 case frontend::ModuleFileInfo:
3162 case frontend::VerifyPCH:
3163 case frontend::PluginAction:
Alex Lorenzfb7654a2017-06-16 20:13:39 +00003164 case frontend::RewriteObjC:
3165 case frontend::RewriteTest:
3166 case frontend::RunAnalysis:
Gabor Horvath207e7b12018-02-10 14:04:45 +00003167 case frontend::TemplightDump:
Alex Lorenzfb7654a2017-06-16 20:13:39 +00003168 case frontend::MigrateSource:
3169 return false;
3170
Aaron Ballman16ed8dd2018-05-31 13:57:09 +00003171 case frontend::DumpCompilerOptions:
Alex Lorenzfb7654a2017-06-16 20:13:39 +00003172 case frontend::DumpRawTokens:
3173 case frontend::DumpTokens:
3174 case frontend::InitOnly:
3175 case frontend::PrintPreamble:
3176 case frontend::PrintPreprocessedInput:
3177 case frontend::RewriteMacros:
3178 case frontend::RunPreprocessorOnly:
Alex Lorenz6e2d36b2019-06-03 22:59:17 +00003179 case frontend::PrintDependencyDirectivesSourceMinimizerOutput:
Alex Lorenzfb7654a2017-06-16 20:13:39 +00003180 return true;
3181 }
3182 llvm_unreachable("invalid frontend action");
3183}
3184
Daniel Dunbar6048e7f2009-12-03 05:11:16 +00003185static void ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args,
Alex Lorenzfb7654a2017-06-16 20:13:39 +00003186 DiagnosticsEngine &Diags,
3187 frontend::ActionKind Action) {
Daniel Dunbar37300482010-05-20 16:54:55 +00003188 Opts.ImplicitPCHInclude = Args.getLastArgValue(OPT_include_pch);
Mike Rice58df1af2018-09-11 17:10:44 +00003189 Opts.PCHWithHdrStop = Args.hasArg(OPT_pch_through_hdrstop_create) ||
3190 Args.hasArg(OPT_pch_through_hdrstop_use);
3191 Opts.PCHWithHdrStopCreate = Args.hasArg(OPT_pch_through_hdrstop_create);
Erich Keane76675de2018-07-05 17:22:13 +00003192 Opts.PCHThroughHeader = Args.getLastArgValue(OPT_pch_through_header_EQ);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00003193 Opts.UsePredefines = !Args.hasArg(OPT_undef);
Douglas Gregor7f6d60d2010-03-19 16:15:56 +00003194 Opts.DetailedRecord = Args.hasArg(OPT_detailed_preprocessing_record);
Douglas Gregorce3a8292010-07-27 00:27:13 +00003195 Opts.DisablePCHValidation = Args.hasArg(OPT_fno_validate_pch);
Argyrios Kyrtzidis7b5d9102017-02-27 02:06:18 +00003196 Opts.AllowPCHWithCompilerErrors = Args.hasArg(OPT_fallow_pch_with_errors);
Argyrios Kyrtzidis0427be92010-10-14 20:14:25 +00003197
Argyrios Kyrtzidisa11aca42010-10-14 20:14:18 +00003198 Opts.DumpDeserializedPCHDecls = Args.hasArg(OPT_dump_deserialized_pch_decls);
Eugene Zelenko44357ee2018-03-26 21:45:04 +00003199 for (const auto *A : Args.filtered(OPT_error_on_deserialized_pch_decl))
Richard Smithbd55daf2012-11-01 04:30:05 +00003200 Opts.DeserializedPCHDeclsToErrorOn.insert(A->getValue());
Douglas Gregorce3a8292010-07-27 00:27:13 +00003201
Douglas Gregor3f4bea02010-07-26 21:36:20 +00003202 if (const Arg *A = Args.getLastArg(OPT_preamble_bytes_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00003203 StringRef Value(A->getValue());
Douglas Gregor3f4bea02010-07-26 21:36:20 +00003204 size_t Comma = Value.find(',');
3205 unsigned Bytes = 0;
3206 unsigned EndOfLine = 0;
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00003207
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003208 if (Comma == StringRef::npos ||
Douglas Gregor3f4bea02010-07-26 21:36:20 +00003209 Value.substr(0, Comma).getAsInteger(10, Bytes) ||
3210 Value.substr(Comma + 1).getAsInteger(10, EndOfLine))
3211 Diags.Report(diag::err_drv_preamble_format);
3212 else {
3213 Opts.PrecompiledPreambleBytes.first = Bytes;
3214 Opts.PrecompiledPreambleBytes.second = (EndOfLine != 0);
3215 }
3216 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00003217
Alexander Ivchenko0fb8c872018-05-18 11:56:21 +00003218 // Add the __CET__ macro if a CFProtection option is set.
3219 if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
3220 StringRef Name = A->getValue();
3221 if (Name == "branch")
3222 Opts.addMacroDef("__CET__=1");
3223 else if (Name == "return")
3224 Opts.addMacroDef("__CET__=2");
3225 else if (Name == "full")
3226 Opts.addMacroDef("__CET__=3");
3227 }
3228
Daniel Dunbarc70c3932009-12-01 03:16:53 +00003229 // Add macros from the command line.
Eugene Zelenko44357ee2018-03-26 21:45:04 +00003230 for (const auto *A : Args.filtered(OPT_D, OPT_U)) {
Sean Silva14facf32015-06-09 01:57:17 +00003231 if (A->getOption().matches(OPT_D))
3232 Opts.addMacroDef(A->getValue());
Daniel Dunbarc70c3932009-12-01 03:16:53 +00003233 else
Sean Silva14facf32015-06-09 01:57:17 +00003234 Opts.addMacroUndef(A->getValue());
Daniel Dunbarc70c3932009-12-01 03:16:53 +00003235 }
3236
Daniel Dunbar37300482010-05-20 16:54:55 +00003237 Opts.MacroIncludes = Args.getAllArgValues(OPT_imacros);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00003238
3239 // Add the ordered list of -includes.
Eugene Zelenko44357ee2018-03-26 21:45:04 +00003240 for (const auto *A : Args.filtered(OPT_include))
Benjamin Kramer3204b152015-05-29 19:42:19 +00003241 Opts.Includes.emplace_back(A->getValue());
Daniel Dunbar6048e7f2009-12-03 05:11:16 +00003242
Eugene Zelenko44357ee2018-03-26 21:45:04 +00003243 for (const auto *A : Args.filtered(OPT_chain_include))
Benjamin Kramer3204b152015-05-29 19:42:19 +00003244 Opts.ChainedIncludes.emplace_back(A->getValue());
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00003245
Eugene Zelenko44357ee2018-03-26 21:45:04 +00003246 for (const auto *A : Args.filtered(OPT_remap_file)) {
Sean Silva14facf32015-06-09 01:57:17 +00003247 std::pair<StringRef, StringRef> Split = StringRef(A->getValue()).split(';');
Daniel Dunbar6048e7f2009-12-03 05:11:16 +00003248
3249 if (Split.second.empty()) {
Daniel Dunbara442fd52010-06-11 22:00:13 +00003250 Diags.Report(diag::err_drv_invalid_remap_file) << A->getAsString(Args);
Daniel Dunbar6048e7f2009-12-03 05:11:16 +00003251 continue;
3252 }
3253
3254 Opts.addRemappedFile(Split.first, Split.second);
3255 }
Sean Silva14facf32015-06-09 01:57:17 +00003256
John McCall31168b02011-06-15 23:02:42 +00003257 if (Arg *A = Args.getLastArg(OPT_fobjc_arc_cxxlib_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00003258 StringRef Name = A->getValue();
John McCall31168b02011-06-15 23:02:42 +00003259 unsigned Library = llvm::StringSwitch<unsigned>(Name)
3260 .Case("libc++", ARCXX_libcxx)
3261 .Case("libstdc++", ARCXX_libstdcxx)
3262 .Case("none", ARCXX_nolib)
3263 .Default(~0U);
3264 if (Library == ~0U)
3265 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
3266 else
3267 Opts.ObjCXXARCStandardLibrary = (ObjCXXARCStandardLibraryKind)Library;
3268 }
Alex Lorenzfb7654a2017-06-16 20:13:39 +00003269
3270 // Always avoid lexing editor placeholders when we're just running the
3271 // preprocessor as we never want to emit the
3272 // "editor placeholder in source file" error in PP only mode.
3273 if (isStrictlyPreprocessorAction(Action))
3274 Opts.LexEditorPlaceholders = false;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00003275}
3276
3277static void ParsePreprocessorOutputArgs(PreprocessorOutputOptions &Opts,
Jordan Rose17441582013-01-30 01:52:57 +00003278 ArgList &Args,
3279 frontend::ActionKind Action) {
Alex Lorenzfb7654a2017-06-16 20:13:39 +00003280 if (isStrictlyPreprocessorAction(Action))
Jordan Rose17441582013-01-30 01:52:57 +00003281 Opts.ShowCPP = !Args.hasArg(OPT_dM);
Alex Lorenzfb7654a2017-06-16 20:13:39 +00003282 else
3283 Opts.ShowCPP = 0;
Jordan Rose17441582013-01-30 01:52:57 +00003284
Daniel Dunbarc70c3932009-12-01 03:16:53 +00003285 Opts.ShowComments = Args.hasArg(OPT_C);
Daniel Dunbard4352752010-08-24 22:44:13 +00003286 Opts.ShowLineMarkers = !Args.hasArg(OPT_P);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00003287 Opts.ShowMacroComments = Args.hasArg(OPT_CC);
Daniel Dunbard4352752010-08-24 22:44:13 +00003288 Opts.ShowMacros = Args.hasArg(OPT_dM) || Args.hasArg(OPT_dD);
Bruno Cardoso Lopes6fa3b742016-11-17 22:45:31 +00003289 Opts.ShowIncludeDirectives = Args.hasArg(OPT_dI);
David Blaikiee993e4c2012-06-14 17:36:09 +00003290 Opts.RewriteIncludes = Args.hasArg(OPT_frewrite_includes);
Richard Smith86a3ef52017-06-09 21:24:02 +00003291 Opts.RewriteImports = Args.hasArg(OPT_frewrite_imports);
Reid Kleckner1df0fea2015-02-26 00:17:25 +00003292 Opts.UseLineDirectives = Args.hasArg(OPT_fuse_line_directives);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00003293}
3294
Saleem Abdulrasoolf7b3d6c2016-04-08 16:52:05 +00003295static void ParseTargetArgs(TargetOptions &Opts, ArgList &Args,
3296 DiagnosticsEngine &Diags) {
Ali Tamurbc1cd922018-10-08 22:25:20 +00003297 Opts.CodeModel = getCodeModel(Args, Diags);
Daniel Dunbar37300482010-05-20 16:54:55 +00003298 Opts.ABI = Args.getLastArgValue(OPT_target_abi);
Saleem Abdulrasoolf7b3d6c2016-04-08 16:52:05 +00003299 if (Arg *A = Args.getLastArg(OPT_meabi)) {
3300 StringRef Value = A->getValue();
3301 llvm::EABI EABIVersion = llvm::StringSwitch<llvm::EABI>(Value)
3302 .Case("default", llvm::EABI::Default)
3303 .Case("4", llvm::EABI::EABI4)
3304 .Case("5", llvm::EABI::EABI5)
3305 .Case("gnu", llvm::EABI::GNU)
3306 .Default(llvm::EABI::Unknown);
3307 if (EABIVersion == llvm::EABI::Unknown)
3308 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
3309 << Value;
3310 else
Yuka Takahashidc771502017-07-01 07:57:23 +00003311 Opts.EABIVersion = EABIVersion;
Saleem Abdulrasoolf7b3d6c2016-04-08 16:52:05 +00003312 }
Daniel Dunbar37300482010-05-20 16:54:55 +00003313 Opts.CPU = Args.getLastArgValue(OPT_target_cpu);
Rafael Espindolaeb265472013-08-21 21:59:03 +00003314 Opts.FPMath = Args.getLastArgValue(OPT_mfpmath);
Douglas Gregorcb177f12012-10-16 23:40:58 +00003315 Opts.FeaturesAsWritten = Args.getAllArgValues(OPT_target_feature);
Daniel Dunbara1d107c2010-08-11 23:07:42 +00003316 Opts.LinkerVersion = Args.getLastArgValue(OPT_target_linker_version);
Petr Hosekf92ca012018-05-25 20:39:37 +00003317 Opts.Triple = Args.getLastArgValue(OPT_triple);
Sebastian Pop8188c8a2011-11-01 21:33:06 +00003318 // Use the default target triple if unspecified.
Daniel Dunbarc70c3932009-12-01 03:16:53 +00003319 if (Opts.Triple.empty())
Sebastian Pop8188c8a2011-11-01 21:33:06 +00003320 Opts.Triple = llvm::sys::getDefaultTargetTriple();
Petr Hosekf92ca012018-05-25 20:39:37 +00003321 Opts.Triple = llvm::Triple::normalize(Opts.Triple);
Alexey Bader0ea07532016-11-01 15:50:52 +00003322 Opts.OpenCLExtensionsAsWritten = Args.getAllArgValues(OPT_cl_ext_EQ);
Mandeep Singh Grangac24bb52018-02-25 03:58:23 +00003323 Opts.ForceEnableInt128 = Args.hasArg(OPT_fforce_enable_int128);
Artem Belevich679dafe2018-05-09 23:10:09 +00003324 Opts.NVPTXUseShortPointers = Args.hasFlag(
3325 options::OPT_fcuda_short_ptr, options::OPT_fno_cuda_short_ptr, false);
Alex Lorenz0a264f32018-12-17 19:19:15 +00003326 if (Arg *A = Args.getLastArg(options::OPT_target_sdk_version_EQ)) {
3327 llvm::VersionTuple Version;
3328 if (Version.tryParse(A->getValue()))
3329 Diags.Report(diag::err_drv_invalid_value)
3330 << A->getAsString(Args) << A->getValue();
3331 else
3332 Opts.SDKVersion = Version;
3333 }
Hans Wennborg50501fb2014-01-13 19:48:18 +00003334}
Daniel Dunbarc70c3932009-12-01 03:16:53 +00003335
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00003336bool CompilerInvocation::CreateFromArgs(CompilerInvocation &Res,
Chris Lattner5159f612010-11-23 08:35:12 +00003337 const char *const *ArgBegin,
3338 const char *const *ArgEnd,
David Blaikie9c902b52011-09-25 23:23:43 +00003339 DiagnosticsEngine &Diags) {
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00003340 bool Success = true;
3341
Daniel Dunbarc70c3932009-12-01 03:16:53 +00003342 // Parse the arguments.
David Blaikie0aaa7622017-01-13 17:34:15 +00003343 std::unique_ptr<OptTable> Opts = createDriverOptTable();
Hans Wennborgd1ddb9a2013-08-02 20:16:22 +00003344 const unsigned IncludedFlagsBitmask = options::CC1Option;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00003345 unsigned MissingArgIndex, MissingArgCount;
David Blaikie69a1d8c2015-06-22 22:07:27 +00003346 InputArgList Args =
David Blaikie6d492ad2015-06-21 06:32:36 +00003347 Opts->ParseArgs(llvm::makeArrayRef(ArgBegin, ArgEnd), MissingArgIndex,
David Blaikie69a1d8c2015-06-22 22:07:27 +00003348 MissingArgCount, IncludedFlagsBitmask);
Wei Mi811ff922016-04-08 17:42:32 +00003349 LangOptions &LangOpts = *Res.getLangOpts();
Daniel Dunbarc70c3932009-12-01 03:16:53 +00003350
3351 // Check for missing argument error.
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00003352 if (MissingArgCount) {
Daniel Dunbarc70c3932009-12-01 03:16:53 +00003353 Diags.Report(diag::err_drv_missing_argument)
David Blaikie69a1d8c2015-06-22 22:07:27 +00003354 << Args.getArgString(MissingArgIndex) << MissingArgCount;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00003355 Success = false;
3356 }
Daniel Dunbarc70c3932009-12-01 03:16:53 +00003357
3358 // Issue errors on unknown arguments.
Eugene Zelenko44357ee2018-03-26 21:45:04 +00003359 for (const auto *A : Args.filtered(OPT_UNKNOWN)) {
Brian Gesiak24910762018-01-06 00:25:40 +00003360 auto ArgString = A->getAsString(Args);
3361 std::string Nearest;
3362 if (Opts->findNearest(ArgString, Nearest, IncludedFlagsBitmask) > 1)
3363 Diags.Report(diag::err_drv_unknown_argument) << ArgString;
3364 else
3365 Diags.Report(diag::err_drv_unknown_argument_with_suggestion)
3366 << ArgString << Nearest;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00003367 Success = false;
3368 }
Daniel Dunbarc70c3932009-12-01 03:16:53 +00003369
David Blaikie69a1d8c2015-06-22 22:07:27 +00003370 Success &= ParseAnalyzerArgs(*Res.getAnalyzerOpts(), Args, Diags);
3371 Success &= ParseMigratorArgs(Res.getMigratorOpts(), Args);
3372 ParseDependencyOutputArgs(Res.getDependencyOutputOpts(), Args);
Bruno Cardoso Lopes76952a72016-10-11 18:21:26 +00003373 Success &=
3374 ParseDiagnosticArgs(Res.getDiagnosticOpts(), Args, &Diags,
3375 false /*DefaultDiagColor*/, false /*DefaultShowOpt*/);
Wei Mi811ff922016-04-08 17:42:32 +00003376 ParseCommentArgs(LangOpts.CommentOpts, Args);
David Blaikie69a1d8c2015-06-22 22:07:27 +00003377 ParseFileSystemArgs(Res.getFileSystemOpts(), Args);
Peter Collingbourneb8e5dd42010-12-04 01:50:36 +00003378 // FIXME: We shouldn't have to pass the DashX option around here
Erik Verbruggene0bde752016-10-27 14:17:10 +00003379 InputKind DashX = ParseFrontendArgs(Res.getFrontendOpts(), Args, Diags,
3380 LangOpts.IsHeaderFile);
Saleem Abdulrasoolf7b3d6c2016-04-08 16:52:05 +00003381 ParseTargetArgs(Res.getTargetOpts(), Args, Diags);
David Blaikie69a1d8c2015-06-22 22:07:27 +00003382 Success &= ParseCodeGenArgs(Res.getCodeGenOpts(), Args, DashX, Diags,
Teresa Johnson9e4321c2018-04-17 16:39:25 +00003383 Res.getTargetOpts(), Res.getFrontendOpts());
Adrian Prantl0ebdeac2017-03-14 23:07:49 +00003384 ParseHeaderSearchArgs(Res.getHeaderSearchOpts(), Args,
3385 Res.getFileSystemOpts().WorkingDir);
Alex Lorenz2e7ab552018-12-06 22:45:58 +00003386 llvm::Triple T(Res.getTargetOpts().Triple);
Richard Smith40c0efa2017-04-26 18:57:40 +00003387 if (DashX.getFormat() == InputKind::Precompiled ||
Rainer Orth09d890d2019-08-05 13:59:26 +00003388 DashX.getLanguage() == Language::LLVM_IR) {
Steven Wu546a1962015-07-17 20:09:56 +00003389 // ObjCAAutoRefCount and Sanitize LangOpts are used to setup the
3390 // PassManager in BackendUtil.cpp. They need to be initializd no matter
3391 // what the input type is.
3392 if (Args.hasArg(OPT_fobjc_arc))
Wei Mi811ff922016-04-08 17:42:32 +00003393 LangOpts.ObjCAutoRefCount = 1;
3394 // PIClevel and PIELevel are needed during code generation and this should be
3395 // set regardless of the input type.
3396 LangOpts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
Rafael Espindolac9d336e2016-06-23 15:07:32 +00003397 LangOpts.PIE = Args.hasArg(OPT_pic_is_pie);
Steven Wu546a1962015-07-17 20:09:56 +00003398 parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
Wei Mi811ff922016-04-08 17:42:32 +00003399 Diags, LangOpts.Sanitize);
Steven Wu546a1962015-07-17 20:09:56 +00003400 } else {
Raphael Isemannb23ccec2018-12-10 12:37:46 +00003401 // Other LangOpts are only initialized when the input is not AST or LLVM IR.
Rainer Orth09d890d2019-08-05 13:59:26 +00003402 // FIXME: Should we really be calling this for an Language::Asm input?
Yaxun Liu143f0832016-06-20 19:26:00 +00003403 ParseLangArgs(LangOpts, Args, DashX, Res.getTargetOpts(),
Richard Smith40c0efa2017-04-26 18:57:40 +00003404 Res.getPreprocessorOpts(), Diags);
Fariborz Jahanian40c5e1a2011-02-25 17:24:55 +00003405 if (Res.getFrontendOpts().ProgramAction == frontend::RewriteObjC)
Wei Mi811ff922016-04-08 17:42:32 +00003406 LangOpts.ObjCExceptions = 1;
Alex Lorenz2e7ab552018-12-06 22:45:58 +00003407 if (T.isOSDarwin() && DashX.isPreprocessed()) {
3408 // Supress the darwin-specific 'stdlibcxx-not-found' diagnostic for
3409 // preprocessed input as we don't expect it to be used with -std=libc++
3410 // anyway.
3411 Res.getDiagnosticOpts().Warnings.push_back("no-stdlibcxx-not-found");
3412 }
Fariborz Jahanian40c5e1a2011-02-25 17:24:55 +00003413 }
Benjamin Kramer12f2de12016-03-14 13:23:58 +00003414
Saleem Abdulrasool3fe5b7a2018-04-19 23:14:57 +00003415 LangOpts.FunctionAlignment =
3416 getLastArgIntValue(Args, OPT_function_alignment, 0, Diags);
3417
Artem Belevich31c3bad2016-05-19 18:44:45 +00003418 if (LangOpts.CUDA) {
3419 // During CUDA device-side compilation, the aux triple is the
3420 // triple used for host compilation.
3421 if (LangOpts.CUDAIsDevice)
3422 Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple;
Justin Lebar76945b22016-04-29 23:05:19 +00003423 }
3424
Gheorghe-Teodor Bercea59d7b772017-06-29 15:49:03 +00003425 // Set the triple of the host for OpenMP device compile.
3426 if (LangOpts.OpenMPIsDevice)
3427 Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple;
3428
Benjamin Kramerfd652b12016-03-15 09:41:39 +00003429 // FIXME: Override value name discarding when asan or msan is used because the
Benjamin Kramer12f2de12016-03-14 13:23:58 +00003430 // backend passes depend on the name of the alloca in order to print out
3431 // names.
Benjamin Kramerfd652b12016-03-15 09:41:39 +00003432 Res.getCodeGenOpts().DiscardValueNames &=
Wei Mi811ff922016-04-08 17:42:32 +00003433 !LangOpts.Sanitize.has(SanitizerKind::Address) &&
Alexander Potapenkod49c32c2018-09-07 09:21:09 +00003434 !LangOpts.Sanitize.has(SanitizerKind::KernelAddress) &&
3435 !LangOpts.Sanitize.has(SanitizerKind::Memory) &&
3436 !LangOpts.Sanitize.has(SanitizerKind::KernelMemory);
Benjamin Kramer12f2de12016-03-14 13:23:58 +00003437
Brian Gesiakf0ef1372018-01-09 21:26:47 +00003438 ParsePreprocessorArgs(Res.getPreprocessorOpts(), Args, Diags,
Alex Lorenzfb7654a2017-06-16 20:13:39 +00003439 Res.getFrontendOpts().ProgramAction);
David Blaikie69a1d8c2015-06-22 22:07:27 +00003440 ParsePreprocessorOutputArgs(Res.getPreprocessorOutputOpts(), Args,
Jordan Rose17441582013-01-30 01:52:57 +00003441 Res.getFrontendOpts().ProgramAction);
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003442
3443 // Turn on -Wspir-compat for SPIR target.
Anastasia Stulovaeba9a6e2019-05-09 10:25:45 +00003444 if (T.isSPIR())
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003445 Res.getDiagnosticOpts().Warnings.push_back("spir-compat");
Wei Mi9b3d6272017-10-16 16:50:27 +00003446
3447 // If sanitizer is enabled, disable OPT_ffine_grained_bitfield_accesses.
3448 if (Res.getCodeGenOpts().FineGrainedBitfieldAccesses &&
3449 !Res.getLangOpts()->Sanitize.empty()) {
3450 Res.getCodeGenOpts().FineGrainedBitfieldAccesses = false;
3451 Diags.Report(diag::warn_drv_fine_grained_bitfield_accesses_ignored);
3452 }
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00003453 return Success;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00003454}
Douglas Gregor1735f4e2011-09-13 23:15:45 +00003455
Douglas Gregor1735f4e2011-09-13 23:15:45 +00003456std::string CompilerInvocation::getModuleHash() const {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00003457 // Note: For QoI reasons, the things we use as a hash here should all be
3458 // dumped via the -module-info flag.
Douglas Gregor7fd08492012-11-05 19:45:09 +00003459 using llvm::hash_code;
3460 using llvm::hash_value;
3461 using llvm::hash_combine;
3462
Douglas Gregor1735f4e2011-09-13 23:15:45 +00003463 // Start the signature with the compiler version.
Douglas Gregordc779ab2012-11-05 23:30:26 +00003464 // FIXME: We'd rather use something more cryptographically sound than
Douglas Gregor7fd08492012-11-05 19:45:09 +00003465 // CityHash, but this will do for now.
3466 hash_code code = hash_value(getClangFullRepositoryVersion());
3467
Douglas Gregor1735f4e2011-09-13 23:15:45 +00003468 // Extend the signature with the language options
3469#define LANGOPT(Name, Bits, Default, Description) \
Douglas Gregor7fd08492012-11-05 19:45:09 +00003470 code = hash_combine(code, LangOpts->Name);
Douglas Gregor1735f4e2011-09-13 23:15:45 +00003471#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
Douglas Gregor7fd08492012-11-05 19:45:09 +00003472 code = hash_combine(code, static_cast<unsigned>(LangOpts->get##Name()));
Douglas Gregor1735f4e2011-09-13 23:15:45 +00003473#define BENIGN_LANGOPT(Name, Bits, Default, Description)
3474#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
3475#include "clang/Basic/LangOptions.def"
Ben Langmuircd98cb72015-06-23 18:20:18 +00003476
3477 for (StringRef Feature : LangOpts->ModuleFeatures)
3478 code = hash_combine(code, Feature);
Douglas Katzman31fdbfe2015-08-05 15:08:53 +00003479
Douglas Gregor7fd08492012-11-05 19:45:09 +00003480 // Extend the signature with the target options.
3481 code = hash_combine(code, TargetOpts->Triple, TargetOpts->CPU,
Argyrios Kyrtzidisfe6b8802014-04-29 18:45:01 +00003482 TargetOpts->ABI);
Eugene Zelenko44357ee2018-03-26 21:45:04 +00003483 for (const auto &FeatureAsWritten : TargetOpts->FeaturesAsWritten)
3484 code = hash_combine(code, FeatureAsWritten);
Douglas Gregor1735f4e2011-09-13 23:15:45 +00003485
Douglas Gregora739d9a2011-09-14 15:55:12 +00003486 // Extend the signature with preprocessor options.
Douglas Gregor7fd08492012-11-05 19:45:09 +00003487 const PreprocessorOptions &ppOpts = getPreprocessorOpts();
Douglas Gregor5dc38992013-02-07 00:21:12 +00003488 const HeaderSearchOptions &hsOpts = getHeaderSearchOpts();
Douglas Gregor7fd08492012-11-05 19:45:09 +00003489 code = hash_combine(code, ppOpts.UsePredefines, ppOpts.DetailedRecord);
3490
Eugene Zelenko44357ee2018-03-26 21:45:04 +00003491 for (const auto &I : getPreprocessorOpts().Macros) {
Douglas Gregor5dc38992013-02-07 00:21:12 +00003492 // If we're supposed to ignore this macro for the purposes of modules,
3493 // don't put it into the hash.
3494 if (!hsOpts.ModulesIgnoreMacros.empty()) {
Douglas Gregor5dc38992013-02-07 00:21:12 +00003495 // Check whether we're ignoring this macro.
Eugene Zelenko44357ee2018-03-26 21:45:04 +00003496 StringRef MacroDef = I.first;
Justin Lebar5e83dfe2016-10-21 21:45:01 +00003497 if (hsOpts.ModulesIgnoreMacros.count(
3498 llvm::CachedHashString(MacroDef.split('=').first)))
Douglas Gregor5dc38992013-02-07 00:21:12 +00003499 continue;
3500 }
3501
Eugene Zelenko44357ee2018-03-26 21:45:04 +00003502 code = hash_combine(code, I.first, I.second);
Douglas Gregor71129d52011-10-17 14:55:37 +00003503 }
Douglas Gregor7fd08492012-11-05 19:45:09 +00003504
Adrian Prantl793038d32016-01-12 21:01:56 +00003505 // Extend the signature with the sysroot and other header search options.
3506 code = hash_combine(code, hsOpts.Sysroot,
3507 hsOpts.ModuleFormat,
3508 hsOpts.UseDebugInfo,
3509 hsOpts.UseBuiltinIncludes,
Douglas Gregor7fd08492012-11-05 19:45:09 +00003510 hsOpts.UseStandardSystemIncludes,
3511 hsOpts.UseStandardCXXIncludes,
Manman Ren47a44452016-07-26 17:12:17 +00003512 hsOpts.UseLibcxx,
3513 hsOpts.ModulesValidateDiagnosticOptions);
Argyrios Kyrtzidisd113788e2014-05-04 05:27:24 +00003514 code = hash_combine(code, hsOpts.ResourceDir);
Douglas Gregor7fd08492012-11-05 19:45:09 +00003515
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00003516 // Extend the signature with the user build path.
3517 code = hash_combine(code, hsOpts.ModuleUserBuildPath);
3518
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003519 // Extend the signature with the module file extensions.
3520 const FrontendOptions &frontendOpts = getFrontendOpts();
Benjamin Kramer2e018ef2016-05-27 13:36:58 +00003521 for (const auto &ext : frontendOpts.ModuleFileExtensions) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003522 code = ext->hashExtension(code);
3523 }
3524
Adrian Prantl55fcb4e2018-11-29 22:33:09 +00003525 // When compiling with -gmodules, also hash -fdebug-prefix-map as it
3526 // affects the debug info in the PCM.
3527 if (getCodeGenOpts().DebugTypeExtRefs)
3528 for (const auto &KeyValue : getCodeGenOpts().DebugPrefixMap)
3529 code = hash_combine(code, KeyValue.first, KeyValue.second);
3530
Vedant Kumar85a83c22017-06-01 20:01:01 +00003531 // Extend the signature with the enabled sanitizers, if at least one is
3532 // enabled. Sanitizers which cannot affect AST generation aren't hashed.
3533 SanitizerSet SanHash = LangOpts->Sanitize;
3534 SanHash.clear(getPPTransparentSanitizers());
3535 if (!SanHash.empty())
3536 code = hash_combine(code, SanHash.Mask);
3537
Douglas Gregor7fd08492012-11-05 19:45:09 +00003538 return llvm::APInt(64, code).toString(36, /*Signed=*/false);
Douglas Gregor1735f4e2011-09-13 23:15:45 +00003539}
Reid Kleckner898229a2013-06-14 17:17:23 +00003540
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003541template<typename IntTy>
3542static IntTy getLastArgIntValueImpl(const ArgList &Args, OptSpecifier Id,
3543 IntTy Default,
3544 DiagnosticsEngine *Diags) {
3545 IntTy Res = Default;
Reid Kleckner898229a2013-06-14 17:17:23 +00003546 if (Arg *A = Args.getLastArg(Id)) {
3547 if (StringRef(A->getValue()).getAsInteger(10, Res)) {
3548 if (Diags)
3549 Diags->Report(diag::err_drv_invalid_int_value) << A->getAsString(Args)
3550 << A->getValue();
3551 }
3552 }
3553 return Res;
3554}
Kostya Serebryanyce2c7262013-12-27 08:11:08 +00003555
Eugene Zelenko44357ee2018-03-26 21:45:04 +00003556namespace clang {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003557
3558// Declared in clang/Frontend/Utils.h.
3559int getLastArgIntValue(const ArgList &Args, OptSpecifier Id, int Default,
3560 DiagnosticsEngine *Diags) {
3561 return getLastArgIntValueImpl<int>(Args, Id, Default, Diags);
3562}
3563
3564uint64_t getLastArgUInt64Value(const ArgList &Args, OptSpecifier Id,
3565 uint64_t Default,
3566 DiagnosticsEngine *Diags) {
3567 return getLastArgIntValueImpl<uint64_t>(Args, Id, Default, Diags);
3568}
3569
Jonas Devliegherefc514902018-10-10 13:27:25 +00003570IntrusiveRefCntPtr<llvm::vfs::FileSystem>
Ben Langmuir8832c062014-04-15 18:16:25 +00003571createVFSFromCompilerInvocation(const CompilerInvocation &CI,
3572 DiagnosticsEngine &Diags) {
Jonas Devliegherefc514902018-10-10 13:27:25 +00003573 return createVFSFromCompilerInvocation(CI, Diags,
3574 llvm::vfs::getRealFileSystem());
Ilya Biryukovaf69e402017-05-23 11:37:52 +00003575}
Ben Langmuir8832c062014-04-15 18:16:25 +00003576
Jonas Devliegherefc514902018-10-10 13:27:25 +00003577IntrusiveRefCntPtr<llvm::vfs::FileSystem> createVFSFromCompilerInvocation(
3578 const CompilerInvocation &CI, DiagnosticsEngine &Diags,
3579 IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS) {
Ilya Biryukovaf69e402017-05-23 11:37:52 +00003580 if (CI.getHeaderSearchOpts().VFSOverlayFiles.empty())
3581 return BaseFS;
3582
Volodymyr Sapsaif239a442018-10-26 22:16:24 +00003583 IntrusiveRefCntPtr<llvm::vfs::FileSystem> Result = BaseFS;
Ben Langmuir8832c062014-04-15 18:16:25 +00003584 // earlier vfs files are on the bottom
Eugene Zelenko44357ee2018-03-26 21:45:04 +00003585 for (const auto &File : CI.getHeaderSearchOpts().VFSOverlayFiles) {
Rafael Espindola2d2b4202014-07-06 17:43:24 +00003586 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
Volodymyr Sapsaif239a442018-10-26 22:16:24 +00003587 Result->getBufferForFile(File);
Rafael Espindola2d2b4202014-07-06 17:43:24 +00003588 if (!Buffer) {
Ben Langmuir8832c062014-04-15 18:16:25 +00003589 Diags.Report(diag::err_missing_vfs_overlay_file) << File;
Ben Langmuir005c2e52018-03-23 17:37:27 +00003590 continue;
Ben Langmuir8832c062014-04-15 18:16:25 +00003591 }
3592
Jonas Devliegherefc514902018-10-10 13:27:25 +00003593 IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS = llvm::vfs::getVFSFromYAML(
Volodymyr Sapsaif239a442018-10-26 22:16:24 +00003594 std::move(Buffer.get()), /*DiagHandler*/ nullptr, File,
3595 /*DiagContext*/ nullptr, Result);
3596 if (!FS) {
Ben Langmuir8832c062014-04-15 18:16:25 +00003597 Diags.Report(diag::err_invalid_vfs_overlay) << File;
Volodymyr Sapsaif239a442018-10-26 22:16:24 +00003598 continue;
3599 }
3600
3601 Result = FS;
Ben Langmuir8832c062014-04-15 18:16:25 +00003602 }
Volodymyr Sapsaif239a442018-10-26 22:16:24 +00003603 return Result;
Reid Kleckner898229a2013-06-14 17:17:23 +00003604}
Eugene Zelenko44357ee2018-03-26 21:45:04 +00003605
3606} // namespace clang