blob: c26d5fb79b3985445b20ff84e0ed7a1e578cf4a6 [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 Liu2c17e822016-08-09 19:43:38 +0000693 Opts.FlushDenorm = Args.hasArg(OPT_cl_denorms_are_zero);
Yaxun Liuffb60902016-08-09 20:10:18 +0000694 Opts.CorrectlyRoundedDivSqrt =
695 Args.hasArg(OPT_cl_fp32_correctly_rounded_divide_sqrt);
Alexey Sotkin20f65922018-02-22 11:54:14 +0000696 Opts.UniformWGSize =
697 Args.hasArg(OPT_cl_uniform_work_group_size);
Craig Topper402b4312017-11-20 17:09:22 +0000698 Opts.Reciprocals = Args.getAllArgValues(OPT_mrecip_EQ);
Sanjay Patel359b1052015-04-09 15:03:23 +0000699 Opts.ReciprocalMath = Args.hasArg(OPT_freciprocal_math);
Sjoerd Meijer0a8d4212016-08-30 08:09:45 +0000700 Opts.NoTrappingMath = Args.hasArg(OPT_fno_trapping_math);
Sanjay Patelc81450e2018-04-30 18:19:03 +0000701 Opts.StrictFloatCastOverflow =
702 !Args.hasArg(OPT_fno_strict_float_cast_overflow);
Sanjay Pateld1754762018-04-27 14:22:48 +0000703
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000704 Opts.NoZeroInitializedInBSS = Args.hasArg(OPT_mno_zero_initialized_in_bss);
Reid Kleckner898229a2013-06-14 17:17:23 +0000705 Opts.NumRegisterParameters = getLastArgIntValue(Args, OPT_mregparm, 0, Diags);
Nick Lewyckyca6b90d2011-06-21 00:14:18 +0000706 Opts.NoExecStack = Args.hasArg(OPT_mno_exec_stack);
Joerg Sonnenbergera43604a2014-08-26 18:40:25 +0000707 Opts.FatalWarnings = Args.hasArg(OPT_massembler_fatal_warnings);
Eric Christopher006208c2013-04-04 06:29:47 +0000708 Opts.EnableSegmentedStacks = Args.hasArg(OPT_split_stacks);
Daniel Dunbarc43b6b22010-05-27 05:39:39 +0000709 Opts.RelaxAll = Args.hasArg(OPT_mrelax_all);
David Majnemer2b9349d2015-12-21 22:09:34 +0000710 Opts.IncrementalLinkerCompatible =
711 Args.hasArg(OPT_mincremental_linker_compatible);
Sriraman Tallam165a8842016-10-19 20:24:06 +0000712 Opts.PIECopyRelocations =
713 Args.hasArg(OPT_mpie_copy_relocations);
Sriraman Tallam5c651482017-11-07 19:37:51 +0000714 Opts.NoPLT = Args.hasArg(OPT_fno_plt);
Daniel Dunbarbb7ac522010-07-01 01:31:45 +0000715 Opts.OmitLeafFramePointer = Args.hasArg(OPT_momit_leaf_frame_pointer);
Daniel Dunbar67919b22011-03-28 22:49:28 +0000716 Opts.SaveTempLabels = Args.hasArg(OPT_msave_temp_labels);
Nick Lewycky1d617ac2011-10-17 23:05:52 +0000717 Opts.NoDwarfDirectoryAsm = Args.hasArg(OPT_fno_dwarf_directory_asm);
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000718 Opts.SoftFloat = Args.hasArg(OPT_msoft_float);
Chandler Carruth8b4140d2012-03-27 23:58:37 +0000719 Opts.StrictEnums = Args.hasArg(OPT_fstrict_enums);
Alex Lorenzc1608f72017-01-04 13:40:34 +0000720 Opts.StrictReturn = !Args.hasArg(OPT_fno_strict_return);
Piotr Padlewski338c9d02015-09-15 21:46:47 +0000721 Opts.StrictVTablePointers = Args.hasArg(OPT_fstrict_vtable_pointers);
Piotr Padlewskie368de32018-06-13 13:55:42 +0000722 Opts.ForceEmitVTables = Args.hasArg(OPT_fforce_emit_vtables);
Chandler Carruth306bd2c2012-01-02 14:19:45 +0000723 Opts.UnsafeFPMath = Args.hasArg(OPT_menable_unsafe_fp_math) ||
724 Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
Peter Collingbourne61d6a752010-12-04 01:51:23 +0000725 Args.hasArg(OPT_cl_fast_relaxed_math);
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000726 Opts.UnwindTables = Args.hasArg(OPT_munwind_tables);
Davide Italiano1a3665bb2017-04-01 21:07:07 +0000727 Opts.RelocationModel = getRelocModel(Args, Diags);
Jonathan Roelofsb140a102014-10-03 21:57:44 +0000728 Opts.ThreadModel = Args.getLastArgValue(OPT_mthread_model, "posix");
729 if (Opts.ThreadModel != "posix" && Opts.ThreadModel != "single")
730 Diags.Report(diag::err_drv_invalid_value)
731 << Args.getLastArg(OPT_mthread_model)->getAsString(Args)
732 << Opts.ThreadModel;
Bob Wilson14adb362012-02-03 06:27:22 +0000733 Opts.TrapFuncName = Args.getLastArgValue(OPT_ftrap_function_EQ);
Rafael Espindola66aa0452012-06-19 01:26:10 +0000734 Opts.UseInitArray = Args.hasArg(OPT_fuse_init_array);
Daniel Dunbarc70c3932009-12-01 03:16:53 +0000735
Nick Lewycky3a410fe2013-10-11 03:35:10 +0000736 Opts.FunctionSections = Args.hasFlag(OPT_ffunction_sections,
737 OPT_fno_function_sections, false);
738 Opts.DataSections = Args.hasFlag(OPT_fdata_sections,
739 OPT_fno_data_sections, false);
Sean Eveson5110d4f2018-01-08 13:42:26 +0000740 Opts.StackSizeSection =
741 Args.hasFlag(OPT_fstack_size_section, OPT_fno_stack_size_section, false);
Rafael Espindola6b07a1c2015-02-20 18:08:57 +0000742 Opts.UniqueSectionNames = Args.hasFlag(OPT_funique_section_names,
743 OPT_fno_unique_section_names, true);
744
Nick Lewyckyf04f2372014-10-24 00:49:29 +0000745 Opts.MergeFunctions = Args.hasArg(OPT_fmerge_functions);
Chris Lattnerdc6040b2010-04-13 00:38:24 +0000746
Nirav Daved2f44d82016-04-05 17:50:43 +0000747 Opts.NoUseJumpTables = Args.hasArg(OPT_fno_jump_tables);
748
Dehao Chen5e97f232017-08-24 21:37:33 +0000749 Opts.ProfileSampleAccurate = Args.hasArg(OPT_fprofile_sample_accurate);
750
Teresa Johnson945bc502015-10-15 20:35:53 +0000751 Opts.PrepareForLTO = Args.hasArg(OPT_flto, OPT_flto_EQ);
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000752 Opts.PrepareForThinLTO = false;
Yuka Takahashi50a9dfa2017-06-14 15:37:11 +0000753 if (Arg *A = Args.getLastArg(OPT_flto_EQ)) {
754 StringRef S = A->getValue();
755 if (S == "thin")
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000756 Opts.PrepareForThinLTO = true;
Yuka Takahashi50a9dfa2017-06-14 15:37:11 +0000757 else if (S != "full")
758 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << S;
759 }
Peter Collingbourne1e1475a2017-01-18 23:55:27 +0000760 Opts.LTOUnit = Args.hasFlag(OPT_flto_unit, OPT_fno_lto_unit, false);
Teresa Johnsonaff22322015-12-07 19:21:34 +0000761 if (Arg *A = Args.getLastArg(OPT_fthinlto_index_EQ)) {
Richard Smith40c0efa2017-04-26 18:57:40 +0000762 if (IK.getLanguage() != InputKind::LLVM_IR)
Teresa Johnsonaff22322015-12-07 19:21:34 +0000763 Diags.Report(diag::err_drv_argument_only_allowed_with)
764 << A->getAsString(Args) << "-x ir";
765 Opts.ThinLTOIndexFile = Args.getLastArgValue(OPT_fthinlto_index_EQ);
766 }
Teresa Johnson9e4321c2018-04-17 16:39:25 +0000767 if (Arg *A = Args.getLastArg(OPT_save_temps_EQ))
768 Opts.SaveTempsFilePrefix =
769 llvm::StringSwitch<std::string>(A->getValue())
770 .Case("obj", FrontendOpts.OutputFile)
771 .Default(llvm::sys::path::filename(FrontendOpts.OutputFile).str());
772
Teresa Johnson488d1dc2017-03-23 19:47:49 +0000773 Opts.ThinLinkBitcodeFile = Args.getLastArgValue(OPT_fthin_link_bitcode_EQ);
Teresa Johnson8749d8042015-07-06 16:23:00 +0000774
David Majnemera5b195a2015-02-14 01:35:12 +0000775 Opts.MSVolatile = Args.hasArg(OPT_fms_volatile);
776
Nick Lewyckyd3f3e4f2013-06-25 01:49:44 +0000777 Opts.VectorizeLoop = Args.hasArg(OPT_vectorize_loops);
778 Opts.VectorizeSLP = Args.hasArg(OPT_vectorize_slp);
779
Craig Topper9a724aa2017-12-11 21:09:19 +0000780 Opts.PreferVectorWidth = Args.getLastArgValue(OPT_mprefer_vector_width_EQ);
781
Daniel Dunbar37300482010-05-20 16:54:55 +0000782 Opts.MainFileName = Args.getLastArgValue(OPT_main_file_name);
John McCallcfcb7752010-02-12 23:47:27 +0000783 Opts.VerifyModule = !Args.hasArg(OPT_disable_llvm_verifier);
Daniel Dunbarfca18c1b42010-04-24 17:56:46 +0000784
Adrian McCarthydb2736d2018-01-09 23:49:30 +0000785 Opts.ControlFlowGuard = Args.hasArg(OPT_cfguard);
786
Nick Lewyckyc02bbb62013-03-20 01:38:16 +0000787 Opts.DisableGCov = Args.hasArg(OPT_test_coverage);
Nick Lewycky207bce32011-04-21 23:44:07 +0000788 Opts.EmitGcovArcs = Args.hasArg(OPT_femit_coverage_data);
789 Opts.EmitGcovNotes = Args.hasArg(OPT_femit_coverage_notes);
Nick Lewycky737a4522013-03-07 08:28:53 +0000790 if (Opts.EmitGcovArcs || Opts.EmitGcovNotes) {
Nick Lewycky97e49ac2016-08-31 23:04:32 +0000791 Opts.CoverageDataFile = Args.getLastArgValue(OPT_coverage_data_file);
792 Opts.CoverageNotesFile = Args.getLastArgValue(OPT_coverage_notes_file);
Nick Lewycky737a4522013-03-07 08:28:53 +0000793 Opts.CoverageExtraChecksum = Args.hasArg(OPT_coverage_cfg_checksum);
Nick Lewycky6f15b2902013-03-20 02:14:38 +0000794 Opts.CoverageNoFunctionNamesInData =
795 Args.hasArg(OPT_coverage_no_function_names_in_data);
Justin Bogner4e462372015-03-16 23:52:21 +0000796 Opts.CoverageExitBlockBeforeBody =
797 Args.hasArg(OPT_coverage_exit_block_before_body);
Nick Lewycky737a4522013-03-07 08:28:53 +0000798 if (Args.hasArg(OPT_coverage_version_EQ)) {
799 StringRef CoverageVersion = Args.getLastArgValue(OPT_coverage_version_EQ);
800 if (CoverageVersion.size() != 4) {
801 Diags.Report(diag::err_drv_invalid_value)
802 << Args.getLastArg(OPT_coverage_version_EQ)->getAsString(Args)
803 << CoverageVersion;
804 } else {
Nick Lewyckyc8bf8242013-03-14 05:14:01 +0000805 memcpy(Opts.CoverageVersion, CoverageVersion.data(), 4);
Nick Lewycky737a4522013-03-07 08:28:53 +0000806 }
807 }
808 }
Steven Wu27fb5222016-05-11 16:26:03 +0000809 // Handle -fembed-bitcode option.
810 if (Arg *A = Args.getLastArg(OPT_fembed_bitcode_EQ)) {
811 StringRef Name = A->getValue();
812 unsigned Model = llvm::StringSwitch<unsigned>(Name)
813 .Case("off", CodeGenOptions::Embed_Off)
814 .Case("all", CodeGenOptions::Embed_All)
815 .Case("bitcode", CodeGenOptions::Embed_Bitcode)
816 .Case("marker", CodeGenOptions::Embed_Marker)
817 .Default(~0U);
818 if (Model == ~0U) {
819 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
820 Success = false;
821 } else
822 Opts.setEmbedBitcode(
823 static_cast<CodeGenOptions::EmbedBitcodeKind>(Model));
824 }
825 // FIXME: For backend options that are not yet recorded as function
826 // attributes in the IR, keep track of them so we can embed them in a
827 // separate data section and use them when building the bitcode.
828 if (Opts.getEmbedBitcode() == CodeGenOptions::Embed_All) {
829 for (const auto &A : Args) {
830 // Do not encode output and input.
831 if (A->getOption().getID() == options::OPT_o ||
832 A->getOption().getID() == options::OPT_INPUT ||
833 A->getOption().getID() == options::OPT_x ||
834 A->getOption().getID() == options::OPT_fembed_bitcode ||
835 (A->getOption().getGroup().isValid() &&
836 A->getOption().getGroup().getID() == options::OPT_W_Group))
837 continue;
838 ArgStringList ASL;
839 A->render(Args, ASL);
840 for (const auto &arg : ASL) {
841 StringRef ArgStr(arg);
842 Opts.CmdArgs.insert(Opts.CmdArgs.end(), ArgStr.begin(), ArgStr.end());
843 // using \00 to seperate each commandline options.
844 Opts.CmdArgs.push_back('\0');
845 }
846 }
847 }
Nick Lewycky737a4522013-03-07 08:28:53 +0000848
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +0000849 Opts.PreserveVec3Type = Args.hasArg(OPT_fpreserve_vec3_type);
Nick Lewycky737a4522013-03-07 08:28:53 +0000850 Opts.InstrumentFunctions = Args.hasArg(OPT_finstrument_functions);
Hans Wennborg76c26c12017-11-14 21:13:27 +0000851 Opts.InstrumentFunctionsAfterInlining =
852 Args.hasArg(OPT_finstrument_functions_after_inlining);
Hans Wennborg14e8a5a2017-11-21 17:30:34 +0000853 Opts.InstrumentFunctionEntryBare =
854 Args.hasArg(OPT_finstrument_function_entry_bare);
Dean Michael Berris488f7c22018-04-13 02:31:58 +0000855
856 Opts.XRayInstrumentFunctions =
857 Args.hasArg(OPT_fxray_instrument);
Dean Michael Berris1a5b10d2017-11-30 00:04:54 +0000858 Opts.XRayAlwaysEmitCustomEvents =
859 Args.hasArg(OPT_fxray_always_emit_customevents);
Keith Wyssf437e352018-04-17 21:32:43 +0000860 Opts.XRayAlwaysEmitTypedEvents =
861 Args.hasArg(OPT_fxray_always_emit_typedevents);
Aaron Ballman7d2aecb2016-07-13 22:32:15 +0000862 Opts.XRayInstructionThreshold =
Dean Michael Berris504fc222017-03-30 22:46:45 +0000863 getLastArgIntValue(Args, OPT_fxray_instruction_threshold_EQ, 200, Diags);
Dean Michael Berris488f7c22018-04-13 02:31:58 +0000864
865 auto XRayInstrBundles =
866 Args.getAllArgValues(OPT_fxray_instrumentation_bundle);
867 if (XRayInstrBundles.empty())
868 Opts.XRayInstrumentationBundle.Mask = XRayInstrKind::All;
869 else
870 for (const auto &A : XRayInstrBundles)
871 parseXRayInstrumentationBundle("-fxray-instrumentation-bundle=", A, Args,
872 Diags, Opts.XRayInstrumentationBundle);
873
Nick Lewycky737a4522013-03-07 08:28:53 +0000874 Opts.InstrumentForProfiling = Args.hasArg(OPT_pg);
Nirav Dave0c86ccf2017-01-31 17:00:35 +0000875 Opts.CallFEntry = Args.hasArg(OPT_mfentry);
Nick Lewycky737a4522013-03-07 08:28:53 +0000876 Opts.EmitOpenCLArgMetadata = Args.hasArg(OPT_cl_kernel_arg_info);
Saleem Abdulrasoold064e912017-06-23 15:34:16 +0000877
Oren Ben Simhon57cc1a52018-01-09 08:53:59 +0000878 if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
879 StringRef Name = A->getValue();
880 if (Name == "full") {
881 Opts.CFProtectionReturn = 1;
882 Opts.CFProtectionBranch = 1;
883 } else if (Name == "return")
884 Opts.CFProtectionReturn = 1;
885 else if (Name == "branch")
886 Opts.CFProtectionBranch = 1;
887 else if (Name != "none") {
888 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
889 Success = false;
890 }
891 }
892
Saleem Abdulrasoold064e912017-06-23 15:34:16 +0000893 if (const Arg *A = Args.getLastArg(OPT_compress_debug_sections,
894 OPT_compress_debug_sections_EQ)) {
895 if (A->getOption().getID() == OPT_compress_debug_sections) {
896 // TODO: be more clever about the compression type auto-detection
897 Opts.setCompressDebugSections(llvm::DebugCompressionType::GNU);
898 } else {
899 auto DCT = llvm::StringSwitch<llvm::DebugCompressionType>(A->getValue())
900 .Case("none", llvm::DebugCompressionType::None)
901 .Case("zlib", llvm::DebugCompressionType::Z)
902 .Case("zlib-gnu", llvm::DebugCompressionType::GNU)
903 .Default(llvm::DebugCompressionType::None);
904 Opts.setCompressDebugSections(DCT);
905 }
906 }
907
Rafael Espindolaf8f01c32016-05-29 02:01:14 +0000908 Opts.RelaxELFRelocations = Args.hasArg(OPT_mrelax_relocations);
Nick Lewyckyba743b72011-10-21 02:32:14 +0000909 Opts.DebugCompilationDir = Args.getLastArgValue(OPT_fdebug_compilation_dir);
Eugene Zelenko44357ee2018-03-26 21:45:04 +0000910 for (auto *A :
911 Args.filtered(OPT_mlink_bitcode_file, OPT_mlink_cuda_bitcode)) {
Justin Lebarb080b632017-01-25 21:29:48 +0000912 CodeGenOptions::BitcodeFileToLink F;
913 F.Filename = A->getValue();
914 if (A->getOption().matches(OPT_mlink_cuda_bitcode)) {
Jonas Devlieghere5eb9c812017-03-13 18:08:11 +0000915 F.LinkFlags = llvm::Linker::Flags::LinkOnlyNeeded;
Justin Lebarb080b632017-01-25 21:29:48 +0000916 // When linking CUDA bitcode, propagate function attributes so that
917 // e.g. libdevice gets fast-math attrs if we're building with fast-math.
918 F.PropagateAttrs = true;
Jonas Devlieghere5eb9c812017-03-13 18:08:11 +0000919 F.Internalize = true;
Justin Lebarb080b632017-01-25 21:29:48 +0000920 }
921 Opts.LinkBitcodeFiles.push_back(F);
Artem Belevich5d40ae32015-10-27 17:56:59 +0000922 }
Alexey Samsonov3f3b3ab2015-05-07 18:31:29 +0000923 Opts.SanitizeCoverageType =
924 getLastArgIntValue(Args, OPT_fsanitize_coverage_type, 0, Diags);
925 Opts.SanitizeCoverageIndirectCalls =
926 Args.hasArg(OPT_fsanitize_coverage_indirect_calls);
927 Opts.SanitizeCoverageTraceBB = Args.hasArg(OPT_fsanitize_coverage_trace_bb);
928 Opts.SanitizeCoverageTraceCmp = Args.hasArg(OPT_fsanitize_coverage_trace_cmp);
Kostya Serebryany3b419712016-08-30 01:27:03 +0000929 Opts.SanitizeCoverageTraceDiv = Args.hasArg(OPT_fsanitize_coverage_trace_div);
930 Opts.SanitizeCoverageTraceGep = Args.hasArg(OPT_fsanitize_coverage_trace_gep);
Alexey Samsonov3f3b3ab2015-05-07 18:31:29 +0000931 Opts.SanitizeCoverage8bitCounters =
932 Args.hasArg(OPT_fsanitize_coverage_8bit_counters);
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000933 Opts.SanitizeCoverageTracePC = Args.hasArg(OPT_fsanitize_coverage_trace_pc);
Kostya Serebryany60cdd612016-09-14 01:39:49 +0000934 Opts.SanitizeCoverageTracePCGuard =
935 Args.hasArg(OPT_fsanitize_coverage_trace_pc_guard);
Kostya Serebryany50fb6182017-05-05 23:28:18 +0000936 Opts.SanitizeCoverageNoPrune = Args.hasArg(OPT_fsanitize_coverage_no_prune);
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000937 Opts.SanitizeCoverageInline8bitCounters =
938 Args.hasArg(OPT_fsanitize_coverage_inline_8bit_counters);
Kostya Serebryany61457762017-07-28 00:10:10 +0000939 Opts.SanitizeCoveragePCTable = Args.hasArg(OPT_fsanitize_coverage_pc_table);
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000940 Opts.SanitizeCoverageStackDepth =
941 Args.hasArg(OPT_fsanitize_coverage_stack_depth);
Alexey Samsonov29524a92013-01-20 13:12:12 +0000942 Opts.SanitizeMemoryTrackOrigins =
Evgeniy Stepanov2bfcaab2014-03-20 14:58:36 +0000943 getLastArgIntValue(Args, OPT_fsanitize_memory_track_origins_EQ, 0, Diags);
Evgeniy Stepanov45be9e02015-07-10 20:07:16 +0000944 Opts.SanitizeMemoryUseAfterDtor =
Matt Morehousebb26f862017-09-14 23:14:37 +0000945 Args.hasFlag(OPT_fsanitize_memory_use_after_dtor,
946 OPT_fno_sanitize_memory_use_after_dtor,
947 false);
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +0000948 Opts.SanitizeMinimalRuntime = Args.hasArg(OPT_fsanitize_minimal_runtime);
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +0000949 Opts.SanitizeCfiCrossDso = Args.hasArg(OPT_fsanitize_cfi_cross_dso);
Vlad Tsyrklevich634c6012017-10-31 22:39:44 +0000950 Opts.SanitizeCfiICallGeneralizePointers =
951 Args.hasArg(OPT_fsanitize_cfi_icall_generalize_pointers);
Peter Collingbournedc134532016-01-16 00:31:22 +0000952 Opts.SanitizeStats = Args.hasArg(OPT_fsanitize_stats);
Filipe Cabecinhas4ba58172018-02-12 11:49:02 +0000953 if (Arg *A = Args.getLastArg(
954 OPT_fsanitize_address_poison_class_member_array_new_cookie,
955 OPT_fno_sanitize_address_poison_class_member_array_new_cookie)) {
956 Opts.SanitizeAddressPoisonClassMemberArrayNewCookie =
957 A->getOption().getID() ==
958 OPT_fsanitize_address_poison_class_member_array_new_cookie;
959 }
Vitaly Bukaa77ac1b2016-10-10 21:31:50 +0000960 if (Arg *A = Args.getLastArg(OPT_fsanitize_address_use_after_scope,
961 OPT_fno_sanitize_address_use_after_scope)) {
962 Opts.SanitizeAddressUseAfterScope =
963 A->getOption().getID() == OPT_fsanitize_address_use_after_scope;
964 }
Evgeniy Stepanovd991cdd2017-05-09 21:57:43 +0000965 Opts.SanitizeAddressGlobalsDeadStripping =
966 Args.hasArg(OPT_fsanitize_address_globals_dead_stripping);
Chad Rosierdb3da832012-08-21 16:16:06 +0000967 Opts.SSPBufferSize =
Reid Kleckner898229a2013-06-14 17:17:23 +0000968 getLastArgIntValue(Args, OPT_stack_protector_buffer_size, 8, Diags);
Nick Lewyckyf4d3f7a2011-12-06 03:33:03 +0000969 Opts.StackRealignment = Args.hasArg(OPT_mstackrealign);
Joerg Sonnenbergerdb66ed02011-12-05 23:05:23 +0000970 if (Arg *A = Args.getLastArg(OPT_mstack_alignment)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000971 StringRef Val = A->getValue();
Douglas Gregorb0eea8b2012-10-23 20:05:01 +0000972 unsigned StackAlignment = Opts.StackAlignment;
973 Val.getAsInteger(10, StackAlignment);
974 Opts.StackAlignment = StackAlignment;
Joerg Sonnenbergerdb66ed02011-12-05 23:05:23 +0000975 }
Chris Lattner3c77a352010-06-22 00:03:40 +0000976
Hans Wennborg77dc2362015-01-20 19:45:50 +0000977 if (Arg *A = Args.getLastArg(OPT_mstack_probe_size)) {
978 StringRef Val = A->getValue();
979 unsigned StackProbeSize = Opts.StackProbeSize;
980 Val.getAsInteger(0, StackProbeSize);
981 Opts.StackProbeSize = StackProbeSize;
982 }
983
Hans Wennborgd43f40d2018-02-23 13:47:36 +0000984 Opts.NoStackArgProbe = Args.hasArg(OPT_mno_stack_arg_probe);
985
Daniel Dunbarfca18c1b42010-04-24 17:56:46 +0000986 if (Arg *A = Args.getLastArg(OPT_fobjc_dispatch_method_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000987 StringRef Name = A->getValue();
Daniel Dunbarfca18c1b42010-04-24 17:56:46 +0000988 unsigned Method = llvm::StringSwitch<unsigned>(Name)
989 .Case("legacy", CodeGenOptions::Legacy)
990 .Case("non-legacy", CodeGenOptions::NonLegacy)
991 .Case("mixed", CodeGenOptions::Mixed)
992 .Default(~0U);
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000993 if (Method == ~0U) {
Daniel Dunbarfca18c1b42010-04-24 17:56:46 +0000994 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000995 Success = false;
996 } else {
Douglas Gregorb0eea8b2012-10-23 20:05:01 +0000997 Opts.setObjCDispatchMethod(
998 static_cast<CodeGenOptions::ObjCDispatchMethodKind>(Method));
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000999 }
Daniel Dunbarfca18c1b42010-04-24 17:56:46 +00001000 }
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00001001
Chih-Hung Hsiehca552b82018-03-01 22:26:19 +00001002 if (Args.getLastArg(OPT_femulated_tls) ||
1003 Args.getLastArg(OPT_fno_emulated_tls)) {
1004 Opts.ExplicitEmulatedTLS = true;
1005 Opts.EmulatedTLS =
1006 Args.hasFlag(OPT_femulated_tls, OPT_fno_emulated_tls, false);
1007 }
Chih-Hung Hsieh2c656c92015-07-28 16:27:56 +00001008
Hans Wennborgf60f6af2012-06-28 08:01:44 +00001009 if (Arg *A = Args.getLastArg(OPT_ftlsmodel_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001010 StringRef Name = A->getValue();
Hans Wennborgf60f6af2012-06-28 08:01:44 +00001011 unsigned Model = llvm::StringSwitch<unsigned>(Name)
1012 .Case("global-dynamic", CodeGenOptions::GeneralDynamicTLSModel)
1013 .Case("local-dynamic", CodeGenOptions::LocalDynamicTLSModel)
1014 .Case("initial-exec", CodeGenOptions::InitialExecTLSModel)
1015 .Case("local-exec", CodeGenOptions::LocalExecTLSModel)
1016 .Default(~0U);
1017 if (Model == ~0U) {
1018 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
1019 Success = false;
1020 } else {
Douglas Gregorb0eea8b2012-10-23 20:05:01 +00001021 Opts.setDefaultTLSModel(static_cast<CodeGenOptions::TLSModel>(Model));
Hans Wennborgf60f6af2012-06-28 08:01:44 +00001022 }
1023 }
1024
Sjoerd Meijer0a8d4212016-08-30 08:09:45 +00001025 if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_EQ)) {
1026 StringRef Val = A->getValue();
1027 if (Val == "ieee")
1028 Opts.FPDenormalMode = "ieee";
1029 else if (Val == "preserve-sign")
1030 Opts.FPDenormalMode = "preserve-sign";
1031 else if (Val == "positive-zero")
1032 Opts.FPDenormalMode = "positive-zero";
1033 else
1034 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
1035 }
1036
John McCall1fe2a8c2013-06-18 02:46:29 +00001037 if (Arg *A = Args.getLastArg(OPT_fpcc_struct_return, OPT_freg_struct_return)) {
1038 if (A->getOption().matches(OPT_fpcc_struct_return)) {
1039 Opts.setStructReturnConvention(CodeGenOptions::SRCK_OnStack);
1040 } else {
1041 assert(A->getOption().matches(OPT_freg_struct_return));
1042 Opts.setStructReturnConvention(CodeGenOptions::SRCK_InRegs);
1043 }
1044 }
1045
Hans Wennborg75958c42013-08-08 00:17:41 +00001046 Opts.DependentLibraries = Args.getAllArgValues(OPT_dependent_lib);
Peter Collingbournedc134532016-01-16 00:31:22 +00001047 Opts.LinkerOptions = Args.getAllArgValues(OPT_linker_option);
Diego Novillo913690c2014-06-24 17:02:17 +00001048 bool NeedLocTracking = false;
Hans Wennborg75958c42013-08-08 00:17:41 +00001049
Hal Finkel8f96e822016-10-11 00:26:09 +00001050 Opts.OptRecordFile = Args.getLastArgValue(OPT_opt_record_file);
1051 if (!Opts.OptRecordFile.empty())
1052 NeedLocTracking = true;
1053
Diego Novillo913690c2014-06-24 17:02:17 +00001054 if (Arg *A = Args.getLastArg(OPT_Rpass_EQ)) {
Diego Novillod23ec942014-05-29 19:55:06 +00001055 Opts.OptimizationRemarkPattern =
1056 GenerateOptimizationRemarkRegex(Diags, Args, A);
Diego Novillo913690c2014-06-24 17:02:17 +00001057 NeedLocTracking = true;
1058 }
Diego Novillod23ec942014-05-29 19:55:06 +00001059
Diego Novillo913690c2014-06-24 17:02:17 +00001060 if (Arg *A = Args.getLastArg(OPT_Rpass_missed_EQ)) {
Diego Novillod23ec942014-05-29 19:55:06 +00001061 Opts.OptimizationRemarkMissedPattern =
1062 GenerateOptimizationRemarkRegex(Diags, Args, A);
Diego Novillo913690c2014-06-24 17:02:17 +00001063 NeedLocTracking = true;
1064 }
Diego Novillod23ec942014-05-29 19:55:06 +00001065
Diego Novillo913690c2014-06-24 17:02:17 +00001066 if (Arg *A = Args.getLastArg(OPT_Rpass_analysis_EQ)) {
Diego Novillod23ec942014-05-29 19:55:06 +00001067 Opts.OptimizationRemarkAnalysisPattern =
1068 GenerateOptimizationRemarkRegex(Diags, Args, A);
Diego Novillo913690c2014-06-24 17:02:17 +00001069 NeedLocTracking = true;
1070 }
1071
Adam Nemet1eea3e52016-09-13 04:32:40 +00001072 Opts.DiagnosticsWithHotness =
1073 Args.hasArg(options::OPT_fdiagnostics_show_hotness);
Brian Gesiak0ea58882017-06-23 02:38:45 +00001074 bool UsingSampleProfile = !Opts.SampleProfileFile.empty();
Brian Gesiak562eab92017-07-01 05:45:26 +00001075 bool UsingProfile = UsingSampleProfile ||
1076 (Opts.getProfileUse() != CodeGenOptions::ProfileNone);
Brian Gesiak0ea58882017-06-23 02:38:45 +00001077
Teresa Johnson66744f82018-05-05 14:37:29 +00001078 if (Opts.DiagnosticsWithHotness && !UsingProfile &&
1079 // An IR file will contain PGO as metadata
1080 IK.getLanguage() != InputKind::LLVM_IR)
Brian Gesiak562eab92017-07-01 05:45:26 +00001081 Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
1082 << "-fdiagnostics-show-hotness";
1083
1084 Opts.DiagnosticsHotnessThreshold = getLastArgUInt64Value(
1085 Args, options::OPT_fdiagnostics_hotness_threshold_EQ, 0);
1086 if (Opts.DiagnosticsHotnessThreshold > 0 && !UsingProfile)
1087 Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
1088 << "-fdiagnostics-hotness-threshold=";
Adam Nemet1eea3e52016-09-13 04:32:40 +00001089
Diego Novillo795f53b2014-10-22 13:00:05 +00001090 // If the user requested to use a sample profile for PGO, then the
1091 // backend will need to track source location information so the profile
1092 // can be incorporated into the IR.
Brian Gesiak0ea58882017-06-23 02:38:45 +00001093 if (UsingSampleProfile)
Diego Novillo795f53b2014-10-22 13:00:05 +00001094 NeedLocTracking = true;
1095
1096 // If the user requested a flag that requires source locations available in
1097 // the backend, make sure that the backend tracks source location information.
Benjamin Kramer8c305922016-02-02 11:06:51 +00001098 if (NeedLocTracking && Opts.getDebugInfo() == codegenoptions::NoDebugInfo)
1099 Opts.setDebugInfo(codegenoptions::LocTrackingOnly);
Diego Novillod23ec942014-05-29 19:55:06 +00001100
Saleem Abdulrasool76a4b952015-01-09 05:10:20 +00001101 Opts.RewriteMapFiles = Args.getAllArgValues(OPT_frewrite_map_file);
1102
Alexey Samsonov88459522015-01-12 22:39:12 +00001103 // Parse -fsanitize-recover= arguments.
1104 // FIXME: Report unrecoverable sanitizers incorrectly specified here.
1105 parseSanitizerKinds("-fsanitize-recover=",
1106 Args.getAllArgValues(OPT_fsanitize_recover_EQ), Diags,
1107 Opts.SanitizeRecover);
Peter Collingbourne9881b782015-06-18 23:59:22 +00001108 parseSanitizerKinds("-fsanitize-trap=",
1109 Args.getAllArgValues(OPT_fsanitize_trap_EQ), Diags,
1110 Opts.SanitizeTrap);
Alexey Samsonov88459522015-01-12 22:39:12 +00001111
Jonas Hahnfelde7681322018-02-28 17:53:46 +00001112 Opts.CudaGpuBinaryFileName =
1113 Args.getLastArgValue(OPT_fcuda_include_gpubinary);
Artem Belevich52cc4872015-05-07 19:34:16 +00001114
Marcin Koscielnickib31ee6d2016-05-04 23:37:40 +00001115 Opts.Backchain = Args.hasArg(OPT_mbackchain);
1116
Filipe Cabecinhasab731f72016-05-12 16:51:36 +00001117 Opts.EmitCheckPathComponentsToStrip = getLastArgIntValue(
1118 Args, OPT_fsanitize_undefined_strip_path_components_EQ, 0, Diags);
1119
Mikhail Maltsev4a4e7a32018-04-23 10:08:46 +00001120 Opts.EmitVersionIdentMetadata = Args.hasFlag(OPT_Qy, OPT_Qn, true);
1121
Peter Collingbourne14b468b2018-07-18 00:27:07 +00001122 Opts.Addrsig = Args.hasArg(OPT_faddrsig);
1123
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00001124 return Success;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001125}
1126
1127static void ParseDependencyOutputArgs(DependencyOutputOptions &Opts,
1128 ArgList &Args) {
Daniel Dunbar37300482010-05-20 16:54:55 +00001129 Opts.OutputFile = Args.getLastArgValue(OPT_dependency_file);
1130 Opts.Targets = Args.getAllArgValues(OPT_MT);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001131 Opts.IncludeSystemHeaders = Args.hasArg(OPT_sys_header_deps);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00001132 Opts.IncludeModuleFiles = Args.hasArg(OPT_module_file_deps);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001133 Opts.UsePhonyTargets = Args.hasArg(OPT_MP);
Daniel Dunbar27734fd2011-02-02 15:41:17 +00001134 Opts.ShowHeaderIncludes = Args.hasArg(OPT_H);
Daniel Dunbar1af1d27512011-02-02 21:11:31 +00001135 Opts.HeaderIncludeOutputFile = Args.getLastArgValue(OPT_header_include_file);
Peter Collingbourne77b0e7f22011-07-12 19:35:15 +00001136 Opts.AddMissingHeaderDeps = Args.hasArg(OPT_MG);
Erich Keane425f48d2018-05-04 15:58:31 +00001137 if (Args.hasArg(OPT_show_includes)) {
1138 // Writing both /showIncludes and preprocessor output to stdout
1139 // would produce interleaved output, so use stderr for /showIncludes.
1140 // This behaves the same as cl.exe, when /E, /EP or /P are passed.
1141 if (Args.hasArg(options::OPT_E) || Args.hasArg(options::OPT_P))
1142 Opts.ShowIncludesDest = ShowIncludesDestination::Stderr;
1143 else
1144 Opts.ShowIncludesDest = ShowIncludesDestination::Stdout;
1145 } else {
1146 Opts.ShowIncludesDest = ShowIncludesDestination::None;
1147 }
Douglas Gregor2e129652012-02-02 23:45:13 +00001148 Opts.DOTOutputFile = Args.getLastArgValue(OPT_dependency_dot);
Justin Bogner86d12592014-06-19 19:36:03 +00001149 Opts.ModuleDependencyOutputDir =
1150 Args.getLastArgValue(OPT_module_dependency_dir);
Paul Robinsond7214a72015-04-27 18:14:32 +00001151 if (Args.hasArg(OPT_MV))
1152 Opts.OutputFormat = DependencyOutputFormat::NMake;
Ivan Krasin1193f2c2015-08-13 04:04:37 +00001153 // Add sanitizer blacklists as extra dependencies.
1154 // They won't be discovered by the regular preprocessor, so
1155 // we let make / ninja to know about this implicit dependency.
Ivan Krasin4c3f2372015-09-02 20:02:38 +00001156 Opts.ExtraDeps = Args.getAllArgValues(OPT_fdepfile_entry);
Boris Kolpackovd30446f2017-08-31 06:26:43 +00001157 // Only the -fmodule-file=<file> form.
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001158 for (const auto *A : Args.filtered(OPT_fmodule_file)) {
Boris Kolpackovd30446f2017-08-31 06:26:43 +00001159 StringRef Val = A->getValue();
1160 if (Val.find('=') == StringRef::npos)
1161 Opts.ExtraDeps.push_back(Val);
1162 }
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001163}
1164
Bruno Cardoso Lopes681d7172016-05-27 20:43:00 +00001165static bool parseShowColorsArgs(const ArgList &Args, bool DefaultColor) {
1166 // Color diagnostics default to auto ("on" if terminal supports) in the driver
1167 // but default to off in cc1, needing an explicit OPT_fdiagnostics_color.
1168 // Support both clang's -f[no-]color-diagnostics and gcc's
1169 // -f[no-]diagnostics-colors[=never|always|auto].
1170 enum {
1171 Colors_On,
1172 Colors_Off,
1173 Colors_Auto
1174 } ShowColors = DefaultColor ? Colors_Auto : Colors_Off;
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001175 for (auto *A : Args) {
Bruno Cardoso Lopes681d7172016-05-27 20:43:00 +00001176 const Option &O = A->getOption();
Bruno Cardoso Lopes681d7172016-05-27 20:43:00 +00001177 if (O.matches(options::OPT_fcolor_diagnostics) ||
1178 O.matches(options::OPT_fdiagnostics_color)) {
1179 ShowColors = Colors_On;
1180 } else if (O.matches(options::OPT_fno_color_diagnostics) ||
1181 O.matches(options::OPT_fno_diagnostics_color)) {
1182 ShowColors = Colors_Off;
Yaron Keren9181e772016-12-10 14:55:14 +00001183 } else if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
Bruno Cardoso Lopes681d7172016-05-27 20:43:00 +00001184 StringRef Value(A->getValue());
1185 if (Value == "always")
1186 ShowColors = Colors_On;
1187 else if (Value == "never")
1188 ShowColors = Colors_Off;
1189 else if (Value == "auto")
1190 ShowColors = Colors_Auto;
1191 }
1192 }
Yaron Keren9181e772016-12-10 14:55:14 +00001193 return ShowColors == Colors_On ||
1194 (ShowColors == Colors_Auto &&
1195 llvm::sys::Process::StandardErrHasColors());
Bruno Cardoso Lopes681d7172016-05-27 20:43:00 +00001196}
1197
Hal Finkel05e46482017-12-16 02:23:22 +00001198static bool checkVerifyPrefixes(const std::vector<std::string> &VerifyPrefixes,
1199 DiagnosticsEngine *Diags) {
1200 bool Success = true;
1201 for (const auto &Prefix : VerifyPrefixes) {
1202 // Every prefix must start with a letter and contain only alphanumeric
1203 // characters, hyphens, and underscores.
1204 auto BadChar = std::find_if(Prefix.begin(), Prefix.end(),
1205 [](char C){return !isAlphanumeric(C)
1206 && C != '-' && C != '_';});
1207 if (BadChar != Prefix.end() || !isLetter(Prefix[0])) {
1208 Success = false;
1209 if (Diags) {
1210 Diags->Report(diag::err_drv_invalid_value) << "-verify=" << Prefix;
1211 Diags->Report(diag::note_drv_verify_prefix_spelling);
1212 }
1213 }
1214 }
1215 return Success;
1216}
1217
Chad Rosierd6f716a2012-03-13 20:09:56 +00001218bool clang::ParseDiagnosticArgs(DiagnosticOptions &Opts, ArgList &Args,
Bruno Cardoso Lopes681d7172016-05-27 20:43:00 +00001219 DiagnosticsEngine *Diags,
Bruno Cardoso Lopes76952a72016-10-11 18:21:26 +00001220 bool DefaultDiagColor, bool DefaultShowOpt) {
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00001221 bool Success = true;
1222
Daniel Dunbar6b584862011-04-07 18:11:14 +00001223 Opts.DiagnosticLogFile = Args.getLastArgValue(OPT_diagnostic_log_file);
Justin Bogner5a6a2fc2014-10-23 22:20:11 +00001224 if (Arg *A =
1225 Args.getLastArg(OPT_diagnostic_serialized_file, OPT__serialize_diags))
1226 Opts.DiagnosticSerializationFile = A->getValue();
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001227 Opts.IgnoreWarnings = Args.hasArg(OPT_w);
1228 Opts.NoRewriteMacros = Args.hasArg(OPT_Wno_rewrite_macros);
1229 Opts.Pedantic = Args.hasArg(OPT_pedantic);
1230 Opts.PedanticErrors = Args.hasArg(OPT_pedantic_errors);
1231 Opts.ShowCarets = !Args.hasArg(OPT_fno_caret_diagnostics);
Bruno Cardoso Lopes681d7172016-05-27 20:43:00 +00001232 Opts.ShowColors = parseShowColorsArgs(Args, DefaultDiagColor);
Douglas Gregor643c9222011-05-21 17:07:29 +00001233 Opts.ShowColumn = Args.hasFlag(OPT_fshow_column,
1234 OPT_fno_show_column,
1235 /*Default=*/true);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001236 Opts.ShowFixits = !Args.hasArg(OPT_fno_diagnostics_fixit_info);
1237 Opts.ShowLocation = !Args.hasArg(OPT_fno_show_source_location);
Hans Wennborgb30f4372016-08-26 15:45:36 +00001238 Opts.AbsolutePath = Args.hasArg(OPT_fdiagnostics_absolute_paths);
Bruno Cardoso Lopes76952a72016-10-11 18:21:26 +00001239 Opts.ShowOptionNames =
1240 Args.hasFlag(OPT_fdiagnostics_show_option,
1241 OPT_fno_diagnostics_show_option, DefaultShowOpt);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00001242
Nico Rieck7857d462013-09-11 00:38:02 +00001243 llvm::sys::Process::UseANSIEscapeCodes(Args.hasArg(OPT_fansi_escape_codes));
1244
Chandler Carruth24284af2011-03-27 20:00:08 +00001245 // Default behavior is to not to show note include stacks.
1246 Opts.ShowNoteIncludeStack = false;
Chandler Carruthb6766f02011-03-27 01:50:55 +00001247 if (Arg *A = Args.getLastArg(OPT_fdiagnostics_show_note_include_stack,
1248 OPT_fno_diagnostics_show_note_include_stack))
Chandler Carruth24284af2011-03-27 20:00:08 +00001249 if (A->getOption().matches(OPT_fdiagnostics_show_note_include_stack))
1250 Opts.ShowNoteIncludeStack = true;
Chandler Carruthb6766f02011-03-27 01:50:55 +00001251
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001252 StringRef ShowOverloads =
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00001253 Args.getLastArgValue(OPT_fshow_overloads_EQ, "all");
1254 if (ShowOverloads == "best")
Douglas Gregor79591782012-10-23 23:11:23 +00001255 Opts.setShowOverloads(Ovl_Best);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00001256 else if (ShowOverloads == "all")
Douglas Gregor79591782012-10-23 23:11:23 +00001257 Opts.setShowOverloads(Ovl_All);
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00001258 else {
Chad Rosierd6f716a2012-03-13 20:09:56 +00001259 Success = false;
1260 if (Diags)
1261 Diags->Report(diag::err_drv_invalid_value)
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00001262 << Args.getLastArg(OPT_fshow_overloads_EQ)->getAsString(Args)
1263 << ShowOverloads;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00001264 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00001265
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001266 StringRef ShowCategory =
Daniel Dunbar37300482010-05-20 16:54:55 +00001267 Args.getLastArgValue(OPT_fdiagnostics_show_category, "none");
Chris Lattnerbf6fac82010-05-04 21:55:25 +00001268 if (ShowCategory == "none")
1269 Opts.ShowCategories = 0;
1270 else if (ShowCategory == "id")
1271 Opts.ShowCategories = 1;
1272 else if (ShowCategory == "name")
1273 Opts.ShowCategories = 2;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00001274 else {
Chad Rosierd6f716a2012-03-13 20:09:56 +00001275 Success = false;
1276 if (Diags)
1277 Diags->Report(diag::err_drv_invalid_value)
Chris Lattnerbf6fac82010-05-04 21:55:25 +00001278 << Args.getLastArg(OPT_fdiagnostics_show_category)->getAsString(Args)
1279 << ShowCategory;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00001280 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00001281
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001282 StringRef Format =
Douglas Gregor643c9222011-05-21 17:07:29 +00001283 Args.getLastArgValue(OPT_fdiagnostics_format, "clang");
1284 if (Format == "clang")
Douglas Gregor79591782012-10-23 23:11:23 +00001285 Opts.setFormat(DiagnosticOptions::Clang);
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00001286 else if (Format == "msvc")
David Majnemer8ab003a2015-02-02 19:30:52 +00001287 Opts.setFormat(DiagnosticOptions::MSVC);
Hans Wennborgf4aee182013-09-24 00:08:55 +00001288 else if (Format == "msvc-fallback") {
David Majnemer8ab003a2015-02-02 19:30:52 +00001289 Opts.setFormat(DiagnosticOptions::MSVC);
Hans Wennborgf4aee182013-09-24 00:08:55 +00001290 Opts.CLFallbackMode = true;
1291 } else if (Format == "vi")
Douglas Gregor79591782012-10-23 23:11:23 +00001292 Opts.setFormat(DiagnosticOptions::Vi);
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00001293 else {
Chad Rosierd6f716a2012-03-13 20:09:56 +00001294 Success = false;
1295 if (Diags)
1296 Diags->Report(diag::err_drv_invalid_value)
Douglas Gregor643c9222011-05-21 17:07:29 +00001297 << Args.getLastArg(OPT_fdiagnostics_format)->getAsString(Args)
1298 << Format;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00001299 }
Eric Fiselier098e6de2015-06-13 07:11:40 +00001300
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001301 Opts.ShowSourceRanges = Args.hasArg(OPT_fdiagnostics_print_source_range_info);
Douglas Gregoreec975c2010-08-19 20:24:43 +00001302 Opts.ShowParseableFixits = Args.hasArg(OPT_fdiagnostics_parseable_fixits);
Richard Smith0b50cb72012-11-14 23:55:25 +00001303 Opts.ShowPresumedLoc = !Args.hasArg(OPT_fno_diagnostics_use_presumed_location);
Hal Finkel05e46482017-12-16 02:23:22 +00001304 Opts.VerifyDiagnostics = Args.hasArg(OPT_verify) || Args.hasArg(OPT_verify_EQ);
1305 Opts.VerifyPrefixes = Args.getAllArgValues(OPT_verify_EQ);
1306 if (Args.hasArg(OPT_verify))
1307 Opts.VerifyPrefixes.push_back("expected");
1308 // Keep VerifyPrefixes in its original order for the sake of diagnostics, and
1309 // then sort it to prepare for fast lookup using std::binary_search.
1310 if (!checkVerifyPrefixes(Opts.VerifyPrefixes, Diags)) {
1311 Opts.VerifyDiagnostics = false;
1312 Success = false;
1313 }
1314 else
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00001315 llvm::sort(Opts.VerifyPrefixes.begin(), Opts.VerifyPrefixes.end());
Eric Fiselier098e6de2015-06-13 07:11:40 +00001316 DiagnosticLevelMask DiagMask = DiagnosticLevelMask::None;
1317 Success &= parseDiagnosticLevelMask("-verify-ignore-unexpected=",
1318 Args.getAllArgValues(OPT_verify_ignore_unexpected_EQ),
1319 Diags, DiagMask);
1320 if (Args.hasArg(OPT_verify_ignore_unexpected))
1321 DiagMask = DiagnosticLevelMask::All;
1322 Opts.setVerifyIgnoreUnexpected(DiagMask);
Richard Trieu91844232012-06-26 18:18:47 +00001323 Opts.ElideType = !Args.hasArg(OPT_fno_elide_type);
1324 Opts.ShowTemplateTree = Args.hasArg(OPT_fdiagnostics_show_template_tree);
Reid Kleckner898229a2013-06-14 17:17:23 +00001325 Opts.ErrorLimit = getLastArgIntValue(Args, OPT_ferror_limit, 0, Diags);
1326 Opts.MacroBacktraceLimit =
1327 getLastArgIntValue(Args, OPT_fmacro_backtrace_limit,
Douglas Gregorcd121fb2010-05-04 17:13:42 +00001328 DiagnosticOptions::DefaultMacroBacktraceLimit, Diags);
Reid Kleckner898229a2013-06-14 17:17:23 +00001329 Opts.TemplateBacktraceLimit = getLastArgIntValue(
1330 Args, OPT_ftemplate_backtrace_limit,
1331 DiagnosticOptions::DefaultTemplateBacktraceLimit, Diags);
1332 Opts.ConstexprBacktraceLimit = getLastArgIntValue(
1333 Args, OPT_fconstexpr_backtrace_limit,
1334 DiagnosticOptions::DefaultConstexprBacktraceLimit, Diags);
Nick Lewycky24653262014-12-16 21:39:02 +00001335 Opts.SpellCheckingLimit = getLastArgIntValue(
1336 Args, OPT_fspell_checking_limit,
1337 DiagnosticOptions::DefaultSpellCheckingLimit, Diags);
Richard Smith0c7d4d7e2017-05-22 23:51:40 +00001338 Opts.SnippetLineLimit = getLastArgIntValue(
1339 Args, OPT_fcaret_diagnostics_max_lines,
1340 DiagnosticOptions::DefaultSnippetLineLimit, Diags);
Reid Kleckner898229a2013-06-14 17:17:23 +00001341 Opts.TabStop = getLastArgIntValue(Args, OPT_ftabstop,
Chris Lattner3d756f12010-01-13 03:06:50 +00001342 DiagnosticOptions::DefaultTabStop, Diags);
1343 if (Opts.TabStop == 0 || Opts.TabStop > DiagnosticOptions::MaxTabStop) {
Chris Lattner3d756f12010-01-13 03:06:50 +00001344 Opts.TabStop = DiagnosticOptions::DefaultTabStop;
Chad Rosierd6f716a2012-03-13 20:09:56 +00001345 if (Diags)
1346 Diags->Report(diag::warn_ignoring_ftabstop_value)
1347 << Opts.TabStop << DiagnosticOptions::DefaultTabStop;
Chris Lattner3d756f12010-01-13 03:06:50 +00001348 }
Reid Kleckner898229a2013-06-14 17:17:23 +00001349 Opts.MessageLength = getLastArgIntValue(Args, OPT_fmessage_length, 0, Diags);
Richard Smith3be1cb22014-08-07 00:24:21 +00001350 addDiagnosticArgs(Args, OPT_W_Group, OPT_W_value_Group, Opts.Warnings);
1351 addDiagnosticArgs(Args, OPT_R_Group, OPT_R_value_Group, Opts.Remarks);
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00001352
1353 return Success;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001354}
1355
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +00001356static void ParseFileSystemArgs(FileSystemOptions &Opts, ArgList &Args) {
1357 Opts.WorkingDir = Args.getLastArgValue(OPT_working_directory);
1358}
1359
Douglas Gregor6623e1f2015-11-03 18:33:07 +00001360/// Parse the argument to the -ftest-module-file-extension
1361/// command-line argument.
1362///
1363/// \returns true on error, false on success.
1364static bool parseTestModuleFileExtensionArg(StringRef Arg,
1365 std::string &BlockName,
1366 unsigned &MajorVersion,
1367 unsigned &MinorVersion,
1368 bool &Hashed,
1369 std::string &UserInfo) {
1370 SmallVector<StringRef, 5> Args;
1371 Arg.split(Args, ':', 5);
1372 if (Args.size() < 5)
1373 return true;
1374
1375 BlockName = Args[0];
1376 if (Args[1].getAsInteger(10, MajorVersion)) return true;
1377 if (Args[2].getAsInteger(10, MinorVersion)) return true;
1378 if (Args[3].getAsInteger(2, Hashed)) return true;
1379 if (Args.size() > 4)
1380 UserInfo = Args[4];
1381 return false;
1382}
1383
Daniel Dunbar9b491e72010-06-07 23:22:09 +00001384static InputKind ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args,
Erik Verbruggene0bde752016-10-27 14:17:10 +00001385 DiagnosticsEngine &Diags,
1386 bool &IsHeaderFile) {
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001387 Opts.ProgramAction = frontend::ParseSyntaxOnly;
1388 if (const Arg *A = Args.getLastArg(OPT_Action_Group)) {
1389 switch (A->getOption().getID()) {
1390 default:
David Blaikie83d382b2011-09-23 05:06:16 +00001391 llvm_unreachable("Invalid option in group!");
Alexander Kornienko4de03592012-07-31 09:37:40 +00001392 case OPT_ast_list:
1393 Opts.ProgramAction = frontend::ASTDeclList; break;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001394 case OPT_ast_dump:
Richard Smith3a36ac12017-03-09 22:00:01 +00001395 case OPT_ast_dump_all:
Richard Smith35f986d2014-08-11 22:11:07 +00001396 case OPT_ast_dump_lookups:
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001397 Opts.ProgramAction = frontend::ASTDump; break;
1398 case OPT_ast_print:
1399 Opts.ProgramAction = frontend::ASTPrint; break;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001400 case OPT_ast_view:
1401 Opts.ProgramAction = frontend::ASTView; break;
Aaron Ballman16ed8dd2018-05-31 13:57:09 +00001402 case OPT_compiler_options_dump:
1403 Opts.ProgramAction = frontend::DumpCompilerOptions; break;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001404 case OPT_dump_raw_tokens:
1405 Opts.ProgramAction = frontend::DumpRawTokens; break;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001406 case OPT_dump_tokens:
1407 Opts.ProgramAction = frontend::DumpTokens; break;
1408 case OPT_S:
1409 Opts.ProgramAction = frontend::EmitAssembly; break;
1410 case OPT_emit_llvm_bc:
1411 Opts.ProgramAction = frontend::EmitBC; break;
1412 case OPT_emit_html:
1413 Opts.ProgramAction = frontend::EmitHTML; break;
1414 case OPT_emit_llvm:
1415 Opts.ProgramAction = frontend::EmitLLVM; break;
1416 case OPT_emit_llvm_only:
1417 Opts.ProgramAction = frontend::EmitLLVMOnly; break;
Daniel Dunbar4c77a642010-05-25 18:41:01 +00001418 case OPT_emit_codegen_only:
1419 Opts.ProgramAction = frontend::EmitCodeGenOnly; break;
Daniel Dunbar92db0fb2010-02-03 01:18:43 +00001420 case OPT_emit_obj:
1421 Opts.ProgramAction = frontend::EmitObj; break;
Nick Lewycky784fad72010-04-24 01:30:46 +00001422 case OPT_fixit_EQ:
Richard Smithbd55daf2012-11-01 04:30:05 +00001423 Opts.FixItSuffix = A->getValue();
Nick Lewycky784fad72010-04-24 01:30:46 +00001424 // fall-through!
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001425 case OPT_fixit:
1426 Opts.ProgramAction = frontend::FixIt; break;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001427 case OPT_emit_module:
1428 Opts.ProgramAction = frontend::GenerateModule; break;
Richard Smithbbcc9f02016-08-26 00:14:38 +00001429 case OPT_emit_module_interface:
1430 Opts.ProgramAction = frontend::GenerateModuleInterface; break;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001431 case OPT_emit_pch:
1432 Opts.ProgramAction = frontend::GeneratePCH; break;
1433 case OPT_emit_pth:
1434 Opts.ProgramAction = frontend::GeneratePTH; break;
Daniel Dunbar1c201fb2010-03-19 19:44:04 +00001435 case OPT_init_only:
1436 Opts.ProgramAction = frontend::InitOnly; break;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001437 case OPT_fsyntax_only:
1438 Opts.ProgramAction = frontend::ParseSyntaxOnly; break;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00001439 case OPT_module_file_info:
1440 Opts.ProgramAction = frontend::ModuleFileInfo; break;
Ben Langmuir2cb4a782014-02-05 22:21:15 +00001441 case OPT_verify_pch:
1442 Opts.ProgramAction = frontend::VerifyPCH; break;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001443 case OPT_print_decl_contexts:
1444 Opts.ProgramAction = frontend::PrintDeclContext; break;
Douglas Gregoraf82e352010-07-20 20:18:03 +00001445 case OPT_print_preamble:
1446 Opts.ProgramAction = frontend::PrintPreamble; break;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001447 case OPT_E:
1448 Opts.ProgramAction = frontend::PrintPreprocessedInput; break;
Gabor Horvath207e7b12018-02-10 14:04:45 +00001449 case OPT_templight_dump:
1450 Opts.ProgramAction = frontend::TemplightDump; break;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001451 case OPT_rewrite_macros:
1452 Opts.ProgramAction = frontend::RewriteMacros; break;
1453 case OPT_rewrite_objc:
1454 Opts.ProgramAction = frontend::RewriteObjC; break;
1455 case OPT_rewrite_test:
1456 Opts.ProgramAction = frontend::RewriteTest; break;
1457 case OPT_analyze:
1458 Opts.ProgramAction = frontend::RunAnalysis; break;
Ted Kremenekf7639e12012-03-06 20:06:33 +00001459 case OPT_migrate:
1460 Opts.ProgramAction = frontend::MigrateSource; break;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001461 case OPT_Eonly:
1462 Opts.ProgramAction = frontend::RunPreprocessorOnly; break;
1463 }
1464 }
Daniel Dunbar7c995e82010-06-16 16:59:23 +00001465
1466 if (const Arg* A = Args.getLastArg(OPT_plugin)) {
Benjamin Kramer3204b152015-05-29 19:42:19 +00001467 Opts.Plugins.emplace_back(A->getValue(0));
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001468 Opts.ProgramAction = frontend::PluginAction;
Richard Smithbd55daf2012-11-01 04:30:05 +00001469 Opts.ActionName = A->getValue();
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001470 }
Nico Weber2992efa2011-01-25 20:34:14 +00001471 Opts.AddPluginActions = Args.getAllArgValues(OPT_add_plugin);
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001472 for (const auto *AA : Args.filtered(OPT_plugin_arg))
John Brawn6c789742016-03-15 12:51:40 +00001473 Opts.PluginArgs[AA->getValue(0)].emplace_back(AA->getValue(1));
Nico Weber2992efa2011-01-25 20:34:14 +00001474
Douglas Gregor6623e1f2015-11-03 18:33:07 +00001475 for (const std::string &Arg :
1476 Args.getAllArgValues(OPT_ftest_module_file_extension_EQ)) {
1477 std::string BlockName;
1478 unsigned MajorVersion;
1479 unsigned MinorVersion;
1480 bool Hashed;
1481 std::string UserInfo;
1482 if (parseTestModuleFileExtensionArg(Arg, BlockName, MajorVersion,
1483 MinorVersion, Hashed, UserInfo)) {
1484 Diags.Report(diag::err_test_module_file_extension_format) << Arg;
1485
1486 continue;
1487 }
1488
1489 // Add the testing module file extension.
1490 Opts.ModuleFileExtensions.push_back(
David Blaikie61137e12017-01-05 18:23:18 +00001491 std::make_shared<TestModuleFileExtension>(
1492 BlockName, MajorVersion, MinorVersion, Hashed, UserInfo));
Douglas Gregor6623e1f2015-11-03 18:33:07 +00001493 }
1494
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001495 if (const Arg *A = Args.getLastArg(OPT_code_completion_at)) {
1496 Opts.CodeCompletionAt =
Richard Smithbd55daf2012-11-01 04:30:05 +00001497 ParsedSourceLocation::FromString(A->getValue());
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001498 if (Opts.CodeCompletionAt.FileName.empty())
1499 Diags.Report(diag::err_drv_invalid_value)
Richard Smithbd55daf2012-11-01 04:30:05 +00001500 << A->getAsString(Args) << A->getValue();
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001501 }
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001502 Opts.DisableFree = Args.hasArg(OPT_disable_free);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001503
Daniel Dunbar37300482010-05-20 16:54:55 +00001504 Opts.OutputFile = Args.getLastArgValue(OPT_o);
1505 Opts.Plugins = Args.getAllArgValues(OPT_load);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001506 Opts.RelocatablePCH = Args.hasArg(OPT_relocatable_pch);
Daniel Dunbar215ca5f2009-12-03 07:01:58 +00001507 Opts.ShowHelp = Args.hasArg(OPT_help);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001508 Opts.ShowStats = Args.hasArg(OPT_print_stats);
1509 Opts.ShowTimers = Args.hasArg(OPT_ftime_report);
Daniel Dunbar215ca5f2009-12-03 07:01:58 +00001510 Opts.ShowVersion = Args.hasArg(OPT_version);
Daniel Dunbar37300482010-05-20 16:54:55 +00001511 Opts.ASTMergeFiles = Args.getAllArgValues(OPT_ast_merge);
1512 Opts.LLVMArgs = Args.getAllArgValues(OPT_mllvm);
Nick Lewycky078a5e22010-08-13 17:31:00 +00001513 Opts.FixWhatYouCan = Args.hasArg(OPT_fix_what_you_can);
Argyrios Kyrtzidis24e9aff2012-01-26 02:40:48 +00001514 Opts.FixOnlyWarnings = Args.hasArg(OPT_fix_only_warnings);
1515 Opts.FixAndRecompile = Args.hasArg(OPT_fixit_recompile);
1516 Opts.FixToTemporaries = Args.hasArg(OPT_fixit_to_temp);
Richard Smith35f986d2014-08-11 22:11:07 +00001517 Opts.ASTDumpDecls = Args.hasArg(OPT_ast_dump);
Richard Smith3a36ac12017-03-09 22:00:01 +00001518 Opts.ASTDumpAll = Args.hasArg(OPT_ast_dump_all);
Alexander Kornienko3db68ee2012-07-26 16:01:23 +00001519 Opts.ASTDumpFilter = Args.getLastArgValue(OPT_ast_dump_filter);
Richard Smith6ea05822013-06-24 01:45:33 +00001520 Opts.ASTDumpLookups = Args.hasArg(OPT_ast_dump_lookups);
Douglas Gregor137f1b92013-01-28 18:38:02 +00001521 Opts.UseGlobalModuleIndex = !Args.hasArg(OPT_fno_modules_global_index);
Douglas Gregorc1bbec82013-01-25 00:45:27 +00001522 Opts.GenerateGlobalModuleIndex = Opts.UseGlobalModuleIndex;
Richard Smith4a89a062014-12-06 01:13:41 +00001523 Opts.ModuleMapFiles = Args.getAllArgValues(OPT_fmodule_map_file);
Boris Kolpackovd30446f2017-08-31 06:26:43 +00001524 // Only the -fmodule-file=<file> form.
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001525 for (const auto *A : Args.filtered(OPT_fmodule_file)) {
Boris Kolpackovd30446f2017-08-31 06:26:43 +00001526 StringRef Val = A->getValue();
1527 if (Val.find('=') == StringRef::npos)
1528 Opts.ModuleFiles.push_back(Val);
1529 }
Richard Smithfb1e7f72015-08-14 05:02:58 +00001530 Opts.ModulesEmbedFiles = Args.getAllArgValues(OPT_fmodules_embed_file_EQ);
Richard Smith919ce232015-11-24 04:22:21 +00001531 Opts.ModulesEmbedAllFiles = Args.hasArg(OPT_fmodules_embed_all_files);
Pierre Gousseau533a8932016-07-13 14:21:11 +00001532 Opts.IncludeTimestamps = !Args.hasArg(OPT_fno_pch_timestamp);
Richard Smithe842a472014-10-22 02:05:46 +00001533
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001534 Opts.CodeCompleteOpts.IncludeMacros
1535 = Args.hasArg(OPT_code_completion_macros);
1536 Opts.CodeCompleteOpts.IncludeCodePatterns
1537 = Args.hasArg(OPT_code_completion_patterns);
1538 Opts.CodeCompleteOpts.IncludeGlobals
1539 = !Args.hasArg(OPT_no_code_completion_globals);
Eric Liufead6ae2017-12-13 10:26:49 +00001540 Opts.CodeCompleteOpts.IncludeNamespaceLevelDecls
1541 = !Args.hasArg(OPT_no_code_completion_ns_level_decls);
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001542 Opts.CodeCompleteOpts.IncludeBriefComments
1543 = Args.hasArg(OPT_code_completion_brief_comments);
Ivan Donchevskiib4670fc2018-05-25 12:56:26 +00001544 Opts.CodeCompleteOpts.IncludeFixIts
1545 = Args.hasArg(OPT_code_completion_with_fixits);
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001546
Douglas Gregore9fc3772012-01-26 07:55:45 +00001547 Opts.OverrideRecordLayoutsFile
1548 = Args.getLastArgValue(OPT_foverride_record_layout_EQ);
Artem Belevichb5bc9232015-09-22 17:23:22 +00001549 Opts.AuxTriple =
1550 llvm::Triple::normalize(Args.getLastArgValue(OPT_aux_triple));
Matthias Braunabb6eea2016-09-26 18:53:34 +00001551 Opts.StatsFile = Args.getLastArgValue(OPT_stats_file);
Artem Belevichb5bc9232015-09-22 17:23:22 +00001552
John McCalld70fb982011-06-15 23:25:17 +00001553 if (const Arg *A = Args.getLastArg(OPT_arcmt_check,
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +00001554 OPT_arcmt_modify,
1555 OPT_arcmt_migrate)) {
John McCalld70fb982011-06-15 23:25:17 +00001556 switch (A->getOption().getID()) {
1557 default:
1558 llvm_unreachable("missed a case");
1559 case OPT_arcmt_check:
1560 Opts.ARCMTAction = FrontendOptions::ARCMT_Check;
1561 break;
1562 case OPT_arcmt_modify:
1563 Opts.ARCMTAction = FrontendOptions::ARCMT_Modify;
1564 break;
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +00001565 case OPT_arcmt_migrate:
1566 Opts.ARCMTAction = FrontendOptions::ARCMT_Migrate;
1567 break;
John McCalld70fb982011-06-15 23:25:17 +00001568 }
1569 }
Ted Kremenekf7639e12012-03-06 20:06:33 +00001570 Opts.MTMigrateDir = Args.getLastArgValue(OPT_mt_migrate_directory);
Argyrios Kyrtzidisd5713632011-07-19 17:20:03 +00001571 Opts.ARCMTMigrateReportOut
1572 = Args.getLastArgValue(OPT_arcmt_migrate_report_output);
1573 Opts.ARCMTMigrateEmitARCErrors
1574 = Args.hasArg(OPT_arcmt_migrate_emit_arc_errors);
John McCalld70fb982011-06-15 23:25:17 +00001575
Ted Kremenekf7639e12012-03-06 20:06:33 +00001576 if (Args.hasArg(OPT_objcmt_migrate_literals))
1577 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Literals;
1578 if (Args.hasArg(OPT_objcmt_migrate_subscripting))
1579 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Subscripting;
Fariborz Jahaniana6556f72014-10-31 21:19:45 +00001580 if (Args.hasArg(OPT_objcmt_migrate_property_dot_syntax))
1581 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_PropertyDotSyntax;
Fariborz Jahaniand83ef842013-07-09 16:59:14 +00001582 if (Args.hasArg(OPT_objcmt_migrate_property))
1583 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Property;
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +00001584 if (Args.hasArg(OPT_objcmt_migrate_readonly_property))
1585 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_ReadonlyProperty;
Fariborz Jahanianc1213862013-10-02 21:32:39 +00001586 if (Args.hasArg(OPT_objcmt_migrate_readwrite_property))
1587 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_ReadwriteProperty;
Fariborz Jahanian2bfa2b92013-10-02 21:58:13 +00001588 if (Args.hasArg(OPT_objcmt_migrate_annotation))
1589 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Annotation;
Fariborz Jahanian23417072013-11-05 22:28:30 +00001590 if (Args.hasArg(OPT_objcmt_returns_innerpointer_property))
1591 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_ReturnsInnerPointerProperty;
Fariborz Jahanian2bfa2b92013-10-02 21:58:13 +00001592 if (Args.hasArg(OPT_objcmt_migrate_instancetype))
1593 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Instancetype;
1594 if (Args.hasArg(OPT_objcmt_migrate_nsmacros))
1595 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_NsMacros;
1596 if (Args.hasArg(OPT_objcmt_migrate_protocol_conformance))
1597 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_ProtocolConformance;
Fariborz Jahanian20a11242013-10-09 19:06:08 +00001598 if (Args.hasArg(OPT_objcmt_atomic_property))
1599 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_AtomicProperty;
Fariborz Jahanian2e793d62013-11-13 00:08:36 +00001600 if (Args.hasArg(OPT_objcmt_ns_nonatomic_iosonly))
1601 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty;
Argyrios Kyrtzidis4f2ecc62013-12-10 18:36:49 +00001602 if (Args.hasArg(OPT_objcmt_migrate_designated_init))
1603 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_DesignatedInitializer;
Fariborz Jahanianc1213862013-10-02 21:32:39 +00001604 if (Args.hasArg(OPT_objcmt_migrate_all))
1605 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_MigrateDecls;
Ted Kremenekf7639e12012-03-06 20:06:33 +00001606
Argyrios Kyrtzidisd5ba86b2013-12-10 18:36:53 +00001607 Opts.ObjCMTWhiteListPath = Args.getLastArgValue(OPT_objcmt_whitelist_dir_path);
Argyrios Kyrtzidis61f20322013-11-14 16:33:29 +00001608
Ted Kremenekf7639e12012-03-06 20:06:33 +00001609 if (Opts.ARCMTAction != FrontendOptions::ARCMT_None &&
1610 Opts.ObjCMTAction != FrontendOptions::ObjCMT_None) {
1611 Diags.Report(diag::err_drv_argument_not_allowed_with)
1612 << "ARC migration" << "ObjC migration";
1613 }
1614
Richard Smith40c0efa2017-04-26 18:57:40 +00001615 InputKind DashX(InputKind::Unknown);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001616 if (const Arg *A = Args.getLastArg(OPT_x)) {
Richard Smith40c0efa2017-04-26 18:57:40 +00001617 StringRef XValue = A->getValue();
Richard Smithf74d9462017-04-28 01:49:42 +00001618
1619 // Parse suffixes: '<lang>(-header|[-module-map][-cpp-output])'.
1620 // FIXME: Supporting '<lang>-header-cpp-output' would be useful.
1621 bool Preprocessed = XValue.consume_back("-cpp-output");
1622 bool ModuleMap = XValue.consume_back("-module-map");
1623 IsHeaderFile =
1624 !Preprocessed && !ModuleMap && XValue.consume_back("-header");
1625
1626 // Principal languages.
Richard Smith40c0efa2017-04-26 18:57:40 +00001627 DashX = llvm::StringSwitch<InputKind>(XValue)
Richard Smithf74d9462017-04-28 01:49:42 +00001628 .Case("c", InputKind::C)
1629 .Case("cl", InputKind::OpenCL)
1630 .Case("cuda", InputKind::CUDA)
Yaxun Liu887c5692018-04-25 01:10:37 +00001631 .Case("hip", InputKind::HIP)
Richard Smithf74d9462017-04-28 01:49:42 +00001632 .Case("c++", InputKind::CXX)
1633 .Case("objective-c", InputKind::ObjC)
1634 .Case("objective-c++", InputKind::ObjCXX)
1635 .Case("renderscript", InputKind::RenderScript)
1636 .Default(InputKind::Unknown);
1637
1638 // "objc[++]-cpp-output" is an acceptable synonym for
1639 // "objective-c[++]-cpp-output".
1640 if (DashX.isUnknown() && Preprocessed && !IsHeaderFile && !ModuleMap)
1641 DashX = llvm::StringSwitch<InputKind>(XValue)
1642 .Case("objc", InputKind::ObjC)
1643 .Case("objc++", InputKind::ObjCXX)
1644 .Default(InputKind::Unknown);
1645
1646 // Some special cases cannot be combined with suffixes.
1647 if (DashX.isUnknown() && !Preprocessed && !ModuleMap && !IsHeaderFile)
1648 DashX = llvm::StringSwitch<InputKind>(XValue)
1649 .Case("cpp-output", InputKind(InputKind::C).getPreprocessed())
1650 .Case("assembler-with-cpp", InputKind::Asm)
1651 .Cases("ast", "pcm",
1652 InputKind(InputKind::Unknown, InputKind::Precompiled))
1653 .Case("ir", InputKind::LLVM_IR)
1654 .Default(InputKind::Unknown);
1655
Richard Smith40c0efa2017-04-26 18:57:40 +00001656 if (DashX.isUnknown())
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001657 Diags.Report(diag::err_drv_invalid_value)
Richard Smithbd55daf2012-11-01 04:30:05 +00001658 << A->getAsString(Args) << A->getValue();
Richard Smith40c0efa2017-04-26 18:57:40 +00001659
Richard Smithf74d9462017-04-28 01:49:42 +00001660 if (Preprocessed)
Richard Smith40c0efa2017-04-26 18:57:40 +00001661 DashX = DashX.getPreprocessed();
Richard Smithf74d9462017-04-28 01:49:42 +00001662 if (ModuleMap)
1663 DashX = DashX.withFormat(InputKind::ModuleMap);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001664 }
1665
1666 // '-' is the default input if none is given.
Daniel Dunbar37300482010-05-20 16:54:55 +00001667 std::vector<std::string> Inputs = Args.getAllArgValues(OPT_INPUT);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001668 Opts.Inputs.clear();
1669 if (Inputs.empty())
1670 Inputs.push_back("-");
1671 for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
Daniel Dunbar9b491e72010-06-07 23:22:09 +00001672 InputKind IK = DashX;
Richard Smith40c0efa2017-04-26 18:57:40 +00001673 if (IK.isUnknown()) {
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001674 IK = FrontendOptions::getInputKindForExtension(
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001675 StringRef(Inputs[i]).rsplit('.').second);
Richard Smith40c0efa2017-04-26 18:57:40 +00001676 // FIXME: Warn on this?
1677 if (IK.isUnknown())
1678 IK = InputKind::C;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001679 // FIXME: Remove this hack.
1680 if (i == 0)
1681 DashX = IK;
1682 }
Richard Smithf74d9462017-04-28 01:49:42 +00001683
1684 // The -emit-module action implicitly takes a module map.
1685 if (Opts.ProgramAction == frontend::GenerateModule &&
1686 IK.getFormat() == InputKind::Source)
1687 IK = IK.withFormat(InputKind::ModuleMap);
1688
Benjamin Kramer3204b152015-05-29 19:42:19 +00001689 Opts.Inputs.emplace_back(std::move(Inputs[i]), IK);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001690 }
1691
1692 return DashX;
1693}
1694
Daniel Dunbara5a166d2009-12-15 00:06:45 +00001695std::string CompilerInvocation::GetResourcesPath(const char *Argv0,
1696 void *MainAddr) {
Alexey Samsonov6465d4f2014-12-29 21:28:15 +00001697 std::string ClangExecutable =
1698 llvm::sys::fs::getMainExecutable(Argv0, MainAddr);
Chandler Carruthfd3cc702014-12-29 12:09:08 +00001699 StringRef Dir = llvm::sys::path::parent_path(ClangExecutable);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001700
Chandler Carruthfd3cc702014-12-29 12:09:08 +00001701 // Compute the path to the resource directory.
1702 StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
1703 SmallString<128> P(Dir);
Yaron Kerena9107412015-08-05 20:06:56 +00001704 if (ClangResourceDir != "")
Chandler Carruthfd3cc702014-12-29 12:09:08 +00001705 llvm::sys::path::append(P, ClangResourceDir);
Yaron Kerena9107412015-08-05 20:06:56 +00001706 else
1707 llvm::sys::path::append(P, "..", Twine("lib") + CLANG_LIBDIR_SUFFIX,
1708 "clang", CLANG_VERSION_STRING);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001709
1710 return P.str();
1711}
1712
Adrian Prantl0ebdeac2017-03-14 23:07:49 +00001713static void ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args,
1714 const std::string &WorkingDir) {
Daniel Dunbar37300482010-05-20 16:54:55 +00001715 Opts.Sysroot = Args.getLastArgValue(OPT_isysroot, "/");
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001716 Opts.Verbose = Args.hasArg(OPT_v);
Francois Pichet698f0192011-10-10 20:34:10 +00001717 Opts.UseBuiltinIncludes = !Args.hasArg(OPT_nobuiltininc);
Daniel Dunbarb25bfde2011-10-11 18:20:10 +00001718 Opts.UseStandardSystemIncludes = !Args.hasArg(OPT_nostdsysteminc);
Douglas Gregor64b046f2010-03-24 20:13:48 +00001719 Opts.UseStandardCXXIncludes = !Args.hasArg(OPT_nostdincxx);
Bob Wilsonb02ea3d2011-06-21 21:12:29 +00001720 if (const Arg *A = Args.getLastArg(OPT_stdlib_EQ))
Richard Smithbd55daf2012-11-01 04:30:05 +00001721 Opts.UseLibcxx = (strcmp(A->getValue(), "libc++") == 0);
Daniel Dunbar37300482010-05-20 16:54:55 +00001722 Opts.ResourceDir = Args.getLastArgValue(OPT_resource_dir);
Adrian Prantl0ebdeac2017-03-14 23:07:49 +00001723
1724 // Canonicalize -fmodules-cache-path before storing it.
1725 SmallString<128> P(Args.getLastArgValue(OPT_fmodules_cache_path));
1726 if (!(P.empty() || llvm::sys::path::is_absolute(P))) {
1727 if (WorkingDir.empty())
1728 llvm::sys::fs::make_absolute(P);
1729 else
1730 llvm::sys::fs::make_absolute(WorkingDir, P);
1731 }
1732 llvm::sys::path::remove_dots(P);
1733 Opts.ModuleCachePath = P.str();
1734
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00001735 Opts.ModuleUserBuildPath = Args.getLastArgValue(OPT_fmodules_user_build_path);
Boris Kolpackovd30446f2017-08-31 06:26:43 +00001736 // Only the -fmodule-file=<name>=<file> form.
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001737 for (const auto *A : Args.filtered(OPT_fmodule_file)) {
Boris Kolpackovd30446f2017-08-31 06:26:43 +00001738 StringRef Val = A->getValue();
1739 if (Val.find('=') != StringRef::npos)
1740 Opts.PrebuiltModuleFiles.insert(Val.split('='));
1741 }
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001742 for (const auto *A : Args.filtered(OPT_fprebuilt_module_path))
Manman Ren11f2a472016-08-18 17:42:15 +00001743 Opts.AddPrebuiltModulePath(A->getValue());
Douglas Gregor1735f4e2011-09-13 23:15:45 +00001744 Opts.DisableModuleHash = Args.hasArg(OPT_fdisable_module_hash);
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00001745 Opts.ModulesHashContent = Args.hasArg(OPT_fmodules_hash_content);
Manman Ren47a44452016-07-26 17:12:17 +00001746 Opts.ModulesValidateDiagnosticOptions =
1747 !Args.hasArg(OPT_fmodules_disable_diagnostic_validation);
Richard Smith47972af2015-06-16 00:08:24 +00001748 Opts.ImplicitModuleMaps = Args.hasArg(OPT_fimplicit_module_maps);
Richard Smith9acb99e32014-12-10 03:09:48 +00001749 Opts.ModuleMapFileHomeIsCwd = Args.hasArg(OPT_fmodule_map_file_home_is_cwd);
Reid Kleckner898229a2013-06-14 17:17:23 +00001750 Opts.ModuleCachePruneInterval =
1751 getLastArgIntValue(Args, OPT_fmodules_prune_interval, 7 * 24 * 60 * 60);
1752 Opts.ModuleCachePruneAfter =
1753 getLastArgIntValue(Args, OPT_fmodules_prune_after, 31 * 24 * 60 * 60);
Dmitri Gribenkof430da42014-02-12 10:33:14 +00001754 Opts.ModulesValidateOncePerBuildSession =
1755 Args.hasArg(OPT_fmodules_validate_once_per_build_session);
1756 Opts.BuildSessionTimestamp =
1757 getLastArgUInt64Value(Args, OPT_fbuild_session_timestamp, 0);
Ben Langmuirdcf73862014-03-12 00:06:17 +00001758 Opts.ModulesValidateSystemHeaders =
1759 Args.hasArg(OPT_fmodules_validate_system_headers);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00001760 if (const Arg *A = Args.getLastArg(OPT_fmodule_format_EQ))
1761 Opts.ModuleFormat = A->getValue();
Ben Langmuirdcf73862014-03-12 00:06:17 +00001762
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001763 for (const auto *A : Args.filtered(OPT_fmodules_ignore_macro)) {
Sean Silva14facf32015-06-09 01:57:17 +00001764 StringRef MacroDef = A->getValue();
Justin Lebar5e83dfe2016-10-21 21:45:01 +00001765 Opts.ModulesIgnoreMacros.insert(
1766 llvm::CachedHashString(MacroDef.split('=').first));
Douglas Gregor5dc38992013-02-07 00:21:12 +00001767 }
1768
Douglas Gregor9f93e382011-07-28 04:45:53 +00001769 // Add -I..., -F..., and -index-header-map options in order.
1770 bool IsIndexHeaderMap = false;
Saleem Abdulrasoolde87e5f2016-05-06 19:13:55 +00001771 bool IsSysrootSpecified =
1772 Args.hasArg(OPT__sysroot_EQ) || Args.hasArg(OPT_isysroot);
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001773 for (const auto *A : Args.filtered(OPT_I, OPT_F, OPT_index_header_map)) {
Sean Silva14facf32015-06-09 01:57:17 +00001774 if (A->getOption().matches(OPT_index_header_map)) {
Douglas Gregor9f93e382011-07-28 04:45:53 +00001775 // -index-header-map applies to the next -I or -F.
1776 IsIndexHeaderMap = true;
1777 continue;
1778 }
Sean Silva14facf32015-06-09 01:57:17 +00001779
1780 frontend::IncludeDirGroup Group =
1781 IsIndexHeaderMap ? frontend::IndexHeaderMap : frontend::Angled;
1782
Saleem Abdulrasoolde87e5f2016-05-06 19:13:55 +00001783 bool IsFramework = A->getOption().matches(OPT_F);
1784 std::string Path = A->getValue();
1785
1786 if (IsSysrootSpecified && !IsFramework && A->getValue()[0] == '=') {
1787 SmallString<32> Buffer;
1788 llvm::sys::path::append(Buffer, Opts.Sysroot,
1789 llvm::StringRef(A->getValue()).substr(1));
1790 Path = Buffer.str();
1791 }
1792
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00001793 Opts.AddPath(Path, Group, IsFramework,
Saleem Abdulrasoolde87e5f2016-05-06 19:13:55 +00001794 /*IgnoreSysroot*/ true);
Douglas Gregor9f93e382011-07-28 04:45:53 +00001795 IsIndexHeaderMap = false;
1796 }
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001797
Daniel Dunbarc9c57e92013-01-25 01:50:34 +00001798 // Add -iprefix/-iwithprefix/-iwithprefixbefore options.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001799 StringRef Prefix = ""; // FIXME: This isn't the correct default prefix.
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001800 for (const auto *A :
Sean Silva14facf32015-06-09 01:57:17 +00001801 Args.filtered(OPT_iprefix, OPT_iwithprefix, OPT_iwithprefixbefore)) {
Daniel Dunbara442fd52010-06-11 22:00:13 +00001802 if (A->getOption().matches(OPT_iprefix))
Richard Smithbd55daf2012-11-01 04:30:05 +00001803 Prefix = A->getValue();
Daniel Dunbara442fd52010-06-11 22:00:13 +00001804 else if (A->getOption().matches(OPT_iwithprefix))
Sean Silva14facf32015-06-09 01:57:17 +00001805 Opts.AddPath(Prefix.str() + A->getValue(), frontend::After, false, true);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001806 else
Sean Silva14facf32015-06-09 01:57:17 +00001807 Opts.AddPath(Prefix.str() + A->getValue(), frontend::Angled, false, true);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00001808 }
1809
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001810 for (const auto *A : Args.filtered(OPT_idirafter))
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001811 Opts.AddPath(A->getValue(), frontend::After, false, true);
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001812 for (const auto *A : Args.filtered(OPT_iquote))
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001813 Opts.AddPath(A->getValue(), frontend::Quoted, false, true);
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001814 for (const auto *A : Args.filtered(OPT_isystem, OPT_iwithsysroot))
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001815 Opts.AddPath(A->getValue(), frontend::System, false,
1816 !A->getOption().matches(OPT_iwithsysroot));
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001817 for (const auto *A : Args.filtered(OPT_iframework))
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001818 Opts.AddPath(A->getValue(), frontend::System, true, true);
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001819 for (const auto *A : Args.filtered(OPT_iframeworkwithsysroot))
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001820 Opts.AddPath(A->getValue(), frontend::System, /*IsFramework=*/true,
1821 /*IgnoreSysRoot=*/false);
1822
1823 // Add the paths for the various language specific isystem flags.
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001824 for (const auto *A : Args.filtered(OPT_c_isystem))
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001825 Opts.AddPath(A->getValue(), frontend::CSystem, false, true);
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001826 for (const auto *A : Args.filtered(OPT_cxx_isystem))
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001827 Opts.AddPath(A->getValue(), frontend::CXXSystem, false, true);
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001828 for (const auto *A : Args.filtered(OPT_objc_isystem))
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001829 Opts.AddPath(A->getValue(), frontend::ObjCSystem, false,true);
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001830 for (const auto *A : Args.filtered(OPT_objcxx_isystem))
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001831 Opts.AddPath(A->getValue(), frontend::ObjCXXSystem, false, true);
1832
1833 // Add the internal paths from a driver that detects standard include paths.
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001834 for (const auto *A :
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001835 Args.filtered(OPT_internal_isystem, OPT_internal_externc_isystem)) {
1836 frontend::IncludeDirGroup Group = frontend::System;
1837 if (A->getOption().matches(OPT_internal_externc_isystem))
1838 Group = frontend::ExternCSystem;
1839 Opts.AddPath(A->getValue(), Group, false, true);
1840 }
1841
1842 // Add the path prefixes which are implicitly treated as being system headers.
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001843 for (const auto *A :
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001844 Args.filtered(OPT_system_header_prefix, OPT_no_system_header_prefix))
1845 Opts.AddSystemHeaderPrefix(
1846 A->getValue(), A->getOption().matches(OPT_system_header_prefix));
1847
Eugene Zelenko44357ee2018-03-26 21:45:04 +00001848 for (const auto *A : Args.filtered(OPT_ivfsoverlay))
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001849 Opts.AddVFSOverlayFile(A->getValue());
1850}
1851
1852void CompilerInvocation::setLangDefaults(LangOptions &Opts, InputKind IK,
1853 const llvm::Triple &T,
1854 PreprocessorOptions &PPOpts,
1855 LangStandard::Kind LangStd) {
1856 // Set some properties which depend solely on the input kind; it would be nice
1857 // to move these to the language standard, and have the driver resolve the
1858 // input kind + language standard.
1859 //
1860 // FIXME: Perhaps a better model would be for a single source file to have
1861 // multiple language standards (C / C++ std, ObjC std, OpenCL std, OpenMP std)
1862 // simultaneously active?
1863 if (IK.getLanguage() == InputKind::Asm) {
1864 Opts.AsmPreprocessor = 1;
1865 } else if (IK.isObjectiveC()) {
1866 Opts.ObjC1 = Opts.ObjC2 = 1;
1867 }
1868
1869 if (LangStd == LangStandard::lang_unspecified) {
1870 // Based on the base language, pick one.
1871 switch (IK.getLanguage()) {
1872 case InputKind::Unknown:
1873 case InputKind::LLVM_IR:
1874 llvm_unreachable("Invalid input kind!");
1875 case InputKind::OpenCL:
1876 LangStd = LangStandard::lang_opencl10;
1877 break;
1878 case InputKind::CUDA:
1879 LangStd = LangStandard::lang_cuda;
1880 break;
1881 case InputKind::Asm:
1882 case InputKind::C:
Michal Gorny4289f4c2018-03-06 21:26:28 +00001883#if defined(CLANG_DEFAULT_STD_C)
1884 LangStd = CLANG_DEFAULT_STD_C;
1885#else
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001886 // The PS4 uses C99 as the default C standard.
1887 if (T.isPS4())
1888 LangStd = LangStandard::lang_gnu99;
1889 else
1890 LangStd = LangStandard::lang_gnu11;
Michal Gorny4289f4c2018-03-06 21:26:28 +00001891#endif
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001892 break;
1893 case InputKind::ObjC:
Michal Gorny4289f4c2018-03-06 21:26:28 +00001894#if defined(CLANG_DEFAULT_STD_C)
1895 LangStd = CLANG_DEFAULT_STD_C;
1896#else
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001897 LangStd = LangStandard::lang_gnu11;
Michal Gorny4289f4c2018-03-06 21:26:28 +00001898#endif
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001899 break;
1900 case InputKind::CXX:
1901 case InputKind::ObjCXX:
Michal Gorny4289f4c2018-03-06 21:26:28 +00001902#if defined(CLANG_DEFAULT_STD_CXX)
1903 LangStd = CLANG_DEFAULT_STD_CXX;
1904#else
Tim Northover36bb6d52017-12-09 12:09:54 +00001905 LangStd = LangStandard::lang_gnucxx14;
Michal Gorny4289f4c2018-03-06 21:26:28 +00001906#endif
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001907 break;
1908 case InputKind::RenderScript:
1909 LangStd = LangStandard::lang_c99;
1910 break;
Yaxun Liu887c5692018-04-25 01:10:37 +00001911 case InputKind::HIP:
1912 LangStd = LangStandard::lang_hip;
1913 break;
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001914 }
1915 }
1916
1917 const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
1918 Opts.LineComment = Std.hasLineComments();
1919 Opts.C99 = Std.isC99();
1920 Opts.C11 = Std.isC11();
1921 Opts.C17 = Std.isC17();
1922 Opts.CPlusPlus = Std.isCPlusPlus();
1923 Opts.CPlusPlus11 = Std.isCPlusPlus11();
1924 Opts.CPlusPlus14 = Std.isCPlusPlus14();
1925 Opts.CPlusPlus17 = Std.isCPlusPlus17();
1926 Opts.CPlusPlus2a = Std.isCPlusPlus2a();
1927 Opts.Digraphs = Std.hasDigraphs();
1928 Opts.GNUMode = Std.isGNUMode();
1929 Opts.GNUInline = !Opts.C99 && !Opts.CPlusPlus;
1930 Opts.HexFloats = Std.hasHexFloats();
1931 Opts.ImplicitInt = Std.hasImplicitInt();
1932
1933 // Set OpenCL Version.
1934 Opts.OpenCL = Std.isOpenCL();
1935 if (LangStd == LangStandard::lang_opencl10)
1936 Opts.OpenCLVersion = 100;
1937 else if (LangStd == LangStandard::lang_opencl11)
1938 Opts.OpenCLVersion = 110;
1939 else if (LangStd == LangStandard::lang_opencl12)
1940 Opts.OpenCLVersion = 120;
1941 else if (LangStd == LangStandard::lang_opencl20)
1942 Opts.OpenCLVersion = 200;
Anastasia Stulovac645f612018-04-12 14:17:04 +00001943 else if (LangStd == LangStandard::lang_openclcpp)
1944 Opts.OpenCLCPlusPlusVersion = 100;
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001945
1946 // OpenCL has some additional defaults.
1947 if (Opts.OpenCL) {
1948 Opts.AltiVec = 0;
1949 Opts.ZVector = 0;
1950 Opts.LaxVectorConversions = 0;
1951 Opts.setDefaultFPContractMode(LangOptions::FPC_On);
1952 Opts.NativeHalfType = 1;
1953 Opts.NativeHalfArgsAndReturns = 1;
Sven van Haastregt49ffffb2018-04-23 11:23:47 +00001954 Opts.OpenCLCPlusPlus = Opts.CPlusPlus;
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001955 // Include default header file for OpenCL.
1956 if (Opts.IncludeDefaultHeader) {
1957 PPOpts.Includes.push_back("opencl-c.h");
1958 }
1959 }
1960
Yaxun Liu887c5692018-04-25 01:10:37 +00001961 Opts.HIP = IK.getLanguage() == InputKind::HIP;
1962 Opts.CUDA = IK.getLanguage() == InputKind::CUDA || Opts.HIP;
Aaron Ballman29dc5de2017-12-07 23:04:11 +00001963 if (Opts.CUDA)
1964 // Set default FP_CONTRACT to FAST.
1965 Opts.setDefaultFPContractMode(LangOptions::FPC_Fast);
1966
1967 Opts.RenderScript = IK.getLanguage() == InputKind::RenderScript;
1968 if (Opts.RenderScript) {
1969 Opts.NativeHalfType = 1;
1970 Opts.NativeHalfArgsAndReturns = 1;
1971 }
1972
1973 // OpenCL and C++ both have bool, true, false keywords.
1974 Opts.Bool = Opts.OpenCL || Opts.CPlusPlus;
1975
1976 // OpenCL has half keyword
1977 Opts.Half = Opts.OpenCL;
1978
1979 // C++ has wchar_t keyword.
1980 Opts.WChar = Opts.CPlusPlus;
1981
1982 Opts.GNUKeywords = Opts.GNUMode;
1983 Opts.CXXOperatorNames = Opts.CPlusPlus;
1984
1985 Opts.AlignedAllocation = Opts.CPlusPlus17;
1986
1987 Opts.DollarIdents = !Opts.AsmPreprocessor;
1988}
1989
1990/// Attempt to parse a visibility value out of the given argument.
1991static Visibility parseVisibility(Arg *arg, ArgList &args,
1992 DiagnosticsEngine &diags) {
1993 StringRef value = arg->getValue();
1994 if (value == "default") {
1995 return DefaultVisibility;
1996 } else if (value == "hidden" || value == "internal") {
1997 return HiddenVisibility;
1998 } else if (value == "protected") {
1999 // FIXME: diagnose if target does not support protected visibility
2000 return ProtectedVisibility;
2001 }
2002
2003 diags.Report(diag::err_drv_invalid_value)
2004 << arg->getAsString(args) << value;
2005 return DefaultVisibility;
2006}
2007
2008/// Check if input file kind and language standard are compatible.
2009static bool IsInputCompatibleWithStandard(InputKind IK,
2010 const LangStandard &S) {
2011 switch (IK.getLanguage()) {
2012 case InputKind::Unknown:
2013 case InputKind::LLVM_IR:
2014 llvm_unreachable("should not parse language flags for this input");
2015
2016 case InputKind::C:
2017 case InputKind::ObjC:
2018 case InputKind::RenderScript:
2019 return S.getLanguage() == InputKind::C;
2020
2021 case InputKind::OpenCL:
2022 return S.getLanguage() == InputKind::OpenCL;
2023
2024 case InputKind::CXX:
2025 case InputKind::ObjCXX:
Richard Smithb0fe7042017-04-26 23:44:33 +00002026 return S.getLanguage() == InputKind::CXX;
Richard Smith40c0efa2017-04-26 18:57:40 +00002027
2028 case InputKind::CUDA:
Richard Smithb0fe7042017-04-26 23:44:33 +00002029 // FIXME: What -std= values should be permitted for CUDA compilations?
2030 return S.getLanguage() == InputKind::CUDA ||
2031 S.getLanguage() == InputKind::CXX;
Richard Smith40c0efa2017-04-26 18:57:40 +00002032
Yaxun Liu887c5692018-04-25 01:10:37 +00002033 case InputKind::HIP:
2034 return S.getLanguage() == InputKind::CXX ||
2035 S.getLanguage() == InputKind::HIP;
2036
Richard Smith40c0efa2017-04-26 18:57:40 +00002037 case InputKind::Asm:
2038 // Accept (and ignore) all -std= values.
2039 // FIXME: The -std= value is not ignored; it affects the tokenization
2040 // and preprocessing rules if we're preprocessing this asm input.
Richard Smith222b30b2017-02-14 23:41:38 +00002041 return true;
Richard Smithc91daf12017-02-14 22:44:20 +00002042 }
Richard Smith40c0efa2017-04-26 18:57:40 +00002043
2044 llvm_unreachable("unexpected input language");
Richard Smithc91daf12017-02-14 22:44:20 +00002045}
2046
2047/// Get language name for given input kind.
2048static const StringRef GetInputKindName(InputKind IK) {
Richard Smith40c0efa2017-04-26 18:57:40 +00002049 switch (IK.getLanguage()) {
2050 case InputKind::C:
Richard Smithb0fe7042017-04-26 23:44:33 +00002051 return "C";
Richard Smith40c0efa2017-04-26 18:57:40 +00002052 case InputKind::ObjC:
Richard Smithb0fe7042017-04-26 23:44:33 +00002053 return "Objective-C";
Richard Smith40c0efa2017-04-26 18:57:40 +00002054 case InputKind::CXX:
Richard Smithb0fe7042017-04-26 23:44:33 +00002055 return "C++";
Richard Smith40c0efa2017-04-26 18:57:40 +00002056 case InputKind::ObjCXX:
Richard Smithb0fe7042017-04-26 23:44:33 +00002057 return "Objective-C++";
Richard Smith40c0efa2017-04-26 18:57:40 +00002058 case InputKind::OpenCL:
Richard Smithc91daf12017-02-14 22:44:20 +00002059 return "OpenCL";
Richard Smith40c0efa2017-04-26 18:57:40 +00002060 case InputKind::CUDA:
Richard Smithc91daf12017-02-14 22:44:20 +00002061 return "CUDA";
Richard Smithb0fe7042017-04-26 23:44:33 +00002062 case InputKind::RenderScript:
2063 return "RenderScript";
Yaxun Liu887c5692018-04-25 01:10:37 +00002064 case InputKind::HIP:
2065 return "HIP";
Richard Smithb0fe7042017-04-26 23:44:33 +00002066
2067 case InputKind::Asm:
2068 return "Asm";
2069 case InputKind::LLVM_IR:
2070 return "LLVM IR";
2071
2072 case InputKind::Unknown:
2073 break;
Richard Smithc91daf12017-02-14 22:44:20 +00002074 }
Richard Smithb0fe7042017-04-26 23:44:33 +00002075 llvm_unreachable("unknown input language");
Richard Smithc91daf12017-02-14 22:44:20 +00002076}
2077
Peter Collingbourneaaeb73b2010-12-04 01:50:27 +00002078static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK,
Samuel Antao45bfe4c2016-02-08 15:59:20 +00002079 const TargetOptions &TargetOpts,
Yaxun Liu143f0832016-06-20 19:26:00 +00002080 PreprocessorOptions &PPOpts,
David Blaikie9c902b52011-09-25 23:23:43 +00002081 DiagnosticsEngine &Diags) {
Peter Collingbourneaaeb73b2010-12-04 01:50:27 +00002082 // FIXME: Cleanup per-file based stuff.
2083 LangStandard::Kind LangStd = LangStandard::lang_unspecified;
2084 if (const Arg *A = Args.getLastArg(OPT_std_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00002085 LangStd = llvm::StringSwitch<LangStandard::Kind>(A->getValue())
Richard Smithb0fe7042017-04-26 23:44:33 +00002086#define LANGSTANDARD(id, name, lang, desc, features) \
Peter Collingbourneaaeb73b2010-12-04 01:50:27 +00002087 .Case(name, LangStandard::lang_##id)
Yaxun Liub5044fe2016-06-17 17:19:28 +00002088#define LANGSTANDARD_ALIAS(id, alias) \
2089 .Case(alias, LangStandard::lang_##id)
Peter Collingbourneaaeb73b2010-12-04 01:50:27 +00002090#include "clang/Frontend/LangStandards.def"
2091 .Default(LangStandard::lang_unspecified);
Richard Smithc91daf12017-02-14 22:44:20 +00002092 if (LangStd == LangStandard::lang_unspecified) {
Peter Collingbourneaaeb73b2010-12-04 01:50:27 +00002093 Diags.Report(diag::err_drv_invalid_value)
Richard Smithbd55daf2012-11-01 04:30:05 +00002094 << A->getAsString(Args) << A->getValue();
Richard Smithc91daf12017-02-14 22:44:20 +00002095 // Report supported standards with short description.
2096 for (unsigned KindValue = 0;
2097 KindValue != LangStandard::lang_unspecified;
2098 ++KindValue) {
2099 const LangStandard &Std = LangStandard::getLangStandardForKind(
2100 static_cast<LangStandard::Kind>(KindValue));
2101 if (IsInputCompatibleWithStandard(IK, Std)) {
Richard Smith8c8fb802017-04-27 01:17:05 +00002102 auto Diag = Diags.Report(diag::note_drv_use_standard);
2103 Diag << Std.getName() << Std.getDescription();
2104 unsigned NumAliases = 0;
2105#define LANGSTANDARD(id, name, lang, desc, features)
2106#define LANGSTANDARD_ALIAS(id, alias) \
2107 if (KindValue == LangStandard::lang_##id) ++NumAliases;
2108#define LANGSTANDARD_ALIAS_DEPR(id, alias)
2109#include "clang/Frontend/LangStandards.def"
2110 Diag << NumAliases;
2111#define LANGSTANDARD(id, name, lang, desc, features)
2112#define LANGSTANDARD_ALIAS(id, alias) \
2113 if (KindValue == LangStandard::lang_##id) Diag << alias;
2114#define LANGSTANDARD_ALIAS_DEPR(id, alias)
2115#include "clang/Frontend/LangStandards.def"
Richard Smithc91daf12017-02-14 22:44:20 +00002116 }
2117 }
2118 } else {
Alp Tokerf6a24ce2013-12-05 16:25:25 +00002119 // Valid standard, check to make sure language and standard are
2120 // compatible.
Chad Rosier24874a42011-05-02 19:24:53 +00002121 const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
Richard Smithc91daf12017-02-14 22:44:20 +00002122 if (!IsInputCompatibleWithStandard(IK, Std)) {
2123 Diags.Report(diag::err_drv_argument_not_allowed_with)
2124 << A->getAsString(Args) << GetInputKindName(IK);
Chad Rosier24874a42011-05-02 19:24:53 +00002125 }
2126 }
Peter Collingbourneaaeb73b2010-12-04 01:50:27 +00002127 }
2128
Oren Ben Simhon220671a2018-03-17 13:31:35 +00002129 if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
2130 StringRef Name = A->getValue();
2131 if (Name == "full" || Name == "branch") {
2132 Opts.CFProtectionBranch = 1;
2133 }
2134 }
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00002135 // -cl-std only applies for OpenCL language standards.
2136 // Override the -std option in this case.
Peter Collingbournefafa6652010-12-04 01:51:40 +00002137 if (const Arg *A = Args.getLastArg(OPT_cl_std_EQ)) {
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00002138 LangStandard::Kind OpenCLLangStd
Richard Smithc91daf12017-02-14 22:44:20 +00002139 = llvm::StringSwitch<LangStandard::Kind>(A->getValue())
Richard Smith8c8fb802017-04-27 01:17:05 +00002140 .Cases("cl", "CL", LangStandard::lang_opencl10)
Richard Smithc91daf12017-02-14 22:44:20 +00002141 .Cases("cl1.1", "CL1.1", LangStandard::lang_opencl11)
2142 .Cases("cl1.2", "CL1.2", LangStandard::lang_opencl12)
2143 .Cases("cl2.0", "CL2.0", LangStandard::lang_opencl20)
Anastasia Stulovac645f612018-04-12 14:17:04 +00002144 .Case("c++", LangStandard::lang_openclcpp)
Richard Smithc91daf12017-02-14 22:44:20 +00002145 .Default(LangStandard::lang_unspecified);
Douglas Katzman31fdbfe2015-08-05 15:08:53 +00002146
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00002147 if (OpenCLLangStd == LangStandard::lang_unspecified) {
Peter Collingbournefafa6652010-12-04 01:51:40 +00002148 Diags.Report(diag::err_drv_invalid_value)
Richard Smithc91daf12017-02-14 22:44:20 +00002149 << A->getAsString(Args) << A->getValue();
Peter Collingbournefafa6652010-12-04 01:51:40 +00002150 }
Tanya Lattner4fdce3f2012-06-19 23:09:52 +00002151 else
2152 LangStd = OpenCLLangStd;
Peter Collingbournefafa6652010-12-04 01:51:40 +00002153 }
Douglas Katzman31fdbfe2015-08-05 15:08:53 +00002154
Yaxun Liu143f0832016-06-20 19:26:00 +00002155 Opts.IncludeDefaultHeader = Args.hasArg(OPT_finclude_default_header);
2156
Sunil Srivastavabf010802016-04-27 19:53:03 +00002157 llvm::Triple T(TargetOpts.Triple);
Yaxun Liu143f0832016-06-20 19:26:00 +00002158 CompilerInvocation::setLangDefaults(Opts, IK, T, PPOpts, LangStd);
Peter Collingbourneaaeb73b2010-12-04 01:50:27 +00002159
Yaxun Liu02c39792016-07-13 21:21:05 +00002160 // -cl-strict-aliasing needs to emit diagnostic in the case where CL > 1.0.
2161 // This option should be deprecated for CL > 1.0 because
2162 // this option was added for compatibility with OpenCL 1.0.
2163 if (Args.getLastArg(OPT_cl_strict_aliasing)
2164 && Opts.OpenCLVersion > 100) {
Yaxun Liu02c39792016-07-13 21:21:05 +00002165 Diags.Report(diag::warn_option_invalid_ocl_version)
Sven van Haastregt35b61392018-05-08 13:47:43 +00002166 << Opts.getOpenCLVersionTuple().getAsString()
2167 << Args.getLastArg(OPT_cl_strict_aliasing)->getAsString(Args);
Yaxun Liu02c39792016-07-13 21:21:05 +00002168 }
2169
Chandler Carruthe03aa552010-04-17 20:17:31 +00002170 // We abuse '-f[no-]gnu-keywords' to force overriding all GNU-extension
2171 // keywords. This behavior is provided by GCC's poorly named '-fasm' flag,
2172 // while a subset (the non-C++ GNU keywords) is provided by GCC's
2173 // '-fgnu-keywords'. Clang conflates the two for simplicity under the single
2174 // name, as it doesn't seem a useful distinction.
2175 Opts.GNUKeywords = Args.hasFlag(OPT_fgnu_keywords, OPT_fno_gnu_keywords,
Peter Collingbourneaaeb73b2010-12-04 01:50:27 +00002176 Opts.GNUKeywords);
Chandler Carruthe03aa552010-04-17 20:17:31 +00002177
Jacob Bandes-Storch33f3e632018-07-17 04:56:22 +00002178 Opts.Digraphs = Args.hasFlag(OPT_fdigraphs, OPT_fno_digraphs, Opts.Digraphs);
2179
Erich Keaned46083c2017-05-25 16:24:49 +00002180 if (Args.hasArg(OPT_fno_operator_names))
Peter Collingbourneaaeb73b2010-12-04 01:50:27 +00002181 Opts.CXXOperatorNames = 0;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002182
Reid Klecknerbbc01782014-12-03 21:53:36 +00002183 if (Args.hasArg(OPT_fcuda_is_device))
2184 Opts.CUDAIsDevice = 1;
2185
Justin Lebar1eac5942016-01-26 17:47:20 +00002186 if (Args.hasArg(OPT_fcuda_allow_variadic_functions))
2187 Opts.CUDAAllowVariadicFunctions = 1;
2188
Justin Lebarba122ab2016-03-30 23:30:21 +00002189 if (Args.hasArg(OPT_fno_cuda_host_device_constexpr))
2190 Opts.CUDAHostDeviceConstexpr = 0;
2191
Justin Lebard3a44f62016-04-05 18:26:20 +00002192 if (Opts.CUDAIsDevice && Args.hasArg(OPT_fcuda_flush_denormals_to_zero))
2193 Opts.CUDADeviceFlushDenormalsToZero = 1;
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);
2596
Alexey Bataeve927ca72017-12-29 17:36:15 +00002597 if (Opts.OpenMP || Opts.OpenMPSimd) {
2598 if (int Version =
2599 getLastArgIntValue(Args, OPT_fopenmp_version_EQ,
Alexey Bataev66f95772018-05-21 16:40:32 +00002600 IsSimdSpecified ? 45 : Opts.OpenMP, Diags))
Alexey Bataevc6bd8912016-05-26 11:10:11 +00002601 Opts.OpenMP = Version;
Alexey Bataev66f95772018-05-21 16:40:32 +00002602 else if (IsSimdSpecified)
Alexey Bataeve927ca72017-12-29 17:36:15 +00002603 Opts.OpenMP = 45;
Alexey Bataevc6bd8912016-05-26 11:10:11 +00002604 // Provide diagnostic when a given target is not expected to be an OpenMP
2605 // device or host.
2606 if (!Opts.OpenMPIsDevice) {
2607 switch (T.getArch()) {
2608 default:
2609 break;
2610 // Add unsupported host targets here:
2611 case llvm::Triple::nvptx:
2612 case llvm::Triple::nvptx64:
Eugene Zelenko44357ee2018-03-26 21:45:04 +00002613 Diags.Report(diag::err_drv_omp_host_target_not_supported)
Alexey Bataevc6bd8912016-05-26 11:10:11 +00002614 << TargetOpts.Triple;
2615 break;
2616 }
Samuel Antao45bfe4c2016-02-08 15:59:20 +00002617 }
2618 }
2619
Gheorghe-Teodor Berceae3b0a192017-08-07 20:57:59 +00002620 // Set the flag to prevent the implementation from emitting device exception
2621 // handling code for those requiring so.
Alexey Bataev1ab34572018-05-02 16:52:07 +00002622 Opts.OpenMPHostCXXExceptions = Opts.Exceptions && Opts.CXXExceptions;
Sven van Haastregt2ca6ba12018-05-09 13:16:17 +00002623 if ((Opts.OpenMPIsDevice && T.isNVPTX()) || Opts.OpenCLCPlusPlus) {
Gheorghe-Teodor Berceae3b0a192017-08-07 20:57:59 +00002624 Opts.Exceptions = 0;
2625 Opts.CXXExceptions = 0;
2626 }
2627
Samuel Antaoee8fb302016-01-06 13:42:12 +00002628 // Get the OpenMP target triples if any.
Samuel Antao1168d63c2016-06-30 21:22:08 +00002629 if (Arg *A = Args.getLastArg(options::OPT_fopenmp_targets_EQ)) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002630
2631 for (unsigned i = 0; i < A->getNumValues(); ++i) {
2632 llvm::Triple TT(A->getValue(i));
2633
Gheorghe-Teodor Berceaef5e1062017-08-07 21:11:10 +00002634 if (TT.getArch() == llvm::Triple::UnknownArch ||
2635 !(TT.getArch() == llvm::Triple::ppc ||
2636 TT.getArch() == llvm::Triple::ppc64 ||
2637 TT.getArch() == llvm::Triple::ppc64le ||
2638 TT.getArch() == llvm::Triple::nvptx ||
2639 TT.getArch() == llvm::Triple::nvptx64 ||
2640 TT.getArch() == llvm::Triple::x86 ||
2641 TT.getArch() == llvm::Triple::x86_64))
Eugene Zelenko44357ee2018-03-26 21:45:04 +00002642 Diags.Report(diag::err_drv_invalid_omp_target) << A->getValue(i);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002643 else
2644 Opts.OMPTargetTriples.push_back(TT);
2645 }
2646 }
2647
2648 // Get OpenMP host file path if any and report if a non existent file is
2649 // found
Samuel Antao1168d63c2016-06-30 21:22:08 +00002650 if (Arg *A = Args.getLastArg(options::OPT_fopenmp_host_ir_file_path)) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002651 Opts.OMPHostIRFile = A->getValue();
2652 if (!llvm::sys::fs::exists(Opts.OMPHostIRFile))
Eugene Zelenko44357ee2018-03-26 21:45:04 +00002653 Diags.Report(diag::err_drv_omp_host_ir_file_not_found)
Samuel Antaoee8fb302016-01-06 13:42:12 +00002654 << Opts.OMPHostIRFile;
2655 }
Douglas Gregor15171282013-01-15 06:45:29 +00002656
Carlo Bertolli79712092018-02-28 20:48:35 +00002657 // set CUDA mode for OpenMP target NVPTX if specified in options
2658 Opts.OpenMPCUDAMode = Opts.OpenMPIsDevice && T.isNVPTX() &&
2659 Args.hasArg(options::OPT_fopenmp_cuda_mode);
2660
Chandler Carruth61fbf622011-04-23 09:27:53 +00002661 // Record whether the __DEPRECATED define was requested.
2662 Opts.Deprecated = Args.hasFlag(OPT_fdeprecated_macro,
2663 OPT_fno_deprecated_macro,
2664 Opts.Deprecated);
2665
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002666 // FIXME: Eliminate this dependency.
Dylan Noblesmith4c004f32012-08-08 16:09:15 +00002667 unsigned Opt = getOptimizationLevel(Args, IK, Diags),
Chad Rosierf2d39642013-04-10 21:30:03 +00002668 OptSize = getOptimizationLevelSize(Args);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002669 Opts.Optimize = Opt != 0;
Dylan Noblesmith4c004f32012-08-08 16:09:15 +00002670 Opts.OptimizeSize = OptSize != 0;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002671
2672 // This is the __NO_INLINE__ define, which just depends on things like the
2673 // optimization level and -fno-inline, not actually whether the backend has
2674 // inlining enabled.
Chandler Carruthfcd33142016-12-23 01:24:49 +00002675 Opts.NoInlineDefine = !Opts.Optimize;
2676 if (Arg *InlineArg = Args.getLastArg(
2677 options::OPT_finline_functions, options::OPT_finline_hint_functions,
2678 options::OPT_fno_inline_functions, options::OPT_fno_inline))
2679 if (InlineArg->getOption().matches(options::OPT_fno_inline))
2680 Opts.NoInlineDefine = true;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002681
Pekka Jaaskelainen37014502014-12-10 16:41:14 +00002682 Opts.FastMath = Args.hasArg(OPT_ffast_math) ||
2683 Args.hasArg(OPT_cl_fast_relaxed_math);
2684 Opts.FiniteMathOnly = Args.hasArg(OPT_ffinite_math_only) ||
2685 Args.hasArg(OPT_cl_finite_math_only) ||
2686 Args.hasArg(OPT_cl_fast_relaxed_math);
Alexandros Lamprineasf5a8e6c2015-10-02 14:56:37 +00002687 Opts.UnsafeFPMath = Args.hasArg(OPT_menable_unsafe_fp_math) ||
2688 Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
2689 Args.hasArg(OPT_cl_fast_relaxed_math);
Chandler Carruth306bd2c2012-01-02 14:19:45 +00002690
Adam Nemet049a31d2017-03-29 21:54:24 +00002691 if (Arg *A = Args.getLastArg(OPT_ffp_contract)) {
2692 StringRef Val = A->getValue();
2693 if (Val == "fast")
2694 Opts.setDefaultFPContractMode(LangOptions::FPC_Fast);
2695 else if (Val == "on")
2696 Opts.setDefaultFPContractMode(LangOptions::FPC_On);
2697 else if (Val == "off")
2698 Opts.setDefaultFPContractMode(LangOptions::FPC_Off);
2699 else
2700 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
2701 }
2702
Ted Kremenekb47e6bc2012-09-13 06:41:18 +00002703 Opts.RetainCommentsFromSystemHeaders =
2704 Args.hasArg(OPT_fretain_comments_from_system_headers);
2705
Reid Kleckner898229a2013-06-14 17:17:23 +00002706 unsigned SSP = getLastArgIntValue(Args, OPT_stack_protector, 0, Diags);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002707 switch (SSP) {
2708 default:
2709 Diags.Report(diag::err_drv_invalid_value)
2710 << Args.getLastArg(OPT_stack_protector)->getAsString(Args) << SSP;
2711 break;
Douglas Gregor79a91412011-09-13 17:21:33 +00002712 case 0: Opts.setStackProtector(LangOptions::SSPOff); break;
2713 case 1: Opts.setStackProtector(LangOptions::SSPOn); break;
Josh Mageee0fc1a82014-02-11 01:35:14 +00002714 case 2: Opts.setStackProtector(LangOptions::SSPStrong); break;
2715 case 3: Opts.setStackProtector(LangOptions::SSPReq); break;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002716 }
Richard Smith52be6192012-11-05 22:04:41 +00002717
2718 // Parse -fsanitize= arguments.
Alexey Samsonov88459522015-01-12 22:39:12 +00002719 parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
2720 Diags, Opts.Sanitize);
Kostya Serebryanyaed71a82014-10-09 17:53:04 +00002721 // -fsanitize-address-field-padding=N has to be a LangOpt, parse it here.
Alexey Samsonova0416102014-11-11 01:26:14 +00002722 Opts.SanitizeAddressFieldPadding =
Kostya Serebryanyaed71a82014-10-09 17:53:04 +00002723 getLastArgIntValue(Args, OPT_fsanitize_address_field_padding, 0, Diags);
Alexey Samsonova511cdd2015-02-04 17:40:08 +00002724 Opts.SanitizerBlacklistFiles = Args.getAllArgValues(OPT_fsanitize_blacklist);
Dean Michael Berris835832d2017-03-30 00:29:36 +00002725
Dean Michael Berris504fc222017-03-30 22:46:45 +00002726 // -fxray-instrument
Dean Michael Berris835832d2017-03-30 00:29:36 +00002727 Opts.XRayInstrument =
2728 Args.hasFlag(OPT_fxray_instrument, OPT_fnoxray_instrument, false);
Dean Michael Berris504fc222017-03-30 22:46:45 +00002729
Dean Michael Berris1a5b10d2017-11-30 00:04:54 +00002730 // -fxray-always-emit-customevents
2731 Opts.XRayAlwaysEmitCustomEvents =
2732 Args.hasFlag(OPT_fxray_always_emit_customevents,
2733 OPT_fnoxray_always_emit_customevents, false);
2734
Keith Wyssf437e352018-04-17 21:32:43 +00002735 // -fxray-always-emit-typedevents
2736 Opts.XRayAlwaysEmitTypedEvents =
2737 Args.hasFlag(OPT_fxray_always_emit_typedevents,
2738 OPT_fnoxray_always_emit_customevents, false);
2739
Dean Michael Berris504fc222017-03-30 22:46:45 +00002740 // -fxray-{always,never}-instrument= filenames.
Dean Michael Berris835832d2017-03-30 00:29:36 +00002741 Opts.XRayAlwaysInstrumentFiles =
2742 Args.getAllArgValues(OPT_fxray_always_instrument);
2743 Opts.XRayNeverInstrumentFiles =
2744 Args.getAllArgValues(OPT_fxray_never_instrument);
Dean Michael Berris20dc6ef2018-04-09 04:02:09 +00002745 Opts.XRayAttrListFiles = Args.getAllArgValues(OPT_fxray_attr_list);
Alex Lorenz1be800c52017-04-19 08:58:56 +00002746
Piotr Padlewskie368de32018-06-13 13:55:42 +00002747 // -fforce-emit-vtables
2748 Opts.ForceEmitVTables = Args.hasArg(OPT_fforce_emit_vtables);
2749
Alex Lorenz1be800c52017-04-19 08:58:56 +00002750 // -fallow-editor-placeholders
2751 Opts.AllowEditorPlaceholders = Args.hasArg(OPT_fallow_editor_placeholders);
Akira Hatanakafcbe17c2018-03-28 21:13:14 +00002752
2753 if (Arg *A = Args.getLastArg(OPT_fclang_abi_compat_EQ)) {
2754 Opts.setClangABICompat(LangOptions::ClangABI::Latest);
2755
2756 StringRef Ver = A->getValue();
2757 std::pair<StringRef, StringRef> VerParts = Ver.split('.');
2758 unsigned Major, Minor = 0;
2759
2760 // Check the version number is valid: either 3.x (0 <= x <= 9) or
2761 // y or y.0 (4 <= y <= current version).
2762 if (!VerParts.first.startswith("0") &&
2763 !VerParts.first.getAsInteger(10, Major) &&
2764 3 <= Major && Major <= CLANG_VERSION_MAJOR &&
2765 (Major == 3 ? VerParts.second.size() == 1 &&
2766 !VerParts.second.getAsInteger(10, Minor)
2767 : VerParts.first.size() == Ver.size() ||
2768 VerParts.second == "0")) {
2769 // Got a valid version number.
2770 if (Major == 3 && Minor <= 8)
2771 Opts.setClangABICompat(LangOptions::ClangABI::Ver3_8);
2772 else if (Major <= 4)
2773 Opts.setClangABICompat(LangOptions::ClangABI::Ver4);
Richard Smith880057c2018-04-02 18:29:44 +00002774 else if (Major <= 6)
2775 Opts.setClangABICompat(LangOptions::ClangABI::Ver6);
Akira Hatanakafcbe17c2018-03-28 21:13:14 +00002776 } else if (Ver != "latest") {
2777 Diags.Report(diag::err_drv_invalid_value)
2778 << A->getAsString(Args) << A->getValue();
2779 }
2780 }
Peter Collingbourne54d13b42018-05-30 03:40:04 +00002781
2782 Opts.CompleteMemberPointers = Args.hasArg(OPT_fcomplete_member_pointers);
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00002783 Opts.BuildingPCHWithObjectFile = Args.hasArg(OPT_building_pch_with_obj);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002784}
2785
Alex Lorenzfb7654a2017-06-16 20:13:39 +00002786static bool isStrictlyPreprocessorAction(frontend::ActionKind Action) {
2787 switch (Action) {
2788 case frontend::ASTDeclList:
2789 case frontend::ASTDump:
2790 case frontend::ASTPrint:
2791 case frontend::ASTView:
2792 case frontend::EmitAssembly:
2793 case frontend::EmitBC:
2794 case frontend::EmitHTML:
2795 case frontend::EmitLLVM:
2796 case frontend::EmitLLVMOnly:
2797 case frontend::EmitCodeGenOnly:
2798 case frontend::EmitObj:
2799 case frontend::FixIt:
2800 case frontend::GenerateModule:
2801 case frontend::GenerateModuleInterface:
2802 case frontend::GeneratePCH:
2803 case frontend::GeneratePTH:
2804 case frontend::ParseSyntaxOnly:
2805 case frontend::ModuleFileInfo:
2806 case frontend::VerifyPCH:
2807 case frontend::PluginAction:
2808 case frontend::PrintDeclContext:
2809 case frontend::RewriteObjC:
2810 case frontend::RewriteTest:
2811 case frontend::RunAnalysis:
Gabor Horvath207e7b12018-02-10 14:04:45 +00002812 case frontend::TemplightDump:
Alex Lorenzfb7654a2017-06-16 20:13:39 +00002813 case frontend::MigrateSource:
2814 return false;
2815
Aaron Ballman16ed8dd2018-05-31 13:57:09 +00002816 case frontend::DumpCompilerOptions:
Alex Lorenzfb7654a2017-06-16 20:13:39 +00002817 case frontend::DumpRawTokens:
2818 case frontend::DumpTokens:
2819 case frontend::InitOnly:
2820 case frontend::PrintPreamble:
2821 case frontend::PrintPreprocessedInput:
2822 case frontend::RewriteMacros:
2823 case frontend::RunPreprocessorOnly:
2824 return true;
2825 }
2826 llvm_unreachable("invalid frontend action");
2827}
2828
Daniel Dunbar6048e7f2009-12-03 05:11:16 +00002829static void ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args,
Alex Lorenzfb7654a2017-06-16 20:13:39 +00002830 DiagnosticsEngine &Diags,
2831 frontend::ActionKind Action) {
Daniel Dunbar37300482010-05-20 16:54:55 +00002832 Opts.ImplicitPCHInclude = Args.getLastArgValue(OPT_include_pch);
2833 Opts.ImplicitPTHInclude = Args.getLastArgValue(OPT_include_pth);
Erich Keane76675de2018-07-05 17:22:13 +00002834 Opts.PCHThroughHeader = Args.getLastArgValue(OPT_pch_through_header_EQ);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002835 if (const Arg *A = Args.getLastArg(OPT_token_cache))
Richard Smithbd55daf2012-11-01 04:30:05 +00002836 Opts.TokenCache = A->getValue();
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002837 else
2838 Opts.TokenCache = Opts.ImplicitPTHInclude;
2839 Opts.UsePredefines = !Args.hasArg(OPT_undef);
Douglas Gregor7f6d60d2010-03-19 16:15:56 +00002840 Opts.DetailedRecord = Args.hasArg(OPT_detailed_preprocessing_record);
Douglas Gregorce3a8292010-07-27 00:27:13 +00002841 Opts.DisablePCHValidation = Args.hasArg(OPT_fno_validate_pch);
Argyrios Kyrtzidis7b5d9102017-02-27 02:06:18 +00002842 Opts.AllowPCHWithCompilerErrors = Args.hasArg(OPT_fallow_pch_with_errors);
Argyrios Kyrtzidis0427be92010-10-14 20:14:25 +00002843
Argyrios Kyrtzidisa11aca42010-10-14 20:14:18 +00002844 Opts.DumpDeserializedPCHDecls = Args.hasArg(OPT_dump_deserialized_pch_decls);
Eugene Zelenko44357ee2018-03-26 21:45:04 +00002845 for (const auto *A : Args.filtered(OPT_error_on_deserialized_pch_decl))
Richard Smithbd55daf2012-11-01 04:30:05 +00002846 Opts.DeserializedPCHDeclsToErrorOn.insert(A->getValue());
Douglas Gregorce3a8292010-07-27 00:27:13 +00002847
Douglas Gregor3f4bea02010-07-26 21:36:20 +00002848 if (const Arg *A = Args.getLastArg(OPT_preamble_bytes_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00002849 StringRef Value(A->getValue());
Douglas Gregor3f4bea02010-07-26 21:36:20 +00002850 size_t Comma = Value.find(',');
2851 unsigned Bytes = 0;
2852 unsigned EndOfLine = 0;
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002853
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002854 if (Comma == StringRef::npos ||
Douglas Gregor3f4bea02010-07-26 21:36:20 +00002855 Value.substr(0, Comma).getAsInteger(10, Bytes) ||
2856 Value.substr(Comma + 1).getAsInteger(10, EndOfLine))
2857 Diags.Report(diag::err_drv_preamble_format);
2858 else {
2859 Opts.PrecompiledPreambleBytes.first = Bytes;
2860 Opts.PrecompiledPreambleBytes.second = (EndOfLine != 0);
2861 }
2862 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002863
Alexander Ivchenko0fb8c872018-05-18 11:56:21 +00002864 // Add the __CET__ macro if a CFProtection option is set.
2865 if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
2866 StringRef Name = A->getValue();
2867 if (Name == "branch")
2868 Opts.addMacroDef("__CET__=1");
2869 else if (Name == "return")
2870 Opts.addMacroDef("__CET__=2");
2871 else if (Name == "full")
2872 Opts.addMacroDef("__CET__=3");
2873 }
2874
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002875 // Add macros from the command line.
Eugene Zelenko44357ee2018-03-26 21:45:04 +00002876 for (const auto *A : Args.filtered(OPT_D, OPT_U)) {
Sean Silva14facf32015-06-09 01:57:17 +00002877 if (A->getOption().matches(OPT_D))
2878 Opts.addMacroDef(A->getValue());
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002879 else
Sean Silva14facf32015-06-09 01:57:17 +00002880 Opts.addMacroUndef(A->getValue());
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002881 }
2882
Daniel Dunbar37300482010-05-20 16:54:55 +00002883 Opts.MacroIncludes = Args.getAllArgValues(OPT_imacros);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002884
2885 // Add the ordered list of -includes.
Eugene Zelenko44357ee2018-03-26 21:45:04 +00002886 for (const auto *A : Args.filtered(OPT_include))
Benjamin Kramer3204b152015-05-29 19:42:19 +00002887 Opts.Includes.emplace_back(A->getValue());
Daniel Dunbar6048e7f2009-12-03 05:11:16 +00002888
Eugene Zelenko44357ee2018-03-26 21:45:04 +00002889 for (const auto *A : Args.filtered(OPT_chain_include))
Benjamin Kramer3204b152015-05-29 19:42:19 +00002890 Opts.ChainedIncludes.emplace_back(A->getValue());
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002891
Eugene Zelenko44357ee2018-03-26 21:45:04 +00002892 for (const auto *A : Args.filtered(OPT_remap_file)) {
Sean Silva14facf32015-06-09 01:57:17 +00002893 std::pair<StringRef, StringRef> Split = StringRef(A->getValue()).split(';');
Daniel Dunbar6048e7f2009-12-03 05:11:16 +00002894
2895 if (Split.second.empty()) {
Daniel Dunbara442fd52010-06-11 22:00:13 +00002896 Diags.Report(diag::err_drv_invalid_remap_file) << A->getAsString(Args);
Daniel Dunbar6048e7f2009-12-03 05:11:16 +00002897 continue;
2898 }
2899
2900 Opts.addRemappedFile(Split.first, Split.second);
2901 }
Sean Silva14facf32015-06-09 01:57:17 +00002902
John McCall31168b02011-06-15 23:02:42 +00002903 if (Arg *A = Args.getLastArg(OPT_fobjc_arc_cxxlib_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00002904 StringRef Name = A->getValue();
John McCall31168b02011-06-15 23:02:42 +00002905 unsigned Library = llvm::StringSwitch<unsigned>(Name)
2906 .Case("libc++", ARCXX_libcxx)
2907 .Case("libstdc++", ARCXX_libstdcxx)
2908 .Case("none", ARCXX_nolib)
2909 .Default(~0U);
2910 if (Library == ~0U)
2911 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
2912 else
2913 Opts.ObjCXXARCStandardLibrary = (ObjCXXARCStandardLibraryKind)Library;
2914 }
Alex Lorenzfb7654a2017-06-16 20:13:39 +00002915
2916 // Always avoid lexing editor placeholders when we're just running the
2917 // preprocessor as we never want to emit the
2918 // "editor placeholder in source file" error in PP only mode.
2919 if (isStrictlyPreprocessorAction(Action))
2920 Opts.LexEditorPlaceholders = false;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002921}
2922
2923static void ParsePreprocessorOutputArgs(PreprocessorOutputOptions &Opts,
Jordan Rose17441582013-01-30 01:52:57 +00002924 ArgList &Args,
2925 frontend::ActionKind Action) {
Alex Lorenzfb7654a2017-06-16 20:13:39 +00002926 if (isStrictlyPreprocessorAction(Action))
Jordan Rose17441582013-01-30 01:52:57 +00002927 Opts.ShowCPP = !Args.hasArg(OPT_dM);
Alex Lorenzfb7654a2017-06-16 20:13:39 +00002928 else
2929 Opts.ShowCPP = 0;
Jordan Rose17441582013-01-30 01:52:57 +00002930
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002931 Opts.ShowComments = Args.hasArg(OPT_C);
Daniel Dunbard4352752010-08-24 22:44:13 +00002932 Opts.ShowLineMarkers = !Args.hasArg(OPT_P);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002933 Opts.ShowMacroComments = Args.hasArg(OPT_CC);
Daniel Dunbard4352752010-08-24 22:44:13 +00002934 Opts.ShowMacros = Args.hasArg(OPT_dM) || Args.hasArg(OPT_dD);
Bruno Cardoso Lopes6fa3b742016-11-17 22:45:31 +00002935 Opts.ShowIncludeDirectives = Args.hasArg(OPT_dI);
David Blaikiee993e4c2012-06-14 17:36:09 +00002936 Opts.RewriteIncludes = Args.hasArg(OPT_frewrite_includes);
Richard Smith86a3ef52017-06-09 21:24:02 +00002937 Opts.RewriteImports = Args.hasArg(OPT_frewrite_imports);
Reid Kleckner1df0fea2015-02-26 00:17:25 +00002938 Opts.UseLineDirectives = Args.hasArg(OPT_fuse_line_directives);
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002939}
2940
Saleem Abdulrasoolf7b3d6c2016-04-08 16:52:05 +00002941static void ParseTargetArgs(TargetOptions &Opts, ArgList &Args,
2942 DiagnosticsEngine &Diags) {
Daniel Dunbar37300482010-05-20 16:54:55 +00002943 Opts.ABI = Args.getLastArgValue(OPT_target_abi);
Saleem Abdulrasoolf7b3d6c2016-04-08 16:52:05 +00002944 if (Arg *A = Args.getLastArg(OPT_meabi)) {
2945 StringRef Value = A->getValue();
2946 llvm::EABI EABIVersion = llvm::StringSwitch<llvm::EABI>(Value)
2947 .Case("default", llvm::EABI::Default)
2948 .Case("4", llvm::EABI::EABI4)
2949 .Case("5", llvm::EABI::EABI5)
2950 .Case("gnu", llvm::EABI::GNU)
2951 .Default(llvm::EABI::Unknown);
2952 if (EABIVersion == llvm::EABI::Unknown)
2953 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
2954 << Value;
2955 else
Yuka Takahashidc771502017-07-01 07:57:23 +00002956 Opts.EABIVersion = EABIVersion;
Saleem Abdulrasoolf7b3d6c2016-04-08 16:52:05 +00002957 }
Daniel Dunbar37300482010-05-20 16:54:55 +00002958 Opts.CPU = Args.getLastArgValue(OPT_target_cpu);
Rafael Espindolaeb265472013-08-21 21:59:03 +00002959 Opts.FPMath = Args.getLastArgValue(OPT_mfpmath);
Douglas Gregorcb177f12012-10-16 23:40:58 +00002960 Opts.FeaturesAsWritten = Args.getAllArgValues(OPT_target_feature);
Daniel Dunbara1d107c2010-08-11 23:07:42 +00002961 Opts.LinkerVersion = Args.getLastArgValue(OPT_target_linker_version);
Petr Hosekf92ca012018-05-25 20:39:37 +00002962 Opts.Triple = Args.getLastArgValue(OPT_triple);
Sebastian Pop8188c8a2011-11-01 21:33:06 +00002963 // Use the default target triple if unspecified.
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002964 if (Opts.Triple.empty())
Sebastian Pop8188c8a2011-11-01 21:33:06 +00002965 Opts.Triple = llvm::sys::getDefaultTargetTriple();
Petr Hosekf92ca012018-05-25 20:39:37 +00002966 Opts.Triple = llvm::Triple::normalize(Opts.Triple);
Alexey Bader0ea07532016-11-01 15:50:52 +00002967 Opts.OpenCLExtensionsAsWritten = Args.getAllArgValues(OPT_cl_ext_EQ);
Mandeep Singh Grangac24bb52018-02-25 03:58:23 +00002968 Opts.ForceEnableInt128 = Args.hasArg(OPT_fforce_enable_int128);
Artem Belevich679dafe2018-05-09 23:10:09 +00002969 Opts.NVPTXUseShortPointers = Args.hasFlag(
2970 options::OPT_fcuda_short_ptr, options::OPT_fno_cuda_short_ptr, false);
Hans Wennborg50501fb2014-01-13 19:48:18 +00002971}
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002972
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00002973bool CompilerInvocation::CreateFromArgs(CompilerInvocation &Res,
Chris Lattner5159f612010-11-23 08:35:12 +00002974 const char *const *ArgBegin,
2975 const char *const *ArgEnd,
David Blaikie9c902b52011-09-25 23:23:43 +00002976 DiagnosticsEngine &Diags) {
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00002977 bool Success = true;
2978
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002979 // Parse the arguments.
David Blaikie0aaa7622017-01-13 17:34:15 +00002980 std::unique_ptr<OptTable> Opts = createDriverOptTable();
Hans Wennborgd1ddb9a2013-08-02 20:16:22 +00002981 const unsigned IncludedFlagsBitmask = options::CC1Option;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002982 unsigned MissingArgIndex, MissingArgCount;
David Blaikie69a1d8c2015-06-22 22:07:27 +00002983 InputArgList Args =
David Blaikie6d492ad2015-06-21 06:32:36 +00002984 Opts->ParseArgs(llvm::makeArrayRef(ArgBegin, ArgEnd), MissingArgIndex,
David Blaikie69a1d8c2015-06-22 22:07:27 +00002985 MissingArgCount, IncludedFlagsBitmask);
Wei Mi811ff922016-04-08 17:42:32 +00002986 LangOptions &LangOpts = *Res.getLangOpts();
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002987
2988 // Check for missing argument error.
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00002989 if (MissingArgCount) {
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002990 Diags.Report(diag::err_drv_missing_argument)
David Blaikie69a1d8c2015-06-22 22:07:27 +00002991 << Args.getArgString(MissingArgIndex) << MissingArgCount;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00002992 Success = false;
2993 }
Daniel Dunbarc70c3932009-12-01 03:16:53 +00002994
2995 // Issue errors on unknown arguments.
Eugene Zelenko44357ee2018-03-26 21:45:04 +00002996 for (const auto *A : Args.filtered(OPT_UNKNOWN)) {
Brian Gesiak24910762018-01-06 00:25:40 +00002997 auto ArgString = A->getAsString(Args);
2998 std::string Nearest;
2999 if (Opts->findNearest(ArgString, Nearest, IncludedFlagsBitmask) > 1)
3000 Diags.Report(diag::err_drv_unknown_argument) << ArgString;
3001 else
3002 Diags.Report(diag::err_drv_unknown_argument_with_suggestion)
3003 << ArgString << Nearest;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00003004 Success = false;
3005 }
Daniel Dunbarc70c3932009-12-01 03:16:53 +00003006
David Blaikie69a1d8c2015-06-22 22:07:27 +00003007 Success &= ParseAnalyzerArgs(*Res.getAnalyzerOpts(), Args, Diags);
3008 Success &= ParseMigratorArgs(Res.getMigratorOpts(), Args);
3009 ParseDependencyOutputArgs(Res.getDependencyOutputOpts(), Args);
Bruno Cardoso Lopes76952a72016-10-11 18:21:26 +00003010 Success &=
3011 ParseDiagnosticArgs(Res.getDiagnosticOpts(), Args, &Diags,
3012 false /*DefaultDiagColor*/, false /*DefaultShowOpt*/);
Wei Mi811ff922016-04-08 17:42:32 +00003013 ParseCommentArgs(LangOpts.CommentOpts, Args);
David Blaikie69a1d8c2015-06-22 22:07:27 +00003014 ParseFileSystemArgs(Res.getFileSystemOpts(), Args);
Peter Collingbourneb8e5dd42010-12-04 01:50:36 +00003015 // FIXME: We shouldn't have to pass the DashX option around here
Erik Verbruggene0bde752016-10-27 14:17:10 +00003016 InputKind DashX = ParseFrontendArgs(Res.getFrontendOpts(), Args, Diags,
3017 LangOpts.IsHeaderFile);
Saleem Abdulrasoolf7b3d6c2016-04-08 16:52:05 +00003018 ParseTargetArgs(Res.getTargetOpts(), Args, Diags);
David Blaikie69a1d8c2015-06-22 22:07:27 +00003019 Success &= ParseCodeGenArgs(Res.getCodeGenOpts(), Args, DashX, Diags,
Teresa Johnson9e4321c2018-04-17 16:39:25 +00003020 Res.getTargetOpts(), Res.getFrontendOpts());
Adrian Prantl0ebdeac2017-03-14 23:07:49 +00003021 ParseHeaderSearchArgs(Res.getHeaderSearchOpts(), Args,
3022 Res.getFileSystemOpts().WorkingDir);
Richard Smith40c0efa2017-04-26 18:57:40 +00003023 if (DashX.getFormat() == InputKind::Precompiled ||
3024 DashX.getLanguage() == InputKind::LLVM_IR) {
Steven Wu546a1962015-07-17 20:09:56 +00003025 // ObjCAAutoRefCount and Sanitize LangOpts are used to setup the
3026 // PassManager in BackendUtil.cpp. They need to be initializd no matter
3027 // what the input type is.
3028 if (Args.hasArg(OPT_fobjc_arc))
Wei Mi811ff922016-04-08 17:42:32 +00003029 LangOpts.ObjCAutoRefCount = 1;
3030 // PIClevel and PIELevel are needed during code generation and this should be
3031 // set regardless of the input type.
3032 LangOpts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
Rafael Espindolac9d336e2016-06-23 15:07:32 +00003033 LangOpts.PIE = Args.hasArg(OPT_pic_is_pie);
Steven Wu546a1962015-07-17 20:09:56 +00003034 parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
Wei Mi811ff922016-04-08 17:42:32 +00003035 Diags, LangOpts.Sanitize);
Steven Wu546a1962015-07-17 20:09:56 +00003036 } else {
3037 // Other LangOpts are only initialzed when the input is not AST or LLVM IR.
Richard Smith40c0efa2017-04-26 18:57:40 +00003038 // FIXME: Should we really be calling this for an InputKind::Asm input?
Yaxun Liu143f0832016-06-20 19:26:00 +00003039 ParseLangArgs(LangOpts, Args, DashX, Res.getTargetOpts(),
Richard Smith40c0efa2017-04-26 18:57:40 +00003040 Res.getPreprocessorOpts(), Diags);
Fariborz Jahanian40c5e1a2011-02-25 17:24:55 +00003041 if (Res.getFrontendOpts().ProgramAction == frontend::RewriteObjC)
Wei Mi811ff922016-04-08 17:42:32 +00003042 LangOpts.ObjCExceptions = 1;
Fariborz Jahanian40c5e1a2011-02-25 17:24:55 +00003043 }
Benjamin Kramer12f2de12016-03-14 13:23:58 +00003044
Saleem Abdulrasool3fe5b7a2018-04-19 23:14:57 +00003045 LangOpts.FunctionAlignment =
3046 getLastArgIntValue(Args, OPT_function_alignment, 0, Diags);
3047
Artem Belevich31c3bad2016-05-19 18:44:45 +00003048 if (LangOpts.CUDA) {
3049 // During CUDA device-side compilation, the aux triple is the
3050 // triple used for host compilation.
3051 if (LangOpts.CUDAIsDevice)
3052 Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple;
Justin Lebar76945b22016-04-29 23:05:19 +00003053 }
3054
Gheorghe-Teodor Bercea59d7b772017-06-29 15:49:03 +00003055 // Set the triple of the host for OpenMP device compile.
3056 if (LangOpts.OpenMPIsDevice)
3057 Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple;
3058
Benjamin Kramerfd652b12016-03-15 09:41:39 +00003059 // FIXME: Override value name discarding when asan or msan is used because the
Benjamin Kramer12f2de12016-03-14 13:23:58 +00003060 // backend passes depend on the name of the alloca in order to print out
3061 // names.
Benjamin Kramerfd652b12016-03-15 09:41:39 +00003062 Res.getCodeGenOpts().DiscardValueNames &=
Wei Mi811ff922016-04-08 17:42:32 +00003063 !LangOpts.Sanitize.has(SanitizerKind::Address) &&
3064 !LangOpts.Sanitize.has(SanitizerKind::Memory);
Benjamin Kramer12f2de12016-03-14 13:23:58 +00003065
Brian Gesiakf0ef1372018-01-09 21:26:47 +00003066 ParsePreprocessorArgs(Res.getPreprocessorOpts(), Args, Diags,
Alex Lorenzfb7654a2017-06-16 20:13:39 +00003067 Res.getFrontendOpts().ProgramAction);
David Blaikie69a1d8c2015-06-22 22:07:27 +00003068 ParsePreprocessorOutputArgs(Res.getPreprocessorOutputOpts(), Args,
Jordan Rose17441582013-01-30 01:52:57 +00003069 Res.getFrontendOpts().ProgramAction);
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003070
3071 // Turn on -Wspir-compat for SPIR target.
3072 llvm::Triple T(Res.getTargetOpts().Triple);
3073 auto Arch = T.getArch();
3074 if (Arch == llvm::Triple::spir || Arch == llvm::Triple::spir64) {
3075 Res.getDiagnosticOpts().Warnings.push_back("spir-compat");
3076 }
Wei Mi9b3d6272017-10-16 16:50:27 +00003077
3078 // If sanitizer is enabled, disable OPT_ffine_grained_bitfield_accesses.
3079 if (Res.getCodeGenOpts().FineGrainedBitfieldAccesses &&
3080 !Res.getLangOpts()->Sanitize.empty()) {
3081 Res.getCodeGenOpts().FineGrainedBitfieldAccesses = false;
3082 Diags.Report(diag::warn_drv_fine_grained_bitfield_accesses_ignored);
3083 }
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +00003084 return Success;
Daniel Dunbarc70c3932009-12-01 03:16:53 +00003085}
Douglas Gregor1735f4e2011-09-13 23:15:45 +00003086
Douglas Gregor1735f4e2011-09-13 23:15:45 +00003087std::string CompilerInvocation::getModuleHash() const {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00003088 // Note: For QoI reasons, the things we use as a hash here should all be
3089 // dumped via the -module-info flag.
Douglas Gregor7fd08492012-11-05 19:45:09 +00003090 using llvm::hash_code;
3091 using llvm::hash_value;
3092 using llvm::hash_combine;
3093
Douglas Gregor1735f4e2011-09-13 23:15:45 +00003094 // Start the signature with the compiler version.
Douglas Gregordc779ab2012-11-05 23:30:26 +00003095 // FIXME: We'd rather use something more cryptographically sound than
Douglas Gregor7fd08492012-11-05 19:45:09 +00003096 // CityHash, but this will do for now.
3097 hash_code code = hash_value(getClangFullRepositoryVersion());
3098
Douglas Gregor1735f4e2011-09-13 23:15:45 +00003099 // Extend the signature with the language options
3100#define LANGOPT(Name, Bits, Default, Description) \
Douglas Gregor7fd08492012-11-05 19:45:09 +00003101 code = hash_combine(code, LangOpts->Name);
Douglas Gregor1735f4e2011-09-13 23:15:45 +00003102#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
Douglas Gregor7fd08492012-11-05 19:45:09 +00003103 code = hash_combine(code, static_cast<unsigned>(LangOpts->get##Name()));
Douglas Gregor1735f4e2011-09-13 23:15:45 +00003104#define BENIGN_LANGOPT(Name, Bits, Default, Description)
3105#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
3106#include "clang/Basic/LangOptions.def"
Ben Langmuircd98cb72015-06-23 18:20:18 +00003107
3108 for (StringRef Feature : LangOpts->ModuleFeatures)
3109 code = hash_combine(code, Feature);
Douglas Katzman31fdbfe2015-08-05 15:08:53 +00003110
Douglas Gregor7fd08492012-11-05 19:45:09 +00003111 // Extend the signature with the target options.
3112 code = hash_combine(code, TargetOpts->Triple, TargetOpts->CPU,
Argyrios Kyrtzidisfe6b8802014-04-29 18:45:01 +00003113 TargetOpts->ABI);
Eugene Zelenko44357ee2018-03-26 21:45:04 +00003114 for (const auto &FeatureAsWritten : TargetOpts->FeaturesAsWritten)
3115 code = hash_combine(code, FeatureAsWritten);
Douglas Gregor1735f4e2011-09-13 23:15:45 +00003116
Douglas Gregora739d9a2011-09-14 15:55:12 +00003117 // Extend the signature with preprocessor options.
Douglas Gregor7fd08492012-11-05 19:45:09 +00003118 const PreprocessorOptions &ppOpts = getPreprocessorOpts();
Douglas Gregor5dc38992013-02-07 00:21:12 +00003119 const HeaderSearchOptions &hsOpts = getHeaderSearchOpts();
Douglas Gregor7fd08492012-11-05 19:45:09 +00003120 code = hash_combine(code, ppOpts.UsePredefines, ppOpts.DetailedRecord);
3121
Eugene Zelenko44357ee2018-03-26 21:45:04 +00003122 for (const auto &I : getPreprocessorOpts().Macros) {
Douglas Gregor5dc38992013-02-07 00:21:12 +00003123 // If we're supposed to ignore this macro for the purposes of modules,
3124 // don't put it into the hash.
3125 if (!hsOpts.ModulesIgnoreMacros.empty()) {
Douglas Gregor5dc38992013-02-07 00:21:12 +00003126 // Check whether we're ignoring this macro.
Eugene Zelenko44357ee2018-03-26 21:45:04 +00003127 StringRef MacroDef = I.first;
Justin Lebar5e83dfe2016-10-21 21:45:01 +00003128 if (hsOpts.ModulesIgnoreMacros.count(
3129 llvm::CachedHashString(MacroDef.split('=').first)))
Douglas Gregor5dc38992013-02-07 00:21:12 +00003130 continue;
3131 }
3132
Eugene Zelenko44357ee2018-03-26 21:45:04 +00003133 code = hash_combine(code, I.first, I.second);
Douglas Gregor71129d52011-10-17 14:55:37 +00003134 }
Douglas Gregor7fd08492012-11-05 19:45:09 +00003135
Adrian Prantl793038d32016-01-12 21:01:56 +00003136 // Extend the signature with the sysroot and other header search options.
3137 code = hash_combine(code, hsOpts.Sysroot,
3138 hsOpts.ModuleFormat,
3139 hsOpts.UseDebugInfo,
3140 hsOpts.UseBuiltinIncludes,
Douglas Gregor7fd08492012-11-05 19:45:09 +00003141 hsOpts.UseStandardSystemIncludes,
3142 hsOpts.UseStandardCXXIncludes,
Manman Ren47a44452016-07-26 17:12:17 +00003143 hsOpts.UseLibcxx,
3144 hsOpts.ModulesValidateDiagnosticOptions);
Argyrios Kyrtzidisd113788e2014-05-04 05:27:24 +00003145 code = hash_combine(code, hsOpts.ResourceDir);
Douglas Gregor7fd08492012-11-05 19:45:09 +00003146
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00003147 // Extend the signature with the user build path.
3148 code = hash_combine(code, hsOpts.ModuleUserBuildPath);
3149
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003150 // Extend the signature with the module file extensions.
3151 const FrontendOptions &frontendOpts = getFrontendOpts();
Benjamin Kramer2e018ef2016-05-27 13:36:58 +00003152 for (const auto &ext : frontendOpts.ModuleFileExtensions) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003153 code = ext->hashExtension(code);
3154 }
3155
Vedant Kumar85a83c22017-06-01 20:01:01 +00003156 // Extend the signature with the enabled sanitizers, if at least one is
3157 // enabled. Sanitizers which cannot affect AST generation aren't hashed.
3158 SanitizerSet SanHash = LangOpts->Sanitize;
3159 SanHash.clear(getPPTransparentSanitizers());
3160 if (!SanHash.empty())
3161 code = hash_combine(code, SanHash.Mask);
3162
Douglas Gregor7fd08492012-11-05 19:45:09 +00003163 return llvm::APInt(64, code).toString(36, /*Signed=*/false);
Douglas Gregor1735f4e2011-09-13 23:15:45 +00003164}
Reid Kleckner898229a2013-06-14 17:17:23 +00003165
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003166template<typename IntTy>
3167static IntTy getLastArgIntValueImpl(const ArgList &Args, OptSpecifier Id,
3168 IntTy Default,
3169 DiagnosticsEngine *Diags) {
3170 IntTy Res = Default;
Reid Kleckner898229a2013-06-14 17:17:23 +00003171 if (Arg *A = Args.getLastArg(Id)) {
3172 if (StringRef(A->getValue()).getAsInteger(10, Res)) {
3173 if (Diags)
3174 Diags->Report(diag::err_drv_invalid_int_value) << A->getAsString(Args)
3175 << A->getValue();
3176 }
3177 }
3178 return Res;
3179}
Kostya Serebryanyce2c7262013-12-27 08:11:08 +00003180
Eugene Zelenko44357ee2018-03-26 21:45:04 +00003181namespace clang {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003182
3183// Declared in clang/Frontend/Utils.h.
3184int getLastArgIntValue(const ArgList &Args, OptSpecifier Id, int Default,
3185 DiagnosticsEngine *Diags) {
3186 return getLastArgIntValueImpl<int>(Args, Id, Default, Diags);
3187}
3188
3189uint64_t getLastArgUInt64Value(const ArgList &Args, OptSpecifier Id,
3190 uint64_t Default,
3191 DiagnosticsEngine *Diags) {
3192 return getLastArgIntValueImpl<uint64_t>(Args, Id, Default, Diags);
3193}
3194
Kostya Serebryanyce2c7262013-12-27 08:11:08 +00003195void BuryPointer(const void *Ptr) {
3196 // This function may be called only a small fixed amount of times per each
3197 // invocation, otherwise we do actually have a leak which we want to report.
3198 // If this function is called more than kGraveYardMaxSize times, the pointers
3199 // will not be properly buried and a leak detector will report a leak, which
3200 // is what we want in such case.
3201 static const size_t kGraveYardMaxSize = 16;
Chandler Carruth2588aa72013-12-28 02:50:00 +00003202 LLVM_ATTRIBUTE_UNUSED static const void *GraveYard[kGraveYardMaxSize];
Benjamin Kramer4527fb22014-03-02 17:08:31 +00003203 static std::atomic<unsigned> GraveYardSize;
3204 unsigned Idx = GraveYardSize++;
Kostya Serebryanyce2c7262013-12-27 08:11:08 +00003205 if (Idx >= kGraveYardMaxSize)
3206 return;
3207 GraveYard[Idx] = Ptr;
3208}
Ben Langmuir8832c062014-04-15 18:16:25 +00003209
3210IntrusiveRefCntPtr<vfs::FileSystem>
3211createVFSFromCompilerInvocation(const CompilerInvocation &CI,
3212 DiagnosticsEngine &Diags) {
Ilya Biryukovaf69e402017-05-23 11:37:52 +00003213 return createVFSFromCompilerInvocation(CI, Diags, vfs::getRealFileSystem());
3214}
Ben Langmuir8832c062014-04-15 18:16:25 +00003215
Ilya Biryukovaf69e402017-05-23 11:37:52 +00003216IntrusiveRefCntPtr<vfs::FileSystem>
3217createVFSFromCompilerInvocation(const CompilerInvocation &CI,
3218 DiagnosticsEngine &Diags,
3219 IntrusiveRefCntPtr<vfs::FileSystem> BaseFS) {
3220 if (CI.getHeaderSearchOpts().VFSOverlayFiles.empty())
3221 return BaseFS;
3222
3223 IntrusiveRefCntPtr<vfs::OverlayFileSystem> Overlay(
3224 new vfs::OverlayFileSystem(BaseFS));
Ben Langmuir8832c062014-04-15 18:16:25 +00003225 // earlier vfs files are on the bottom
Eugene Zelenko44357ee2018-03-26 21:45:04 +00003226 for (const auto &File : CI.getHeaderSearchOpts().VFSOverlayFiles) {
Rafael Espindola2d2b4202014-07-06 17:43:24 +00003227 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
Ilya Biryukovaf69e402017-05-23 11:37:52 +00003228 BaseFS->getBufferForFile(File);
Rafael Espindola2d2b4202014-07-06 17:43:24 +00003229 if (!Buffer) {
Ben Langmuir8832c062014-04-15 18:16:25 +00003230 Diags.Report(diag::err_missing_vfs_overlay_file) << File;
Ben Langmuir005c2e52018-03-23 17:37:27 +00003231 continue;
Ben Langmuir8832c062014-04-15 18:16:25 +00003232 }
3233
Bruno Cardoso Lopesd878e282016-03-20 02:08:48 +00003234 IntrusiveRefCntPtr<vfs::FileSystem> FS = vfs::getVFSFromYAML(
3235 std::move(Buffer.get()), /*DiagHandler*/ nullptr, File);
Ben Langmuir005c2e52018-03-23 17:37:27 +00003236 if (FS)
3237 Overlay->pushOverlay(FS);
3238 else
Ben Langmuir8832c062014-04-15 18:16:25 +00003239 Diags.Report(diag::err_invalid_vfs_overlay) << File;
Ben Langmuir8832c062014-04-15 18:16:25 +00003240 }
3241 return Overlay;
Reid Kleckner898229a2013-06-14 17:17:23 +00003242}
Eugene Zelenko44357ee2018-03-26 21:45:04 +00003243
3244} // namespace clang