blob: ed22c1a745c09044e772bbc4a182014ad603b2cd [file] [log] [blame]
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001//===- CompilerInvocation.cpp ---------------------------------------------===//
Daniel Dunbar629f6bb2009-11-17 06:02:29 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Mehdi Amini9670f842016-07-18 19:02:11 +000010#include "clang/Frontend/CompilerInvocation.h"
Douglas Gregor6623e1f2015-11-03 18:33:07 +000011#include "TestModuleFileExtension.h"
Chad Rosier7dbc9cf2016-01-06 14:35:46 +000012#include "clang/Basic/Builtins.h"
Eugene Zelenko44357ee2018-03-26 21:45:04 +000013#include "clang/Basic/CharInfo.h"
14#include "clang/Basic/CommentOptions.h"
15#include "clang/Basic/DebugInfoOptions.h"
16#include "clang/Basic/Diagnostic.h"
17#include "clang/Basic/DiagnosticOptions.h"
18#include "clang/Basic/FileSystemOptions.h"
19#include "clang/Basic/LLVM.h"
20#include "clang/Basic/LangOptions.h"
21#include "clang/Basic/ObjCRuntime.h"
22#include "clang/Basic/Sanitizers.h"
23#include "clang/Basic/SourceLocation.h"
24#include "clang/Basic/TargetOptions.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/Basic/Version.h"
Eugene Zelenko44357ee2018-03-26 21:45:04 +000026#include "clang/Basic/VirtualFileSystem.h"
27#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"
Daniel Dunbarc70c3932009-12-01 03:16:53 +000030#include "clang/Driver/DriverDiagnostic.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "clang/Driver/Options.h"
Eugene Zelenko44357ee2018-03-26 21:45:04 +000032#include "clang/Frontend/CodeGenOptions.h"
33#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"
Daniel Dunbarc70c3932009-12-01 03:16:53 +000037#include "clang/Frontend/LangStandard.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"
Artem Belevich5d40ae32015-10-27 17:56:59 +000058#include "llvm/Linker/Linker.h"
Eugene Zelenko44357ee2018-03-26 21:45:04 +000059#include "llvm/MC/MCTargetOptions.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000060#include "llvm/Option/Arg.h"
61#include "llvm/Option/ArgList.h"
Eugene Zelenko44357ee2018-03-26 21:45:04 +000062#include "llvm/Option/OptSpecifier.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000063#include "llvm/Option/OptTable.h"
64#include "llvm/Option/Option.h"
Rong Xu9c6f1532016-03-02 20:59:36 +000065#include "llvm/ProfileData/InstrProfReader.h"
Saleem Abdulrasool62849c62014-05-08 02:28:32 +000066#include "llvm/Support/CodeGen.h"
Eugene Zelenko44357ee2018-03-26 21:45:04 +000067#include "llvm/Support/Compiler.h"
68#include "llvm/Support/Error.h"
Daniel Dunbar629f6bb2009-11-17 06:02:29 +000069#include "llvm/Support/ErrorHandling.h"
Eugene Zelenko44357ee2018-03-26 21:45:04 +000070#include "llvm/Support/ErrorOr.h"
Rafael Espindola9678d272013-06-26 05:03:40 +000071#include "llvm/Support/FileSystem.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000072#include "llvm/Support/Host.h"
Eugene Zelenko44357ee2018-03-26 21:45:04 +000073#include "llvm/Support/MathExtras.h"
74#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000075#include "llvm/Support/Path.h"
Nico Rieck7857d462013-09-11 00:38:02 +000076#include "llvm/Support/Process.h"
Eugene Zelenko44357ee2018-03-26 21:45:04 +000077#include "llvm/Support/Regex.h"
Pavel Labathd8c62902018-06-11 10:28:04 +000078#include "llvm/Support/VersionTuple.h"
Eugene Zelenko44357ee2018-03-26 21:45:04 +000079#include "llvm/Support/raw_ostream.h"
Renato Golin4854d802015-11-09 12:40:41 +000080#include "llvm/Target/TargetOptions.h"
Eugene Zelenko44357ee2018-03-26 21:45:04 +000081#include <algorithm>
Benjamin Kramer4527fb22014-03-02 17:08:31 +000082#include <atomic>
Eugene Zelenko44357ee2018-03-26 21:45:04 +000083#include <cassert>
84#include <cstddef>
85#include <cstring>
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000086#include <memory>
Eugene Zelenko44357ee2018-03-26 21:45:04 +000087#include <string>
88#include <tuple>
89#include <utility>
90#include <vector>
91
Daniel Dunbar629f6bb2009-11-17 06:02:29 +000092using namespace clang;
Eugene Zelenko44357ee2018-03-26 21:45:04 +000093using namespace driver;
94using namespace options;
95using namespace llvm::opt;
Daniel Dunbar629f6bb2009-11-17 06:02:29 +000096
Ted Kremenek8cf47df2011-11-17 23:01:24 +000097//===----------------------------------------------------------------------===//
98// Initialization.
99//===----------------------------------------------------------------------===//
100
Ted Kremenek2acedbd2011-11-18 04:32:13 +0000101CompilerInvocationBase::CompilerInvocationBase()
Eugene Zelenko44357ee2018-03-26 21:45:04 +0000102 : LangOpts(new LangOptions()), TargetOpts(new TargetOptions()),
103 DiagnosticOpts(new DiagnosticOptions()),
104 HeaderSearchOpts(new HeaderSearchOptions()),
105 PreprocessorOpts(new PreprocessorOptions()) {}
Ted Kremenek8cf47df2011-11-17 23:01:24 +0000106
Ted Kremenek2acedbd2011-11-18 04:32:13 +0000107CompilerInvocationBase::CompilerInvocationBase(const CompilerInvocationBase &X)
David Blaikieea4395e2017-01-06 19:49:01 +0000108 : LangOpts(new LangOptions(*X.getLangOpts())),
109 TargetOpts(new TargetOptions(X.getTargetOpts())),
110 DiagnosticOpts(new DiagnosticOptions(X.getDiagnosticOpts())),
111 HeaderSearchOpts(new HeaderSearchOptions(X.getHeaderSearchOpts())),
112 PreprocessorOpts(new PreprocessorOptions(X.getPreprocessorOpts())) {}
Ted Kremenek8cf47df2011-11-17 23:01:24 +0000113
Eugene Zelenko44357ee2018-03-26 21:45:04 +0000114CompilerInvocationBase::~CompilerInvocationBase() = default;
Alp Tokerc7dc0622014-05-11 22:10:52 +0000115
Ted Kremenek8cf47df2011-11-17 23:01:24 +0000116//===----------------------------------------------------------------------===//
Richard Smith33fd5512012-11-01 03:48:49 +0000117// Deserialization (from args)
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000118//===----------------------------------------------------------------------===//
119
Peter Collingbourneb8e5dd42010-12-04 01:50:36 +0000120static unsigned getOptimizationLevel(ArgList &Args, InputKind IK,
David Blaikie9c902b52011-09-25 23:23:43 +0000121 DiagnosticsEngine &Diags) {
Peter Collingbourne31587c82010-12-04 01:50:45 +0000122 unsigned DefaultOpt = 0;
Richard Smith40c0efa2017-04-26 18:57:40 +0000123 if (IK.getLanguage() == InputKind::OpenCL && !Args.hasArg(OPT_cl_opt_disable))
Peter Collingbourne31587c82010-12-04 01:50:45 +0000124 DefaultOpt = 2;
James Molloya3c85b82012-05-01 14:57:16 +0000125
126 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
127 if (A->getOption().matches(options::OPT_O0))
128 return 0;
129
Chad Rosier153d7c62013-04-10 21:26:02 +0000130 if (A->getOption().matches(options::OPT_Ofast))
131 return 3;
132
Eugene Zelenko44357ee2018-03-26 21:45:04 +0000133 assert(A->getOption().matches(options::OPT_O));
James Molloya3c85b82012-05-01 14:57:16 +0000134
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000135 StringRef S(A->getValue());
James Molloya3c85b82012-05-01 14:57:16 +0000136 if (S == "s" || S == "z" || S.empty())
137 return 2;
138
Sylvestre Ledrud340ccc2016-11-11 17:29:56 +0000139 if (S == "g")
140 return 1;
141
Reid Kleckner898229a2013-06-14 17:17:23 +0000142 return getLastArgIntValue(Args, OPT_O, DefaultOpt, Diags);
James Molloya3c85b82012-05-01 14:57:16 +0000143 }
144
145 return DefaultOpt;
146}
147
Chad Rosierf2d39642013-04-10 21:30:03 +0000148static unsigned getOptimizationLevelSize(ArgList &Args) {
James Molloya3c85b82012-05-01 14:57:16 +0000149 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
150 if (A->getOption().matches(options::OPT_O)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000151 switch (A->getValue()[0]) {
James Molloya3c85b82012-05-01 14:57:16 +0000152 default:
153 return 0;
154 case 's':
155 return 1;
156 case 'z':
157 return 2;
158 }
159 }
160 }
161 return 0;
162}
163
Richard Smith3be1cb22014-08-07 00:24:21 +0000164static void addDiagnosticArgs(ArgList &Args, OptSpecifier Group,
165 OptSpecifier GroupWithValue,
166 std::vector<std::string> &Diagnostics) {
Eugene Zelenko44357ee2018-03-26 21:45:04 +0000167 for (auto *A : Args.filtered(Group)) {
James Molloya3c85b82012-05-01 14:57:16 +0000168 if (A->getOption().getKind() == Option::FlagClass) {
Richard Smith3be1cb22014-08-07 00:24:21 +0000169 // The argument is a pure flag (such as OPT_Wall or OPT_Wdeprecated). Add
170 // its name (minus the "W" or "R" at the beginning) to the warning list.
171 Diagnostics.push_back(A->getOption().getName().drop_front(1));
172 } else if (A->getOption().matches(GroupWithValue)) {
173 // This is -Wfoo= or -Rfoo=, where foo is the name of the diagnostic group.
174 Diagnostics.push_back(A->getOption().getName().drop_front(1).rtrim("=-"));
James Molloya3c85b82012-05-01 14:57:16 +0000175 } else {
Richard Smith3be1cb22014-08-07 00:24:21 +0000176 // Otherwise, add its value (for OPT_W_Joined and similar).
Eugene Zelenko44357ee2018-03-26 21:45:04 +0000177 for (const auto *Arg : A->getValues())
Benjamin Kramer3204b152015-05-29 19:42:19 +0000178 Diagnostics.emplace_back(Arg);
James Molloya3c85b82012-05-01 14:57:16 +0000179 }
180 }
Peter Collingbourneb8e5dd42010-12-04 01:50:36 +0000181}
182
Chad Rosier7dbc9cf2016-01-06 14:35:46 +0000183static void getAllNoBuiltinFuncValues(ArgList &Args,
184 std::vector<std::string> &Funcs) {
185 SmallVector<const char *, 8> Values;
186 for (const auto &Arg : Args) {
187 const Option &O = Arg->getOption();
188 if (O.matches(options::OPT_fno_builtin_)) {
189 const char *FuncName = Arg->getValue();
190 if (Builtin::Context::isBuiltinFunc(FuncName))
191 Values.push_back(FuncName);
192 }
193 }
194 Funcs.insert(Funcs.end(), Values.begin(), Values.end());
195}
196
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000197static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args,
David Blaikie9c902b52011-09-25 23:23:43 +0000198 DiagnosticsEngine &Diags) {
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000199 bool Success = true;
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000200 if (Arg *A = Args.getLastArg(OPT_analyzer_store)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000201 StringRef Name = A->getValue();
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000202 AnalysisStores Value = llvm::StringSwitch<AnalysisStores>(Name)
203#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN) \
204 .Case(CMDFLAG, NAME##Model)
Ted Kremeneka5770cd2012-08-31 04:35:58 +0000205#include "clang/StaticAnalyzer/Core/Analyses.def"
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000206 .Default(NumStores);
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000207 if (Value == NumStores) {
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000208 Diags.Report(diag::err_drv_invalid_value)
Daniel Dunbar0bcb62d2010-06-09 22:30:54 +0000209 << A->getAsString(Args) << Name;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000210 Success = false;
211 } else {
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000212 Opts.AnalysisStoreOpt = Value;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000213 }
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000214 }
215
216 if (Arg *A = Args.getLastArg(OPT_analyzer_constraints)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000217 StringRef Name = A->getValue();
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000218 AnalysisConstraints Value = llvm::StringSwitch<AnalysisConstraints>(Name)
219#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \
220 .Case(CMDFLAG, NAME##Model)
Ted Kremeneka5770cd2012-08-31 04:35:58 +0000221#include "clang/StaticAnalyzer/Core/Analyses.def"
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000222 .Default(NumConstraints);
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000223 if (Value == NumConstraints) {
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000224 Diags.Report(diag::err_drv_invalid_value)
Daniel Dunbar0bcb62d2010-06-09 22:30:54 +0000225 << A->getAsString(Args) << Name;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000226 Success = false;
227 } else {
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000228 Opts.AnalysisConstraintsOpt = Value;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000229 }
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000230 }
231
232 if (Arg *A = Args.getLastArg(OPT_analyzer_output)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000233 StringRef Name = A->getValue();
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000234 AnalysisDiagClients Value = llvm::StringSwitch<AnalysisDiagClients>(Name)
Jordan Rose367843a2013-08-16 01:06:30 +0000235#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000236 .Case(CMDFLAG, PD_##NAME)
Ted Kremeneka5770cd2012-08-31 04:35:58 +0000237#include "clang/StaticAnalyzer/Core/Analyses.def"
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000238 .Default(NUM_ANALYSIS_DIAG_CLIENTS);
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000239 if (Value == NUM_ANALYSIS_DIAG_CLIENTS) {
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000240 Diags.Report(diag::err_drv_invalid_value)
Daniel Dunbar0bcb62d2010-06-09 22:30:54 +0000241 << A->getAsString(Args) << Name;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000242 Success = false;
243 } else {
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000244 Opts.AnalysisDiagOpt = Value;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000245 }
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000246 }
247
Anna Zaks8d4c8e12011-09-30 02:03:00 +0000248 if (Arg *A = Args.getLastArg(OPT_analyzer_purge)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000249 StringRef Name = A->getValue();
Anna Zaks8d4c8e12011-09-30 02:03:00 +0000250 AnalysisPurgeMode Value = llvm::StringSwitch<AnalysisPurgeMode>(Name)
251#define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \
252 .Case(CMDFLAG, NAME)
Ted Kremeneka5770cd2012-08-31 04:35:58 +0000253#include "clang/StaticAnalyzer/Core/Analyses.def"
Anna Zaks8d4c8e12011-09-30 02:03:00 +0000254 .Default(NumPurgeModes);
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000255 if (Value == NumPurgeModes) {
Anna Zaks8d4c8e12011-09-30 02:03:00 +0000256 Diags.Report(diag::err_drv_invalid_value)
257 << A->getAsString(Args) << Name;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000258 Success = false;
259 } else {
Anna Zaks8d4c8e12011-09-30 02:03:00 +0000260 Opts.AnalysisPurgeOpt = Value;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000261 }
Anna Zaks8d4c8e12011-09-30 02:03:00 +0000262 }
263
Anna Zaks0af3e062012-03-08 23:16:35 +0000264 if (Arg *A = Args.getLastArg(OPT_analyzer_inlining_mode)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000265 StringRef Name = A->getValue();
Anna Zaks0af3e062012-03-08 23:16:35 +0000266 AnalysisInliningMode Value = llvm::StringSwitch<AnalysisInliningMode>(Name)
267#define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \
268 .Case(CMDFLAG, NAME)
Ted Kremeneka5770cd2012-08-31 04:35:58 +0000269#include "clang/StaticAnalyzer/Core/Analyses.def"
Anna Zaks0af3e062012-03-08 23:16:35 +0000270 .Default(NumInliningModes);
271 if (Value == NumInliningModes) {
272 Diags.Report(diag::err_drv_invalid_value)
273 << A->getAsString(Args) << Name;
274 Success = false;
275 } else {
276 Opts.InliningMode = Value;
277 }
278 }
279
Argyrios Kyrtzidis17bee3e2011-02-25 00:09:51 +0000280 Opts.ShowCheckerHelp = Args.hasArg(OPT_analyzer_checker_help);
Gabor Horvathc4309902016-08-08 13:41:04 +0000281 Opts.ShowEnabledCheckerList = Args.hasArg(OPT_analyzer_list_enabled_checkers);
Anna Zaksd5478fd2014-08-29 20:01:38 +0000282 Opts.DisableAllChecks = Args.hasArg(OPT_analyzer_disable_all_checks);
283
Ted Kremenekb8f8b352012-08-30 19:26:53 +0000284 Opts.visualizeExplodedGraphWithGraphViz =
285 Args.hasArg(OPT_analyzer_viz_egraph_graphviz);
286 Opts.visualizeExplodedGraphWithUbiGraph =
287 Args.hasArg(OPT_analyzer_viz_egraph_ubigraph);
Anna Zaks72eee392012-03-28 19:59:16 +0000288 Opts.NoRetryExhausted = Args.hasArg(OPT_analyzer_disable_retry_exhausted);
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000289 Opts.AnalyzeAll = Args.hasArg(OPT_analyzer_opt_analyze_headers);
290 Opts.AnalyzerDisplayProgress = Args.hasArg(OPT_analyzer_display_progress);
Ted Kremenek68189912009-12-07 22:06:12 +0000291 Opts.AnalyzeNestedBlocks =
292 Args.hasArg(OPT_analyzer_opt_analyze_nested_blocks);
Ted Kremenek6f5131f2012-08-30 19:26:48 +0000293 Opts.eagerlyAssumeBinOpBifurcation = Args.hasArg(OPT_analyzer_eagerly_assume);
Daniel Dunbar37300482010-05-20 16:54:55 +0000294 Opts.AnalyzeSpecificFunction = Args.getLastArgValue(OPT_analyze_function);
Ted Kremenek4a2b2372010-08-03 00:09:51 +0000295 Opts.UnoptimizedCFG = Args.hasArg(OPT_analysis_UnoptimizedCFG);
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000296 Opts.TrimGraph = Args.hasArg(OPT_trim_egraph);
Reid Kleckner898229a2013-06-14 17:17:23 +0000297 Opts.maxBlockVisitOnPath =
298 getLastArgIntValue(Args, OPT_analyzer_max_loop, 4, Diags);
Anna Zaksb0286542012-02-27 21:33:16 +0000299 Opts.PrintStats = Args.hasArg(OPT_analyzer_stats);
Anna Zaks26508772012-03-02 19:05:03 +0000300 Opts.InlineMaxStackDepth =
Reid Kleckner898229a2013-06-14 17:17:23 +0000301 getLastArgIntValue(Args, OPT_analyzer_inline_max_stack_depth,
302 Opts.InlineMaxStackDepth, Diags);
Argyrios Kyrtzidis556c45e2011-02-14 18:13:31 +0000303
304 Opts.CheckersControlList.clear();
Sean Silva14facf32015-06-09 01:57:17 +0000305 for (const Arg *A :
306 Args.filtered(OPT_analyzer_checker, OPT_analyzer_disable_checker)) {
Argyrios Kyrtzidis556c45e2011-02-14 18:13:31 +0000307 A->claim();
308 bool enable = (A->getOption().getID() == OPT_analyzer_checker);
Argyrios Kyrtzidisc08d89e2011-02-24 08:42:20 +0000309 // We can have a list of comma separated checker names, e.g:
310 // '-analyzer-checker=cocoa,unix'
Richard Smithbd55daf2012-11-01 04:30:05 +0000311 StringRef checkerList = A->getValue();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000312 SmallVector<StringRef, 4> checkers;
Argyrios Kyrtzidisc08d89e2011-02-24 08:42:20 +0000313 checkerList.split(checkers, ",");
Eugene Zelenko44357ee2018-03-26 21:45:04 +0000314 for (auto checker : checkers)
Benjamin Kramer3204b152015-05-29 19:42:19 +0000315 Opts.CheckersControlList.emplace_back(checker, enable);
Argyrios Kyrtzidis556c45e2011-02-14 18:13:31 +0000316 }
Jacques Pienaara50178c2015-02-24 21:45:33 +0000317
Ted Kremenekfb5351e2012-08-29 05:55:00 +0000318 // Go through the analyzer configuration options.
Eugene Zelenko44357ee2018-03-26 21:45:04 +0000319 for (const auto *A : Args.filtered(OPT_analyzer_config)) {
Ted Kremenekfb5351e2012-08-29 05:55:00 +0000320 A->claim();
321 // We can have a list of comma separated config names, e.g:
Ted Kremenek53f3e7d2012-08-30 05:49:16 +0000322 // '-analyzer-config key1=val1,key2=val2'
Richard Smithbd55daf2012-11-01 04:30:05 +0000323 StringRef configList = A->getValue();
Ted Kremenekfb5351e2012-08-29 05:55:00 +0000324 SmallVector<StringRef, 4> configVals;
325 configList.split(configVals, ",");
Eugene Zelenko44357ee2018-03-26 21:45:04 +0000326 for (const auto &configVal : configVals) {
Ted Kremenekfb5351e2012-08-29 05:55:00 +0000327 StringRef key, val;
Eugene Zelenko44357ee2018-03-26 21:45:04 +0000328 std::tie(key, val) = configVal.split("=");
Ted Kremenekfb5351e2012-08-29 05:55:00 +0000329 if (val.empty()) {
330 Diags.Report(SourceLocation(),
Eugene Zelenko44357ee2018-03-26 21:45:04 +0000331 diag::err_analyzer_config_no_value) << configVal;
Ted Kremenekfb5351e2012-08-29 05:55:00 +0000332 Success = false;
333 break;
334 }
Ted Kremenek53f3e7d2012-08-30 05:49:16 +0000335 if (val.find('=') != StringRef::npos) {
Ted Kremenekfb5351e2012-08-29 05:55:00 +0000336 Diags.Report(SourceLocation(),
337 diag::err_analyzer_config_multiple_values)
Eugene Zelenko44357ee2018-03-26 21:45:04 +0000338 << configVal;
Ted Kremenekfb5351e2012-08-29 05:55:00 +0000339 Success = false;
340 break;
341 }
342 Opts.Config[key] = val;
343 }
344 }
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000345
George Karpenkov4a190fe2018-01-23 19:28:52 +0000346 llvm::raw_string_ostream os(Opts.FullCompilerInvocation);
Eugene Zelenko44357ee2018-03-26 21:45:04 +0000347 for (unsigned i = 0; i < Args.getNumInputArgStrings(); ++i) {
George Karpenkov4a190fe2018-01-23 19:28:52 +0000348 if (i != 0)
349 os << " ";
350 os << Args.getArgString(i);
351 }
352 os.flush();
353
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000354 return Success;
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000355}
356
Fariborz Jahanianaa7b9aa2012-01-25 00:20:29 +0000357static bool ParseMigratorArgs(MigratorOptions &Opts, ArgList &Args) {
358 Opts.NoNSAllocReallocError = Args.hasArg(OPT_migrator_no_nsalloc_error);
Fariborz Jahanian48fd81b2012-01-26 20:57:58 +0000359 Opts.NoFinalizeRemoval = Args.hasArg(OPT_migrator_no_finalize_removal);
Fariborz Jahanianaa7b9aa2012-01-25 00:20:29 +0000360 return true;
361}
362
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000363static void ParseCommentArgs(CommentOptions &Opts, ArgList &Args) {
364 Opts.BlockCommandNames = Args.getAllArgValues(OPT_fcomment_block_commands);
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +0000365 Opts.ParseAllComments = Args.hasArg(OPT_fparse_all_comments);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000366}
367
Saleem Abdulrasool62849c62014-05-08 02:28:32 +0000368static StringRef getCodeModel(ArgList &Args, DiagnosticsEngine &Diags) {
369 if (Arg *A = Args.getLastArg(OPT_mcode_model)) {
370 StringRef Value = A->getValue();
371 if (Value == "small" || Value == "kernel" || Value == "medium" ||
372 Value == "large")
373 return Value;
374 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Value;
375 }
376 return "default";
377}
378
Rafael Espindolae1d70532018-01-18 00:20:03 +0000379static llvm::Reloc::Model getRelocModel(ArgList &Args,
380 DiagnosticsEngine &Diags) {
Davide Italiano1a3665bb2017-04-01 21:07:07 +0000381 if (Arg *A = Args.getLastArg(OPT_mrelocation_model)) {
382 StringRef Value = A->getValue();
Rafael Espindolae1d70532018-01-18 00:20:03 +0000383 auto RM = llvm::StringSwitch<llvm::Optional<llvm::Reloc::Model>>(Value)
384 .Case("static", llvm::Reloc::Static)
385 .Case("pic", llvm::Reloc::PIC_)
386 .Case("ropi", llvm::Reloc::ROPI)
387 .Case("rwpi", llvm::Reloc::RWPI)
388 .Case("ropi-rwpi", llvm::Reloc::ROPI_RWPI)
389 .Case("dynamic-no-pic", llvm::Reloc::DynamicNoPIC)
390 .Default(None);
391 if (RM.hasValue())
392 return *RM;
Davide Italiano1a3665bb2017-04-01 21:07:07 +0000393 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Value;
394 }
Rafael Espindolae1d70532018-01-18 00:20:03 +0000395 return llvm::Reloc::PIC_;
Davide Italiano1a3665bb2017-04-01 21:07:07 +0000396}
397
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000398/// Create a new Regex instance out of the string value in \p RpassArg.
Diego Novillod23ec942014-05-29 19:55:06 +0000399/// It returns a pointer to the newly generated Regex instance.
400static std::shared_ptr<llvm::Regex>
401GenerateOptimizationRemarkRegex(DiagnosticsEngine &Diags, ArgList &Args,
402 Arg *RpassArg) {
403 StringRef Val = RpassArg->getValue();
404 std::string RegexError;
405 std::shared_ptr<llvm::Regex> Pattern = std::make_shared<llvm::Regex>(Val);
406 if (!Pattern->isValid(RegexError)) {
407 Diags.Report(diag::err_drv_optimization_remark_pattern)
408 << RegexError << RpassArg->getAsString(Args);
409 Pattern.reset();
410 }
411 return Pattern;
412}
413
Eric Fiselier098e6de2015-06-13 07:11:40 +0000414static bool parseDiagnosticLevelMask(StringRef FlagName,
415 const std::vector<std::string> &Levels,
416 DiagnosticsEngine *Diags,
417 DiagnosticLevelMask &M) {
418 bool Success = true;
419 for (const auto &Level : Levels) {
420 DiagnosticLevelMask const PM =
421 llvm::StringSwitch<DiagnosticLevelMask>(Level)
422 .Case("note", DiagnosticLevelMask::Note)
423 .Case("remark", DiagnosticLevelMask::Remark)
424 .Case("warning", DiagnosticLevelMask::Warning)
425 .Case("error", DiagnosticLevelMask::Error)
426 .Default(DiagnosticLevelMask::None);
427 if (PM == DiagnosticLevelMask::None) {
428 Success = false;
429 if (Diags)
430 Diags->Report(diag::err_drv_invalid_value) << FlagName << Level;
431 }
432 M = M | PM;
433 }
434 return Success;
435}
436
Alexey Samsonov88459522015-01-12 22:39:12 +0000437static void parseSanitizerKinds(StringRef FlagName,
438 const std::vector<std::string> &Sanitizers,
439 DiagnosticsEngine &Diags, SanitizerSet &S) {
440 for (const auto &Sanitizer : Sanitizers) {
Peter Collingbournebf59c342015-05-11 21:39:20 +0000441 SanitizerMask K = parseSanitizerValue(Sanitizer, /*AllowGroups=*/false);
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000442 if (K == 0)
Alexey Samsonov88459522015-01-12 22:39:12 +0000443 Diags.Report(diag::err_drv_invalid_value) << FlagName << Sanitizer;
444 else
445 S.set(K, true);
446 }
447}
448
Dean Michael Berris488f7c22018-04-13 02:31:58 +0000449static void parseXRayInstrumentationBundle(StringRef FlagName, StringRef Bundle,
450 ArgList &Args, DiagnosticsEngine &D,
451 XRayInstrSet &S) {
452 llvm::SmallVector<StringRef, 2> BundleParts;
453 llvm::SplitString(Bundle, BundleParts, ",");
454 for (const auto B : BundleParts) {
455 auto Mask = parseXRayInstrValue(B);
456 if (Mask == XRayInstrKind::None)
457 if (B != "none")
458 D.Report(diag::err_drv_invalid_value) << FlagName << Bundle;
459 else
460 S.Mask = Mask;
461 else if (Mask == XRayInstrKind::All)
462 S.Mask = Mask;
463 else
464 S.set(Mask, true);
465 }
466}
467
Rong Xu9c6f1532016-03-02 20:59:36 +0000468// Set the profile kind for fprofile-instrument.
469static void setPGOInstrumentor(CodeGenOptions &Opts, ArgList &Args,
470 DiagnosticsEngine &Diags) {
471 Arg *A = Args.getLastArg(OPT_fprofile_instrument_EQ);
472 if (A == nullptr)
473 return;
474 StringRef S = A->getValue();
475 unsigned I = llvm::StringSwitch<unsigned>(S)
476 .Case("none", CodeGenOptions::ProfileNone)
477 .Case("clang", CodeGenOptions::ProfileClangInstr)
478 .Case("llvm", CodeGenOptions::ProfileIRInstr)
479 .Default(~0U);
480 if (I == ~0U) {
481 Diags.Report(diag::err_drv_invalid_pgo_instrumentor) << A->getAsString(Args)
482 << S;
483 return;
484 }
Eugene Zelenko44357ee2018-03-26 21:45:04 +0000485 auto Instrumentor = static_cast<CodeGenOptions::ProfileInstrKind>(I);
Rong Xu9c6f1532016-03-02 20:59:36 +0000486 Opts.setProfileInstr(Instrumentor);
487}
488
489// Set the profile kind using fprofile-instrument-use-path.
490static void setPGOUseInstrumentor(CodeGenOptions &Opts,
Benjamin Kramer442b9a92016-05-29 11:04:56 +0000491 const Twine &ProfileName) {
Rong Xu9c6f1532016-03-02 20:59:36 +0000492 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(ProfileName);
493 // In error, return silently and let Clang PGOUse report the error message.
Vedant Kumarfa2d5952016-05-19 03:54:54 +0000494 if (auto E = ReaderOrErr.takeError()) {
495 llvm::consumeError(std::move(E));
Rong Xu9c6f1532016-03-02 20:59:36 +0000496 Opts.setProfileUse(CodeGenOptions::ProfileClangInstr);
497 return;
498 }
499 std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader =
500 std::move(ReaderOrErr.get());
501 if (PGOReader->isIRLevelProfile())
502 Opts.setProfileUse(CodeGenOptions::ProfileIRInstr);
503 else
504 Opts.setProfileUse(CodeGenOptions::ProfileClangInstr);
505}
506
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000507static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK,
Adrian Prantla7634472014-01-07 01:19:08 +0000508 DiagnosticsEngine &Diags,
Teresa Johnson9e4321c2018-04-17 16:39:25 +0000509 const TargetOptions &TargetOpts,
510 const FrontendOptions &FrontendOpts) {
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000511 bool Success = true;
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +0000512 llvm::Triple Triple = llvm::Triple(TargetOpts.Triple);
Peter Collingbourneb8e5dd42010-12-04 01:50:36 +0000513
Rafael Espindolafd8de1c2014-12-16 21:57:03 +0000514 unsigned OptimizationLevel = getOptimizationLevel(Args, IK, Diags);
Sylvestre Ledru5abf2ec2013-11-18 13:23:07 +0000515 // TODO: This could be done in Driver
516 unsigned MaxOptLevel = 3;
Rafael Espindolafd8de1c2014-12-16 21:57:03 +0000517 if (OptimizationLevel > MaxOptLevel) {
518 // If the optimization level is not supported, fall back on the default
519 // optimization
Sylvestre Ledru5abf2ec2013-11-18 13:23:07 +0000520 Diags.Report(diag::warn_drv_optimization_value)
521 << Args.getLastArg(OPT_O)->getAsString(Args) << "-O" << MaxOptLevel;
Rafael Espindolafd8de1c2014-12-16 21:57:03 +0000522 OptimizationLevel = MaxOptLevel;
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000523 }
Rafael Espindolafd8de1c2014-12-16 21:57:03 +0000524 Opts.OptimizationLevel = OptimizationLevel;
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000525
Chandler Carruthfcd33142016-12-23 01:24:49 +0000526 // At O0 we want to fully disable inlining outside of cases marked with
527 // 'alwaysinline' that are required for correctness.
528 Opts.setInlining((Opts.OptimizationLevel == 0)
529 ? CodeGenOptions::OnlyAlwaysInlining
530 : CodeGenOptions::NormalInlining);
531 // Explicit inlining flags can disable some or all inlining even at
532 // optimization levels above zero.
533 if (Arg *InlineArg = Args.getLastArg(
534 options::OPT_finline_functions, options::OPT_finline_hint_functions,
535 options::OPT_fno_inline_functions, options::OPT_fno_inline)) {
536 if (Opts.OptimizationLevel > 0) {
537 const Option &InlineOpt = InlineArg->getOption();
538 if (InlineOpt.matches(options::OPT_finline_functions))
539 Opts.setInlining(CodeGenOptions::NormalInlining);
540 else if (InlineOpt.matches(options::OPT_finline_hint_functions))
541 Opts.setInlining(CodeGenOptions::OnlyHintInlining);
542 else
543 Opts.setInlining(CodeGenOptions::OnlyAlwaysInlining);
544 }
Hans Wennborg7a008882016-05-24 20:40:51 +0000545 }
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000546
Chandler Carruth50f9e892016-12-23 20:44:01 +0000547 Opts.ExperimentalNewPassManager = Args.hasFlag(
548 OPT_fexperimental_new_pass_manager, OPT_fno_experimental_new_pass_manager,
Petr Hosekc3aa97a2018-04-06 00:53:00 +0000549 /* Default */ ENABLE_EXPERIMENTAL_NEW_PASS_MANAGER);
Chandler Carruth50f9e892016-12-23 20:44:01 +0000550
Tim Shenb13eebe2017-06-29 23:10:13 +0000551 Opts.DebugPassManager =
552 Args.hasFlag(OPT_fdebug_pass_manager, OPT_fno_debug_pass_manager,
553 /* Default */ false);
554
Michael Zolotukhinc888dd02015-03-17 20:03:11 +0000555 if (Arg *A = Args.getLastArg(OPT_fveclib)) {
556 StringRef Name = A->getValue();
557 if (Name == "Accelerate")
558 Opts.setVecLib(CodeGenOptions::Accelerate);
Matt Masten6731dea2016-07-29 16:44:24 +0000559 else if (Name == "SVML")
560 Opts.setVecLib(CodeGenOptions::SVML);
Michael Zolotukhinc888dd02015-03-17 20:03:11 +0000561 else if (Name == "none")
562 Opts.setVecLib(CodeGenOptions::NoLibrary);
563 else
564 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
565 }
566
Douglas Katzman3459ce22015-10-08 04:24:12 +0000567 if (Arg *A = Args.getLastArg(OPT_debug_info_kind_EQ)) {
Douglas Katzmana2ef81f2016-01-06 01:37:57 +0000568 unsigned Val =
569 llvm::StringSwitch<unsigned>(A->getValue())
Benjamin Kramer8c305922016-02-02 11:06:51 +0000570 .Case("line-tables-only", codegenoptions::DebugLineTablesOnly)
571 .Case("limited", codegenoptions::LimitedDebugInfo)
572 .Case("standalone", codegenoptions::FullDebugInfo)
Douglas Katzmana2ef81f2016-01-06 01:37:57 +0000573 .Default(~0U);
574 if (Val == ~0U)
575 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
576 << A->getValue();
577 else
Benjamin Kramer8c305922016-02-02 11:06:51 +0000578 Opts.setDebugInfo(static_cast<codegenoptions::DebugInfoKind>(Val));
Alexey Samsonov486e1fe2012-04-27 07:24:20 +0000579 }
Paul Robinson45784a72015-12-19 02:24:10 +0000580 if (Arg *A = Args.getLastArg(OPT_debugger_tuning_EQ)) {
Douglas Katzmana2ef81f2016-01-06 01:37:57 +0000581 unsigned Val = llvm::StringSwitch<unsigned>(A->getValue())
Paul Robinson9ef13db2016-02-05 23:23:25 +0000582 .Case("gdb", unsigned(llvm::DebuggerKind::GDB))
583 .Case("lldb", unsigned(llvm::DebuggerKind::LLDB))
584 .Case("sce", unsigned(llvm::DebuggerKind::SCE))
Douglas Katzmana2ef81f2016-01-06 01:37:57 +0000585 .Default(~0U);
586 if (Val == ~0U)
587 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
588 << A->getValue();
589 else
Paul Robinson9ef13db2016-02-05 23:23:25 +0000590 Opts.setDebuggerTuning(static_cast<llvm::DebuggerKind>(Val));
Paul Robinson45784a72015-12-19 02:24:10 +0000591 }
Douglas Katzman3459ce22015-10-08 04:24:12 +0000592 Opts.DwarfVersion = getLastArgIntValue(Args, OPT_dwarf_version_EQ, 0, Diags);
Eric Christophera2f7eb72012-10-18 21:52:18 +0000593 Opts.DebugColumnInfo = Args.hasArg(OPT_dwarf_column_info);
Douglas Katzman3459ce22015-10-08 04:24:12 +0000594 Opts.EmitCodeView = Args.hasArg(OPT_gcodeview);
Amjad Aboud546bc112017-02-09 22:07:24 +0000595 Opts.MacroDebugInfo = Args.hasArg(OPT_debug_info_macro);
Peter Collingbournefb532b92016-02-24 20:46:36 +0000596 Opts.WholeProgramVTables = Args.hasArg(OPT_fwhole_program_vtables);
Peter Collingbourne3afb2662016-04-28 17:09:37 +0000597 Opts.LTOVisibilityPublicStd = Args.hasArg(OPT_flto_visibility_public_std);
David Blaikie81503552017-04-21 23:35:36 +0000598 Opts.EnableSplitDwarf = Args.hasArg(OPT_enable_split_dwarf);
Eric Christopherf1545832013-02-22 23:50:16 +0000599 Opts.SplitDwarfFile = Args.getLastArgValue(OPT_split_dwarf_file);
David Blaikiea45c31a2016-08-24 18:29:58 +0000600 Opts.SplitDwarfInlining = !Args.hasArg(OPT_fno_split_dwarf_inlining);
Adrian Prantl6b21ab22015-08-27 19:46:20 +0000601 Opts.DebugTypeExtRefs = Args.hasArg(OPT_dwarf_ext_refs);
Paul Robinsona8280812017-09-29 21:25:07 +0000602 Opts.DebugExplicitImport = Args.hasArg(OPT_dwarf_explicit_import);
Paul Robinson1787f812017-09-28 18:37:02 +0000603 Opts.DebugFwdTemplateParams = Args.hasArg(OPT_debug_forward_template_params);
Scott Lindera2fbcef2018-02-26 17:32:31 +0000604 Opts.EmbedSource = Args.hasArg(OPT_gembed_source);
Alexey Samsonov486e1fe2012-04-27 07:24:20 +0000605
Saleem Abdulrasool436256a2015-10-12 20:21:08 +0000606 for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ))
607 Opts.DebugPrefixMap.insert(StringRef(Arg).split('='));
608
Duncan P. N. Exon Smithbb618252015-04-15 01:16:18 +0000609 if (const Arg *A =
610 Args.getLastArg(OPT_emit_llvm_uselists, OPT_no_emit_llvm_uselists))
611 Opts.EmitLLVMUseLists = A->getOption().getID() == OPT_emit_llvm_uselists;
612
Steven Wu546a1962015-07-17 20:09:56 +0000613 Opts.DisableLLVMPasses = Args.hasArg(OPT_disable_llvm_passes);
Mehdi Amini7f873072017-01-06 23:18:09 +0000614 Opts.DisableLifetimeMarkers = Args.hasArg(OPT_disable_lifetimemarkers);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +0000615 Opts.DisableO0ImplyOptNone = Args.hasArg(OPT_disable_O0_optnone);
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000616 Opts.DisableRedZone = Args.hasArg(OPT_disable_red_zone);
John McCall7ef5cb32011-03-18 02:56:14 +0000617 Opts.ForbidGuardVariables = Args.hasArg(OPT_fforbid_guard_variables);
Daniel Dunbard3f3d932011-06-21 18:54:46 +0000618 Opts.UseRegisterSizedBitfieldAccess = Args.hasArg(
619 OPT_fuse_register_sized_bitfield_access);
Chad Rosierb71f6aa2013-04-24 18:09:54 +0000620 Opts.RelaxedAliasing = Args.hasArg(OPT_relaxed_aliasing);
Manman Renf5d9d342013-10-11 20:48:38 +0000621 Opts.StructPathTBAA = !Args.hasArg(OPT_no_struct_path_tbaa);
Ivan A. Kosarevfa03a6a2017-11-20 11:16:16 +0000622 Opts.NewStructPathTBAA = !Args.hasArg(OPT_no_struct_path_tbaa) &&
623 Args.hasArg(OPT_new_struct_path_tbaa);
Wei Mi9b3d6272017-10-16 16:50:27 +0000624 Opts.FineGrainedBitfieldAccesses =
625 Args.hasFlag(OPT_ffine_grained_bitfield_accesses,
626 OPT_fno_fine_grained_bitfield_accesses, false);
Daniel Dunbar37300482010-05-20 16:54:55 +0000627 Opts.DwarfDebugFlags = Args.getLastArgValue(OPT_dwarf_debug_flags);
Manoj Gupta4b3eefa2018-04-05 15:29:52 +0000628 Opts.MergeAllConstants = Args.hasArg(OPT_fmerge_all_constants);
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000629 Opts.NoCommon = Args.hasArg(OPT_fno_common);
630 Opts.NoImplicitFloat = Args.hasArg(OPT_no_implicit_float);
Chad Rosierf2d39642013-04-10 21:30:03 +0000631 Opts.OptimizeSize = getOptimizationLevelSize(Args);
Daniel Dunbar6d5824f2010-06-07 23:19:17 +0000632 Opts.SimplifyLibCalls = !(Args.hasArg(OPT_fno_builtin) ||
633 Args.hasArg(OPT_ffreestanding));
Chad Rosier7dbc9cf2016-01-06 14:35:46 +0000634 if (Opts.SimplifyLibCalls)
635 getAllNoBuiltinFuncValues(Args, Opts.NoBuiltinFuncs);
Chandler Carruth54c29102013-08-08 08:34:35 +0000636 Opts.UnrollLoops =
637 Args.hasFlag(OPT_funroll_loops, OPT_fno_unroll_loops,
Marianne Mailhot-Sarrasin21ac3bf2016-05-04 15:26:28 +0000638 (Opts.OptimizationLevel > 1));
Hal Finkelce0697f2013-11-17 16:03:29 +0000639 Opts.RerollLoops = Args.hasArg(OPT_freroll_loops);
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000640
Saleem Abdulrasoolcfeb90d2014-02-23 00:40:30 +0000641 Opts.DisableIntegratedAS = Args.hasArg(OPT_fno_integrated_as);
Daniel Dunbare246fbe2013-04-16 18:21:19 +0000642 Opts.Autolink = !Args.hasArg(OPT_fno_autolink);
Diego Novillo5c297052013-11-13 12:22:39 +0000643 Opts.SampleProfileFile = Args.getLastArgValue(OPT_fprofile_sample_use_EQ);
Dehao Chenb3a70de2017-01-19 00:44:21 +0000644 Opts.DebugInfoForProfiling = Args.hasFlag(
645 OPT_fdebug_info_for_profiling, OPT_fno_debug_info_for_profiling, false);
Peter Collingbourneb52e2362017-09-12 21:50:41 +0000646 Opts.GnuPubnames = Args.hasArg(OPT_ggnu_pubnames);
Rong Xu9837ef52016-02-04 18:39:09 +0000647
Rong Xu9c6f1532016-03-02 20:59:36 +0000648 setPGOInstrumentor(Opts, Args, Diags);
649 Opts.InstrProfileOutput =
650 Args.getLastArgValue(OPT_fprofile_instrument_path_EQ);
651 Opts.ProfileInstrumentUsePath =
652 Args.getLastArgValue(OPT_fprofile_instrument_use_path_EQ);
653 if (!Opts.ProfileInstrumentUsePath.empty())
654 setPGOUseInstrumentor(Opts, Opts.ProfileInstrumentUsePath);
Rong Xu9837ef52016-02-04 18:39:09 +0000655
Diego Novilloc4b94da2015-08-05 23:27:40 +0000656 Opts.CoverageMapping =
657 Args.hasFlag(OPT_fcoverage_mapping, OPT_fno_coverage_mapping, false);
Alex Lorenzf2cf38e2014-08-08 23:41:24 +0000658 Opts.DumpCoverageMapping = Args.hasArg(OPT_dump_coverage_mapping);
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000659 Opts.AsmVerbose = Args.hasArg(OPT_masm_verbose);
Nirav Dave993a1392016-07-27 19:57:40 +0000660 Opts.PreserveAsmComments = !Args.hasArg(OPT_fno_preserve_as_comments);
Richard Smith351241c2016-04-07 21:46:12 +0000661 Opts.AssumeSaneOperatorNew = !Args.hasArg(OPT_fno_assume_sane_operator_new);
John McCall31168b02011-06-15 23:02:42 +0000662 Opts.ObjCAutoRefCountExceptions = Args.hasArg(OPT_fobjc_arc_exceptions);
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000663 Opts.CXAAtExit = !Args.hasArg(OPT_fno_use_cxa_atexit);
Akira Hatanaka617e2612018-04-17 18:41:52 +0000664 Opts.RegisterGlobalDtorsWithAtExit =
665 Args.hasArg(OPT_fregister_global_dtors_with_atexit);
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000666 Opts.CXXCtorDtorAliases = Args.hasArg(OPT_mconstructor_aliases);
Saleem Abdulrasool62849c62014-05-08 02:28:32 +0000667 Opts.CodeModel = getCodeModel(Args, Diags);
Daniel Dunbar37300482010-05-20 16:54:55 +0000668 Opts.DebugPass = Args.getLastArgValue(OPT_mdebug_pass);
Xinliang David Li4dff8752015-11-23 17:30:31 +0000669 Opts.DisableFPElim =
670 (Args.hasArg(OPT_mdisable_fp_elim) || Args.hasArg(OPT_pg));
Nick Lewycky92a6c742013-06-21 21:15:32 +0000671 Opts.DisableFree = Args.hasArg(OPT_disable_free);
Benjamin Kramer12f2de12016-03-14 13:23:58 +0000672 Opts.DiscardValueNames = Args.hasArg(OPT_discard_value_names);
Nick Lewycky1c8c4362012-01-23 08:29:12 +0000673 Opts.DisableTailCalls = Args.hasArg(OPT_mdisable_tail_calls);
Akira Hatanaka627586b2018-03-02 01:53:15 +0000674 Opts.NoEscapingBlockTailCalls =
675 Args.hasArg(OPT_fno_escaping_block_tail_calls);
Daniel Dunbar37300482010-05-20 16:54:55 +0000676 Opts.FloatABI = Args.getLastArgValue(OPT_mfloat_abi);
Egor Churaev45c26ee2017-03-27 10:38:01 +0000677 Opts.LessPreciseFPMAD = Args.hasArg(OPT_cl_mad_enable) ||
678 Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
679 Args.hasArg(OPT_cl_fast_relaxed_math);
Daniel Dunbar37300482010-05-20 16:54:55 +0000680 Opts.LimitFloatPrecision = Args.getLastArgValue(OPT_mlimit_float_precision);
Daniel Dunbar19939cc2011-12-09 23:41:18 +0000681 Opts.NoInfsFPMath = (Args.hasArg(OPT_menable_no_infinities) ||
Pekka Jaaskelainen37014502014-12-10 16:41:14 +0000682 Args.hasArg(OPT_cl_finite_math_only) ||
Daniel Dunbar19939cc2011-12-09 23:41:18 +0000683 Args.hasArg(OPT_cl_fast_relaxed_math));
684 Opts.NoNaNsFPMath = (Args.hasArg(OPT_menable_no_nans) ||
Pekka Jaaskelainen37014502014-12-10 16:41:14 +0000685 Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
686 Args.hasArg(OPT_cl_finite_math_only) ||
Daniel Dunbar19939cc2011-12-09 23:41:18 +0000687 Args.hasArg(OPT_cl_fast_relaxed_math));
Yaxun Liu79c99fb2016-07-08 20:28:29 +0000688 Opts.NoSignedZeros = (Args.hasArg(OPT_fno_signed_zeros) ||
Egor Churaev45c26ee2017-03-27 10:38:01 +0000689 Args.hasArg(OPT_cl_no_signed_zeros) ||
690 Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
691 Args.hasArg(OPT_cl_fast_relaxed_math));
Sanjay Patelcb8c0092017-12-16 16:11:17 +0000692 Opts.Reassociate = Args.hasArg(OPT_mreassociate);
Yaxun Liue1bfbc52018-07-21 02:02:22 +0000693 Opts.FlushDenorm = Args.hasArg(OPT_cl_denorms_are_zero) ||
694 (Args.hasArg(OPT_fcuda_is_device) &&
695 Args.hasArg(OPT_fcuda_flush_denormals_to_zero));
Yaxun Liuffb60902016-08-09 20:10:18 +0000696 Opts.CorrectlyRoundedDivSqrt =
697 Args.hasArg(OPT_cl_fp32_correctly_rounded_divide_sqrt);
Alexey Sotkin20f65922018-02-22 11:54:14 +0000698 Opts.UniformWGSize =
699 Args.hasArg(OPT_cl_uniform_work_group_size);
Craig Topper402b4312017-11-20 17:09:22 +0000700 Opts.Reciprocals = Args.getAllArgValues(OPT_mrecip_EQ);
Sanjay Patel359b1052015-04-09 15:03:23 +0000701 Opts.ReciprocalMath = Args.hasArg(OPT_freciprocal_math);
Sjoerd Meijer0a8d4212016-08-30 08:09:45 +0000702 Opts.NoTrappingMath = Args.hasArg(OPT_fno_trapping_math);
Sanjay Patelc81450e2018-04-30 18:19:03 +0000703 Opts.StrictFloatCastOverflow =
704 !Args.hasArg(OPT_fno_strict_float_cast_overflow);
Sanjay Pateld1754762018-04-27 14:22:48 +0000705
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000706 Opts.NoZeroInitializedInBSS = Args.hasArg(OPT_mno_zero_initialized_in_bss);
Reid Kleckner898229a2013-06-14 17:17:23 +0000707 Opts.NumRegisterParameters = getLastArgIntValue(Args, OPT_mregparm, 0, Diags);
Nick Lewyckyca6b90d2011-06-21 00:14:18 +0000708 Opts.NoExecStack = Args.hasArg(OPT_mno_exec_stack);
Joerg Sonnenbergera43604a2014-08-26 18:40:25 +0000709 Opts.FatalWarnings = Args.hasArg(OPT_massembler_fatal_warnings);
Eric Christopher006208c2013-04-04 06:29:47 +0000710 Opts.EnableSegmentedStacks = Args.hasArg(OPT_split_stacks);
Daniel Dunbarc43b6b22010-05-27 05:39:39 +0000711 Opts.RelaxAll = Args.hasArg(OPT_mrelax_all);
David Majnemer2b9349d2015-12-21 22:09:34 +0000712 Opts.IncrementalLinkerCompatible =
713 Args.hasArg(OPT_mincremental_linker_compatible);
Sriraman Tallam165a8842016-10-19 20:24:06 +0000714 Opts.PIECopyRelocations =
715 Args.hasArg(OPT_mpie_copy_relocations);
Sriraman Tallam5c651482017-11-07 19:37:51 +0000716 Opts.NoPLT = Args.hasArg(OPT_fno_plt);
Daniel Dunbarbb7ac522010-07-01 01:31:45 +0000717 Opts.OmitLeafFramePointer = Args.hasArg(OPT_momit_leaf_frame_pointer);
Daniel Dunbar67919b22011-03-28 22:49:28 +0000718 Opts.SaveTempLabels = Args.hasArg(OPT_msave_temp_labels);
Nick Lewycky1d617ac2011-10-17 23:05:52 +0000719 Opts.NoDwarfDirectoryAsm = Args.hasArg(OPT_fno_dwarf_directory_asm);
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000720 Opts.SoftFloat = Args.hasArg(OPT_msoft_float);
Chandler Carruth8b4140d2012-03-27 23:58:37 +0000721 Opts.StrictEnums = Args.hasArg(OPT_fstrict_enums);
Alex Lorenzc1608f72017-01-04 13:40:34 +0000722 Opts.StrictReturn = !Args.hasArg(OPT_fno_strict_return);
Piotr Padlewski338c9d02015-09-15 21:46:47 +0000723 Opts.StrictVTablePointers = Args.hasArg(OPT_fstrict_vtable_pointers);
Piotr Padlewskie368de32018-06-13 13:55:42 +0000724 Opts.ForceEmitVTables = Args.hasArg(OPT_fforce_emit_vtables);
Chandler Carruth306bd2c2012-01-02 14:19:45 +0000725 Opts.UnsafeFPMath = Args.hasArg(OPT_menable_unsafe_fp_math) ||
726 Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
Peter Collingbourne61d6a752010-12-04 01:51:23 +0000727 Args.hasArg(OPT_cl_fast_relaxed_math);
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000728 Opts.UnwindTables = Args.hasArg(OPT_munwind_tables);
Davide Italiano1a3665bb2017-04-01 21:07:07 +0000729 Opts.RelocationModel = getRelocModel(Args, Diags);
Jonathan Roelofsb140a102014-10-03 21:57:44 +0000730 Opts.ThreadModel = Args.getLastArgValue(OPT_mthread_model, "posix");
731 if (Opts.ThreadModel != "posix" && Opts.ThreadModel != "single")
732 Diags.Report(diag::err_drv_invalid_value)
733 << Args.getLastArg(OPT_mthread_model)->getAsString(Args)
734 << Opts.ThreadModel;
Bob Wilson14adb362012-02-03 06:27:22 +0000735 Opts.TrapFuncName = Args.getLastArgValue(OPT_ftrap_function_EQ);
Rafael Espindola66aa0452012-06-19 01:26:10 +0000736 Opts.UseInitArray = Args.hasArg(OPT_fuse_init_array);
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000737
Nick Lewycky3a410fe2013-10-11 03:35:10 +0000738 Opts.FunctionSections = Args.hasFlag(OPT_ffunction_sections,
739 OPT_fno_function_sections, false);
740 Opts.DataSections = Args.hasFlag(OPT_fdata_sections,
741 OPT_fno_data_sections, false);
Sean Eveson5110d4f2018-01-08 13:42:26 +0000742 Opts.StackSizeSection =
743 Args.hasFlag(OPT_fstack_size_section, OPT_fno_stack_size_section, false);
Rafael Espindola6b07a1c2015-02-20 18:08:57 +0000744 Opts.UniqueSectionNames = Args.hasFlag(OPT_funique_section_names,
745 OPT_fno_unique_section_names, true);
746
Nick Lewyckyf04f2372014-10-24 00:49:29 +0000747 Opts.MergeFunctions = Args.hasArg(OPT_fmerge_functions);
Chris Lattnerdc6040b2010-04-13 00:38:24 +0000748
Nirav Daved2f44d82016-04-05 17:50:43 +0000749 Opts.NoUseJumpTables = Args.hasArg(OPT_fno_jump_tables);
750
Manoj Guptada08f6a2018-07-19 00:44:52 +0000751 Opts.NullPointerIsValid = Args.hasArg(OPT_fno_delete_null_pointer_checks);
752
Dehao Chen5e97f232017-08-24 21:37:33 +0000753 Opts.ProfileSampleAccurate = Args.hasArg(OPT_fprofile_sample_accurate);
754
Teresa Johnson945bc502015-10-15 20:35:53 +0000755 Opts.PrepareForLTO = Args.hasArg(OPT_flto, OPT_flto_EQ);
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000756 Opts.PrepareForThinLTO = false;
Yuka Takahashi50a9dfa2017-06-14 15:37:11 +0000757 if (Arg *A = Args.getLastArg(OPT_flto_EQ)) {
758 StringRef S = A->getValue();
759 if (S == "thin")
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000760 Opts.PrepareForThinLTO = true;
Yuka Takahashi50a9dfa2017-06-14 15:37:11 +0000761 else if (S != "full")
762 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << S;
763 }
Peter Collingbourne1e1475a2017-01-18 23:55:27 +0000764 Opts.LTOUnit = Args.hasFlag(OPT_flto_unit, OPT_fno_lto_unit, false);
Teresa Johnsonaff22322015-12-07 19:21:34 +0000765 if (Arg *A = Args.getLastArg(OPT_fthinlto_index_EQ)) {
Richard Smith40c0efa2017-04-26 18:57:40 +0000766 if (IK.getLanguage() != InputKind::LLVM_IR)
Teresa Johnsonaff22322015-12-07 19:21:34 +0000767 Diags.Report(diag::err_drv_argument_only_allowed_with)
768 << A->getAsString(Args) << "-x ir";
769 Opts.ThinLTOIndexFile = Args.getLastArgValue(OPT_fthinlto_index_EQ);
770 }
Teresa Johnson9e4321c2018-04-17 16:39:25 +0000771 if (Arg *A = Args.getLastArg(OPT_save_temps_EQ))
772 Opts.SaveTempsFilePrefix =
773 llvm::StringSwitch<std::string>(A->getValue())
774 .Case("obj", FrontendOpts.OutputFile)
775 .Default(llvm::sys::path::filename(FrontendOpts.OutputFile).str());
776
Teresa Johnson488d1dc2017-03-23 19:47:49 +0000777 Opts.ThinLinkBitcodeFile = Args.getLastArgValue(OPT_fthin_link_bitcode_EQ);
Teresa Johnson8749d8042015-07-06 16:23:00 +0000778
David Majnemera5b195a2015-02-14 01:35:12 +0000779 Opts.MSVolatile = Args.hasArg(OPT_fms_volatile);
780
Nick Lewyckyd3f3e4f2013-06-25 01:49:44 +0000781 Opts.VectorizeLoop = Args.hasArg(OPT_vectorize_loops);
782 Opts.VectorizeSLP = Args.hasArg(OPT_vectorize_slp);
783
Craig Topper9a724aa2017-12-11 21:09:19 +0000784 Opts.PreferVectorWidth = Args.getLastArgValue(OPT_mprefer_vector_width_EQ);
785
Daniel Dunbar37300482010-05-20 16:54:55 +0000786 Opts.MainFileName = Args.getLastArgValue(OPT_main_file_name);
John McCallcfcb7752010-02-12 23:47:27 +0000787 Opts.VerifyModule = !Args.hasArg(OPT_disable_llvm_verifier);
Daniel Dunbarfca18c1b42010-04-24 17:56:46 +0000788
Adrian McCarthydb2736d2018-01-09 23:49:30 +0000789 Opts.ControlFlowGuard = Args.hasArg(OPT_cfguard);
790
Nick Lewyckyc02bbb62013-03-20 01:38:16 +0000791 Opts.DisableGCov = Args.hasArg(OPT_test_coverage);
Nick Lewycky207bce32011-04-21 23:44:07 +0000792 Opts.EmitGcovArcs = Args.hasArg(OPT_femit_coverage_data);
793 Opts.EmitGcovNotes = Args.hasArg(OPT_femit_coverage_notes);
Nick Lewycky737a4522013-03-07 08:28:53 +0000794 if (Opts.EmitGcovArcs || Opts.EmitGcovNotes) {
Nick Lewycky97e49ac2016-08-31 23:04:32 +0000795 Opts.CoverageDataFile = Args.getLastArgValue(OPT_coverage_data_file);
796 Opts.CoverageNotesFile = Args.getLastArgValue(OPT_coverage_notes_file);
Nick Lewycky737a4522013-03-07 08:28:53 +0000797 Opts.CoverageExtraChecksum = Args.hasArg(OPT_coverage_cfg_checksum);
Nick Lewycky6f15b2902013-03-20 02:14:38 +0000798 Opts.CoverageNoFunctionNamesInData =
799 Args.hasArg(OPT_coverage_no_function_names_in_data);
Justin Bogner4e462372015-03-16 23:52:21 +0000800 Opts.CoverageExitBlockBeforeBody =
801 Args.hasArg(OPT_coverage_exit_block_before_body);
Nick Lewycky737a4522013-03-07 08:28:53 +0000802 if (Args.hasArg(OPT_coverage_version_EQ)) {
803 StringRef CoverageVersion = Args.getLastArgValue(OPT_coverage_version_EQ);
804 if (CoverageVersion.size() != 4) {
805 Diags.Report(diag::err_drv_invalid_value)
806 << Args.getLastArg(OPT_coverage_version_EQ)->getAsString(Args)
807 << CoverageVersion;
808 } else {
Nick Lewyckyc8bf8242013-03-14 05:14:01 +0000809 memcpy(Opts.CoverageVersion, CoverageVersion.data(), 4);
Nick Lewycky737a4522013-03-07 08:28:53 +0000810 }
811 }
812 }
Fangrui Song99337e22018-07-20 08:19:20 +0000813 // Handle -fembed-bitcode option.
Steven Wu27fb5222016-05-11 16:26:03 +0000814 if (Arg *A = Args.getLastArg(OPT_fembed_bitcode_EQ)) {
815 StringRef Name = A->getValue();
816 unsigned Model = llvm::StringSwitch<unsigned>(Name)
817 .Case("off", CodeGenOptions::Embed_Off)
818 .Case("all", CodeGenOptions::Embed_All)
819 .Case("bitcode", CodeGenOptions::Embed_Bitcode)
820 .Case("marker", CodeGenOptions::Embed_Marker)
821 .Default(~0U);
822 if (Model == ~0U) {
823 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
824 Success = false;
825 } else
826 Opts.setEmbedBitcode(
827 static_cast<CodeGenOptions::EmbedBitcodeKind>(Model));
828 }
829 // FIXME: For backend options that are not yet recorded as function
830 // attributes in the IR, keep track of them so we can embed them in a
831 // separate data section and use them when building the bitcode.
832 if (Opts.getEmbedBitcode() == CodeGenOptions::Embed_All) {
833 for (const auto &A : Args) {
834 // Do not encode output and input.
835 if (A->getOption().getID() == options::OPT_o ||
836 A->getOption().getID() == options::OPT_INPUT ||
837 A->getOption().getID() == options::OPT_x ||
838 A->getOption().getID() == options::OPT_fembed_bitcode ||
839 (A->getOption().getGroup().isValid() &&
840 A->getOption().getGroup().getID() == options::OPT_W_Group))
841 continue;
842 ArgStringList ASL;
843 A->render(Args, ASL);
844 for (const auto &arg : ASL) {
845 StringRef ArgStr(arg);
846 Opts.CmdArgs.insert(Opts.CmdArgs.end(), ArgStr.begin(), ArgStr.end());
847 // using \00 to seperate each commandline options.
848 Opts.CmdArgs.push_back('\0');
849 }
850 }
851 }
Nick Lewycky737a4522013-03-07 08:28:53 +0000852
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +0000853 Opts.PreserveVec3Type = Args.hasArg(OPT_fpreserve_vec3_type);
Nick Lewycky737a4522013-03-07 08:28:53 +0000854 Opts.InstrumentFunctions = Args.hasArg(OPT_finstrument_functions);
Hans Wennborg76c26c12017-11-14 21:13:27 +0000855 Opts.InstrumentFunctionsAfterInlining =
856 Args.hasArg(OPT_finstrument_functions_after_inlining);
Hans Wennborg14e8a5a2017-11-21 17:30:34 +0000857 Opts.InstrumentFunctionEntryBare =
858 Args.hasArg(OPT_finstrument_function_entry_bare);
Dean Michael Berris488f7c22018-04-13 02:31:58 +0000859
860 Opts.XRayInstrumentFunctions =
861 Args.hasArg(OPT_fxray_instrument);
Dean Michael Berris1a5b10d2017-11-30 00:04:54 +0000862 Opts.XRayAlwaysEmitCustomEvents =
863 Args.hasArg(OPT_fxray_always_emit_customevents);
Keith Wyssf437e352018-04-17 21:32:43 +0000864 Opts.XRayAlwaysEmitTypedEvents =
865 Args.hasArg(OPT_fxray_always_emit_typedevents);
Aaron Ballman7d2aecb2016-07-13 22:32:15 +0000866 Opts.XRayInstructionThreshold =
Dean Michael Berris504fc222017-03-30 22:46:45 +0000867 getLastArgIntValue(Args, OPT_fxray_instruction_threshold_EQ, 200, Diags);
Dean Michael Berris488f7c22018-04-13 02:31:58 +0000868
869 auto XRayInstrBundles =
870 Args.getAllArgValues(OPT_fxray_instrumentation_bundle);
871 if (XRayInstrBundles.empty())
872 Opts.XRayInstrumentationBundle.Mask = XRayInstrKind::All;
873 else
874 for (const auto &A : XRayInstrBundles)
875 parseXRayInstrumentationBundle("-fxray-instrumentation-bundle=", A, Args,
876 Diags, Opts.XRayInstrumentationBundle);
877
Nick Lewycky737a4522013-03-07 08:28:53 +0000878 Opts.InstrumentForProfiling = Args.hasArg(OPT_pg);
Nirav Dave0c86ccf2017-01-31 17:00:35 +0000879 Opts.CallFEntry = Args.hasArg(OPT_mfentry);
Nick Lewycky737a4522013-03-07 08:28:53 +0000880 Opts.EmitOpenCLArgMetadata = Args.hasArg(OPT_cl_kernel_arg_info);
Saleem Abdulrasoold064e912017-06-23 15:34:16 +0000881
Oren Ben Simhon57cc1a52018-01-09 08:53:59 +0000882 if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
883 StringRef Name = A->getValue();
884 if (Name == "full") {
885 Opts.CFProtectionReturn = 1;
886 Opts.CFProtectionBranch = 1;
887 } else if (Name == "return")
888 Opts.CFProtectionReturn = 1;
889 else if (Name == "branch")
890 Opts.CFProtectionBranch = 1;
891 else if (Name != "none") {
892 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
893 Success = false;
894 }
895 }
896
Saleem Abdulrasoold064e912017-06-23 15:34:16 +0000897 if (const Arg *A = Args.getLastArg(OPT_compress_debug_sections,
898 OPT_compress_debug_sections_EQ)) {
899 if (A->getOption().getID() == OPT_compress_debug_sections) {
900 // TODO: be more clever about the compression type auto-detection
901 Opts.setCompressDebugSections(llvm::DebugCompressionType::GNU);
902 } else {
903 auto DCT = llvm::StringSwitch<llvm::DebugCompressionType>(A->getValue())
904 .Case("none", llvm::DebugCompressionType::None)
905 .Case("zlib", llvm::DebugCompressionType::Z)
906 .Case("zlib-gnu", llvm::DebugCompressionType::GNU)
907 .Default(llvm::DebugCompressionType::None);
908 Opts.setCompressDebugSections(DCT);
909 }
910 }
911
Rafael Espindolaf8f01c32016-05-29 02:01:14 +0000912 Opts.RelaxELFRelocations = Args.hasArg(OPT_mrelax_relocations);
Nick Lewyckyba743b72011-10-21 02:32:14 +0000913 Opts.DebugCompilationDir = Args.getLastArgValue(OPT_fdebug_compilation_dir);
Eugene Zelenko44357ee2018-03-26 21:45:04 +0000914 for (auto *A :
915 Args.filtered(OPT_mlink_bitcode_file, OPT_mlink_cuda_bitcode)) {
Justin Lebarb080b632017-01-25 21:29:48 +0000916 CodeGenOptions::BitcodeFileToLink F;
917 F.Filename = A->getValue();
918 if (A->getOption().matches(OPT_mlink_cuda_bitcode)) {
Jonas Devlieghere5eb9c812017-03-13 18:08:11 +0000919 F.LinkFlags = llvm::Linker::Flags::LinkOnlyNeeded;
Justin Lebarb080b632017-01-25 21:29:48 +0000920 // When linking CUDA bitcode, propagate function attributes so that
921 // e.g. libdevice gets fast-math attrs if we're building with fast-math.
922 F.PropagateAttrs = true;
Jonas Devlieghere5eb9c812017-03-13 18:08:11 +0000923 F.Internalize = true;
Justin Lebarb080b632017-01-25 21:29:48 +0000924 }
925 Opts.LinkBitcodeFiles.push_back(F);
Artem Belevich5d40ae32015-10-27 17:56:59 +0000926 }
Alexey Samsonov3f3b3ab2015-05-07 18:31:29 +0000927 Opts.SanitizeCoverageType =
928 getLastArgIntValue(Args, OPT_fsanitize_coverage_type, 0, Diags);
929 Opts.SanitizeCoverageIndirectCalls =
930 Args.hasArg(OPT_fsanitize_coverage_indirect_calls);
931 Opts.SanitizeCoverageTraceBB = Args.hasArg(OPT_fsanitize_coverage_trace_bb);
932 Opts.SanitizeCoverageTraceCmp = Args.hasArg(OPT_fsanitize_coverage_trace_cmp);
Kostya Serebryany3b419712016-08-30 01:27:03 +0000933 Opts.SanitizeCoverageTraceDiv = Args.hasArg(OPT_fsanitize_coverage_trace_div);
934 Opts.SanitizeCoverageTraceGep = Args.hasArg(OPT_fsanitize_coverage_trace_gep);
Alexey Samsonov3f3b3ab2015-05-07 18:31:29 +0000935 Opts.SanitizeCoverage8bitCounters =
936 Args.hasArg(OPT_fsanitize_coverage_8bit_counters);
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000937 Opts.SanitizeCoverageTracePC = Args.hasArg(OPT_fsanitize_coverage_trace_pc);
Kostya Serebryany60cdd612016-09-14 01:39:49 +0000938 Opts.SanitizeCoverageTracePCGuard =
939 Args.hasArg(OPT_fsanitize_coverage_trace_pc_guard);
Kostya Serebryany50fb6182017-05-05 23:28:18 +0000940 Opts.SanitizeCoverageNoPrune = Args.hasArg(OPT_fsanitize_coverage_no_prune);
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000941 Opts.SanitizeCoverageInline8bitCounters =
942 Args.hasArg(OPT_fsanitize_coverage_inline_8bit_counters);
Kostya Serebryany61457762017-07-28 00:10:10 +0000943 Opts.SanitizeCoveragePCTable = Args.hasArg(OPT_fsanitize_coverage_pc_table);
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000944 Opts.SanitizeCoverageStackDepth =
945 Args.hasArg(OPT_fsanitize_coverage_stack_depth);
Alexey Samsonov29524a92013-01-20 13:12:12 +0000946 Opts.SanitizeMemoryTrackOrigins =
Evgeniy Stepanov2bfcaab2014-03-20 14:58:36 +0000947 getLastArgIntValue(Args, OPT_fsanitize_memory_track_origins_EQ, 0, Diags);
Evgeniy Stepanov45be9e02015-07-10 20:07:16 +0000948 Opts.SanitizeMemoryUseAfterDtor =
Matt Morehousebb26f862017-09-14 23:14:37 +0000949 Args.hasFlag(OPT_fsanitize_memory_use_after_dtor,
950 OPT_fno_sanitize_memory_use_after_dtor,
951 false);
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +0000952 Opts.SanitizeMinimalRuntime = Args.hasArg(OPT_fsanitize_minimal_runtime);
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +0000953 Opts.SanitizeCfiCrossDso = Args.hasArg(OPT_fsanitize_cfi_cross_dso);
Vlad Tsyrklevich634c6012017-10-31 22:39:44 +0000954 Opts.SanitizeCfiICallGeneralizePointers =
955 Args.hasArg(OPT_fsanitize_cfi_icall_generalize_pointers);
Peter Collingbournedc134532016-01-16 00:31:22 +0000956 Opts.SanitizeStats = Args.hasArg(OPT_fsanitize_stats);
Filipe Cabecinhas4ba58172018-02-12 11:49:02 +0000957 if (Arg *A = Args.getLastArg(
958 OPT_fsanitize_address_poison_class_member_array_new_cookie,
959 OPT_fno_sanitize_address_poison_class_member_array_new_cookie)) {
960 Opts.SanitizeAddressPoisonClassMemberArrayNewCookie =
961 A->getOption().getID() ==
962 OPT_fsanitize_address_poison_class_member_array_new_cookie;
963 }
Vitaly Bukaa77ac1b2016-10-10 21:31:50 +0000964 if (Arg *A = Args.getLastArg(OPT_fsanitize_address_use_after_scope,
965 OPT_fno_sanitize_address_use_after_scope)) {
966 Opts.SanitizeAddressUseAfterScope =
967 A->getOption().getID() == OPT_fsanitize_address_use_after_scope;
968 }
Evgeniy Stepanovd991cdd2017-05-09 21:57:43 +0000969 Opts.SanitizeAddressGlobalsDeadStripping =
970 Args.hasArg(OPT_fsanitize_address_globals_dead_stripping);
Chad Rosierdb3da832012-08-21 16:16:06 +0000971 Opts.SSPBufferSize =
Reid Kleckner898229a2013-06-14 17:17:23 +0000972 getLastArgIntValue(Args, OPT_stack_protector_buffer_size, 8, Diags);
Nick Lewyckyf4d3f7a2011-12-06 03:33:03 +0000973 Opts.StackRealignment = Args.hasArg(OPT_mstackrealign);
Joerg Sonnenbergerdb66ed02011-12-05 23:05:23 +0000974 if (Arg *A = Args.getLastArg(OPT_mstack_alignment)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000975 StringRef Val = A->getValue();
Douglas Gregorb0eea8b2012-10-23 20:05:01 +0000976 unsigned StackAlignment = Opts.StackAlignment;
977 Val.getAsInteger(10, StackAlignment);
978 Opts.StackAlignment = StackAlignment;
Joerg Sonnenbergerdb66ed02011-12-05 23:05:23 +0000979 }
Chris Lattner3c77a352010-06-22 00:03:40 +0000980
Hans Wennborg77dc2362015-01-20 19:45:50 +0000981 if (Arg *A = Args.getLastArg(OPT_mstack_probe_size)) {
982 StringRef Val = A->getValue();
983 unsigned StackProbeSize = Opts.StackProbeSize;
984 Val.getAsInteger(0, StackProbeSize);
985 Opts.StackProbeSize = StackProbeSize;
986 }
987
Hans Wennborgd43f40d2018-02-23 13:47:36 +0000988 Opts.NoStackArgProbe = Args.hasArg(OPT_mno_stack_arg_probe);
989
Daniel Dunbarfca18c1b42010-04-24 17:56:46 +0000990 if (Arg *A = Args.getLastArg(OPT_fobjc_dispatch_method_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000991 StringRef Name = A->getValue();
Daniel Dunbarfca18c1b42010-04-24 17:56:46 +0000992 unsigned Method = llvm::StringSwitch<unsigned>(Name)
993 .Case("legacy", CodeGenOptions::Legacy)
994 .Case("non-legacy", CodeGenOptions::NonLegacy)
995 .Case("mixed", CodeGenOptions::Mixed)
996 .Default(~0U);
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000997 if (Method == ~0U) {
Daniel Dunbarfca18c1b42010-04-24 17:56:46 +0000998 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000999 Success = false;
1000 } else {
Douglas Gregorb0eea8b2012-10-23 20:05:01 +00001001 Opts.setObjCDispatchMethod(
1002 static_cast<CodeGenOptions::ObjCDispatchMethodKind>(Method));
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00001003 }
Daniel Dunbarfca18c1b42010-04-24 17:56:46 +00001004 }
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00001005
Chih-Hung Hsiehca552b82018-03-01 22:26:19 +00001006 if (Args.getLastArg(OPT_femulated_tls) ||
1007 Args.getLastArg(OPT_fno_emulated_tls)) {
1008 Opts.ExplicitEmulatedTLS = true;
1009 Opts.EmulatedTLS =
1010 Args.hasFlag(OPT_femulated_tls, OPT_fno_emulated_tls, false);
1011 }
Chih-Hung Hsieh2c656c92015-07-28 16:27:56 +00001012
Hans Wennborgf60f6af2012-06-28 08:01:44 +00001013 if (Arg *A = Args.getLastArg(OPT_ftlsmodel_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001014 StringRef Name = A->getValue();
Hans Wennborgf60f6af2012-06-28 08:01:44 +00001015 unsigned Model = llvm::StringSwitch<unsigned>(Name)
1016 .Case("global-dynamic", CodeGenOptions::GeneralDynamicTLSModel)
1017 .Case("local-dynamic", CodeGenOptions::LocalDynamicTLSModel)
1018 .Case("initial-exec", CodeGenOptions::InitialExecTLSModel)
1019 .Case("local-exec", CodeGenOptions::LocalExecTLSModel)
1020 .Default(~0U);
1021 if (Model == ~0U) {
1022 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
1023 Success = false;
1024 } else {
Douglas Gregorb0eea8b2012-10-23 20:05:01 +00001025 Opts.setDefaultTLSModel(static_cast<CodeGenOptions::TLSModel>(Model));
Hans Wennborgf60f6af2012-06-28 08:01:44 +00001026 }
1027 }
1028
Sjoerd Meijer0a8d4212016-08-30 08:09:45 +00001029 if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_EQ)) {
1030 StringRef Val = A->getValue();
1031 if (Val == "ieee")
1032 Opts.FPDenormalMode = "ieee";
1033 else if (Val == "preserve-sign")
1034 Opts.FPDenormalMode = "preserve-sign";
1035 else if (Val == "positive-zero")
1036 Opts.FPDenormalMode = "positive-zero";
1037 else
1038 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
1039 }
1040
John McCall1fe2a8c2013-06-18 02:46:29 +00001041 if (Arg *A = Args.getLastArg(OPT_fpcc_struct_return, OPT_freg_struct_return)) {
1042 if (A->getOption().matches(OPT_fpcc_struct_return)) {
1043 Opts.setStructReturnConvention(CodeGenOptions::SRCK_OnStack);
1044 } else {
1045 assert(A->getOption().matches(OPT_freg_struct_return));
1046 Opts.setStructReturnConvention(CodeGenOptions::SRCK_InRegs);
1047 }
1048 }
1049
Hans Wennborg75958c42013-08-08 00:17:41 +00001050 Opts.DependentLibraries = Args.getAllArgValues(OPT_dependent_lib);
Peter Collingbournedc134532016-01-16 00:31:22 +00001051 Opts.LinkerOptions = Args.getAllArgValues(OPT_linker_option);
Diego Novillo913690c2014-06-24 17:02:17 +00001052 bool NeedLocTracking = false;
Hans Wennborg75958c42013-08-08 00:17:41 +00001053
Hal Finkel8f96e822016-10-11 00:26:09 +00001054 Opts.OptRecordFile = Args.getLastArgValue(OPT_opt_record_file);
1055 if (!Opts.OptRecordFile.empty())
1056 NeedLocTracking = true;
1057
Diego Novillo913690c2014-06-24 17:02:17 +00001058 if (Arg *A = Args.getLastArg(OPT_Rpass_EQ)) {
Diego Novillod23ec942014-05-29 19:55:06 +00001059 Opts.OptimizationRemarkPattern =
1060 GenerateOptimizationRemarkRegex(Diags, Args, A);
Diego Novillo913690c2014-06-24 17:02:17 +00001061 NeedLocTracking = true;
1062 }
Diego Novillod23ec942014-05-29 19:55:06 +00001063
Diego Novillo913690c2014-06-24 17:02:17 +00001064 if (Arg *A = Args.getLastArg(OPT_Rpass_missed_EQ)) {
Diego Novillod23ec942014-05-29 19:55:06 +00001065 Opts.OptimizationRemarkMissedPattern =
1066 GenerateOptimizationRemarkRegex(Diags, Args, A);
Diego Novillo913690c2014-06-24 17:02:17 +00001067 NeedLocTracking = true;
1068 }
Diego Novillod23ec942014-05-29 19:55:06 +00001069
Diego Novillo913690c2014-06-24 17:02:17 +00001070 if (Arg *A = Args.getLastArg(OPT_Rpass_analysis_EQ)) {
Diego Novillod23ec942014-05-29 19:55:06 +00001071 Opts.OptimizationRemarkAnalysisPattern =
1072 GenerateOptimizationRemarkRegex(Diags, Args, A);
Diego Novillo913690c2014-06-24 17:02:17 +00001073 NeedLocTracking = true;
1074 }
1075
Adam Nemet1eea3e52016-09-13 04:32:40 +00001076 Opts.DiagnosticsWithHotness =
1077 Args.hasArg(options::OPT_fdiagnostics_show_hotness);
Brian Gesiak0ea58882017-06-23 02:38:45 +00001078 bool UsingSampleProfile = !Opts.SampleProfileFile.empty();
Brian Gesiak562eab92017-07-01 05:45:26 +00001079 bool UsingProfile = UsingSampleProfile ||
1080 (Opts.getProfileUse() != CodeGenOptions::ProfileNone);
Brian Gesiak0ea58882017-06-23 02:38:45 +00001081
Teresa Johnson66744f82018-05-05 14:37:29 +00001082 if (Opts.DiagnosticsWithHotness && !UsingProfile &&
1083 // An IR file will contain PGO as metadata
1084 IK.getLanguage() != InputKind::LLVM_IR)
Brian Gesiak562eab92017-07-01 05:45:26 +00001085 Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
1086 << "-fdiagnostics-show-hotness";
1087
1088 Opts.DiagnosticsHotnessThreshold = getLastArgUInt64Value(
1089 Args, options::OPT_fdiagnostics_hotness_threshold_EQ, 0);
1090 if (Opts.DiagnosticsHotnessThreshold > 0 && !UsingProfile)
1091 Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
1092 << "-fdiagnostics-hotness-threshold=";
Adam Nemet1eea3e52016-09-13 04:32:40 +00001093
Diego Novillo795f53b2014-10-22 13:00:05 +00001094 // If the user requested to use a sample profile for PGO, then the
1095 // backend will need to track source location information so the profile
1096 // can be incorporated into the IR.
Brian Gesiak0ea58882017-06-23 02:38:45 +00001097 if (UsingSampleProfile)
Diego Novillo795f53b2014-10-22 13:00:05 +00001098 NeedLocTracking = true;
1099
1100 // If the user requested a flag that requires source locations available in
1101 // the backend, make sure that the backend tracks source location information.
Benjamin Kramer8c305922016-02-02 11:06:51 +00001102 if (NeedLocTracking && Opts.getDebugInfo() == codegenoptions::NoDebugInfo)
1103 Opts.setDebugInfo(codegenoptions::LocTrackingOnly);
Diego Novillod23ec942014-05-29 19:55:06 +00001104
Saleem Abdulrasool76a4b952015-01-09 05:10:20 +00001105 Opts.RewriteMapFiles = Args.getAllArgValues(OPT_frewrite_map_file);
1106
Alexey Samsonov88459522015-01-12 22:39:12 +00001107 // Parse -fsanitize-recover= arguments.
1108 // FIXME: Report unrecoverable sanitizers incorrectly specified here.
1109 parseSanitizerKinds("-fsanitize-recover=",
1110 Args.getAllArgValues(OPT_fsanitize_recover_EQ), Diags,
1111 Opts.SanitizeRecover);
Peter Collingbourne9881b782015-06-18 23:59:22 +00001112 parseSanitizerKinds("-fsanitize-trap=",
1113 Args.getAllArgValues(OPT_fsanitize_trap_EQ), Diags,
1114 Opts.SanitizeTrap);
Alexey Samsonov88459522015-01-12 22:39:12 +00001115
Jonas Hahnfelde7681322018-02-28 17:53:46 +00001116 Opts.CudaGpuBinaryFileName =
1117 Args.getLastArgValue(OPT_fcuda_include_gpubinary);
Artem Belevich52cc4872015-05-07 19:34:16 +00001118
Marcin Koscielnickib31ee6d2016-05-04 23:37:40 +00001119 Opts.Backchain = Args.hasArg(OPT_mbackchain);
1120
Filipe Cabecinhasab731f72016-05-12 16:51:36 +00001121 Opts.EmitCheckPathComponentsToStrip = getLastArgIntValue(
1122 Args, OPT_fsanitize_undefined_strip_path_components_EQ, 0, Diags);
1123
Mikhail Maltsev4a4e7a32018-04-23 10:08:46 +00001124 Opts.EmitVersionIdentMetadata = Args.hasFlag(OPT_Qy, OPT_Qn, true);
1125
Peter Collingbourne14b468b2018-07-18 00:27:07 +00001126 Opts.Addrsig = Args.hasArg(OPT_faddrsig);
1127
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00001128 return Success;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001129}
1130
1131static void ParseDependencyOutputArgs(DependencyOutputOptions &Opts,
1132 ArgList &Args) {
Daniel Dunbar37300482010-05-20 16:54:55 +00001133 Opts.OutputFile = Args.getLastArgValue(OPT_dependency_file);
1134 Opts.Targets = Args.getAllArgValues(OPT_MT);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001135 Opts.IncludeSystemHeaders = Args.hasArg(OPT_sys_header_deps);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00001136 Opts.IncludeModuleFiles = Args.hasArg(OPT_module_file_deps);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001137 Opts.UsePhonyTargets = Args.hasArg(OPT_MP);
Daniel Dunbar27734fd2011-02-02 15:41:17 +00001138 Opts.ShowHeaderIncludes = Args.hasArg(OPT_H);
Daniel Dunbar1af1d27512011-02-02 21:11:31 +00001139 Opts.HeaderIncludeOutputFile = Args.getLastArgValue(OPT_header_include_file);
Peter Collingbourne77b0e7f22011-07-12 19:35:15 +00001140 Opts.AddMissingHeaderDeps = Args.hasArg(OPT_MG);
Erich Keane425f48d2018-05-04 15:58:31 +00001141 if (Args.hasArg(OPT_show_includes)) {
1142 // Writing both /showIncludes and preprocessor output to stdout
1143 // would produce interleaved output, so use stderr for /showIncludes.
1144 // This behaves the same as cl.exe, when /E, /EP or /P are passed.
1145 if (Args.hasArg(options::OPT_E) || Args.hasArg(options::OPT_P))
1146 Opts.ShowIncludesDest = ShowIncludesDestination::Stderr;
1147 else
1148 Opts.ShowIncludesDest = ShowIncludesDestination::Stdout;
1149 } else {
1150 Opts.ShowIncludesDest = ShowIncludesDestination::None;
1151 }
Douglas Gregor2e129652012-02-02 23:45:13 +00001152 Opts.DOTOutputFile = Args.getLastArgValue(OPT_dependency_dot);
Justin Bogner86d12592014-06-19 19:36:03 +00001153 Opts.ModuleDependencyOutputDir =
1154 Args.getLastArgValue(OPT_module_dependency_dir);
Paul Robinsond7214a72015-04-27 18:14:32 +00001155 if (Args.hasArg(OPT_MV))
1156 Opts.OutputFormat = DependencyOutputFormat::NMake;
Ivan Krasin1193f2c2015-08-13 04:04:37 +00001157 // Add sanitizer blacklists as extra dependencies.
1158 // They won't be discovered by the regular preprocessor, so
1159 // we let make / ninja to know about this implicit dependency.
Ivan Krasin4c3f2372015-09-02 20:02:38 +00001160 Opts.ExtraDeps = Args.getAllArgValues(OPT_fdepfile_entry);
Boris Kolpackovd30446f2017-08-31 06:26:43 +00001161 // Only the -fmodule-file=<file> form.
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001162 for (const auto *A : Args.filtered(OPT_fmodule_file)) {
Boris Kolpackovd30446f2017-08-31 06:26:43 +00001163 StringRef Val = A->getValue();
1164 if (Val.find('=') == StringRef::npos)
1165 Opts.ExtraDeps.push_back(Val);
1166 }
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001167}
1168
Bruno Cardoso Lopes681d7172016-05-27 20:43:00 +00001169static bool parseShowColorsArgs(const ArgList &Args, bool DefaultColor) {
1170 // Color diagnostics default to auto ("on" if terminal supports) in the driver
1171 // but default to off in cc1, needing an explicit OPT_fdiagnostics_color.
1172 // Support both clang's -f[no-]color-diagnostics and gcc's
1173 // -f[no-]diagnostics-colors[=never|always|auto].
1174 enum {
1175 Colors_On,
1176 Colors_Off,
1177 Colors_Auto
1178 } ShowColors = DefaultColor ? Colors_Auto : Colors_Off;
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001179 for (auto *A : Args) {
Bruno Cardoso Lopes681d7172016-05-27 20:43:00 +00001180 const Option &O = A->getOption();
Bruno Cardoso Lopes681d7172016-05-27 20:43:00 +00001181 if (O.matches(options::OPT_fcolor_diagnostics) ||
1182 O.matches(options::OPT_fdiagnostics_color)) {
1183 ShowColors = Colors_On;
1184 } else if (O.matches(options::OPT_fno_color_diagnostics) ||
1185 O.matches(options::OPT_fno_diagnostics_color)) {
1186 ShowColors = Colors_Off;
Yaron Keren9181e772016-12-10 14:55:14 +00001187 } else if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
Bruno Cardoso Lopes681d7172016-05-27 20:43:00 +00001188 StringRef Value(A->getValue());
1189 if (Value == "always")
1190 ShowColors = Colors_On;
1191 else if (Value == "never")
1192 ShowColors = Colors_Off;
1193 else if (Value == "auto")
1194 ShowColors = Colors_Auto;
1195 }
1196 }
Yaron Keren9181e772016-12-10 14:55:14 +00001197 return ShowColors == Colors_On ||
1198 (ShowColors == Colors_Auto &&
1199 llvm::sys::Process::StandardErrHasColors());
Bruno Cardoso Lopes681d7172016-05-27 20:43:00 +00001200}
1201
Hal Finkel05e46482017-12-16 02:23:22 +00001202static bool checkVerifyPrefixes(const std::vector<std::string> &VerifyPrefixes,
1203 DiagnosticsEngine *Diags) {
1204 bool Success = true;
1205 for (const auto &Prefix : VerifyPrefixes) {
1206 // Every prefix must start with a letter and contain only alphanumeric
1207 // characters, hyphens, and underscores.
1208 auto BadChar = std::find_if(Prefix.begin(), Prefix.end(),
1209 [](char C){return !isAlphanumeric(C)
1210 && C != '-' && C != '_';});
1211 if (BadChar != Prefix.end() || !isLetter(Prefix[0])) {
1212 Success = false;
1213 if (Diags) {
1214 Diags->Report(diag::err_drv_invalid_value) << "-verify=" << Prefix;
1215 Diags->Report(diag::note_drv_verify_prefix_spelling);
1216 }
1217 }
1218 }
1219 return Success;
1220}
1221
Chad Rosierd6f716a2012-03-13 20:09:56 +00001222bool clang::ParseDiagnosticArgs(DiagnosticOptions &Opts, ArgList &Args,
Bruno Cardoso Lopes681d7172016-05-27 20:43:00 +00001223 DiagnosticsEngine *Diags,
Bruno Cardoso Lopes76952a72016-10-11 18:21:26 +00001224 bool DefaultDiagColor, bool DefaultShowOpt) {
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00001225 bool Success = true;
1226
Daniel Dunbar6b584862011-04-07 18:11:14 +00001227 Opts.DiagnosticLogFile = Args.getLastArgValue(OPT_diagnostic_log_file);
Justin Bogner5a6a2fc2014-10-23 22:20:11 +00001228 if (Arg *A =
1229 Args.getLastArg(OPT_diagnostic_serialized_file, OPT__serialize_diags))
1230 Opts.DiagnosticSerializationFile = A->getValue();
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001231 Opts.IgnoreWarnings = Args.hasArg(OPT_w);
1232 Opts.NoRewriteMacros = Args.hasArg(OPT_Wno_rewrite_macros);
1233 Opts.Pedantic = Args.hasArg(OPT_pedantic);
1234 Opts.PedanticErrors = Args.hasArg(OPT_pedantic_errors);
1235 Opts.ShowCarets = !Args.hasArg(OPT_fno_caret_diagnostics);
Bruno Cardoso Lopes681d7172016-05-27 20:43:00 +00001236 Opts.ShowColors = parseShowColorsArgs(Args, DefaultDiagColor);
Douglas Gregor643c9222011-05-21 17:07:29 +00001237 Opts.ShowColumn = Args.hasFlag(OPT_fshow_column,
1238 OPT_fno_show_column,
1239 /*Default=*/true);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001240 Opts.ShowFixits = !Args.hasArg(OPT_fno_diagnostics_fixit_info);
1241 Opts.ShowLocation = !Args.hasArg(OPT_fno_show_source_location);
Hans Wennborgb30f4372016-08-26 15:45:36 +00001242 Opts.AbsolutePath = Args.hasArg(OPT_fdiagnostics_absolute_paths);
Bruno Cardoso Lopes76952a72016-10-11 18:21:26 +00001243 Opts.ShowOptionNames =
1244 Args.hasFlag(OPT_fdiagnostics_show_option,
1245 OPT_fno_diagnostics_show_option, DefaultShowOpt);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00001246
Nico Rieck7857d462013-09-11 00:38:02 +00001247 llvm::sys::Process::UseANSIEscapeCodes(Args.hasArg(OPT_fansi_escape_codes));
1248
Chandler Carruth24284af2011-03-27 20:00:08 +00001249 // Default behavior is to not to show note include stacks.
1250 Opts.ShowNoteIncludeStack = false;
Chandler Carruthb6766f02011-03-27 01:50:55 +00001251 if (Arg *A = Args.getLastArg(OPT_fdiagnostics_show_note_include_stack,
1252 OPT_fno_diagnostics_show_note_include_stack))
Chandler Carruth24284af2011-03-27 20:00:08 +00001253 if (A->getOption().matches(OPT_fdiagnostics_show_note_include_stack))
1254 Opts.ShowNoteIncludeStack = true;
Chandler Carruthb6766f02011-03-27 01:50:55 +00001255
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001256 StringRef ShowOverloads =
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00001257 Args.getLastArgValue(OPT_fshow_overloads_EQ, "all");
1258 if (ShowOverloads == "best")
Douglas Gregor79591782012-10-23 23:11:23 +00001259 Opts.setShowOverloads(Ovl_Best);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00001260 else if (ShowOverloads == "all")
Douglas Gregor79591782012-10-23 23:11:23 +00001261 Opts.setShowOverloads(Ovl_All);
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00001262 else {
Chad Rosierd6f716a2012-03-13 20:09:56 +00001263 Success = false;
1264 if (Diags)
1265 Diags->Report(diag::err_drv_invalid_value)
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00001266 << Args.getLastArg(OPT_fshow_overloads_EQ)->getAsString(Args)
1267 << ShowOverloads;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00001268 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00001269
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001270 StringRef ShowCategory =
Daniel Dunbar37300482010-05-20 16:54:55 +00001271 Args.getLastArgValue(OPT_fdiagnostics_show_category, "none");
Chris Lattnerbf6fac82010-05-04 21:55:25 +00001272 if (ShowCategory == "none")
1273 Opts.ShowCategories = 0;
1274 else if (ShowCategory == "id")
1275 Opts.ShowCategories = 1;
1276 else if (ShowCategory == "name")
1277 Opts.ShowCategories = 2;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00001278 else {
Chad Rosierd6f716a2012-03-13 20:09:56 +00001279 Success = false;
1280 if (Diags)
1281 Diags->Report(diag::err_drv_invalid_value)
Chris Lattnerbf6fac82010-05-04 21:55:25 +00001282 << Args.getLastArg(OPT_fdiagnostics_show_category)->getAsString(Args)
1283 << ShowCategory;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00001284 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00001285
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001286 StringRef Format =
Douglas Gregor643c9222011-05-21 17:07:29 +00001287 Args.getLastArgValue(OPT_fdiagnostics_format, "clang");
1288 if (Format == "clang")
Douglas Gregor79591782012-10-23 23:11:23 +00001289 Opts.setFormat(DiagnosticOptions::Clang);
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00001290 else if (Format == "msvc")
David Majnemer8ab003a2015-02-02 19:30:52 +00001291 Opts.setFormat(DiagnosticOptions::MSVC);
Hans Wennborgf4aee182013-09-24 00:08:55 +00001292 else if (Format == "msvc-fallback") {
David Majnemer8ab003a2015-02-02 19:30:52 +00001293 Opts.setFormat(DiagnosticOptions::MSVC);
Hans Wennborgf4aee182013-09-24 00:08:55 +00001294 Opts.CLFallbackMode = true;
1295 } else if (Format == "vi")
Douglas Gregor79591782012-10-23 23:11:23 +00001296 Opts.setFormat(DiagnosticOptions::Vi);
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00001297 else {
Chad Rosierd6f716a2012-03-13 20:09:56 +00001298 Success = false;
1299 if (Diags)
1300 Diags->Report(diag::err_drv_invalid_value)
Douglas Gregor643c9222011-05-21 17:07:29 +00001301 << Args.getLastArg(OPT_fdiagnostics_format)->getAsString(Args)
1302 << Format;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00001303 }
Eric Fiselier098e6de2015-06-13 07:11:40 +00001304
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001305 Opts.ShowSourceRanges = Args.hasArg(OPT_fdiagnostics_print_source_range_info);
Douglas Gregoreec975c2010-08-19 20:24:43 +00001306 Opts.ShowParseableFixits = Args.hasArg(OPT_fdiagnostics_parseable_fixits);
Richard Smith0b50cb72012-11-14 23:55:25 +00001307 Opts.ShowPresumedLoc = !Args.hasArg(OPT_fno_diagnostics_use_presumed_location);
Hal Finkel05e46482017-12-16 02:23:22 +00001308 Opts.VerifyDiagnostics = Args.hasArg(OPT_verify) || Args.hasArg(OPT_verify_EQ);
1309 Opts.VerifyPrefixes = Args.getAllArgValues(OPT_verify_EQ);
1310 if (Args.hasArg(OPT_verify))
1311 Opts.VerifyPrefixes.push_back("expected");
1312 // Keep VerifyPrefixes in its original order for the sake of diagnostics, and
1313 // then sort it to prepare for fast lookup using std::binary_search.
1314 if (!checkVerifyPrefixes(Opts.VerifyPrefixes, Diags)) {
1315 Opts.VerifyDiagnostics = false;
1316 Success = false;
1317 }
1318 else
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00001319 llvm::sort(Opts.VerifyPrefixes.begin(), Opts.VerifyPrefixes.end());
Eric Fiselier098e6de2015-06-13 07:11:40 +00001320 DiagnosticLevelMask DiagMask = DiagnosticLevelMask::None;
1321 Success &= parseDiagnosticLevelMask("-verify-ignore-unexpected=",
1322 Args.getAllArgValues(OPT_verify_ignore_unexpected_EQ),
1323 Diags, DiagMask);
1324 if (Args.hasArg(OPT_verify_ignore_unexpected))
1325 DiagMask = DiagnosticLevelMask::All;
1326 Opts.setVerifyIgnoreUnexpected(DiagMask);
Richard Trieu91844232012-06-26 18:18:47 +00001327 Opts.ElideType = !Args.hasArg(OPT_fno_elide_type);
1328 Opts.ShowTemplateTree = Args.hasArg(OPT_fdiagnostics_show_template_tree);
Reid Kleckner898229a2013-06-14 17:17:23 +00001329 Opts.ErrorLimit = getLastArgIntValue(Args, OPT_ferror_limit, 0, Diags);
1330 Opts.MacroBacktraceLimit =
1331 getLastArgIntValue(Args, OPT_fmacro_backtrace_limit,
Douglas Gregorcd121fb2010-05-04 17:13:42 +00001332 DiagnosticOptions::DefaultMacroBacktraceLimit, Diags);
Reid Kleckner898229a2013-06-14 17:17:23 +00001333 Opts.TemplateBacktraceLimit = getLastArgIntValue(
1334 Args, OPT_ftemplate_backtrace_limit,
1335 DiagnosticOptions::DefaultTemplateBacktraceLimit, Diags);
1336 Opts.ConstexprBacktraceLimit = getLastArgIntValue(
1337 Args, OPT_fconstexpr_backtrace_limit,
1338 DiagnosticOptions::DefaultConstexprBacktraceLimit, Diags);
Nick Lewycky24653262014-12-16 21:39:02 +00001339 Opts.SpellCheckingLimit = getLastArgIntValue(
1340 Args, OPT_fspell_checking_limit,
1341 DiagnosticOptions::DefaultSpellCheckingLimit, Diags);
Richard Smith0c7d4d7e2017-05-22 23:51:40 +00001342 Opts.SnippetLineLimit = getLastArgIntValue(
1343 Args, OPT_fcaret_diagnostics_max_lines,
1344 DiagnosticOptions::DefaultSnippetLineLimit, Diags);
Reid Kleckner898229a2013-06-14 17:17:23 +00001345 Opts.TabStop = getLastArgIntValue(Args, OPT_ftabstop,
Chris Lattner3d756f12010-01-13 03:06:50 +00001346 DiagnosticOptions::DefaultTabStop, Diags);
1347 if (Opts.TabStop == 0 || Opts.TabStop > DiagnosticOptions::MaxTabStop) {
Chris Lattner3d756f12010-01-13 03:06:50 +00001348 Opts.TabStop = DiagnosticOptions::DefaultTabStop;
Chad Rosierd6f716a2012-03-13 20:09:56 +00001349 if (Diags)
1350 Diags->Report(diag::warn_ignoring_ftabstop_value)
1351 << Opts.TabStop << DiagnosticOptions::DefaultTabStop;
Chris Lattner3d756f12010-01-13 03:06:50 +00001352 }
Reid Kleckner898229a2013-06-14 17:17:23 +00001353 Opts.MessageLength = getLastArgIntValue(Args, OPT_fmessage_length, 0, Diags);
Richard Smith3be1cb22014-08-07 00:24:21 +00001354 addDiagnosticArgs(Args, OPT_W_Group, OPT_W_value_Group, Opts.Warnings);
1355 addDiagnosticArgs(Args, OPT_R_Group, OPT_R_value_Group, Opts.Remarks);
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00001356
1357 return Success;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001358}
1359
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +00001360static void ParseFileSystemArgs(FileSystemOptions &Opts, ArgList &Args) {
1361 Opts.WorkingDir = Args.getLastArgValue(OPT_working_directory);
1362}
1363
Douglas Gregor6623e1f2015-11-03 18:33:07 +00001364/// Parse the argument to the -ftest-module-file-extension
1365/// command-line argument.
1366///
1367/// \returns true on error, false on success.
1368static bool parseTestModuleFileExtensionArg(StringRef Arg,
1369 std::string &BlockName,
1370 unsigned &MajorVersion,
1371 unsigned &MinorVersion,
1372 bool &Hashed,
1373 std::string &UserInfo) {
1374 SmallVector<StringRef, 5> Args;
1375 Arg.split(Args, ':', 5);
1376 if (Args.size() < 5)
1377 return true;
1378
1379 BlockName = Args[0];
1380 if (Args[1].getAsInteger(10, MajorVersion)) return true;
1381 if (Args[2].getAsInteger(10, MinorVersion)) return true;
1382 if (Args[3].getAsInteger(2, Hashed)) return true;
1383 if (Args.size() > 4)
1384 UserInfo = Args[4];
1385 return false;
1386}
1387
Daniel Dunbar9b491e72010-06-07 23:22:09 +00001388static InputKind ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args,
Erik Verbruggene0bde752016-10-27 14:17:10 +00001389 DiagnosticsEngine &Diags,
1390 bool &IsHeaderFile) {
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001391 Opts.ProgramAction = frontend::ParseSyntaxOnly;
1392 if (const Arg *A = Args.getLastArg(OPT_Action_Group)) {
1393 switch (A->getOption().getID()) {
1394 default:
David Blaikie83d382b2011-09-23 05:06:16 +00001395 llvm_unreachable("Invalid option in group!");
Alexander Kornienko4de03592012-07-31 09:37:40 +00001396 case OPT_ast_list:
1397 Opts.ProgramAction = frontend::ASTDeclList; break;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001398 case OPT_ast_dump:
Richard Smith3a36ac12017-03-09 22:00:01 +00001399 case OPT_ast_dump_all:
Richard Smith35f986d2014-08-11 22:11:07 +00001400 case OPT_ast_dump_lookups:
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001401 Opts.ProgramAction = frontend::ASTDump; break;
1402 case OPT_ast_print:
1403 Opts.ProgramAction = frontend::ASTPrint; break;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001404 case OPT_ast_view:
1405 Opts.ProgramAction = frontend::ASTView; break;
Aaron Ballman16ed8dd2018-05-31 13:57:09 +00001406 case OPT_compiler_options_dump:
1407 Opts.ProgramAction = frontend::DumpCompilerOptions; break;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001408 case OPT_dump_raw_tokens:
1409 Opts.ProgramAction = frontend::DumpRawTokens; break;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001410 case OPT_dump_tokens:
1411 Opts.ProgramAction = frontend::DumpTokens; break;
1412 case OPT_S:
1413 Opts.ProgramAction = frontend::EmitAssembly; break;
1414 case OPT_emit_llvm_bc:
1415 Opts.ProgramAction = frontend::EmitBC; break;
1416 case OPT_emit_html:
1417 Opts.ProgramAction = frontend::EmitHTML; break;
1418 case OPT_emit_llvm:
1419 Opts.ProgramAction = frontend::EmitLLVM; break;
1420 case OPT_emit_llvm_only:
1421 Opts.ProgramAction = frontend::EmitLLVMOnly; break;
Daniel Dunbar4c77a642010-05-25 18:41:01 +00001422 case OPT_emit_codegen_only:
1423 Opts.ProgramAction = frontend::EmitCodeGenOnly; break;
Daniel Dunbar92db0fb2010-02-03 01:18:43 +00001424 case OPT_emit_obj:
1425 Opts.ProgramAction = frontend::EmitObj; break;
Nick Lewycky784fad72010-04-24 01:30:46 +00001426 case OPT_fixit_EQ:
Richard Smithbd55daf2012-11-01 04:30:05 +00001427 Opts.FixItSuffix = A->getValue();
Nick Lewycky784fad72010-04-24 01:30:46 +00001428 // fall-through!
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001429 case OPT_fixit:
1430 Opts.ProgramAction = frontend::FixIt; break;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001431 case OPT_emit_module:
1432 Opts.ProgramAction = frontend::GenerateModule; break;
Richard Smithbbcc9f02016-08-26 00:14:38 +00001433 case OPT_emit_module_interface:
1434 Opts.ProgramAction = frontend::GenerateModuleInterface; break;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001435 case OPT_emit_pch:
1436 Opts.ProgramAction = frontend::GeneratePCH; break;
1437 case OPT_emit_pth:
1438 Opts.ProgramAction = frontend::GeneratePTH; break;
Daniel Dunbar1c201fb2010-03-19 19:44:04 +00001439 case OPT_init_only:
1440 Opts.ProgramAction = frontend::InitOnly; break;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001441 case OPT_fsyntax_only:
1442 Opts.ProgramAction = frontend::ParseSyntaxOnly; break;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00001443 case OPT_module_file_info:
1444 Opts.ProgramAction = frontend::ModuleFileInfo; break;
Ben Langmuir2cb4a782014-02-05 22:21:15 +00001445 case OPT_verify_pch:
1446 Opts.ProgramAction = frontend::VerifyPCH; break;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001447 case OPT_print_decl_contexts:
1448 Opts.ProgramAction = frontend::PrintDeclContext; break;
Douglas Gregoraf82e352010-07-20 20:18:03 +00001449 case OPT_print_preamble:
1450 Opts.ProgramAction = frontend::PrintPreamble; break;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001451 case OPT_E:
1452 Opts.ProgramAction = frontend::PrintPreprocessedInput; break;
Gabor Horvath207e7b12018-02-10 14:04:45 +00001453 case OPT_templight_dump:
1454 Opts.ProgramAction = frontend::TemplightDump; break;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001455 case OPT_rewrite_macros:
1456 Opts.ProgramAction = frontend::RewriteMacros; break;
1457 case OPT_rewrite_objc:
1458 Opts.ProgramAction = frontend::RewriteObjC; break;
1459 case OPT_rewrite_test:
1460 Opts.ProgramAction = frontend::RewriteTest; break;
1461 case OPT_analyze:
1462 Opts.ProgramAction = frontend::RunAnalysis; break;
Ted Kremenekf7639e12012-03-06 20:06:33 +00001463 case OPT_migrate:
1464 Opts.ProgramAction = frontend::MigrateSource; break;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001465 case OPT_Eonly:
1466 Opts.ProgramAction = frontend::RunPreprocessorOnly; break;
1467 }
1468 }
Daniel Dunbar7c995e82010-06-16 16:59:23 +00001469
1470 if (const Arg* A = Args.getLastArg(OPT_plugin)) {
Benjamin Kramer3204b152015-05-29 19:42:19 +00001471 Opts.Plugins.emplace_back(A->getValue(0));
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001472 Opts.ProgramAction = frontend::PluginAction;
Richard Smithbd55daf2012-11-01 04:30:05 +00001473 Opts.ActionName = A->getValue();
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001474 }
Nico Weber2992efa2011-01-25 20:34:14 +00001475 Opts.AddPluginActions = Args.getAllArgValues(OPT_add_plugin);
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001476 for (const auto *AA : Args.filtered(OPT_plugin_arg))
John Brawn6c789742016-03-15 12:51:40 +00001477 Opts.PluginArgs[AA->getValue(0)].emplace_back(AA->getValue(1));
Nico Weber2992efa2011-01-25 20:34:14 +00001478
Douglas Gregor6623e1f2015-11-03 18:33:07 +00001479 for (const std::string &Arg :
1480 Args.getAllArgValues(OPT_ftest_module_file_extension_EQ)) {
1481 std::string BlockName;
1482 unsigned MajorVersion;
1483 unsigned MinorVersion;
1484 bool Hashed;
1485 std::string UserInfo;
1486 if (parseTestModuleFileExtensionArg(Arg, BlockName, MajorVersion,
1487 MinorVersion, Hashed, UserInfo)) {
1488 Diags.Report(diag::err_test_module_file_extension_format) << Arg;
1489
1490 continue;
1491 }
1492
1493 // Add the testing module file extension.
1494 Opts.ModuleFileExtensions.push_back(
David Blaikie61137e12017-01-05 18:23:18 +00001495 std::make_shared<TestModuleFileExtension>(
1496 BlockName, MajorVersion, MinorVersion, Hashed, UserInfo));
Douglas Gregor6623e1f2015-11-03 18:33:07 +00001497 }
1498
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001499 if (const Arg *A = Args.getLastArg(OPT_code_completion_at)) {
1500 Opts.CodeCompletionAt =
Richard Smithbd55daf2012-11-01 04:30:05 +00001501 ParsedSourceLocation::FromString(A->getValue());
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001502 if (Opts.CodeCompletionAt.FileName.empty())
1503 Diags.Report(diag::err_drv_invalid_value)
Richard Smithbd55daf2012-11-01 04:30:05 +00001504 << A->getAsString(Args) << A->getValue();
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001505 }
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001506 Opts.DisableFree = Args.hasArg(OPT_disable_free);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001507
Daniel Dunbar37300482010-05-20 16:54:55 +00001508 Opts.OutputFile = Args.getLastArgValue(OPT_o);
1509 Opts.Plugins = Args.getAllArgValues(OPT_load);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001510 Opts.RelocatablePCH = Args.hasArg(OPT_relocatable_pch);
Daniel Dunbar215ca5f2009-12-03 07:01:58 +00001511 Opts.ShowHelp = Args.hasArg(OPT_help);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001512 Opts.ShowStats = Args.hasArg(OPT_print_stats);
1513 Opts.ShowTimers = Args.hasArg(OPT_ftime_report);
Daniel Dunbar215ca5f2009-12-03 07:01:58 +00001514 Opts.ShowVersion = Args.hasArg(OPT_version);
Daniel Dunbar37300482010-05-20 16:54:55 +00001515 Opts.ASTMergeFiles = Args.getAllArgValues(OPT_ast_merge);
1516 Opts.LLVMArgs = Args.getAllArgValues(OPT_mllvm);
Nick Lewycky078a5e22010-08-13 17:31:00 +00001517 Opts.FixWhatYouCan = Args.hasArg(OPT_fix_what_you_can);
Argyrios Kyrtzidis24e9aff2012-01-26 02:40:48 +00001518 Opts.FixOnlyWarnings = Args.hasArg(OPT_fix_only_warnings);
1519 Opts.FixAndRecompile = Args.hasArg(OPT_fixit_recompile);
1520 Opts.FixToTemporaries = Args.hasArg(OPT_fixit_to_temp);
Richard Smith35f986d2014-08-11 22:11:07 +00001521 Opts.ASTDumpDecls = Args.hasArg(OPT_ast_dump);
Richard Smith3a36ac12017-03-09 22:00:01 +00001522 Opts.ASTDumpAll = Args.hasArg(OPT_ast_dump_all);
Alexander Kornienko3db68ee2012-07-26 16:01:23 +00001523 Opts.ASTDumpFilter = Args.getLastArgValue(OPT_ast_dump_filter);
Richard Smith6ea05822013-06-24 01:45:33 +00001524 Opts.ASTDumpLookups = Args.hasArg(OPT_ast_dump_lookups);
Douglas Gregor137f1b92013-01-28 18:38:02 +00001525 Opts.UseGlobalModuleIndex = !Args.hasArg(OPT_fno_modules_global_index);
Douglas Gregorc1bbec82013-01-25 00:45:27 +00001526 Opts.GenerateGlobalModuleIndex = Opts.UseGlobalModuleIndex;
Richard Smith4a89a062014-12-06 01:13:41 +00001527 Opts.ModuleMapFiles = Args.getAllArgValues(OPT_fmodule_map_file);
Boris Kolpackovd30446f2017-08-31 06:26:43 +00001528 // Only the -fmodule-file=<file> form.
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001529 for (const auto *A : Args.filtered(OPT_fmodule_file)) {
Boris Kolpackovd30446f2017-08-31 06:26:43 +00001530 StringRef Val = A->getValue();
1531 if (Val.find('=') == StringRef::npos)
1532 Opts.ModuleFiles.push_back(Val);
1533 }
Richard Smithfb1e7f72015-08-14 05:02:58 +00001534 Opts.ModulesEmbedFiles = Args.getAllArgValues(OPT_fmodules_embed_file_EQ);
Richard Smith919ce232015-11-24 04:22:21 +00001535 Opts.ModulesEmbedAllFiles = Args.hasArg(OPT_fmodules_embed_all_files);
Pierre Gousseau533a8932016-07-13 14:21:11 +00001536 Opts.IncludeTimestamps = !Args.hasArg(OPT_fno_pch_timestamp);
Richard Smithe842a472014-10-22 02:05:46 +00001537
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001538 Opts.CodeCompleteOpts.IncludeMacros
1539 = Args.hasArg(OPT_code_completion_macros);
1540 Opts.CodeCompleteOpts.IncludeCodePatterns
1541 = Args.hasArg(OPT_code_completion_patterns);
1542 Opts.CodeCompleteOpts.IncludeGlobals
1543 = !Args.hasArg(OPT_no_code_completion_globals);
Eric Liufead6ae2017-12-13 10:26:49 +00001544 Opts.CodeCompleteOpts.IncludeNamespaceLevelDecls
1545 = !Args.hasArg(OPT_no_code_completion_ns_level_decls);
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001546 Opts.CodeCompleteOpts.IncludeBriefComments
1547 = Args.hasArg(OPT_code_completion_brief_comments);
Ivan Donchevskiib4670fc2018-05-25 12:56:26 +00001548 Opts.CodeCompleteOpts.IncludeFixIts
1549 = Args.hasArg(OPT_code_completion_with_fixits);
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001550
Douglas Gregore9fc3772012-01-26 07:55:45 +00001551 Opts.OverrideRecordLayoutsFile
1552 = Args.getLastArgValue(OPT_foverride_record_layout_EQ);
Petr Hosek7b274542018-08-08 22:23:57 +00001553 Opts.AuxTriple = Args.getLastArgValue(OPT_aux_triple);
Matthias Braunabb6eea2016-09-26 18:53:34 +00001554 Opts.StatsFile = Args.getLastArgValue(OPT_stats_file);
Artem Belevichb5bc9232015-09-22 17:23:22 +00001555
John McCalld70fb982011-06-15 23:25:17 +00001556 if (const Arg *A = Args.getLastArg(OPT_arcmt_check,
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +00001557 OPT_arcmt_modify,
1558 OPT_arcmt_migrate)) {
John McCalld70fb982011-06-15 23:25:17 +00001559 switch (A->getOption().getID()) {
1560 default:
1561 llvm_unreachable("missed a case");
1562 case OPT_arcmt_check:
1563 Opts.ARCMTAction = FrontendOptions::ARCMT_Check;
1564 break;
1565 case OPT_arcmt_modify:
1566 Opts.ARCMTAction = FrontendOptions::ARCMT_Modify;
1567 break;
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +00001568 case OPT_arcmt_migrate:
1569 Opts.ARCMTAction = FrontendOptions::ARCMT_Migrate;
1570 break;
John McCalld70fb982011-06-15 23:25:17 +00001571 }
1572 }
Ted Kremenekf7639e12012-03-06 20:06:33 +00001573 Opts.MTMigrateDir = Args.getLastArgValue(OPT_mt_migrate_directory);
Argyrios Kyrtzidisd5713632011-07-19 17:20:03 +00001574 Opts.ARCMTMigrateReportOut
1575 = Args.getLastArgValue(OPT_arcmt_migrate_report_output);
1576 Opts.ARCMTMigrateEmitARCErrors
1577 = Args.hasArg(OPT_arcmt_migrate_emit_arc_errors);
John McCalld70fb982011-06-15 23:25:17 +00001578
Ted Kremenekf7639e12012-03-06 20:06:33 +00001579 if (Args.hasArg(OPT_objcmt_migrate_literals))
1580 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Literals;
1581 if (Args.hasArg(OPT_objcmt_migrate_subscripting))
1582 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Subscripting;
Fariborz Jahaniana6556f72014-10-31 21:19:45 +00001583 if (Args.hasArg(OPT_objcmt_migrate_property_dot_syntax))
1584 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_PropertyDotSyntax;
Fariborz Jahaniand83ef842013-07-09 16:59:14 +00001585 if (Args.hasArg(OPT_objcmt_migrate_property))
1586 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Property;
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +00001587 if (Args.hasArg(OPT_objcmt_migrate_readonly_property))
1588 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_ReadonlyProperty;
Fariborz Jahanianc1213862013-10-02 21:32:39 +00001589 if (Args.hasArg(OPT_objcmt_migrate_readwrite_property))
1590 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_ReadwriteProperty;
Fariborz Jahanian2bfa2b92013-10-02 21:58:13 +00001591 if (Args.hasArg(OPT_objcmt_migrate_annotation))
1592 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Annotation;
Fariborz Jahanian23417072013-11-05 22:28:30 +00001593 if (Args.hasArg(OPT_objcmt_returns_innerpointer_property))
1594 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_ReturnsInnerPointerProperty;
Fariborz Jahanian2bfa2b92013-10-02 21:58:13 +00001595 if (Args.hasArg(OPT_objcmt_migrate_instancetype))
1596 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Instancetype;
1597 if (Args.hasArg(OPT_objcmt_migrate_nsmacros))
1598 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_NsMacros;
1599 if (Args.hasArg(OPT_objcmt_migrate_protocol_conformance))
1600 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_ProtocolConformance;
Fariborz Jahanian20a11242013-10-09 19:06:08 +00001601 if (Args.hasArg(OPT_objcmt_atomic_property))
1602 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_AtomicProperty;
Fariborz Jahanian2e793d62013-11-13 00:08:36 +00001603 if (Args.hasArg(OPT_objcmt_ns_nonatomic_iosonly))
1604 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty;
Argyrios Kyrtzidis4f2ecc62013-12-10 18:36:49 +00001605 if (Args.hasArg(OPT_objcmt_migrate_designated_init))
1606 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_DesignatedInitializer;
Fariborz Jahanianc1213862013-10-02 21:32:39 +00001607 if (Args.hasArg(OPT_objcmt_migrate_all))
1608 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_MigrateDecls;
Ted Kremenekf7639e12012-03-06 20:06:33 +00001609
Argyrios Kyrtzidisd5ba86b2013-12-10 18:36:53 +00001610 Opts.ObjCMTWhiteListPath = Args.getLastArgValue(OPT_objcmt_whitelist_dir_path);
Argyrios Kyrtzidis61f20322013-11-14 16:33:29 +00001611
Ted Kremenekf7639e12012-03-06 20:06:33 +00001612 if (Opts.ARCMTAction != FrontendOptions::ARCMT_None &&
1613 Opts.ObjCMTAction != FrontendOptions::ObjCMT_None) {
1614 Diags.Report(diag::err_drv_argument_not_allowed_with)
1615 << "ARC migration" << "ObjC migration";
1616 }
1617
Richard Smith40c0efa2017-04-26 18:57:40 +00001618 InputKind DashX(InputKind::Unknown);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001619 if (const Arg *A = Args.getLastArg(OPT_x)) {
Richard Smith40c0efa2017-04-26 18:57:40 +00001620 StringRef XValue = A->getValue();
Richard Smithf74d9462017-04-28 01:49:42 +00001621
1622 // Parse suffixes: '<lang>(-header|[-module-map][-cpp-output])'.
1623 // FIXME: Supporting '<lang>-header-cpp-output' would be useful.
1624 bool Preprocessed = XValue.consume_back("-cpp-output");
1625 bool ModuleMap = XValue.consume_back("-module-map");
1626 IsHeaderFile =
1627 !Preprocessed && !ModuleMap && XValue.consume_back("-header");
1628
1629 // Principal languages.
Richard Smith40c0efa2017-04-26 18:57:40 +00001630 DashX = llvm::StringSwitch<InputKind>(XValue)
Richard Smithf74d9462017-04-28 01:49:42 +00001631 .Case("c", InputKind::C)
1632 .Case("cl", InputKind::OpenCL)
1633 .Case("cuda", InputKind::CUDA)
Yaxun Liu887c5692018-04-25 01:10:37 +00001634 .Case("hip", InputKind::HIP)
Richard Smithf74d9462017-04-28 01:49:42 +00001635 .Case("c++", InputKind::CXX)
1636 .Case("objective-c", InputKind::ObjC)
1637 .Case("objective-c++", InputKind::ObjCXX)
1638 .Case("renderscript", InputKind::RenderScript)
1639 .Default(InputKind::Unknown);
1640
1641 // "objc[++]-cpp-output" is an acceptable synonym for
1642 // "objective-c[++]-cpp-output".
1643 if (DashX.isUnknown() && Preprocessed && !IsHeaderFile && !ModuleMap)
1644 DashX = llvm::StringSwitch<InputKind>(XValue)
1645 .Case("objc", InputKind::ObjC)
1646 .Case("objc++", InputKind::ObjCXX)
1647 .Default(InputKind::Unknown);
1648
1649 // Some special cases cannot be combined with suffixes.
1650 if (DashX.isUnknown() && !Preprocessed && !ModuleMap && !IsHeaderFile)
1651 DashX = llvm::StringSwitch<InputKind>(XValue)
1652 .Case("cpp-output", InputKind(InputKind::C).getPreprocessed())
1653 .Case("assembler-with-cpp", InputKind::Asm)
1654 .Cases("ast", "pcm",
1655 InputKind(InputKind::Unknown, InputKind::Precompiled))
1656 .Case("ir", InputKind::LLVM_IR)
1657 .Default(InputKind::Unknown);
1658
Richard Smith40c0efa2017-04-26 18:57:40 +00001659 if (DashX.isUnknown())
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001660 Diags.Report(diag::err_drv_invalid_value)
Richard Smithbd55daf2012-11-01 04:30:05 +00001661 << A->getAsString(Args) << A->getValue();
Richard Smith40c0efa2017-04-26 18:57:40 +00001662
Richard Smithf74d9462017-04-28 01:49:42 +00001663 if (Preprocessed)
Richard Smith40c0efa2017-04-26 18:57:40 +00001664 DashX = DashX.getPreprocessed();
Richard Smithf74d9462017-04-28 01:49:42 +00001665 if (ModuleMap)
1666 DashX = DashX.withFormat(InputKind::ModuleMap);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001667 }
1668
1669 // '-' is the default input if none is given.
Daniel Dunbar37300482010-05-20 16:54:55 +00001670 std::vector<std::string> Inputs = Args.getAllArgValues(OPT_INPUT);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001671 Opts.Inputs.clear();
1672 if (Inputs.empty())
1673 Inputs.push_back("-");
1674 for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
Daniel Dunbar9b491e72010-06-07 23:22:09 +00001675 InputKind IK = DashX;
Richard Smith40c0efa2017-04-26 18:57:40 +00001676 if (IK.isUnknown()) {
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001677 IK = FrontendOptions::getInputKindForExtension(
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001678 StringRef(Inputs[i]).rsplit('.').second);
Richard Smith40c0efa2017-04-26 18:57:40 +00001679 // FIXME: Warn on this?
1680 if (IK.isUnknown())
1681 IK = InputKind::C;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001682 // FIXME: Remove this hack.
1683 if (i == 0)
1684 DashX = IK;
1685 }
Richard Smithf74d9462017-04-28 01:49:42 +00001686
1687 // The -emit-module action implicitly takes a module map.
1688 if (Opts.ProgramAction == frontend::GenerateModule &&
1689 IK.getFormat() == InputKind::Source)
1690 IK = IK.withFormat(InputKind::ModuleMap);
1691
Benjamin Kramer3204b152015-05-29 19:42:19 +00001692 Opts.Inputs.emplace_back(std::move(Inputs[i]), IK);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001693 }
1694
1695 return DashX;
1696}
1697
Daniel Dunbara5a166d2009-12-15 00:06:45 +00001698std::string CompilerInvocation::GetResourcesPath(const char *Argv0,
1699 void *MainAddr) {
Alexey Samsonov6465d4f2014-12-29 21:28:15 +00001700 std::string ClangExecutable =
1701 llvm::sys::fs::getMainExecutable(Argv0, MainAddr);
Chandler Carruthfd3cc702014-12-29 12:09:08 +00001702 StringRef Dir = llvm::sys::path::parent_path(ClangExecutable);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001703
Chandler Carruthfd3cc702014-12-29 12:09:08 +00001704 // Compute the path to the resource directory.
1705 StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
1706 SmallString<128> P(Dir);
Yaron Kerena9107412015-08-05 20:06:56 +00001707 if (ClangResourceDir != "")
Chandler Carruthfd3cc702014-12-29 12:09:08 +00001708 llvm::sys::path::append(P, ClangResourceDir);
Yaron Kerena9107412015-08-05 20:06:56 +00001709 else
1710 llvm::sys::path::append(P, "..", Twine("lib") + CLANG_LIBDIR_SUFFIX,
1711 "clang", CLANG_VERSION_STRING);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001712
1713 return P.str();
1714}
1715
Adrian Prantl0ebdeac2017-03-14 23:07:49 +00001716static void ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args,
1717 const std::string &WorkingDir) {
Daniel Dunbar37300482010-05-20 16:54:55 +00001718 Opts.Sysroot = Args.getLastArgValue(OPT_isysroot, "/");
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001719 Opts.Verbose = Args.hasArg(OPT_v);
Francois Pichet698f0192011-10-10 20:34:10 +00001720 Opts.UseBuiltinIncludes = !Args.hasArg(OPT_nobuiltininc);
Daniel Dunbarb25bfde2011-10-11 18:20:10 +00001721 Opts.UseStandardSystemIncludes = !Args.hasArg(OPT_nostdsysteminc);
Douglas Gregor64b046f2010-03-24 20:13:48 +00001722 Opts.UseStandardCXXIncludes = !Args.hasArg(OPT_nostdincxx);
Bob Wilsonb02ea3d2011-06-21 21:12:29 +00001723 if (const Arg *A = Args.getLastArg(OPT_stdlib_EQ))
Richard Smithbd55daf2012-11-01 04:30:05 +00001724 Opts.UseLibcxx = (strcmp(A->getValue(), "libc++") == 0);
Daniel Dunbar37300482010-05-20 16:54:55 +00001725 Opts.ResourceDir = Args.getLastArgValue(OPT_resource_dir);
Adrian Prantl0ebdeac2017-03-14 23:07:49 +00001726
1727 // Canonicalize -fmodules-cache-path before storing it.
1728 SmallString<128> P(Args.getLastArgValue(OPT_fmodules_cache_path));
1729 if (!(P.empty() || llvm::sys::path::is_absolute(P))) {
1730 if (WorkingDir.empty())
1731 llvm::sys::fs::make_absolute(P);
1732 else
1733 llvm::sys::fs::make_absolute(WorkingDir, P);
1734 }
1735 llvm::sys::path::remove_dots(P);
1736 Opts.ModuleCachePath = P.str();
1737
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00001738 Opts.ModuleUserBuildPath = Args.getLastArgValue(OPT_fmodules_user_build_path);
Boris Kolpackovd30446f2017-08-31 06:26:43 +00001739 // Only the -fmodule-file=<name>=<file> form.
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001740 for (const auto *A : Args.filtered(OPT_fmodule_file)) {
Boris Kolpackovd30446f2017-08-31 06:26:43 +00001741 StringRef Val = A->getValue();
1742 if (Val.find('=') != StringRef::npos)
1743 Opts.PrebuiltModuleFiles.insert(Val.split('='));
1744 }
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001745 for (const auto *A : Args.filtered(OPT_fprebuilt_module_path))
Manman Ren11f2a472016-08-18 17:42:15 +00001746 Opts.AddPrebuiltModulePath(A->getValue());
Douglas Gregor1735f4e2011-09-13 23:15:45 +00001747 Opts.DisableModuleHash = Args.hasArg(OPT_fdisable_module_hash);
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00001748 Opts.ModulesHashContent = Args.hasArg(OPT_fmodules_hash_content);
Manman Ren47a44452016-07-26 17:12:17 +00001749 Opts.ModulesValidateDiagnosticOptions =
1750 !Args.hasArg(OPT_fmodules_disable_diagnostic_validation);
Richard Smith47972af2015-06-16 00:08:24 +00001751 Opts.ImplicitModuleMaps = Args.hasArg(OPT_fimplicit_module_maps);
Richard Smith9acb99e32014-12-10 03:09:48 +00001752 Opts.ModuleMapFileHomeIsCwd = Args.hasArg(OPT_fmodule_map_file_home_is_cwd);
Reid Kleckner898229a2013-06-14 17:17:23 +00001753 Opts.ModuleCachePruneInterval =
1754 getLastArgIntValue(Args, OPT_fmodules_prune_interval, 7 * 24 * 60 * 60);
1755 Opts.ModuleCachePruneAfter =
1756 getLastArgIntValue(Args, OPT_fmodules_prune_after, 31 * 24 * 60 * 60);
Dmitri Gribenkof430da42014-02-12 10:33:14 +00001757 Opts.ModulesValidateOncePerBuildSession =
1758 Args.hasArg(OPT_fmodules_validate_once_per_build_session);
1759 Opts.BuildSessionTimestamp =
1760 getLastArgUInt64Value(Args, OPT_fbuild_session_timestamp, 0);
Ben Langmuirdcf73862014-03-12 00:06:17 +00001761 Opts.ModulesValidateSystemHeaders =
1762 Args.hasArg(OPT_fmodules_validate_system_headers);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00001763 if (const Arg *A = Args.getLastArg(OPT_fmodule_format_EQ))
1764 Opts.ModuleFormat = A->getValue();
Ben Langmuirdcf73862014-03-12 00:06:17 +00001765
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001766 for (const auto *A : Args.filtered(OPT_fmodules_ignore_macro)) {
Sean Silva14facf32015-06-09 01:57:17 +00001767 StringRef MacroDef = A->getValue();
Justin Lebar5e83dfe2016-10-21 21:45:01 +00001768 Opts.ModulesIgnoreMacros.insert(
1769 llvm::CachedHashString(MacroDef.split('=').first));
Douglas Gregor5dc38992013-02-07 00:21:12 +00001770 }
1771
Douglas Gregor9f93e382011-07-28 04:45:53 +00001772 // Add -I..., -F..., and -index-header-map options in order.
1773 bool IsIndexHeaderMap = false;
Saleem Abdulrasoolde87e5f2016-05-06 19:13:55 +00001774 bool IsSysrootSpecified =
1775 Args.hasArg(OPT__sysroot_EQ) || Args.hasArg(OPT_isysroot);
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001776 for (const auto *A : Args.filtered(OPT_I, OPT_F, OPT_index_header_map)) {
Sean Silva14facf32015-06-09 01:57:17 +00001777 if (A->getOption().matches(OPT_index_header_map)) {
Douglas Gregor9f93e382011-07-28 04:45:53 +00001778 // -index-header-map applies to the next -I or -F.
1779 IsIndexHeaderMap = true;
1780 continue;
1781 }
Sean Silva14facf32015-06-09 01:57:17 +00001782
1783 frontend::IncludeDirGroup Group =
1784 IsIndexHeaderMap ? frontend::IndexHeaderMap : frontend::Angled;
1785
Saleem Abdulrasoolde87e5f2016-05-06 19:13:55 +00001786 bool IsFramework = A->getOption().matches(OPT_F);
1787 std::string Path = A->getValue();
1788
1789 if (IsSysrootSpecified && !IsFramework && A->getValue()[0] == '=') {
1790 SmallString<32> Buffer;
1791 llvm::sys::path::append(Buffer, Opts.Sysroot,
1792 llvm::StringRef(A->getValue()).substr(1));
1793 Path = Buffer.str();
1794 }
1795
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00001796 Opts.AddPath(Path, Group, IsFramework,
Saleem Abdulrasoolde87e5f2016-05-06 19:13:55 +00001797 /*IgnoreSysroot*/ true);
Douglas Gregor9f93e382011-07-28 04:45:53 +00001798 IsIndexHeaderMap = false;
1799 }
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001800
Daniel Dunbarc9c57e92013-01-25 01:50:34 +00001801 // Add -iprefix/-iwithprefix/-iwithprefixbefore options.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001802 StringRef Prefix = ""; // FIXME: This isn't the correct default prefix.
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001803 for (const auto *A :
Sean Silva14facf32015-06-09 01:57:17 +00001804 Args.filtered(OPT_iprefix, OPT_iwithprefix, OPT_iwithprefixbefore)) {
Daniel Dunbara442fd52010-06-11 22:00:13 +00001805 if (A->getOption().matches(OPT_iprefix))
Richard Smithbd55daf2012-11-01 04:30:05 +00001806 Prefix = A->getValue();
Daniel Dunbara442fd52010-06-11 22:00:13 +00001807 else if (A->getOption().matches(OPT_iwithprefix))
Sean Silva14facf32015-06-09 01:57:17 +00001808 Opts.AddPath(Prefix.str() + A->getValue(), frontend::After, false, true);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001809 else
Sean Silva14facf32015-06-09 01:57:17 +00001810 Opts.AddPath(Prefix.str() + A->getValue(), frontend::Angled, false, true);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001811 }
1812
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001813 for (const auto *A : Args.filtered(OPT_idirafter))
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001814 Opts.AddPath(A->getValue(), frontend::After, false, true);
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001815 for (const auto *A : Args.filtered(OPT_iquote))
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001816 Opts.AddPath(A->getValue(), frontend::Quoted, false, true);
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001817 for (const auto *A : Args.filtered(OPT_isystem, OPT_iwithsysroot))
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001818 Opts.AddPath(A->getValue(), frontend::System, false,
1819 !A->getOption().matches(OPT_iwithsysroot));
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001820 for (const auto *A : Args.filtered(OPT_iframework))
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001821 Opts.AddPath(A->getValue(), frontend::System, true, true);
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001822 for (const auto *A : Args.filtered(OPT_iframeworkwithsysroot))
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001823 Opts.AddPath(A->getValue(), frontend::System, /*IsFramework=*/true,
1824 /*IgnoreSysRoot=*/false);
1825
1826 // Add the paths for the various language specific isystem flags.
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001827 for (const auto *A : Args.filtered(OPT_c_isystem))
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001828 Opts.AddPath(A->getValue(), frontend::CSystem, false, true);
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001829 for (const auto *A : Args.filtered(OPT_cxx_isystem))
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001830 Opts.AddPath(A->getValue(), frontend::CXXSystem, false, true);
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001831 for (const auto *A : Args.filtered(OPT_objc_isystem))
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001832 Opts.AddPath(A->getValue(), frontend::ObjCSystem, false,true);
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001833 for (const auto *A : Args.filtered(OPT_objcxx_isystem))
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001834 Opts.AddPath(A->getValue(), frontend::ObjCXXSystem, false, true);
1835
1836 // Add the internal paths from a driver that detects standard include paths.
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001837 for (const auto *A :
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001838 Args.filtered(OPT_internal_isystem, OPT_internal_externc_isystem)) {
1839 frontend::IncludeDirGroup Group = frontend::System;
1840 if (A->getOption().matches(OPT_internal_externc_isystem))
1841 Group = frontend::ExternCSystem;
1842 Opts.AddPath(A->getValue(), Group, false, true);
1843 }
1844
1845 // Add the path prefixes which are implicitly treated as being system headers.
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001846 for (const auto *A :
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001847 Args.filtered(OPT_system_header_prefix, OPT_no_system_header_prefix))
1848 Opts.AddSystemHeaderPrefix(
1849 A->getValue(), A->getOption().matches(OPT_system_header_prefix));
1850
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001851 for (const auto *A : Args.filtered(OPT_ivfsoverlay))
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001852 Opts.AddVFSOverlayFile(A->getValue());
1853}
1854
1855void CompilerInvocation::setLangDefaults(LangOptions &Opts, InputKind IK,
1856 const llvm::Triple &T,
1857 PreprocessorOptions &PPOpts,
1858 LangStandard::Kind LangStd) {
1859 // Set some properties which depend solely on the input kind; it would be nice
1860 // to move these to the language standard, and have the driver resolve the
1861 // input kind + language standard.
1862 //
1863 // FIXME: Perhaps a better model would be for a single source file to have
1864 // multiple language standards (C / C++ std, ObjC std, OpenCL std, OpenMP std)
1865 // simultaneously active?
1866 if (IK.getLanguage() == InputKind::Asm) {
1867 Opts.AsmPreprocessor = 1;
1868 } else if (IK.isObjectiveC()) {
1869 Opts.ObjC1 = Opts.ObjC2 = 1;
1870 }
1871
1872 if (LangStd == LangStandard::lang_unspecified) {
1873 // Based on the base language, pick one.
1874 switch (IK.getLanguage()) {
1875 case InputKind::Unknown:
1876 case InputKind::LLVM_IR:
1877 llvm_unreachable("Invalid input kind!");
1878 case InputKind::OpenCL:
1879 LangStd = LangStandard::lang_opencl10;
1880 break;
1881 case InputKind::CUDA:
1882 LangStd = LangStandard::lang_cuda;
1883 break;
1884 case InputKind::Asm:
1885 case InputKind::C:
Michal Gorny4289f4c2018-03-06 21:26:28 +00001886#if defined(CLANG_DEFAULT_STD_C)
1887 LangStd = CLANG_DEFAULT_STD_C;
1888#else
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001889 // The PS4 uses C99 as the default C standard.
1890 if (T.isPS4())
1891 LangStd = LangStandard::lang_gnu99;
1892 else
1893 LangStd = LangStandard::lang_gnu11;
Michal Gorny4289f4c2018-03-06 21:26:28 +00001894#endif
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001895 break;
1896 case InputKind::ObjC:
Michal Gorny4289f4c2018-03-06 21:26:28 +00001897#if defined(CLANG_DEFAULT_STD_C)
1898 LangStd = CLANG_DEFAULT_STD_C;
1899#else
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001900 LangStd = LangStandard::lang_gnu11;
Michal Gorny4289f4c2018-03-06 21:26:28 +00001901#endif
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001902 break;
1903 case InputKind::CXX:
1904 case InputKind::ObjCXX:
Michal Gorny4289f4c2018-03-06 21:26:28 +00001905#if defined(CLANG_DEFAULT_STD_CXX)
1906 LangStd = CLANG_DEFAULT_STD_CXX;
1907#else
Tim Northover36bb6d52017-12-09 12:09:54 +00001908 LangStd = LangStandard::lang_gnucxx14;
Michal Gorny4289f4c2018-03-06 21:26:28 +00001909#endif
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001910 break;
1911 case InputKind::RenderScript:
1912 LangStd = LangStandard::lang_c99;
1913 break;
Yaxun Liu887c5692018-04-25 01:10:37 +00001914 case InputKind::HIP:
1915 LangStd = LangStandard::lang_hip;
1916 break;
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001917 }
1918 }
1919
1920 const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
1921 Opts.LineComment = Std.hasLineComments();
1922 Opts.C99 = Std.isC99();
1923 Opts.C11 = Std.isC11();
1924 Opts.C17 = Std.isC17();
1925 Opts.CPlusPlus = Std.isCPlusPlus();
1926 Opts.CPlusPlus11 = Std.isCPlusPlus11();
1927 Opts.CPlusPlus14 = Std.isCPlusPlus14();
1928 Opts.CPlusPlus17 = Std.isCPlusPlus17();
1929 Opts.CPlusPlus2a = Std.isCPlusPlus2a();
1930 Opts.Digraphs = Std.hasDigraphs();
1931 Opts.GNUMode = Std.isGNUMode();
1932 Opts.GNUInline = !Opts.C99 && !Opts.CPlusPlus;
1933 Opts.HexFloats = Std.hasHexFloats();
1934 Opts.ImplicitInt = Std.hasImplicitInt();
1935
1936 // Set OpenCL Version.
1937 Opts.OpenCL = Std.isOpenCL();
1938 if (LangStd == LangStandard::lang_opencl10)
1939 Opts.OpenCLVersion = 100;
1940 else if (LangStd == LangStandard::lang_opencl11)
1941 Opts.OpenCLVersion = 110;
1942 else if (LangStd == LangStandard::lang_opencl12)
1943 Opts.OpenCLVersion = 120;
1944 else if (LangStd == LangStandard::lang_opencl20)
1945 Opts.OpenCLVersion = 200;
Anastasia Stulovac645f612018-04-12 14:17:04 +00001946 else if (LangStd == LangStandard::lang_openclcpp)
1947 Opts.OpenCLCPlusPlusVersion = 100;
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001948
1949 // OpenCL has some additional defaults.
1950 if (Opts.OpenCL) {
1951 Opts.AltiVec = 0;
1952 Opts.ZVector = 0;
1953 Opts.LaxVectorConversions = 0;
1954 Opts.setDefaultFPContractMode(LangOptions::FPC_On);
1955 Opts.NativeHalfType = 1;
1956 Opts.NativeHalfArgsAndReturns = 1;
Sven van Haastregt49ffffb2018-04-23 11:23:47 +00001957 Opts.OpenCLCPlusPlus = Opts.CPlusPlus;
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001958 // Include default header file for OpenCL.
1959 if (Opts.IncludeDefaultHeader) {
1960 PPOpts.Includes.push_back("opencl-c.h");
1961 }
1962 }
1963
Yaxun Liu887c5692018-04-25 01:10:37 +00001964 Opts.HIP = IK.getLanguage() == InputKind::HIP;
1965 Opts.CUDA = IK.getLanguage() == InputKind::CUDA || Opts.HIP;
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001966 if (Opts.CUDA)
1967 // Set default FP_CONTRACT to FAST.
1968 Opts.setDefaultFPContractMode(LangOptions::FPC_Fast);
1969
1970 Opts.RenderScript = IK.getLanguage() == InputKind::RenderScript;
1971 if (Opts.RenderScript) {
1972 Opts.NativeHalfType = 1;
1973 Opts.NativeHalfArgsAndReturns = 1;
1974 }
1975
1976 // OpenCL and C++ both have bool, true, false keywords.
1977 Opts.Bool = Opts.OpenCL || Opts.CPlusPlus;
1978
1979 // OpenCL has half keyword
1980 Opts.Half = Opts.OpenCL;
1981
1982 // C++ has wchar_t keyword.
1983 Opts.WChar = Opts.CPlusPlus;
1984
1985 Opts.GNUKeywords = Opts.GNUMode;
1986 Opts.CXXOperatorNames = Opts.CPlusPlus;
1987
1988 Opts.AlignedAllocation = Opts.CPlusPlus17;
1989
1990 Opts.DollarIdents = !Opts.AsmPreprocessor;
1991}
1992
1993/// Attempt to parse a visibility value out of the given argument.
1994static Visibility parseVisibility(Arg *arg, ArgList &args,
1995 DiagnosticsEngine &diags) {
1996 StringRef value = arg->getValue();
1997 if (value == "default") {
1998 return DefaultVisibility;
1999 } else if (value == "hidden" || value == "internal") {
2000 return HiddenVisibility;
2001 } else if (value == "protected") {
2002 // FIXME: diagnose if target does not support protected visibility
2003 return ProtectedVisibility;
2004 }
2005
2006 diags.Report(diag::err_drv_invalid_value)
2007 << arg->getAsString(args) << value;
2008 return DefaultVisibility;
2009}
2010
2011/// Check if input file kind and language standard are compatible.
2012static bool IsInputCompatibleWithStandard(InputKind IK,
2013 const LangStandard &S) {
2014 switch (IK.getLanguage()) {
2015 case InputKind::Unknown:
2016 case InputKind::LLVM_IR:
2017 llvm_unreachable("should not parse language flags for this input");
2018
2019 case InputKind::C:
2020 case InputKind::ObjC:
2021 case InputKind::RenderScript:
2022 return S.getLanguage() == InputKind::C;
2023
2024 case InputKind::OpenCL:
2025 return S.getLanguage() == InputKind::OpenCL;
2026
2027 case InputKind::CXX:
2028 case InputKind::ObjCXX:
Richard Smithb0fe7042017-04-26 23:44:33 +00002029 return S.getLanguage() == InputKind::CXX;
Richard Smith40c0efa2017-04-26 18:57:40 +00002030
2031 case InputKind::CUDA:
Richard Smithb0fe7042017-04-26 23:44:33 +00002032 // FIXME: What -std= values should be permitted for CUDA compilations?
2033 return S.getLanguage() == InputKind::CUDA ||
2034 S.getLanguage() == InputKind::CXX;
Richard Smith40c0efa2017-04-26 18:57:40 +00002035
Yaxun Liu887c5692018-04-25 01:10:37 +00002036 case InputKind::HIP:
2037 return S.getLanguage() == InputKind::CXX ||
2038 S.getLanguage() == InputKind::HIP;
2039
Richard Smith40c0efa2017-04-26 18:57:40 +00002040 case InputKind::Asm:
2041 // Accept (and ignore) all -std= values.
2042 // FIXME: The -std= value is not ignored; it affects the tokenization
2043 // and preprocessing rules if we're preprocessing this asm input.
Richard Smith222b30b2017-02-14 23:41:38 +00002044 return true;
Richard Smithc91daf12017-02-14 22:44:20 +00002045 }
Richard Smith40c0efa2017-04-26 18:57:40 +00002046
2047 llvm_unreachable("unexpected input language");
Richard Smithc91daf12017-02-14 22:44:20 +00002048}
2049
2050/// Get language name for given input kind.
2051static const StringRef GetInputKindName(InputKind IK) {
Richard Smith40c0efa2017-04-26 18:57:40 +00002052 switch (IK.getLanguage()) {
2053 case InputKind::C:
Richard Smithb0fe7042017-04-26 23:44:33 +00002054 return "C";
Richard Smith40c0efa2017-04-26 18:57:40 +00002055 case InputKind::ObjC:
Richard Smithb0fe7042017-04-26 23:44:33 +00002056 return "Objective-C";
Richard Smith40c0efa2017-04-26 18:57:40 +00002057 case InputKind::CXX:
Richard Smithb0fe7042017-04-26 23:44:33 +00002058 return "C++";
Richard Smith40c0efa2017-04-26 18:57:40 +00002059 case InputKind::ObjCXX:
Richard Smithb0fe7042017-04-26 23:44:33 +00002060 return "Objective-C++";
Richard Smith40c0efa2017-04-26 18:57:40 +00002061 case InputKind::OpenCL:
Richard Smithc91daf12017-02-14 22:44:20 +00002062 return "OpenCL";
Richard Smith40c0efa2017-04-26 18:57:40 +00002063 case InputKind::CUDA:
Richard Smithc91daf12017-02-14 22:44:20 +00002064 return "CUDA";
Richard Smithb0fe7042017-04-26 23:44:33 +00002065 case InputKind::RenderScript:
2066 return "RenderScript";
Yaxun Liu887c5692018-04-25 01:10:37 +00002067 case InputKind::HIP:
2068 return "HIP";
Richard Smithb0fe7042017-04-26 23:44:33 +00002069
2070 case InputKind::Asm:
2071 return "Asm";
2072 case InputKind::LLVM_IR:
2073 return "LLVM IR";
2074
2075 case InputKind::Unknown:
2076 break;
Richard Smithc91daf12017-02-14 22:44:20 +00002077 }
Richard Smithb0fe7042017-04-26 23:44:33 +00002078 llvm_unreachable("unknown input language");
Richard Smithc91daf12017-02-14 22:44:20 +00002079}
2080
Peter Collingbourneaaeb73b2010-12-04 01:50:27 +00002081static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK,
Samuel Antao45bfe4c2016-02-08 15:59:20 +00002082 const TargetOptions &TargetOpts,
Yaxun Liu143f0832016-06-20 19:26:00 +00002083 PreprocessorOptions &PPOpts,
David Blaikie9c902b52011-09-25 23:23:43 +00002084 DiagnosticsEngine &Diags) {
Peter Collingbourneaaeb73b2010-12-04 01:50:27 +00002085 // FIXME: Cleanup per-file based stuff.
2086 LangStandard::Kind LangStd = LangStandard::lang_unspecified;
2087 if (const Arg *A = Args.getLastArg(OPT_std_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00002088 LangStd = llvm::StringSwitch<LangStandard::Kind>(A->getValue())
Richard Smithb0fe7042017-04-26 23:44:33 +00002089#define LANGSTANDARD(id, name, lang, desc, features) \
Peter Collingbourneaaeb73b2010-12-04 01:50:27 +00002090 .Case(name, LangStandard::lang_##id)
Yaxun Liub5044fe2016-06-17 17:19:28 +00002091#define LANGSTANDARD_ALIAS(id, alias) \
2092 .Case(alias, LangStandard::lang_##id)
Peter Collingbourneaaeb73b2010-12-04 01:50:27 +00002093#include "clang/Frontend/LangStandards.def"
2094 .Default(LangStandard::lang_unspecified);
Richard Smithc91daf12017-02-14 22:44:20 +00002095 if (LangStd == LangStandard::lang_unspecified) {
Peter Collingbourneaaeb73b2010-12-04 01:50:27 +00002096 Diags.Report(diag::err_drv_invalid_value)
Richard Smithbd55daf2012-11-01 04:30:05 +00002097 << A->getAsString(Args) << A->getValue();
Richard Smithc91daf12017-02-14 22:44:20 +00002098 // Report supported standards with short description.
2099 for (unsigned KindValue = 0;
2100 KindValue != LangStandard::lang_unspecified;
2101 ++KindValue) {
2102 const LangStandard &Std = LangStandard::getLangStandardForKind(
2103 static_cast<LangStandard::Kind>(KindValue));
2104 if (IsInputCompatibleWithStandard(IK, Std)) {
Richard Smith8c8fb802017-04-27 01:17:05 +00002105 auto Diag = Diags.Report(diag::note_drv_use_standard);
2106 Diag << Std.getName() << Std.getDescription();
2107 unsigned NumAliases = 0;
2108#define LANGSTANDARD(id, name, lang, desc, features)
2109#define LANGSTANDARD_ALIAS(id, alias) \
2110 if (KindValue == LangStandard::lang_##id) ++NumAliases;
2111#define LANGSTANDARD_ALIAS_DEPR(id, alias)
2112#include "clang/Frontend/LangStandards.def"
2113 Diag << NumAliases;
2114#define LANGSTANDARD(id, name, lang, desc, features)
2115#define LANGSTANDARD_ALIAS(id, alias) \
2116 if (KindValue == LangStandard::lang_##id) Diag << alias;
2117#define LANGSTANDARD_ALIAS_DEPR(id, alias)
2118#include "clang/Frontend/LangStandards.def"
Richard Smithc91daf12017-02-14 22:44:20 +00002119 }
2120 }
2121 } else {
Alp Tokerf6a24ce2013-12-05 16:25:25 +00002122 // Valid standard, check to make sure language and standard are
2123 // compatible.
Chad Rosier24874a42011-05-02 19:24:53 +00002124 const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
Richard Smithc91daf12017-02-14 22:44:20 +00002125 if (!IsInputCompatibleWithStandard(IK, Std)) {
2126 Diags.Report(diag::err_drv_argument_not_allowed_with)
2127 << A->getAsString(Args) << GetInputKindName(IK);
Chad Rosier24874a42011-05-02 19:24:53 +00002128 }
2129 }
Peter Collingbourneaaeb73b2010-12-04 01:50:27 +00002130 }
2131
Oren Ben Simhon220671a2018-03-17 13:31:35 +00002132 if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
2133 StringRef Name = A->getValue();
2134 if (Name == "full" || Name == "branch") {
2135 Opts.CFProtectionBranch = 1;
2136 }
2137 }
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00002138 // -cl-std only applies for OpenCL language standards.
2139 // Override the -std option in this case.
Peter Collingbournefafa6652010-12-04 01:51:40 +00002140 if (const Arg *A = Args.getLastArg(OPT_cl_std_EQ)) {
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00002141 LangStandard::Kind OpenCLLangStd
Richard Smithc91daf12017-02-14 22:44:20 +00002142 = llvm::StringSwitch<LangStandard::Kind>(A->getValue())
Richard Smith8c8fb802017-04-27 01:17:05 +00002143 .Cases("cl", "CL", LangStandard::lang_opencl10)
Richard Smithc91daf12017-02-14 22:44:20 +00002144 .Cases("cl1.1", "CL1.1", LangStandard::lang_opencl11)
2145 .Cases("cl1.2", "CL1.2", LangStandard::lang_opencl12)
2146 .Cases("cl2.0", "CL2.0", LangStandard::lang_opencl20)
Anastasia Stulovac645f612018-04-12 14:17:04 +00002147 .Case("c++", LangStandard::lang_openclcpp)
Richard Smithc91daf12017-02-14 22:44:20 +00002148 .Default(LangStandard::lang_unspecified);
Douglas Katzman31fdbfe2015-08-05 15:08:53 +00002149
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00002150 if (OpenCLLangStd == LangStandard::lang_unspecified) {
Peter Collingbournefafa6652010-12-04 01:51:40 +00002151 Diags.Report(diag::err_drv_invalid_value)
Richard Smithc91daf12017-02-14 22:44:20 +00002152 << A->getAsString(Args) << A->getValue();
Peter Collingbournefafa6652010-12-04 01:51:40 +00002153 }
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00002154 else
2155 LangStd = OpenCLLangStd;
Peter Collingbournefafa6652010-12-04 01:51:40 +00002156 }
Douglas Katzman31fdbfe2015-08-05 15:08:53 +00002157
Yaxun Liu143f0832016-06-20 19:26:00 +00002158 Opts.IncludeDefaultHeader = Args.hasArg(OPT_finclude_default_header);
2159
Sunil Srivastavabf010802016-04-27 19:53:03 +00002160 llvm::Triple T(TargetOpts.Triple);
Yaxun Liu143f0832016-06-20 19:26:00 +00002161 CompilerInvocation::setLangDefaults(Opts, IK, T, PPOpts, LangStd);
Peter Collingbourneaaeb73b2010-12-04 01:50:27 +00002162
Yaxun Liu02c39792016-07-13 21:21:05 +00002163 // -cl-strict-aliasing needs to emit diagnostic in the case where CL > 1.0.
2164 // This option should be deprecated for CL > 1.0 because
2165 // this option was added for compatibility with OpenCL 1.0.
2166 if (Args.getLastArg(OPT_cl_strict_aliasing)
2167 && Opts.OpenCLVersion > 100) {
Yaxun Liu02c39792016-07-13 21:21:05 +00002168 Diags.Report(diag::warn_option_invalid_ocl_version)
Sven van Haastregt35b61392018-05-08 13:47:43 +00002169 << Opts.getOpenCLVersionTuple().getAsString()
2170 << Args.getLastArg(OPT_cl_strict_aliasing)->getAsString(Args);
Yaxun Liu02c39792016-07-13 21:21:05 +00002171 }
2172
Chandler Carruthe03aa552010-04-17 20:17:31 +00002173 // We abuse '-f[no-]gnu-keywords' to force overriding all GNU-extension
2174 // keywords. This behavior is provided by GCC's poorly named '-fasm' flag,
2175 // while a subset (the non-C++ GNU keywords) is provided by GCC's
2176 // '-fgnu-keywords'. Clang conflates the two for simplicity under the single
2177 // name, as it doesn't seem a useful distinction.
2178 Opts.GNUKeywords = Args.hasFlag(OPT_fgnu_keywords, OPT_fno_gnu_keywords,
Peter Collingbourneaaeb73b2010-12-04 01:50:27 +00002179 Opts.GNUKeywords);
Chandler Carruthe03aa552010-04-17 20:17:31 +00002180
Jacob Bandes-Storch33f3e632018-07-17 04:56:22 +00002181 Opts.Digraphs = Args.hasFlag(OPT_fdigraphs, OPT_fno_digraphs, Opts.Digraphs);
2182
Erich Keaned46083c2017-05-25 16:24:49 +00002183 if (Args.hasArg(OPT_fno_operator_names))
Peter Collingbourneaaeb73b2010-12-04 01:50:27 +00002184 Opts.CXXOperatorNames = 0;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002185
Reid Klecknerbbc01782014-12-03 21:53:36 +00002186 if (Args.hasArg(OPT_fcuda_is_device))
2187 Opts.CUDAIsDevice = 1;
2188
Justin Lebar1eac5942016-01-26 17:47:20 +00002189 if (Args.hasArg(OPT_fcuda_allow_variadic_functions))
2190 Opts.CUDAAllowVariadicFunctions = 1;
2191
Justin Lebarba122ab2016-03-30 23:30:21 +00002192 if (Args.hasArg(OPT_fno_cuda_host_device_constexpr))
2193 Opts.CUDAHostDeviceConstexpr = 0;
2194
Justin Lebar91f6f072016-05-23 20:19:56 +00002195 if (Opts.CUDAIsDevice && Args.hasArg(OPT_fcuda_approx_transcendentals))
2196 Opts.CUDADeviceApproxTranscendentals = 1;
2197
Jonas Hahnfeld5379c6d2018-02-12 10:46:45 +00002198 Opts.CUDARelocatableDeviceCode = Args.hasArg(OPT_fcuda_rdc);
2199
John McCall31168b02011-06-15 23:02:42 +00002200 if (Opts.ObjC1) {
John McCall5fb5df92012-06-20 06:18:46 +00002201 if (Arg *arg = Args.getLastArg(OPT_fobjc_runtime_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00002202 StringRef value = arg->getValue();
John McCall5fb5df92012-06-20 06:18:46 +00002203 if (Opts.ObjCRuntime.tryParse(value))
2204 Diags.Report(diag::err_drv_unknown_objc_runtime) << value;
2205 }
2206
John McCall31168b02011-06-15 23:02:42 +00002207 if (Args.hasArg(OPT_fobjc_gc_only))
Douglas Gregor79a91412011-09-13 17:21:33 +00002208 Opts.setGC(LangOptions::GCOnly);
John McCall31168b02011-06-15 23:02:42 +00002209 else if (Args.hasArg(OPT_fobjc_gc))
Douglas Gregor79a91412011-09-13 17:21:33 +00002210 Opts.setGC(LangOptions::HybridGC);
John McCall31168b02011-06-15 23:02:42 +00002211 else if (Args.hasArg(OPT_fobjc_arc)) {
2212 Opts.ObjCAutoRefCount = 1;
John McCall3deb1ad2012-08-21 02:47:43 +00002213 if (!Opts.ObjCRuntime.allowsARC())
2214 Diags.Report(diag::err_arc_unsupported_on_runtime);
John McCall460ce582015-10-22 18:38:17 +00002215 }
John McCall31168b02011-06-15 23:02:42 +00002216
John McCall460ce582015-10-22 18:38:17 +00002217 // ObjCWeakRuntime tracks whether the runtime supports __weak, not
2218 // whether the feature is actually enabled. This is predominantly
2219 // determined by -fobjc-runtime, but we allow it to be overridden
2220 // from the command line for testing purposes.
2221 if (Args.hasArg(OPT_fobjc_runtime_has_weak))
2222 Opts.ObjCWeakRuntime = 1;
2223 else
2224 Opts.ObjCWeakRuntime = Opts.ObjCRuntime.allowsWeak();
2225
2226 // ObjCWeak determines whether __weak is actually enabled.
John McCallfbe5ed72015-11-05 19:19:56 +00002227 // Note that we allow -fno-objc-weak to disable this even in ARC mode.
2228 if (auto weakArg = Args.getLastArg(OPT_fobjc_weak, OPT_fno_objc_weak)) {
2229 if (!weakArg->getOption().matches(OPT_fobjc_weak)) {
2230 assert(!Opts.ObjCWeak);
2231 } else if (Opts.getGC() != LangOptions::NonGC) {
John McCall460ce582015-10-22 18:38:17 +00002232 Diags.Report(diag::err_objc_weak_with_gc);
John McCallfbe5ed72015-11-05 19:19:56 +00002233 } else if (!Opts.ObjCWeakRuntime) {
John McCall460ce582015-10-22 18:38:17 +00002234 Diags.Report(diag::err_objc_weak_unsupported);
John McCallfbe5ed72015-11-05 19:19:56 +00002235 } else {
2236 Opts.ObjCWeak = 1;
John McCall460ce582015-10-22 18:38:17 +00002237 }
John McCallfbe5ed72015-11-05 19:19:56 +00002238 } else if (Opts.ObjCAutoRefCount) {
2239 Opts.ObjCWeak = Opts.ObjCWeakRuntime;
John McCall3deb1ad2012-08-21 02:47:43 +00002240 }
John McCall24fc0de2011-07-06 00:26:06 +00002241
John McCall31168b02011-06-15 23:02:42 +00002242 if (Args.hasArg(OPT_fno_objc_infer_related_result_type))
2243 Opts.ObjCInferRelatedResultType = 0;
Douglas Katzman31fdbfe2015-08-05 15:08:53 +00002244
Fariborz Jahaniane1e33f82013-11-01 21:58:17 +00002245 if (Args.hasArg(OPT_fobjc_subscripting_legacy_runtime))
2246 Opts.ObjCSubscriptingLegacyRuntime =
2247 (Opts.ObjCRuntime.getKind() == ObjCRuntime::FragileMacOSX);
John McCall31168b02011-06-15 23:02:42 +00002248 }
Douglas Katzman31fdbfe2015-08-05 15:08:53 +00002249
Peter Collingbourne470d9422015-05-13 22:07:22 +00002250 if (Args.hasArg(OPT_fgnu89_inline)) {
2251 if (Opts.CPlusPlus)
Richard Smithc91daf12017-02-14 22:44:20 +00002252 Diags.Report(diag::err_drv_argument_not_allowed_with)
2253 << "-fgnu89-inline" << GetInputKindName(IK);
Peter Collingbourne470d9422015-05-13 22:07:22 +00002254 else
2255 Opts.GNUInline = 1;
2256 }
Rafael Espindolafb2af642011-06-02 16:13:27 +00002257
Fariborz Jahanianf7f04452011-02-04 00:01:24 +00002258 if (Args.hasArg(OPT_fapple_kext)) {
2259 if (!Opts.CPlusPlus)
2260 Diags.Report(diag::warn_c_kext);
2261 else
2262 Opts.AppleKext = 1;
2263 }
2264
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002265 if (Args.hasArg(OPT_print_ivar_layout))
2266 Opts.ObjCGCBitmapPrint = 1;
Fariborz Jahanian63408e82010-04-22 20:26:39 +00002267 if (Args.hasArg(OPT_fno_constant_cfstrings))
2268 Opts.NoConstantCFStrings = 1;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002269
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00002270 if (Args.hasArg(OPT_fzvector))
2271 Opts.ZVector = 1;
2272
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002273 if (Args.hasArg(OPT_pthread))
2274 Opts.POSIXThreads = 1;
2275
John McCallb4a99d32013-02-19 01:57:35 +00002276 // The value-visibility mode defaults to "default".
2277 if (Arg *visOpt = Args.getLastArg(OPT_fvisibility)) {
2278 Opts.setValueVisibilityMode(parseVisibility(visOpt, Args, Diags));
2279 } else {
2280 Opts.setValueVisibilityMode(DefaultVisibility);
2281 }
2282
2283 // The type-visibility mode defaults to the value-visibility mode.
2284 if (Arg *typeVisOpt = Args.getLastArg(OPT_ftype_visibility)) {
2285 Opts.setTypeVisibilityMode(parseVisibility(typeVisOpt, Args, Diags));
2286 } else {
2287 Opts.setTypeVisibilityMode(Opts.getValueVisibilityMode());
2288 }
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002289
Douglas Gregor08329632010-06-15 17:05:35 +00002290 if (Args.hasArg(OPT_fvisibility_inlines_hidden))
2291 Opts.InlineVisibilityHidden = 1;
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002292
David Chisnalldd84ef12010-09-17 18:29:54 +00002293 if (Args.hasArg(OPT_ftrapv)) {
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002294 Opts.setSignedOverflowBehavior(LangOptions::SOB_Trapping);
David Chisnalldd84ef12010-09-17 18:29:54 +00002295 // Set the handler, if one is specified.
2296 Opts.OverflowHandler =
2297 Args.getLastArgValue(OPT_ftrapv_handler);
2298 }
Chris Lattner51924e512010-06-26 21:25:03 +00002299 else if (Args.hasArg(OPT_fwrapv))
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002300 Opts.setSignedOverflowBehavior(LangOptions::SOB_Defined);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002301
Nico Weberb62ba512014-12-22 18:35:03 +00002302 Opts.MSVCCompat = Args.hasArg(OPT_fms_compatibility);
2303 Opts.MicrosoftExt = Opts.MSVCCompat || Args.hasArg(OPT_fms_extensions);
2304 Opts.AsmBlocks = Args.hasArg(OPT_fasm_blocks) || Opts.MicrosoftExt;
David Majnemerc371ff02015-03-22 08:39:22 +00002305 Opts.MSCompatibilityVersion = 0;
2306 if (const Arg *A = Args.getLastArg(OPT_fms_compatibility_version)) {
2307 VersionTuple VT;
2308 if (VT.tryParse(A->getValue()))
2309 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
2310 << A->getValue();
2311 Opts.MSCompatibilityVersion = VT.getMajor() * 10000000 +
2312 VT.getMinor().getValueOr(0) * 100000 +
2313 VT.getSubminor().getValueOr(0);
2314 }
Nico Weberb62ba512014-12-22 18:35:03 +00002315
2316 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
2317 // is specified, or -std is set to a conforming mode.
2318 // Trigraphs are disabled by default in c++1z onwards.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00002319 Opts.Trigraphs = !Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus17;
Nico Weber00721502014-12-23 22:32:37 +00002320 Opts.Trigraphs =
2321 Args.hasFlag(OPT_ftrigraphs, OPT_fno_trigraphs, Opts.Trigraphs);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002322
Daniel Dunbar15cef0e2009-12-16 20:10:18 +00002323 Opts.DollarIdents = Args.hasFlag(OPT_fdollars_in_identifiers,
2324 OPT_fno_dollars_in_identifiers,
Peter Collingbourneaaeb73b2010-12-04 01:50:27 +00002325 Opts.DollarIdents);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002326 Opts.PascalStrings = Args.hasArg(OPT_fpascal_strings);
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00002327 Opts.VtorDispMode = getLastArgIntValue(Args, OPT_vtordisp_mode_EQ, 1, Diags);
Dawn Perchik68bb1b42010-09-02 23:59:25 +00002328 Opts.Borland = Args.hasArg(OPT_fborland_extensions);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002329 Opts.WritableStrings = Args.hasArg(OPT_fwritable_strings);
Chandler Carruthb009b142011-04-23 06:30:43 +00002330 Opts.ConstStrings = Args.hasFlag(OPT_fconst_strings, OPT_fno_const_strings,
2331 Opts.ConstStrings);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002332 if (Args.hasArg(OPT_fno_lax_vector_conversions))
Anders Carlssonfcd764a2010-02-06 23:23:06 +00002333 Opts.LaxVectorConversions = 0;
2334 if (Args.hasArg(OPT_fno_threadsafe_statics))
Anders Carlsson5d40c6f2010-02-11 08:02:13 +00002335 Opts.ThreadsafeStatics = 0;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002336 Opts.Exceptions = Args.hasArg(OPT_fexceptions);
Anders Carlsson3320e152011-02-22 01:52:06 +00002337 Opts.ObjCExceptions = Args.hasArg(OPT_fobjc_exceptions);
Anders Carlsson33e56a02011-02-23 03:16:42 +00002338 Opts.CXXExceptions = Args.hasArg(OPT_fcxx_exceptions);
Martell Malonec950c652017-11-29 07:25:12 +00002339
Leonard Chanf921d852018-06-04 16:07:52 +00002340 // -ffixed-point
2341 Opts.FixedPoint =
2342 Args.hasFlag(OPT_ffixed_point, OPT_fno_fixed_point, /*Default=*/false) &&
2343 !Opts.CPlusPlus;
Leonard Chan6e16c602018-06-29 17:08:19 +00002344 Opts.PaddingOnUnsignedFixedPoint =
2345 Args.hasFlag(OPT_fpadding_on_unsigned_fixed_point,
2346 OPT_fno_padding_on_unsigned_fixed_point,
Leonard Chandb01c3a2018-06-20 17:19:40 +00002347 /*Default=*/false) &&
2348 Opts.FixedPoint;
Leonard Chanf921d852018-06-04 16:07:52 +00002349
Martell Malonec950c652017-11-29 07:25:12 +00002350 // Handle exception personalities
2351 Arg *A = Args.getLastArg(options::OPT_fsjlj_exceptions,
2352 options::OPT_fseh_exceptions,
2353 options::OPT_fdwarf_exceptions);
2354 if (A) {
2355 const Option &Opt = A->getOption();
Shoaib Meenaid8d15472018-06-07 22:54:54 +00002356 llvm::Triple T(TargetOpts.Triple);
2357 if (T.isWindowsMSVCEnvironment())
2358 Diags.Report(diag::err_fe_invalid_exception_model)
2359 << Opt.getName() << T.str();
2360
Martell Malonec950c652017-11-29 07:25:12 +00002361 Opts.SjLjExceptions = Opt.matches(options::OPT_fsjlj_exceptions);
2362 Opts.SEHExceptions = Opt.matches(options::OPT_fseh_exceptions);
2363 Opts.DWARFExceptions = Opt.matches(options::OPT_fdwarf_exceptions);
2364 }
2365
David Majnemer960813e2016-02-20 09:23:47 +00002366 Opts.ExternCNoUnwind = Args.hasArg(OPT_fexternc_nounwind);
Daniel Dunbar1057f862011-03-18 21:23:38 +00002367 Opts.TraditionalCPP = Args.hasArg(OPT_traditional_cpp);
Anders Carlsson33e56a02011-02-23 03:16:42 +00002368
Yunzhong Gaobacf7e42016-01-26 20:15:02 +00002369 Opts.RTTI = Opts.CPlusPlus && !Args.hasArg(OPT_fno_rtti);
David Majnemerf6072342014-07-01 22:24:56 +00002370 Opts.RTTIData = Opts.RTTI && !Args.hasArg(OPT_fno_rtti_data);
Yaxun Liu18e3fd32016-06-14 21:43:01 +00002371 Opts.Blocks = Args.hasArg(OPT_fblocks) || (Opts.OpenCL
Anastasia Stulovac645f612018-04-12 14:17:04 +00002372 && Opts.OpenCLVersion == 200);
John McCall7959fee2011-09-09 20:41:01 +00002373 Opts.BlocksRuntimeOptional = Args.hasArg(OPT_fblocks_runtime_optional);
Gor Nishanov4ffb4342016-10-02 03:31:58 +00002374 Opts.CoroutinesTS = Args.hasArg(OPT_fcoroutines_ts);
Aaron Ballman29dc5de2017-12-07 23:04:11 +00002375
Aaron Ballman606093a2017-10-15 15:01:42 +00002376 // Enable [[]] attributes in C++11 by default.
2377 Opts.DoubleSquareBracketAttributes =
2378 Args.hasFlag(OPT_fdouble_square_bracket_attributes,
2379 OPT_fno_double_square_bracket_attributes, Opts.CPlusPlus11);
2380
Richard Smithc7bf3802016-07-23 02:32:21 +00002381 Opts.ModulesTS = Args.hasArg(OPT_fmodules_ts);
2382 Opts.Modules = Args.hasArg(OPT_fmodules) || Opts.ModulesTS;
Daniel Jasper962b38e2014-04-11 11:47:45 +00002383 Opts.ModulesStrictDeclUse = Args.hasArg(OPT_fmodules_strict_decluse);
2384 Opts.ModulesDeclUse =
2385 Args.hasArg(OPT_fmodules_decluse) || Opts.ModulesStrictDeclUse;
Richard Smithee977932015-05-01 21:22:17 +00002386 Opts.ModulesLocalVisibility =
Richard Smithc7bf3802016-07-23 02:32:21 +00002387 Args.hasArg(OPT_fmodules_local_submodule_visibility) || Opts.ModulesTS;
David Blaikief63556d2017-04-12 20:58:33 +00002388 Opts.ModulesCodegen = Args.hasArg(OPT_fmodules_codegen);
2389 Opts.ModulesDebugInfo = Args.hasArg(OPT_fmodules_debuginfo);
John Thompson2255f2c2014-04-23 12:57:01 +00002390 Opts.ModulesSearchAll = Opts.Modules &&
2391 !Args.hasArg(OPT_fno_modules_search_all) &&
2392 Args.hasArg(OPT_fmodules_search_all);
Richard Smith3d23c422014-05-07 02:25:43 +00002393 Opts.ModulesErrorRecovery = !Args.hasArg(OPT_fno_modules_error_recovery);
Manuel Klimekd2e8b042015-02-20 11:44:41 +00002394 Opts.ImplicitModules = !Args.hasArg(OPT_fno_implicit_modules);
David Tweed2da64382013-09-09 09:17:24 +00002395 Opts.CharIsSigned = Opts.OpenCL || !Args.hasArg(OPT_fno_signed_char);
Abramo Bagnara73bf7f52012-09-05 17:30:57 +00002396 Opts.WChar = Opts.CPlusPlus && !Args.hasArg(OPT_fno_wchar);
Richard Smith3a8244d2018-05-01 05:02:45 +00002397 Opts.Char8 = Args.hasArg(OPT_fchar8__t);
Saleem Abdulrasool729379a2017-10-06 23:09:55 +00002398 if (const Arg *A = Args.getLastArg(OPT_fwchar_type_EQ)) {
2399 Opts.WCharSize = llvm::StringSwitch<unsigned>(A->getValue())
2400 .Case("char", 1)
2401 .Case("short", 2)
2402 .Case("int", 4)
2403 .Default(0);
2404 if (Opts.WCharSize == 0)
2405 Diags.Report(diag::err_fe_invalid_wchar_type) << A->getValue();
2406 }
2407 Opts.WCharIsSigned = Args.hasFlag(OPT_fsigned_wchar, OPT_fno_signed_wchar, true);
Argyrios Kyrtzidis74825bc2010-10-08 00:25:19 +00002408 Opts.ShortEnums = Args.hasArg(OPT_fshort_enums);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002409 Opts.Freestanding = Args.hasArg(OPT_ffreestanding);
2410 Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding;
Chad Rosier7dbc9cf2016-01-06 14:35:46 +00002411 if (!Opts.NoBuiltin)
2412 getAllNoBuiltinFuncValues(Args, Opts.NoBuiltinFuncs);
Eli Benderskyaefa5e22013-07-23 00:13:01 +00002413 Opts.NoMathBuiltin = Args.hasArg(OPT_fno_math_builtin);
Richard Smith26b86ea2016-12-31 21:41:23 +00002414 Opts.RelaxedTemplateTemplateArgs =
2415 Args.hasArg(OPT_frelaxed_template_template_args);
Reid Kleckner7ffc3fb2015-03-20 00:31:07 +00002416 Opts.SizedDeallocation = Args.hasArg(OPT_fsized_deallocation);
Richard Smith59139022016-09-30 22:41:36 +00002417 Opts.AlignedAllocation =
2418 Args.hasFlag(OPT_faligned_allocation, OPT_fno_aligned_allocation,
2419 Opts.AlignedAllocation);
Akira Hatanakacae83f72017-06-29 18:48:40 +00002420 Opts.AlignedAllocationUnavailable =
2421 Opts.AlignedAllocation && Args.hasArg(OPT_aligned_alloc_unavailable);
Richard Smith59139022016-09-30 22:41:36 +00002422 Opts.NewAlignOverride =
2423 getLastArgIntValue(Args, OPT_fnew_alignment_EQ, 0, Diags);
2424 if (Opts.NewAlignOverride && !llvm::isPowerOf2_32(Opts.NewAlignOverride)) {
2425 Arg *A = Args.getLastArg(OPT_fnew_alignment_EQ);
2426 Diags.Report(diag::err_fe_invalid_alignment) << A->getAsString(Args)
2427 << A->getValue();
2428 Opts.NewAlignOverride = 0;
2429 }
Faisal Vali24d59d12015-05-22 01:11:10 +00002430 Opts.ConceptsTS = Args.hasArg(OPT_fconcepts_ts);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002431 Opts.HeinousExtensions = Args.hasArg(OPT_fheinous_gnu_extensions);
John McCall3155f572010-04-09 19:03:51 +00002432 Opts.AccessControl = !Args.hasArg(OPT_fno_access_control);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002433 Opts.ElideConstructors = !Args.hasArg(OPT_fno_elide_constructors);
David Tweed2da64382013-09-09 09:17:24 +00002434 Opts.MathErrno = !Opts.OpenCL && Args.hasArg(OPT_fmath_errno);
Reid Kleckner898229a2013-06-14 17:17:23 +00002435 Opts.InstantiationDepth =
Richard Smithe55b4732016-08-17 21:41:45 +00002436 getLastArgIntValue(Args, OPT_ftemplate_depth, 1024, Diags);
Richard Smith79c927b2013-11-06 19:31:51 +00002437 Opts.ArrowDepth =
2438 getLastArgIntValue(Args, OPT_foperator_arrow_depth, 256, Diags);
Reid Kleckner898229a2013-06-14 17:17:23 +00002439 Opts.ConstexprCallDepth =
2440 getLastArgIntValue(Args, OPT_fconstexpr_depth, 512, Diags);
2441 Opts.ConstexprStepLimit =
2442 getLastArgIntValue(Args, OPT_fconstexpr_steps, 1048576, Diags);
2443 Opts.BracketDepth = getLastArgIntValue(Args, OPT_fbracket_depth, 256, Diags);
Francois Pichet1c229c02011-04-22 22:18:13 +00002444 Opts.DelayedTemplateParsing = Args.hasArg(OPT_fdelayed_template_parsing);
Reid Kleckner898229a2013-06-14 17:17:23 +00002445 Opts.NumLargeByValueCopy =
2446 getLastArgIntValue(Args, OPT_Wlarge_by_value_copy_EQ, 0, Diags);
Douglas Gregordbe39272011-02-01 15:15:22 +00002447 Opts.MSBitfields = Args.hasArg(OPT_mms_bitfields);
Daniel Dunbar37300482010-05-20 16:54:55 +00002448 Opts.ObjCConstantStringClass =
2449 Args.getLastArgValue(OPT_fconstant_string_class);
Ted Kremenek1d56c9e2010-12-23 21:35:43 +00002450 Opts.ObjCDefaultSynthProperties =
Rafael Espindolaea1ba0a2013-09-27 20:21:48 +00002451 !Args.hasArg(OPT_disable_objc_default_synthesize_properties);
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00002452 Opts.EncodeExtendedBlockSig =
2453 Args.hasArg(OPT_fencode_extended_block_signature);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002454 Opts.EmitAllDecls = Args.hasArg(OPT_femit_all_decls);
Reid Kleckner898229a2013-06-14 17:17:23 +00002455 Opts.PackStruct = getLastArgIntValue(Args, OPT_fpack_struct_EQ, 0, Diags);
Fariborz Jahanianbcd82af2014-08-05 18:37:48 +00002456 Opts.MaxTypeAlign = getLastArgIntValue(Args, OPT_fmax_type_align_EQ, 0, Diags);
Reid Kleckner8195f692016-05-04 02:58:24 +00002457 Opts.AlignDouble = Args.hasArg(OPT_malign_double);
Reid Kleckner898229a2013-06-14 17:17:23 +00002458 Opts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
Rafael Espindolac9d336e2016-06-23 15:07:32 +00002459 Opts.PIE = Args.hasArg(OPT_pic_is_pie);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002460 Opts.Static = Args.hasArg(OPT_static_define);
Douglas Gregore9fc3772012-01-26 07:55:45 +00002461 Opts.DumpRecordLayoutsSimple = Args.hasArg(OPT_fdump_record_layouts_simple);
Douglas Katzman31fdbfe2015-08-05 15:08:53 +00002462 Opts.DumpRecordLayouts = Opts.DumpRecordLayoutsSimple
Douglas Gregore9fc3772012-01-26 07:55:45 +00002463 || Args.hasArg(OPT_fdump_record_layouts);
Anders Carlsson11e51402010-04-17 20:15:18 +00002464 Opts.DumpVTableLayouts = Args.hasArg(OPT_fdump_vtable_layouts);
Douglas Gregor8ed0c0b2010-07-09 17:35:33 +00002465 Opts.SpellChecking = !Args.hasArg(OPT_fno_spell_checking);
Daniel Dunbar9302f602010-04-15 15:06:22 +00002466 Opts.NoBitFieldTypeAlign = Args.hasArg(OPT_fno_bitfield_type_align);
Peter Collingbourne0b69e1a2010-12-04 01:50:56 +00002467 Opts.SinglePrecisionConstants = Args.hasArg(OPT_cl_single_precision_constant);
Peter Collingbourne61d6a752010-12-04 01:51:23 +00002468 Opts.FastRelaxedMath = Args.hasArg(OPT_cl_fast_relaxed_math);
Tony Linthicum76329bf2011-12-12 21:14:55 +00002469 Opts.HexagonQdsp6Compat = Args.hasArg(OPT_mqdsp6_compat);
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00002470 Opts.FakeAddressSpaceMap = Args.hasArg(OPT_ffake_address_space_map);
John McCall39439732011-04-09 22:50:59 +00002471 Opts.ParseUnknownAnytype = Args.hasArg(OPT_funknown_anytype);
John McCall3f4138c2011-07-13 17:56:40 +00002472 Opts.DebuggerSupport = Args.hasArg(OPT_fdebugger_support);
Sean Callanan1ce3a6b2012-02-04 01:29:37 +00002473 Opts.DebuggerCastResultToId = Args.hasArg(OPT_fdebugger_cast_result_to_id);
Ted Kremenekf7639e12012-03-06 20:06:33 +00002474 Opts.DebuggerObjCLiteral = Args.hasArg(OPT_fdebugger_objc_literal);
Eli Friedman055c9702011-11-02 01:53:16 +00002475 Opts.ApplePragmaPack = Args.hasArg(OPT_fapple_pragma_pack);
Bruno Cardoso Lopes970b2812018-03-20 22:36:39 +00002476 Opts.ModuleName = Args.getLastArgValue(OPT_fmodule_name_EQ);
2477 Opts.CurrentModule = Opts.ModuleName;
Bob Wilsonb111ec92015-03-02 19:01:14 +00002478 Opts.AppExt = Args.hasArg(OPT_fapplication_extension);
Ben Langmuir532d2102015-02-02 21:56:15 +00002479 Opts.ModuleFeatures = Args.getAllArgValues(OPT_fmodule_feature);
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00002480 llvm::sort(Opts.ModuleFeatures.begin(), Opts.ModuleFeatures.end());
Pirama Arumuga Nainare9bcddd2015-05-14 23:44:18 +00002481 Opts.NativeHalfType |= Args.hasArg(OPT_fnative_half_type);
Pirama Arumuga Nainar8e2e9d62016-03-18 16:58:36 +00002482 Opts.NativeHalfArgsAndReturns |= Args.hasArg(OPT_fnative_half_arguments_and_returns);
2483 // Enable HalfArgsAndReturns if present in Args or if NativeHalfArgsAndReturns
2484 // is enabled.
2485 Opts.HalfArgsAndReturns = Args.hasArg(OPT_fallow_half_arguments_and_returns)
2486 | Opts.NativeHalfArgsAndReturns;
Steven Wucb0d13f2015-01-16 23:05:28 +00002487 Opts.GNUAsm = !Args.hasArg(OPT_fno_gnu_inline_asm);
Ben Langmuirb537a3a2014-07-23 15:30:23 +00002488
Saleem Abdulrasoold170c4b2015-10-04 17:51:05 +00002489 // __declspec is enabled by default for the PS4 by the driver, and also
2490 // enabled for Microsoft Extensions or Borland Extensions, here.
2491 //
2492 // FIXME: __declspec is also currently enabled for CUDA, but isn't really a
Justin Lebar2dfbe9a2016-10-08 22:16:08 +00002493 // CUDA extension. However, it is required for supporting
2494 // __clang_cuda_builtin_vars.h, which uses __declspec(property). Once that has
2495 // been rewritten in terms of something more generic, remove the Opts.CUDA
2496 // term here.
Saleem Abdulrasoold170c4b2015-10-04 17:51:05 +00002497 Opts.DeclSpecKeyword =
2498 Args.hasFlag(OPT_fdeclspec, OPT_fno_declspec,
2499 (Opts.MicrosoftExt || Opts.Borland || Opts.CUDA));
2500
David Tweed31d09b02013-09-13 12:04:22 +00002501 if (Arg *A = Args.getLastArg(OPT_faddress_space_map_mangling_EQ)) {
2502 switch (llvm::StringSwitch<unsigned>(A->getValue())
2503 .Case("target", LangOptions::ASMM_Target)
2504 .Case("no", LangOptions::ASMM_Off)
2505 .Case("yes", LangOptions::ASMM_On)
2506 .Default(255)) {
2507 default:
Douglas Katzman31fdbfe2015-08-05 15:08:53 +00002508 Diags.Report(diag::err_drv_invalid_value)
David Tweed31d09b02013-09-13 12:04:22 +00002509 << "-faddress-space-map-mangling=" << A->getValue();
2510 break;
2511 case LangOptions::ASMM_Target:
2512 Opts.setAddressSpaceMapMangling(LangOptions::ASMM_Target);
2513 break;
2514 case LangOptions::ASMM_On:
2515 Opts.setAddressSpaceMapMangling(LangOptions::ASMM_On);
2516 break;
2517 case LangOptions::ASMM_Off:
2518 Opts.setAddressSpaceMapMangling(LangOptions::ASMM_Off);
2519 break;
2520 }
2521 }
2522
David Majnemer86c318f2014-02-11 21:05:00 +00002523 if (Arg *A = Args.getLastArg(OPT_fms_memptr_rep_EQ)) {
2524 LangOptions::PragmaMSPointersToMembersKind InheritanceModel =
2525 llvm::StringSwitch<LangOptions::PragmaMSPointersToMembersKind>(
2526 A->getValue())
2527 .Case("single",
2528 LangOptions::PPTMK_FullGeneralitySingleInheritance)
2529 .Case("multiple",
2530 LangOptions::PPTMK_FullGeneralityMultipleInheritance)
2531 .Case("virtual",
2532 LangOptions::PPTMK_FullGeneralityVirtualInheritance)
2533 .Default(LangOptions::PPTMK_BestCase);
2534 if (InheritanceModel == LangOptions::PPTMK_BestCase)
2535 Diags.Report(diag::err_drv_invalid_value)
2536 << "-fms-memptr-rep=" << A->getValue();
2537
2538 Opts.setMSPointerToMemberRepresentationMethod(InheritanceModel);
2539 }
2540
Alexey Bataeva7547182016-05-18 09:06:38 +00002541 // Check for MS default calling conventions being specified.
2542 if (Arg *A = Args.getLastArg(OPT_fdefault_calling_conv_EQ)) {
2543 LangOptions::DefaultCallingConvention DefaultCC =
Erich Keanea957ffb2017-11-02 21:08:00 +00002544 llvm::StringSwitch<LangOptions::DefaultCallingConvention>(A->getValue())
Alexey Bataeva7547182016-05-18 09:06:38 +00002545 .Case("cdecl", LangOptions::DCC_CDecl)
2546 .Case("fastcall", LangOptions::DCC_FastCall)
2547 .Case("stdcall", LangOptions::DCC_StdCall)
2548 .Case("vectorcall", LangOptions::DCC_VectorCall)
Erich Keanea957ffb2017-11-02 21:08:00 +00002549 .Case("regcall", LangOptions::DCC_RegCall)
Alexey Bataeva7547182016-05-18 09:06:38 +00002550 .Default(LangOptions::DCC_None);
2551 if (DefaultCC == LangOptions::DCC_None)
2552 Diags.Report(diag::err_drv_invalid_value)
2553 << "-fdefault-calling-conv=" << A->getValue();
2554
2555 llvm::Triple T(TargetOpts.Triple);
2556 llvm::Triple::ArchType Arch = T.getArch();
2557 bool emitError = (DefaultCC == LangOptions::DCC_FastCall ||
Reid Kleckner4b2f3262017-05-31 15:39:28 +00002558 DefaultCC == LangOptions::DCC_StdCall) &&
2559 Arch != llvm::Triple::x86;
Erich Keanea957ffb2017-11-02 21:08:00 +00002560 emitError |= (DefaultCC == LangOptions::DCC_VectorCall ||
2561 DefaultCC == LangOptions::DCC_RegCall) &&
Alexey Bataeva7547182016-05-18 09:06:38 +00002562 !(Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64);
2563 if (emitError)
2564 Diags.Report(diag::err_drv_argument_not_allowed_with)
2565 << A->getSpelling() << T.getTriple();
2566 else
2567 Opts.setDefaultCallingConv(DefaultCC);
2568 }
2569
2570 // -mrtd option
2571 if (Arg *A = Args.getLastArg(OPT_mrtd)) {
2572 if (Opts.getDefaultCallingConv() != LangOptions::DCC_None)
2573 Diags.Report(diag::err_drv_argument_not_allowed_with)
2574 << A->getSpelling() << "-fdefault-calling-conv";
2575 else {
2576 llvm::Triple T(TargetOpts.Triple);
2577 if (T.getArch() != llvm::Triple::x86)
2578 Diags.Report(diag::err_drv_argument_not_allowed_with)
2579 << A->getSpelling() << T.getTriple();
2580 else
2581 Opts.setDefaultCallingConv(LangOptions::DCC_StdCall);
2582 }
2583 }
2584
Alexey Bataevdb390212015-05-20 04:24:19 +00002585 // Check if -fopenmp is specified.
Alexey Bataev18c48522016-05-27 04:13:39 +00002586 Opts.OpenMP = Args.hasArg(options::OPT_fopenmp) ? 1 : 0;
Alexey Bataeve927ca72017-12-29 17:36:15 +00002587 // Check if -fopenmp-simd is specified.
Alexey Bataev66f95772018-05-21 16:40:32 +00002588 bool IsSimdSpecified =
2589 Args.hasFlag(options::OPT_fopenmp_simd, options::OPT_fno_openmp_simd,
2590 /*Default=*/false);
2591 Opts.OpenMPSimd = !Opts.OpenMP && IsSimdSpecified;
Samuel Antaof8b50122015-07-13 22:54:53 +00002592 Opts.OpenMPUseTLS =
2593 Opts.OpenMP && !Args.hasArg(options::OPT_fnoopenmp_use_tls);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002594 Opts.OpenMPIsDevice =
2595 Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_is_device);
Alexey Bataev77403de2018-07-26 15:17:38 +00002596 bool IsTargetSpecified =
2597 Opts.OpenMPIsDevice || Args.hasArg(options::OPT_fopenmp_targets_EQ);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002598
Alexey Bataeve927ca72017-12-29 17:36:15 +00002599 if (Opts.OpenMP || Opts.OpenMPSimd) {
Alexey Bataev77403de2018-07-26 15:17:38 +00002600 if (int Version = getLastArgIntValue(
2601 Args, OPT_fopenmp_version_EQ,
2602 (IsSimdSpecified || IsTargetSpecified) ? 45 : Opts.OpenMP, Diags))
Alexey Bataevc6bd8912016-05-26 11:10:11 +00002603 Opts.OpenMP = Version;
Alexey Bataev77403de2018-07-26 15:17:38 +00002604 else if (IsSimdSpecified || IsTargetSpecified)
Alexey Bataeve927ca72017-12-29 17:36:15 +00002605 Opts.OpenMP = 45;
Alexey Bataevc6bd8912016-05-26 11:10:11 +00002606 // Provide diagnostic when a given target is not expected to be an OpenMP
2607 // device or host.
2608 if (!Opts.OpenMPIsDevice) {
2609 switch (T.getArch()) {
2610 default:
2611 break;
2612 // Add unsupported host targets here:
2613 case llvm::Triple::nvptx:
2614 case llvm::Triple::nvptx64:
Eugene Zelenko44357ee2018-03-26 21:45:04 +00002615 Diags.Report(diag::err_drv_omp_host_target_not_supported)
Alexey Bataevc6bd8912016-05-26 11:10:11 +00002616 << TargetOpts.Triple;
2617 break;
2618 }
Samuel Antao45bfe4c2016-02-08 15:59:20 +00002619 }
2620 }
2621
Gheorghe-Teodor Berceae3b0a192017-08-07 20:57:59 +00002622 // Set the flag to prevent the implementation from emitting device exception
2623 // handling code for those requiring so.
Alexey Bataev1ab34572018-05-02 16:52:07 +00002624 Opts.OpenMPHostCXXExceptions = Opts.Exceptions && Opts.CXXExceptions;
Sven van Haastregt2ca6ba12018-05-09 13:16:17 +00002625 if ((Opts.OpenMPIsDevice && T.isNVPTX()) || Opts.OpenCLCPlusPlus) {
Gheorghe-Teodor Berceae3b0a192017-08-07 20:57:59 +00002626 Opts.Exceptions = 0;
2627 Opts.CXXExceptions = 0;
2628 }
2629
Samuel Antaoee8fb302016-01-06 13:42:12 +00002630 // Get the OpenMP target triples if any.
Samuel Antao1168d63c2016-06-30 21:22:08 +00002631 if (Arg *A = Args.getLastArg(options::OPT_fopenmp_targets_EQ)) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002632
2633 for (unsigned i = 0; i < A->getNumValues(); ++i) {
2634 llvm::Triple TT(A->getValue(i));
2635
Gheorghe-Teodor Berceaef5e1062017-08-07 21:11:10 +00002636 if (TT.getArch() == llvm::Triple::UnknownArch ||
2637 !(TT.getArch() == llvm::Triple::ppc ||
2638 TT.getArch() == llvm::Triple::ppc64 ||
2639 TT.getArch() == llvm::Triple::ppc64le ||
2640 TT.getArch() == llvm::Triple::nvptx ||
2641 TT.getArch() == llvm::Triple::nvptx64 ||
2642 TT.getArch() == llvm::Triple::x86 ||
2643 TT.getArch() == llvm::Triple::x86_64))
Eugene Zelenko44357ee2018-03-26 21:45:04 +00002644 Diags.Report(diag::err_drv_invalid_omp_target) << A->getValue(i);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002645 else
2646 Opts.OMPTargetTriples.push_back(TT);
2647 }
2648 }
2649
2650 // Get OpenMP host file path if any and report if a non existent file is
2651 // found
Samuel Antao1168d63c2016-06-30 21:22:08 +00002652 if (Arg *A = Args.getLastArg(options::OPT_fopenmp_host_ir_file_path)) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002653 Opts.OMPHostIRFile = A->getValue();
2654 if (!llvm::sys::fs::exists(Opts.OMPHostIRFile))
Eugene Zelenko44357ee2018-03-26 21:45:04 +00002655 Diags.Report(diag::err_drv_omp_host_ir_file_not_found)
Samuel Antaoee8fb302016-01-06 13:42:12 +00002656 << Opts.OMPHostIRFile;
2657 }
Douglas Gregor15171282013-01-15 06:45:29 +00002658
Carlo Bertolli79712092018-02-28 20:48:35 +00002659 // set CUDA mode for OpenMP target NVPTX if specified in options
2660 Opts.OpenMPCUDAMode = Opts.OpenMPIsDevice && T.isNVPTX() &&
2661 Args.hasArg(options::OPT_fopenmp_cuda_mode);
2662
Chandler Carruth61fbf622011-04-23 09:27:53 +00002663 // Record whether the __DEPRECATED define was requested.
2664 Opts.Deprecated = Args.hasFlag(OPT_fdeprecated_macro,
2665 OPT_fno_deprecated_macro,
2666 Opts.Deprecated);
2667
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002668 // FIXME: Eliminate this dependency.
Dylan Noblesmith4c004f32012-08-08 16:09:15 +00002669 unsigned Opt = getOptimizationLevel(Args, IK, Diags),
Chad Rosierf2d39642013-04-10 21:30:03 +00002670 OptSize = getOptimizationLevelSize(Args);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002671 Opts.Optimize = Opt != 0;
Dylan Noblesmith4c004f32012-08-08 16:09:15 +00002672 Opts.OptimizeSize = OptSize != 0;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002673
2674 // This is the __NO_INLINE__ define, which just depends on things like the
2675 // optimization level and -fno-inline, not actually whether the backend has
2676 // inlining enabled.
Chandler Carruthfcd33142016-12-23 01:24:49 +00002677 Opts.NoInlineDefine = !Opts.Optimize;
2678 if (Arg *InlineArg = Args.getLastArg(
2679 options::OPT_finline_functions, options::OPT_finline_hint_functions,
2680 options::OPT_fno_inline_functions, options::OPT_fno_inline))
2681 if (InlineArg->getOption().matches(options::OPT_fno_inline))
2682 Opts.NoInlineDefine = true;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002683
Pekka Jaaskelainen37014502014-12-10 16:41:14 +00002684 Opts.FastMath = Args.hasArg(OPT_ffast_math) ||
2685 Args.hasArg(OPT_cl_fast_relaxed_math);
2686 Opts.FiniteMathOnly = Args.hasArg(OPT_ffinite_math_only) ||
2687 Args.hasArg(OPT_cl_finite_math_only) ||
2688 Args.hasArg(OPT_cl_fast_relaxed_math);
Alexandros Lamprineasf5a8e6c2015-10-02 14:56:37 +00002689 Opts.UnsafeFPMath = Args.hasArg(OPT_menable_unsafe_fp_math) ||
2690 Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
2691 Args.hasArg(OPT_cl_fast_relaxed_math);
Chandler Carruth306bd2c2012-01-02 14:19:45 +00002692
Adam Nemet049a31d2017-03-29 21:54:24 +00002693 if (Arg *A = Args.getLastArg(OPT_ffp_contract)) {
2694 StringRef Val = A->getValue();
2695 if (Val == "fast")
2696 Opts.setDefaultFPContractMode(LangOptions::FPC_Fast);
2697 else if (Val == "on")
2698 Opts.setDefaultFPContractMode(LangOptions::FPC_On);
2699 else if (Val == "off")
2700 Opts.setDefaultFPContractMode(LangOptions::FPC_Off);
2701 else
2702 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
2703 }
2704
Ted Kremenekb47e6bc2012-09-13 06:41:18 +00002705 Opts.RetainCommentsFromSystemHeaders =
2706 Args.hasArg(OPT_fretain_comments_from_system_headers);
2707
Reid Kleckner898229a2013-06-14 17:17:23 +00002708 unsigned SSP = getLastArgIntValue(Args, OPT_stack_protector, 0, Diags);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002709 switch (SSP) {
2710 default:
2711 Diags.Report(diag::err_drv_invalid_value)
2712 << Args.getLastArg(OPT_stack_protector)->getAsString(Args) << SSP;
2713 break;
Douglas Gregor79a91412011-09-13 17:21:33 +00002714 case 0: Opts.setStackProtector(LangOptions::SSPOff); break;
2715 case 1: Opts.setStackProtector(LangOptions::SSPOn); break;
Josh Mageee0fc1a82014-02-11 01:35:14 +00002716 case 2: Opts.setStackProtector(LangOptions::SSPStrong); break;
2717 case 3: Opts.setStackProtector(LangOptions::SSPReq); break;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002718 }
Richard Smith52be6192012-11-05 22:04:41 +00002719
2720 // Parse -fsanitize= arguments.
Alexey Samsonov88459522015-01-12 22:39:12 +00002721 parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
2722 Diags, Opts.Sanitize);
Kostya Serebryanyaed71a82014-10-09 17:53:04 +00002723 // -fsanitize-address-field-padding=N has to be a LangOpt, parse it here.
Alexey Samsonova0416102014-11-11 01:26:14 +00002724 Opts.SanitizeAddressFieldPadding =
Kostya Serebryanyaed71a82014-10-09 17:53:04 +00002725 getLastArgIntValue(Args, OPT_fsanitize_address_field_padding, 0, Diags);
Alexey Samsonova511cdd2015-02-04 17:40:08 +00002726 Opts.SanitizerBlacklistFiles = Args.getAllArgValues(OPT_fsanitize_blacklist);
Dean Michael Berris835832d2017-03-30 00:29:36 +00002727
Dean Michael Berris504fc222017-03-30 22:46:45 +00002728 // -fxray-instrument
Dean Michael Berris835832d2017-03-30 00:29:36 +00002729 Opts.XRayInstrument =
2730 Args.hasFlag(OPT_fxray_instrument, OPT_fnoxray_instrument, false);
Dean Michael Berris504fc222017-03-30 22:46:45 +00002731
Dean Michael Berris1a5b10d2017-11-30 00:04:54 +00002732 // -fxray-always-emit-customevents
2733 Opts.XRayAlwaysEmitCustomEvents =
2734 Args.hasFlag(OPT_fxray_always_emit_customevents,
2735 OPT_fnoxray_always_emit_customevents, false);
2736
Keith Wyssf437e352018-04-17 21:32:43 +00002737 // -fxray-always-emit-typedevents
2738 Opts.XRayAlwaysEmitTypedEvents =
2739 Args.hasFlag(OPT_fxray_always_emit_typedevents,
2740 OPT_fnoxray_always_emit_customevents, false);
2741
Dean Michael Berris504fc222017-03-30 22:46:45 +00002742 // -fxray-{always,never}-instrument= filenames.
Dean Michael Berris835832d2017-03-30 00:29:36 +00002743 Opts.XRayAlwaysInstrumentFiles =
2744 Args.getAllArgValues(OPT_fxray_always_instrument);
2745 Opts.XRayNeverInstrumentFiles =
2746 Args.getAllArgValues(OPT_fxray_never_instrument);
Dean Michael Berris20dc6ef2018-04-09 04:02:09 +00002747 Opts.XRayAttrListFiles = Args.getAllArgValues(OPT_fxray_attr_list);
Alex Lorenz1be800c52017-04-19 08:58:56 +00002748
Piotr Padlewskie368de32018-06-13 13:55:42 +00002749 // -fforce-emit-vtables
2750 Opts.ForceEmitVTables = Args.hasArg(OPT_fforce_emit_vtables);
2751
Alex Lorenz1be800c52017-04-19 08:58:56 +00002752 // -fallow-editor-placeholders
2753 Opts.AllowEditorPlaceholders = Args.hasArg(OPT_fallow_editor_placeholders);
Akira Hatanakafcbe17c2018-03-28 21:13:14 +00002754
2755 if (Arg *A = Args.getLastArg(OPT_fclang_abi_compat_EQ)) {
2756 Opts.setClangABICompat(LangOptions::ClangABI::Latest);
2757
2758 StringRef Ver = A->getValue();
2759 std::pair<StringRef, StringRef> VerParts = Ver.split('.');
2760 unsigned Major, Minor = 0;
2761
2762 // Check the version number is valid: either 3.x (0 <= x <= 9) or
2763 // y or y.0 (4 <= y <= current version).
2764 if (!VerParts.first.startswith("0") &&
2765 !VerParts.first.getAsInteger(10, Major) &&
2766 3 <= Major && Major <= CLANG_VERSION_MAJOR &&
2767 (Major == 3 ? VerParts.second.size() == 1 &&
2768 !VerParts.second.getAsInteger(10, Minor)
2769 : VerParts.first.size() == Ver.size() ||
2770 VerParts.second == "0")) {
2771 // Got a valid version number.
2772 if (Major == 3 && Minor <= 8)
2773 Opts.setClangABICompat(LangOptions::ClangABI::Ver3_8);
2774 else if (Major <= 4)
2775 Opts.setClangABICompat(LangOptions::ClangABI::Ver4);
Richard Smith880057c2018-04-02 18:29:44 +00002776 else if (Major <= 6)
2777 Opts.setClangABICompat(LangOptions::ClangABI::Ver6);
Akira Hatanakafcbe17c2018-03-28 21:13:14 +00002778 } else if (Ver != "latest") {
2779 Diags.Report(diag::err_drv_invalid_value)
2780 << A->getAsString(Args) << A->getValue();
2781 }
2782 }
Peter Collingbourne54d13b42018-05-30 03:40:04 +00002783
2784 Opts.CompleteMemberPointers = Args.hasArg(OPT_fcomplete_member_pointers);
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00002785 Opts.BuildingPCHWithObjectFile = Args.hasArg(OPT_building_pch_with_obj);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002786}
2787
Alex Lorenzfb7654a2017-06-16 20:13:39 +00002788static bool isStrictlyPreprocessorAction(frontend::ActionKind Action) {
2789 switch (Action) {
2790 case frontend::ASTDeclList:
2791 case frontend::ASTDump:
2792 case frontend::ASTPrint:
2793 case frontend::ASTView:
2794 case frontend::EmitAssembly:
2795 case frontend::EmitBC:
2796 case frontend::EmitHTML:
2797 case frontend::EmitLLVM:
2798 case frontend::EmitLLVMOnly:
2799 case frontend::EmitCodeGenOnly:
2800 case frontend::EmitObj:
2801 case frontend::FixIt:
2802 case frontend::GenerateModule:
2803 case frontend::GenerateModuleInterface:
2804 case frontend::GeneratePCH:
2805 case frontend::GeneratePTH:
2806 case frontend::ParseSyntaxOnly:
2807 case frontend::ModuleFileInfo:
2808 case frontend::VerifyPCH:
2809 case frontend::PluginAction:
2810 case frontend::PrintDeclContext:
2811 case frontend::RewriteObjC:
2812 case frontend::RewriteTest:
2813 case frontend::RunAnalysis:
Gabor Horvath207e7b12018-02-10 14:04:45 +00002814 case frontend::TemplightDump:
Alex Lorenzfb7654a2017-06-16 20:13:39 +00002815 case frontend::MigrateSource:
2816 return false;
2817
Aaron Ballman16ed8dd2018-05-31 13:57:09 +00002818 case frontend::DumpCompilerOptions:
Alex Lorenzfb7654a2017-06-16 20:13:39 +00002819 case frontend::DumpRawTokens:
2820 case frontend::DumpTokens:
2821 case frontend::InitOnly:
2822 case frontend::PrintPreamble:
2823 case frontend::PrintPreprocessedInput:
2824 case frontend::RewriteMacros:
2825 case frontend::RunPreprocessorOnly:
2826 return true;
2827 }
2828 llvm_unreachable("invalid frontend action");
2829}
2830
Daniel Dunbar6048e7f2009-12-03 05:11:16 +00002831static void ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args,
Alex Lorenzfb7654a2017-06-16 20:13:39 +00002832 DiagnosticsEngine &Diags,
2833 frontend::ActionKind Action) {
Daniel Dunbar37300482010-05-20 16:54:55 +00002834 Opts.ImplicitPCHInclude = Args.getLastArgValue(OPT_include_pch);
2835 Opts.ImplicitPTHInclude = Args.getLastArgValue(OPT_include_pth);
Erich Keane76675de2018-07-05 17:22:13 +00002836 Opts.PCHThroughHeader = Args.getLastArgValue(OPT_pch_through_header_EQ);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002837 if (const Arg *A = Args.getLastArg(OPT_token_cache))
Richard Smithbd55daf2012-11-01 04:30:05 +00002838 Opts.TokenCache = A->getValue();
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002839 else
2840 Opts.TokenCache = Opts.ImplicitPTHInclude;
2841 Opts.UsePredefines = !Args.hasArg(OPT_undef);
Douglas Gregor7f6d60d2010-03-19 16:15:56 +00002842 Opts.DetailedRecord = Args.hasArg(OPT_detailed_preprocessing_record);
Douglas Gregorce3a8292010-07-27 00:27:13 +00002843 Opts.DisablePCHValidation = Args.hasArg(OPT_fno_validate_pch);
Argyrios Kyrtzidis7b5d9102017-02-27 02:06:18 +00002844 Opts.AllowPCHWithCompilerErrors = Args.hasArg(OPT_fallow_pch_with_errors);
Argyrios Kyrtzidis0427be92010-10-14 20:14:25 +00002845
Argyrios Kyrtzidisa11aca42010-10-14 20:14:18 +00002846 Opts.DumpDeserializedPCHDecls = Args.hasArg(OPT_dump_deserialized_pch_decls);
Eugene Zelenko44357ee2018-03-26 21:45:04 +00002847 for (const auto *A : Args.filtered(OPT_error_on_deserialized_pch_decl))
Richard Smithbd55daf2012-11-01 04:30:05 +00002848 Opts.DeserializedPCHDeclsToErrorOn.insert(A->getValue());
Douglas Gregorce3a8292010-07-27 00:27:13 +00002849
Douglas Gregor3f4bea02010-07-26 21:36:20 +00002850 if (const Arg *A = Args.getLastArg(OPT_preamble_bytes_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00002851 StringRef Value(A->getValue());
Douglas Gregor3f4bea02010-07-26 21:36:20 +00002852 size_t Comma = Value.find(',');
2853 unsigned Bytes = 0;
2854 unsigned EndOfLine = 0;
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002855
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002856 if (Comma == StringRef::npos ||
Douglas Gregor3f4bea02010-07-26 21:36:20 +00002857 Value.substr(0, Comma).getAsInteger(10, Bytes) ||
2858 Value.substr(Comma + 1).getAsInteger(10, EndOfLine))
2859 Diags.Report(diag::err_drv_preamble_format);
2860 else {
2861 Opts.PrecompiledPreambleBytes.first = Bytes;
2862 Opts.PrecompiledPreambleBytes.second = (EndOfLine != 0);
2863 }
2864 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002865
Alexander Ivchenko0fb8c872018-05-18 11:56:21 +00002866 // Add the __CET__ macro if a CFProtection option is set.
2867 if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
2868 StringRef Name = A->getValue();
2869 if (Name == "branch")
2870 Opts.addMacroDef("__CET__=1");
2871 else if (Name == "return")
2872 Opts.addMacroDef("__CET__=2");
2873 else if (Name == "full")
2874 Opts.addMacroDef("__CET__=3");
2875 }
2876
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002877 // Add macros from the command line.
Eugene Zelenko44357ee2018-03-26 21:45:04 +00002878 for (const auto *A : Args.filtered(OPT_D, OPT_U)) {
Sean Silva14facf32015-06-09 01:57:17 +00002879 if (A->getOption().matches(OPT_D))
2880 Opts.addMacroDef(A->getValue());
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002881 else
Sean Silva14facf32015-06-09 01:57:17 +00002882 Opts.addMacroUndef(A->getValue());
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002883 }
2884
Daniel Dunbar37300482010-05-20 16:54:55 +00002885 Opts.MacroIncludes = Args.getAllArgValues(OPT_imacros);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002886
2887 // Add the ordered list of -includes.
Eugene Zelenko44357ee2018-03-26 21:45:04 +00002888 for (const auto *A : Args.filtered(OPT_include))
Benjamin Kramer3204b152015-05-29 19:42:19 +00002889 Opts.Includes.emplace_back(A->getValue());
Daniel Dunbar6048e7f2009-12-03 05:11:16 +00002890
Eugene Zelenko44357ee2018-03-26 21:45:04 +00002891 for (const auto *A : Args.filtered(OPT_chain_include))
Benjamin Kramer3204b152015-05-29 19:42:19 +00002892 Opts.ChainedIncludes.emplace_back(A->getValue());
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002893
Eugene Zelenko44357ee2018-03-26 21:45:04 +00002894 for (const auto *A : Args.filtered(OPT_remap_file)) {
Sean Silva14facf32015-06-09 01:57:17 +00002895 std::pair<StringRef, StringRef> Split = StringRef(A->getValue()).split(';');
Daniel Dunbar6048e7f2009-12-03 05:11:16 +00002896
2897 if (Split.second.empty()) {
Daniel Dunbara442fd52010-06-11 22:00:13 +00002898 Diags.Report(diag::err_drv_invalid_remap_file) << A->getAsString(Args);
Daniel Dunbar6048e7f2009-12-03 05:11:16 +00002899 continue;
2900 }
2901
2902 Opts.addRemappedFile(Split.first, Split.second);
2903 }
Sean Silva14facf32015-06-09 01:57:17 +00002904
John McCall31168b02011-06-15 23:02:42 +00002905 if (Arg *A = Args.getLastArg(OPT_fobjc_arc_cxxlib_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00002906 StringRef Name = A->getValue();
John McCall31168b02011-06-15 23:02:42 +00002907 unsigned Library = llvm::StringSwitch<unsigned>(Name)
2908 .Case("libc++", ARCXX_libcxx)
2909 .Case("libstdc++", ARCXX_libstdcxx)
2910 .Case("none", ARCXX_nolib)
2911 .Default(~0U);
2912 if (Library == ~0U)
2913 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
2914 else
2915 Opts.ObjCXXARCStandardLibrary = (ObjCXXARCStandardLibraryKind)Library;
2916 }
Alex Lorenzfb7654a2017-06-16 20:13:39 +00002917
2918 // Always avoid lexing editor placeholders when we're just running the
2919 // preprocessor as we never want to emit the
2920 // "editor placeholder in source file" error in PP only mode.
2921 if (isStrictlyPreprocessorAction(Action))
2922 Opts.LexEditorPlaceholders = false;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002923}
2924
2925static void ParsePreprocessorOutputArgs(PreprocessorOutputOptions &Opts,
Jordan Rose17441582013-01-30 01:52:57 +00002926 ArgList &Args,
2927 frontend::ActionKind Action) {
Alex Lorenzfb7654a2017-06-16 20:13:39 +00002928 if (isStrictlyPreprocessorAction(Action))
Jordan Rose17441582013-01-30 01:52:57 +00002929 Opts.ShowCPP = !Args.hasArg(OPT_dM);
Alex Lorenzfb7654a2017-06-16 20:13:39 +00002930 else
2931 Opts.ShowCPP = 0;
Jordan Rose17441582013-01-30 01:52:57 +00002932
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002933 Opts.ShowComments = Args.hasArg(OPT_C);
Daniel Dunbard4352752010-08-24 22:44:13 +00002934 Opts.ShowLineMarkers = !Args.hasArg(OPT_P);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002935 Opts.ShowMacroComments = Args.hasArg(OPT_CC);
Daniel Dunbard4352752010-08-24 22:44:13 +00002936 Opts.ShowMacros = Args.hasArg(OPT_dM) || Args.hasArg(OPT_dD);
Bruno Cardoso Lopes6fa3b742016-11-17 22:45:31 +00002937 Opts.ShowIncludeDirectives = Args.hasArg(OPT_dI);
David Blaikiee993e4c2012-06-14 17:36:09 +00002938 Opts.RewriteIncludes = Args.hasArg(OPT_frewrite_includes);
Richard Smith86a3ef52017-06-09 21:24:02 +00002939 Opts.RewriteImports = Args.hasArg(OPT_frewrite_imports);
Reid Kleckner1df0fea2015-02-26 00:17:25 +00002940 Opts.UseLineDirectives = Args.hasArg(OPT_fuse_line_directives);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002941}
2942
Saleem Abdulrasoolf7b3d6c2016-04-08 16:52:05 +00002943static void ParseTargetArgs(TargetOptions &Opts, ArgList &Args,
2944 DiagnosticsEngine &Diags) {
Daniel Dunbar37300482010-05-20 16:54:55 +00002945 Opts.ABI = Args.getLastArgValue(OPT_target_abi);
Saleem Abdulrasoolf7b3d6c2016-04-08 16:52:05 +00002946 if (Arg *A = Args.getLastArg(OPT_meabi)) {
2947 StringRef Value = A->getValue();
2948 llvm::EABI EABIVersion = llvm::StringSwitch<llvm::EABI>(Value)
2949 .Case("default", llvm::EABI::Default)
2950 .Case("4", llvm::EABI::EABI4)
2951 .Case("5", llvm::EABI::EABI5)
2952 .Case("gnu", llvm::EABI::GNU)
2953 .Default(llvm::EABI::Unknown);
2954 if (EABIVersion == llvm::EABI::Unknown)
2955 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
2956 << Value;
2957 else
Yuka Takahashidc771502017-07-01 07:57:23 +00002958 Opts.EABIVersion = EABIVersion;
Saleem Abdulrasoolf7b3d6c2016-04-08 16:52:05 +00002959 }
Daniel Dunbar37300482010-05-20 16:54:55 +00002960 Opts.CPU = Args.getLastArgValue(OPT_target_cpu);
Rafael Espindolaeb265472013-08-21 21:59:03 +00002961 Opts.FPMath = Args.getLastArgValue(OPT_mfpmath);
Douglas Gregorcb177f12012-10-16 23:40:58 +00002962 Opts.FeaturesAsWritten = Args.getAllArgValues(OPT_target_feature);
Daniel Dunbara1d107c2010-08-11 23:07:42 +00002963 Opts.LinkerVersion = Args.getLastArgValue(OPT_target_linker_version);
Petr Hosekf92ca012018-05-25 20:39:37 +00002964 Opts.Triple = Args.getLastArgValue(OPT_triple);
Sebastian Pop8188c8a2011-11-01 21:33:06 +00002965 // Use the default target triple if unspecified.
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002966 if (Opts.Triple.empty())
Sebastian Pop8188c8a2011-11-01 21:33:06 +00002967 Opts.Triple = llvm::sys::getDefaultTargetTriple();
Petr Hosekf92ca012018-05-25 20:39:37 +00002968 Opts.Triple = llvm::Triple::normalize(Opts.Triple);
Alexey Bader0ea07532016-11-01 15:50:52 +00002969 Opts.OpenCLExtensionsAsWritten = Args.getAllArgValues(OPT_cl_ext_EQ);
Mandeep Singh Grangac24bb52018-02-25 03:58:23 +00002970 Opts.ForceEnableInt128 = Args.hasArg(OPT_fforce_enable_int128);
Artem Belevich679dafe2018-05-09 23:10:09 +00002971 Opts.NVPTXUseShortPointers = Args.hasFlag(
2972 options::OPT_fcuda_short_ptr, options::OPT_fno_cuda_short_ptr, false);
Hans Wennborg50501fb2014-01-13 19:48:18 +00002973}
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002974
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00002975bool CompilerInvocation::CreateFromArgs(CompilerInvocation &Res,
Chris Lattner5159f612010-11-23 08:35:12 +00002976 const char *const *ArgBegin,
2977 const char *const *ArgEnd,
David Blaikie9c902b52011-09-25 23:23:43 +00002978 DiagnosticsEngine &Diags) {
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00002979 bool Success = true;
2980
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002981 // Parse the arguments.
David Blaikie0aaa7622017-01-13 17:34:15 +00002982 std::unique_ptr<OptTable> Opts = createDriverOptTable();
Hans Wennborgd1ddb9a2013-08-02 20:16:22 +00002983 const unsigned IncludedFlagsBitmask = options::CC1Option;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002984 unsigned MissingArgIndex, MissingArgCount;
David Blaikie69a1d8c2015-06-22 22:07:27 +00002985 InputArgList Args =
David Blaikie6d492ad2015-06-21 06:32:36 +00002986 Opts->ParseArgs(llvm::makeArrayRef(ArgBegin, ArgEnd), MissingArgIndex,
David Blaikie69a1d8c2015-06-22 22:07:27 +00002987 MissingArgCount, IncludedFlagsBitmask);
Wei Mi811ff922016-04-08 17:42:32 +00002988 LangOptions &LangOpts = *Res.getLangOpts();
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002989
2990 // Check for missing argument error.
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00002991 if (MissingArgCount) {
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002992 Diags.Report(diag::err_drv_missing_argument)
David Blaikie69a1d8c2015-06-22 22:07:27 +00002993 << Args.getArgString(MissingArgIndex) << MissingArgCount;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00002994 Success = false;
2995 }
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002996
2997 // Issue errors on unknown arguments.
Eugene Zelenko44357ee2018-03-26 21:45:04 +00002998 for (const auto *A : Args.filtered(OPT_UNKNOWN)) {
Brian Gesiak24910762018-01-06 00:25:40 +00002999 auto ArgString = A->getAsString(Args);
3000 std::string Nearest;
3001 if (Opts->findNearest(ArgString, Nearest, IncludedFlagsBitmask) > 1)
3002 Diags.Report(diag::err_drv_unknown_argument) << ArgString;
3003 else
3004 Diags.Report(diag::err_drv_unknown_argument_with_suggestion)
3005 << ArgString << Nearest;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00003006 Success = false;
3007 }
Daniel Dunbarc70c3932009-12-01 03:16:53 +00003008
David Blaikie69a1d8c2015-06-22 22:07:27 +00003009 Success &= ParseAnalyzerArgs(*Res.getAnalyzerOpts(), Args, Diags);
3010 Success &= ParseMigratorArgs(Res.getMigratorOpts(), Args);
3011 ParseDependencyOutputArgs(Res.getDependencyOutputOpts(), Args);
Bruno Cardoso Lopes76952a72016-10-11 18:21:26 +00003012 Success &=
3013 ParseDiagnosticArgs(Res.getDiagnosticOpts(), Args, &Diags,
3014 false /*DefaultDiagColor*/, false /*DefaultShowOpt*/);
Wei Mi811ff922016-04-08 17:42:32 +00003015 ParseCommentArgs(LangOpts.CommentOpts, Args);
David Blaikie69a1d8c2015-06-22 22:07:27 +00003016 ParseFileSystemArgs(Res.getFileSystemOpts(), Args);
Peter Collingbourneb8e5dd42010-12-04 01:50:36 +00003017 // FIXME: We shouldn't have to pass the DashX option around here
Erik Verbruggene0bde752016-10-27 14:17:10 +00003018 InputKind DashX = ParseFrontendArgs(Res.getFrontendOpts(), Args, Diags,
3019 LangOpts.IsHeaderFile);
Saleem Abdulrasoolf7b3d6c2016-04-08 16:52:05 +00003020 ParseTargetArgs(Res.getTargetOpts(), Args, Diags);
David Blaikie69a1d8c2015-06-22 22:07:27 +00003021 Success &= ParseCodeGenArgs(Res.getCodeGenOpts(), Args, DashX, Diags,
Teresa Johnson9e4321c2018-04-17 16:39:25 +00003022 Res.getTargetOpts(), Res.getFrontendOpts());
Adrian Prantl0ebdeac2017-03-14 23:07:49 +00003023 ParseHeaderSearchArgs(Res.getHeaderSearchOpts(), Args,
3024 Res.getFileSystemOpts().WorkingDir);
Richard Smith40c0efa2017-04-26 18:57:40 +00003025 if (DashX.getFormat() == InputKind::Precompiled ||
3026 DashX.getLanguage() == InputKind::LLVM_IR) {
Steven Wu546a1962015-07-17 20:09:56 +00003027 // ObjCAAutoRefCount and Sanitize LangOpts are used to setup the
3028 // PassManager in BackendUtil.cpp. They need to be initializd no matter
3029 // what the input type is.
3030 if (Args.hasArg(OPT_fobjc_arc))
Wei Mi811ff922016-04-08 17:42:32 +00003031 LangOpts.ObjCAutoRefCount = 1;
3032 // PIClevel and PIELevel are needed during code generation and this should be
3033 // set regardless of the input type.
3034 LangOpts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
Rafael Espindolac9d336e2016-06-23 15:07:32 +00003035 LangOpts.PIE = Args.hasArg(OPT_pic_is_pie);
Steven Wu546a1962015-07-17 20:09:56 +00003036 parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
Wei Mi811ff922016-04-08 17:42:32 +00003037 Diags, LangOpts.Sanitize);
Steven Wu546a1962015-07-17 20:09:56 +00003038 } else {
3039 // Other LangOpts are only initialzed when the input is not AST or LLVM IR.
Richard Smith40c0efa2017-04-26 18:57:40 +00003040 // FIXME: Should we really be calling this for an InputKind::Asm input?
Yaxun Liu143f0832016-06-20 19:26:00 +00003041 ParseLangArgs(LangOpts, Args, DashX, Res.getTargetOpts(),
Richard Smith40c0efa2017-04-26 18:57:40 +00003042 Res.getPreprocessorOpts(), Diags);
Fariborz Jahanian40c5e1a2011-02-25 17:24:55 +00003043 if (Res.getFrontendOpts().ProgramAction == frontend::RewriteObjC)
Wei Mi811ff922016-04-08 17:42:32 +00003044 LangOpts.ObjCExceptions = 1;
Fariborz Jahanian40c5e1a2011-02-25 17:24:55 +00003045 }
Benjamin Kramer12f2de12016-03-14 13:23:58 +00003046
Saleem Abdulrasool3fe5b7a2018-04-19 23:14:57 +00003047 LangOpts.FunctionAlignment =
3048 getLastArgIntValue(Args, OPT_function_alignment, 0, Diags);
3049
Artem Belevich31c3bad2016-05-19 18:44:45 +00003050 if (LangOpts.CUDA) {
3051 // During CUDA device-side compilation, the aux triple is the
3052 // triple used for host compilation.
3053 if (LangOpts.CUDAIsDevice)
3054 Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple;
Justin Lebar76945b22016-04-29 23:05:19 +00003055 }
3056
Gheorghe-Teodor Bercea59d7b772017-06-29 15:49:03 +00003057 // Set the triple of the host for OpenMP device compile.
3058 if (LangOpts.OpenMPIsDevice)
3059 Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple;
3060
Benjamin Kramerfd652b12016-03-15 09:41:39 +00003061 // FIXME: Override value name discarding when asan or msan is used because the
Benjamin Kramer12f2de12016-03-14 13:23:58 +00003062 // backend passes depend on the name of the alloca in order to print out
3063 // names.
Benjamin Kramerfd652b12016-03-15 09:41:39 +00003064 Res.getCodeGenOpts().DiscardValueNames &=
Wei Mi811ff922016-04-08 17:42:32 +00003065 !LangOpts.Sanitize.has(SanitizerKind::Address) &&
3066 !LangOpts.Sanitize.has(SanitizerKind::Memory);
Benjamin Kramer12f2de12016-03-14 13:23:58 +00003067
Brian Gesiakf0ef1372018-01-09 21:26:47 +00003068 ParsePreprocessorArgs(Res.getPreprocessorOpts(), Args, Diags,
Alex Lorenzfb7654a2017-06-16 20:13:39 +00003069 Res.getFrontendOpts().ProgramAction);
David Blaikie69a1d8c2015-06-22 22:07:27 +00003070 ParsePreprocessorOutputArgs(Res.getPreprocessorOutputOpts(), Args,
Jordan Rose17441582013-01-30 01:52:57 +00003071 Res.getFrontendOpts().ProgramAction);
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003072
3073 // Turn on -Wspir-compat for SPIR target.
3074 llvm::Triple T(Res.getTargetOpts().Triple);
3075 auto Arch = T.getArch();
3076 if (Arch == llvm::Triple::spir || Arch == llvm::Triple::spir64) {
3077 Res.getDiagnosticOpts().Warnings.push_back("spir-compat");
3078 }
Wei Mi9b3d6272017-10-16 16:50:27 +00003079
3080 // If sanitizer is enabled, disable OPT_ffine_grained_bitfield_accesses.
3081 if (Res.getCodeGenOpts().FineGrainedBitfieldAccesses &&
3082 !Res.getLangOpts()->Sanitize.empty()) {
3083 Res.getCodeGenOpts().FineGrainedBitfieldAccesses = false;
3084 Diags.Report(diag::warn_drv_fine_grained_bitfield_accesses_ignored);
3085 }
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00003086 return Success;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00003087}
Douglas Gregor1735f4e2011-09-13 23:15:45 +00003088
Douglas Gregor1735f4e2011-09-13 23:15:45 +00003089std::string CompilerInvocation::getModuleHash() const {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00003090 // Note: For QoI reasons, the things we use as a hash here should all be
3091 // dumped via the -module-info flag.
Douglas Gregor7fd08492012-11-05 19:45:09 +00003092 using llvm::hash_code;
3093 using llvm::hash_value;
3094 using llvm::hash_combine;
3095
Douglas Gregor1735f4e2011-09-13 23:15:45 +00003096 // Start the signature with the compiler version.
Douglas Gregordc779ab2012-11-05 23:30:26 +00003097 // FIXME: We'd rather use something more cryptographically sound than
Douglas Gregor7fd08492012-11-05 19:45:09 +00003098 // CityHash, but this will do for now.
3099 hash_code code = hash_value(getClangFullRepositoryVersion());
3100
Douglas Gregor1735f4e2011-09-13 23:15:45 +00003101 // Extend the signature with the language options
3102#define LANGOPT(Name, Bits, Default, Description) \
Douglas Gregor7fd08492012-11-05 19:45:09 +00003103 code = hash_combine(code, LangOpts->Name);
Douglas Gregor1735f4e2011-09-13 23:15:45 +00003104#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
Douglas Gregor7fd08492012-11-05 19:45:09 +00003105 code = hash_combine(code, static_cast<unsigned>(LangOpts->get##Name()));
Douglas Gregor1735f4e2011-09-13 23:15:45 +00003106#define BENIGN_LANGOPT(Name, Bits, Default, Description)
3107#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
3108#include "clang/Basic/LangOptions.def"
Ben Langmuircd98cb72015-06-23 18:20:18 +00003109
3110 for (StringRef Feature : LangOpts->ModuleFeatures)
3111 code = hash_combine(code, Feature);
Douglas Katzman31fdbfe2015-08-05 15:08:53 +00003112
Douglas Gregor7fd08492012-11-05 19:45:09 +00003113 // Extend the signature with the target options.
3114 code = hash_combine(code, TargetOpts->Triple, TargetOpts->CPU,
Argyrios Kyrtzidisfe6b8802014-04-29 18:45:01 +00003115 TargetOpts->ABI);
Eugene Zelenko44357ee2018-03-26 21:45:04 +00003116 for (const auto &FeatureAsWritten : TargetOpts->FeaturesAsWritten)
3117 code = hash_combine(code, FeatureAsWritten);
Douglas Gregor1735f4e2011-09-13 23:15:45 +00003118
Douglas Gregora739d9a2011-09-14 15:55:12 +00003119 // Extend the signature with preprocessor options.
Douglas Gregor7fd08492012-11-05 19:45:09 +00003120 const PreprocessorOptions &ppOpts = getPreprocessorOpts();
Douglas Gregor5dc38992013-02-07 00:21:12 +00003121 const HeaderSearchOptions &hsOpts = getHeaderSearchOpts();
Douglas Gregor7fd08492012-11-05 19:45:09 +00003122 code = hash_combine(code, ppOpts.UsePredefines, ppOpts.DetailedRecord);
3123
Eugene Zelenko44357ee2018-03-26 21:45:04 +00003124 for (const auto &I : getPreprocessorOpts().Macros) {
Douglas Gregor5dc38992013-02-07 00:21:12 +00003125 // If we're supposed to ignore this macro for the purposes of modules,
3126 // don't put it into the hash.
3127 if (!hsOpts.ModulesIgnoreMacros.empty()) {
Douglas Gregor5dc38992013-02-07 00:21:12 +00003128 // Check whether we're ignoring this macro.
Eugene Zelenko44357ee2018-03-26 21:45:04 +00003129 StringRef MacroDef = I.first;
Justin Lebar5e83dfe2016-10-21 21:45:01 +00003130 if (hsOpts.ModulesIgnoreMacros.count(
3131 llvm::CachedHashString(MacroDef.split('=').first)))
Douglas Gregor5dc38992013-02-07 00:21:12 +00003132 continue;
3133 }
3134
Eugene Zelenko44357ee2018-03-26 21:45:04 +00003135 code = hash_combine(code, I.first, I.second);
Douglas Gregor71129d52011-10-17 14:55:37 +00003136 }
Douglas Gregor7fd08492012-11-05 19:45:09 +00003137
Adrian Prantl793038d32016-01-12 21:01:56 +00003138 // Extend the signature with the sysroot and other header search options.
3139 code = hash_combine(code, hsOpts.Sysroot,
3140 hsOpts.ModuleFormat,
3141 hsOpts.UseDebugInfo,
3142 hsOpts.UseBuiltinIncludes,
Douglas Gregor7fd08492012-11-05 19:45:09 +00003143 hsOpts.UseStandardSystemIncludes,
3144 hsOpts.UseStandardCXXIncludes,
Manman Ren47a44452016-07-26 17:12:17 +00003145 hsOpts.UseLibcxx,
3146 hsOpts.ModulesValidateDiagnosticOptions);
Argyrios Kyrtzidisd113788e2014-05-04 05:27:24 +00003147 code = hash_combine(code, hsOpts.ResourceDir);
Douglas Gregor7fd08492012-11-05 19:45:09 +00003148
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00003149 // Extend the signature with the user build path.
3150 code = hash_combine(code, hsOpts.ModuleUserBuildPath);
3151
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003152 // Extend the signature with the module file extensions.
3153 const FrontendOptions &frontendOpts = getFrontendOpts();
Benjamin Kramer2e018ef2016-05-27 13:36:58 +00003154 for (const auto &ext : frontendOpts.ModuleFileExtensions) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003155 code = ext->hashExtension(code);
3156 }
3157
Vedant Kumar85a83c22017-06-01 20:01:01 +00003158 // Extend the signature with the enabled sanitizers, if at least one is
3159 // enabled. Sanitizers which cannot affect AST generation aren't hashed.
3160 SanitizerSet SanHash = LangOpts->Sanitize;
3161 SanHash.clear(getPPTransparentSanitizers());
3162 if (!SanHash.empty())
3163 code = hash_combine(code, SanHash.Mask);
3164
Douglas Gregor7fd08492012-11-05 19:45:09 +00003165 return llvm::APInt(64, code).toString(36, /*Signed=*/false);
Douglas Gregor1735f4e2011-09-13 23:15:45 +00003166}
Reid Kleckner898229a2013-06-14 17:17:23 +00003167
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003168template<typename IntTy>
3169static IntTy getLastArgIntValueImpl(const ArgList &Args, OptSpecifier Id,
3170 IntTy Default,
3171 DiagnosticsEngine *Diags) {
3172 IntTy Res = Default;
Reid Kleckner898229a2013-06-14 17:17:23 +00003173 if (Arg *A = Args.getLastArg(Id)) {
3174 if (StringRef(A->getValue()).getAsInteger(10, Res)) {
3175 if (Diags)
3176 Diags->Report(diag::err_drv_invalid_int_value) << A->getAsString(Args)
3177 << A->getValue();
3178 }
3179 }
3180 return Res;
3181}
Kostya Serebryanyce2c7262013-12-27 08:11:08 +00003182
Eugene Zelenko44357ee2018-03-26 21:45:04 +00003183namespace clang {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003184
3185// Declared in clang/Frontend/Utils.h.
3186int getLastArgIntValue(const ArgList &Args, OptSpecifier Id, int Default,
3187 DiagnosticsEngine *Diags) {
3188 return getLastArgIntValueImpl<int>(Args, Id, Default, Diags);
3189}
3190
3191uint64_t getLastArgUInt64Value(const ArgList &Args, OptSpecifier Id,
3192 uint64_t Default,
3193 DiagnosticsEngine *Diags) {
3194 return getLastArgIntValueImpl<uint64_t>(Args, Id, Default, Diags);
3195}
3196
Kostya Serebryanyce2c7262013-12-27 08:11:08 +00003197void BuryPointer(const void *Ptr) {
3198 // This function may be called only a small fixed amount of times per each
3199 // invocation, otherwise we do actually have a leak which we want to report.
3200 // If this function is called more than kGraveYardMaxSize times, the pointers
3201 // will not be properly buried and a leak detector will report a leak, which
3202 // is what we want in such case.
3203 static const size_t kGraveYardMaxSize = 16;
Chandler Carruth2588aa72013-12-28 02:50:00 +00003204 LLVM_ATTRIBUTE_UNUSED static const void *GraveYard[kGraveYardMaxSize];
Benjamin Kramer4527fb22014-03-02 17:08:31 +00003205 static std::atomic<unsigned> GraveYardSize;
3206 unsigned Idx = GraveYardSize++;
Kostya Serebryanyce2c7262013-12-27 08:11:08 +00003207 if (Idx >= kGraveYardMaxSize)
3208 return;
3209 GraveYard[Idx] = Ptr;
3210}
Ben Langmuir8832c062014-04-15 18:16:25 +00003211
3212IntrusiveRefCntPtr<vfs::FileSystem>
3213createVFSFromCompilerInvocation(const CompilerInvocation &CI,
3214 DiagnosticsEngine &Diags) {
Ilya Biryukovaf69e402017-05-23 11:37:52 +00003215 return createVFSFromCompilerInvocation(CI, Diags, vfs::getRealFileSystem());
3216}
Ben Langmuir8832c062014-04-15 18:16:25 +00003217
Ilya Biryukovaf69e402017-05-23 11:37:52 +00003218IntrusiveRefCntPtr<vfs::FileSystem>
3219createVFSFromCompilerInvocation(const CompilerInvocation &CI,
3220 DiagnosticsEngine &Diags,
3221 IntrusiveRefCntPtr<vfs::FileSystem> BaseFS) {
3222 if (CI.getHeaderSearchOpts().VFSOverlayFiles.empty())
3223 return BaseFS;
3224
3225 IntrusiveRefCntPtr<vfs::OverlayFileSystem> Overlay(
3226 new vfs::OverlayFileSystem(BaseFS));
Ben Langmuir8832c062014-04-15 18:16:25 +00003227 // earlier vfs files are on the bottom
Eugene Zelenko44357ee2018-03-26 21:45:04 +00003228 for (const auto &File : CI.getHeaderSearchOpts().VFSOverlayFiles) {
Rafael Espindola2d2b4202014-07-06 17:43:24 +00003229 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
Ilya Biryukovaf69e402017-05-23 11:37:52 +00003230 BaseFS->getBufferForFile(File);
Rafael Espindola2d2b4202014-07-06 17:43:24 +00003231 if (!Buffer) {
Ben Langmuir8832c062014-04-15 18:16:25 +00003232 Diags.Report(diag::err_missing_vfs_overlay_file) << File;
Ben Langmuir005c2e52018-03-23 17:37:27 +00003233 continue;
Ben Langmuir8832c062014-04-15 18:16:25 +00003234 }
3235
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00003236 IntrusiveRefCntPtr<vfs::FileSystem> FS = vfs::getVFSFromYAML(
3237 std::move(Buffer.get()), /*DiagHandler*/ nullptr, File);
Ben Langmuir005c2e52018-03-23 17:37:27 +00003238 if (FS)
3239 Overlay->pushOverlay(FS);
3240 else
Ben Langmuir8832c062014-04-15 18:16:25 +00003241 Diags.Report(diag::err_invalid_vfs_overlay) << File;
Ben Langmuir8832c062014-04-15 18:16:25 +00003242 }
3243 return Overlay;
Reid Kleckner898229a2013-06-14 17:17:23 +00003244}
Eugene Zelenko44357ee2018-03-26 21:45:04 +00003245
3246} // namespace clang