blob: 1d35d6e78cca5e3bcdf9991f094ba8a3dd04eecf [file] [log] [blame]
Nick Lewyckye47c2452010-09-23 23:48:20 +00001//===--- Driver.cpp - Clang GCC Compatible Driver -------------------------===//
Daniel Dunbar544ecd12009-03-02 19:59:07 +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
Daniel Dunbar544ecd12009-03-02 19:59:07 +000010#include "clang/Driver/Driver.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000011#include "InputInfo.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000012#include "ToolChains/AMDGPU.h"
13#include "ToolChains/AVR.h"
Ed Schouten4dabea22017-06-25 08:29:09 +000014#include "ToolChains/Ananas.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000015#include "ToolChains/Bitrig.h"
16#include "ToolChains/Clang.h"
17#include "ToolChains/CloudABI.h"
18#include "ToolChains/Contiki.h"
19#include "ToolChains/CrossWindows.h"
20#include "ToolChains/Cuda.h"
21#include "ToolChains/Darwin.h"
22#include "ToolChains/DragonFly.h"
23#include "ToolChains/FreeBSD.h"
24#include "ToolChains/Fuchsia.h"
25#include "ToolChains/Gnu.h"
Jonathan Roelofs901c7762017-05-25 15:42:13 +000026#include "ToolChains/BareMetal.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000027#include "ToolChains/Haiku.h"
28#include "ToolChains/Hexagon.h"
29#include "ToolChains/Lanai.h"
30#include "ToolChains/Linux.h"
31#include "ToolChains/MinGW.h"
32#include "ToolChains/Minix.h"
Konstantin Zhuravlyove37b32c2017-03-08 22:36:04 +000033#include "ToolChains/MipsLinux.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000034#include "ToolChains/MSVC.h"
35#include "ToolChains/Myriad.h"
36#include "ToolChains/NaCl.h"
37#include "ToolChains/NetBSD.h"
38#include "ToolChains/OpenBSD.h"
39#include "ToolChains/PS4CPU.h"
40#include "ToolChains/Solaris.h"
41#include "ToolChains/TCE.h"
42#include "ToolChains/WebAssembly.h"
43#include "ToolChains/XCore.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000044#include "clang/Basic/Version.h"
Benjamin Kramerd45b2052015-10-07 15:48:01 +000045#include "clang/Basic/VirtualFileSystem.h"
Alp Toker1d257e12014-06-04 03:28:55 +000046#include "clang/Config/config.h"
Daniel Dunbar1688f1a2009-03-12 07:58:46 +000047#include "clang/Driver/Action.h"
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000048#include "clang/Driver/Compilation.h"
Daniel Dunbarc0b3e952009-03-12 08:55:43 +000049#include "clang/Driver/DriverDiagnostic.h"
Daniel Dunbare75d8342009-03-16 06:56:51 +000050#include "clang/Driver/Job.h"
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000051#include "clang/Driver/Options.h"
Peter Collingbournea4ccff32015-02-20 20:30:56 +000052#include "clang/Driver/SanitizerArgs.h"
Daniel Dunbare75d8342009-03-16 06:56:51 +000053#include "clang/Driver/Tool.h"
54#include "clang/Driver/ToolChain.h"
Chris Lattnerce6c42f2011-03-23 04:04:01 +000055#include "llvm/ADT/ArrayRef.h"
Hans Wennborg6ddc6902013-07-27 00:23:45 +000056#include "llvm/ADT/STLExtras.h"
Justin Lebar62907612016-07-06 21:21:39 +000057#include "llvm/ADT/SmallSet.h"
Hans Wennborg23d26a32014-06-18 17:21:50 +000058#include "llvm/ADT/StringExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000059#include "llvm/ADT/StringSet.h"
Hans Wennborg70850d82013-07-18 20:29:38 +000060#include "llvm/ADT/StringSwitch.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000061#include "llvm/Option/Arg.h"
62#include "llvm/Option/ArgList.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000063#include "llvm/Option/OptSpecifier.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000064#include "llvm/Option/OptTable.h"
65#include "llvm/Option/Option.h"
David Blaikie79000202011-09-23 05:57:42 +000066#include "llvm/Support/ErrorHandling.h"
Michael J. Spencerf28df4c2010-12-17 21:22:22 +000067#include "llvm/Support/FileSystem.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000068#include "llvm/Support/Path.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000069#include "llvm/Support/PrettyStackTrace.h"
Hans Wennborg23d26a32014-06-18 17:21:50 +000070#include "llvm/Support/Process.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000071#include "llvm/Support/Program.h"
Dimitry Andric81c40422017-06-06 21:54:21 +000072#include "llvm/Support/TargetRegistry.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000073#include "llvm/Support/raw_ostream.h"
Dylan Noblesmith4f4e7452012-02-02 00:40:14 +000074#include <map>
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000075#include <memory>
Benjamin Kramercfeacf52016-05-27 14:27:13 +000076#include <utility>
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +000077#if LLVM_ON_UNIX
78#include <unistd.h> // getpid
79#endif
Dylan Noblesmith86780e92012-02-01 14:25:28 +000080
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000081using namespace clang::driver;
Chris Lattnerada1c912009-03-26 05:56:24 +000082using namespace clang;
Reid Kleckner898229a2013-06-14 17:17:23 +000083using namespace llvm::opt;
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000084
Reid Kleckner68eb60b2015-02-02 22:41:48 +000085Driver::Driver(StringRef ClangExecutable, StringRef DefaultTargetTriple,
Benjamin Kramerd45b2052015-10-07 15:48:01 +000086 DiagnosticsEngine &Diags,
87 IntrusiveRefCntPtr<vfs::FileSystem> VFS)
Benjamin Kramercfeacf52016-05-27 14:27:13 +000088 : Opts(createDriverOptTable()), Diags(Diags), VFS(std::move(VFS)),
89 Mode(GCCMode), SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
90 LTOMode(LTOK_None), ClangExecutable(ClangExecutable),
Reid Kleckner68eb60b2015-02-02 22:41:48 +000091 SysRoot(DEFAULT_SYSROOT), UseStdLib(true),
Reid Kleckner68eb60b2015-02-02 22:41:48 +000092 DriverTitle("clang LLVM compiler"), CCPrintOptionsFilename(nullptr),
93 CCPrintHeadersFilename(nullptr), CCLogDiagnosticsFilename(nullptr),
94 CCCPrintBindings(false), CCPrintHeaders(false), CCLogDiagnostics(false),
Vedant Kumarf2030b92016-07-18 19:56:33 +000095 CCGenDiagnostics(false), DefaultTargetTriple(DefaultTargetTriple),
96 CCCGenericGCCName(""), CheckInputsExist(true), CCCUsePCH(true),
Bruno Cardoso Lopes52dfe712017-04-12 21:46:20 +000097 GenReproducer(false), SuppressMissingInputWarning(false) {
Daniel Dunbar3f3e2cd2010-01-20 02:35:16 +000098
Benjamin Kramerd45b2052015-10-07 15:48:01 +000099 // Provide a sane fallback if no VFS is specified.
100 if (!this->VFS)
101 this->VFS = vfs::getRealFileSystem();
102
Sumanth Gundapaneni3a1592942015-03-03 20:43:12 +0000103 Name = llvm::sys::path::filename(ClangExecutable);
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000104 Dir = llvm::sys::path::parent_path(ClangExecutable);
Benjamin Kramerf420dda2015-10-13 15:19:32 +0000105 InstalledDir = Dir; // Provide a sensible default installed dir.
Bob Wilsona20a1da2013-03-23 05:17:59 +0000106
107 // Compute the path to the resource directory.
108 StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
109 SmallString<128> P(Dir);
Chandler Carruthfd3cc702014-12-29 12:09:08 +0000110 if (ClangResourceDir != "") {
Bob Wilsona20a1da2013-03-23 05:17:59 +0000111 llvm::sys::path::append(P, ClangResourceDir);
Chandler Carruthfd3cc702014-12-29 12:09:08 +0000112 } else {
113 StringRef ClangLibdirSuffix(CLANG_LIBDIR_SUFFIX);
Argyrios Kyrtzidisbcae0472017-02-25 18:14:35 +0000114 P = llvm::sys::path::parent_path(Dir);
115 llvm::sys::path::append(P, Twine("lib") + ClangLibdirSuffix, "clang",
Chandler Carruthfd3cc702014-12-29 12:09:08 +0000116 CLANG_VERSION_STRING);
117 }
Bob Wilsona20a1da2013-03-23 05:17:59 +0000118 ResourceDir = P.str();
Daniel Dunbar544ecd12009-03-02 19:59:07 +0000119}
120
Zachary Turneraff19c32016-08-12 17:47:52 +0000121void Driver::ParseDriverMode(StringRef ProgramName,
122 ArrayRef<const char *> Args) {
123 auto Default = ToolChain::getTargetAndModeFromProgramName(ProgramName);
124 StringRef DefaultMode(Default.second);
125 setDriverModeFromOption(DefaultMode);
Hans Wennborg70850d82013-07-18 20:29:38 +0000126
Douglas Katzman6bbffc42015-06-25 18:51:37 +0000127 for (const char *ArgPtr : Args) {
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000128 // Ingore nullptrs, they are response file's EOL markers
Douglas Katzman6bbffc42015-06-25 18:51:37 +0000129 if (ArgPtr == nullptr)
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000130 continue;
Douglas Katzman6bbffc42015-06-25 18:51:37 +0000131 const StringRef Arg = ArgPtr;
Zachary Turneraff19c32016-08-12 17:47:52 +0000132 setDriverModeFromOption(Arg);
Hans Wennborg70850d82013-07-18 20:29:38 +0000133 }
134}
135
Zachary Turneraff19c32016-08-12 17:47:52 +0000136void Driver::setDriverModeFromOption(StringRef Opt) {
137 const std::string OptName =
138 getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
139 if (!Opt.startswith(OptName))
140 return;
141 StringRef Value = Opt.drop_front(OptName.size());
142
143 const unsigned M = llvm::StringSwitch<unsigned>(Value)
144 .Case("gcc", GCCMode)
145 .Case("g++", GXXMode)
146 .Case("cpp", CPPMode)
147 .Case("cl", CLMode)
148 .Default(~0U);
149
150 if (M != ~0U)
151 Mode = static_cast<DriverMode>(M);
152 else
153 Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
154}
155
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000156InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings,
157 bool &ContainsError) {
Daniel Dunbar2608c542009-03-18 01:38:48 +0000158 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000159 ContainsError = false;
Hans Wennborg6ddc6902013-07-27 00:23:45 +0000160
161 unsigned IncludedFlagsBitmask;
162 unsigned ExcludedFlagsBitmask;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000163 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000164 getIncludeExcludeOptionFlagMasks();
Hans Wennborg6ddc6902013-07-27 00:23:45 +0000165
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000166 unsigned MissingArgIndex, MissingArgCount;
David Blaikie69a1d8c2015-06-22 22:07:27 +0000167 InputArgList Args =
David Blaikie6d492ad2015-06-21 06:32:36 +0000168 getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
169 IncludedFlagsBitmask, ExcludedFlagsBitmask);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +0000170
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000171 // Check for missing argument error.
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000172 if (MissingArgCount) {
173 Diag(diag::err_drv_missing_argument)
David Blaikie69a1d8c2015-06-22 22:07:27 +0000174 << Args.getArgString(MissingArgIndex) << MissingArgCount;
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000175 ContainsError |=
176 Diags.getDiagnosticLevel(diag::err_drv_missing_argument,
177 SourceLocation()) > DiagnosticsEngine::Warning;
178 }
Daniel Dunbar65229332009-03-13 11:38:42 +0000179
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000180 // Check for unsupported options.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000181 for (const Arg *A : Args) {
Michael J. Spencer66e2b202012-10-19 22:37:06 +0000182 if (A->getOption().hasFlag(options::Unsupported)) {
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000183 Diag(diag::err_drv_unsupported_opt) << A->getAsString(Args);
184 ContainsError |= Diags.getDiagnosticLevel(diag::err_drv_unsupported_opt,
185 SourceLocation()) >
186 DiagnosticsEngine::Warning;
Daniel Dunbard8500f32009-03-22 23:26:43 +0000187 continue;
188 }
Chad Rosierce975d92012-02-22 17:55:22 +0000189
190 // Warn about -mcpu= without an argument.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000191 if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000192 Diag(diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
193 ContainsError |= Diags.getDiagnosticLevel(
194 diag::warn_drv_empty_joined_argument,
195 SourceLocation()) > DiagnosticsEngine::Warning;
Chad Rosierce975d92012-02-22 17:55:22 +0000196 }
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000197 }
198
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000199 for (const Arg *A : Args.filtered(options::OPT_UNKNOWN)) {
200 auto ID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl
201 : diag::err_drv_unknown_argument;
202
203 Diags.Report(ID) << A->getAsString(Args);
204 ContainsError |= Diags.getDiagnosticLevel(ID, SourceLocation()) >
205 DiagnosticsEngine::Warning;
206 }
Rafael Espindola8a2d4962013-09-23 23:55:25 +0000207
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000208 return Args;
209}
210
Chad Rosier7742b5d2011-07-27 23:36:45 +0000211// Determine which compilation mode we are in. We look for options which
212// affect the phase, starting with the earliest phases, and record which
213// option we used to determine the final phase.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000214phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
215 Arg **FinalPhaseArg) const {
Craig Topper92fc2df2014-05-17 16:56:41 +0000216 Arg *PhaseArg = nullptr;
Chad Rosier7742b5d2011-07-27 23:36:45 +0000217 phases::ID FinalPhase;
Eric Christopherf901e852011-08-17 22:59:59 +0000218
Hans Wennborge50cec32014-06-13 20:59:54 +0000219 // -{E,EP,P,M,MM} only run the preprocessor.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000220 if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
Hans Wennborge50cec32014-06-13 20:59:54 +0000221 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
Hans Wennborge0053472013-12-20 18:40:46 +0000222 (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
223 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000224 FinalPhase = phases::Preprocess;
Eric Christopherf901e852011-08-17 22:59:59 +0000225
Richard Smithdd4ad3d2016-08-30 19:06:26 +0000226 // --precompile only runs up to precompilation.
227 } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile))) {
228 FinalPhase = phases::Precompile;
229
Bob Wilson23a55f12014-12-21 07:00:00 +0000230 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
Chad Rosier7742b5d2011-07-27 23:36:45 +0000231 } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000232 (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
Ben Langmuir2cb4a782014-02-05 22:21:15 +0000233 (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
Chad Rosier7742b5d2011-07-27 23:36:45 +0000234 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
Fariborz Jahanian73223bb2012-04-02 15:59:19 +0000235 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
Ted Kremenekf7639e12012-03-06 20:06:33 +0000236 (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
Chad Rosier7742b5d2011-07-27 23:36:45 +0000237 (PhaseArg = DAL.getLastArg(options::OPT__analyze,
Chad Rosier1aeb15a2012-03-06 23:14:35 +0000238 options::OPT__analyze_auto)) ||
Bob Wilson23a55f12014-12-21 07:00:00 +0000239 (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000240 FinalPhase = phases::Compile;
241
Bob Wilson23a55f12014-12-21 07:00:00 +0000242 // -S only runs up to the backend.
243 } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
244 FinalPhase = phases::Backend;
245
Artem Belevich4242f412015-07-28 21:01:21 +0000246 // -c compilation only runs up to the assembler.
247 } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000248 FinalPhase = phases::Assemble;
249
250 // Otherwise do everything.
251 } else
252 FinalPhase = phases::Link;
253
254 if (FinalPhaseArg)
255 *FinalPhaseArg = PhaseArg;
256
257 return FinalPhase;
258}
259
David Blaikie0aaa7622017-01-13 17:34:15 +0000260static Arg *MakeInputArg(DerivedArgList &Args, OptTable &Opts,
Hans Wennborged1d0722013-08-13 21:32:29 +0000261 StringRef Value) {
David Blaikie0aaa7622017-01-13 17:34:15 +0000262 Arg *A = new Arg(Opts.getOption(options::OPT_INPUT), Value,
Hans Wennborged1d0722013-08-13 21:32:29 +0000263 Args.getBaseArgs().MakeIndex(Value), Value.data());
Hans Wennborg55362852014-05-02 22:55:30 +0000264 Args.AddSynthesizedArg(A);
Hans Wennborged1d0722013-08-13 21:32:29 +0000265 A->claim();
266 return A;
267}
268
Daniel Dunbar775d4062010-06-11 22:00:26 +0000269DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
270 DerivedArgList *DAL = new DerivedArgList(Args);
271
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000272 bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
Nirav Daveb0bb6142015-11-24 16:07:21 +0000273 bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +0000274 for (Arg *A : Args) {
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000275 // Unfortunately, we have to parse some forwarding options (-Xassembler,
276 // -Xlinker, -Xpreprocessor) because we either integrate their functionality
277 // (assembler and preprocessor), or bypass a previous driver ('collect2').
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000278
279 // Rewrite linker options, to replace --no-demangle with a custom internal
280 // option.
281 if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
282 A->getOption().matches(options::OPT_Xlinker)) &&
283 A->containsValue("--no-demangle")) {
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000284 // Add the rewritten no-demangle argument.
285 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
286
287 // Add the remaining values as Xlinker arguments.
Benjamin Kramer72e64312015-09-24 14:48:49 +0000288 for (StringRef Val : A->getValues())
Douglas Katzmana34b7bf2015-06-30 19:32:57 +0000289 if (Val != "--no-demangle")
290 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), Val);
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000291
292 continue;
293 }
294
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000295 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
296 // some build systems. We don't try to be complete here because we don't
297 // care to encourage this usage model.
298 if (A->getOption().matches(options::OPT_Wp_COMMA) &&
Richard Smithbd55daf2012-11-01 04:30:05 +0000299 (A->getValue(0) == StringRef("-MD") ||
300 A->getValue(0) == StringRef("-MMD"))) {
Daniel Dunbar3648ba72010-06-15 20:30:18 +0000301 // Rewrite to -MD/-MMD along with -MF.
Richard Smithbd55daf2012-11-01 04:30:05 +0000302 if (A->getValue(0) == StringRef("-MD"))
Daniel Dunbar3648ba72010-06-15 20:30:18 +0000303 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
304 else
305 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
Michael J. Spencer70d85be2012-11-07 23:37:14 +0000306 if (A->getNumValues() == 2)
307 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
308 A->getValue(1));
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000309 continue;
310 }
311
Shantonu Senafeb03b2010-09-17 18:39:08 +0000312 // Rewrite reserved library names.
313 if (A->getOption().matches(options::OPT_l)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000314 StringRef Value = A->getValue();
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000315
Shantonu Senafeb03b2010-09-17 18:39:08 +0000316 // Rewrite unless -nostdlib is present.
Nirav Daveb0bb6142015-11-24 16:07:21 +0000317 if (!HasNostdlib && !HasNodefaultlib && Value == "stdc++") {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000318 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_stdcxx));
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000319 continue;
320 }
Shantonu Senafeb03b2010-09-17 18:39:08 +0000321
322 // Rewrite unconditionally.
323 if (Value == "cc_kext") {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000324 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_cckext));
Shantonu Senafeb03b2010-09-17 18:39:08 +0000325 continue;
326 }
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000327 }
328
Hans Wennborged1d0722013-08-13 21:32:29 +0000329 // Pick up inputs via the -- option.
330 if (A->getOption().matches(options::OPT__DASH_DASH)) {
331 A->claim();
Benjamin Kramer72e64312015-09-24 14:48:49 +0000332 for (StringRef Val : A->getValues())
David Blaikie0aaa7622017-01-13 17:34:15 +0000333 DAL->append(MakeInputArg(*DAL, *Opts, Val));
Hans Wennborged1d0722013-08-13 21:32:29 +0000334 continue;
335 }
336
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +0000337 DAL->append(A);
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000338 }
Daniel Dunbar775d4062010-06-11 22:00:26 +0000339
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000340 // Enforce -static if -miamcu is present.
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000341 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false))
342 DAL->AddFlagArg(0, Opts->getOption(options::OPT_static));
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000343
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000344// Add a default value of -mlinker-version=, if one was given and the user
345// didn't specify one.
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000346#if defined(HOST_LINK_VERSION)
Tim Northover018578c2015-06-12 19:21:35 +0000347 if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
348 strlen(HOST_LINK_VERSION) > 0) {
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000349 DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
350 HOST_LINK_VERSION);
Daniel Dunbarb613ffc2010-08-17 22:32:45 +0000351 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000352 }
353#endif
354
Daniel Dunbar775d4062010-06-11 22:00:26 +0000355 return DAL;
356}
357
Artem Belevich959e0542015-07-10 19:47:55 +0000358/// \brief Compute target triple from args.
359///
360/// This routine provides the logic to compute a target triple from various
361/// args passed to the driver and the default triple string.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000362static llvm::Triple computeTargetTriple(const Driver &D,
363 StringRef DefaultTargetTriple,
Artem Belevich959e0542015-07-10 19:47:55 +0000364 const ArgList &Args,
365 StringRef DarwinArchName = "") {
366 // FIXME: Already done in Compilation *Driver::BuildCompilation
367 if (const Arg *A = Args.getLastArg(options::OPT_target))
368 DefaultTargetTriple = A->getValue();
369
370 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
371
372 // Handle Apple-specific options available here.
373 if (Target.isOSBinFormatMachO()) {
374 // If an explict Darwin arch name is given, that trumps all.
375 if (!DarwinArchName.empty()) {
376 tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
377 return Target;
378 }
379
380 // Handle the Darwin '-arch' flag.
381 if (Arg *A = Args.getLastArg(options::OPT_arch)) {
382 StringRef ArchName = A->getValue();
383 tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
384 }
385 }
386
387 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
388 // '-mbig-endian'/'-EB'.
389 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
390 options::OPT_mbig_endian)) {
391 if (A->getOption().matches(options::OPT_mlittle_endian)) {
392 llvm::Triple LE = Target.getLittleEndianArchVariant();
393 if (LE.getArch() != llvm::Triple::UnknownArch)
394 Target = std::move(LE);
395 } else {
396 llvm::Triple BE = Target.getBigEndianArchVariant();
397 if (BE.getArch() != llvm::Triple::UnknownArch)
398 Target = std::move(BE);
399 }
400 }
401
402 // Skip further flag support on OSes which don't support '-m32' or '-m64'.
Douglas Katzman15a63ed2015-08-12 18:36:12 +0000403 if (Target.getArch() == llvm::Triple::tce ||
404 Target.getOS() == llvm::Triple::Minix)
Artem Belevich959e0542015-07-10 19:47:55 +0000405 return Target;
406
407 // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000408 Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
409 options::OPT_m32, options::OPT_m16);
410 if (A) {
Artem Belevich959e0542015-07-10 19:47:55 +0000411 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
412
413 if (A->getOption().matches(options::OPT_m64)) {
414 AT = Target.get64BitArchVariant().getArch();
415 if (Target.getEnvironment() == llvm::Triple::GNUX32)
416 Target.setEnvironment(llvm::Triple::GNU);
417 } else if (A->getOption().matches(options::OPT_mx32) &&
418 Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
419 AT = llvm::Triple::x86_64;
420 Target.setEnvironment(llvm::Triple::GNUX32);
421 } else if (A->getOption().matches(options::OPT_m32)) {
422 AT = Target.get32BitArchVariant().getArch();
423 if (Target.getEnvironment() == llvm::Triple::GNUX32)
424 Target.setEnvironment(llvm::Triple::GNU);
425 } else if (A->getOption().matches(options::OPT_m16) &&
426 Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
427 AT = llvm::Triple::x86;
428 Target.setEnvironment(llvm::Triple::CODE16);
429 }
430
431 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
432 Target.setArch(AT);
433 }
434
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000435 // Handle -miamcu flag.
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000436 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
437 if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
438 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
439 << Target.str();
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000440
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000441 if (A && !A->getOption().matches(options::OPT_m32))
442 D.Diag(diag::err_drv_argument_not_allowed_with)
443 << "-miamcu" << A->getBaseArg().getAsString(Args);
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000444
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000445 Target.setArch(llvm::Triple::x86);
446 Target.setArchName("i586");
447 Target.setEnvironment(llvm::Triple::UnknownEnvironment);
448 Target.setEnvironmentName("");
449 Target.setOS(llvm::Triple::ELFIAMCU);
450 Target.setVendor(llvm::Triple::UnknownVendor);
451 Target.setVendorName("intel");
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000452 }
453
Artem Belevich959e0542015-07-10 19:47:55 +0000454 return Target;
455}
456
Teresa Johnson945bc502015-10-15 20:35:53 +0000457// \brief Parse the LTO options and record the type of LTO compilation
458// based on which -f(no-)?lto(=.*)? option occurs last.
459void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
460 LTOMode = LTOK_None;
461 if (!Args.hasFlag(options::OPT_flto, options::OPT_flto_EQ,
462 options::OPT_fno_lto, false))
463 return;
464
465 StringRef LTOName("full");
466
467 const Arg *A = Args.getLastArg(options::OPT_flto_EQ);
Teresa Johnson6ef80dc2015-11-02 18:03:12 +0000468 if (A)
469 LTOName = A->getValue();
Teresa Johnson945bc502015-10-15 20:35:53 +0000470
471 LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
472 .Case("full", LTOK_Full)
473 .Case("thin", LTOK_Thin)
474 .Default(LTOK_Unknown);
475
476 if (LTOMode == LTOK_Unknown) {
477 assert(A);
478 Diag(diag::err_drv_unsupported_option_argument) << A->getOption().getName()
479 << A->getValue();
480 }
481}
482
Samuel Antao39f9da22016-10-27 16:38:05 +0000483/// Compute the desired OpenMP runtime from the flags provided.
484Driver::OpenMPRuntimeKind Driver::getOpenMPRuntime(const ArgList &Args) const {
485 StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
486
487 const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
488 if (A)
489 RuntimeName = A->getValue();
490
491 auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
492 .Case("libomp", OMPRT_OMP)
493 .Case("libgomp", OMPRT_GOMP)
494 .Case("libiomp5", OMPRT_IOMP5)
495 .Default(OMPRT_Unknown);
496
497 if (RT == OMPRT_Unknown) {
498 if (A)
499 Diag(diag::err_drv_unsupported_option_argument)
500 << A->getOption().getName() << A->getValue();
501 else
502 // FIXME: We could use a nicer diagnostic here.
503 Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
504 }
505
506 return RT;
507}
508
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000509void Driver::CreateOffloadingDeviceToolChains(Compilation &C,
510 InputList &Inputs) {
511
512 //
513 // CUDA
514 //
515 // We need to generate a CUDA toolchain if any of the inputs has a CUDA type.
516 if (llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
517 return types::isCuda(I.first);
518 })) {
Justin Lebar66c4fd72016-11-18 00:41:22 +0000519 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
520 const llvm::Triple &HostTriple = HostTC->getTriple();
521 llvm::Triple CudaTriple(HostTriple.isArch64Bit() ? "nvptx64-nvidia-cuda"
522 : "nvptx-nvidia-cuda");
523 // Use the CUDA and host triples as the key into the ToolChains map, because
524 // the device toolchain we create depends on both.
David Blaikie6ad71012017-01-13 18:53:43 +0000525 auto &CudaTC = ToolChains[CudaTriple.str() + "/" + HostTriple.str()];
Justin Lebar66c4fd72016-11-18 00:41:22 +0000526 if (!CudaTC) {
David Blaikie6ad71012017-01-13 18:53:43 +0000527 CudaTC = llvm::make_unique<toolchains::CudaToolChain>(
528 *this, CudaTriple, *HostTC, C.getInputArgs());
Justin Lebar66c4fd72016-11-18 00:41:22 +0000529 }
David Blaikie6ad71012017-01-13 18:53:43 +0000530 C.addOffloadDeviceToolChain(CudaTC.get(), Action::OFK_Cuda);
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000531 }
532
533 //
Samuel Antao39f9da22016-10-27 16:38:05 +0000534 // OpenMP
535 //
536 // We need to generate an OpenMP toolchain if the user specified targets with
537 // the -fopenmp-targets option.
538 if (Arg *OpenMPTargets =
539 C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
540 if (OpenMPTargets->getNumValues()) {
541 // We expect that -fopenmp-targets is always used in conjunction with the
542 // option -fopenmp specifying a valid runtime with offloading support,
543 // i.e. libomp or libiomp.
544 bool HasValidOpenMPRuntime = C.getInputArgs().hasFlag(
545 options::OPT_fopenmp, options::OPT_fopenmp_EQ,
546 options::OPT_fno_openmp, false);
547 if (HasValidOpenMPRuntime) {
548 OpenMPRuntimeKind OpenMPKind = getOpenMPRuntime(C.getInputArgs());
549 HasValidOpenMPRuntime =
550 OpenMPKind == OMPRT_OMP || OpenMPKind == OMPRT_IOMP5;
551 }
552
553 if (HasValidOpenMPRuntime) {
554 llvm::StringMap<const char *> FoundNormalizedTriples;
555 for (const char *Val : OpenMPTargets->getValues()) {
556 llvm::Triple TT(Val);
557 std::string NormalizedName = TT.normalize();
558
559 // Make sure we don't have a duplicate triple.
560 auto Duplicate = FoundNormalizedTriples.find(NormalizedName);
561 if (Duplicate != FoundNormalizedTriples.end()) {
562 Diag(clang::diag::warn_drv_omp_offload_target_duplicate)
563 << Val << Duplicate->second;
564 continue;
565 }
566
567 // Store the current triple so that we can check for duplicates in the
568 // following iterations.
569 FoundNormalizedTriples[NormalizedName] = Val;
570
571 // If the specified target is invalid, emit a diagnostic.
572 if (TT.getArch() == llvm::Triple::UnknownArch)
573 Diag(clang::diag::err_drv_invalid_omp_target) << Val;
574 else {
Gheorghe-Teodor Bercea6a5df722017-07-06 16:08:15 +0000575 const ToolChain *TC;
576 // CUDA toolchains have to be selected differently. They pair host
577 // and device in their implementation.
578 if (TT.isNVPTX()) {
579 const ToolChain *HostTC =
580 C.getSingleOffloadToolChain<Action::OFK_Host>();
581 assert(HostTC && "Host toolchain should be always defined.");
582 auto &CudaTC =
583 ToolChains[TT.str() + "/" + HostTC->getTriple().str()];
584 if (!CudaTC)
585 CudaTC = llvm::make_unique<toolchains::CudaToolChain>(
586 *this, TT, *HostTC, C.getInputArgs());
587 TC = CudaTC.get();
588 } else
589 TC = &getToolChain(C.getInputArgs(), TT);
590 C.addOffloadDeviceToolChain(TC, Action::OFK_OpenMP);
Samuel Antao39f9da22016-10-27 16:38:05 +0000591 }
592 }
593 } else
594 Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
595 } else
596 Diag(clang::diag::warn_drv_empty_joined_argument)
597 << OpenMPTargets->getAsString(C.getInputArgs());
598 }
599
600 //
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000601 // TODO: Add support for other offloading programming models here.
602 //
603
604 return;
605}
606
Chris Lattner54b16772011-07-23 17:14:25 +0000607Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
Daniel Dunbar2608c542009-03-18 01:38:48 +0000608 llvm::PrettyStackTraceString CrashInfo("Compilation construction");
609
Eric Christopherf901e852011-08-17 22:59:59 +0000610 // FIXME: Handle environment options which affect driver behavior, somewhere
Bill Wendlingadbeb9f2012-03-12 21:24:57 +0000611 // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
Chad Rosier82301162011-09-14 00:47:55 +0000612
David Majnemer85c25b42016-07-24 17:44:03 +0000613 if (Optional<std::string> CompilerPathValue =
614 llvm::sys::Process::GetEnv("COMPILER_PATH")) {
615 StringRef CompilerPath = *CompilerPathValue;
Chad Rosier82301162011-09-14 00:47:55 +0000616 while (!CompilerPath.empty()) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000617 std::pair<StringRef, StringRef> Split =
618 CompilerPath.split(llvm::sys::EnvPathSeparator);
Chad Rosier82301162011-09-14 00:47:55 +0000619 PrefixDirs.push_back(Split.first);
620 CompilerPath = Split.second;
621 }
622 }
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +0000623
Hans Wennborg70850d82013-07-18 20:29:38 +0000624 // We look for the driver mode option early, because the mode can affect
625 // how other options are parsed.
Zachary Turneraff19c32016-08-12 17:47:52 +0000626 ParseDriverMode(ClangExecutable, ArgList.slice(1));
Hans Wennborg70850d82013-07-18 20:29:38 +0000627
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +0000628 // FIXME: What are we going to do with -V and -b?
629
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +0000630 // FIXME: This stuff needs to go into the Compilation, not the driver.
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +0000631 bool CCCPrintPhases;
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000632
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000633 bool ContainsError;
634 InputArgList Args = ParseArgStrings(ArgList.slice(1), ContainsError);
Daniel Dunbaracd69572009-12-04 21:55:23 +0000635
Filipe Cabecinhas136f35e2015-07-18 06:35:24 +0000636 // Silence driver warnings if requested
637 Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w));
638
Rafael Espindola59ae7992009-12-07 18:28:29 +0000639 // -no-canonical-prefixes is used very early in main.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000640 Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
Rafael Espindola59ae7992009-12-07 18:28:29 +0000641
Daniel Dunbar926f81f2010-08-02 02:38:03 +0000642 // Ignore -pipe.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000643 Args.ClaimAllArgs(options::OPT_pipe);
Daniel Dunbar926f81f2010-08-02 02:38:03 +0000644
Daniel Dunbaracd69572009-12-04 21:55:23 +0000645 // Extract -ccc args.
Daniel Dunbaree66cf22009-03-10 20:52:46 +0000646 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +0000647 // FIXME: We need to figure out where this behavior should live. Most of it
648 // should be outside in the client; the parts that aren't should have proper
649 // options, either by introducing new ones or by overloading gcc ones like -V
650 // or -b.
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +0000651 CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
David Blaikie69a1d8c2015-06-22 22:07:27 +0000652 CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
653 if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
Richard Smithbd55daf2012-11-01 04:30:05 +0000654 CCCGenericGCCName = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000655 CCCUsePCH =
656 Args.hasFlag(options::OPT_ccc_pch_is_pch, options::OPT_ccc_pch_is_pth);
Bruno Cardoso Lopes52dfe712017-04-12 21:46:20 +0000657 GenReproducer = Args.hasFlag(options::OPT_gen_reproducer,
658 options::OPT_fno_crash_diagnostics,
659 !!::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH"));
Joerg Sonnenberger17d75512012-02-22 19:15:16 +0000660 // FIXME: DefaultTargetTriple is used by the target-prefixed calls to as/ld
661 // and getToolChain is const.
Hans Wennborg2e274592013-08-13 23:38:57 +0000662 if (IsCLMode()) {
Hans Wennborg73609a02014-03-28 01:19:04 +0000663 // clang-cl targets MSVC-style Win32.
Hans Wennborg2e274592013-08-13 23:38:57 +0000664 llvm::Triple T(DefaultTargetTriple);
Hans Wennborg9d9ce7a2014-03-28 20:49:28 +0000665 T.setOS(llvm::Triple::Win32);
Hans Wennborg0f0e8d62015-09-18 17:11:50 +0000666 T.setVendor(llvm::Triple::PC);
Hans Wennborg9d9ce7a2014-03-28 20:49:28 +0000667 T.setEnvironment(llvm::Triple::MSVC);
Hans Wennborg2e274592013-08-13 23:38:57 +0000668 DefaultTargetTriple = T.str();
669 }
David Blaikie69a1d8c2015-06-22 22:07:27 +0000670 if (const Arg *A = Args.getLastArg(options::OPT_target))
Richard Smithbd55daf2012-11-01 04:30:05 +0000671 DefaultTargetTriple = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000672 if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
Richard Smithbd55daf2012-11-01 04:30:05 +0000673 Dir = InstalledDir = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000674 for (const Arg *A : Args.filtered(options::OPT_B)) {
Benjamin Kramer1a648d12011-02-08 20:31:42 +0000675 A->claim();
Richard Smithbd55daf2012-11-01 04:30:05 +0000676 PrefixDirs.push_back(A->getValue(0));
Benjamin Kramer1a648d12011-02-08 20:31:42 +0000677 }
David Blaikie69a1d8c2015-06-22 22:07:27 +0000678 if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
Richard Smithbd55daf2012-11-01 04:30:05 +0000679 SysRoot = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000680 if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
Peter Collingbourne9d9e1fc2013-05-27 21:40:20 +0000681 DyldPrefix = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000682 if (Args.hasArg(options::OPT_nostdlib))
Joerg Sonnenbergerbc923f32011-03-21 13:59:26 +0000683 UseStdLib = false;
Daniel Dunbaree66cf22009-03-10 20:52:46 +0000684
David Blaikie69a1d8c2015-06-22 22:07:27 +0000685 if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
Bob Wilsona20a1da2013-03-23 05:17:59 +0000686 ResourceDir = A->getValue();
Jim Grosbach061dabf2013-03-12 20:17:58 +0000687
David Blaikie69a1d8c2015-06-22 22:07:27 +0000688 if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
Reid Kleckner68eb60b2015-02-02 22:41:48 +0000689 SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
690 .Case("cwd", SaveTempsCwd)
691 .Case("obj", SaveTempsObj)
692 .Default(SaveTempsCwd);
693 }
694
Steven Wu1257cd82016-05-18 17:04:52 +0000695 setLTOMode(Args);
696
Steven Wu844ab6a2016-11-16 06:06:44 +0000697 // Process -fembed-bitcode= flags.
698 if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
699 StringRef Name = A->getValue();
700 unsigned Model = llvm::StringSwitch<unsigned>(Name)
701 .Case("off", EmbedNone)
702 .Case("all", EmbedBitcode)
703 .Case("bitcode", EmbedBitcode)
704 .Case("marker", EmbedMarker)
705 .Default(~0U);
706 if (Model == ~0U) {
707 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
708 << Name;
709 } else
710 BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
Steven Wu574b0f22016-03-01 01:07:58 +0000711 }
712
David Blaikie69a1d8c2015-06-22 22:07:27 +0000713 std::unique_ptr<llvm::opt::InputArgList> UArgs =
714 llvm::make_unique<InputArgList>(std::move(Args));
715
Daniel Dunbar775d4062010-06-11 22:00:26 +0000716 // Perform the default argument translations.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000717 DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
Daniel Dunbar775d4062010-06-11 22:00:26 +0000718
Chandler Carruthcb916192012-01-25 08:49:21 +0000719 // Owned by the host.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000720 const ToolChain &TC = getToolChain(
721 *UArgs, computeTargetTriple(*this, DefaultTargetTriple, *UArgs));
Chandler Carruthcb916192012-01-25 08:49:21 +0000722
Daniel Dunbar3ce436d2009-03-16 06:42:30 +0000723 // The compilation takes ownership of Args.
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000724 Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs,
725 ContainsError);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +0000726
Daniel Dunbarf0eddb82009-03-18 02:55:38 +0000727 if (!HandleImmediateArgs(*C))
728 return C;
729
Chad Rosierecdede82011-08-12 22:08:57 +0000730 // Construct the list of inputs.
731 InputList Inputs;
Hans Wennborged1d0722013-08-13 21:32:29 +0000732 BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
Chad Rosierecdede82011-08-12 22:08:57 +0000733
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000734 // Populate the tool chains for the offloading devices, if any.
735 CreateOffloadingDeviceToolChains(*C, Inputs);
Justin Lebar0e450a52016-03-30 23:30:25 +0000736
Chandler Carruth7f1417f2012-01-24 10:43:44 +0000737 // Construct the list of abstract actions to perform for this compilation. On
Tim Northover157d9112014-01-16 08:48:16 +0000738 // MachO targets this uses the driver-driver and universal actions.
739 if (TC.getTriple().isOSBinFormatMachO())
Artem Belevich5e2a3ec2015-11-17 22:28:40 +0000740 BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +0000741 else
Justin Lebar0f3474c2016-02-11 02:00:50 +0000742 BuildActions(*C, C->getArgs(), Inputs, C->getActions());
Daniel Dunbarf0eddb82009-03-18 02:55:38 +0000743
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +0000744 if (CCCPrintPhases) {
Daniel Dunbareb843be2009-03-18 03:13:20 +0000745 PrintActions(*C);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +0000746 return C;
747 }
748
749 BuildJobs(*C);
Daniel Dunbaradc91e62009-03-15 01:38:15 +0000750
751 return C;
Daniel Dunbaree66cf22009-03-10 20:52:46 +0000752}
753
Justin Bognered9cbe02015-07-09 06:58:31 +0000754static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
755 llvm::opt::ArgStringList ASL;
756 for (const auto *A : Args)
757 A->render(Args, ASL);
758
759 for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
760 if (I != ASL.begin())
761 OS << ' ';
762 Command::printArg(OS, *I, true);
763 }
764 OS << '\n';
765}
766
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +0000767bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename,
768 SmallString<128> &CrashDiagDir) {
769 using namespace llvm::sys;
770 assert(llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin() &&
771 "Only knows about .crash files on Darwin");
772
773 // The .crash file can be found on at ~/Library/Logs/DiagnosticReports/
774 // (or /Library/Logs/DiagnosticReports for root) and has the filename pattern
775 // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash.
776 path::home_directory(CrashDiagDir);
777 if (CrashDiagDir.startswith("/var/root"))
778 CrashDiagDir = "/";
779 path::append(CrashDiagDir, "Library/Logs/DiagnosticReports");
780 int PID =
781#if LLVM_ON_UNIX
782 getpid();
783#else
784 0;
785#endif
786 std::error_code EC;
787 fs::file_status FileStatus;
788 TimePoint<> LastAccessTime;
789 SmallString<128> CrashFilePath;
790 // Lookup the .crash files and get the one generated by a subprocess spawned
791 // by this driver invocation.
792 for (fs::directory_iterator File(CrashDiagDir, EC), FileEnd;
793 File != FileEnd && !EC; File.increment(EC)) {
794 StringRef FileName = path::filename(File->path());
795 if (!FileName.startswith(Name))
796 continue;
797 if (fs::status(File->path(), FileStatus))
798 continue;
799 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CrashFile =
800 llvm::MemoryBuffer::getFile(File->path());
801 if (!CrashFile)
802 continue;
803 // The first line should start with "Process:", otherwise this isn't a real
804 // .crash file.
805 StringRef Data = CrashFile.get()->getBuffer();
806 if (!Data.startswith("Process:"))
807 continue;
808 // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]"
809 size_t ParentProcPos = Data.find("Parent Process:");
810 if (ParentProcPos == StringRef::npos)
811 continue;
812 size_t LineEnd = Data.find_first_of("\n", ParentProcPos);
813 if (LineEnd == StringRef::npos)
814 continue;
815 StringRef ParentProcess = Data.slice(ParentProcPos+15, LineEnd).trim();
816 int OpenBracket = -1, CloseBracket = -1;
817 for (size_t i = 0, e = ParentProcess.size(); i < e; ++i) {
818 if (ParentProcess[i] == '[')
819 OpenBracket = i;
820 if (ParentProcess[i] == ']')
821 CloseBracket = i;
822 }
823 // Extract the parent process PID from the .crash file and check whether
824 // it matches this driver invocation pid.
825 int CrashPID;
826 if (OpenBracket < 0 || CloseBracket < 0 ||
827 ParentProcess.slice(OpenBracket + 1, CloseBracket)
828 .getAsInteger(10, CrashPID) || CrashPID != PID) {
829 continue;
830 }
831
832 // Found a .crash file matching the driver pid. To avoid getting an older
833 // and misleading crash file, continue looking for the most recent.
834 // FIXME: the driver can dispatch multiple cc1 invocations, leading to
835 // multiple crashes poiting to the same parent process. Since the driver
836 // does not collect pid information for the dispatched invocation there's
837 // currently no way to distinguish among them.
838 const auto FileAccessTime = FileStatus.getLastModificationTime();
839 if (FileAccessTime > LastAccessTime) {
840 CrashFilePath.assign(File->path());
841 LastAccessTime = FileAccessTime;
842 }
843 }
844
845 // If found, copy it over to the location of other reproducer files.
846 if (!CrashFilePath.empty()) {
847 EC = fs::copy_file(CrashFilePath, ReproCrashFilename);
848 if (EC)
849 return false;
850 return true;
851 }
852
853 return false;
854}
855
Eric Christopherf901e852011-08-17 22:59:59 +0000856// When clang crashes, produce diagnostic information including the fully
857// preprocessed source file(s). Request that the developer attach the
Chad Rosierbe10f982011-08-02 17:58:04 +0000858// diagnostic information to a bug report.
859void Driver::generateCompilationDiagnostics(Compilation &C,
Justin Bognere1a33d12014-10-20 21:02:05 +0000860 const Command &FailingCommand) {
Chad Rosier877c0a22012-02-22 00:30:39 +0000861 if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
Chad Rosier62135492012-07-09 17:31:28 +0000862 return;
Chad Rosierbee5a1d2012-03-07 00:30:40 +0000863
Chad Rosierdbf46a12013-02-01 18:30:26 +0000864 // Don't try to generate diagnostics for link or dsymutil jobs.
Justin Bognere1a33d12014-10-20 21:02:05 +0000865 if (FailingCommand.getCreator().isLinkJob() ||
866 FailingCommand.getCreator().isDsymutilJob())
Chad Rosier877c0a22012-02-22 00:30:39 +0000867 return;
868
Chad Rosier8179f112012-06-19 17:51:34 +0000869 // Print the version of the compiler.
870 PrintVersion(C, llvm::errs());
871
Chad Rosierbe10f982011-08-02 17:58:04 +0000872 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000873 << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the "
874 "crash backtrace, preprocessed source, and associated run script.";
Chad Rosierbe10f982011-08-02 17:58:04 +0000875
876 // Suppress driver output and emit preprocessor output to temp file.
Hans Wennborg70850d82013-07-18 20:29:38 +0000877 Mode = CPPMode;
Chad Rosierbe10f982011-08-02 17:58:04 +0000878 CCGenDiagnostics = true;
879
Chad Rosiercdb008d2011-11-02 21:29:05 +0000880 // Save the original job command(s).
Justin Bogner25645152014-10-21 17:24:44 +0000881 Command Cmd = FailingCommand;
Chad Rosiercdb008d2011-11-02 21:29:05 +0000882
Richard Smith5bb4cdf2012-12-20 02:22:15 +0000883 // Keep track of whether we produce any errors while trying to produce
884 // preprocessed sources.
885 DiagnosticErrorTrap Trap(Diags);
886
887 // Suppress tool output.
Chad Rosierbe10f982011-08-02 17:58:04 +0000888 C.initCompilationForDiagnostics();
Chad Rosierecdede82011-08-12 22:08:57 +0000889
890 // Construct the list of inputs.
891 InputList Inputs;
892 BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
Chad Rosierbe10f982011-08-02 17:58:04 +0000893
Chad Rosier4f81fc22011-08-12 23:30:05 +0000894 for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
Chad Rosierd57133d2011-08-18 00:22:25 +0000895 bool IgnoreInput = false;
896
897 // Ignore input from stdin or any inputs that cannot be preprocessed.
Paul Robinsonf44157d2014-04-28 22:24:44 +0000898 // Check type first as not all linker inputs have a value.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000899 if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
Paul Robinsonf44157d2014-04-28 22:24:44 +0000900 IgnoreInput = true;
901 } else if (!strcmp(it->second->getValue(), "-")) {
Chad Rosierd57133d2011-08-18 00:22:25 +0000902 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000903 << "Error generating preprocessed source(s) - "
904 "ignoring input from stdin.";
Chad Rosierd57133d2011-08-18 00:22:25 +0000905 IgnoreInput = true;
Chad Rosierd57133d2011-08-18 00:22:25 +0000906 }
907
908 if (IgnoreInput) {
Chad Rosier4f81fc22011-08-12 23:30:05 +0000909 it = Inputs.erase(it);
910 ie = Inputs.end();
Chad Rosier6fdf38b2011-08-17 23:08:45 +0000911 } else {
Chad Rosier4f81fc22011-08-12 23:30:05 +0000912 ++it;
Chad Rosier6fdf38b2011-08-17 23:08:45 +0000913 }
Chad Rosier4f81fc22011-08-12 23:30:05 +0000914 }
Chad Rosierd57133d2011-08-18 00:22:25 +0000915
Chad Rosierc5103c32013-01-29 23:57:10 +0000916 if (Inputs.empty()) {
917 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000918 << "Error generating preprocessed source(s) - "
919 "no preprocessable inputs.";
Chad Rosierc5103c32013-01-29 23:57:10 +0000920 return;
921 }
922
Chad Rosiere75ef402011-09-06 23:52:36 +0000923 // Don't attempt to generate preprocessed files if multiple -arch options are
Chad Rosier636d2832012-02-13 18:16:28 +0000924 // used, unless they're all duplicates.
925 llvm::StringSet<> ArchNames;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +0000926 for (const Arg *A : C.getArgs()) {
Chad Rosiere75ef402011-09-06 23:52:36 +0000927 if (A->getOption().matches(options::OPT_arch)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000928 StringRef ArchName = A->getValue();
Chad Rosier636d2832012-02-13 18:16:28 +0000929 ArchNames.insert(ArchName);
Chad Rosiere75ef402011-09-06 23:52:36 +0000930 }
931 }
Chad Rosier636d2832012-02-13 18:16:28 +0000932 if (ArchNames.size() > 1) {
933 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000934 << "Error generating preprocessed source(s) - cannot generate "
935 "preprocessed source with multiple -arch options.";
Chad Rosier636d2832012-02-13 18:16:28 +0000936 return;
937 }
Chad Rosiere75ef402011-09-06 23:52:36 +0000938
Chandler Carruth7f1417f2012-01-24 10:43:44 +0000939 // Construct the list of abstract actions to perform for this compilation. On
940 // Darwin OSes this uses the driver-driver and builds universal actions.
Chandler Carruthcb916192012-01-25 08:49:21 +0000941 const ToolChain &TC = C.getDefaultToolChain();
Tim Northover157d9112014-01-16 08:48:16 +0000942 if (TC.getTriple().isOSBinFormatMachO())
Artem Belevich5e2a3ec2015-11-17 22:28:40 +0000943 BuildUniversalActions(C, TC, Inputs);
Chad Rosierbe10f982011-08-02 17:58:04 +0000944 else
Justin Lebar0f3474c2016-02-11 02:00:50 +0000945 BuildActions(C, C.getArgs(), Inputs, C.getActions());
Chad Rosierbe10f982011-08-02 17:58:04 +0000946
947 BuildJobs(C);
948
949 // If there were errors building the compilation, quit now.
Richard Smith5bb4cdf2012-12-20 02:22:15 +0000950 if (Trap.hasErrorOccurred()) {
Chad Rosierbe10f982011-08-02 17:58:04 +0000951 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000952 << "Error generating preprocessed source(s).";
Chad Rosierbe10f982011-08-02 17:58:04 +0000953 return;
954 }
955
956 // Generate preprocessed output.
Chad Rosierdd60e092013-01-29 20:15:05 +0000957 SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
Justin Bogner0cd92482015-07-02 22:52:08 +0000958 C.ExecuteJobs(C.getJobs(), FailingCommands);
Chad Rosierbe10f982011-08-02 17:58:04 +0000959
Justin Bognerbc89b182014-10-20 21:20:27 +0000960 // If any of the preprocessing commands failed, clean up and exit.
961 if (!FailingCommands.empty()) {
Reid Kleckner68eb60b2015-02-02 22:41:48 +0000962 if (!isSaveTempsEnabled())
Chad Rosierbe10f982011-08-02 17:58:04 +0000963 C.CleanupFileList(C.getTempFiles(), true);
964
965 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000966 << "Error generating preprocessed source(s).";
Justin Bognerbc89b182014-10-20 21:20:27 +0000967 return;
Chad Rosierbe10f982011-08-02 17:58:04 +0000968 }
Justin Bognerbc89b182014-10-20 21:20:27 +0000969
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000970 const ArgStringList &TempFiles = C.getTempFiles();
971 if (TempFiles.empty()) {
972 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000973 << "Error generating preprocessed source(s).";
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000974 return;
975 }
976
Justin Bognerbc89b182014-10-20 21:20:27 +0000977 Diag(clang::diag::note_drv_command_failed_diag_msg)
978 << "\n********************\n\n"
979 "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
980 "Preprocessed source(s) and associated run script(s) are located at:";
Justin Bognerbc89b182014-10-20 21:20:27 +0000981
Justin Bogner659ecc32014-10-20 22:47:23 +0000982 SmallString<128> VFS;
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +0000983 SmallString<128> ReproCrashFilename;
Justin Bogner659ecc32014-10-20 22:47:23 +0000984 for (const char *TempFile : TempFiles) {
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000985 Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +0000986 if (ReproCrashFilename.empty()) {
987 ReproCrashFilename = TempFile;
988 llvm::sys::path::replace_extension(ReproCrashFilename, ".crash");
989 }
Justin Bogner659ecc32014-10-20 22:47:23 +0000990 if (StringRef(TempFile).endswith(".cache")) {
991 // In some cases (modules) we'll dump extra data to help with reproducing
992 // the crash into a directory next to the output.
993 VFS = llvm::sys::path::filename(TempFile);
994 llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
995 }
996 }
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000997
998 // Assume associated files are based off of the first temporary file.
Justin Bogner25645152014-10-21 17:24:44 +0000999 CrashReportInfo CrashInfo(TempFiles[0], VFS);
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001000
Justin Bogner25645152014-10-21 17:24:44 +00001001 std::string Script = CrashInfo.Filename.rsplit('.').first.str() + ".sh";
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001002 std::error_code EC;
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001003 llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::F_Excl);
1004 if (EC) {
1005 Diag(clang::diag::note_drv_command_failed_diag_msg)
1006 << "Error generating run script: " + Script + " " + EC.message();
1007 } else {
Justin Bogner42220ed2015-03-12 00:14:35 +00001008 ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
Justin Bognered9cbe02015-07-09 06:58:31 +00001009 << "# Driver args: ";
1010 printArgList(ScriptOS, C.getInputArgs());
1011 ScriptOS << "# Original command: ";
Justin Bogner42220ed2015-03-12 00:14:35 +00001012 Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
Justin Bogner33bdbc62014-10-21 18:03:08 +00001013 Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001014 Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
Justin Bognerbc89b182014-10-20 21:20:27 +00001015 }
Saleem Abdulrasool3661a822015-01-12 02:33:09 +00001016
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +00001017 // On darwin, provide information about the .crash diagnostic report.
1018 if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) {
1019 SmallString<128> CrashDiagDir;
1020 if (getCrashDiagnosticFile(ReproCrashFilename, CrashDiagDir)) {
1021 Diag(clang::diag::note_drv_command_failed_diag_msg)
1022 << ReproCrashFilename.str();
1023 } else { // Suggest a directory for the user to look for .crash files.
1024 llvm::sys::path::append(CrashDiagDir, Name);
1025 CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash";
1026 Diag(clang::diag::note_drv_command_failed_diag_msg)
1027 << "Crash backtrace is located in";
1028 Diag(clang::diag::note_drv_command_failed_diag_msg)
1029 << CrashDiagDir.str();
1030 Diag(clang::diag::note_drv_command_failed_diag_msg)
1031 << "(choose the .crash file that corresponds to your crash)";
1032 }
1033 }
1034
Saleem Abdulrasool3661a822015-01-12 02:33:09 +00001035 for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file,
1036 options::OPT_frewrite_map_file_EQ))
1037 Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
1038
Justin Bognerbc89b182014-10-20 21:20:27 +00001039 Diag(clang::diag::note_drv_command_failed_diag_msg)
1040 << "\n\n********************";
Chad Rosierbe10f982011-08-02 17:58:04 +00001041}
1042
Justin Bogner0cd92482015-07-02 22:52:08 +00001043void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
Oleg Ranevskyycd516372016-01-05 19:54:39 +00001044 // Since commandLineFitsWithinSystemLimits() may underestimate system's capacity
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001045 // if the tool does not support response files, there is a chance/ that things
1046 // will just work without a response file, so we silently just skip it.
Justin Bogner0cd92482015-07-02 22:52:08 +00001047 if (Cmd.getCreator().getResponseFilesSupport() == Tool::RF_None ||
Oleg Ranevskyycd516372016-01-05 19:54:39 +00001048 llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(), Cmd.getArguments()))
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001049 return;
1050
1051 std::string TmpName = GetTemporaryPath("response", "txt");
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00001052 Cmd.setResponseFile(C.addTempFile(C.getArgs().MakeArgString(TmpName)));
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001053}
1054
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001055int Driver::ExecuteCompilation(
1056 Compilation &C,
1057 SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001058 // Just print if -### was present.
1059 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
Hans Wennborgb212b342013-09-12 18:23:34 +00001060 C.getJobs().Print(llvm::errs(), "\n", true);
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001061 return 0;
1062 }
1063
1064 // If there were errors building the compilation, quit now.
Chad Rosierbe10f982011-08-02 17:58:04 +00001065 if (Diags.hasErrorOccurred())
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001066 return 1;
1067
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001068 // Set up response file names for each command, if necessary
Justin Bogner0cd92482015-07-02 22:52:08 +00001069 for (auto &Job : C.getJobs())
1070 setUpResponseFiles(C, Job);
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001071
Justin Bogner0cd92482015-07-02 22:52:08 +00001072 C.ExecuteJobs(C.getJobs(), FailingCommands);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001073
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001074 // Remove temp files.
1075 C.CleanupFileList(C.getTempFiles());
1076
Daniel Dunbar07494792010-05-22 00:37:20 +00001077 // If the command succeeded, we are done.
Chad Rosierdd60e092013-01-29 20:15:05 +00001078 if (FailingCommands.empty())
1079 return 0;
Daniel Dunbar07494792010-05-22 00:37:20 +00001080
Chad Rosierdd60e092013-01-29 20:15:05 +00001081 // Otherwise, remove result files and print extra information about abnormal
1082 // failures.
Douglas Katzman6bbffc42015-06-25 18:51:37 +00001083 for (const auto &CmdPair : FailingCommands) {
1084 int Res = CmdPair.first;
1085 const Command *FailingCommand = CmdPair.second;
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001086
Chad Rosierdd60e092013-01-29 20:15:05 +00001087 // Remove result files if we're not saving temps.
Reid Kleckner68eb60b2015-02-02 22:41:48 +00001088 if (!isSaveTempsEnabled()) {
Chad Rosierdd60e092013-01-29 20:15:05 +00001089 const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
1090 C.CleanupFileMap(C.getResultFiles(), JA, true);
1091
1092 // Failure result files are valid unless we crashed.
1093 if (Res < 0)
1094 C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
1095 }
1096
1097 // Print extra information about abnormal failures, if possible.
1098 //
1099 // This is ad-hoc, but we don't want to be excessively noisy. If the result
Justin Bogner5aaf2e72014-06-26 20:59:36 +00001100 // status was 1, assume the command failed normally. In particular, if it
Chad Rosierdd60e092013-01-29 20:15:05 +00001101 // was the compiler then assume it gave a reasonable error code. Failures
1102 // in other tools are less common, and they generally have worse
1103 // diagnostics, so always print the diagnostic there.
1104 const Tool &FailingTool = FailingCommand->getCreator();
1105
1106 if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
1107 // FIXME: See FIXME above regarding result code interpretation.
1108 if (Res < 0)
1109 Diag(clang::diag::err_drv_command_signalled)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001110 << FailingTool.getShortName();
Chad Rosierdd60e092013-01-29 20:15:05 +00001111 else
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001112 Diag(clang::diag::err_drv_command_failed) << FailingTool.getShortName()
1113 << Res;
Chad Rosierdd60e092013-01-29 20:15:05 +00001114 }
Peter Collingbourne119cfaa2011-11-21 00:01:05 +00001115 }
Chad Rosierdd60e092013-01-29 20:15:05 +00001116 return 0;
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001117}
1118
Daniel Dunbara7b5e212009-04-15 16:34:29 +00001119void Driver::PrintHelp(bool ShowHidden) const {
Hans Wennborg6ddc6902013-07-27 00:23:45 +00001120 unsigned IncludedFlagsBitmask;
1121 unsigned ExcludedFlagsBitmask;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001122 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001123 getIncludeExcludeOptionFlagMasks();
Hans Wennborg6ddc6902013-07-27 00:23:45 +00001124
1125 ExcludedFlagsBitmask |= options::NoDriverOption;
1126 if (!ShowHidden)
1127 ExcludedFlagsBitmask |= HelpHidden;
1128
1129 getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
1130 IncludedFlagsBitmask, ExcludedFlagsBitmask);
Daniel Dunbar7c925282009-03-31 21:38:17 +00001131}
1132
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001133void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001134 // FIXME: The following handlers should use a callback mechanism, we don't
1135 // know what the client would like to do.
Ted Kremenek4c0df3d2010-01-23 02:11:34 +00001136 OS << getClangFullVersion() << '\n';
Daniel Dunbarb10248802009-03-26 16:09:13 +00001137 const ToolChain &TC = C.getDefaultToolChain();
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001138 OS << "Target: " << TC.getTripleString() << '\n';
Daniel Dunbar10978e42009-06-16 23:32:58 +00001139
1140 // Print the threading model.
Jonathan Roelofsb140a102014-10-03 21:57:44 +00001141 if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
1142 // Don't print if the ToolChain would have barfed on it already
1143 if (TC.isThreadModelSupported(A->getValue()))
1144 OS << "Thread model: " << A->getValue();
1145 } else
1146 OS << "Thread model: " << TC.getThreadModel();
1147 OS << '\n';
Chandler Carruth9ade6a92015-08-05 17:07:33 +00001148
1149 // Print out the install directory.
1150 OS << "InstalledDir: " << InstalledDir << '\n';
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001151}
1152
Chris Lattner86ed5b02010-05-05 05:53:24 +00001153/// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
1154/// option.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001155static void PrintDiagnosticCategories(raw_ostream &OS) {
Argyrios Kyrtzidis0e37afa2011-05-25 05:05:01 +00001156 // Skip the empty category.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001157 for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
1158 ++i)
Argyrios Kyrtzidis0e37afa2011-05-25 05:05:01 +00001159 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
Chris Lattner86ed5b02010-05-05 05:53:24 +00001160}
1161
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001162bool Driver::HandleImmediateArgs(const Compilation &C) {
Daniel Dunbar18974bd2010-06-11 22:00:19 +00001163 // The order these options are handled in gcc is all over the place, but we
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001164 // don't expect inconsistencies w.r.t. that to matter in practice.
Daniel Dunbar7c925282009-03-31 21:38:17 +00001165
Daniel Dunbar1b09e042010-09-17 02:47:28 +00001166 if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
1167 llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
1168 return false;
1169 }
1170
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001171 if (C.getArgs().hasArg(options::OPT_dumpversion)) {
Daniel Dunbare26e5002011-01-12 00:43:47 +00001172 // Since -dumpversion is only implemented for pedantic GCC compatibility, we
1173 // return an answer which matches our definition of __VERSION__.
1174 //
1175 // If we want to return a more correct answer some day, then we should
1176 // introduce a non-pedantically GCC compatible mode to Clang in which we
1177 // provide sensible definitions for -dumpversion, __VERSION__, etc.
1178 llvm::outs() << "4.2.1\n";
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001179 return false;
1180 }
Daniel Dunbarfb3d7472010-06-14 21:23:12 +00001181
Chris Lattner86ed5b02010-05-05 05:53:24 +00001182 if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
1183 PrintDiagnosticCategories(llvm::outs());
1184 return false;
1185 }
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001186
James Molloya3c85b82012-05-01 14:57:16 +00001187 if (C.getArgs().hasArg(options::OPT_help) ||
Daniel Dunbara7b5e212009-04-15 16:34:29 +00001188 C.getArgs().hasArg(options::OPT__help_hidden)) {
1189 PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
Daniel Dunbar7c925282009-03-31 21:38:17 +00001190 return false;
1191 }
1192
Daniel Dunbarb0006ae2009-04-02 15:05:41 +00001193 if (C.getArgs().hasArg(options::OPT__version)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001194 // Follow gcc behavior and use stdout for --version and stderr for -v.
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001195 PrintVersion(C, llvm::outs());
Dimitry Andric0527c322017-06-07 12:05:41 +00001196
1197 // Print registered targets.
1198 llvm::outs() << '\n';
1199 llvm::TargetRegistry::printRegisteredTargetsForVersion(llvm::outs());
Daniel Dunbarb0006ae2009-04-02 15:05:41 +00001200 return false;
1201 }
1202
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001203 if (C.getArgs().hasArg(options::OPT_v) ||
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001204 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001205 PrintVersion(C, llvm::errs());
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001206 SuppressMissingInputWarning = true;
1207 }
1208
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001209 const ToolChain &TC = C.getDefaultToolChain();
Chandler Carruth0ae39aa2013-07-30 17:57:09 +00001210
1211 if (C.getArgs().hasArg(options::OPT_v))
1212 TC.printVerboseInfo(llvm::errs());
1213
Meador Inge51208a32017-04-04 21:46:50 +00001214 if (C.getArgs().hasArg(options::OPT_print_resource_dir)) {
Meador Ingea9113952017-04-05 22:27:20 +00001215 llvm::outs() << ResourceDir << '\n';
Meador Inge51208a32017-04-04 21:46:50 +00001216 return false;
1217 }
1218
Daniel Dunbard972e222009-03-20 04:37:21 +00001219 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
1220 llvm::outs() << "programs: =";
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001221 bool separator = false;
1222 for (const std::string &Path : TC.getProgramPaths()) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001223 if (separator)
1224 llvm::outs() << ':';
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001225 llvm::outs() << Path;
1226 separator = true;
Daniel Dunbard972e222009-03-20 04:37:21 +00001227 }
1228 llvm::outs() << "\n";
Peter Collingbournefa9771f2011-09-06 02:08:31 +00001229 llvm::outs() << "libraries: =" << ResourceDir;
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001230
Sebastian Pop980920a2012-04-16 04:16:43 +00001231 StringRef sysroot = C.getSysRoot();
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001232
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001233 for (const std::string &Path : TC.getFilePaths()) {
1234 // Always print a separator. ResourceDir was the first item shown.
Peter Collingbournefa9771f2011-09-06 02:08:31 +00001235 llvm::outs() << ':';
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001236 // Interpretation of leading '=' is needed only for NetBSD.
1237 if (Path[0] == '=')
Douglas Katzman26eabf62015-06-24 15:10:30 +00001238 llvm::outs() << sysroot << Path.substr(1);
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001239 else
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001240 llvm::outs() << Path;
Daniel Dunbard972e222009-03-20 04:37:21 +00001241 }
1242 llvm::outs() << "\n";
Daniel Dunbar7c925282009-03-31 21:38:17 +00001243 return false;
Daniel Dunbard972e222009-03-20 04:37:21 +00001244 }
1245
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001246 // FIXME: The following handlers should use a callback mechanism, we don't
1247 // know what the client would like to do.
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001248 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001249 llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001250 return false;
1251 }
1252
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001253 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001254 llvm::outs() << GetProgramPath(A->getValue(), TC) << "\n";
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001255 return false;
1256 }
1257
Yuka Takahashic8068db2017-05-23 18:39:08 +00001258 if (Arg *A = C.getArgs().getLastArg(options::OPT_autocomplete)) {
1259 // Print out all options that start with a given argument. This is used for
1260 // shell autocompletion.
Yuka Takahashiba5d4af2017-06-20 16:31:31 +00001261 StringRef PassedFlags = A->getValue();
1262 std::vector<std::string> SuggestedCompletions;
1263
Yuka Takahashi33cf63b2017-07-08 17:48:59 +00001264 unsigned short DisableFlags = options::NoDriverOption | options::Unsupported | options::Ignored;
1265 // We want to show cc1-only options only when clang is invoked as "clang -cc1".
1266 // When clang is invoked as "clang -cc1", we add "#" to the beginning of an --autocomplete
1267 // option so that the clang driver can distinguish whether it is requested to show cc1-only options or not.
1268 if (PassedFlags[0] == '#') {
1269 DisableFlags &= ~options::NoDriverOption;
1270 PassedFlags = PassedFlags.substr(1);
1271 }
1272
Yuka Takahashiba5d4af2017-06-20 16:31:31 +00001273 if (PassedFlags.find(',') == StringRef::npos) {
1274 // If the flag is in the form of "--autocomplete=-foo",
1275 // we were requested to print out all option names that start with "-foo".
1276 // For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only".
Yuka Takahashi33cf63b2017-07-08 17:48:59 +00001277 SuggestedCompletions = Opts->findByPrefix(PassedFlags, DisableFlags);
Yuka Takahashi64918d02017-07-16 15:07:20 +00001278
1279 // We have to query the -W flags manually as they're not in the OptTable.
1280 // TODO: Find a good way to add them to OptTable instead and them remove
1281 // this code.
1282 for (StringRef S : DiagnosticIDs::getDiagnosticFlags())
1283 if (S.startswith(PassedFlags))
1284 SuggestedCompletions.push_back(S);
Yuka Takahashiba5d4af2017-06-20 16:31:31 +00001285 } else {
1286 // If the flag is in the form of "--autocomplete=foo,bar", we were
1287 // requested to print out all option values for "-foo" that start with
1288 // "bar". For example,
1289 // "--autocomplete=-stdlib=,l" is expanded to "libc++" and "libstdc++".
1290 StringRef Option, Arg;
1291 std::tie(Option, Arg) = PassedFlags.split(',');
1292 SuggestedCompletions = Opts->suggestValueCompletions(Option, Arg);
1293 }
1294
Rui Ueyama5cb4b352017-06-23 15:37:52 +00001295 // Sort the autocomplete candidates so that shells print them out in a
1296 // deterministic order. We could sort in any way, but we chose
1297 // case-insensitive sorting for consistency with the -help option
1298 // which prints out options in the case-insensitive alphabetical order.
1299 std::sort(SuggestedCompletions.begin(), SuggestedCompletions.end(),
1300 [](StringRef A, StringRef B) { return A.compare_lower(B) < 0; });
1301
Yuka Takahashiba5d4af2017-06-20 16:31:31 +00001302 llvm::outs() << llvm::join(SuggestedCompletions, " ") << '\n';
Yuka Takahashic8068db2017-05-23 18:39:08 +00001303 return false;
1304 }
1305
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001306 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
Michal Gorny7cfe4802016-10-10 12:23:40 +00001307 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(C.getArgs());
1308 switch (RLT) {
1309 case ToolChain::RLT_CompilerRT:
1310 llvm::outs() << TC.getCompilerRT(C.getArgs(), "builtins") << "\n";
1311 break;
1312 case ToolChain::RLT_Libgcc:
1313 llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
1314 break;
1315 }
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001316 return false;
1317 }
1318
Daniel Dunbar1b3ec3a2009-06-16 23:25:22 +00001319 if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
Douglas Katzmana34b7bf2015-06-30 19:32:57 +00001320 for (const Multilib &Multilib : TC.getMultilibs())
1321 llvm::outs() << Multilib << "\n";
Daniel Dunbar1b3ec3a2009-06-16 23:25:22 +00001322 return false;
1323 }
1324
Jonathan Roelofs2cea1be2014-02-12 03:21:20 +00001325 if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
Douglas Katzmana34b7bf2015-06-30 19:32:57 +00001326 for (const Multilib &Multilib : TC.getMultilibs()) {
Douglas Katzman6bbffc42015-06-25 18:51:37 +00001327 if (Multilib.gccSuffix().empty())
Jonathan Roelofs2cea1be2014-02-12 03:21:20 +00001328 llvm::outs() << ".\n";
1329 else {
Douglas Katzman6bbffc42015-06-25 18:51:37 +00001330 StringRef Suffix(Multilib.gccSuffix());
Jonathan Roelofs2cea1be2014-02-12 03:21:20 +00001331 assert(Suffix.front() == '/');
1332 llvm::outs() << Suffix.substr(1) << "\n";
1333 }
Jonathan Roelofs3fa96d82014-02-12 01:36:51 +00001334 }
Jonathan Roelofs0e7ec602014-02-12 01:29:25 +00001335 return false;
1336 }
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001337 return true;
1338}
1339
Douglas Katzmanfd528672015-06-11 15:05:22 +00001340// Display an action graph human-readably. Action A is the "sink" node
1341// and latest-occuring action. Traversal is in pre-order, visiting the
1342// inputs to each action before printing the action itself.
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001343static unsigned PrintActions1(const Compilation &C, Action *A,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001344 std::map<Action *, unsigned> &Ids) {
Douglas Katzmanfd528672015-06-11 15:05:22 +00001345 if (Ids.count(A)) // A was already visited.
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001346 return Ids[A];
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001347
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001348 std::string str;
1349 llvm::raw_string_ostream os(str);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001350
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001351 os << Action::getClassName(A->getKind()) << ", ";
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001352 if (InputAction *IA = dyn_cast<InputAction>(A)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001353 os << "\"" << IA->getInputArg().getValue() << "\"";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001354 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001355 os << '"' << BIA->getArchName() << '"' << ", {"
Nico Weber5a459f82016-02-23 19:30:43 +00001356 << PrintActions1(C, *BIA->input_begin(), Ids) << "}";
Samuel Antaod06239d2016-07-15 23:13:27 +00001357 } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
1358 bool IsFirst = true;
1359 OA->doOnEachDependence(
1360 [&](Action *A, const ToolChain *TC, const char *BoundArch) {
1361 // E.g. for two CUDA device dependences whose bound arch is sm_20 and
1362 // sm_35 this will generate:
1363 // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
1364 // (nvptx64-nvidia-cuda:sm_35) {#ID}
1365 if (!IsFirst)
1366 os << ", ";
1367 os << '"';
1368 if (TC)
1369 os << A->getOffloadingKindPrefix();
1370 else
1371 os << "host";
1372 os << " (";
1373 os << TC->getTriple().normalize();
1374
1375 if (BoundArch)
1376 os << ":" << BoundArch;
1377 os << ")";
1378 os << '"';
1379 os << " {" << PrintActions1(C, A, Ids) << "}";
1380 IsFirst = false;
1381 });
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001382 } else {
Samuel Antaod06239d2016-07-15 23:13:27 +00001383 const ActionList *AL = &A->getInputs();
Artem Belevich0ff05cd2015-07-13 23:27:56 +00001384
Artem Belevich23256752015-09-22 17:23:09 +00001385 if (AL->size()) {
1386 const char *Prefix = "{";
1387 for (Action *PreRequisite : *AL) {
1388 os << Prefix << PrintActions1(C, PreRequisite, Ids);
1389 Prefix = ", ";
1390 }
1391 os << "}";
1392 } else
1393 os << "{}";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001394 }
1395
Samuel Antaod06239d2016-07-15 23:13:27 +00001396 // Append offload info for all options other than the offloading action
1397 // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
1398 std::string offload_str;
1399 llvm::raw_string_ostream offload_os(offload_str);
1400 if (!isa<OffloadAction>(A)) {
1401 auto S = A->getOffloadingKindPrefix();
1402 if (!S.empty()) {
1403 offload_os << ", (" << S;
1404 if (A->getOffloadingArch())
1405 offload_os << ", " << A->getOffloadingArch();
1406 offload_os << ")";
1407 }
1408 }
1409
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001410 unsigned Id = Ids.size();
1411 Ids[A] = Id;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001412 llvm::errs() << Id << ": " << os.str() << ", "
Samuel Antaod06239d2016-07-15 23:13:27 +00001413 << types::getTypeName(A->getType()) << offload_os.str() << "\n";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001414
1415 return Id;
1416}
1417
Douglas Katzmanfd528672015-06-11 15:05:22 +00001418// Print the action graphs in a compilation C.
1419// For example "clang -c file1.c file2.c" is composed of two subgraphs.
Daniel Dunbareb843be2009-03-18 03:13:20 +00001420void Driver::PrintActions(const Compilation &C) const {
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001421 std::map<Action *, unsigned> Ids;
1422 for (Action *A : C.getActions())
1423 PrintActions1(C, A, Ids);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001424}
1425
Joerg Sonnenberger5fe4a7d2011-05-06 14:05:11 +00001426/// \brief Check whether the given input tree contains any compilation or
1427/// assembly actions.
1428static bool ContainsCompileOrAssembleAction(const Action *A) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001429 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
Bob Wilson23a55f12014-12-21 07:00:00 +00001430 isa<AssembleJobAction>(A))
Daniel Dunbar00d3d8e2010-06-29 16:38:33 +00001431 return true;
1432
Nico Weber5a459f82016-02-23 19:30:43 +00001433 for (const Action *Input : A->inputs())
Nico Weberfb80f962015-09-19 21:36:51 +00001434 if (ContainsCompileOrAssembleAction(Input))
Daniel Dunbar00d3d8e2010-06-29 16:38:33 +00001435 return true;
1436
1437 return false;
1438}
1439
Artem Belevich5e2a3ec2015-11-17 22:28:40 +00001440void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
1441 const InputList &BAInputs) const {
1442 DerivedArgList &Args = C.getArgs();
1443 ActionList &Actions = C.getActions();
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001444 llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
1445 // Collect the list of architectures. Duplicates are allowed, but should only
1446 // be handled once (in the order seen).
Daniel Dunbare5dc4822009-03-13 20:33:35 +00001447 llvm::StringSet<> ArchNames;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001448 SmallVector<const char *, 4> Archs;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00001449 for (Arg *A : Args) {
Daniel Dunbar0bfb21e2009-11-19 03:26:40 +00001450 if (A->getOption().matches(options::OPT_arch)) {
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001451 // Validate the option here; we don't save the type here because its
1452 // particular spelling may participate in other driver choices.
1453 llvm::Triple::ArchType Arch =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001454 tools::darwin::getArchTypeForMachOArchName(A->getValue());
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001455 if (Arch == llvm::Triple::UnknownArch) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001456 Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001457 continue;
1458 }
1459
Daniel Dunbar2da02722009-03-19 07:55:12 +00001460 A->claim();
David Blaikie61b86d42014-11-19 02:56:13 +00001461 if (ArchNames.insert(A->getValue()).second)
Richard Smithbd55daf2012-11-01 04:30:05 +00001462 Archs.push_back(A->getValue());
Daniel Dunbarf479c122009-03-12 18:40:18 +00001463 }
1464 }
1465
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001466 // When there is no explicit arch for this platform, make sure we still bind
1467 // the architecture (to the default) so that -Xarch_ is handled correctly.
Daniel Dunbareb843be2009-03-18 03:13:20 +00001468 if (!Archs.size())
Daniel Dunbarc3bd9f52012-11-08 03:38:26 +00001469 Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
Daniel Dunbarf479c122009-03-12 18:40:18 +00001470
Daniel Dunbarf479c122009-03-12 18:40:18 +00001471 ActionList SingleActions;
Justin Lebar0f3474c2016-02-11 02:00:50 +00001472 BuildActions(C, Args, BAInputs, SingleActions);
Daniel Dunbarf479c122009-03-12 18:40:18 +00001473
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001474 // Add in arch bindings for every top level action, as well as lipo and
1475 // dsymutil steps if needed.
Nico Weberfb80f962015-09-19 21:36:51 +00001476 for (Action* Act : SingleActions) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001477 // Make sure we can lipo this kind of output. If not (and it is an actual
1478 // output) then we disallow, since we can't create an output file with the
1479 // right name without overwriting it. We could remove this oddity by just
1480 // changing the output names to include the arch, which would also fix
Daniel Dunbarf479c122009-03-12 18:40:18 +00001481 // -save-temps. Compatibility wins for now.
1482
Daniel Dunbare2ca3bd2009-03-13 17:46:02 +00001483 if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
Daniel Dunbarf479c122009-03-12 18:40:18 +00001484 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001485 << types::getTypeName(Act->getType());
Daniel Dunbarf479c122009-03-12 18:40:18 +00001486
1487 ActionList Inputs;
Justin Lebar41094612016-01-11 23:07:27 +00001488 for (unsigned i = 0, e = Archs.size(); i != e; ++i)
1489 Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
Daniel Dunbarf479c122009-03-12 18:40:18 +00001490
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001491 // Lipo if necessary, we do it this way because we need to set the arch flag
1492 // so that -Xarch_ gets overwritten.
Daniel Dunbarf479c122009-03-12 18:40:18 +00001493 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
1494 Actions.append(Inputs.begin(), Inputs.end());
1495 else
Justin Lebar41094612016-01-11 23:07:27 +00001496 Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001497
Eric Christopher65c05fa2012-02-06 19:43:51 +00001498 // Handle debug info queries.
1499 Arg *A = Args.getLastArg(options::OPT_g_Group);
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001500 if (A && !A->getOption().matches(options::OPT_g0) &&
1501 !A->getOption().matches(options::OPT_gstabs) &&
1502 ContainsCompileOrAssembleAction(Actions.back())) {
Chad Rosier62135492012-07-09 17:31:28 +00001503
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001504 // Add a 'dsymutil' step if necessary, when debug info is enabled and we
1505 // have a compile input. We need to run 'dsymutil' ourselves in such cases
Eric Christopher776c26f2013-01-28 17:39:03 +00001506 // because the debug info will refer to a temporary object file which
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001507 // will be removed at the end of the compilation process.
1508 if (Act->getType() == types::TY_Image) {
1509 ActionList Inputs;
1510 Inputs.push_back(Actions.back());
1511 Actions.pop_back();
Justin Lebar41094612016-01-11 23:07:27 +00001512 Actions.push_back(
1513 C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001514 }
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001515
Ben Langmuir9b9a8d32014-02-06 18:53:25 +00001516 // Verify the debug info output.
Alp Tokere9d2bfc2014-01-17 02:06:23 +00001517 if (Args.hasArg(options::OPT_verify_debug_info)) {
Justin Lebar41094612016-01-11 23:07:27 +00001518 Action* LastAction = Actions.back();
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001519 Actions.pop_back();
Justin Lebar41094612016-01-11 23:07:27 +00001520 Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
1521 LastAction, types::TY_Nothing));
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001522 }
1523 }
Daniel Dunbarf479c122009-03-12 18:40:18 +00001524 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001525}
1526
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001527/// \brief Check that the file referenced by Value exists. If it doesn't,
1528/// issue a diagnostic and return false.
Alp Toker8c8a8752013-12-03 06:53:35 +00001529static bool DiagnoseInputExistence(const Driver &D, const DerivedArgList &Args,
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001530 StringRef Value, types::ID Ty) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001531 if (!D.getCheckInputsExist())
1532 return true;
1533
1534 // stdin always exists.
1535 if (Value == "-")
1536 return true;
1537
1538 SmallString<64> Path(Value);
1539 if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
Yaron Keren92e1b622015-03-18 10:17:07 +00001540 if (!llvm::sys::path::is_absolute(Path)) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001541 SmallString<64> Directory(WorkDir->getValue());
1542 llvm::sys::path::append(Directory, Value);
1543 Path.assign(Directory);
1544 }
1545 }
1546
1547 if (llvm::sys::fs::exists(Twine(Path)))
1548 return true;
1549
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001550 if (D.IsCLMode()) {
1551 if (!llvm::sys::path::is_absolute(Twine(Path)) &&
1552 llvm::sys::Process::FindInEnvPath("LIB", Value))
1553 return true;
1554
1555 if (Args.hasArg(options::OPT__SLASH_link) && Ty == types::TY_Object) {
1556 // Arguments to the /link flag might cause the linker to search for object
1557 // and library files in paths we don't know about. Don't error in such
1558 // cases.
1559 return true;
1560 }
1561 }
Hans Wennborg23d26a32014-06-18 17:21:50 +00001562
Yaron Keren92e1b622015-03-18 10:17:07 +00001563 D.Diag(clang::diag::err_drv_no_such_file) << Path;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001564 return false;
1565}
1566
Chad Rosierecdede82011-08-12 22:08:57 +00001567// Construct a the list of inputs and their types.
Hans Wennborg55362852014-05-02 22:55:30 +00001568void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
Chad Rosierecdede82011-08-12 22:08:57 +00001569 InputList &Inputs) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001570 // Track the current user specified (-x) input. We also explicitly track the
1571 // argument used to set the type; we only want to claim the type when we
1572 // actually use it, so we warn about unused -x arguments.
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00001573 types::ID InputType = types::TY_Nothing;
Craig Topper92fc2df2014-05-17 16:56:41 +00001574 Arg *InputTypeArg = nullptr;
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00001575
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001576 // The last /TC or /TP option sets the input type to C or C++ globally.
Ehsan Akhgaric249abb2014-09-12 21:44:24 +00001577 if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
1578 options::OPT__SLASH_TP)) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001579 InputTypeArg = TCTP;
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001580 InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001581 ? types::TY_C
1582 : types::TY_CXX;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001583
Richard Smith0aef3052017-02-18 01:14:43 +00001584 Arg *Previous = nullptr;
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001585 bool ShowNote = false;
Richard Smith0aef3052017-02-18 01:14:43 +00001586 for (Arg *A : Args.filtered(options::OPT__SLASH_TC, options::OPT__SLASH_TP)) {
1587 if (Previous) {
1588 Diag(clang::diag::warn_drv_overriding_flag_option)
1589 << Previous->getSpelling() << A->getSpelling();
1590 ShowNote = true;
1591 }
1592 Previous = A;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001593 }
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001594 if (ShowNote)
1595 Diag(clang::diag::note_drv_t_option_is_global);
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001596
1597 // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
1598 assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
1599 }
1600
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00001601 for (Arg *A : Args) {
Michael J. Spencerad3ccc32012-08-20 21:41:17 +00001602 if (A->getOption().getKind() == Option::InputClass) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001603 const char *Value = A->getValue();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001604 types::ID Ty = types::TY_INVALID;
1605
1606 // Infer the input type if necessary.
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00001607 if (InputType == types::TY_Nothing) {
1608 // If there was an explicit arg for this, claim it.
1609 if (InputTypeArg)
1610 InputTypeArg->claim();
1611
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001612 // stdin must be handled specially.
1613 if (memcmp(Value, "-", 2) == 0) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001614 // If running with -E, treat as a C input (this changes the builtin
1615 // macros, for example). This may be overridden by -ObjC below.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001616 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001617 // Otherwise emit an error but still use a valid type to avoid
1618 // spurious errors (e.g., no inputs).
Hans Wennborg70850d82013-07-18 20:29:38 +00001619 if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
Hans Wennborgcfdd8b52014-01-29 01:04:40 +00001620 Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
1621 : clang::diag::err_drv_unknown_stdin_type);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001622 Ty = types::TY_C;
1623 } else {
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00001624 // Otherwise lookup by extension.
1625 // Fallback is C if invoked as C preprocessor or Object otherwise.
1626 // We use a host hook here because Darwin at least has its own
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001627 // idea of what .s is.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001628 if (const char *Ext = strrchr(Value, '.'))
Daniel Dunbarcc7df6c2010-08-02 05:43:56 +00001629 Ty = TC.LookupTypeForExtension(Ext + 1);
Daniel Dunbarea9f0322009-03-20 23:39:23 +00001630
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00001631 if (Ty == types::TY_INVALID) {
Hans Wennborg70850d82013-07-18 20:29:38 +00001632 if (CCCIsCPP())
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00001633 Ty = types::TY_C;
1634 else
1635 Ty = types::TY_Object;
1636 }
Daniel Dunbar0ac94452010-02-17 20:32:58 +00001637
1638 // If the driver is invoked as C++ compiler (like clang++ or c++) it
1639 // should autodetect some input files as C++ for g++ compatibility.
Hans Wennborg70850d82013-07-18 20:29:38 +00001640 if (CCCIsCXX()) {
Daniel Dunbar0ac94452010-02-17 20:32:58 +00001641 types::ID OldTy = Ty;
1642 Ty = types::lookupCXXTypeForCType(Ty);
1643
1644 if (Ty != OldTy)
1645 Diag(clang::diag::warn_drv_treating_input_as_cxx)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001646 << getTypeName(OldTy) << getTypeName(Ty);
Daniel Dunbar0ac94452010-02-17 20:32:58 +00001647 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001648 }
1649
Daniel Dunbar82b22102009-05-18 21:47:54 +00001650 // -ObjC and -ObjC++ override the default language, but only for "source
1651 // files". We just treat everything that isn't a linker input as a
1652 // source file.
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001653 //
Daniel Dunbar82b22102009-05-18 21:47:54 +00001654 // FIXME: Clean this up if we move the phase sequence into the type.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001655 if (Ty != types::TY_Object) {
1656 if (Args.hasArg(options::OPT_ObjC))
1657 Ty = types::TY_ObjC;
1658 else if (Args.hasArg(options::OPT_ObjCXX))
1659 Ty = types::TY_ObjCXX;
1660 }
1661 } else {
1662 assert(InputTypeArg && "InputType set w/o InputTypeArg");
Ehsan Akhgari7e954ea2014-09-12 18:15:10 +00001663 if (!InputTypeArg->getOption().matches(options::OPT_x)) {
1664 // If emulating cl.exe, make sure that /TC and /TP don't affect input
1665 // object files.
1666 const char *Ext = strrchr(Value, '.');
1667 if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
1668 Ty = types::TY_Object;
1669 }
1670 if (Ty == types::TY_INVALID) {
1671 Ty = InputType;
1672 InputTypeArg->claim();
1673 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001674 }
1675
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001676 if (DiagnoseInputExistence(*this, Args, Value, Ty))
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001677 Inputs.push_back(std::make_pair(Ty, A));
1678
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001679 } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
1680 StringRef Value = A->getValue();
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001681 if (DiagnoseInputExistence(*this, Args, Value, types::TY_C)) {
David Blaikie0aaa7622017-01-13 17:34:15 +00001682 Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001683 Inputs.push_back(std::make_pair(types::TY_C, InputArg));
1684 }
1685 A->claim();
1686 } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
1687 StringRef Value = A->getValue();
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001688 if (DiagnoseInputExistence(*this, Args, Value, types::TY_CXX)) {
David Blaikie0aaa7622017-01-13 17:34:15 +00001689 Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001690 Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
1691 }
1692 A->claim();
Michael J. Spencer66e2b202012-10-19 22:37:06 +00001693 } else if (A->getOption().hasFlag(options::LinkerInput)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001694 // Just treat as object type, we could make a special type for this if
1695 // necessary.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001696 Inputs.push_back(std::make_pair(types::TY_Object, A));
1697
Daniel Dunbar0bfb21e2009-11-19 03:26:40 +00001698 } else if (A->getOption().matches(options::OPT_x)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001699 InputTypeArg = A;
Richard Smithbd55daf2012-11-01 04:30:05 +00001700 InputType = types::lookupTypeForTypeSpecifier(A->getValue());
Chad Rosier706c2352012-04-07 00:01:31 +00001701 A->claim();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001702
1703 // Follow gcc behavior and treat as linker input for invalid -x
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001704 // options. Its not clear why we shouldn't just revert to unknown; but
Michael J. Spencer1a4fe8c2010-12-17 21:22:33 +00001705 // this isn't very important, we might as well be bug compatible.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001706 if (!InputType) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001707 Diag(clang::diag::err_drv_unknown_language) << A->getValue();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001708 InputType = types::TY_Object;
1709 }
Hans Wennborg091f1b62017-01-27 17:09:41 +00001710 } else if (A->getOption().getID() == options::OPT__SLASH_U) {
1711 assert(A->getNumValues() == 1 && "The /U option has one value.");
1712 StringRef Val = A->getValue(0);
1713 if (Val.find_first_of("/\\") != StringRef::npos) {
1714 // Warn about e.g. "/Users/me/myfile.c".
1715 Diag(diag::warn_slash_u_filename) << Val;
1716 Diag(diag::note_use_dashdash);
1717 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001718 }
1719 }
Hans Wennborg70850d82013-07-18 20:29:38 +00001720 if (CCCIsCPP() && Inputs.empty()) {
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00001721 // If called as standalone preprocessor, stdin is processed
1722 // if no other input is present.
David Blaikie0aaa7622017-01-13 17:34:15 +00001723 Arg *A = MakeInputArg(Args, *Opts, "-");
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00001724 Inputs.push_back(std::make_pair(types::TY_C, A));
1725 }
Chad Rosierecdede82011-08-12 22:08:57 +00001726}
1727
Samuel Antao64e965e2016-09-30 15:34:19 +00001728namespace {
1729/// Provides a convenient interface for different programming models to generate
1730/// the required device actions.
1731class OffloadingActionBuilder final {
1732 /// Flag used to trace errors in the builder.
1733 bool IsValid = false;
1734
1735 /// The compilation that is using this builder.
1736 Compilation &C;
1737
Samuel Antao64e965e2016-09-30 15:34:19 +00001738 /// Map between an input argument and the offload kinds used to process it.
1739 std::map<const Arg *, unsigned> InputArgToOffloadKindMap;
1740
1741 /// Builder interface. It doesn't build anything or keep any state.
1742 class DeviceActionBuilder {
1743 public:
1744 typedef llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PhasesTy;
1745
1746 enum ActionBuilderReturnCode {
1747 // The builder acted successfully on the current action.
1748 ABRT_Success,
1749 // The builder didn't have to act on the current action.
1750 ABRT_Inactive,
1751 // The builder was successful and requested the host action to not be
1752 // generated.
1753 ABRT_Ignore_Host,
1754 };
1755
1756 protected:
1757 /// Compilation associated with this builder.
1758 Compilation &C;
1759
1760 /// Tool chains associated with this builder. The same programming
1761 /// model may have associated one or more tool chains.
1762 SmallVector<const ToolChain *, 2> ToolChains;
1763
1764 /// The derived arguments associated with this builder.
1765 DerivedArgList &Args;
1766
1767 /// The inputs associated with this builder.
1768 const Driver::InputList &Inputs;
1769
1770 /// The associated offload kind.
1771 Action::OffloadKind AssociatedOffloadKind = Action::OFK_None;
1772
1773 public:
1774 DeviceActionBuilder(Compilation &C, DerivedArgList &Args,
1775 const Driver::InputList &Inputs,
1776 Action::OffloadKind AssociatedOffloadKind)
1777 : C(C), Args(Args), Inputs(Inputs),
1778 AssociatedOffloadKind(AssociatedOffloadKind) {}
1779 virtual ~DeviceActionBuilder() {}
1780
1781 /// Fill up the array \a DA with all the device dependences that should be
1782 /// added to the provided host action \a HostAction. By default it is
1783 /// inactive.
1784 virtual ActionBuilderReturnCode
Samuel Antao28c4f182016-10-27 17:08:03 +00001785 getDeviceDependences(OffloadAction::DeviceDependences &DA,
1786 phases::ID CurPhase, phases::ID FinalPhase,
1787 PhasesTy &Phases) {
Samuel Antao64e965e2016-09-30 15:34:19 +00001788 return ABRT_Inactive;
1789 }
1790
1791 /// Update the state to include the provided host action \a HostAction as a
1792 /// dependency of the current device action. By default it is inactive.
1793 virtual ActionBuilderReturnCode addDeviceDepences(Action *HostAction) {
1794 return ABRT_Inactive;
1795 }
1796
1797 /// Append top level actions generated by the builder. Return true if errors
1798 /// were found.
1799 virtual void appendTopLevelActions(ActionList &AL) {}
1800
1801 /// Append linker actions generated by the builder. Return true if errors
1802 /// were found.
1803 virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {}
1804
1805 /// Initialize the builder. Return true if any initialization errors are
1806 /// found.
1807 virtual bool initialize() { return false; }
1808
Samuel Antao69d6f312016-10-27 17:50:43 +00001809 /// Return true if the builder can use bundling/unbundling.
1810 virtual bool canUseBundlerUnbundler() const { return false; }
1811
Samuel Antao64e965e2016-09-30 15:34:19 +00001812 /// Return true if this builder is valid. We have a valid builder if we have
1813 /// associated device tool chains.
1814 bool isValid() { return !ToolChains.empty(); }
1815
1816 /// Return the associated offload kind.
1817 Action::OffloadKind getAssociatedOffloadKind() {
1818 return AssociatedOffloadKind;
1819 }
1820 };
1821
1822 /// \brief CUDA action builder. It injects device code in the host backend
1823 /// action.
1824 class CudaActionBuilder final : public DeviceActionBuilder {
1825 /// Flags to signal if the user requested host-only or device-only
1826 /// compilation.
1827 bool CompileHostOnly = false;
1828 bool CompileDeviceOnly = false;
1829
1830 /// List of GPU architectures to use in this compilation.
1831 SmallVector<CudaArch, 4> GpuArchList;
1832
1833 /// The CUDA actions for the current input.
1834 ActionList CudaDeviceActions;
1835
1836 /// The CUDA fat binary if it was generated for the current input.
1837 Action *CudaFatBinary = nullptr;
1838
1839 /// Flag that is set to true if this builder acted on the current input.
1840 bool IsActive = false;
1841
1842 public:
1843 CudaActionBuilder(Compilation &C, DerivedArgList &Args,
1844 const Driver::InputList &Inputs)
1845 : DeviceActionBuilder(C, Args, Inputs, Action::OFK_Cuda) {}
1846
1847 ActionBuilderReturnCode
Samuel Antao28c4f182016-10-27 17:08:03 +00001848 getDeviceDependences(OffloadAction::DeviceDependences &DA,
1849 phases::ID CurPhase, phases::ID FinalPhase,
1850 PhasesTy &Phases) override {
Samuel Antao64e965e2016-09-30 15:34:19 +00001851 if (!IsActive)
1852 return ABRT_Inactive;
1853
1854 // If we don't have more CUDA actions, we don't have any dependences to
1855 // create for the host.
1856 if (CudaDeviceActions.empty())
1857 return ABRT_Success;
1858
1859 assert(CudaDeviceActions.size() == GpuArchList.size() &&
1860 "Expecting one action per GPU architecture.");
1861 assert(!CompileHostOnly &&
1862 "Not expecting CUDA actions in host-only compilation.");
1863
1864 // If we are generating code for the device or we are in a backend phase,
1865 // we attempt to generate the fat binary. We compile each arch to ptx and
1866 // assemble to cubin, then feed the cubin *and* the ptx into a device
1867 // "link" action, which uses fatbinary to combine these cubins into one
1868 // fatbin. The fatbin is then an input to the host action if not in
1869 // device-only mode.
1870 if (CompileDeviceOnly || CurPhase == phases::Backend) {
1871 ActionList DeviceActions;
1872 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
1873 // Produce the device action from the current phase up to the assemble
1874 // phase.
1875 for (auto Ph : Phases) {
1876 // Skip the phases that were already dealt with.
1877 if (Ph < CurPhase)
1878 continue;
1879 // We have to be consistent with the host final phase.
1880 if (Ph > FinalPhase)
1881 break;
1882
1883 CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction(
1884 C, Args, Ph, CudaDeviceActions[I]);
1885
1886 if (Ph == phases::Assemble)
1887 break;
1888 }
1889
1890 // If we didn't reach the assemble phase, we can't generate the fat
1891 // binary. We don't need to generate the fat binary if we are not in
1892 // device-only mode.
1893 if (!isa<AssembleJobAction>(CudaDeviceActions[I]) ||
1894 CompileDeviceOnly)
1895 continue;
1896
1897 Action *AssembleAction = CudaDeviceActions[I];
1898 assert(AssembleAction->getType() == types::TY_Object);
1899 assert(AssembleAction->getInputs().size() == 1);
1900
1901 Action *BackendAction = AssembleAction->getInputs()[0];
1902 assert(BackendAction->getType() == types::TY_PP_Asm);
1903
1904 for (auto &A : {AssembleAction, BackendAction}) {
1905 OffloadAction::DeviceDependences DDep;
1906 DDep.add(*A, *ToolChains.front(), CudaArchToString(GpuArchList[I]),
1907 Action::OFK_Cuda);
1908 DeviceActions.push_back(
1909 C.MakeAction<OffloadAction>(DDep, A->getType()));
1910 }
1911 }
1912
1913 // We generate the fat binary if we have device input actions.
1914 if (!DeviceActions.empty()) {
1915 CudaFatBinary =
1916 C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN);
1917
1918 if (!CompileDeviceOnly) {
1919 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
1920 Action::OFK_Cuda);
1921 // Clear the fat binary, it is already a dependence to an host
1922 // action.
1923 CudaFatBinary = nullptr;
1924 }
1925
1926 // Remove the CUDA actions as they are already connected to an host
1927 // action or fat binary.
1928 CudaDeviceActions.clear();
1929 }
1930
1931 // We avoid creating host action in device-only mode.
1932 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
Samuel Antao5b1a89a2016-10-27 00:53:34 +00001933 } else if (CurPhase > phases::Backend) {
1934 // If we are past the backend phase and still have a device action, we
1935 // don't have to do anything as this action is already a device
1936 // top-level action.
1937 return ABRT_Success;
Samuel Antao64e965e2016-09-30 15:34:19 +00001938 }
1939
1940 assert(CurPhase < phases::Backend && "Generating single CUDA "
1941 "instructions should only occur "
1942 "before the backend phase!");
1943
1944 // By default, we produce an action for each device arch.
1945 for (Action *&A : CudaDeviceActions)
1946 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
1947
1948 return ABRT_Success;
1949 }
1950
1951 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
1952 // While generating code for CUDA, we only depend on the host input action
1953 // to trigger the creation of all the CUDA device actions.
1954
1955 // If we are dealing with an input action, replicate it for each GPU
1956 // architecture. If we are in host-only mode we return 'success' so that
1957 // the host uses the CUDA offload kind.
1958 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
1959 assert(!GpuArchList.empty() &&
1960 "We should have at least one GPU architecture.");
1961
1962 // If the host input is not CUDA, we don't need to bother about this
1963 // input.
1964 if (IA->getType() != types::TY_CUDA) {
1965 // The builder will ignore this input.
1966 IsActive = false;
1967 return ABRT_Inactive;
1968 }
1969
1970 // Set the flag to true, so that the builder acts on the current input.
1971 IsActive = true;
1972
1973 if (CompileHostOnly)
1974 return ABRT_Success;
1975
1976 // Replicate inputs for each GPU architecture.
1977 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
1978 CudaDeviceActions.push_back(C.MakeAction<InputAction>(
1979 IA->getInputArg(), types::TY_CUDA_DEVICE));
1980
1981 return ABRT_Success;
1982 }
1983
1984 return IsActive ? ABRT_Success : ABRT_Inactive;
1985 }
1986
1987 void appendTopLevelActions(ActionList &AL) override {
1988 // Utility to append actions to the top level list.
1989 auto AddTopLevel = [&](Action *A, CudaArch BoundArch) {
1990 OffloadAction::DeviceDependences Dep;
1991 Dep.add(*A, *ToolChains.front(), CudaArchToString(BoundArch),
1992 Action::OFK_Cuda);
1993 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
1994 };
1995
1996 // If we have a fat binary, add it to the list.
1997 if (CudaFatBinary) {
1998 AddTopLevel(CudaFatBinary, CudaArch::UNKNOWN);
1999 CudaDeviceActions.clear();
2000 CudaFatBinary = nullptr;
2001 return;
2002 }
2003
2004 if (CudaDeviceActions.empty())
2005 return;
2006
2007 // If we have CUDA actions at this point, that's because we have a have
2008 // partial compilation, so we should have an action for each GPU
2009 // architecture.
2010 assert(CudaDeviceActions.size() == GpuArchList.size() &&
2011 "Expecting one action per GPU architecture.");
2012 assert(ToolChains.size() == 1 &&
2013 "Expecting to have a sing CUDA toolchain.");
2014 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
2015 AddTopLevel(CudaDeviceActions[I], GpuArchList[I]);
2016
2017 CudaDeviceActions.clear();
2018 }
2019
2020 bool initialize() override {
2021 // We don't need to support CUDA.
2022 if (!C.hasOffloadToolChain<Action::OFK_Cuda>())
2023 return false;
2024
2025 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
2026 assert(HostTC && "No toolchain for host compilation.");
2027 if (HostTC->getTriple().isNVPTX()) {
2028 // We do not support targeting NVPTX for host compilation. Throw
2029 // an error and abort pipeline construction early so we don't trip
2030 // asserts that assume device-side compilation.
2031 C.getDriver().Diag(diag::err_drv_cuda_nvptx_host);
2032 return true;
2033 }
2034
2035 ToolChains.push_back(C.getSingleOffloadToolChain<Action::OFK_Cuda>());
2036
2037 Arg *PartialCompilationArg = Args.getLastArg(
2038 options::OPT_cuda_host_only, options::OPT_cuda_device_only,
2039 options::OPT_cuda_compile_host_device);
2040 CompileHostOnly = PartialCompilationArg &&
2041 PartialCompilationArg->getOption().matches(
2042 options::OPT_cuda_host_only);
2043 CompileDeviceOnly = PartialCompilationArg &&
2044 PartialCompilationArg->getOption().matches(
2045 options::OPT_cuda_device_only);
2046
2047 // Collect all cuda_gpu_arch parameters, removing duplicates.
Artem Belevicha424e882016-12-09 22:59:17 +00002048 std::set<CudaArch> GpuArchs;
Samuel Antao64e965e2016-09-30 15:34:19 +00002049 bool Error = false;
2050 for (Arg *A : Args) {
Artem Belevicha424e882016-12-09 22:59:17 +00002051 if (!(A->getOption().matches(options::OPT_cuda_gpu_arch_EQ) ||
2052 A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ)))
Samuel Antao64e965e2016-09-30 15:34:19 +00002053 continue;
2054 A->claim();
2055
Artem Belevicha424e882016-12-09 22:59:17 +00002056 const StringRef ArchStr = A->getValue();
2057 if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ) &&
2058 ArchStr == "all") {
2059 GpuArchs.clear();
2060 continue;
2061 }
Samuel Antao64e965e2016-09-30 15:34:19 +00002062 CudaArch Arch = StringToCudaArch(ArchStr);
2063 if (Arch == CudaArch::UNKNOWN) {
2064 C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
2065 Error = true;
Artem Belevicha424e882016-12-09 22:59:17 +00002066 } else if (A->getOption().matches(options::OPT_cuda_gpu_arch_EQ))
2067 GpuArchs.insert(Arch);
2068 else if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ))
2069 GpuArchs.erase(Arch);
2070 else
2071 llvm_unreachable("Unexpected option.");
Samuel Antao64e965e2016-09-30 15:34:19 +00002072 }
2073
Artem Belevicha424e882016-12-09 22:59:17 +00002074 // Collect list of GPUs remaining in the set.
2075 for (CudaArch Arch : GpuArchs)
2076 GpuArchList.push_back(Arch);
2077
2078 // Default to sm_20 which is the lowest common denominator for
2079 // supported GPUs. sm_20 code should work correctly, if
2080 // suboptimally, on all newer GPUs.
Samuel Antao64e965e2016-09-30 15:34:19 +00002081 if (GpuArchList.empty())
2082 GpuArchList.push_back(CudaArch::SM_20);
2083
2084 return Error;
2085 }
2086 };
2087
Samuel Antao28c4f182016-10-27 17:08:03 +00002088 /// OpenMP action builder. The host bitcode is passed to the device frontend
2089 /// and all the device linked images are passed to the host link phase.
2090 class OpenMPActionBuilder final : public DeviceActionBuilder {
2091 /// The OpenMP actions for the current input.
2092 ActionList OpenMPDeviceActions;
2093
2094 /// The linker inputs obtained for each toolchain.
2095 SmallVector<ActionList, 8> DeviceLinkerInputs;
2096
2097 public:
2098 OpenMPActionBuilder(Compilation &C, DerivedArgList &Args,
2099 const Driver::InputList &Inputs)
2100 : DeviceActionBuilder(C, Args, Inputs, Action::OFK_OpenMP) {}
2101
2102 ActionBuilderReturnCode
2103 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2104 phases::ID CurPhase, phases::ID FinalPhase,
2105 PhasesTy &Phases) override {
2106
2107 // We should always have an action for each input.
2108 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2109 "Number of OpenMP actions and toolchains do not match.");
2110
2111 // The host only depends on device action in the linking phase, when all
2112 // the device images have to be embedded in the host image.
2113 if (CurPhase == phases::Link) {
2114 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2115 "Toolchains and linker inputs sizes do not match.");
2116 auto LI = DeviceLinkerInputs.begin();
2117 for (auto *A : OpenMPDeviceActions) {
2118 LI->push_back(A);
2119 ++LI;
2120 }
2121
2122 // We passed the device action as a host dependence, so we don't need to
2123 // do anything else with them.
2124 OpenMPDeviceActions.clear();
2125 return ABRT_Success;
2126 }
2127
2128 // By default, we produce an action for each device arch.
2129 for (Action *&A : OpenMPDeviceActions)
2130 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2131
2132 return ABRT_Success;
2133 }
2134
2135 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2136
2137 // If this is an input action replicate it for each OpenMP toolchain.
2138 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2139 OpenMPDeviceActions.clear();
2140 for (unsigned I = 0; I < ToolChains.size(); ++I)
2141 OpenMPDeviceActions.push_back(
2142 C.MakeAction<InputAction>(IA->getInputArg(), IA->getType()));
2143 return ABRT_Success;
2144 }
2145
Samuel Antaofab4f372016-10-27 18:00:51 +00002146 // If this is an unbundling action use it as is for each OpenMP toolchain.
2147 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2148 OpenMPDeviceActions.clear();
2149 for (unsigned I = 0; I < ToolChains.size(); ++I) {
2150 OpenMPDeviceActions.push_back(UA);
2151 UA->registerDependentActionInfo(
2152 ToolChains[I], /*BoundArch=*/StringRef(), Action::OFK_OpenMP);
2153 }
2154 return ABRT_Success;
2155 }
2156
Samuel Antao28c4f182016-10-27 17:08:03 +00002157 // When generating code for OpenMP we use the host compile phase result as
2158 // a dependence to the device compile phase so that it can learn what
2159 // declarations should be emitted. However, this is not the only use for
2160 // the host action, so we prevent it from being collapsed.
2161 if (isa<CompileJobAction>(HostAction)) {
2162 HostAction->setCannotBeCollapsedWithNextDependentAction();
2163 assert(ToolChains.size() == OpenMPDeviceActions.size() &&
2164 "Toolchains and device action sizes do not match.");
2165 OffloadAction::HostDependence HDep(
2166 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2167 /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2168 auto TC = ToolChains.begin();
2169 for (Action *&A : OpenMPDeviceActions) {
2170 assert(isa<CompileJobAction>(A));
2171 OffloadAction::DeviceDependences DDep;
2172 DDep.add(*A, **TC, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2173 A = C.MakeAction<OffloadAction>(HDep, DDep);
2174 ++TC;
2175 }
2176 }
2177 return ABRT_Success;
2178 }
2179
Samuel Antao69d6f312016-10-27 17:50:43 +00002180 void appendTopLevelActions(ActionList &AL) override {
2181 if (OpenMPDeviceActions.empty())
2182 return;
2183
2184 // We should always have an action for each input.
2185 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2186 "Number of OpenMP actions and toolchains do not match.");
2187
2188 // Append all device actions followed by the proper offload action.
2189 auto TI = ToolChains.begin();
2190 for (auto *A : OpenMPDeviceActions) {
2191 OffloadAction::DeviceDependences Dep;
2192 Dep.add(*A, **TI, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2193 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2194 ++TI;
2195 }
2196 // We no longer need the action stored in this builder.
2197 OpenMPDeviceActions.clear();
2198 }
2199
Samuel Antao28c4f182016-10-27 17:08:03 +00002200 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {
2201 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2202 "Toolchains and linker inputs sizes do not match.");
2203
2204 // Append a new link action for each device.
2205 auto TC = ToolChains.begin();
2206 for (auto &LI : DeviceLinkerInputs) {
2207 auto *DeviceLinkAction =
2208 C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2209 DA.add(*DeviceLinkAction, **TC, /*BoundArch=*/nullptr,
2210 Action::OFK_OpenMP);
2211 ++TC;
2212 }
2213 }
2214
2215 bool initialize() override {
2216 // Get the OpenMP toolchains. If we don't get any, the action builder will
2217 // know there is nothing to do related to OpenMP offloading.
2218 auto OpenMPTCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
2219 for (auto TI = OpenMPTCRange.first, TE = OpenMPTCRange.second; TI != TE;
2220 ++TI)
2221 ToolChains.push_back(TI->second);
2222
2223 DeviceLinkerInputs.resize(ToolChains.size());
2224 return false;
2225 }
Samuel Antao69d6f312016-10-27 17:50:43 +00002226
2227 bool canUseBundlerUnbundler() const override {
2228 // OpenMP should use bundled files whenever possible.
2229 return true;
2230 }
Samuel Antao28c4f182016-10-27 17:08:03 +00002231 };
2232
2233 ///
2234 /// TODO: Add the implementation for other specialized builders here.
2235 ///
Samuel Antao64e965e2016-09-30 15:34:19 +00002236
2237 /// Specialized builders being used by this offloading action builder.
2238 SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders;
2239
Samuel Antao69d6f312016-10-27 17:50:43 +00002240 /// Flag set to true if all valid builders allow file bundling/unbundling.
2241 bool CanUseBundler;
2242
Samuel Antao64e965e2016-09-30 15:34:19 +00002243public:
2244 OffloadingActionBuilder(Compilation &C, DerivedArgList &Args,
2245 const Driver::InputList &Inputs)
Samuel Antao10e905c2016-10-27 01:08:58 +00002246 : C(C) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002247 // Create a specialized builder for each device toolchain.
2248
2249 IsValid = true;
2250
2251 // Create a specialized builder for CUDA.
2252 SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs));
2253
Samuel Antao28c4f182016-10-27 17:08:03 +00002254 // Create a specialized builder for OpenMP.
2255 SpecializedBuilders.push_back(new OpenMPActionBuilder(C, Args, Inputs));
2256
Samuel Antao64e965e2016-09-30 15:34:19 +00002257 //
2258 // TODO: Build other specialized builders here.
2259 //
2260
Samuel Antao69d6f312016-10-27 17:50:43 +00002261 // Initialize all the builders, keeping track of errors. If all valid
2262 // builders agree that we can use bundling, set the flag to true.
2263 unsigned ValidBuilders = 0u;
2264 unsigned ValidBuildersSupportingBundling = 0u;
2265 for (auto *SB : SpecializedBuilders) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002266 IsValid = IsValid && !SB->initialize();
Samuel Antao69d6f312016-10-27 17:50:43 +00002267
2268 // Update the counters if the builder is valid.
2269 if (SB->isValid()) {
2270 ++ValidBuilders;
2271 if (SB->canUseBundlerUnbundler())
2272 ++ValidBuildersSupportingBundling;
2273 }
2274 }
2275 CanUseBundler =
2276 ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling;
Artem Belevichf981e30b2016-08-02 22:37:47 +00002277 }
Justin Lebardc3c5042016-04-19 02:27:07 +00002278
Samuel Antao64e965e2016-09-30 15:34:19 +00002279 ~OffloadingActionBuilder() {
2280 for (auto *SB : SpecializedBuilders)
2281 delete SB;
Samuel Antaod06239d2016-07-15 23:13:27 +00002282 }
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002283
Samuel Antao64e965e2016-09-30 15:34:19 +00002284 /// Generate an action that adds device dependences (if any) to a host action.
2285 /// If no device dependence actions exist, just return the host action \a
2286 /// HostAction. If an error is found or if no builder requires the host action
2287 /// to be generated, return nullptr.
2288 Action *
2289 addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg,
2290 phases::ID CurPhase, phases::ID FinalPhase,
2291 DeviceActionBuilder::PhasesTy &Phases) {
2292 if (!IsValid)
2293 return nullptr;
Justin Lebar7bf77982016-01-11 23:27:13 +00002294
Samuel Antao64e965e2016-09-30 15:34:19 +00002295 if (SpecializedBuilders.empty())
2296 return HostAction;
2297
2298 assert(HostAction && "Invalid host action!");
2299
2300 OffloadAction::DeviceDependences DDeps;
2301 // Check if all the programming models agree we should not emit the host
2302 // action. Also, keep track of the offloading kinds employed.
2303 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2304 unsigned InactiveBuilders = 0u;
2305 unsigned IgnoringBuilders = 0u;
2306 for (auto *SB : SpecializedBuilders) {
2307 if (!SB->isValid()) {
2308 ++InactiveBuilders;
2309 continue;
2310 }
2311
Samuel Antao28c4f182016-10-27 17:08:03 +00002312 auto RetCode =
2313 SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases);
Samuel Antao64e965e2016-09-30 15:34:19 +00002314
2315 // If the builder explicitly says the host action should be ignored,
2316 // we need to increment the variable that tracks the builders that request
2317 // the host object to be ignored.
2318 if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host)
2319 ++IgnoringBuilders;
2320
2321 // Unless the builder was inactive for this action, we have to record the
2322 // offload kind because the host will have to use it.
2323 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2324 OffloadKind |= SB->getAssociatedOffloadKind();
2325 }
2326
2327 // If all builders agree that the host object should be ignored, just return
2328 // nullptr.
2329 if (IgnoringBuilders &&
2330 SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders))
2331 return nullptr;
2332
2333 if (DDeps.getActions().empty())
2334 return HostAction;
2335
2336 // We have dependences we need to bundle together. We use an offload action
2337 // for that.
2338 OffloadAction::HostDependence HDep(
2339 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2340 /*BoundArch=*/nullptr, DDeps);
2341 return C.MakeAction<OffloadAction>(HDep, DDeps);
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002342 }
2343
Samuel Antao64e965e2016-09-30 15:34:19 +00002344 /// Generate an action that adds a host dependence to a device action. The
2345 /// results will be kept in this action builder. Return true if an error was
2346 /// found.
Samuel Antaofab4f372016-10-27 18:00:51 +00002347 bool addHostDependenceToDeviceActions(Action *&HostAction,
Samuel Antao64e965e2016-09-30 15:34:19 +00002348 const Arg *InputArg) {
2349 if (!IsValid)
2350 return true;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002351
Samuel Antaofab4f372016-10-27 18:00:51 +00002352 // If we are supporting bundling/unbundling and the current action is an
2353 // input action of non-source file, we replace the host action by the
2354 // unbundling action. The bundler tool has the logic to detect if an input
2355 // is a bundle or not and if the input is not a bundle it assumes it is a
2356 // host file. Therefore it is safe to create an unbundling action even if
2357 // the input is not a bundle.
2358 if (CanUseBundler && isa<InputAction>(HostAction) &&
2359 InputArg->getOption().getKind() == llvm::opt::Option::InputClass &&
2360 !types::isSrcFile(HostAction->getType())) {
2361 auto UnbundlingHostAction =
2362 C.MakeAction<OffloadUnbundlingJobAction>(HostAction);
2363 UnbundlingHostAction->registerDependentActionInfo(
2364 C.getSingleOffloadToolChain<Action::OFK_Host>(),
2365 /*BoundArch=*/StringRef(), Action::OFK_Host);
2366 HostAction = UnbundlingHostAction;
2367 }
2368
Samuel Antao64e965e2016-09-30 15:34:19 +00002369 assert(HostAction && "Invalid host action!");
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002370
Samuel Antao64e965e2016-09-30 15:34:19 +00002371 // Register the offload kinds that are used.
2372 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2373 for (auto *SB : SpecializedBuilders) {
2374 if (!SB->isValid())
2375 continue;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002376
Samuel Antao64e965e2016-09-30 15:34:19 +00002377 auto RetCode = SB->addDeviceDepences(HostAction);
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002378
Samuel Antao64e965e2016-09-30 15:34:19 +00002379 // Host dependences for device actions are not compatible with that same
2380 // action being ignored.
2381 assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host &&
2382 "Host dependence not expected to be ignored.!");
Samuel Antaod06239d2016-07-15 23:13:27 +00002383
Samuel Antao64e965e2016-09-30 15:34:19 +00002384 // Unless the builder was inactive for this action, we have to record the
2385 // offload kind because the host will have to use it.
2386 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2387 OffloadKind |= SB->getAssociatedOffloadKind();
2388 }
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002389
Samuel Antao64e965e2016-09-30 15:34:19 +00002390 return false;
2391 }
2392
Samuel Antao69d6f312016-10-27 17:50:43 +00002393 /// Add the offloading top level actions to the provided action list. This
2394 /// function can replace the host action by a bundling action if the
2395 /// programming models allow it.
Samuel Antao64e965e2016-09-30 15:34:19 +00002396 bool appendTopLevelActions(ActionList &AL, Action *HostAction,
2397 const Arg *InputArg) {
Samuel Antao69d6f312016-10-27 17:50:43 +00002398 // Get the device actions to be appended.
2399 ActionList OffloadAL;
Samuel Antao64e965e2016-09-30 15:34:19 +00002400 for (auto *SB : SpecializedBuilders) {
2401 if (!SB->isValid())
2402 continue;
Samuel Antao69d6f312016-10-27 17:50:43 +00002403 SB->appendTopLevelActions(OffloadAL);
Samuel Antao64e965e2016-09-30 15:34:19 +00002404 }
2405
Samuel Antao69d6f312016-10-27 17:50:43 +00002406 // If we can use the bundler, replace the host action by the bundling one in
2407 // the resulting list. Otherwise, just append the device actions.
2408 if (CanUseBundler && !OffloadAL.empty()) {
2409 // Add the host action to the list in order to create the bundling action.
2410 OffloadAL.push_back(HostAction);
2411
2412 // We expect that the host action was just appended to the action list
2413 // before this method was called.
2414 assert(HostAction == AL.back() && "Host action not in the list??");
2415 HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL);
2416 AL.back() = HostAction;
2417 } else
2418 AL.append(OffloadAL.begin(), OffloadAL.end());
2419
Samuel Antao64e965e2016-09-30 15:34:19 +00002420 // Propagate to the current host action (if any) the offload information
2421 // associated with the current input.
2422 if (HostAction)
2423 HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg],
2424 /*BoundArch=*/nullptr);
Samuel Antao64e965e2016-09-30 15:34:19 +00002425 return false;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002426 }
Artem Belevich5bde4e02015-07-20 20:02:54 +00002427
Samuel Antao64e965e2016-09-30 15:34:19 +00002428 /// Processes the host linker action. This currently consists of replacing it
2429 /// with an offload action if there are device link objects and propagate to
2430 /// the host action all the offload kinds used in the current compilation. The
2431 /// resulting action is returned.
2432 Action *processHostLinkAction(Action *HostAction) {
2433 // Add all the dependences from the device linking actions.
2434 OffloadAction::DeviceDependences DDeps;
2435 for (auto *SB : SpecializedBuilders) {
2436 if (!SB->isValid())
2437 continue;
Justin Lebar21e5d4f2016-01-14 21:41:27 +00002438
Samuel Antao64e965e2016-09-30 15:34:19 +00002439 SB->appendLinkDependences(DDeps);
Justin Lebar21e5d4f2016-01-14 21:41:27 +00002440 }
Samuel Antaod06239d2016-07-15 23:13:27 +00002441
Samuel Antao64e965e2016-09-30 15:34:19 +00002442 // Calculate all the offload kinds used in the current compilation.
2443 unsigned ActiveOffloadKinds = 0u;
2444 for (auto &I : InputArgToOffloadKindMap)
2445 ActiveOffloadKinds |= I.second;
2446
2447 // If we don't have device dependencies, we don't have to create an offload
2448 // action.
2449 if (DDeps.getActions().empty()) {
2450 // Propagate all the active kinds to host action. Given that it is a link
2451 // action it is assumed to depend on all actions generated so far.
2452 HostAction->propagateHostOffloadInfo(ActiveOffloadKinds,
2453 /*BoundArch=*/nullptr);
2454 return HostAction;
2455 }
2456
2457 // Create the offload action with all dependences. When an offload action
2458 // is created the kinds are propagated to the host action, so we don't have
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002459 // to do that explicitly here.
Samuel Antao64e965e2016-09-30 15:34:19 +00002460 OffloadAction::HostDependence HDep(
2461 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2462 /*BoundArch*/ nullptr, ActiveOffloadKinds);
2463 return C.MakeAction<OffloadAction>(HDep, DDeps);
2464 }
2465};
2466} // anonymous namespace.
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002467
Justin Lebar0f3474c2016-02-11 02:00:50 +00002468void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
2469 const InputList &Inputs, ActionList &Actions) const {
Chad Rosierecdede82011-08-12 22:08:57 +00002470 llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00002471
Daniel Dunbar34c41872009-03-13 00:17:48 +00002472 if (!SuppressMissingInputWarning && Inputs.empty()) {
Daniel Dunbarbfeec742009-03-12 23:55:14 +00002473 Diag(clang::diag::err_drv_no_input_files);
2474 return;
2475 }
2476
Chad Rosier7742b5d2011-07-27 23:36:45 +00002477 Arg *FinalPhaseArg;
2478 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
Daniel Dunbarbfeec742009-03-12 23:55:14 +00002479
Bob Haarmanaaf51912017-02-27 19:40:19 +00002480 if (FinalPhase == phases::Link) {
2481 if (Args.hasArg(options::OPT_emit_llvm))
2482 Diag(clang::diag::err_drv_emit_llvm_link);
2483 if (IsCLMode() && LTOMode != LTOK_None &&
2484 !Args.getLastArgValue(options::OPT_fuse_ld_EQ).equals_lower("lld"))
2485 Diag(clang::diag::err_drv_lto_without_lld);
Rafael Espindolae8025642013-08-25 14:27:09 +00002486 }
2487
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002488 // Reject -Z* at the top level, these options should never have been exposed
2489 // by gcc.
Daniel Dunbardd765242009-03-26 16:12:09 +00002490 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
Daniel Dunbar0e759942009-03-20 06:14:23 +00002491 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
Daniel Dunbarbfeec742009-03-12 23:55:14 +00002492
Hans Wennborg13b7fe72013-08-12 23:26:25 +00002493 // Diagnose misuse of /Fo.
2494 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
Hans Wennborg13b7fe72013-08-12 23:26:25 +00002495 StringRef V = A->getValue();
Hans Wennborg61647532014-11-17 19:16:36 +00002496 if (Inputs.size() > 1 && !V.empty() &&
2497 !llvm::sys::path::is_separator(V.back())) {
Hans Wennborg13b7fe72013-08-12 23:26:25 +00002498 // Check whether /Fo tries to name an output file for multiple inputs.
Hans Wennborg9c1659b2013-10-18 22:49:04 +00002499 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002500 << A->getSpelling() << V;
Hans Wennborg13b7fe72013-08-12 23:26:25 +00002501 Args.eraseArg(options::OPT__SLASH_Fo);
2502 }
2503 }
2504
Hans Wennborg9c1659b2013-10-18 22:49:04 +00002505 // Diagnose misuse of /Fa.
2506 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
2507 StringRef V = A->getValue();
Hans Wennborg61647532014-11-17 19:16:36 +00002508 if (Inputs.size() > 1 && !V.empty() &&
2509 !llvm::sys::path::is_separator(V.back())) {
Hans Wennborg9c1659b2013-10-18 22:49:04 +00002510 // Check whether /Fa tries to name an asm file for multiple inputs.
2511 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002512 << A->getSpelling() << V;
Hans Wennborg9c1659b2013-10-18 22:49:04 +00002513 Args.eraseArg(options::OPT__SLASH_Fa);
2514 }
2515 }
2516
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00002517 // Diagnose misuse of /o.
2518 if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
2519 if (A->getValue()[0] == '\0') {
2520 // It has to have a value.
2521 Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
2522 Args.eraseArg(options::OPT__SLASH_o);
2523 }
2524 }
2525
Nico Weber2ca4be92016-03-01 23:16:44 +00002526 // Diagnose unsupported forms of /Yc /Yu. Ignore /Yc/Yu for now if:
2527 // * no filename after it
2528 // * both /Yc and /Yu passed but with different filenames
2529 // * corresponding file not also passed as /FI
2530 Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
2531 Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
2532 if (YcArg && YcArg->getValue()[0] == '\0') {
2533 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YcArg->getSpelling();
2534 Args.eraseArg(options::OPT__SLASH_Yc);
2535 YcArg = nullptr;
2536 }
2537 if (YuArg && YuArg->getValue()[0] == '\0') {
2538 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YuArg->getSpelling();
2539 Args.eraseArg(options::OPT__SLASH_Yu);
2540 YuArg = nullptr;
2541 }
2542 if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
2543 Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
2544 Args.eraseArg(options::OPT__SLASH_Yc);
2545 Args.eraseArg(options::OPT__SLASH_Yu);
2546 YcArg = YuArg = nullptr;
2547 }
2548 if (YcArg || YuArg) {
2549 StringRef Val = YcArg ? YcArg->getValue() : YuArg->getValue();
2550 bool FoundMatchingInclude = false;
2551 for (const Arg *Inc : Args.filtered(options::OPT_include)) {
2552 // FIXME: Do case-insensitive matching and consider / and \ as equal.
2553 if (Inc->getValue() == Val)
2554 FoundMatchingInclude = true;
2555 }
2556 if (!FoundMatchingInclude) {
2557 Diag(clang::diag::warn_drv_ycyu_no_fi_arg_clang_cl)
2558 << (YcArg ? YcArg : YuArg)->getSpelling();
2559 Args.eraseArg(options::OPT__SLASH_Yc);
2560 Args.eraseArg(options::OPT__SLASH_Yu);
2561 YcArg = YuArg = nullptr;
2562 }
2563 }
2564 if (YcArg && Inputs.size() > 1) {
2565 Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
2566 Args.eraseArg(options::OPT__SLASH_Yc);
2567 YcArg = nullptr;
2568 }
2569 if (Args.hasArg(options::OPT__SLASH_Y_)) {
2570 // /Y- disables all pch handling. Rather than check for it everywhere,
2571 // just remove clang-cl pch-related flags here.
2572 Args.eraseArg(options::OPT__SLASH_Fp);
2573 Args.eraseArg(options::OPT__SLASH_Yc);
2574 Args.eraseArg(options::OPT__SLASH_Yu);
2575 YcArg = YuArg = nullptr;
2576 }
Nico Weber2ca4be92016-03-01 23:16:44 +00002577
Samuel Antao64e965e2016-09-30 15:34:19 +00002578 // Builder to be used to build offloading actions.
2579 OffloadingActionBuilder OffloadBuilder(C, Args, Inputs);
Samuel Antaod06239d2016-07-15 23:13:27 +00002580
Daniel Dunbar65229332009-03-13 11:38:42 +00002581 // Construct the actions to perform.
2582 ActionList LinkerInputs;
Alp Toker965f8822013-11-27 05:22:15 +00002583
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002584 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL;
Artem Belevich5bde4e02015-07-20 20:02:54 +00002585 for (auto &I : Inputs) {
2586 types::ID InputType = I.first;
2587 const Arg *InputArg = I.second;
Daniel Dunbar65229332009-03-13 11:38:42 +00002588
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002589 PL.clear();
2590 types::getCompilationPhases(InputType, PL);
Daniel Dunbar65229332009-03-13 11:38:42 +00002591
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002592 // If the first step comes after the final phase we are doing as part of
2593 // this compilation, warn the user about it.
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002594 phases::ID InitialPhase = PL[0];
Daniel Dunbar65229332009-03-13 11:38:42 +00002595 if (InitialPhase > FinalPhase) {
Daniel Dunbaradc5c7c2009-03-19 07:57:08 +00002596 // Claim here to avoid the more general unused warning.
2597 InputArg->claim();
Daniel Dunbar07806ca2009-09-17 04:13:26 +00002598
Daniel Dunbar2db3e732011-04-20 15:44:48 +00002599 // Suppress all unused style warnings with -Qunused-arguments
2600 if (Args.hasArg(options::OPT_Qunused_arguments))
2601 continue;
2602
Richard Smith403f76e2012-08-06 04:09:06 +00002603 // Special case when final phase determined by binary name, rather than
2604 // by a command-line argument with a corresponding Arg.
Hans Wennborg70850d82013-07-18 20:29:38 +00002605 if (CCCIsCPP())
Richard Smith403f76e2012-08-06 04:09:06 +00002606 Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002607 << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
Daniel Dunbar07806ca2009-09-17 04:13:26 +00002608 // Special case '-E' warning on a previously preprocessed file to make
2609 // more sense.
Richard Smith403f76e2012-08-06 04:09:06 +00002610 else if (InitialPhase == phases::Compile &&
2611 FinalPhase == phases::Preprocess &&
2612 getPreprocessedType(InputType) == types::TY_INVALID)
Daniel Dunbar07806ca2009-09-17 04:13:26 +00002613 Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002614 << InputArg->getAsString(Args) << !!FinalPhaseArg
2615 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
Daniel Dunbar07806ca2009-09-17 04:13:26 +00002616 else
2617 Diag(clang::diag::warn_drv_input_file_unused)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002618 << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
2619 << !!FinalPhaseArg
2620 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
Daniel Dunbar65229332009-03-13 11:38:42 +00002621 continue;
2622 }
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002623
Nico Weberad2d8f32016-04-21 19:59:10 +00002624 if (YcArg) {
2625 // Add a separate precompile phase for the compile phase.
2626 if (FinalPhase >= phases::Compile) {
Richard Smith8cd452d2016-08-30 18:55:16 +00002627 const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType);
Nico Weberad2d8f32016-04-21 19:59:10 +00002628 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PCHPL;
Richard Smith8cd452d2016-08-30 18:55:16 +00002629 types::getCompilationPhases(HeaderType, PCHPL);
David Blaikie0aaa7622017-01-13 17:34:15 +00002630 Arg *PchInputArg = MakeInputArg(Args, *Opts, YcArg->getValue());
Nico Weberad2d8f32016-04-21 19:59:10 +00002631
2632 // Build the pipeline for the pch file.
Richard Smith8cd452d2016-08-30 18:55:16 +00002633 Action *ClangClPch =
2634 C.MakeAction<InputAction>(*PchInputArg, HeaderType);
Nico Weberad2d8f32016-04-21 19:59:10 +00002635 for (phases::ID Phase : PCHPL)
2636 ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
2637 assert(ClangClPch);
2638 Actions.push_back(ClangClPch);
2639 // The driver currently exits after the first failed command. This
2640 // relies on that behavior, to make sure if the pch generation fails,
2641 // the main compilation won't run.
2642 }
2643 }
2644
Daniel Dunbar65229332009-03-13 11:38:42 +00002645 // Build the pipeline for this file.
Justin Lebar41094612016-01-11 23:07:27 +00002646 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
Samuel Antao64e965e2016-09-30 15:34:19 +00002647
2648 // Use the current host action in any of the offloading actions, if
2649 // required.
2650 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
2651 break;
2652
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002653 for (SmallVectorImpl<phases::ID>::iterator i = PL.begin(), e = PL.end();
2654 i != e; ++i) {
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002655 phases::ID Phase = *i;
Daniel Dunbar65229332009-03-13 11:38:42 +00002656
2657 // We are done if this step is past what the user requested.
2658 if (Phase > FinalPhase)
2659 break;
2660
Samuel Antao64e965e2016-09-30 15:34:19 +00002661 // Add any offload action the host action depends on.
2662 Current = OffloadBuilder.addDeviceDependencesToHostAction(
2663 Current, InputArg, Phase, FinalPhase, PL);
2664 if (!Current)
2665 break;
2666
Daniel Dunbar65229332009-03-13 11:38:42 +00002667 // Queue linker inputs.
2668 if (Phase == phases::Link) {
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002669 assert((i + 1) == e && "linking must be final compilation step.");
Justin Lebar41094612016-01-11 23:07:27 +00002670 LinkerInputs.push_back(Current);
2671 Current = nullptr;
Daniel Dunbar65229332009-03-13 11:38:42 +00002672 break;
2673 }
2674
Samuel Antao64e965e2016-09-30 15:34:19 +00002675 // Otherwise construct the appropriate action.
2676 auto *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current);
2677
2678 // We didn't create a new action, so we will just move to the next phase.
2679 if (NewCurrent == Current)
Daniel Dunbar13864952009-03-24 20:17:30 +00002680 continue;
2681
Samuel Antao64e965e2016-09-30 15:34:19 +00002682 Current = NewCurrent;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002683
Samuel Antao64e965e2016-09-30 15:34:19 +00002684 // Use the current host action in any of the offloading actions, if
2685 // required.
2686 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
2687 break;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002688
Daniel Dunbar65229332009-03-13 11:38:42 +00002689 if (Current->getType() == types::TY_Nothing)
2690 break;
2691 }
2692
Samuel Antao64e965e2016-09-30 15:34:19 +00002693 // If we ended with something, add to the output list.
2694 if (Current)
Justin Lebar41094612016-01-11 23:07:27 +00002695 Actions.push_back(Current);
Samuel Antao64e965e2016-09-30 15:34:19 +00002696
2697 // Add any top level actions generated for offloading.
2698 OffloadBuilder.appendTopLevelActions(Actions, Current, InputArg);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002699 }
Daniel Dunbar65229332009-03-13 11:38:42 +00002700
Samuel Antao64e965e2016-09-30 15:34:19 +00002701 // Add a link action if necessary.
Samuel Antaod06239d2016-07-15 23:13:27 +00002702 if (!LinkerInputs.empty()) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002703 Action *LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image);
2704 LA = OffloadBuilder.processHostLinkAction(LA);
2705 Actions.push_back(LA);
Samuel Antaod06239d2016-07-15 23:13:27 +00002706 }
Daniel Dunbarc7a67b72009-12-22 23:19:32 +00002707
2708 // If we are linking, claim any options which are obviously only used for
2709 // compilation.
Hans Wennborga8ef14f2013-09-17 00:03:41 +00002710 if (FinalPhase == phases::Link && PL.size() == 1) {
Daniel Dunbarc7a67b72009-12-22 23:19:32 +00002711 Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
Hans Wennborga8ef14f2013-09-17 00:03:41 +00002712 Args.ClaimAllArgs(options::OPT_cl_compile_Group);
2713 }
2714
2715 // Claim ignored clang-cl options.
2716 Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
Artem Belevichbaae0932015-07-28 21:01:30 +00002717
Justin Lebardc3c5042016-04-19 02:27:07 +00002718 // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed
2719 // to non-CUDA compilations and should not trigger warnings there.
Artem Belevichbaae0932015-07-28 21:01:30 +00002720 Args.ClaimAllArgs(options::OPT_cuda_host_only);
Justin Lebardc3c5042016-04-19 02:27:07 +00002721 Args.ClaimAllArgs(options::OPT_cuda_compile_host_device);
Daniel Dunbar65229332009-03-13 11:38:42 +00002722}
2723
Justin Lebar0f3474c2016-02-11 02:00:50 +00002724Action *Driver::ConstructPhaseAction(Compilation &C, const ArgList &Args,
2725 phases::ID Phase, Action *Input) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00002726 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
Samuel Antao64e965e2016-09-30 15:34:19 +00002727
2728 // Some types skip the assembler phase (e.g., llvm-bc), but we can't
2729 // encode this in the steps because the intermediate type depends on
2730 // arguments. Just special case here.
2731 if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm)
2732 return Input;
2733
Daniel Dunbar65229332009-03-13 11:38:42 +00002734 // Build the appropriate action.
2735 switch (Phase) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002736 case phases::Link:
2737 llvm_unreachable("link action invalid here.");
Daniel Dunbar65229332009-03-13 11:38:42 +00002738 case phases::Preprocess: {
Daniel Dunbard67a3222009-03-30 06:36:42 +00002739 types::ID OutputTy;
2740 // -{M, MM} alter the output type.
Daniel Dunbar86aed7d2010-12-08 21:33:40 +00002741 if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
Daniel Dunbard67a3222009-03-30 06:36:42 +00002742 OutputTy = types::TY_Dependencies;
2743 } else {
David Blaikie5d577a22012-06-29 22:03:56 +00002744 OutputTy = Input->getType();
2745 if (!Args.hasFlag(options::OPT_frewrite_includes,
Justin Bognerce8245b2014-06-24 08:01:01 +00002746 options::OPT_fno_rewrite_includes, false) &&
Richard Smith86a3ef52017-06-09 21:24:02 +00002747 !Args.hasFlag(options::OPT_frewrite_imports,
2748 options::OPT_fno_rewrite_imports, false) &&
Justin Bognerce8245b2014-06-24 08:01:01 +00002749 !CCGenDiagnostics)
David Blaikie5d577a22012-06-29 22:03:56 +00002750 OutputTy = types::getPreprocessedType(OutputTy);
Daniel Dunbard67a3222009-03-30 06:36:42 +00002751 assert(OutputTy != types::TY_INVALID &&
2752 "Cannot preprocess this input type!");
2753 }
Justin Lebar41094612016-01-11 23:07:27 +00002754 return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
Daniel Dunbar65229332009-03-13 11:38:42 +00002755 }
Aaron Ballman1f10cc52012-07-31 01:21:00 +00002756 case phases::Precompile: {
Richard Smithdd4ad3d2016-08-30 19:06:26 +00002757 types::ID OutputTy = getPrecompiledType(Input->getType());
2758 assert(OutputTy != types::TY_INVALID &&
2759 "Cannot precompile this input type!");
Aaron Ballman1f10cc52012-07-31 01:21:00 +00002760 if (Args.hasArg(options::OPT_fsyntax_only)) {
2761 // Syntax checks should not emit a PCH file
2762 OutputTy = types::TY_Nothing;
2763 }
Justin Lebar41094612016-01-11 23:07:27 +00002764 return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
Aaron Ballman1f10cc52012-07-31 01:21:00 +00002765 }
Daniel Dunbar65229332009-03-13 11:38:42 +00002766 case phases::Compile: {
David Blaikie486f4402014-08-29 07:25:23 +00002767 if (Args.hasArg(options::OPT_fsyntax_only))
Justin Lebar41094612016-01-11 23:07:27 +00002768 return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
David Blaikie486f4402014-08-29 07:25:23 +00002769 if (Args.hasArg(options::OPT_rewrite_objc))
Justin Lebar41094612016-01-11 23:07:27 +00002770 return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
David Blaikie486f4402014-08-29 07:25:23 +00002771 if (Args.hasArg(options::OPT_rewrite_legacy_objc))
Justin Lebar41094612016-01-11 23:07:27 +00002772 return C.MakeAction<CompileJobAction>(Input,
2773 types::TY_RewrittenLegacyObjC);
David Blaikie486f4402014-08-29 07:25:23 +00002774 if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto))
Justin Lebar41094612016-01-11 23:07:27 +00002775 return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
David Blaikie486f4402014-08-29 07:25:23 +00002776 if (Args.hasArg(options::OPT__migrate))
Justin Lebar41094612016-01-11 23:07:27 +00002777 return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
David Blaikie486f4402014-08-29 07:25:23 +00002778 if (Args.hasArg(options::OPT_emit_ast))
Justin Lebar41094612016-01-11 23:07:27 +00002779 return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
David Blaikie486f4402014-08-29 07:25:23 +00002780 if (Args.hasArg(options::OPT_module_file_info))
Justin Lebar41094612016-01-11 23:07:27 +00002781 return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
David Blaikie486f4402014-08-29 07:25:23 +00002782 if (Args.hasArg(options::OPT_verify_pch))
Justin Lebar41094612016-01-11 23:07:27 +00002783 return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
2784 return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
Bob Wilson23a55f12014-12-21 07:00:00 +00002785 }
2786 case phases::Backend: {
Teresa Johnson945bc502015-10-15 20:35:53 +00002787 if (isUsingLTO()) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002788 types::ID Output =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002789 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
Justin Lebar41094612016-01-11 23:07:27 +00002790 return C.MakeAction<BackendJobAction>(Input, Output);
David Blaikie486f4402014-08-29 07:25:23 +00002791 }
2792 if (Args.hasArg(options::OPT_emit_llvm)) {
Shuxin Yang4b3c7ff2013-08-23 21:34:57 +00002793 types::ID Output =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002794 Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
Justin Lebar41094612016-01-11 23:07:27 +00002795 return C.MakeAction<BackendJobAction>(Input, Output);
Daniel Dunbar65229332009-03-13 11:38:42 +00002796 }
Justin Lebar41094612016-01-11 23:07:27 +00002797 return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
Daniel Dunbar65229332009-03-13 11:38:42 +00002798 }
2799 case phases::Assemble:
Justin Lebar21e5d4f2016-01-14 21:41:27 +00002800 return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
Daniel Dunbar65229332009-03-13 11:38:42 +00002801 }
2802
David Blaikie83d382b2011-09-23 05:06:16 +00002803 llvm_unreachable("invalid phase in ConstructPhaseAction");
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002804}
2805
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00002806void Driver::BuildJobs(Compilation &C) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00002807 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
Daniel Dunbare75d8342009-03-16 06:56:51 +00002808
2809 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
2810
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002811 // It is an error to provide a -o option if we are making multiple output
2812 // files.
Daniel Dunbare75d8342009-03-16 06:56:51 +00002813 if (FinalOutput) {
2814 unsigned NumOutputs = 0;
Saleem Abdulrasoolda3f4e52014-12-29 21:02:47 +00002815 for (const Action *A : C.getActions())
2816 if (A->getType() != types::TY_Nothing)
Daniel Dunbare75d8342009-03-16 06:56:51 +00002817 ++NumOutputs;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002818
Daniel Dunbare75d8342009-03-16 06:56:51 +00002819 if (NumOutputs > 1) {
2820 Diag(clang::diag::err_drv_output_argument_with_multiple_files);
Craig Topper92fc2df2014-05-17 16:56:41 +00002821 FinalOutput = nullptr;
Daniel Dunbare75d8342009-03-16 06:56:51 +00002822 }
2823 }
2824
Chad Rosier35767232013-04-30 22:01:21 +00002825 // Collect the list of architectures.
2826 llvm::StringSet<> ArchNames;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00002827 if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO())
2828 for (const Arg *A : C.getArgs())
Chad Rosier35767232013-04-30 22:01:21 +00002829 if (A->getOption().matches(options::OPT_arch))
2830 ArchNames.insert(A->getValue());
Chad Rosier35767232013-04-30 22:01:21 +00002831
Justin Lebarb44f6fe2016-01-14 21:41:21 +00002832 // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
2833 std::map<std::pair<const Action *, std::string>, InputInfo> CachedResults;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00002834 for (Action *A : C.getActions()) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002835 // If we are linking an image for multiple archs then the linker wants
2836 // -arch_multiple and -final_output <final image name>. Unfortunately, this
2837 // doesn't fit in cleanly because we have to pass this information down.
Daniel Dunbare75d8342009-03-16 06:56:51 +00002838 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002839 // FIXME: This is a hack; find a cleaner way to integrate this into the
2840 // process.
Craig Topper92fc2df2014-05-17 16:56:41 +00002841 const char *LinkingOutput = nullptr;
Daniel Dunbardd765242009-03-26 16:12:09 +00002842 if (isa<LipoJobAction>(A)) {
Daniel Dunbare75d8342009-03-16 06:56:51 +00002843 if (FinalOutput)
Richard Smithbd55daf2012-11-01 04:30:05 +00002844 LinkingOutput = FinalOutput->getValue();
Daniel Dunbare75d8342009-03-16 06:56:51 +00002845 else
Hans Wennborga7707222015-01-09 17:38:53 +00002846 LinkingOutput = getDefaultImageName();
Daniel Dunbare75d8342009-03-16 06:56:51 +00002847 }
2848
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002849 BuildJobsForAction(C, A, &C.getDefaultToolChain(),
Mehdi Aminic50b1a22016-10-07 21:27:26 +00002850 /*BoundArch*/ StringRef(),
Daniel Dunbare75d8342009-03-16 06:56:51 +00002851 /*AtTopLevel*/ true,
Chad Rosier35767232013-04-30 22:01:21 +00002852 /*MultipleArchs*/ ArchNames.size() > 1,
Samuel Antaod06239d2016-07-15 23:13:27 +00002853 /*LinkingOutput*/ LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00002854 /*TargetDeviceOffloadKind*/ Action::OFK_None);
Daniel Dunbare75d8342009-03-16 06:56:51 +00002855 }
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00002856
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002857 // If the user passed -Qunused-arguments or there were errors, don't warn
2858 // about any unused arguments.
Argyrios Kyrtzidis31448a42010-11-18 21:47:07 +00002859 if (Diags.hasErrorOccurred() ||
Daniel Dunbara3cfbe32009-04-07 19:04:18 +00002860 C.getArgs().hasArg(options::OPT_Qunused_arguments))
Daniel Dunbard175d972009-03-18 18:03:46 +00002861 return;
2862
Daniel Dunbar58399ae2009-03-29 22:24:54 +00002863 // Claim -### here.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002864 (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002865
Nico Weber47bf5052016-04-25 21:15:49 +00002866 // Claim --driver-mode, --rsp-quoting, it was handled earlier.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002867 (void)C.getArgs().hasArg(options::OPT_driver_mode);
Nico Weber47bf5052016-04-25 21:15:49 +00002868 (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
Hans Wennborg70850d82013-07-18 20:29:38 +00002869
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00002870 for (Arg *A : C.getArgs()) {
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00002871 // FIXME: It would be nice to be able to send the argument to the
David Blaikie9c902b52011-09-25 23:23:43 +00002872 // DiagnosticsEngine, so that extra values, position, and so on could be
2873 // printed.
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00002874 if (!A->isClaimed()) {
Michael J. Spencer66e2b202012-10-19 22:37:06 +00002875 if (A->getOption().hasFlag(options::NoArgumentUnused))
Daniel Dunbara3cfbe32009-04-07 19:04:18 +00002876 continue;
2877
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002878 // Suppress the warning automatically if this is just a flag, and it is an
2879 // instance of an argument we already claimed.
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00002880 const Option &Opt = A->getOption();
Michael J. Spencerad3ccc32012-08-20 21:41:17 +00002881 if (Opt.getKind() == Option::FlagClass) {
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00002882 bool DuplicateClaimed = false;
2883
Sean Silva14facf32015-06-09 01:57:17 +00002884 for (const Arg *AA : C.getArgs().filtered(&Opt)) {
2885 if (AA->isClaimed()) {
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00002886 DuplicateClaimed = true;
2887 break;
2888 }
2889 }
2890
2891 if (DuplicateClaimed)
2892 continue;
2893 }
2894
Ehsan Akhgarid8518332016-01-25 21:14:52 +00002895 // In clang-cl, don't mention unknown arguments here since they have
2896 // already been warned about.
2897 if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN))
2898 Diag(clang::diag::warn_drv_unused_argument)
2899 << A->getAsString(C.getArgs());
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00002900 }
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00002901 }
Daniel Dunbar95e6b192009-03-13 22:12:33 +00002902}
Daniel Dunbarc4343942010-02-03 03:07:56 +00002903
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002904namespace {
2905/// Utility class to control the collapse of dependent actions and select the
2906/// tools accordingly.
2907class ToolSelector final {
2908 /// The tool chain this selector refers to.
2909 const ToolChain &TC;
Daniel Dunbarf9ff3502010-05-14 02:03:00 +00002910
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002911 /// The compilation this selector refers to.
2912 const Compilation &C;
Samuel Antaod06239d2016-07-15 23:13:27 +00002913
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002914 /// The base action this selector refers to.
2915 const JobAction *BaseAction;
Samuel Antaod06239d2016-07-15 23:13:27 +00002916
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002917 /// Set to true if the current toolchain refers to host actions.
2918 bool IsHostSelector;
Samuel Antaod06239d2016-07-15 23:13:27 +00002919
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002920 /// Set to true if save-temps and embed-bitcode functionalities are active.
2921 bool SaveTemps;
2922 bool EmbedBitcode;
2923
2924 /// Get previous dependent action or null if that does not exist. If
2925 /// \a CanBeCollapsed is false, that action must be legal to collapse or
2926 /// null will be returned.
2927 const JobAction *getPrevDependentAction(const ActionList &Inputs,
2928 ActionList &SavedOffloadAction,
2929 bool CanBeCollapsed = true) {
2930 // An option can be collapsed only if it has a single input.
2931 if (Inputs.size() != 1)
Craig Topper92fc2df2014-05-17 16:56:41 +00002932 return nullptr;
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002933
2934 Action *CurAction = *Inputs.begin();
2935 if (CanBeCollapsed &&
2936 !CurAction->isCollapsingWithNextDependentActionLegal())
2937 return nullptr;
2938
2939 // If the input action is an offload action. Look through it and save any
2940 // offload action that can be dropped in the event of a collapse.
2941 if (auto *OA = dyn_cast<OffloadAction>(CurAction)) {
2942 // If the dependent action is a device action, we will attempt to collapse
2943 // only with other device actions. Otherwise, we would do the same but
2944 // with host actions only.
2945 if (!IsHostSelector) {
2946 if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) {
2947 CurAction =
2948 OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
2949 if (CanBeCollapsed &&
2950 !CurAction->isCollapsingWithNextDependentActionLegal())
2951 return nullptr;
2952 SavedOffloadAction.push_back(OA);
2953 return dyn_cast<JobAction>(CurAction);
2954 }
2955 } else if (OA->hasHostDependence()) {
2956 CurAction = OA->getHostDependence();
2957 if (CanBeCollapsed &&
2958 !CurAction->isCollapsingWithNextDependentActionLegal())
2959 return nullptr;
2960 SavedOffloadAction.push_back(OA);
2961 return dyn_cast<JobAction>(CurAction);
2962 }
2963 return nullptr;
2964 }
2965
2966 return dyn_cast<JobAction>(CurAction);
2967 }
2968
2969 /// Return true if an assemble action can be collapsed.
2970 bool canCollapseAssembleAction() const {
2971 return TC.useIntegratedAs() && !SaveTemps &&
2972 !C.getArgs().hasArg(options::OPT_via_file_asm) &&
2973 !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
2974 !C.getArgs().hasArg(options::OPT__SLASH_Fa);
2975 }
2976
2977 /// Return true if a preprocessor action can be collapsed.
2978 bool canCollapsePreprocessorAction() const {
2979 return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
2980 !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
2981 !C.getArgs().hasArg(options::OPT_rewrite_objc);
2982 }
2983
2984 /// Struct that relates an action with the offload actions that would be
2985 /// collapsed with it.
2986 struct JobActionInfo final {
2987 /// The action this info refers to.
2988 const JobAction *JA = nullptr;
2989 /// The offload actions we need to take care off if this action is
2990 /// collapsed.
2991 ActionList SavedOffloadAction;
2992 };
2993
2994 /// Append collapsed offload actions from the give nnumber of elements in the
2995 /// action info array.
2996 static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction,
2997 ArrayRef<JobActionInfo> &ActionInfo,
2998 unsigned ElementNum) {
2999 assert(ElementNum <= ActionInfo.size() && "Invalid number of elements.");
3000 for (unsigned I = 0; I < ElementNum; ++I)
3001 CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(),
3002 ActionInfo[I].SavedOffloadAction.end());
3003 }
3004
3005 /// Functions that attempt to perform the combining. They detect if that is
3006 /// legal, and if so they update the inputs \a Inputs and the offload action
3007 /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with
3008 /// the combined action is returned. If the combining is not legal or if the
3009 /// tool does not exist, null is returned.
3010 /// Currently three kinds of collapsing are supported:
3011 /// - Assemble + Backend + Compile;
3012 /// - Assemble + Backend ;
3013 /// - Backend + Compile.
3014 const Tool *
3015 combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
3016 const ActionList *&Inputs,
3017 ActionList &CollapsedOffloadAction) {
3018 if (ActionInfo.size() < 3 || !canCollapseAssembleAction())
3019 return nullptr;
3020 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
3021 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
3022 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA);
3023 if (!AJ || !BJ || !CJ)
3024 return nullptr;
3025
3026 // Get compiler tool.
3027 const Tool *T = TC.SelectTool(*CJ);
3028 if (!T)
3029 return nullptr;
3030
Steven Wu574b0f22016-03-01 01:07:58 +00003031 // When using -fembed-bitcode, it is required to have the same tool (clang)
3032 // for both CompilerJA and BackendJA. Otherwise, combine two stages.
3033 if (EmbedBitcode) {
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003034 const Tool *BT = TC.SelectTool(*BJ);
3035 if (BT == T)
3036 return nullptr;
Steven Wu574b0f22016-03-01 01:07:58 +00003037 }
Bob Wilson23a55f12014-12-21 07:00:00 +00003038
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003039 if (!T->hasIntegratedAssembler())
Bob Wilson23a55f12014-12-21 07:00:00 +00003040 return nullptr;
Samuel Antaod06239d2016-07-15 23:13:27 +00003041
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003042 Inputs = &CJ->getInputs();
3043 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3044 /*NumElements=*/3);
3045 return T;
3046 }
3047 const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo,
3048 const ActionList *&Inputs,
3049 ActionList &CollapsedOffloadAction) {
3050 if (ActionInfo.size() < 2 || !canCollapseAssembleAction())
3051 return nullptr;
3052 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
3053 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
3054 if (!AJ || !BJ)
3055 return nullptr;
3056
3057 // Retrieve the compile job, backend action must always be preceded by one.
3058 ActionList CompileJobOffloadActions;
3059 auto *CJ = getPrevDependentAction(BJ->getInputs(), CompileJobOffloadActions,
3060 /*CanBeCollapsed=*/false);
3061 if (!AJ || !BJ || !CJ)
3062 return nullptr;
3063
3064 assert(isa<CompileJobAction>(CJ) &&
3065 "Expecting compile job preceding backend job.");
3066
3067 // Get compiler tool.
3068 const Tool *T = TC.SelectTool(*CJ);
3069 if (!T)
3070 return nullptr;
3071
3072 if (!T->hasIntegratedAssembler())
3073 return nullptr;
3074
3075 Inputs = &BJ->getInputs();
3076 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3077 /*NumElements=*/2);
3078 return T;
3079 }
3080 const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
3081 const ActionList *&Inputs,
3082 ActionList &CollapsedOffloadAction) {
3083 if (ActionInfo.size() < 2 || !canCollapsePreprocessorAction())
3084 return nullptr;
3085 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA);
3086 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA);
3087 if (!BJ || !CJ)
3088 return nullptr;
3089
3090 // Get compiler tool.
3091 const Tool *T = TC.SelectTool(*CJ);
3092 if (!T)
3093 return nullptr;
3094
3095 if (T->canEmitIR() && (SaveTemps || EmbedBitcode))
3096 return nullptr;
3097
3098 Inputs = &CJ->getInputs();
3099 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3100 /*NumElements=*/2);
3101 return T;
3102 }
3103
3104 /// Updates the inputs if the obtained tool supports combining with
3105 /// preprocessor action, and the current input is indeed a preprocessor
3106 /// action. If combining results in the collapse of offloading actions, those
3107 /// are appended to \a CollapsedOffloadAction.
3108 void combineWithPreprocessor(const Tool *T, const ActionList *&Inputs,
3109 ActionList &CollapsedOffloadAction) {
3110 if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP())
3111 return;
3112
3113 // Attempt to get a preprocessor action dependence.
3114 ActionList PreprocessJobOffloadActions;
3115 auto *PJ = getPrevDependentAction(*Inputs, PreprocessJobOffloadActions);
3116 if (!PJ || !isa<PreprocessJobAction>(PJ))
3117 return;
3118
3119 // This is legal to combine. Append any offload action we found and set the
3120 // current inputs to preprocessor inputs.
3121 CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(),
3122 PreprocessJobOffloadActions.end());
3123 Inputs = &PJ->getInputs();
3124 }
3125
3126public:
3127 ToolSelector(const JobAction *BaseAction, const ToolChain &TC,
3128 const Compilation &C, bool SaveTemps, bool EmbedBitcode)
3129 : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps),
3130 EmbedBitcode(EmbedBitcode) {
3131 assert(BaseAction && "Invalid base action.");
3132 IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None;
3133 }
3134
3135 /// Check if a chain of actions can be combined and return the tool that can
3136 /// handle the combination of actions. The pointer to the current inputs \a
3137 /// Inputs and the list of offload actions \a CollapsedOffloadActions
3138 /// connected to collapsed actions are updated accordingly. The latter enables
3139 /// the caller of the selector to process them afterwards instead of just
3140 /// dropping them. If no suitable tool is found, null will be returned.
3141 const Tool *getTool(const ActionList *&Inputs,
3142 ActionList &CollapsedOffloadAction) {
3143 //
3144 // Get the largest chain of actions that we could combine.
3145 //
3146
3147 SmallVector<JobActionInfo, 5> ActionChain(1);
3148 ActionChain.back().JA = BaseAction;
3149 while (ActionChain.back().JA) {
3150 const Action *CurAction = ActionChain.back().JA;
3151
3152 // Grow the chain by one element.
3153 ActionChain.resize(ActionChain.size() + 1);
3154 JobActionInfo &AI = ActionChain.back();
3155
3156 // Attempt to fill it with the
3157 AI.JA =
3158 getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction);
Daniel Dunbarc4343942010-02-03 03:07:56 +00003159 }
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003160
3161 // Pop the last action info as it could not be filled.
3162 ActionChain.pop_back();
3163
3164 //
3165 // Attempt to combine actions. If all combining attempts failed, just return
3166 // the tool of the provided action. At the end we attempt to combine the
3167 // action with any preprocessor action it may depend on.
3168 //
3169
3170 const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs,
3171 CollapsedOffloadAction);
3172 if (!T)
3173 T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction);
3174 if (!T)
3175 T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction);
3176 if (!T) {
3177 Inputs = &BaseAction->getInputs();
3178 T = TC.SelectTool(*BaseAction);
3179 }
3180
3181 combineWithPreprocessor(T, Inputs, CollapsedOffloadAction);
3182 return T;
Daniel Dunbarc4343942010-02-03 03:07:56 +00003183 }
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003184};
Daniel Dunbarc4343942010-02-03 03:07:56 +00003185}
3186
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003187/// Return a string that uniquely identifies the result of a job. The bound arch
3188/// is not necessarily represented in the toolchain's triple -- for example,
3189/// armv7 and armv7s both map to the same triple -- so we need both in our map.
3190/// Also, we need to add the offloading device kind, as the same tool chain can
3191/// be used for host and device for some programming models, e.g. OpenMP.
3192static std::string GetTriplePlusArchString(const ToolChain *TC,
3193 StringRef BoundArch,
3194 Action::OffloadKind OffloadKind) {
Justin Lebar55c83322016-01-16 03:30:08 +00003195 std::string TriplePlusArch = TC->getTriple().normalize();
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003196 if (!BoundArch.empty()) {
Justin Lebar55c83322016-01-16 03:30:08 +00003197 TriplePlusArch += "-";
3198 TriplePlusArch += BoundArch;
3199 }
Samuel Antao59efaed2016-10-27 17:31:22 +00003200 TriplePlusArch += "-";
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003201 TriplePlusArch += Action::GetOffloadKindName(OffloadKind);
3202 return TriplePlusArch;
3203}
3204
3205InputInfo Driver::BuildJobsForAction(
3206 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
3207 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
3208 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
3209 Action::OffloadKind TargetDeviceOffloadKind) const {
3210 std::pair<const Action *, std::string> ActionTC = {
3211 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003212 auto CachedResult = CachedResults.find(ActionTC);
3213 if (CachedResult != CachedResults.end()) {
3214 return CachedResult->second;
3215 }
Samuel Antaod06239d2016-07-15 23:13:27 +00003216 InputInfo Result = BuildJobsForActionNoCache(
3217 C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003218 CachedResults, TargetDeviceOffloadKind);
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003219 CachedResults[ActionTC] = Result;
3220 return Result;
3221}
3222
3223InputInfo Driver::BuildJobsForActionNoCache(
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003224 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003225 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
Samuel Antaod06239d2016-07-15 23:13:27 +00003226 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003227 Action::OffloadKind TargetDeviceOffloadKind) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003228 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
Daniel Dunbarc4acf9d2009-03-18 23:18:19 +00003229
Samuel Antaod06239d2016-07-15 23:13:27 +00003230 InputInfoList OffloadDependencesInputInfo;
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003231 bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None;
Samuel Antaod06239d2016-07-15 23:13:27 +00003232 if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
3233 // The offload action is expected to be used in four different situations.
3234 //
3235 // a) Set a toolchain/architecture/kind for a host action:
3236 // Host Action 1 -> OffloadAction -> Host Action 2
3237 //
3238 // b) Set a toolchain/architecture/kind for a device action;
3239 // Device Action 1 -> OffloadAction -> Device Action 2
3240 //
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003241 // c) Specify a device dependence to a host action;
Samuel Antaod06239d2016-07-15 23:13:27 +00003242 // Device Action 1 _
3243 // \
3244 // Host Action 1 ---> OffloadAction -> Host Action 2
3245 //
3246 // d) Specify a host dependence to a device action.
3247 // Host Action 1 _
3248 // \
3249 // Device Action 1 ---> OffloadAction -> Device Action 2
3250 //
3251 // For a) and b), we just return the job generated for the dependence. For
3252 // c) and d) we override the current action with the host/device dependence
3253 // if the current toolchain is host/device and set the offload dependences
3254 // info with the jobs obtained from the device/host dependence(s).
3255
3256 // If there is a single device option, just generate the job for it.
3257 if (OA->hasSingleDeviceDependence()) {
3258 InputInfo DevA;
3259 OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
3260 const char *DepBoundArch) {
3261 DevA =
3262 BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
3263 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003264 CachedResults, DepA->getOffloadingDeviceKind());
Samuel Antaod06239d2016-07-15 23:13:27 +00003265 });
3266 return DevA;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003267 }
Samuel Antaod06239d2016-07-15 23:13:27 +00003268
3269 // If 'Action 2' is host, we generate jobs for the device dependences and
3270 // override the current action with the host dependence. Otherwise, we
3271 // generate the host dependences and override the action with the device
3272 // dependence. The dependences can't therefore be a top-level action.
3273 OA->doOnEachDependence(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003274 /*IsHostDependence=*/BuildingForOffloadDevice,
Samuel Antaod06239d2016-07-15 23:13:27 +00003275 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3276 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
3277 C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false,
3278 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003279 DepA->getOffloadingDeviceKind()));
Samuel Antaod06239d2016-07-15 23:13:27 +00003280 });
3281
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003282 A = BuildingForOffloadDevice
Samuel Antaod06239d2016-07-15 23:13:27 +00003283 ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
3284 : OA->getHostDependence();
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003285 }
3286
Daniel Dunbare75d8342009-03-16 06:56:51 +00003287 if (const InputAction *IA = dyn_cast<InputAction>(A)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003288 // FIXME: It would be nice to not claim this here; maybe the old scheme of
3289 // just using Args was better?
Daniel Dunbar5cdf3e02009-03-19 07:29:38 +00003290 const Arg &Input = IA->getInputArg();
3291 Input.claim();
Daniel Dunbar35cbfeb2010-06-09 22:31:08 +00003292 if (Input.getOption().matches(options::OPT_INPUT)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00003293 const char *Name = Input.getValue();
Justin Lebard98cea82016-01-11 23:15:21 +00003294 return InputInfo(A, Name, /* BaseInput = */ Name);
Douglas Katzman678d0cb2015-06-16 18:01:24 +00003295 }
Justin Lebard98cea82016-01-11 23:15:21 +00003296 return InputInfo(A, &Input, /* BaseInput = */ "");
Daniel Dunbare75d8342009-03-16 06:56:51 +00003297 }
3298
3299 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
Chad Rosiera78a6eb2012-04-27 16:50:38 +00003300 const ToolChain *TC;
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003301 StringRef ArchName = BAA->getArchName();
Daniel Dunbar1ef3f2a2009-09-08 23:37:19 +00003302
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003303 if (!ArchName.empty())
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +00003304 TC = &getToolChain(C.getArgs(),
3305 computeTargetTriple(*this, DefaultTargetTriple,
3306 C.getArgs(), ArchName));
Chad Rosiera78a6eb2012-04-27 16:50:38 +00003307 else
3308 TC = &C.getDefaultToolChain();
Daniel Dunbar1ef3f2a2009-09-08 23:37:19 +00003309
Nico Weber5a459f82016-02-23 19:30:43 +00003310 return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
Samuel Antaod06239d2016-07-15 23:13:27 +00003311 MultipleArchs, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003312 TargetDeviceOffloadKind);
Daniel Dunbare75d8342009-03-16 06:56:51 +00003313 }
3314
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003315
Daniel Dunbare75d8342009-03-16 06:56:51 +00003316 const ActionList *Inputs = &A->getInputs();
Daniel Dunbarc4343942010-02-03 03:07:56 +00003317
3318 const JobAction *JA = cast<JobAction>(A);
Samuel Antaod06239d2016-07-15 23:13:27 +00003319 ActionList CollapsedOffloadActions;
3320
Mehdi Amini6683e222017-01-24 18:12:25 +00003321 ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(),
3322 embedBitcodeInObject() && !isUsingLTO());
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003323 const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions);
3324
Rafael Espindola79764462013-03-24 15:06:53 +00003325 if (!T)
Justin Lebar9eaa4892016-01-11 23:09:32 +00003326 return InputInfo();
Daniel Dunbare75d8342009-03-16 06:56:51 +00003327
Samuel Antaod06239d2016-07-15 23:13:27 +00003328 // If we've collapsed action list that contained OffloadAction we
3329 // need to build jobs for host/device-side inputs it may have held.
3330 for (const auto *OA : CollapsedOffloadActions)
3331 cast<OffloadAction>(OA)->doOnEachDependence(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003332 /*IsHostDependence=*/BuildingForOffloadDevice,
Samuel Antaod06239d2016-07-15 23:13:27 +00003333 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3334 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
Artem Belevichbee2f412016-08-22 18:50:34 +00003335 C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false,
Samuel Antaod06239d2016-07-15 23:13:27 +00003336 /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003337 DepA->getOffloadingDeviceKind()));
Samuel Antaod06239d2016-07-15 23:13:27 +00003338 });
Artem Belevichf8144ab2015-08-27 18:10:41 +00003339
Daniel Dunbare75d8342009-03-16 06:56:51 +00003340 // Only use pipes when there is exactly one input.
Daniel Dunbar1a093d22009-03-18 06:00:36 +00003341 InputInfoList InputInfos;
Saleem Abdulrasoolda3f4e52014-12-29 21:02:47 +00003342 for (const Action *Input : *Inputs) {
Eric Christopher14668dd2013-02-18 00:38:25 +00003343 // Treat dsymutil and verify sub-jobs as being at the top-level too, they
3344 // shouldn't get temporary output names.
Daniel Dunbar6beaf512010-06-04 18:28:41 +00003345 // FIXME: Clean this up.
Justin Lebar9eaa4892016-01-11 23:09:32 +00003346 bool SubJobAtTopLevel =
3347 AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
Samuel Antaod06239d2016-07-15 23:13:27 +00003348 InputInfos.push_back(BuildJobsForAction(
3349 C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003350 CachedResults, A->getOffloadingDeviceKind()));
Daniel Dunbare75d8342009-03-16 06:56:51 +00003351 }
3352
Daniel Dunbare75d8342009-03-16 06:56:51 +00003353 // Always use the first input as the base input.
3354 const char *BaseInput = InputInfos[0].getBaseInput();
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003355
Daniel Dunbar6beaf512010-06-04 18:28:41 +00003356 // ... except dsymutil actions, which use their actual input as the base
3357 // input.
3358 if (JA->getType() == types::TY_dSYM)
3359 BaseInput = InputInfos[0].getFilename();
3360
Samuel Antaod06239d2016-07-15 23:13:27 +00003361 // Append outputs of offload device jobs to the input list
3362 if (!OffloadDependencesInputInfo.empty())
3363 InputInfos.append(OffloadDependencesInputInfo.begin(),
3364 OffloadDependencesInputInfo.end());
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003365
Vedant Kumar18286cf2016-07-27 23:02:20 +00003366 // Set the effective triple of the toolchain for the duration of this job.
3367 llvm::Triple EffectiveTriple;
3368 const ToolChain &ToolTC = T->getToolChain();
Samuel Antao31fef982016-10-27 17:39:44 +00003369 const ArgList &Args =
3370 C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind());
Vedant Kumar18286cf2016-07-27 23:02:20 +00003371 if (InputInfos.size() != 1) {
3372 EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args));
3373 } else {
3374 // Pass along the input type if it can be unambiguously determined.
3375 EffectiveTriple = llvm::Triple(
3376 ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType()));
3377 }
3378 RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple);
3379
Daniel Dunbard00272f2010-08-02 02:38:15 +00003380 // Determine the place to write output to, if any.
Justin Lebar9eaa4892016-01-11 23:09:32 +00003381 InputInfo Result;
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003382 InputInfoList UnbundlingResults;
3383 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) {
3384 // If we have an unbundling job, we need to create results for all the
3385 // outputs. We also update the results cache so that other actions using
3386 // this unbundling action can get the right results.
3387 for (auto &UI : UA->getDependentActionsInfo()) {
3388 assert(UI.DependentOffloadKind != Action::OFK_None &&
3389 "Unbundling with no offloading??");
3390
3391 // Unbundling actions are never at the top level. When we generate the
3392 // offloading prefix, we also do that for the host file because the
3393 // unbundling action does not change the type of the output which can
3394 // cause a overwrite.
3395 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
3396 UI.DependentOffloadKind,
3397 UI.DependentToolChain->getTriple().normalize(),
3398 /*CreatePrefixForHost=*/true);
3399 auto CurI = InputInfo(
3400 UA, GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch,
3401 /*AtTopLevel=*/false, MultipleArchs,
3402 OffloadingPrefix),
3403 BaseInput);
3404 // Save the unbundling result.
3405 UnbundlingResults.push_back(CurI);
3406
3407 // Get the unique string identifier for this dependence and cache the
3408 // result.
3409 CachedResults[{A, GetTriplePlusArchString(
3410 UI.DependentToolChain, UI.DependentBoundArch,
3411 UI.DependentOffloadKind)}] = CurI;
3412 }
3413
3414 // Now that we have all the results generated, select the one that should be
3415 // returned for the current depending action.
3416 std::pair<const Action *, std::string> ActionTC = {
3417 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
3418 assert(CachedResults.find(ActionTC) != CachedResults.end() &&
3419 "Result does not exist??");
3420 Result = CachedResults[ActionTC];
3421 } else if (JA->getType() == types::TY_Nothing)
Justin Lebard98cea82016-01-11 23:15:21 +00003422 Result = InputInfo(A, BaseInput);
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003423 else {
3424 // We only have to generate a prefix for the host if this is not a top-level
3425 // action.
3426 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
3427 A->getOffloadingDeviceKind(), TC->getTriple().normalize(),
3428 /*CreatePrefixForHost=*/!!A->getOffloadingHostActiveKinds() &&
3429 !AtTopLevel);
Justin Lebard98cea82016-01-11 23:15:21 +00003430 Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
Samuel Antaod06239d2016-07-15 23:13:27 +00003431 AtTopLevel, MultipleArchs,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003432 OffloadingPrefix),
Justin Lebard98cea82016-01-11 23:15:21 +00003433 BaseInput);
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003434 }
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003435
Chad Rosierbe10f982011-08-02 17:58:04 +00003436 if (CCCPrintBindings && !CCGenDiagnostics) {
Rafael Espindola79764462013-03-24 15:06:53 +00003437 llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
3438 << " - \"" << T->getName() << "\", inputs: [";
Daniel Dunbarb39cc522009-03-17 22:47:06 +00003439 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
3440 llvm::errs() << InputInfos[i].getAsString();
3441 if (i + 1 != e)
3442 llvm::errs() << ", ";
3443 }
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003444 if (UnbundlingResults.empty())
3445 llvm::errs() << "], output: " << Result.getAsString() << "\n";
3446 else {
3447 llvm::errs() << "], outputs: [";
3448 for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) {
3449 llvm::errs() << UnbundlingResults[i].getAsString();
3450 if (i + 1 != e)
3451 llvm::errs() << ", ";
3452 }
3453 llvm::errs() << "] \n";
3454 }
Daniel Dunbarb39cc522009-03-17 22:47:06 +00003455 } else {
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003456 if (UnbundlingResults.empty())
3457 T->ConstructJob(
3458 C, *JA, Result, InputInfos,
3459 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
3460 LinkingOutput);
3461 else
Samuel Antao7108bf32016-11-03 15:41:50 +00003462 T->ConstructJobMultipleOutputs(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003463 C, *JA, UnbundlingResults, InputInfos,
3464 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
3465 LinkingOutput);
Daniel Dunbarb39cc522009-03-17 22:47:06 +00003466 }
Justin Lebar9eaa4892016-01-11 23:09:32 +00003467 return Result;
Daniel Dunbare75d8342009-03-16 06:56:51 +00003468}
3469
Hans Wennborga7707222015-01-09 17:38:53 +00003470const char *Driver::getDefaultImageName() const {
3471 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
3472 return Target.isOSWindows() ? "a.exe" : "a.out";
3473}
3474
Hans Wennborg2c21f742013-10-17 16:16:23 +00003475/// \brief Create output filename based on ArgValue, which could either be a
3476/// full filename, filename without extension, or a directory. If ArgValue
3477/// does not provide a filename, then use BaseName, and use the extension
3478/// suitable for FileType.
Hans Wennborg207fcf02013-08-12 21:56:42 +00003479static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003480 StringRef BaseName,
3481 types::ID FileType) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00003482 SmallString<128> Filename = ArgValue;
Justin Bogner5aaf2e72014-06-26 20:59:36 +00003483
Hans Wennborgf1a74252013-09-10 20:18:04 +00003484 if (ArgValue.empty()) {
3485 // If the argument is empty, output to BaseName in the current dir.
3486 Filename = BaseName;
3487 } else if (llvm::sys::path::is_separator(Filename.back())) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00003488 // If the argument is a directory, output to BaseName in that dir.
3489 llvm::sys::path::append(Filename, BaseName);
3490 }
3491
3492 if (!llvm::sys::path::has_extension(ArgValue)) {
3493 // If the argument didn't provide an extension, then set it.
3494 const char *Extension = types::getTypeTempSuffix(FileType, true);
Hans Wennborgf1a74252013-09-10 20:18:04 +00003495
3496 if (FileType == types::TY_Image &&
3497 Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
3498 // The output file is a dll.
3499 Extension = "dll";
3500 }
3501
Hans Wennborg207fcf02013-08-12 21:56:42 +00003502 llvm::sys::path::replace_extension(Filename, Extension);
3503 }
3504
3505 return Args.MakeArgString(Filename.c_str());
3506}
3507
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003508const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003509 const char *BaseInput,
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003510 StringRef BoundArch, bool AtTopLevel,
Samuel Antaod06239d2016-07-15 23:13:27 +00003511 bool MultipleArchs,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003512 StringRef OffloadingPrefix) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00003513 llvm::PrettyStackTraceString CrashInfo("Computing output path");
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003514 // Output to a user requested destination?
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003515 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003516 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
Chad Rosier633dcdc2013-01-24 19:14:47 +00003517 return C.addResultFile(FinalOutput->getValue(), &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003518 }
3519
Hans Wennborge0053472013-12-20 18:40:46 +00003520 // For /P, preprocess to file named after BaseInput.
3521 if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
3522 assert(AtTopLevel && isa<PreprocessJobAction>(JA));
3523 StringRef BaseName = llvm::sys::path::filename(BaseInput);
Hans Wennborg04c764f2014-06-17 00:19:12 +00003524 StringRef NameArg;
Greg Bedwell065f70a2015-06-09 10:24:06 +00003525 if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
Hans Wennborg04c764f2014-06-17 00:19:12 +00003526 NameArg = A->getValue();
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003527 return C.addResultFile(
3528 MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
3529 &JA);
Hans Wennborge0053472013-12-20 18:40:46 +00003530 }
3531
Nick Lewycky6e1ce292010-09-24 00:46:53 +00003532 // Default to writing to stdout?
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00003533 if (AtTopLevel && !CCGenDiagnostics &&
3534 (isa<PreprocessJobAction>(JA) || JA.getType() == types::TY_ModuleFile))
Nick Lewycky6e1ce292010-09-24 00:46:53 +00003535 return "-";
3536
Hans Wennborg2c21f742013-10-17 16:16:23 +00003537 // Is this the assembly listing for /FA?
3538 if (JA.getType() == types::TY_PP_Asm &&
3539 (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
3540 C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
3541 // Use /Fa and the input filename to determine the asm file name.
3542 StringRef BaseName = llvm::sys::path::filename(BaseInput);
3543 StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003544 return C.addResultFile(
3545 MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
3546 &JA);
Hans Wennborg2c21f742013-10-17 16:16:23 +00003547 }
3548
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003549 // Output to a temporary file?
Reid Kleckner68eb60b2015-02-02 22:41:48 +00003550 if ((!AtTopLevel && !isSaveTempsEnabled() &&
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003551 !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
Chad Rosierbe10f982011-08-02 17:58:04 +00003552 CCGenDiagnostics) {
Chad Rosier97c37372011-08-26 22:27:02 +00003553 StringRef Name = llvm::sys::path::filename(BaseInput);
3554 std::pair<StringRef, StringRef> Split = Name.split('.');
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003555 std::string TmpName = GetTemporaryPath(
3556 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00003557 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003558 }
3559
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003560 SmallString<128> BasePath(BaseInput);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003561 StringRef BaseName;
Daniel Dunbar67fea712011-03-25 18:16:51 +00003562
3563 // Dsymutil actions should use the full path.
Eric Christopher551ef452011-08-23 17:56:55 +00003564 if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
Daniel Dunbar67fea712011-03-25 18:16:51 +00003565 BaseName = BasePath;
3566 else
3567 BaseName = llvm::sys::path::filename(BasePath);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003568
3569 // Determine what the derived output name should be.
3570 const char *NamedOutput;
Hans Wennborg2b89a262013-08-06 22:11:28 +00003571
Hans Wennborg625fba82016-10-04 21:01:04 +00003572 if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) &&
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00003573 C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
3574 // The /Fo or /o flag decides the object filename.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003575 StringRef Val =
3576 C.getArgs()
3577 .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
3578 ->getValue();
3579 NamedOutput =
3580 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
Hans Wennborg207fcf02013-08-12 21:56:42 +00003581 } else if (JA.getType() == types::TY_Image &&
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003582 C.getArgs().hasArg(options::OPT__SLASH_Fe,
3583 options::OPT__SLASH_o)) {
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00003584 // The /Fe or /o flag names the linked file.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003585 StringRef Val =
3586 C.getArgs()
3587 .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
3588 ->getValue();
3589 NamedOutput =
3590 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
Hans Wennborgf1a74252013-09-10 20:18:04 +00003591 } else if (JA.getType() == types::TY_Image) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00003592 if (IsCLMode()) {
3593 // clang-cl uses BaseName for the executable name.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003594 NamedOutput =
3595 MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
Samuel Antao59efaed2016-10-27 17:31:22 +00003596 } else {
Hans Wennborga7707222015-01-09 17:38:53 +00003597 SmallString<128> Output(getDefaultImageName());
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003598 Output += OffloadingPrefix;
Samuel Antao59efaed2016-10-27 17:31:22 +00003599 if (MultipleArchs && !BoundArch.empty()) {
3600 Output += "-";
3601 Output.append(BoundArch);
3602 }
Chad Rosier35767232013-04-30 22:01:21 +00003603 NamedOutput = C.getArgs().MakeArgString(Output.c_str());
Nico Weber2ca4be92016-03-01 23:16:44 +00003604 }
3605 } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00003606 NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName));
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003607 } else {
Hans Wennborg0a096a02013-09-05 17:05:56 +00003608 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003609 assert(Suffix && "All types used for output should have a suffix.");
3610
3611 std::string::size_type End = std::string::npos;
3612 if (!types::appendSuffixForType(JA.getType()))
3613 End = BaseName.rfind('.');
Chad Rosier35767232013-04-30 22:01:21 +00003614 SmallString<128> Suffixed(BaseName.substr(0, End));
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003615 Suffixed += OffloadingPrefix;
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003616 if (MultipleArchs && !BoundArch.empty()) {
Chad Rosier35767232013-04-30 22:01:21 +00003617 Suffixed += "-";
3618 Suffixed.append(BoundArch);
3619 }
Bob Wilson23a55f12014-12-21 07:00:00 +00003620 // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
3621 // the unoptimized bitcode so that it does not get overwritten by the ".bc"
3622 // optimized bitcode output.
3623 if (!AtTopLevel && C.getArgs().hasArg(options::OPT_emit_llvm) &&
3624 JA.getType() == types::TY_LLVM_BC)
3625 Suffixed += ".tmp";
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003626 Suffixed += '.';
3627 Suffixed += Suffix;
3628 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
3629 }
3630
Reid Kleckner68eb60b2015-02-02 22:41:48 +00003631 // Prepend object file path if -save-temps=obj
3632 if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
3633 JA.getType() != types::TY_PCH) {
3634 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
3635 SmallString<128> TempPath(FinalOutput->getValue());
3636 llvm::sys::path::remove_filename(TempPath);
3637 StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
3638 llvm::sys::path::append(TempPath, OutputFileName);
3639 NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
3640 }
3641
Chad Rosier62135492012-07-09 17:31:28 +00003642 // If we're saving temps and the temp file conflicts with the input file,
Chad Rosier5b58af02012-04-20 20:05:08 +00003643 // then avoid overwriting input file.
Reid Kleckner68eb60b2015-02-02 22:41:48 +00003644 if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
Chad Rosier5b58af02012-04-20 20:05:08 +00003645 bool SameFile = false;
3646 SmallString<256> Result;
3647 llvm::sys::fs::current_path(Result);
3648 llvm::sys::path::append(Result, BaseName);
3649 llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
3650 // Must share the same path to conflict.
3651 if (SameFile) {
3652 StringRef Name = llvm::sys::path::filename(BaseInput);
3653 std::pair<StringRef, StringRef> Split = Name.split('.');
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003654 std::string TmpName = GetTemporaryPath(
3655 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00003656 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
Chad Rosier5b58af02012-04-20 20:05:08 +00003657 }
Chad Rosierf8412cd2011-07-15 21:54:29 +00003658 }
3659
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003660 // As an annoying special case, PCH generation doesn't strip the pathname.
Nico Weber8ab92192016-03-02 23:29:29 +00003661 if (JA.getType() == types::TY_PCH && !IsCLMode()) {
Michael J. Spencere1696752010-12-18 00:19:12 +00003662 llvm::sys::path::remove_filename(BasePath);
3663 if (BasePath.empty())
Daniel Dunbare6c83192009-03-18 09:58:30 +00003664 BasePath = NamedOutput;
3665 else
Michael J. Spencere1696752010-12-18 00:19:12 +00003666 llvm::sys::path::append(BasePath, NamedOutput);
Chad Rosier633dcdc2013-01-24 19:14:47 +00003667 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003668 } else {
Chad Rosier633dcdc2013-01-24 19:14:47 +00003669 return C.addResultFile(NamedOutput, &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003670 }
3671}
3672
Mehdi Amini12011172016-10-06 05:11:48 +00003673std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const {
Chandler Carruth84559242010-03-22 01:52:07 +00003674 // Respect a limited subset of the '-Bprefix' functionality in GCC by
Logan Chiencd679fd2012-10-04 08:08:56 +00003675 // attempting to use this prefix when looking for file paths.
Douglas Katzman26eabf62015-06-24 15:10:30 +00003676 for (const std::string &Dir : PrefixDirs) {
Joerg Sonnenberger6165ab12011-03-21 13:51:29 +00003677 if (Dir.empty())
3678 continue;
Douglas Katzman26eabf62015-06-24 15:10:30 +00003679 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
Rafael Espindola609a6642013-06-24 18:33:43 +00003680 llvm::sys::path::append(P, Name);
3681 if (llvm::sys::fs::exists(Twine(P)))
Chandler Carruth84559242010-03-22 01:52:07 +00003682 return P.str();
3683 }
3684
Rafael Espindola609a6642013-06-24 18:33:43 +00003685 SmallString<128> P(ResourceDir);
3686 llvm::sys::path::append(P, Name);
3687 if (llvm::sys::fs::exists(Twine(P)))
Peter Collingbournefa9771f2011-09-06 02:08:31 +00003688 return P.str();
3689
Douglas Katzman26eabf62015-06-24 15:10:30 +00003690 for (const std::string &Dir : TC.getFilePaths()) {
Joerg Sonnenberger6165ab12011-03-21 13:51:29 +00003691 if (Dir.empty())
3692 continue;
Douglas Katzman26eabf62015-06-24 15:10:30 +00003693 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
Rafael Espindola609a6642013-06-24 18:33:43 +00003694 llvm::sys::path::append(P, Name);
3695 if (llvm::sys::fs::exists(Twine(P)))
Daniel Dunbar1ce81532009-09-09 22:33:00 +00003696 return P.str();
Daniel Dunbar68b01a02009-03-18 20:26:19 +00003697 }
3698
Daniel Dunbar1ce81532009-09-09 22:33:00 +00003699 return Name;
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00003700}
3701
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003702void Driver::generatePrefixedToolNames(
Mehdi Amini12011172016-10-06 05:11:48 +00003703 StringRef Tool, const ToolChain &TC,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003704 SmallVectorImpl<std::string> &Names) const {
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00003705 // FIXME: Needs a better variable than DefaultTargetTriple
Mehdi Amini12011172016-10-06 05:11:48 +00003706 Names.emplace_back((DefaultTargetTriple + "-" + Tool).str());
Benjamin Kramer3204b152015-05-29 19:42:19 +00003707 Names.emplace_back(Tool);
Vasileios Kalintirisc744e122015-11-12 15:26:54 +00003708
3709 // Allow the discovery of tools prefixed with LLVM's default target triple.
3710 std::string LLVMDefaultTargetTriple = llvm::sys::getDefaultTargetTriple();
3711 if (LLVMDefaultTargetTriple != DefaultTargetTriple)
Mehdi Amini12011172016-10-06 05:11:48 +00003712 Names.emplace_back((LLVMDefaultTargetTriple + "-" + Tool).str());
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00003713}
3714
Benjamin Kramer7111b912014-11-04 20:26:01 +00003715static bool ScanDirForExecutable(SmallString<128> &Dir,
3716 ArrayRef<std::string> Names) {
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00003717 for (const auto &Name : Names) {
3718 llvm::sys::path::append(Dir, Name);
3719 if (llvm::sys::fs::can_execute(Twine(Dir)))
3720 return true;
3721 llvm::sys::path::remove_filename(Dir);
3722 }
3723 return false;
3724}
3725
Mehdi Amini12011172016-10-06 05:11:48 +00003726std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const {
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00003727 SmallVector<std::string, 2> TargetSpecificExecutables;
3728 generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
3729
Chandler Carruth84559242010-03-22 01:52:07 +00003730 // Respect a limited subset of the '-Bprefix' functionality in GCC by
Logan Chiencd679fd2012-10-04 08:08:56 +00003731 // attempting to use this prefix when looking for program paths.
Saleem Abdulrasool23d99b12014-09-16 03:48:32 +00003732 for (const auto &PrefixDir : PrefixDirs) {
3733 if (llvm::sys::fs::is_directory(PrefixDir)) {
3734 SmallString<128> P(PrefixDir);
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00003735 if (ScanDirForExecutable(P, TargetSpecificExecutables))
Rafael Espindola8be5c052013-06-19 13:24:29 +00003736 return P.str();
Simon Atanasyana47ba292012-10-31 14:39:28 +00003737 } else {
Mehdi Amini12011172016-10-06 05:11:48 +00003738 SmallString<128> P((PrefixDir + Name).str());
Rafael Espindola609a6642013-06-24 18:33:43 +00003739 if (llvm::sys::fs::can_execute(Twine(P)))
Rafael Espindola8be5c052013-06-19 13:24:29 +00003740 return P.str();
Simon Atanasyan86bdab72012-10-31 12:01:53 +00003741 }
Chandler Carruth84559242010-03-22 01:52:07 +00003742 }
3743
Daniel Dunbar68b01a02009-03-18 20:26:19 +00003744 const ToolChain::path_list &List = TC.getProgramPaths();
Saleem Abdulrasool23d99b12014-09-16 03:48:32 +00003745 for (const auto &Path : List) {
3746 SmallString<128> P(Path);
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00003747 if (ScanDirForExecutable(P, TargetSpecificExecutables))
Rafael Espindola8be5c052013-06-19 13:24:29 +00003748 return P.str();
Daniel Dunbar68b01a02009-03-18 20:26:19 +00003749 }
3750
Daniel Dunbar76ce7412009-03-23 16:15:50 +00003751 // If all else failed, search the path.
Michael J. Spencerb011d482014-11-07 21:30:32 +00003752 for (const auto &TargetSpecificExecutable : TargetSpecificExecutables)
3753 if (llvm::ErrorOr<std::string> P =
3754 llvm::sys::findProgramByName(TargetSpecificExecutable))
Michael J. Spencer04162ea2014-11-04 01:30:55 +00003755 return *P;
Daniel Dunbar6f668772009-03-18 21:34:08 +00003756
Daniel Dunbar1ce81532009-09-09 22:33:00 +00003757 return Name;
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00003758}
3759
Mehdi Amini12011172016-10-06 05:11:48 +00003760std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const {
Rafael Espindola37d229d2013-06-25 04:26:55 +00003761 SmallString<128> Path;
Rafael Espindolac0809172014-06-12 14:02:15 +00003762 std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
Rafael Espindola37d229d2013-06-25 04:26:55 +00003763 if (EC) {
3764 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
Daniel Dunbare627c1c2009-03-18 19:34:39 +00003765 return "";
3766 }
3767
Rafael Espindola37d229d2013-06-25 04:26:55 +00003768 return Path.str();
Daniel Dunbare627c1c2009-03-18 19:34:39 +00003769}
3770
Nico Weber2ca4be92016-03-01 23:16:44 +00003771std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
3772 SmallString<128> Output;
3773 if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
3774 // FIXME: If anybody needs it, implement this obscure rule:
3775 // "If you specify a directory without a file name, the default file name
3776 // is VCx0.pch., where x is the major version of Visual C++ in use."
3777 Output = FpArg->getValue();
3778
3779 // "If you do not specify an extension as part of the path name, an
3780 // extension of .pch is assumed. "
3781 if (!llvm::sys::path::has_extension(Output))
3782 Output += ".pch";
3783 } else {
3784 Output = BaseName;
3785 llvm::sys::path::replace_extension(Output, ".pch");
3786 }
3787 return Output.str();
3788}
3789
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003790const ToolChain &Driver::getToolChain(const ArgList &Args,
Artem Belevich959e0542015-07-10 19:47:55 +00003791 const llvm::Triple &Target) const {
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003792
David Blaikie6ad71012017-01-13 18:53:43 +00003793 auto &TC = ToolChains[Target.str()];
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003794 if (!TC) {
3795 switch (Target.getOS()) {
Reid Kleckner330fb172016-05-11 16:19:05 +00003796 case llvm::Triple::Haiku:
David Blaikie6ad71012017-01-13 18:53:43 +00003797 TC = llvm::make_unique<toolchains::Haiku>(*this, Target, Args);
Reid Kleckner330fb172016-05-11 16:19:05 +00003798 break;
Ed Schouten4dabea22017-06-25 08:29:09 +00003799 case llvm::Triple::Ananas:
3800 TC = llvm::make_unique<toolchains::Ananas>(*this, Target, Args);
3801 break;
Ed Schouten3c3e58c2015-03-26 11:13:44 +00003802 case llvm::Triple::CloudABI:
David Blaikie6ad71012017-01-13 18:53:43 +00003803 TC = llvm::make_unique<toolchains::CloudABI>(*this, Target, Args);
Ed Schouten3c3e58c2015-03-26 11:13:44 +00003804 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003805 case llvm::Triple::Darwin:
3806 case llvm::Triple::MacOSX:
3807 case llvm::Triple::IOS:
Tim Northover6f3ff222015-10-30 16:30:27 +00003808 case llvm::Triple::TvOS:
3809 case llvm::Triple::WatchOS:
David Blaikie6ad71012017-01-13 18:53:43 +00003810 TC = llvm::make_unique<toolchains::DarwinClang>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003811 break;
3812 case llvm::Triple::DragonFly:
David Blaikie6ad71012017-01-13 18:53:43 +00003813 TC = llvm::make_unique<toolchains::DragonFly>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003814 break;
3815 case llvm::Triple::OpenBSD:
David Blaikie6ad71012017-01-13 18:53:43 +00003816 TC = llvm::make_unique<toolchains::OpenBSD>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003817 break;
Eli Friedman9fa28852012-08-08 23:57:20 +00003818 case llvm::Triple::Bitrig:
David Blaikie6ad71012017-01-13 18:53:43 +00003819 TC = llvm::make_unique<toolchains::Bitrig>(*this, Target, Args);
Eli Friedman9fa28852012-08-08 23:57:20 +00003820 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003821 case llvm::Triple::NetBSD:
David Blaikie6ad71012017-01-13 18:53:43 +00003822 TC = llvm::make_unique<toolchains::NetBSD>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003823 break;
3824 case llvm::Triple::FreeBSD:
David Blaikie6ad71012017-01-13 18:53:43 +00003825 TC = llvm::make_unique<toolchains::FreeBSD>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003826 break;
3827 case llvm::Triple::Minix:
David Blaikie6ad71012017-01-13 18:53:43 +00003828 TC = llvm::make_unique<toolchains::Minix>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003829 break;
3830 case llvm::Triple::Linux:
Andrey Turetskiy4798eb62016-06-16 10:36:09 +00003831 case llvm::Triple::ELFIAMCU:
Chandler Carruthcf705b22012-01-25 21:03:58 +00003832 if (Target.getArch() == llvm::Triple::hexagon)
David Blaikie6ad71012017-01-13 18:53:43 +00003833 TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
3834 Args);
Vasileios Kalintirisc744e122015-11-12 15:26:54 +00003835 else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
3836 !Target.hasEnvironment())
David Blaikie6ad71012017-01-13 18:53:43 +00003837 TC = llvm::make_unique<toolchains::MipsLLVMToolChain>(*this, Target,
3838 Args);
Chandler Carruthcf705b22012-01-25 21:03:58 +00003839 else
David Blaikie6ad71012017-01-13 18:53:43 +00003840 TC = llvm::make_unique<toolchains::Linux>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003841 break;
Derek Schuff6ab52fa2015-03-30 20:31:33 +00003842 case llvm::Triple::NaCl:
David Blaikie6ad71012017-01-13 18:53:43 +00003843 TC = llvm::make_unique<toolchains::NaClToolChain>(*this, Target, Args);
Derek Schuff6ab52fa2015-03-30 20:31:33 +00003844 break;
Petr Hosek62e1d232016-10-06 06:08:09 +00003845 case llvm::Triple::Fuchsia:
David Blaikie6ad71012017-01-13 18:53:43 +00003846 TC = llvm::make_unique<toolchains::Fuchsia>(*this, Target, Args);
Petr Hosek62e1d232016-10-06 06:08:09 +00003847 break;
David Chisnallf571cde2012-02-15 13:39:01 +00003848 case llvm::Triple::Solaris:
David Blaikie6ad71012017-01-13 18:53:43 +00003849 TC = llvm::make_unique<toolchains::Solaris>(*this, Target, Args);
David Chisnallf571cde2012-02-15 13:39:01 +00003850 break;
Tom Stellard8fa33092015-07-18 01:49:05 +00003851 case llvm::Triple::AMDHSA:
David Blaikie6ad71012017-01-13 18:53:43 +00003852 TC = llvm::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args);
Tom Stellard8fa33092015-07-18 01:49:05 +00003853 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003854 case llvm::Triple::Win32:
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00003855 switch (Target.getEnvironment()) {
3856 default:
3857 if (Target.isOSBinFormatELF())
David Blaikie6ad71012017-01-13 18:53:43 +00003858 TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00003859 else if (Target.isOSBinFormatMachO())
David Blaikie6ad71012017-01-13 18:53:43 +00003860 TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00003861 else
David Blaikie6ad71012017-01-13 18:53:43 +00003862 TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00003863 break;
3864 case llvm::Triple::GNU:
David Blaikie6ad71012017-01-13 18:53:43 +00003865 TC = llvm::make_unique<toolchains::MinGW>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00003866 break;
Saleem Abdulrasool543a78b2014-10-24 03:13:37 +00003867 case llvm::Triple::Itanium:
David Blaikie6ad71012017-01-13 18:53:43 +00003868 TC = llvm::make_unique<toolchains::CrossWindowsToolChain>(*this, Target,
3869 Args);
Saleem Abdulrasool543a78b2014-10-24 03:13:37 +00003870 break;
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00003871 case llvm::Triple::MSVC:
3872 case llvm::Triple::UnknownEnvironment:
David Blaikie6ad71012017-01-13 18:53:43 +00003873 TC = llvm::make_unique<toolchains::MSVCToolChain>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00003874 break;
3875 }
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003876 break;
Filipe Cabecinhasc888e192015-10-14 12:25:43 +00003877 case llvm::Triple::PS4:
David Blaikie6ad71012017-01-13 18:53:43 +00003878 TC = llvm::make_unique<toolchains::PS4CPU>(*this, Target, Args);
Filipe Cabecinhasc888e192015-10-14 12:25:43 +00003879 break;
David L Kreitzerd397ea42016-10-14 20:44:33 +00003880 case llvm::Triple::Contiki:
David Blaikie6ad71012017-01-13 18:53:43 +00003881 TC = llvm::make_unique<toolchains::Contiki>(*this, Target, Args);
David L Kreitzerd397ea42016-10-14 20:44:33 +00003882 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003883 default:
Douglas Katzman9f5e70e2015-05-26 18:01:33 +00003884 // Of these targets, Hexagon is the only one that might have
3885 // an OS of Linux, in which case it got handled above already.
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003886 switch (Target.getArch()) {
3887 case llvm::Triple::tce:
David Blaikie6ad71012017-01-13 18:53:43 +00003888 TC = llvm::make_unique<toolchains::TCEToolChain>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003889 break;
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00003890 case llvm::Triple::tcele:
David Blaikie6ad71012017-01-13 18:53:43 +00003891 TC = llvm::make_unique<toolchains::TCELEToolChain>(*this, Target, Args);
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00003892 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003893 case llvm::Triple::hexagon:
David Blaikie6ad71012017-01-13 18:53:43 +00003894 TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
3895 Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003896 break;
Jacques Pienaard964cc22016-03-28 21:02:54 +00003897 case llvm::Triple::lanai:
David Blaikie6ad71012017-01-13 18:53:43 +00003898 TC = llvm::make_unique<toolchains::LanaiToolChain>(*this, Target, Args);
Jacques Pienaard964cc22016-03-28 21:02:54 +00003899 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003900 case llvm::Triple::xcore:
David Blaikie6ad71012017-01-13 18:53:43 +00003901 TC = llvm::make_unique<toolchains::XCoreToolChain>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003902 break;
Dan Gohmanc2853072015-09-03 22:51:53 +00003903 case llvm::Triple::wasm32:
3904 case llvm::Triple::wasm64:
David Blaikie6ad71012017-01-13 18:53:43 +00003905 TC = llvm::make_unique<toolchains::WebAssembly>(*this, Target, Args);
Dan Gohmanc2853072015-09-03 22:51:53 +00003906 break;
Dylan McKay924fa3a2017-01-05 05:20:27 +00003907 case llvm::Triple::avr:
David Blaikie6ad71012017-01-13 18:53:43 +00003908 TC = llvm::make_unique<toolchains::AVRToolChain>(*this, Target, Args);
Dylan McKay924fa3a2017-01-05 05:20:27 +00003909 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003910 default:
Douglas Katzmand6e597c2015-09-17 19:56:40 +00003911 if (Target.getVendor() == llvm::Triple::Myriad)
David Blaikie6ad71012017-01-13 18:53:43 +00003912 TC = llvm::make_unique<toolchains::MyriadToolChain>(*this, Target,
3913 Args);
Jonathan Roelofs901c7762017-05-25 15:42:13 +00003914 else if (toolchains::BareMetal::handlesTarget(Target))
3915 TC = llvm::make_unique<toolchains::BareMetal>(*this, Target, Args);
Douglas Katzmand6e597c2015-09-17 19:56:40 +00003916 else if (Target.isOSBinFormatELF())
David Blaikie6ad71012017-01-13 18:53:43 +00003917 TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003918 else if (Target.isOSBinFormatMachO())
David Blaikie6ad71012017-01-13 18:53:43 +00003919 TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003920 else
David Blaikie6ad71012017-01-13 18:53:43 +00003921 TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003922 }
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003923 }
3924 }
Justin Lebar66c4fd72016-11-18 00:41:22 +00003925
3926 // Intentionally omitted from the switch above: llvm::Triple::CUDA. CUDA
3927 // compiles always need two toolchains, the CUDA toolchain and the host
3928 // toolchain. So the only valid way to create a CUDA toolchain is via
3929 // CreateOffloadingDeviceToolChains.
3930
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003931 return *TC;
Daniel Dunbar4dff6a42009-03-10 23:41:59 +00003932}
Daniel Dunbar8fa879d2009-03-24 18:57:02 +00003933
Rafael Espindola2f69d402013-03-18 15:33:26 +00003934bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
Douglas Katzman00249092015-06-12 15:45:21 +00003935 // Say "no" if there is not exactly one input of a type clang understands.
Nico Weber5a459f82016-02-23 19:30:43 +00003936 if (JA.size() != 1 ||
3937 !types::isAcceptedByClang((*JA.input_begin())->getType()))
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00003938 return false;
3939
Douglas Katzman00249092015-06-12 15:45:21 +00003940 // And say "no" if this is not a kind of action clang understands.
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00003941 if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
Bob Wilson23a55f12014-12-21 07:00:00 +00003942 !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00003943 return false;
3944
3945 return true;
3946}
3947
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003948/// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
3949/// grouped values as integers. Numbers which are not provided are set to 0.
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003950///
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003951/// \return True if the entire string was parsed (9.2), or all groups were
3952/// parsed (10.3.5extrastuff).
Mehdi Amini12011172016-10-06 05:11:48 +00003953bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
3954 unsigned &Micro, bool &HadExtra) {
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003955 HadExtra = false;
3956
3957 Major = Minor = Micro = 0;
Mehdi Amini12011172016-10-06 05:11:48 +00003958 if (Str.empty())
Bob Wilson433cb312015-04-07 01:03:35 +00003959 return false;
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003960
Mehdi Amini12011172016-10-06 05:11:48 +00003961 if (Str.consumeInteger(10, Major))
3962 return false;
3963 if (Str.empty())
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003964 return true;
Mehdi Amini12011172016-10-06 05:11:48 +00003965 if (Str[0] != '.')
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003966 return false;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003967
Mehdi Amini12011172016-10-06 05:11:48 +00003968 Str = Str.drop_front(1);
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003969
Mehdi Amini12011172016-10-06 05:11:48 +00003970 if (Str.consumeInteger(10, Minor))
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003971 return false;
Mehdi Amini12011172016-10-06 05:11:48 +00003972 if (Str.empty())
3973 return true;
3974 if (Str[0] != '.')
3975 return false;
3976 Str = Str.drop_front(1);
3977
3978 if (Str.consumeInteger(10, Micro))
3979 return false;
3980 if (!Str.empty())
3981 HadExtra = true;
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003982 return true;
3983}
Hans Wennborg6ddc6902013-07-27 00:23:45 +00003984
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00003985/// Parse digits from a string \p Str and fulfill \p Digits with
3986/// the parsed numbers. This method assumes that the max number of
3987/// digits to look for is equal to Digits.size().
3988///
3989/// \return True if the entire string was parsed and there are
3990/// no extra characters remaining at the end.
Mehdi Amini12011172016-10-06 05:11:48 +00003991bool Driver::GetReleaseVersion(StringRef Str,
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00003992 MutableArrayRef<unsigned> Digits) {
Mehdi Amini12011172016-10-06 05:11:48 +00003993 if (Str.empty())
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00003994 return false;
3995
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00003996 unsigned CurDigit = 0;
3997 while (CurDigit < Digits.size()) {
Mehdi Amini12011172016-10-06 05:11:48 +00003998 unsigned Digit;
3999 if (Str.consumeInteger(10, Digit))
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004000 return false;
Mehdi Amini12011172016-10-06 05:11:48 +00004001 Digits[CurDigit] = Digit;
4002 if (Str.empty())
4003 return true;
4004 if (Str[0] != '.')
4005 return false;
4006 Str = Str.drop_front(1);
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004007 CurDigit++;
4008 }
4009
4010 // More digits than requested, bail out...
4011 return false;
4012}
4013
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004014std::pair<unsigned, unsigned> Driver::getIncludeExcludeOptionFlagMasks() const {
4015 unsigned IncludedFlagsBitmask = 0;
Rafael Espindolacc707bc2013-09-25 15:54:41 +00004016 unsigned ExcludedFlagsBitmask = options::NoDriverOption;
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004017
4018 if (Mode == CLMode) {
Hans Wennborg19076102013-07-31 20:51:53 +00004019 // Include CL and Core options.
4020 IncludedFlagsBitmask |= options::CLOption;
4021 IncludedFlagsBitmask |= options::CoreOption;
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004022 } else {
4023 ExcludedFlagsBitmask |= options::CLOption;
4024 }
4025
4026 return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
4027}
Benjamin Kramerab88f622014-03-25 18:02:07 +00004028
Douglas Katzmanf08fadf2015-06-04 14:40:44 +00004029bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
Benjamin Kramerab88f622014-03-25 18:02:07 +00004030 return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);
4031}