blob: d07ac96a3108fc8780a6ef07b22afd6acf64df02 [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"
14#include "ToolChains/Bitrig.h"
15#include "ToolChains/Clang.h"
16#include "ToolChains/CloudABI.h"
17#include "ToolChains/Contiki.h"
18#include "ToolChains/CrossWindows.h"
19#include "ToolChains/Cuda.h"
20#include "ToolChains/Darwin.h"
21#include "ToolChains/DragonFly.h"
22#include "ToolChains/FreeBSD.h"
23#include "ToolChains/Fuchsia.h"
24#include "ToolChains/Gnu.h"
Jonathan Roelofs901c7762017-05-25 15:42:13 +000025#include "ToolChains/BareMetal.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000026#include "ToolChains/Haiku.h"
27#include "ToolChains/Hexagon.h"
28#include "ToolChains/Lanai.h"
29#include "ToolChains/Linux.h"
30#include "ToolChains/MinGW.h"
31#include "ToolChains/Minix.h"
Konstantin Zhuravlyove37b32c2017-03-08 22:36:04 +000032#include "ToolChains/MipsLinux.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000033#include "ToolChains/MSVC.h"
34#include "ToolChains/Myriad.h"
35#include "ToolChains/NaCl.h"
36#include "ToolChains/NetBSD.h"
37#include "ToolChains/OpenBSD.h"
38#include "ToolChains/PS4CPU.h"
39#include "ToolChains/Solaris.h"
40#include "ToolChains/TCE.h"
41#include "ToolChains/WebAssembly.h"
42#include "ToolChains/XCore.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000043#include "clang/Basic/Version.h"
Benjamin Kramerd45b2052015-10-07 15:48:01 +000044#include "clang/Basic/VirtualFileSystem.h"
Alp Toker1d257e12014-06-04 03:28:55 +000045#include "clang/Config/config.h"
Daniel Dunbar1688f1a2009-03-12 07:58:46 +000046#include "clang/Driver/Action.h"
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000047#include "clang/Driver/Compilation.h"
Daniel Dunbarc0b3e952009-03-12 08:55:43 +000048#include "clang/Driver/DriverDiagnostic.h"
Daniel Dunbare75d8342009-03-16 06:56:51 +000049#include "clang/Driver/Job.h"
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000050#include "clang/Driver/Options.h"
Peter Collingbournea4ccff32015-02-20 20:30:56 +000051#include "clang/Driver/SanitizerArgs.h"
Daniel Dunbare75d8342009-03-16 06:56:51 +000052#include "clang/Driver/Tool.h"
53#include "clang/Driver/ToolChain.h"
Chris Lattnerce6c42f2011-03-23 04:04:01 +000054#include "llvm/ADT/ArrayRef.h"
Hans Wennborg6ddc6902013-07-27 00:23:45 +000055#include "llvm/ADT/STLExtras.h"
Justin Lebar62907612016-07-06 21:21:39 +000056#include "llvm/ADT/SmallSet.h"
Hans Wennborg23d26a32014-06-18 17:21:50 +000057#include "llvm/ADT/StringExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000058#include "llvm/ADT/StringSet.h"
Hans Wennborg70850d82013-07-18 20:29:38 +000059#include "llvm/ADT/StringSwitch.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000060#include "llvm/Option/Arg.h"
61#include "llvm/Option/ArgList.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000062#include "llvm/Option/OptSpecifier.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000063#include "llvm/Option/OptTable.h"
64#include "llvm/Option/Option.h"
David Blaikie79000202011-09-23 05:57:42 +000065#include "llvm/Support/ErrorHandling.h"
Michael J. Spencerf28df4c2010-12-17 21:22:22 +000066#include "llvm/Support/FileSystem.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000067#include "llvm/Support/Path.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000068#include "llvm/Support/PrettyStackTrace.h"
Hans Wennborg23d26a32014-06-18 17:21:50 +000069#include "llvm/Support/Process.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000070#include "llvm/Support/Program.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000071#include "llvm/Support/raw_ostream.h"
Dylan Noblesmith4f4e7452012-02-02 00:40:14 +000072#include <map>
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000073#include <memory>
Benjamin Kramercfeacf52016-05-27 14:27:13 +000074#include <utility>
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +000075#if LLVM_ON_UNIX
76#include <unistd.h> // getpid
77#endif
Dylan Noblesmith86780e92012-02-01 14:25:28 +000078
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000079using namespace clang::driver;
Chris Lattnerada1c912009-03-26 05:56:24 +000080using namespace clang;
Reid Kleckner898229a2013-06-14 17:17:23 +000081using namespace llvm::opt;
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000082
Reid Kleckner68eb60b2015-02-02 22:41:48 +000083Driver::Driver(StringRef ClangExecutable, StringRef DefaultTargetTriple,
Benjamin Kramerd45b2052015-10-07 15:48:01 +000084 DiagnosticsEngine &Diags,
85 IntrusiveRefCntPtr<vfs::FileSystem> VFS)
Benjamin Kramercfeacf52016-05-27 14:27:13 +000086 : Opts(createDriverOptTable()), Diags(Diags), VFS(std::move(VFS)),
87 Mode(GCCMode), SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
88 LTOMode(LTOK_None), ClangExecutable(ClangExecutable),
Reid Kleckner68eb60b2015-02-02 22:41:48 +000089 SysRoot(DEFAULT_SYSROOT), UseStdLib(true),
Reid Kleckner68eb60b2015-02-02 22:41:48 +000090 DriverTitle("clang LLVM compiler"), CCPrintOptionsFilename(nullptr),
91 CCPrintHeadersFilename(nullptr), CCLogDiagnosticsFilename(nullptr),
92 CCCPrintBindings(false), CCPrintHeaders(false), CCLogDiagnostics(false),
Vedant Kumarf2030b92016-07-18 19:56:33 +000093 CCGenDiagnostics(false), DefaultTargetTriple(DefaultTargetTriple),
94 CCCGenericGCCName(""), CheckInputsExist(true), CCCUsePCH(true),
Bruno Cardoso Lopes52dfe712017-04-12 21:46:20 +000095 GenReproducer(false), SuppressMissingInputWarning(false) {
Daniel Dunbar3f3e2cd2010-01-20 02:35:16 +000096
Benjamin Kramerd45b2052015-10-07 15:48:01 +000097 // Provide a sane fallback if no VFS is specified.
98 if (!this->VFS)
99 this->VFS = vfs::getRealFileSystem();
100
Sumanth Gundapaneni3a1592942015-03-03 20:43:12 +0000101 Name = llvm::sys::path::filename(ClangExecutable);
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000102 Dir = llvm::sys::path::parent_path(ClangExecutable);
Benjamin Kramerf420dda2015-10-13 15:19:32 +0000103 InstalledDir = Dir; // Provide a sensible default installed dir.
Bob Wilsona20a1da2013-03-23 05:17:59 +0000104
105 // Compute the path to the resource directory.
106 StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
107 SmallString<128> P(Dir);
Chandler Carruthfd3cc702014-12-29 12:09:08 +0000108 if (ClangResourceDir != "") {
Bob Wilsona20a1da2013-03-23 05:17:59 +0000109 llvm::sys::path::append(P, ClangResourceDir);
Chandler Carruthfd3cc702014-12-29 12:09:08 +0000110 } else {
111 StringRef ClangLibdirSuffix(CLANG_LIBDIR_SUFFIX);
Argyrios Kyrtzidisbcae0472017-02-25 18:14:35 +0000112 P = llvm::sys::path::parent_path(Dir);
113 llvm::sys::path::append(P, Twine("lib") + ClangLibdirSuffix, "clang",
Chandler Carruthfd3cc702014-12-29 12:09:08 +0000114 CLANG_VERSION_STRING);
115 }
Bob Wilsona20a1da2013-03-23 05:17:59 +0000116 ResourceDir = P.str();
Daniel Dunbar544ecd12009-03-02 19:59:07 +0000117}
118
Zachary Turneraff19c32016-08-12 17:47:52 +0000119void Driver::ParseDriverMode(StringRef ProgramName,
120 ArrayRef<const char *> Args) {
121 auto Default = ToolChain::getTargetAndModeFromProgramName(ProgramName);
122 StringRef DefaultMode(Default.second);
123 setDriverModeFromOption(DefaultMode);
Hans Wennborg70850d82013-07-18 20:29:38 +0000124
Douglas Katzman6bbffc42015-06-25 18:51:37 +0000125 for (const char *ArgPtr : Args) {
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000126 // Ingore nullptrs, they are response file's EOL markers
Douglas Katzman6bbffc42015-06-25 18:51:37 +0000127 if (ArgPtr == nullptr)
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000128 continue;
Douglas Katzman6bbffc42015-06-25 18:51:37 +0000129 const StringRef Arg = ArgPtr;
Zachary Turneraff19c32016-08-12 17:47:52 +0000130 setDriverModeFromOption(Arg);
Hans Wennborg70850d82013-07-18 20:29:38 +0000131 }
132}
133
Zachary Turneraff19c32016-08-12 17:47:52 +0000134void Driver::setDriverModeFromOption(StringRef Opt) {
135 const std::string OptName =
136 getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
137 if (!Opt.startswith(OptName))
138 return;
139 StringRef Value = Opt.drop_front(OptName.size());
140
141 const unsigned M = llvm::StringSwitch<unsigned>(Value)
142 .Case("gcc", GCCMode)
143 .Case("g++", GXXMode)
144 .Case("cpp", CPPMode)
145 .Case("cl", CLMode)
146 .Default(~0U);
147
148 if (M != ~0U)
149 Mode = static_cast<DriverMode>(M);
150 else
151 Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
152}
153
David Blaikie69a1d8c2015-06-22 22:07:27 +0000154InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings) {
Daniel Dunbar2608c542009-03-18 01:38:48 +0000155 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
Hans Wennborg6ddc6902013-07-27 00:23:45 +0000156
157 unsigned IncludedFlagsBitmask;
158 unsigned ExcludedFlagsBitmask;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000159 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000160 getIncludeExcludeOptionFlagMasks();
Hans Wennborg6ddc6902013-07-27 00:23:45 +0000161
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000162 unsigned MissingArgIndex, MissingArgCount;
David Blaikie69a1d8c2015-06-22 22:07:27 +0000163 InputArgList Args =
David Blaikie6d492ad2015-06-21 06:32:36 +0000164 getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
165 IncludedFlagsBitmask, ExcludedFlagsBitmask);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +0000166
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000167 // Check for missing argument error.
168 if (MissingArgCount)
169 Diag(clang::diag::err_drv_missing_argument)
David Blaikie69a1d8c2015-06-22 22:07:27 +0000170 << Args.getArgString(MissingArgIndex) << MissingArgCount;
Daniel Dunbar65229332009-03-13 11:38:42 +0000171
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000172 // Check for unsupported options.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000173 for (const Arg *A : Args) {
Michael J. Spencer66e2b202012-10-19 22:37:06 +0000174 if (A->getOption().hasFlag(options::Unsupported)) {
David Blaikie69a1d8c2015-06-22 22:07:27 +0000175 Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(Args);
Daniel Dunbard8500f32009-03-22 23:26:43 +0000176 continue;
177 }
Chad Rosierce975d92012-02-22 17:55:22 +0000178
179 // Warn about -mcpu= without an argument.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000180 if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
David Blaikie69a1d8c2015-06-22 22:07:27 +0000181 Diag(clang::diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
Chad Rosierce975d92012-02-22 17:55:22 +0000182 }
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000183 }
184
David Blaikie69a1d8c2015-06-22 22:07:27 +0000185 for (const Arg *A : Args.filtered(options::OPT_UNKNOWN))
Ehsan Akhgarid8518332016-01-25 21:14:52 +0000186 Diags.Report(IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl :
187 diag::err_drv_unknown_argument)
188 << A->getAsString(Args);
Rafael Espindola8a2d4962013-09-23 23:55:25 +0000189
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000190 return Args;
191}
192
Chad Rosier7742b5d2011-07-27 23:36:45 +0000193// Determine which compilation mode we are in. We look for options which
194// affect the phase, starting with the earliest phases, and record which
195// option we used to determine the final phase.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000196phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
197 Arg **FinalPhaseArg) const {
Craig Topper92fc2df2014-05-17 16:56:41 +0000198 Arg *PhaseArg = nullptr;
Chad Rosier7742b5d2011-07-27 23:36:45 +0000199 phases::ID FinalPhase;
Eric Christopherf901e852011-08-17 22:59:59 +0000200
Hans Wennborge50cec32014-06-13 20:59:54 +0000201 // -{E,EP,P,M,MM} only run the preprocessor.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000202 if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
Hans Wennborge50cec32014-06-13 20:59:54 +0000203 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
Hans Wennborge0053472013-12-20 18:40:46 +0000204 (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
205 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000206 FinalPhase = phases::Preprocess;
Eric Christopherf901e852011-08-17 22:59:59 +0000207
Richard Smithdd4ad3d2016-08-30 19:06:26 +0000208 // --precompile only runs up to precompilation.
209 } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile))) {
210 FinalPhase = phases::Precompile;
211
Bob Wilson23a55f12014-12-21 07:00:00 +0000212 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
Chad Rosier7742b5d2011-07-27 23:36:45 +0000213 } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000214 (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
Ben Langmuir2cb4a782014-02-05 22:21:15 +0000215 (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
Chad Rosier7742b5d2011-07-27 23:36:45 +0000216 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
Fariborz Jahanian73223bb2012-04-02 15:59:19 +0000217 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
Ted Kremenekf7639e12012-03-06 20:06:33 +0000218 (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
Chad Rosier7742b5d2011-07-27 23:36:45 +0000219 (PhaseArg = DAL.getLastArg(options::OPT__analyze,
Chad Rosier1aeb15a2012-03-06 23:14:35 +0000220 options::OPT__analyze_auto)) ||
Bob Wilson23a55f12014-12-21 07:00:00 +0000221 (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000222 FinalPhase = phases::Compile;
223
Bob Wilson23a55f12014-12-21 07:00:00 +0000224 // -S only runs up to the backend.
225 } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
226 FinalPhase = phases::Backend;
227
Artem Belevich4242f412015-07-28 21:01:21 +0000228 // -c compilation only runs up to the assembler.
229 } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000230 FinalPhase = phases::Assemble;
231
232 // Otherwise do everything.
233 } else
234 FinalPhase = phases::Link;
235
236 if (FinalPhaseArg)
237 *FinalPhaseArg = PhaseArg;
238
239 return FinalPhase;
240}
241
David Blaikie0aaa7622017-01-13 17:34:15 +0000242static Arg *MakeInputArg(DerivedArgList &Args, OptTable &Opts,
Hans Wennborged1d0722013-08-13 21:32:29 +0000243 StringRef Value) {
David Blaikie0aaa7622017-01-13 17:34:15 +0000244 Arg *A = new Arg(Opts.getOption(options::OPT_INPUT), Value,
Hans Wennborged1d0722013-08-13 21:32:29 +0000245 Args.getBaseArgs().MakeIndex(Value), Value.data());
Hans Wennborg55362852014-05-02 22:55:30 +0000246 Args.AddSynthesizedArg(A);
Hans Wennborged1d0722013-08-13 21:32:29 +0000247 A->claim();
248 return A;
249}
250
Daniel Dunbar775d4062010-06-11 22:00:26 +0000251DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
252 DerivedArgList *DAL = new DerivedArgList(Args);
253
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000254 bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
Nirav Daveb0bb6142015-11-24 16:07:21 +0000255 bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +0000256 for (Arg *A : Args) {
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000257 // Unfortunately, we have to parse some forwarding options (-Xassembler,
258 // -Xlinker, -Xpreprocessor) because we either integrate their functionality
259 // (assembler and preprocessor), or bypass a previous driver ('collect2').
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000260
261 // Rewrite linker options, to replace --no-demangle with a custom internal
262 // option.
263 if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
264 A->getOption().matches(options::OPT_Xlinker)) &&
265 A->containsValue("--no-demangle")) {
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000266 // Add the rewritten no-demangle argument.
267 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
268
269 // Add the remaining values as Xlinker arguments.
Benjamin Kramer72e64312015-09-24 14:48:49 +0000270 for (StringRef Val : A->getValues())
Douglas Katzmana34b7bf2015-06-30 19:32:57 +0000271 if (Val != "--no-demangle")
272 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), Val);
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000273
274 continue;
275 }
276
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000277 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
278 // some build systems. We don't try to be complete here because we don't
279 // care to encourage this usage model.
280 if (A->getOption().matches(options::OPT_Wp_COMMA) &&
Richard Smithbd55daf2012-11-01 04:30:05 +0000281 (A->getValue(0) == StringRef("-MD") ||
282 A->getValue(0) == StringRef("-MMD"))) {
Daniel Dunbar3648ba72010-06-15 20:30:18 +0000283 // Rewrite to -MD/-MMD along with -MF.
Richard Smithbd55daf2012-11-01 04:30:05 +0000284 if (A->getValue(0) == StringRef("-MD"))
Daniel Dunbar3648ba72010-06-15 20:30:18 +0000285 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
286 else
287 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
Michael J. Spencer70d85be2012-11-07 23:37:14 +0000288 if (A->getNumValues() == 2)
289 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
290 A->getValue(1));
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000291 continue;
292 }
293
Shantonu Senafeb03b2010-09-17 18:39:08 +0000294 // Rewrite reserved library names.
295 if (A->getOption().matches(options::OPT_l)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000296 StringRef Value = A->getValue();
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000297
Shantonu Senafeb03b2010-09-17 18:39:08 +0000298 // Rewrite unless -nostdlib is present.
Nirav Daveb0bb6142015-11-24 16:07:21 +0000299 if (!HasNostdlib && !HasNodefaultlib && Value == "stdc++") {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000300 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_stdcxx));
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000301 continue;
302 }
Shantonu Senafeb03b2010-09-17 18:39:08 +0000303
304 // Rewrite unconditionally.
305 if (Value == "cc_kext") {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000306 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_cckext));
Shantonu Senafeb03b2010-09-17 18:39:08 +0000307 continue;
308 }
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000309 }
310
Hans Wennborged1d0722013-08-13 21:32:29 +0000311 // Pick up inputs via the -- option.
312 if (A->getOption().matches(options::OPT__DASH_DASH)) {
313 A->claim();
Benjamin Kramer72e64312015-09-24 14:48:49 +0000314 for (StringRef Val : A->getValues())
David Blaikie0aaa7622017-01-13 17:34:15 +0000315 DAL->append(MakeInputArg(*DAL, *Opts, Val));
Hans Wennborged1d0722013-08-13 21:32:29 +0000316 continue;
317 }
318
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +0000319 DAL->append(A);
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000320 }
Daniel Dunbar775d4062010-06-11 22:00:26 +0000321
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000322 // Enforce -static if -miamcu is present.
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000323 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false))
324 DAL->AddFlagArg(0, Opts->getOption(options::OPT_static));
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000325
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000326// Add a default value of -mlinker-version=, if one was given and the user
327// didn't specify one.
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000328#if defined(HOST_LINK_VERSION)
Tim Northover018578c2015-06-12 19:21:35 +0000329 if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
330 strlen(HOST_LINK_VERSION) > 0) {
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000331 DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
332 HOST_LINK_VERSION);
Daniel Dunbarb613ffc2010-08-17 22:32:45 +0000333 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000334 }
335#endif
336
Daniel Dunbar775d4062010-06-11 22:00:26 +0000337 return DAL;
338}
339
Artem Belevich959e0542015-07-10 19:47:55 +0000340/// \brief Compute target triple from args.
341///
342/// This routine provides the logic to compute a target triple from various
343/// args passed to the driver and the default triple string.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000344static llvm::Triple computeTargetTriple(const Driver &D,
345 StringRef DefaultTargetTriple,
Artem Belevich959e0542015-07-10 19:47:55 +0000346 const ArgList &Args,
347 StringRef DarwinArchName = "") {
348 // FIXME: Already done in Compilation *Driver::BuildCompilation
349 if (const Arg *A = Args.getLastArg(options::OPT_target))
350 DefaultTargetTriple = A->getValue();
351
352 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
353
354 // Handle Apple-specific options available here.
355 if (Target.isOSBinFormatMachO()) {
356 // If an explict Darwin arch name is given, that trumps all.
357 if (!DarwinArchName.empty()) {
358 tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
359 return Target;
360 }
361
362 // Handle the Darwin '-arch' flag.
363 if (Arg *A = Args.getLastArg(options::OPT_arch)) {
364 StringRef ArchName = A->getValue();
365 tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
366 }
367 }
368
369 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
370 // '-mbig-endian'/'-EB'.
371 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
372 options::OPT_mbig_endian)) {
373 if (A->getOption().matches(options::OPT_mlittle_endian)) {
374 llvm::Triple LE = Target.getLittleEndianArchVariant();
375 if (LE.getArch() != llvm::Triple::UnknownArch)
376 Target = std::move(LE);
377 } else {
378 llvm::Triple BE = Target.getBigEndianArchVariant();
379 if (BE.getArch() != llvm::Triple::UnknownArch)
380 Target = std::move(BE);
381 }
382 }
383
384 // Skip further flag support on OSes which don't support '-m32' or '-m64'.
Douglas Katzman15a63ed2015-08-12 18:36:12 +0000385 if (Target.getArch() == llvm::Triple::tce ||
386 Target.getOS() == llvm::Triple::Minix)
Artem Belevich959e0542015-07-10 19:47:55 +0000387 return Target;
388
389 // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000390 Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
391 options::OPT_m32, options::OPT_m16);
392 if (A) {
Artem Belevich959e0542015-07-10 19:47:55 +0000393 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
394
395 if (A->getOption().matches(options::OPT_m64)) {
396 AT = Target.get64BitArchVariant().getArch();
397 if (Target.getEnvironment() == llvm::Triple::GNUX32)
398 Target.setEnvironment(llvm::Triple::GNU);
399 } else if (A->getOption().matches(options::OPT_mx32) &&
400 Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
401 AT = llvm::Triple::x86_64;
402 Target.setEnvironment(llvm::Triple::GNUX32);
403 } else if (A->getOption().matches(options::OPT_m32)) {
404 AT = Target.get32BitArchVariant().getArch();
405 if (Target.getEnvironment() == llvm::Triple::GNUX32)
406 Target.setEnvironment(llvm::Triple::GNU);
407 } else if (A->getOption().matches(options::OPT_m16) &&
408 Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
409 AT = llvm::Triple::x86;
410 Target.setEnvironment(llvm::Triple::CODE16);
411 }
412
413 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
414 Target.setArch(AT);
415 }
416
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000417 // Handle -miamcu flag.
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000418 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
419 if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
420 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
421 << Target.str();
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000422
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000423 if (A && !A->getOption().matches(options::OPT_m32))
424 D.Diag(diag::err_drv_argument_not_allowed_with)
425 << "-miamcu" << A->getBaseArg().getAsString(Args);
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000426
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000427 Target.setArch(llvm::Triple::x86);
428 Target.setArchName("i586");
429 Target.setEnvironment(llvm::Triple::UnknownEnvironment);
430 Target.setEnvironmentName("");
431 Target.setOS(llvm::Triple::ELFIAMCU);
432 Target.setVendor(llvm::Triple::UnknownVendor);
433 Target.setVendorName("intel");
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000434 }
435
Artem Belevich959e0542015-07-10 19:47:55 +0000436 return Target;
437}
438
Teresa Johnson945bc502015-10-15 20:35:53 +0000439// \brief Parse the LTO options and record the type of LTO compilation
440// based on which -f(no-)?lto(=.*)? option occurs last.
441void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
442 LTOMode = LTOK_None;
443 if (!Args.hasFlag(options::OPT_flto, options::OPT_flto_EQ,
444 options::OPT_fno_lto, false))
445 return;
446
447 StringRef LTOName("full");
448
449 const Arg *A = Args.getLastArg(options::OPT_flto_EQ);
Teresa Johnson6ef80dc2015-11-02 18:03:12 +0000450 if (A)
451 LTOName = A->getValue();
Teresa Johnson945bc502015-10-15 20:35:53 +0000452
453 LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
454 .Case("full", LTOK_Full)
455 .Case("thin", LTOK_Thin)
456 .Default(LTOK_Unknown);
457
458 if (LTOMode == LTOK_Unknown) {
459 assert(A);
460 Diag(diag::err_drv_unsupported_option_argument) << A->getOption().getName()
461 << A->getValue();
462 }
463}
464
Samuel Antao39f9da22016-10-27 16:38:05 +0000465/// Compute the desired OpenMP runtime from the flags provided.
466Driver::OpenMPRuntimeKind Driver::getOpenMPRuntime(const ArgList &Args) const {
467 StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
468
469 const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
470 if (A)
471 RuntimeName = A->getValue();
472
473 auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
474 .Case("libomp", OMPRT_OMP)
475 .Case("libgomp", OMPRT_GOMP)
476 .Case("libiomp5", OMPRT_IOMP5)
477 .Default(OMPRT_Unknown);
478
479 if (RT == OMPRT_Unknown) {
480 if (A)
481 Diag(diag::err_drv_unsupported_option_argument)
482 << A->getOption().getName() << A->getValue();
483 else
484 // FIXME: We could use a nicer diagnostic here.
485 Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
486 }
487
488 return RT;
489}
490
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000491void Driver::CreateOffloadingDeviceToolChains(Compilation &C,
492 InputList &Inputs) {
493
494 //
495 // CUDA
496 //
497 // We need to generate a CUDA toolchain if any of the inputs has a CUDA type.
498 if (llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
499 return types::isCuda(I.first);
500 })) {
Justin Lebar66c4fd72016-11-18 00:41:22 +0000501 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
502 const llvm::Triple &HostTriple = HostTC->getTriple();
503 llvm::Triple CudaTriple(HostTriple.isArch64Bit() ? "nvptx64-nvidia-cuda"
504 : "nvptx-nvidia-cuda");
505 // Use the CUDA and host triples as the key into the ToolChains map, because
506 // the device toolchain we create depends on both.
David Blaikie6ad71012017-01-13 18:53:43 +0000507 auto &CudaTC = ToolChains[CudaTriple.str() + "/" + HostTriple.str()];
Justin Lebar66c4fd72016-11-18 00:41:22 +0000508 if (!CudaTC) {
David Blaikie6ad71012017-01-13 18:53:43 +0000509 CudaTC = llvm::make_unique<toolchains::CudaToolChain>(
510 *this, CudaTriple, *HostTC, C.getInputArgs());
Justin Lebar66c4fd72016-11-18 00:41:22 +0000511 }
David Blaikie6ad71012017-01-13 18:53:43 +0000512 C.addOffloadDeviceToolChain(CudaTC.get(), Action::OFK_Cuda);
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000513 }
514
515 //
Samuel Antao39f9da22016-10-27 16:38:05 +0000516 // OpenMP
517 //
518 // We need to generate an OpenMP toolchain if the user specified targets with
519 // the -fopenmp-targets option.
520 if (Arg *OpenMPTargets =
521 C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
522 if (OpenMPTargets->getNumValues()) {
523 // We expect that -fopenmp-targets is always used in conjunction with the
524 // option -fopenmp specifying a valid runtime with offloading support,
525 // i.e. libomp or libiomp.
526 bool HasValidOpenMPRuntime = C.getInputArgs().hasFlag(
527 options::OPT_fopenmp, options::OPT_fopenmp_EQ,
528 options::OPT_fno_openmp, false);
529 if (HasValidOpenMPRuntime) {
530 OpenMPRuntimeKind OpenMPKind = getOpenMPRuntime(C.getInputArgs());
531 HasValidOpenMPRuntime =
532 OpenMPKind == OMPRT_OMP || OpenMPKind == OMPRT_IOMP5;
533 }
534
535 if (HasValidOpenMPRuntime) {
536 llvm::StringMap<const char *> FoundNormalizedTriples;
537 for (const char *Val : OpenMPTargets->getValues()) {
538 llvm::Triple TT(Val);
539 std::string NormalizedName = TT.normalize();
540
541 // Make sure we don't have a duplicate triple.
542 auto Duplicate = FoundNormalizedTriples.find(NormalizedName);
543 if (Duplicate != FoundNormalizedTriples.end()) {
544 Diag(clang::diag::warn_drv_omp_offload_target_duplicate)
545 << Val << Duplicate->second;
546 continue;
547 }
548
549 // Store the current triple so that we can check for duplicates in the
550 // following iterations.
551 FoundNormalizedTriples[NormalizedName] = Val;
552
553 // If the specified target is invalid, emit a diagnostic.
554 if (TT.getArch() == llvm::Triple::UnknownArch)
555 Diag(clang::diag::err_drv_invalid_omp_target) << Val;
556 else {
557 const ToolChain &TC = getToolChain(C.getInputArgs(), TT);
558 C.addOffloadDeviceToolChain(&TC, Action::OFK_OpenMP);
559 }
560 }
561 } else
562 Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
563 } else
564 Diag(clang::diag::warn_drv_empty_joined_argument)
565 << OpenMPTargets->getAsString(C.getInputArgs());
566 }
567
568 //
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000569 // TODO: Add support for other offloading programming models here.
570 //
571
572 return;
573}
574
Chris Lattner54b16772011-07-23 17:14:25 +0000575Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
Daniel Dunbar2608c542009-03-18 01:38:48 +0000576 llvm::PrettyStackTraceString CrashInfo("Compilation construction");
577
Eric Christopherf901e852011-08-17 22:59:59 +0000578 // FIXME: Handle environment options which affect driver behavior, somewhere
Bill Wendlingadbeb9f2012-03-12 21:24:57 +0000579 // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
Chad Rosier82301162011-09-14 00:47:55 +0000580
David Majnemer85c25b42016-07-24 17:44:03 +0000581 if (Optional<std::string> CompilerPathValue =
582 llvm::sys::Process::GetEnv("COMPILER_PATH")) {
583 StringRef CompilerPath = *CompilerPathValue;
Chad Rosier82301162011-09-14 00:47:55 +0000584 while (!CompilerPath.empty()) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000585 std::pair<StringRef, StringRef> Split =
586 CompilerPath.split(llvm::sys::EnvPathSeparator);
Chad Rosier82301162011-09-14 00:47:55 +0000587 PrefixDirs.push_back(Split.first);
588 CompilerPath = Split.second;
589 }
590 }
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +0000591
Hans Wennborg70850d82013-07-18 20:29:38 +0000592 // We look for the driver mode option early, because the mode can affect
593 // how other options are parsed.
Zachary Turneraff19c32016-08-12 17:47:52 +0000594 ParseDriverMode(ClangExecutable, ArgList.slice(1));
Hans Wennborg70850d82013-07-18 20:29:38 +0000595
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +0000596 // FIXME: What are we going to do with -V and -b?
597
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +0000598 // FIXME: This stuff needs to go into the Compilation, not the driver.
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +0000599 bool CCCPrintPhases;
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000600
David Blaikie69a1d8c2015-06-22 22:07:27 +0000601 InputArgList Args = ParseArgStrings(ArgList.slice(1));
Serge Pavlovb43573b2017-05-24 14:57:17 +0000602 if (Diags.hasErrorOccurred())
603 return nullptr;
Daniel Dunbaracd69572009-12-04 21:55:23 +0000604
Filipe Cabecinhas136f35e2015-07-18 06:35:24 +0000605 // Silence driver warnings if requested
606 Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w));
607
Rafael Espindola59ae7992009-12-07 18:28:29 +0000608 // -no-canonical-prefixes is used very early in main.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000609 Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
Rafael Espindola59ae7992009-12-07 18:28:29 +0000610
Daniel Dunbar926f81f2010-08-02 02:38:03 +0000611 // Ignore -pipe.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000612 Args.ClaimAllArgs(options::OPT_pipe);
Daniel Dunbar926f81f2010-08-02 02:38:03 +0000613
Daniel Dunbaracd69572009-12-04 21:55:23 +0000614 // Extract -ccc args.
Daniel Dunbaree66cf22009-03-10 20:52:46 +0000615 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +0000616 // FIXME: We need to figure out where this behavior should live. Most of it
617 // should be outside in the client; the parts that aren't should have proper
618 // options, either by introducing new ones or by overloading gcc ones like -V
619 // or -b.
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +0000620 CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
David Blaikie69a1d8c2015-06-22 22:07:27 +0000621 CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
622 if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
Richard Smithbd55daf2012-11-01 04:30:05 +0000623 CCCGenericGCCName = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000624 CCCUsePCH =
625 Args.hasFlag(options::OPT_ccc_pch_is_pch, options::OPT_ccc_pch_is_pth);
Bruno Cardoso Lopes52dfe712017-04-12 21:46:20 +0000626 GenReproducer = Args.hasFlag(options::OPT_gen_reproducer,
627 options::OPT_fno_crash_diagnostics,
628 !!::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH"));
Joerg Sonnenberger17d75512012-02-22 19:15:16 +0000629 // FIXME: DefaultTargetTriple is used by the target-prefixed calls to as/ld
630 // and getToolChain is const.
Hans Wennborg2e274592013-08-13 23:38:57 +0000631 if (IsCLMode()) {
Hans Wennborg73609a02014-03-28 01:19:04 +0000632 // clang-cl targets MSVC-style Win32.
Hans Wennborg2e274592013-08-13 23:38:57 +0000633 llvm::Triple T(DefaultTargetTriple);
Hans Wennborg9d9ce7a2014-03-28 20:49:28 +0000634 T.setOS(llvm::Triple::Win32);
Hans Wennborg0f0e8d62015-09-18 17:11:50 +0000635 T.setVendor(llvm::Triple::PC);
Hans Wennborg9d9ce7a2014-03-28 20:49:28 +0000636 T.setEnvironment(llvm::Triple::MSVC);
Hans Wennborg2e274592013-08-13 23:38:57 +0000637 DefaultTargetTriple = T.str();
638 }
David Blaikie69a1d8c2015-06-22 22:07:27 +0000639 if (const Arg *A = Args.getLastArg(options::OPT_target))
Richard Smithbd55daf2012-11-01 04:30:05 +0000640 DefaultTargetTriple = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000641 if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
Richard Smithbd55daf2012-11-01 04:30:05 +0000642 Dir = InstalledDir = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000643 for (const Arg *A : Args.filtered(options::OPT_B)) {
Benjamin Kramer1a648d12011-02-08 20:31:42 +0000644 A->claim();
Richard Smithbd55daf2012-11-01 04:30:05 +0000645 PrefixDirs.push_back(A->getValue(0));
Benjamin Kramer1a648d12011-02-08 20:31:42 +0000646 }
David Blaikie69a1d8c2015-06-22 22:07:27 +0000647 if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
Richard Smithbd55daf2012-11-01 04:30:05 +0000648 SysRoot = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000649 if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
Peter Collingbourne9d9e1fc2013-05-27 21:40:20 +0000650 DyldPrefix = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000651 if (Args.hasArg(options::OPT_nostdlib))
Joerg Sonnenbergerbc923f32011-03-21 13:59:26 +0000652 UseStdLib = false;
Daniel Dunbaree66cf22009-03-10 20:52:46 +0000653
David Blaikie69a1d8c2015-06-22 22:07:27 +0000654 if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
Bob Wilsona20a1da2013-03-23 05:17:59 +0000655 ResourceDir = A->getValue();
Jim Grosbach061dabf2013-03-12 20:17:58 +0000656
David Blaikie69a1d8c2015-06-22 22:07:27 +0000657 if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
Reid Kleckner68eb60b2015-02-02 22:41:48 +0000658 SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
659 .Case("cwd", SaveTempsCwd)
660 .Case("obj", SaveTempsObj)
661 .Default(SaveTempsCwd);
662 }
663
Steven Wu1257cd82016-05-18 17:04:52 +0000664 setLTOMode(Args);
665
Steven Wu844ab6a2016-11-16 06:06:44 +0000666 // Process -fembed-bitcode= flags.
667 if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
668 StringRef Name = A->getValue();
669 unsigned Model = llvm::StringSwitch<unsigned>(Name)
670 .Case("off", EmbedNone)
671 .Case("all", EmbedBitcode)
672 .Case("bitcode", EmbedBitcode)
673 .Case("marker", EmbedMarker)
674 .Default(~0U);
675 if (Model == ~0U) {
676 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
677 << Name;
678 } else
679 BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
Steven Wu574b0f22016-03-01 01:07:58 +0000680 }
681
David Blaikie69a1d8c2015-06-22 22:07:27 +0000682 std::unique_ptr<llvm::opt::InputArgList> UArgs =
683 llvm::make_unique<InputArgList>(std::move(Args));
684
Daniel Dunbar775d4062010-06-11 22:00:26 +0000685 // Perform the default argument translations.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000686 DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
Daniel Dunbar775d4062010-06-11 22:00:26 +0000687
Chandler Carruthcb916192012-01-25 08:49:21 +0000688 // Owned by the host.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000689 const ToolChain &TC = getToolChain(
690 *UArgs, computeTargetTriple(*this, DefaultTargetTriple, *UArgs));
Chandler Carruthcb916192012-01-25 08:49:21 +0000691
Daniel Dunbar3ce436d2009-03-16 06:42:30 +0000692 // The compilation takes ownership of Args.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000693 Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +0000694
Daniel Dunbarf0eddb82009-03-18 02:55:38 +0000695 if (!HandleImmediateArgs(*C))
696 return C;
697
Chad Rosierecdede82011-08-12 22:08:57 +0000698 // Construct the list of inputs.
699 InputList Inputs;
Hans Wennborged1d0722013-08-13 21:32:29 +0000700 BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
Chad Rosierecdede82011-08-12 22:08:57 +0000701
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000702 // Populate the tool chains for the offloading devices, if any.
703 CreateOffloadingDeviceToolChains(*C, Inputs);
Justin Lebar0e450a52016-03-30 23:30:25 +0000704
Chandler Carruth7f1417f2012-01-24 10:43:44 +0000705 // Construct the list of abstract actions to perform for this compilation. On
Tim Northover157d9112014-01-16 08:48:16 +0000706 // MachO targets this uses the driver-driver and universal actions.
707 if (TC.getTriple().isOSBinFormatMachO())
Artem Belevich5e2a3ec2015-11-17 22:28:40 +0000708 BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +0000709 else
Justin Lebar0f3474c2016-02-11 02:00:50 +0000710 BuildActions(*C, C->getArgs(), Inputs, C->getActions());
Daniel Dunbarf0eddb82009-03-18 02:55:38 +0000711
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +0000712 if (CCCPrintPhases) {
Daniel Dunbareb843be2009-03-18 03:13:20 +0000713 PrintActions(*C);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +0000714 return C;
715 }
716
717 BuildJobs(*C);
Daniel Dunbaradc91e62009-03-15 01:38:15 +0000718
719 return C;
Daniel Dunbaree66cf22009-03-10 20:52:46 +0000720}
721
Justin Bognered9cbe02015-07-09 06:58:31 +0000722static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
723 llvm::opt::ArgStringList ASL;
724 for (const auto *A : Args)
725 A->render(Args, ASL);
726
727 for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
728 if (I != ASL.begin())
729 OS << ' ';
730 Command::printArg(OS, *I, true);
731 }
732 OS << '\n';
733}
734
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +0000735bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename,
736 SmallString<128> &CrashDiagDir) {
737 using namespace llvm::sys;
738 assert(llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin() &&
739 "Only knows about .crash files on Darwin");
740
741 // The .crash file can be found on at ~/Library/Logs/DiagnosticReports/
742 // (or /Library/Logs/DiagnosticReports for root) and has the filename pattern
743 // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash.
744 path::home_directory(CrashDiagDir);
745 if (CrashDiagDir.startswith("/var/root"))
746 CrashDiagDir = "/";
747 path::append(CrashDiagDir, "Library/Logs/DiagnosticReports");
748 int PID =
749#if LLVM_ON_UNIX
750 getpid();
751#else
752 0;
753#endif
754 std::error_code EC;
755 fs::file_status FileStatus;
756 TimePoint<> LastAccessTime;
757 SmallString<128> CrashFilePath;
758 // Lookup the .crash files and get the one generated by a subprocess spawned
759 // by this driver invocation.
760 for (fs::directory_iterator File(CrashDiagDir, EC), FileEnd;
761 File != FileEnd && !EC; File.increment(EC)) {
762 StringRef FileName = path::filename(File->path());
763 if (!FileName.startswith(Name))
764 continue;
765 if (fs::status(File->path(), FileStatus))
766 continue;
767 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CrashFile =
768 llvm::MemoryBuffer::getFile(File->path());
769 if (!CrashFile)
770 continue;
771 // The first line should start with "Process:", otherwise this isn't a real
772 // .crash file.
773 StringRef Data = CrashFile.get()->getBuffer();
774 if (!Data.startswith("Process:"))
775 continue;
776 // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]"
777 size_t ParentProcPos = Data.find("Parent Process:");
778 if (ParentProcPos == StringRef::npos)
779 continue;
780 size_t LineEnd = Data.find_first_of("\n", ParentProcPos);
781 if (LineEnd == StringRef::npos)
782 continue;
783 StringRef ParentProcess = Data.slice(ParentProcPos+15, LineEnd).trim();
784 int OpenBracket = -1, CloseBracket = -1;
785 for (size_t i = 0, e = ParentProcess.size(); i < e; ++i) {
786 if (ParentProcess[i] == '[')
787 OpenBracket = i;
788 if (ParentProcess[i] == ']')
789 CloseBracket = i;
790 }
791 // Extract the parent process PID from the .crash file and check whether
792 // it matches this driver invocation pid.
793 int CrashPID;
794 if (OpenBracket < 0 || CloseBracket < 0 ||
795 ParentProcess.slice(OpenBracket + 1, CloseBracket)
796 .getAsInteger(10, CrashPID) || CrashPID != PID) {
797 continue;
798 }
799
800 // Found a .crash file matching the driver pid. To avoid getting an older
801 // and misleading crash file, continue looking for the most recent.
802 // FIXME: the driver can dispatch multiple cc1 invocations, leading to
803 // multiple crashes poiting to the same parent process. Since the driver
804 // does not collect pid information for the dispatched invocation there's
805 // currently no way to distinguish among them.
806 const auto FileAccessTime = FileStatus.getLastModificationTime();
807 if (FileAccessTime > LastAccessTime) {
808 CrashFilePath.assign(File->path());
809 LastAccessTime = FileAccessTime;
810 }
811 }
812
813 // If found, copy it over to the location of other reproducer files.
814 if (!CrashFilePath.empty()) {
815 EC = fs::copy_file(CrashFilePath, ReproCrashFilename);
816 if (EC)
817 return false;
818 return true;
819 }
820
821 return false;
822}
823
Eric Christopherf901e852011-08-17 22:59:59 +0000824// When clang crashes, produce diagnostic information including the fully
825// preprocessed source file(s). Request that the developer attach the
Chad Rosierbe10f982011-08-02 17:58:04 +0000826// diagnostic information to a bug report.
827void Driver::generateCompilationDiagnostics(Compilation &C,
Justin Bognere1a33d12014-10-20 21:02:05 +0000828 const Command &FailingCommand) {
Chad Rosier877c0a22012-02-22 00:30:39 +0000829 if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
Chad Rosier62135492012-07-09 17:31:28 +0000830 return;
Chad Rosierbee5a1d2012-03-07 00:30:40 +0000831
Chad Rosierdbf46a12013-02-01 18:30:26 +0000832 // Don't try to generate diagnostics for link or dsymutil jobs.
Justin Bognere1a33d12014-10-20 21:02:05 +0000833 if (FailingCommand.getCreator().isLinkJob() ||
834 FailingCommand.getCreator().isDsymutilJob())
Chad Rosier877c0a22012-02-22 00:30:39 +0000835 return;
836
Chad Rosier8179f112012-06-19 17:51:34 +0000837 // Print the version of the compiler.
838 PrintVersion(C, llvm::errs());
839
Chad Rosierbe10f982011-08-02 17:58:04 +0000840 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000841 << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the "
842 "crash backtrace, preprocessed source, and associated run script.";
Chad Rosierbe10f982011-08-02 17:58:04 +0000843
844 // Suppress driver output and emit preprocessor output to temp file.
Hans Wennborg70850d82013-07-18 20:29:38 +0000845 Mode = CPPMode;
Chad Rosierbe10f982011-08-02 17:58:04 +0000846 CCGenDiagnostics = true;
847
Chad Rosiercdb008d2011-11-02 21:29:05 +0000848 // Save the original job command(s).
Justin Bogner25645152014-10-21 17:24:44 +0000849 Command Cmd = FailingCommand;
Chad Rosiercdb008d2011-11-02 21:29:05 +0000850
Richard Smith5bb4cdf2012-12-20 02:22:15 +0000851 // Keep track of whether we produce any errors while trying to produce
852 // preprocessed sources.
853 DiagnosticErrorTrap Trap(Diags);
854
855 // Suppress tool output.
Chad Rosierbe10f982011-08-02 17:58:04 +0000856 C.initCompilationForDiagnostics();
Chad Rosierecdede82011-08-12 22:08:57 +0000857
858 // Construct the list of inputs.
859 InputList Inputs;
860 BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
Chad Rosierbe10f982011-08-02 17:58:04 +0000861
Chad Rosier4f81fc22011-08-12 23:30:05 +0000862 for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
Chad Rosierd57133d2011-08-18 00:22:25 +0000863 bool IgnoreInput = false;
864
865 // Ignore input from stdin or any inputs that cannot be preprocessed.
Paul Robinsonf44157d2014-04-28 22:24:44 +0000866 // Check type first as not all linker inputs have a value.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000867 if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
Paul Robinsonf44157d2014-04-28 22:24:44 +0000868 IgnoreInput = true;
869 } else if (!strcmp(it->second->getValue(), "-")) {
Chad Rosierd57133d2011-08-18 00:22:25 +0000870 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000871 << "Error generating preprocessed source(s) - "
872 "ignoring input from stdin.";
Chad Rosierd57133d2011-08-18 00:22:25 +0000873 IgnoreInput = true;
Chad Rosierd57133d2011-08-18 00:22:25 +0000874 }
875
876 if (IgnoreInput) {
Chad Rosier4f81fc22011-08-12 23:30:05 +0000877 it = Inputs.erase(it);
878 ie = Inputs.end();
Chad Rosier6fdf38b2011-08-17 23:08:45 +0000879 } else {
Chad Rosier4f81fc22011-08-12 23:30:05 +0000880 ++it;
Chad Rosier6fdf38b2011-08-17 23:08:45 +0000881 }
Chad Rosier4f81fc22011-08-12 23:30:05 +0000882 }
Chad Rosierd57133d2011-08-18 00:22:25 +0000883
Chad Rosierc5103c32013-01-29 23:57:10 +0000884 if (Inputs.empty()) {
885 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000886 << "Error generating preprocessed source(s) - "
887 "no preprocessable inputs.";
Chad Rosierc5103c32013-01-29 23:57:10 +0000888 return;
889 }
890
Chad Rosiere75ef402011-09-06 23:52:36 +0000891 // Don't attempt to generate preprocessed files if multiple -arch options are
Chad Rosier636d2832012-02-13 18:16:28 +0000892 // used, unless they're all duplicates.
893 llvm::StringSet<> ArchNames;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +0000894 for (const Arg *A : C.getArgs()) {
Chad Rosiere75ef402011-09-06 23:52:36 +0000895 if (A->getOption().matches(options::OPT_arch)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000896 StringRef ArchName = A->getValue();
Chad Rosier636d2832012-02-13 18:16:28 +0000897 ArchNames.insert(ArchName);
Chad Rosiere75ef402011-09-06 23:52:36 +0000898 }
899 }
Chad Rosier636d2832012-02-13 18:16:28 +0000900 if (ArchNames.size() > 1) {
901 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000902 << "Error generating preprocessed source(s) - cannot generate "
903 "preprocessed source with multiple -arch options.";
Chad Rosier636d2832012-02-13 18:16:28 +0000904 return;
905 }
Chad Rosiere75ef402011-09-06 23:52:36 +0000906
Chandler Carruth7f1417f2012-01-24 10:43:44 +0000907 // Construct the list of abstract actions to perform for this compilation. On
908 // Darwin OSes this uses the driver-driver and builds universal actions.
Chandler Carruthcb916192012-01-25 08:49:21 +0000909 const ToolChain &TC = C.getDefaultToolChain();
Tim Northover157d9112014-01-16 08:48:16 +0000910 if (TC.getTriple().isOSBinFormatMachO())
Artem Belevich5e2a3ec2015-11-17 22:28:40 +0000911 BuildUniversalActions(C, TC, Inputs);
Chad Rosierbe10f982011-08-02 17:58:04 +0000912 else
Justin Lebar0f3474c2016-02-11 02:00:50 +0000913 BuildActions(C, C.getArgs(), Inputs, C.getActions());
Chad Rosierbe10f982011-08-02 17:58:04 +0000914
915 BuildJobs(C);
916
917 // If there were errors building the compilation, quit now.
Richard Smith5bb4cdf2012-12-20 02:22:15 +0000918 if (Trap.hasErrorOccurred()) {
Chad Rosierbe10f982011-08-02 17:58:04 +0000919 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000920 << "Error generating preprocessed source(s).";
Chad Rosierbe10f982011-08-02 17:58:04 +0000921 return;
922 }
923
924 // Generate preprocessed output.
Chad Rosierdd60e092013-01-29 20:15:05 +0000925 SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
Justin Bogner0cd92482015-07-02 22:52:08 +0000926 C.ExecuteJobs(C.getJobs(), FailingCommands);
Chad Rosierbe10f982011-08-02 17:58:04 +0000927
Justin Bognerbc89b182014-10-20 21:20:27 +0000928 // If any of the preprocessing commands failed, clean up and exit.
929 if (!FailingCommands.empty()) {
Reid Kleckner68eb60b2015-02-02 22:41:48 +0000930 if (!isSaveTempsEnabled())
Chad Rosierbe10f982011-08-02 17:58:04 +0000931 C.CleanupFileList(C.getTempFiles(), true);
932
933 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000934 << "Error generating preprocessed source(s).";
Justin Bognerbc89b182014-10-20 21:20:27 +0000935 return;
Chad Rosierbe10f982011-08-02 17:58:04 +0000936 }
Justin Bognerbc89b182014-10-20 21:20:27 +0000937
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000938 const ArgStringList &TempFiles = C.getTempFiles();
939 if (TempFiles.empty()) {
940 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000941 << "Error generating preprocessed source(s).";
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000942 return;
943 }
944
Justin Bognerbc89b182014-10-20 21:20:27 +0000945 Diag(clang::diag::note_drv_command_failed_diag_msg)
946 << "\n********************\n\n"
947 "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
948 "Preprocessed source(s) and associated run script(s) are located at:";
Justin Bognerbc89b182014-10-20 21:20:27 +0000949
Justin Bogner659ecc32014-10-20 22:47:23 +0000950 SmallString<128> VFS;
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +0000951 SmallString<128> ReproCrashFilename;
Justin Bogner659ecc32014-10-20 22:47:23 +0000952 for (const char *TempFile : TempFiles) {
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000953 Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +0000954 if (ReproCrashFilename.empty()) {
955 ReproCrashFilename = TempFile;
956 llvm::sys::path::replace_extension(ReproCrashFilename, ".crash");
957 }
Justin Bogner659ecc32014-10-20 22:47:23 +0000958 if (StringRef(TempFile).endswith(".cache")) {
959 // In some cases (modules) we'll dump extra data to help with reproducing
960 // the crash into a directory next to the output.
961 VFS = llvm::sys::path::filename(TempFile);
962 llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
963 }
964 }
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000965
966 // Assume associated files are based off of the first temporary file.
Justin Bogner25645152014-10-21 17:24:44 +0000967 CrashReportInfo CrashInfo(TempFiles[0], VFS);
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000968
Justin Bogner25645152014-10-21 17:24:44 +0000969 std::string Script = CrashInfo.Filename.rsplit('.').first.str() + ".sh";
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000970 std::error_code EC;
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000971 llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::F_Excl);
972 if (EC) {
973 Diag(clang::diag::note_drv_command_failed_diag_msg)
974 << "Error generating run script: " + Script + " " + EC.message();
975 } else {
Justin Bogner42220ed2015-03-12 00:14:35 +0000976 ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
Justin Bognered9cbe02015-07-09 06:58:31 +0000977 << "# Driver args: ";
978 printArgList(ScriptOS, C.getInputArgs());
979 ScriptOS << "# Original command: ";
Justin Bogner42220ed2015-03-12 00:14:35 +0000980 Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
Justin Bogner33bdbc62014-10-21 18:03:08 +0000981 Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000982 Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
Justin Bognerbc89b182014-10-20 21:20:27 +0000983 }
Saleem Abdulrasool3661a822015-01-12 02:33:09 +0000984
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +0000985 // On darwin, provide information about the .crash diagnostic report.
986 if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) {
987 SmallString<128> CrashDiagDir;
988 if (getCrashDiagnosticFile(ReproCrashFilename, CrashDiagDir)) {
989 Diag(clang::diag::note_drv_command_failed_diag_msg)
990 << ReproCrashFilename.str();
991 } else { // Suggest a directory for the user to look for .crash files.
992 llvm::sys::path::append(CrashDiagDir, Name);
993 CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash";
994 Diag(clang::diag::note_drv_command_failed_diag_msg)
995 << "Crash backtrace is located in";
996 Diag(clang::diag::note_drv_command_failed_diag_msg)
997 << CrashDiagDir.str();
998 Diag(clang::diag::note_drv_command_failed_diag_msg)
999 << "(choose the .crash file that corresponds to your crash)";
1000 }
1001 }
1002
Saleem Abdulrasool3661a822015-01-12 02:33:09 +00001003 for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file,
1004 options::OPT_frewrite_map_file_EQ))
1005 Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
1006
Justin Bognerbc89b182014-10-20 21:20:27 +00001007 Diag(clang::diag::note_drv_command_failed_diag_msg)
1008 << "\n\n********************";
Chad Rosierbe10f982011-08-02 17:58:04 +00001009}
1010
Justin Bogner0cd92482015-07-02 22:52:08 +00001011void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
Oleg Ranevskyycd516372016-01-05 19:54:39 +00001012 // Since commandLineFitsWithinSystemLimits() may underestimate system's capacity
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001013 // if the tool does not support response files, there is a chance/ that things
1014 // will just work without a response file, so we silently just skip it.
Justin Bogner0cd92482015-07-02 22:52:08 +00001015 if (Cmd.getCreator().getResponseFilesSupport() == Tool::RF_None ||
Oleg Ranevskyycd516372016-01-05 19:54:39 +00001016 llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(), Cmd.getArguments()))
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001017 return;
1018
1019 std::string TmpName = GetTemporaryPath("response", "txt");
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00001020 Cmd.setResponseFile(C.addTempFile(C.getArgs().MakeArgString(TmpName)));
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001021}
1022
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001023int Driver::ExecuteCompilation(
1024 Compilation &C,
1025 SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001026 // Just print if -### was present.
1027 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
Hans Wennborgb212b342013-09-12 18:23:34 +00001028 C.getJobs().Print(llvm::errs(), "\n", true);
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001029 return 0;
1030 }
1031
1032 // If there were errors building the compilation, quit now.
Chad Rosierbe10f982011-08-02 17:58:04 +00001033 if (Diags.hasErrorOccurred())
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001034 return 1;
1035
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001036 // Set up response file names for each command, if necessary
Justin Bogner0cd92482015-07-02 22:52:08 +00001037 for (auto &Job : C.getJobs())
1038 setUpResponseFiles(C, Job);
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001039
Justin Bogner0cd92482015-07-02 22:52:08 +00001040 C.ExecuteJobs(C.getJobs(), FailingCommands);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001041
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001042 // Remove temp files.
1043 C.CleanupFileList(C.getTempFiles());
1044
Daniel Dunbar07494792010-05-22 00:37:20 +00001045 // If the command succeeded, we are done.
Chad Rosierdd60e092013-01-29 20:15:05 +00001046 if (FailingCommands.empty())
1047 return 0;
Daniel Dunbar07494792010-05-22 00:37:20 +00001048
Chad Rosierdd60e092013-01-29 20:15:05 +00001049 // Otherwise, remove result files and print extra information about abnormal
1050 // failures.
Douglas Katzman6bbffc42015-06-25 18:51:37 +00001051 for (const auto &CmdPair : FailingCommands) {
1052 int Res = CmdPair.first;
1053 const Command *FailingCommand = CmdPair.second;
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001054
Chad Rosierdd60e092013-01-29 20:15:05 +00001055 // Remove result files if we're not saving temps.
Reid Kleckner68eb60b2015-02-02 22:41:48 +00001056 if (!isSaveTempsEnabled()) {
Chad Rosierdd60e092013-01-29 20:15:05 +00001057 const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
1058 C.CleanupFileMap(C.getResultFiles(), JA, true);
1059
1060 // Failure result files are valid unless we crashed.
1061 if (Res < 0)
1062 C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
1063 }
1064
1065 // Print extra information about abnormal failures, if possible.
1066 //
1067 // This is ad-hoc, but we don't want to be excessively noisy. If the result
Justin Bogner5aaf2e72014-06-26 20:59:36 +00001068 // status was 1, assume the command failed normally. In particular, if it
Chad Rosierdd60e092013-01-29 20:15:05 +00001069 // was the compiler then assume it gave a reasonable error code. Failures
1070 // in other tools are less common, and they generally have worse
1071 // diagnostics, so always print the diagnostic there.
1072 const Tool &FailingTool = FailingCommand->getCreator();
1073
1074 if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
1075 // FIXME: See FIXME above regarding result code interpretation.
1076 if (Res < 0)
1077 Diag(clang::diag::err_drv_command_signalled)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001078 << FailingTool.getShortName();
Chad Rosierdd60e092013-01-29 20:15:05 +00001079 else
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001080 Diag(clang::diag::err_drv_command_failed) << FailingTool.getShortName()
1081 << Res;
Chad Rosierdd60e092013-01-29 20:15:05 +00001082 }
Peter Collingbourne119cfaa2011-11-21 00:01:05 +00001083 }
Chad Rosierdd60e092013-01-29 20:15:05 +00001084 return 0;
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001085}
1086
Daniel Dunbara7b5e212009-04-15 16:34:29 +00001087void Driver::PrintHelp(bool ShowHidden) const {
Hans Wennborg6ddc6902013-07-27 00:23:45 +00001088 unsigned IncludedFlagsBitmask;
1089 unsigned ExcludedFlagsBitmask;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001090 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001091 getIncludeExcludeOptionFlagMasks();
Hans Wennborg6ddc6902013-07-27 00:23:45 +00001092
1093 ExcludedFlagsBitmask |= options::NoDriverOption;
1094 if (!ShowHidden)
1095 ExcludedFlagsBitmask |= HelpHidden;
1096
1097 getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
1098 IncludedFlagsBitmask, ExcludedFlagsBitmask);
Daniel Dunbar7c925282009-03-31 21:38:17 +00001099}
1100
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001101void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001102 // FIXME: The following handlers should use a callback mechanism, we don't
1103 // know what the client would like to do.
Ted Kremenek4c0df3d2010-01-23 02:11:34 +00001104 OS << getClangFullVersion() << '\n';
Daniel Dunbarb10248802009-03-26 16:09:13 +00001105 const ToolChain &TC = C.getDefaultToolChain();
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001106 OS << "Target: " << TC.getTripleString() << '\n';
Daniel Dunbar10978e42009-06-16 23:32:58 +00001107
1108 // Print the threading model.
Jonathan Roelofsb140a102014-10-03 21:57:44 +00001109 if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
1110 // Don't print if the ToolChain would have barfed on it already
1111 if (TC.isThreadModelSupported(A->getValue()))
1112 OS << "Thread model: " << A->getValue();
1113 } else
1114 OS << "Thread model: " << TC.getThreadModel();
1115 OS << '\n';
Chandler Carruth9ade6a92015-08-05 17:07:33 +00001116
1117 // Print out the install directory.
1118 OS << "InstalledDir: " << InstalledDir << '\n';
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001119}
1120
Chris Lattner86ed5b02010-05-05 05:53:24 +00001121/// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
1122/// option.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001123static void PrintDiagnosticCategories(raw_ostream &OS) {
Argyrios Kyrtzidis0e37afa2011-05-25 05:05:01 +00001124 // Skip the empty category.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001125 for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
1126 ++i)
Argyrios Kyrtzidis0e37afa2011-05-25 05:05:01 +00001127 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
Chris Lattner86ed5b02010-05-05 05:53:24 +00001128}
1129
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001130bool Driver::HandleImmediateArgs(const Compilation &C) {
Daniel Dunbar18974bd2010-06-11 22:00:19 +00001131 // The order these options are handled in gcc is all over the place, but we
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001132 // don't expect inconsistencies w.r.t. that to matter in practice.
Daniel Dunbar7c925282009-03-31 21:38:17 +00001133
Daniel Dunbar1b09e042010-09-17 02:47:28 +00001134 if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
1135 llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
1136 return false;
1137 }
1138
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001139 if (C.getArgs().hasArg(options::OPT_dumpversion)) {
Daniel Dunbare26e5002011-01-12 00:43:47 +00001140 // Since -dumpversion is only implemented for pedantic GCC compatibility, we
1141 // return an answer which matches our definition of __VERSION__.
1142 //
1143 // If we want to return a more correct answer some day, then we should
1144 // introduce a non-pedantically GCC compatible mode to Clang in which we
1145 // provide sensible definitions for -dumpversion, __VERSION__, etc.
1146 llvm::outs() << "4.2.1\n";
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001147 return false;
1148 }
Daniel Dunbarfb3d7472010-06-14 21:23:12 +00001149
Chris Lattner86ed5b02010-05-05 05:53:24 +00001150 if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
1151 PrintDiagnosticCategories(llvm::outs());
1152 return false;
1153 }
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001154
James Molloya3c85b82012-05-01 14:57:16 +00001155 if (C.getArgs().hasArg(options::OPT_help) ||
Daniel Dunbara7b5e212009-04-15 16:34:29 +00001156 C.getArgs().hasArg(options::OPT__help_hidden)) {
1157 PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
Daniel Dunbar7c925282009-03-31 21:38:17 +00001158 return false;
1159 }
1160
Daniel Dunbarb0006ae2009-04-02 15:05:41 +00001161 if (C.getArgs().hasArg(options::OPT__version)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001162 // Follow gcc behavior and use stdout for --version and stderr for -v.
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001163 PrintVersion(C, llvm::outs());
Daniel Dunbarb0006ae2009-04-02 15:05:41 +00001164 return false;
1165 }
1166
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001167 if (C.getArgs().hasArg(options::OPT_v) ||
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001168 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001169 PrintVersion(C, llvm::errs());
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001170 SuppressMissingInputWarning = true;
1171 }
1172
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001173 const ToolChain &TC = C.getDefaultToolChain();
Chandler Carruth0ae39aa2013-07-30 17:57:09 +00001174
1175 if (C.getArgs().hasArg(options::OPT_v))
1176 TC.printVerboseInfo(llvm::errs());
1177
Meador Inge51208a32017-04-04 21:46:50 +00001178 if (C.getArgs().hasArg(options::OPT_print_resource_dir)) {
Meador Ingea9113952017-04-05 22:27:20 +00001179 llvm::outs() << ResourceDir << '\n';
Meador Inge51208a32017-04-04 21:46:50 +00001180 return false;
1181 }
1182
Daniel Dunbard972e222009-03-20 04:37:21 +00001183 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
1184 llvm::outs() << "programs: =";
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001185 bool separator = false;
1186 for (const std::string &Path : TC.getProgramPaths()) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001187 if (separator)
1188 llvm::outs() << ':';
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001189 llvm::outs() << Path;
1190 separator = true;
Daniel Dunbard972e222009-03-20 04:37:21 +00001191 }
1192 llvm::outs() << "\n";
Peter Collingbournefa9771f2011-09-06 02:08:31 +00001193 llvm::outs() << "libraries: =" << ResourceDir;
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001194
Sebastian Pop980920a2012-04-16 04:16:43 +00001195 StringRef sysroot = C.getSysRoot();
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001196
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001197 for (const std::string &Path : TC.getFilePaths()) {
1198 // Always print a separator. ResourceDir was the first item shown.
Peter Collingbournefa9771f2011-09-06 02:08:31 +00001199 llvm::outs() << ':';
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001200 // Interpretation of leading '=' is needed only for NetBSD.
1201 if (Path[0] == '=')
Douglas Katzman26eabf62015-06-24 15:10:30 +00001202 llvm::outs() << sysroot << Path.substr(1);
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001203 else
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001204 llvm::outs() << Path;
Daniel Dunbard972e222009-03-20 04:37:21 +00001205 }
1206 llvm::outs() << "\n";
Daniel Dunbar7c925282009-03-31 21:38:17 +00001207 return false;
Daniel Dunbard972e222009-03-20 04:37:21 +00001208 }
1209
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001210 // FIXME: The following handlers should use a callback mechanism, we don't
1211 // know what the client would like to do.
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001212 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001213 llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001214 return false;
1215 }
1216
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001217 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001218 llvm::outs() << GetProgramPath(A->getValue(), TC) << "\n";
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001219 return false;
1220 }
1221
Yuka Takahashic8068db2017-05-23 18:39:08 +00001222 if (Arg *A = C.getArgs().getLastArg(options::OPT_autocomplete)) {
1223 // Print out all options that start with a given argument. This is used for
1224 // shell autocompletion.
1225 llvm::outs() << llvm::join(Opts->findByPrefix(A->getValue()), " ") << '\n';
1226 return false;
1227 }
1228
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001229 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
Michal Gorny7cfe4802016-10-10 12:23:40 +00001230 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(C.getArgs());
1231 switch (RLT) {
1232 case ToolChain::RLT_CompilerRT:
1233 llvm::outs() << TC.getCompilerRT(C.getArgs(), "builtins") << "\n";
1234 break;
1235 case ToolChain::RLT_Libgcc:
1236 llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
1237 break;
1238 }
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001239 return false;
1240 }
1241
Daniel Dunbar1b3ec3a2009-06-16 23:25:22 +00001242 if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
Douglas Katzmana34b7bf2015-06-30 19:32:57 +00001243 for (const Multilib &Multilib : TC.getMultilibs())
1244 llvm::outs() << Multilib << "\n";
Daniel Dunbar1b3ec3a2009-06-16 23:25:22 +00001245 return false;
1246 }
1247
Jonathan Roelofs2cea1be2014-02-12 03:21:20 +00001248 if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
Douglas Katzmana34b7bf2015-06-30 19:32:57 +00001249 for (const Multilib &Multilib : TC.getMultilibs()) {
Douglas Katzman6bbffc42015-06-25 18:51:37 +00001250 if (Multilib.gccSuffix().empty())
Jonathan Roelofs2cea1be2014-02-12 03:21:20 +00001251 llvm::outs() << ".\n";
1252 else {
Douglas Katzman6bbffc42015-06-25 18:51:37 +00001253 StringRef Suffix(Multilib.gccSuffix());
Jonathan Roelofs2cea1be2014-02-12 03:21:20 +00001254 assert(Suffix.front() == '/');
1255 llvm::outs() << Suffix.substr(1) << "\n";
1256 }
Jonathan Roelofs3fa96d82014-02-12 01:36:51 +00001257 }
Jonathan Roelofs0e7ec602014-02-12 01:29:25 +00001258 return false;
1259 }
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001260 return true;
1261}
1262
Douglas Katzmanfd528672015-06-11 15:05:22 +00001263// Display an action graph human-readably. Action A is the "sink" node
1264// and latest-occuring action. Traversal is in pre-order, visiting the
1265// inputs to each action before printing the action itself.
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001266static unsigned PrintActions1(const Compilation &C, Action *A,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001267 std::map<Action *, unsigned> &Ids) {
Douglas Katzmanfd528672015-06-11 15:05:22 +00001268 if (Ids.count(A)) // A was already visited.
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001269 return Ids[A];
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001270
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001271 std::string str;
1272 llvm::raw_string_ostream os(str);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001273
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001274 os << Action::getClassName(A->getKind()) << ", ";
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001275 if (InputAction *IA = dyn_cast<InputAction>(A)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001276 os << "\"" << IA->getInputArg().getValue() << "\"";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001277 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001278 os << '"' << BIA->getArchName() << '"' << ", {"
Nico Weber5a459f82016-02-23 19:30:43 +00001279 << PrintActions1(C, *BIA->input_begin(), Ids) << "}";
Samuel Antaod06239d2016-07-15 23:13:27 +00001280 } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
1281 bool IsFirst = true;
1282 OA->doOnEachDependence(
1283 [&](Action *A, const ToolChain *TC, const char *BoundArch) {
1284 // E.g. for two CUDA device dependences whose bound arch is sm_20 and
1285 // sm_35 this will generate:
1286 // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
1287 // (nvptx64-nvidia-cuda:sm_35) {#ID}
1288 if (!IsFirst)
1289 os << ", ";
1290 os << '"';
1291 if (TC)
1292 os << A->getOffloadingKindPrefix();
1293 else
1294 os << "host";
1295 os << " (";
1296 os << TC->getTriple().normalize();
1297
1298 if (BoundArch)
1299 os << ":" << BoundArch;
1300 os << ")";
1301 os << '"';
1302 os << " {" << PrintActions1(C, A, Ids) << "}";
1303 IsFirst = false;
1304 });
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001305 } else {
Samuel Antaod06239d2016-07-15 23:13:27 +00001306 const ActionList *AL = &A->getInputs();
Artem Belevich0ff05cd2015-07-13 23:27:56 +00001307
Artem Belevich23256752015-09-22 17:23:09 +00001308 if (AL->size()) {
1309 const char *Prefix = "{";
1310 for (Action *PreRequisite : *AL) {
1311 os << Prefix << PrintActions1(C, PreRequisite, Ids);
1312 Prefix = ", ";
1313 }
1314 os << "}";
1315 } else
1316 os << "{}";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001317 }
1318
Samuel Antaod06239d2016-07-15 23:13:27 +00001319 // Append offload info for all options other than the offloading action
1320 // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
1321 std::string offload_str;
1322 llvm::raw_string_ostream offload_os(offload_str);
1323 if (!isa<OffloadAction>(A)) {
1324 auto S = A->getOffloadingKindPrefix();
1325 if (!S.empty()) {
1326 offload_os << ", (" << S;
1327 if (A->getOffloadingArch())
1328 offload_os << ", " << A->getOffloadingArch();
1329 offload_os << ")";
1330 }
1331 }
1332
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001333 unsigned Id = Ids.size();
1334 Ids[A] = Id;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001335 llvm::errs() << Id << ": " << os.str() << ", "
Samuel Antaod06239d2016-07-15 23:13:27 +00001336 << types::getTypeName(A->getType()) << offload_os.str() << "\n";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001337
1338 return Id;
1339}
1340
Douglas Katzmanfd528672015-06-11 15:05:22 +00001341// Print the action graphs in a compilation C.
1342// For example "clang -c file1.c file2.c" is composed of two subgraphs.
Daniel Dunbareb843be2009-03-18 03:13:20 +00001343void Driver::PrintActions(const Compilation &C) const {
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001344 std::map<Action *, unsigned> Ids;
1345 for (Action *A : C.getActions())
1346 PrintActions1(C, A, Ids);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001347}
1348
Joerg Sonnenberger5fe4a7d2011-05-06 14:05:11 +00001349/// \brief Check whether the given input tree contains any compilation or
1350/// assembly actions.
1351static bool ContainsCompileOrAssembleAction(const Action *A) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001352 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
Bob Wilson23a55f12014-12-21 07:00:00 +00001353 isa<AssembleJobAction>(A))
Daniel Dunbar00d3d8e2010-06-29 16:38:33 +00001354 return true;
1355
Nico Weber5a459f82016-02-23 19:30:43 +00001356 for (const Action *Input : A->inputs())
Nico Weberfb80f962015-09-19 21:36:51 +00001357 if (ContainsCompileOrAssembleAction(Input))
Daniel Dunbar00d3d8e2010-06-29 16:38:33 +00001358 return true;
1359
1360 return false;
1361}
1362
Artem Belevich5e2a3ec2015-11-17 22:28:40 +00001363void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
1364 const InputList &BAInputs) const {
1365 DerivedArgList &Args = C.getArgs();
1366 ActionList &Actions = C.getActions();
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001367 llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
1368 // Collect the list of architectures. Duplicates are allowed, but should only
1369 // be handled once (in the order seen).
Daniel Dunbare5dc4822009-03-13 20:33:35 +00001370 llvm::StringSet<> ArchNames;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001371 SmallVector<const char *, 4> Archs;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00001372 for (Arg *A : Args) {
Daniel Dunbar0bfb21e2009-11-19 03:26:40 +00001373 if (A->getOption().matches(options::OPT_arch)) {
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001374 // Validate the option here; we don't save the type here because its
1375 // particular spelling may participate in other driver choices.
1376 llvm::Triple::ArchType Arch =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001377 tools::darwin::getArchTypeForMachOArchName(A->getValue());
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001378 if (Arch == llvm::Triple::UnknownArch) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001379 Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001380 continue;
1381 }
1382
Daniel Dunbar2da02722009-03-19 07:55:12 +00001383 A->claim();
David Blaikie61b86d42014-11-19 02:56:13 +00001384 if (ArchNames.insert(A->getValue()).second)
Richard Smithbd55daf2012-11-01 04:30:05 +00001385 Archs.push_back(A->getValue());
Daniel Dunbarf479c122009-03-12 18:40:18 +00001386 }
1387 }
1388
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001389 // When there is no explicit arch for this platform, make sure we still bind
1390 // the architecture (to the default) so that -Xarch_ is handled correctly.
Daniel Dunbareb843be2009-03-18 03:13:20 +00001391 if (!Archs.size())
Daniel Dunbarc3bd9f52012-11-08 03:38:26 +00001392 Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
Daniel Dunbarf479c122009-03-12 18:40:18 +00001393
Daniel Dunbarf479c122009-03-12 18:40:18 +00001394 ActionList SingleActions;
Justin Lebar0f3474c2016-02-11 02:00:50 +00001395 BuildActions(C, Args, BAInputs, SingleActions);
Daniel Dunbarf479c122009-03-12 18:40:18 +00001396
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001397 // Add in arch bindings for every top level action, as well as lipo and
1398 // dsymutil steps if needed.
Nico Weberfb80f962015-09-19 21:36:51 +00001399 for (Action* Act : SingleActions) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001400 // Make sure we can lipo this kind of output. If not (and it is an actual
1401 // output) then we disallow, since we can't create an output file with the
1402 // right name without overwriting it. We could remove this oddity by just
1403 // changing the output names to include the arch, which would also fix
Daniel Dunbarf479c122009-03-12 18:40:18 +00001404 // -save-temps. Compatibility wins for now.
1405
Daniel Dunbare2ca3bd2009-03-13 17:46:02 +00001406 if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
Daniel Dunbarf479c122009-03-12 18:40:18 +00001407 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001408 << types::getTypeName(Act->getType());
Daniel Dunbarf479c122009-03-12 18:40:18 +00001409
1410 ActionList Inputs;
Justin Lebar41094612016-01-11 23:07:27 +00001411 for (unsigned i = 0, e = Archs.size(); i != e; ++i)
1412 Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
Daniel Dunbarf479c122009-03-12 18:40:18 +00001413
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001414 // Lipo if necessary, we do it this way because we need to set the arch flag
1415 // so that -Xarch_ gets overwritten.
Daniel Dunbarf479c122009-03-12 18:40:18 +00001416 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
1417 Actions.append(Inputs.begin(), Inputs.end());
1418 else
Justin Lebar41094612016-01-11 23:07:27 +00001419 Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001420
Eric Christopher65c05fa2012-02-06 19:43:51 +00001421 // Handle debug info queries.
1422 Arg *A = Args.getLastArg(options::OPT_g_Group);
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001423 if (A && !A->getOption().matches(options::OPT_g0) &&
1424 !A->getOption().matches(options::OPT_gstabs) &&
1425 ContainsCompileOrAssembleAction(Actions.back())) {
Chad Rosier62135492012-07-09 17:31:28 +00001426
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001427 // Add a 'dsymutil' step if necessary, when debug info is enabled and we
1428 // have a compile input. We need to run 'dsymutil' ourselves in such cases
Eric Christopher776c26f2013-01-28 17:39:03 +00001429 // because the debug info will refer to a temporary object file which
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001430 // will be removed at the end of the compilation process.
1431 if (Act->getType() == types::TY_Image) {
1432 ActionList Inputs;
1433 Inputs.push_back(Actions.back());
1434 Actions.pop_back();
Justin Lebar41094612016-01-11 23:07:27 +00001435 Actions.push_back(
1436 C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001437 }
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001438
Ben Langmuir9b9a8d32014-02-06 18:53:25 +00001439 // Verify the debug info output.
Alp Tokere9d2bfc2014-01-17 02:06:23 +00001440 if (Args.hasArg(options::OPT_verify_debug_info)) {
Justin Lebar41094612016-01-11 23:07:27 +00001441 Action* LastAction = Actions.back();
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001442 Actions.pop_back();
Justin Lebar41094612016-01-11 23:07:27 +00001443 Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
1444 LastAction, types::TY_Nothing));
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001445 }
1446 }
Daniel Dunbarf479c122009-03-12 18:40:18 +00001447 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001448}
1449
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001450/// \brief Check that the file referenced by Value exists. If it doesn't,
1451/// issue a diagnostic and return false.
Alp Toker8c8a8752013-12-03 06:53:35 +00001452static bool DiagnoseInputExistence(const Driver &D, const DerivedArgList &Args,
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001453 StringRef Value, types::ID Ty) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001454 if (!D.getCheckInputsExist())
1455 return true;
1456
1457 // stdin always exists.
1458 if (Value == "-")
1459 return true;
1460
1461 SmallString<64> Path(Value);
1462 if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
Yaron Keren92e1b622015-03-18 10:17:07 +00001463 if (!llvm::sys::path::is_absolute(Path)) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001464 SmallString<64> Directory(WorkDir->getValue());
1465 llvm::sys::path::append(Directory, Value);
1466 Path.assign(Directory);
1467 }
1468 }
1469
1470 if (llvm::sys::fs::exists(Twine(Path)))
1471 return true;
1472
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001473 if (D.IsCLMode()) {
1474 if (!llvm::sys::path::is_absolute(Twine(Path)) &&
1475 llvm::sys::Process::FindInEnvPath("LIB", Value))
1476 return true;
1477
1478 if (Args.hasArg(options::OPT__SLASH_link) && Ty == types::TY_Object) {
1479 // Arguments to the /link flag might cause the linker to search for object
1480 // and library files in paths we don't know about. Don't error in such
1481 // cases.
1482 return true;
1483 }
1484 }
Hans Wennborg23d26a32014-06-18 17:21:50 +00001485
Yaron Keren92e1b622015-03-18 10:17:07 +00001486 D.Diag(clang::diag::err_drv_no_such_file) << Path;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001487 return false;
1488}
1489
Chad Rosierecdede82011-08-12 22:08:57 +00001490// Construct a the list of inputs and their types.
Hans Wennborg55362852014-05-02 22:55:30 +00001491void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
Chad Rosierecdede82011-08-12 22:08:57 +00001492 InputList &Inputs) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001493 // Track the current user specified (-x) input. We also explicitly track the
1494 // argument used to set the type; we only want to claim the type when we
1495 // actually use it, so we warn about unused -x arguments.
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00001496 types::ID InputType = types::TY_Nothing;
Craig Topper92fc2df2014-05-17 16:56:41 +00001497 Arg *InputTypeArg = nullptr;
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00001498
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001499 // The last /TC or /TP option sets the input type to C or C++ globally.
Ehsan Akhgaric249abb2014-09-12 21:44:24 +00001500 if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
1501 options::OPT__SLASH_TP)) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001502 InputTypeArg = TCTP;
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001503 InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001504 ? types::TY_C
1505 : types::TY_CXX;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001506
Richard Smith0aef3052017-02-18 01:14:43 +00001507 Arg *Previous = nullptr;
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001508 bool ShowNote = false;
Richard Smith0aef3052017-02-18 01:14:43 +00001509 for (Arg *A : Args.filtered(options::OPT__SLASH_TC, options::OPT__SLASH_TP)) {
1510 if (Previous) {
1511 Diag(clang::diag::warn_drv_overriding_flag_option)
1512 << Previous->getSpelling() << A->getSpelling();
1513 ShowNote = true;
1514 }
1515 Previous = A;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001516 }
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001517 if (ShowNote)
1518 Diag(clang::diag::note_drv_t_option_is_global);
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001519
1520 // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
1521 assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
1522 }
1523
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00001524 for (Arg *A : Args) {
Michael J. Spencerad3ccc32012-08-20 21:41:17 +00001525 if (A->getOption().getKind() == Option::InputClass) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001526 const char *Value = A->getValue();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001527 types::ID Ty = types::TY_INVALID;
1528
1529 // Infer the input type if necessary.
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00001530 if (InputType == types::TY_Nothing) {
1531 // If there was an explicit arg for this, claim it.
1532 if (InputTypeArg)
1533 InputTypeArg->claim();
1534
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001535 // stdin must be handled specially.
1536 if (memcmp(Value, "-", 2) == 0) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001537 // If running with -E, treat as a C input (this changes the builtin
1538 // macros, for example). This may be overridden by -ObjC below.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001539 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001540 // Otherwise emit an error but still use a valid type to avoid
1541 // spurious errors (e.g., no inputs).
Hans Wennborg70850d82013-07-18 20:29:38 +00001542 if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
Hans Wennborgcfdd8b52014-01-29 01:04:40 +00001543 Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
1544 : clang::diag::err_drv_unknown_stdin_type);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001545 Ty = types::TY_C;
1546 } else {
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00001547 // Otherwise lookup by extension.
1548 // Fallback is C if invoked as C preprocessor or Object otherwise.
1549 // We use a host hook here because Darwin at least has its own
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001550 // idea of what .s is.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001551 if (const char *Ext = strrchr(Value, '.'))
Daniel Dunbarcc7df6c2010-08-02 05:43:56 +00001552 Ty = TC.LookupTypeForExtension(Ext + 1);
Daniel Dunbarea9f0322009-03-20 23:39:23 +00001553
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00001554 if (Ty == types::TY_INVALID) {
Hans Wennborg70850d82013-07-18 20:29:38 +00001555 if (CCCIsCPP())
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00001556 Ty = types::TY_C;
1557 else
1558 Ty = types::TY_Object;
1559 }
Daniel Dunbar0ac94452010-02-17 20:32:58 +00001560
1561 // If the driver is invoked as C++ compiler (like clang++ or c++) it
1562 // should autodetect some input files as C++ for g++ compatibility.
Hans Wennborg70850d82013-07-18 20:29:38 +00001563 if (CCCIsCXX()) {
Daniel Dunbar0ac94452010-02-17 20:32:58 +00001564 types::ID OldTy = Ty;
1565 Ty = types::lookupCXXTypeForCType(Ty);
1566
1567 if (Ty != OldTy)
1568 Diag(clang::diag::warn_drv_treating_input_as_cxx)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001569 << getTypeName(OldTy) << getTypeName(Ty);
Daniel Dunbar0ac94452010-02-17 20:32:58 +00001570 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001571 }
1572
Daniel Dunbar82b22102009-05-18 21:47:54 +00001573 // -ObjC and -ObjC++ override the default language, but only for "source
1574 // files". We just treat everything that isn't a linker input as a
1575 // source file.
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001576 //
Daniel Dunbar82b22102009-05-18 21:47:54 +00001577 // FIXME: Clean this up if we move the phase sequence into the type.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001578 if (Ty != types::TY_Object) {
1579 if (Args.hasArg(options::OPT_ObjC))
1580 Ty = types::TY_ObjC;
1581 else if (Args.hasArg(options::OPT_ObjCXX))
1582 Ty = types::TY_ObjCXX;
1583 }
1584 } else {
1585 assert(InputTypeArg && "InputType set w/o InputTypeArg");
Ehsan Akhgari7e954ea2014-09-12 18:15:10 +00001586 if (!InputTypeArg->getOption().matches(options::OPT_x)) {
1587 // If emulating cl.exe, make sure that /TC and /TP don't affect input
1588 // object files.
1589 const char *Ext = strrchr(Value, '.');
1590 if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
1591 Ty = types::TY_Object;
1592 }
1593 if (Ty == types::TY_INVALID) {
1594 Ty = InputType;
1595 InputTypeArg->claim();
1596 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001597 }
1598
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001599 if (DiagnoseInputExistence(*this, Args, Value, Ty))
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001600 Inputs.push_back(std::make_pair(Ty, A));
1601
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001602 } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
1603 StringRef Value = A->getValue();
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001604 if (DiagnoseInputExistence(*this, Args, Value, types::TY_C)) {
David Blaikie0aaa7622017-01-13 17:34:15 +00001605 Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001606 Inputs.push_back(std::make_pair(types::TY_C, InputArg));
1607 }
1608 A->claim();
1609 } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
1610 StringRef Value = A->getValue();
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001611 if (DiagnoseInputExistence(*this, Args, Value, types::TY_CXX)) {
David Blaikie0aaa7622017-01-13 17:34:15 +00001612 Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001613 Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
1614 }
1615 A->claim();
Michael J. Spencer66e2b202012-10-19 22:37:06 +00001616 } else if (A->getOption().hasFlag(options::LinkerInput)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001617 // Just treat as object type, we could make a special type for this if
1618 // necessary.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001619 Inputs.push_back(std::make_pair(types::TY_Object, A));
1620
Daniel Dunbar0bfb21e2009-11-19 03:26:40 +00001621 } else if (A->getOption().matches(options::OPT_x)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001622 InputTypeArg = A;
Richard Smithbd55daf2012-11-01 04:30:05 +00001623 InputType = types::lookupTypeForTypeSpecifier(A->getValue());
Chad Rosier706c2352012-04-07 00:01:31 +00001624 A->claim();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001625
1626 // Follow gcc behavior and treat as linker input for invalid -x
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001627 // options. Its not clear why we shouldn't just revert to unknown; but
Michael J. Spencer1a4fe8c2010-12-17 21:22:33 +00001628 // this isn't very important, we might as well be bug compatible.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001629 if (!InputType) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001630 Diag(clang::diag::err_drv_unknown_language) << A->getValue();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001631 InputType = types::TY_Object;
1632 }
Hans Wennborg091f1b62017-01-27 17:09:41 +00001633 } else if (A->getOption().getID() == options::OPT__SLASH_U) {
1634 assert(A->getNumValues() == 1 && "The /U option has one value.");
1635 StringRef Val = A->getValue(0);
1636 if (Val.find_first_of("/\\") != StringRef::npos) {
1637 // Warn about e.g. "/Users/me/myfile.c".
1638 Diag(diag::warn_slash_u_filename) << Val;
1639 Diag(diag::note_use_dashdash);
1640 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001641 }
1642 }
Hans Wennborg70850d82013-07-18 20:29:38 +00001643 if (CCCIsCPP() && Inputs.empty()) {
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00001644 // If called as standalone preprocessor, stdin is processed
1645 // if no other input is present.
David Blaikie0aaa7622017-01-13 17:34:15 +00001646 Arg *A = MakeInputArg(Args, *Opts, "-");
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00001647 Inputs.push_back(std::make_pair(types::TY_C, A));
1648 }
Chad Rosierecdede82011-08-12 22:08:57 +00001649}
1650
Samuel Antao64e965e2016-09-30 15:34:19 +00001651namespace {
1652/// Provides a convenient interface for different programming models to generate
1653/// the required device actions.
1654class OffloadingActionBuilder final {
1655 /// Flag used to trace errors in the builder.
1656 bool IsValid = false;
1657
1658 /// The compilation that is using this builder.
1659 Compilation &C;
1660
Samuel Antao64e965e2016-09-30 15:34:19 +00001661 /// Map between an input argument and the offload kinds used to process it.
1662 std::map<const Arg *, unsigned> InputArgToOffloadKindMap;
1663
1664 /// Builder interface. It doesn't build anything or keep any state.
1665 class DeviceActionBuilder {
1666 public:
1667 typedef llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PhasesTy;
1668
1669 enum ActionBuilderReturnCode {
1670 // The builder acted successfully on the current action.
1671 ABRT_Success,
1672 // The builder didn't have to act on the current action.
1673 ABRT_Inactive,
1674 // The builder was successful and requested the host action to not be
1675 // generated.
1676 ABRT_Ignore_Host,
1677 };
1678
1679 protected:
1680 /// Compilation associated with this builder.
1681 Compilation &C;
1682
1683 /// Tool chains associated with this builder. The same programming
1684 /// model may have associated one or more tool chains.
1685 SmallVector<const ToolChain *, 2> ToolChains;
1686
1687 /// The derived arguments associated with this builder.
1688 DerivedArgList &Args;
1689
1690 /// The inputs associated with this builder.
1691 const Driver::InputList &Inputs;
1692
1693 /// The associated offload kind.
1694 Action::OffloadKind AssociatedOffloadKind = Action::OFK_None;
1695
1696 public:
1697 DeviceActionBuilder(Compilation &C, DerivedArgList &Args,
1698 const Driver::InputList &Inputs,
1699 Action::OffloadKind AssociatedOffloadKind)
1700 : C(C), Args(Args), Inputs(Inputs),
1701 AssociatedOffloadKind(AssociatedOffloadKind) {}
1702 virtual ~DeviceActionBuilder() {}
1703
1704 /// Fill up the array \a DA with all the device dependences that should be
1705 /// added to the provided host action \a HostAction. By default it is
1706 /// inactive.
1707 virtual ActionBuilderReturnCode
Samuel Antao28c4f182016-10-27 17:08:03 +00001708 getDeviceDependences(OffloadAction::DeviceDependences &DA,
1709 phases::ID CurPhase, phases::ID FinalPhase,
1710 PhasesTy &Phases) {
Samuel Antao64e965e2016-09-30 15:34:19 +00001711 return ABRT_Inactive;
1712 }
1713
1714 /// Update the state to include the provided host action \a HostAction as a
1715 /// dependency of the current device action. By default it is inactive.
1716 virtual ActionBuilderReturnCode addDeviceDepences(Action *HostAction) {
1717 return ABRT_Inactive;
1718 }
1719
1720 /// Append top level actions generated by the builder. Return true if errors
1721 /// were found.
1722 virtual void appendTopLevelActions(ActionList &AL) {}
1723
1724 /// Append linker actions generated by the builder. Return true if errors
1725 /// were found.
1726 virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {}
1727
1728 /// Initialize the builder. Return true if any initialization errors are
1729 /// found.
1730 virtual bool initialize() { return false; }
1731
Samuel Antao69d6f312016-10-27 17:50:43 +00001732 /// Return true if the builder can use bundling/unbundling.
1733 virtual bool canUseBundlerUnbundler() const { return false; }
1734
Samuel Antao64e965e2016-09-30 15:34:19 +00001735 /// Return true if this builder is valid. We have a valid builder if we have
1736 /// associated device tool chains.
1737 bool isValid() { return !ToolChains.empty(); }
1738
1739 /// Return the associated offload kind.
1740 Action::OffloadKind getAssociatedOffloadKind() {
1741 return AssociatedOffloadKind;
1742 }
1743 };
1744
1745 /// \brief CUDA action builder. It injects device code in the host backend
1746 /// action.
1747 class CudaActionBuilder final : public DeviceActionBuilder {
1748 /// Flags to signal if the user requested host-only or device-only
1749 /// compilation.
1750 bool CompileHostOnly = false;
1751 bool CompileDeviceOnly = false;
1752
1753 /// List of GPU architectures to use in this compilation.
1754 SmallVector<CudaArch, 4> GpuArchList;
1755
1756 /// The CUDA actions for the current input.
1757 ActionList CudaDeviceActions;
1758
1759 /// The CUDA fat binary if it was generated for the current input.
1760 Action *CudaFatBinary = nullptr;
1761
1762 /// Flag that is set to true if this builder acted on the current input.
1763 bool IsActive = false;
1764
1765 public:
1766 CudaActionBuilder(Compilation &C, DerivedArgList &Args,
1767 const Driver::InputList &Inputs)
1768 : DeviceActionBuilder(C, Args, Inputs, Action::OFK_Cuda) {}
1769
1770 ActionBuilderReturnCode
Samuel Antao28c4f182016-10-27 17:08:03 +00001771 getDeviceDependences(OffloadAction::DeviceDependences &DA,
1772 phases::ID CurPhase, phases::ID FinalPhase,
1773 PhasesTy &Phases) override {
Samuel Antao64e965e2016-09-30 15:34:19 +00001774 if (!IsActive)
1775 return ABRT_Inactive;
1776
1777 // If we don't have more CUDA actions, we don't have any dependences to
1778 // create for the host.
1779 if (CudaDeviceActions.empty())
1780 return ABRT_Success;
1781
1782 assert(CudaDeviceActions.size() == GpuArchList.size() &&
1783 "Expecting one action per GPU architecture.");
1784 assert(!CompileHostOnly &&
1785 "Not expecting CUDA actions in host-only compilation.");
1786
1787 // If we are generating code for the device or we are in a backend phase,
1788 // we attempt to generate the fat binary. We compile each arch to ptx and
1789 // assemble to cubin, then feed the cubin *and* the ptx into a device
1790 // "link" action, which uses fatbinary to combine these cubins into one
1791 // fatbin. The fatbin is then an input to the host action if not in
1792 // device-only mode.
1793 if (CompileDeviceOnly || CurPhase == phases::Backend) {
1794 ActionList DeviceActions;
1795 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
1796 // Produce the device action from the current phase up to the assemble
1797 // phase.
1798 for (auto Ph : Phases) {
1799 // Skip the phases that were already dealt with.
1800 if (Ph < CurPhase)
1801 continue;
1802 // We have to be consistent with the host final phase.
1803 if (Ph > FinalPhase)
1804 break;
1805
1806 CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction(
1807 C, Args, Ph, CudaDeviceActions[I]);
1808
1809 if (Ph == phases::Assemble)
1810 break;
1811 }
1812
1813 // If we didn't reach the assemble phase, we can't generate the fat
1814 // binary. We don't need to generate the fat binary if we are not in
1815 // device-only mode.
1816 if (!isa<AssembleJobAction>(CudaDeviceActions[I]) ||
1817 CompileDeviceOnly)
1818 continue;
1819
1820 Action *AssembleAction = CudaDeviceActions[I];
1821 assert(AssembleAction->getType() == types::TY_Object);
1822 assert(AssembleAction->getInputs().size() == 1);
1823
1824 Action *BackendAction = AssembleAction->getInputs()[0];
1825 assert(BackendAction->getType() == types::TY_PP_Asm);
1826
1827 for (auto &A : {AssembleAction, BackendAction}) {
1828 OffloadAction::DeviceDependences DDep;
1829 DDep.add(*A, *ToolChains.front(), CudaArchToString(GpuArchList[I]),
1830 Action::OFK_Cuda);
1831 DeviceActions.push_back(
1832 C.MakeAction<OffloadAction>(DDep, A->getType()));
1833 }
1834 }
1835
1836 // We generate the fat binary if we have device input actions.
1837 if (!DeviceActions.empty()) {
1838 CudaFatBinary =
1839 C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN);
1840
1841 if (!CompileDeviceOnly) {
1842 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
1843 Action::OFK_Cuda);
1844 // Clear the fat binary, it is already a dependence to an host
1845 // action.
1846 CudaFatBinary = nullptr;
1847 }
1848
1849 // Remove the CUDA actions as they are already connected to an host
1850 // action or fat binary.
1851 CudaDeviceActions.clear();
1852 }
1853
1854 // We avoid creating host action in device-only mode.
1855 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
Samuel Antao5b1a89a2016-10-27 00:53:34 +00001856 } else if (CurPhase > phases::Backend) {
1857 // If we are past the backend phase and still have a device action, we
1858 // don't have to do anything as this action is already a device
1859 // top-level action.
1860 return ABRT_Success;
Samuel Antao64e965e2016-09-30 15:34:19 +00001861 }
1862
1863 assert(CurPhase < phases::Backend && "Generating single CUDA "
1864 "instructions should only occur "
1865 "before the backend phase!");
1866
1867 // By default, we produce an action for each device arch.
1868 for (Action *&A : CudaDeviceActions)
1869 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
1870
1871 return ABRT_Success;
1872 }
1873
1874 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
1875 // While generating code for CUDA, we only depend on the host input action
1876 // to trigger the creation of all the CUDA device actions.
1877
1878 // If we are dealing with an input action, replicate it for each GPU
1879 // architecture. If we are in host-only mode we return 'success' so that
1880 // the host uses the CUDA offload kind.
1881 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
1882 assert(!GpuArchList.empty() &&
1883 "We should have at least one GPU architecture.");
1884
1885 // If the host input is not CUDA, we don't need to bother about this
1886 // input.
1887 if (IA->getType() != types::TY_CUDA) {
1888 // The builder will ignore this input.
1889 IsActive = false;
1890 return ABRT_Inactive;
1891 }
1892
1893 // Set the flag to true, so that the builder acts on the current input.
1894 IsActive = true;
1895
1896 if (CompileHostOnly)
1897 return ABRT_Success;
1898
1899 // Replicate inputs for each GPU architecture.
1900 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
1901 CudaDeviceActions.push_back(C.MakeAction<InputAction>(
1902 IA->getInputArg(), types::TY_CUDA_DEVICE));
1903
1904 return ABRT_Success;
1905 }
1906
1907 return IsActive ? ABRT_Success : ABRT_Inactive;
1908 }
1909
1910 void appendTopLevelActions(ActionList &AL) override {
1911 // Utility to append actions to the top level list.
1912 auto AddTopLevel = [&](Action *A, CudaArch BoundArch) {
1913 OffloadAction::DeviceDependences Dep;
1914 Dep.add(*A, *ToolChains.front(), CudaArchToString(BoundArch),
1915 Action::OFK_Cuda);
1916 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
1917 };
1918
1919 // If we have a fat binary, add it to the list.
1920 if (CudaFatBinary) {
1921 AddTopLevel(CudaFatBinary, CudaArch::UNKNOWN);
1922 CudaDeviceActions.clear();
1923 CudaFatBinary = nullptr;
1924 return;
1925 }
1926
1927 if (CudaDeviceActions.empty())
1928 return;
1929
1930 // If we have CUDA actions at this point, that's because we have a have
1931 // partial compilation, so we should have an action for each GPU
1932 // architecture.
1933 assert(CudaDeviceActions.size() == GpuArchList.size() &&
1934 "Expecting one action per GPU architecture.");
1935 assert(ToolChains.size() == 1 &&
1936 "Expecting to have a sing CUDA toolchain.");
1937 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
1938 AddTopLevel(CudaDeviceActions[I], GpuArchList[I]);
1939
1940 CudaDeviceActions.clear();
1941 }
1942
1943 bool initialize() override {
1944 // We don't need to support CUDA.
1945 if (!C.hasOffloadToolChain<Action::OFK_Cuda>())
1946 return false;
1947
1948 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
1949 assert(HostTC && "No toolchain for host compilation.");
1950 if (HostTC->getTriple().isNVPTX()) {
1951 // We do not support targeting NVPTX for host compilation. Throw
1952 // an error and abort pipeline construction early so we don't trip
1953 // asserts that assume device-side compilation.
1954 C.getDriver().Diag(diag::err_drv_cuda_nvptx_host);
1955 return true;
1956 }
1957
1958 ToolChains.push_back(C.getSingleOffloadToolChain<Action::OFK_Cuda>());
1959
1960 Arg *PartialCompilationArg = Args.getLastArg(
1961 options::OPT_cuda_host_only, options::OPT_cuda_device_only,
1962 options::OPT_cuda_compile_host_device);
1963 CompileHostOnly = PartialCompilationArg &&
1964 PartialCompilationArg->getOption().matches(
1965 options::OPT_cuda_host_only);
1966 CompileDeviceOnly = PartialCompilationArg &&
1967 PartialCompilationArg->getOption().matches(
1968 options::OPT_cuda_device_only);
1969
1970 // Collect all cuda_gpu_arch parameters, removing duplicates.
Artem Belevicha424e882016-12-09 22:59:17 +00001971 std::set<CudaArch> GpuArchs;
Samuel Antao64e965e2016-09-30 15:34:19 +00001972 bool Error = false;
1973 for (Arg *A : Args) {
Artem Belevicha424e882016-12-09 22:59:17 +00001974 if (!(A->getOption().matches(options::OPT_cuda_gpu_arch_EQ) ||
1975 A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ)))
Samuel Antao64e965e2016-09-30 15:34:19 +00001976 continue;
1977 A->claim();
1978
Artem Belevicha424e882016-12-09 22:59:17 +00001979 const StringRef ArchStr = A->getValue();
1980 if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ) &&
1981 ArchStr == "all") {
1982 GpuArchs.clear();
1983 continue;
1984 }
Samuel Antao64e965e2016-09-30 15:34:19 +00001985 CudaArch Arch = StringToCudaArch(ArchStr);
1986 if (Arch == CudaArch::UNKNOWN) {
1987 C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
1988 Error = true;
Artem Belevicha424e882016-12-09 22:59:17 +00001989 } else if (A->getOption().matches(options::OPT_cuda_gpu_arch_EQ))
1990 GpuArchs.insert(Arch);
1991 else if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ))
1992 GpuArchs.erase(Arch);
1993 else
1994 llvm_unreachable("Unexpected option.");
Samuel Antao64e965e2016-09-30 15:34:19 +00001995 }
1996
Artem Belevicha424e882016-12-09 22:59:17 +00001997 // Collect list of GPUs remaining in the set.
1998 for (CudaArch Arch : GpuArchs)
1999 GpuArchList.push_back(Arch);
2000
2001 // Default to sm_20 which is the lowest common denominator for
2002 // supported GPUs. sm_20 code should work correctly, if
2003 // suboptimally, on all newer GPUs.
Samuel Antao64e965e2016-09-30 15:34:19 +00002004 if (GpuArchList.empty())
2005 GpuArchList.push_back(CudaArch::SM_20);
2006
2007 return Error;
2008 }
2009 };
2010
Samuel Antao28c4f182016-10-27 17:08:03 +00002011 /// OpenMP action builder. The host bitcode is passed to the device frontend
2012 /// and all the device linked images are passed to the host link phase.
2013 class OpenMPActionBuilder final : public DeviceActionBuilder {
2014 /// The OpenMP actions for the current input.
2015 ActionList OpenMPDeviceActions;
2016
2017 /// The linker inputs obtained for each toolchain.
2018 SmallVector<ActionList, 8> DeviceLinkerInputs;
2019
2020 public:
2021 OpenMPActionBuilder(Compilation &C, DerivedArgList &Args,
2022 const Driver::InputList &Inputs)
2023 : DeviceActionBuilder(C, Args, Inputs, Action::OFK_OpenMP) {}
2024
2025 ActionBuilderReturnCode
2026 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2027 phases::ID CurPhase, phases::ID FinalPhase,
2028 PhasesTy &Phases) override {
2029
2030 // We should always have an action for each input.
2031 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2032 "Number of OpenMP actions and toolchains do not match.");
2033
2034 // The host only depends on device action in the linking phase, when all
2035 // the device images have to be embedded in the host image.
2036 if (CurPhase == phases::Link) {
2037 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2038 "Toolchains and linker inputs sizes do not match.");
2039 auto LI = DeviceLinkerInputs.begin();
2040 for (auto *A : OpenMPDeviceActions) {
2041 LI->push_back(A);
2042 ++LI;
2043 }
2044
2045 // We passed the device action as a host dependence, so we don't need to
2046 // do anything else with them.
2047 OpenMPDeviceActions.clear();
2048 return ABRT_Success;
2049 }
2050
2051 // By default, we produce an action for each device arch.
2052 for (Action *&A : OpenMPDeviceActions)
2053 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2054
2055 return ABRT_Success;
2056 }
2057
2058 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2059
2060 // If this is an input action replicate it for each OpenMP toolchain.
2061 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2062 OpenMPDeviceActions.clear();
2063 for (unsigned I = 0; I < ToolChains.size(); ++I)
2064 OpenMPDeviceActions.push_back(
2065 C.MakeAction<InputAction>(IA->getInputArg(), IA->getType()));
2066 return ABRT_Success;
2067 }
2068
Samuel Antaofab4f372016-10-27 18:00:51 +00002069 // If this is an unbundling action use it as is for each OpenMP toolchain.
2070 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2071 OpenMPDeviceActions.clear();
2072 for (unsigned I = 0; I < ToolChains.size(); ++I) {
2073 OpenMPDeviceActions.push_back(UA);
2074 UA->registerDependentActionInfo(
2075 ToolChains[I], /*BoundArch=*/StringRef(), Action::OFK_OpenMP);
2076 }
2077 return ABRT_Success;
2078 }
2079
Samuel Antao28c4f182016-10-27 17:08:03 +00002080 // When generating code for OpenMP we use the host compile phase result as
2081 // a dependence to the device compile phase so that it can learn what
2082 // declarations should be emitted. However, this is not the only use for
2083 // the host action, so we prevent it from being collapsed.
2084 if (isa<CompileJobAction>(HostAction)) {
2085 HostAction->setCannotBeCollapsedWithNextDependentAction();
2086 assert(ToolChains.size() == OpenMPDeviceActions.size() &&
2087 "Toolchains and device action sizes do not match.");
2088 OffloadAction::HostDependence HDep(
2089 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2090 /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2091 auto TC = ToolChains.begin();
2092 for (Action *&A : OpenMPDeviceActions) {
2093 assert(isa<CompileJobAction>(A));
2094 OffloadAction::DeviceDependences DDep;
2095 DDep.add(*A, **TC, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2096 A = C.MakeAction<OffloadAction>(HDep, DDep);
2097 ++TC;
2098 }
2099 }
2100 return ABRT_Success;
2101 }
2102
Samuel Antao69d6f312016-10-27 17:50:43 +00002103 void appendTopLevelActions(ActionList &AL) override {
2104 if (OpenMPDeviceActions.empty())
2105 return;
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 // Append all device actions followed by the proper offload action.
2112 auto TI = ToolChains.begin();
2113 for (auto *A : OpenMPDeviceActions) {
2114 OffloadAction::DeviceDependences Dep;
2115 Dep.add(*A, **TI, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2116 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2117 ++TI;
2118 }
2119 // We no longer need the action stored in this builder.
2120 OpenMPDeviceActions.clear();
2121 }
2122
Samuel Antao28c4f182016-10-27 17:08:03 +00002123 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {
2124 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2125 "Toolchains and linker inputs sizes do not match.");
2126
2127 // Append a new link action for each device.
2128 auto TC = ToolChains.begin();
2129 for (auto &LI : DeviceLinkerInputs) {
2130 auto *DeviceLinkAction =
2131 C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2132 DA.add(*DeviceLinkAction, **TC, /*BoundArch=*/nullptr,
2133 Action::OFK_OpenMP);
2134 ++TC;
2135 }
2136 }
2137
2138 bool initialize() override {
2139 // Get the OpenMP toolchains. If we don't get any, the action builder will
2140 // know there is nothing to do related to OpenMP offloading.
2141 auto OpenMPTCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
2142 for (auto TI = OpenMPTCRange.first, TE = OpenMPTCRange.second; TI != TE;
2143 ++TI)
2144 ToolChains.push_back(TI->second);
2145
2146 DeviceLinkerInputs.resize(ToolChains.size());
2147 return false;
2148 }
Samuel Antao69d6f312016-10-27 17:50:43 +00002149
2150 bool canUseBundlerUnbundler() const override {
2151 // OpenMP should use bundled files whenever possible.
2152 return true;
2153 }
Samuel Antao28c4f182016-10-27 17:08:03 +00002154 };
2155
2156 ///
2157 /// TODO: Add the implementation for other specialized builders here.
2158 ///
Samuel Antao64e965e2016-09-30 15:34:19 +00002159
2160 /// Specialized builders being used by this offloading action builder.
2161 SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders;
2162
Samuel Antao69d6f312016-10-27 17:50:43 +00002163 /// Flag set to true if all valid builders allow file bundling/unbundling.
2164 bool CanUseBundler;
2165
Samuel Antao64e965e2016-09-30 15:34:19 +00002166public:
2167 OffloadingActionBuilder(Compilation &C, DerivedArgList &Args,
2168 const Driver::InputList &Inputs)
Samuel Antao10e905c2016-10-27 01:08:58 +00002169 : C(C) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002170 // Create a specialized builder for each device toolchain.
2171
2172 IsValid = true;
2173
2174 // Create a specialized builder for CUDA.
2175 SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs));
2176
Samuel Antao28c4f182016-10-27 17:08:03 +00002177 // Create a specialized builder for OpenMP.
2178 SpecializedBuilders.push_back(new OpenMPActionBuilder(C, Args, Inputs));
2179
Samuel Antao64e965e2016-09-30 15:34:19 +00002180 //
2181 // TODO: Build other specialized builders here.
2182 //
2183
Samuel Antao69d6f312016-10-27 17:50:43 +00002184 // Initialize all the builders, keeping track of errors. If all valid
2185 // builders agree that we can use bundling, set the flag to true.
2186 unsigned ValidBuilders = 0u;
2187 unsigned ValidBuildersSupportingBundling = 0u;
2188 for (auto *SB : SpecializedBuilders) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002189 IsValid = IsValid && !SB->initialize();
Samuel Antao69d6f312016-10-27 17:50:43 +00002190
2191 // Update the counters if the builder is valid.
2192 if (SB->isValid()) {
2193 ++ValidBuilders;
2194 if (SB->canUseBundlerUnbundler())
2195 ++ValidBuildersSupportingBundling;
2196 }
2197 }
2198 CanUseBundler =
2199 ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling;
Artem Belevichf981e30b2016-08-02 22:37:47 +00002200 }
Justin Lebardc3c5042016-04-19 02:27:07 +00002201
Samuel Antao64e965e2016-09-30 15:34:19 +00002202 ~OffloadingActionBuilder() {
2203 for (auto *SB : SpecializedBuilders)
2204 delete SB;
Samuel Antaod06239d2016-07-15 23:13:27 +00002205 }
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002206
Samuel Antao64e965e2016-09-30 15:34:19 +00002207 /// Generate an action that adds device dependences (if any) to a host action.
2208 /// If no device dependence actions exist, just return the host action \a
2209 /// HostAction. If an error is found or if no builder requires the host action
2210 /// to be generated, return nullptr.
2211 Action *
2212 addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg,
2213 phases::ID CurPhase, phases::ID FinalPhase,
2214 DeviceActionBuilder::PhasesTy &Phases) {
2215 if (!IsValid)
2216 return nullptr;
Justin Lebar7bf77982016-01-11 23:27:13 +00002217
Samuel Antao64e965e2016-09-30 15:34:19 +00002218 if (SpecializedBuilders.empty())
2219 return HostAction;
2220
2221 assert(HostAction && "Invalid host action!");
2222
2223 OffloadAction::DeviceDependences DDeps;
2224 // Check if all the programming models agree we should not emit the host
2225 // action. Also, keep track of the offloading kinds employed.
2226 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2227 unsigned InactiveBuilders = 0u;
2228 unsigned IgnoringBuilders = 0u;
2229 for (auto *SB : SpecializedBuilders) {
2230 if (!SB->isValid()) {
2231 ++InactiveBuilders;
2232 continue;
2233 }
2234
Samuel Antao28c4f182016-10-27 17:08:03 +00002235 auto RetCode =
2236 SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases);
Samuel Antao64e965e2016-09-30 15:34:19 +00002237
2238 // If the builder explicitly says the host action should be ignored,
2239 // we need to increment the variable that tracks the builders that request
2240 // the host object to be ignored.
2241 if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host)
2242 ++IgnoringBuilders;
2243
2244 // Unless the builder was inactive for this action, we have to record the
2245 // offload kind because the host will have to use it.
2246 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2247 OffloadKind |= SB->getAssociatedOffloadKind();
2248 }
2249
2250 // If all builders agree that the host object should be ignored, just return
2251 // nullptr.
2252 if (IgnoringBuilders &&
2253 SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders))
2254 return nullptr;
2255
2256 if (DDeps.getActions().empty())
2257 return HostAction;
2258
2259 // We have dependences we need to bundle together. We use an offload action
2260 // for that.
2261 OffloadAction::HostDependence HDep(
2262 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2263 /*BoundArch=*/nullptr, DDeps);
2264 return C.MakeAction<OffloadAction>(HDep, DDeps);
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002265 }
2266
Samuel Antao64e965e2016-09-30 15:34:19 +00002267 /// Generate an action that adds a host dependence to a device action. The
2268 /// results will be kept in this action builder. Return true if an error was
2269 /// found.
Samuel Antaofab4f372016-10-27 18:00:51 +00002270 bool addHostDependenceToDeviceActions(Action *&HostAction,
Samuel Antao64e965e2016-09-30 15:34:19 +00002271 const Arg *InputArg) {
2272 if (!IsValid)
2273 return true;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002274
Samuel Antaofab4f372016-10-27 18:00:51 +00002275 // If we are supporting bundling/unbundling and the current action is an
2276 // input action of non-source file, we replace the host action by the
2277 // unbundling action. The bundler tool has the logic to detect if an input
2278 // is a bundle or not and if the input is not a bundle it assumes it is a
2279 // host file. Therefore it is safe to create an unbundling action even if
2280 // the input is not a bundle.
2281 if (CanUseBundler && isa<InputAction>(HostAction) &&
2282 InputArg->getOption().getKind() == llvm::opt::Option::InputClass &&
2283 !types::isSrcFile(HostAction->getType())) {
2284 auto UnbundlingHostAction =
2285 C.MakeAction<OffloadUnbundlingJobAction>(HostAction);
2286 UnbundlingHostAction->registerDependentActionInfo(
2287 C.getSingleOffloadToolChain<Action::OFK_Host>(),
2288 /*BoundArch=*/StringRef(), Action::OFK_Host);
2289 HostAction = UnbundlingHostAction;
2290 }
2291
Samuel Antao64e965e2016-09-30 15:34:19 +00002292 assert(HostAction && "Invalid host action!");
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002293
Samuel Antao64e965e2016-09-30 15:34:19 +00002294 // Register the offload kinds that are used.
2295 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2296 for (auto *SB : SpecializedBuilders) {
2297 if (!SB->isValid())
2298 continue;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002299
Samuel Antao64e965e2016-09-30 15:34:19 +00002300 auto RetCode = SB->addDeviceDepences(HostAction);
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002301
Samuel Antao64e965e2016-09-30 15:34:19 +00002302 // Host dependences for device actions are not compatible with that same
2303 // action being ignored.
2304 assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host &&
2305 "Host dependence not expected to be ignored.!");
Samuel Antaod06239d2016-07-15 23:13:27 +00002306
Samuel Antao64e965e2016-09-30 15:34:19 +00002307 // Unless the builder was inactive for this action, we have to record the
2308 // offload kind because the host will have to use it.
2309 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2310 OffloadKind |= SB->getAssociatedOffloadKind();
2311 }
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002312
Samuel Antao64e965e2016-09-30 15:34:19 +00002313 return false;
2314 }
2315
Samuel Antao69d6f312016-10-27 17:50:43 +00002316 /// Add the offloading top level actions to the provided action list. This
2317 /// function can replace the host action by a bundling action if the
2318 /// programming models allow it.
Samuel Antao64e965e2016-09-30 15:34:19 +00002319 bool appendTopLevelActions(ActionList &AL, Action *HostAction,
2320 const Arg *InputArg) {
Samuel Antao69d6f312016-10-27 17:50:43 +00002321 // Get the device actions to be appended.
2322 ActionList OffloadAL;
Samuel Antao64e965e2016-09-30 15:34:19 +00002323 for (auto *SB : SpecializedBuilders) {
2324 if (!SB->isValid())
2325 continue;
Samuel Antao69d6f312016-10-27 17:50:43 +00002326 SB->appendTopLevelActions(OffloadAL);
Samuel Antao64e965e2016-09-30 15:34:19 +00002327 }
2328
Samuel Antao69d6f312016-10-27 17:50:43 +00002329 // If we can use the bundler, replace the host action by the bundling one in
2330 // the resulting list. Otherwise, just append the device actions.
2331 if (CanUseBundler && !OffloadAL.empty()) {
2332 // Add the host action to the list in order to create the bundling action.
2333 OffloadAL.push_back(HostAction);
2334
2335 // We expect that the host action was just appended to the action list
2336 // before this method was called.
2337 assert(HostAction == AL.back() && "Host action not in the list??");
2338 HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL);
2339 AL.back() = HostAction;
2340 } else
2341 AL.append(OffloadAL.begin(), OffloadAL.end());
2342
Samuel Antao64e965e2016-09-30 15:34:19 +00002343 // Propagate to the current host action (if any) the offload information
2344 // associated with the current input.
2345 if (HostAction)
2346 HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg],
2347 /*BoundArch=*/nullptr);
Samuel Antao64e965e2016-09-30 15:34:19 +00002348 return false;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002349 }
Artem Belevich5bde4e02015-07-20 20:02:54 +00002350
Samuel Antao64e965e2016-09-30 15:34:19 +00002351 /// Processes the host linker action. This currently consists of replacing it
2352 /// with an offload action if there are device link objects and propagate to
2353 /// the host action all the offload kinds used in the current compilation. The
2354 /// resulting action is returned.
2355 Action *processHostLinkAction(Action *HostAction) {
2356 // Add all the dependences from the device linking actions.
2357 OffloadAction::DeviceDependences DDeps;
2358 for (auto *SB : SpecializedBuilders) {
2359 if (!SB->isValid())
2360 continue;
Justin Lebar21e5d4f2016-01-14 21:41:27 +00002361
Samuel Antao64e965e2016-09-30 15:34:19 +00002362 SB->appendLinkDependences(DDeps);
Justin Lebar21e5d4f2016-01-14 21:41:27 +00002363 }
Samuel Antaod06239d2016-07-15 23:13:27 +00002364
Samuel Antao64e965e2016-09-30 15:34:19 +00002365 // Calculate all the offload kinds used in the current compilation.
2366 unsigned ActiveOffloadKinds = 0u;
2367 for (auto &I : InputArgToOffloadKindMap)
2368 ActiveOffloadKinds |= I.second;
2369
2370 // If we don't have device dependencies, we don't have to create an offload
2371 // action.
2372 if (DDeps.getActions().empty()) {
2373 // Propagate all the active kinds to host action. Given that it is a link
2374 // action it is assumed to depend on all actions generated so far.
2375 HostAction->propagateHostOffloadInfo(ActiveOffloadKinds,
2376 /*BoundArch=*/nullptr);
2377 return HostAction;
2378 }
2379
2380 // Create the offload action with all dependences. When an offload action
2381 // is created the kinds are propagated to the host action, so we don't have
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002382 // to do that explicitly here.
Samuel Antao64e965e2016-09-30 15:34:19 +00002383 OffloadAction::HostDependence HDep(
2384 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2385 /*BoundArch*/ nullptr, ActiveOffloadKinds);
2386 return C.MakeAction<OffloadAction>(HDep, DDeps);
2387 }
2388};
2389} // anonymous namespace.
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002390
Justin Lebar0f3474c2016-02-11 02:00:50 +00002391void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
2392 const InputList &Inputs, ActionList &Actions) const {
Chad Rosierecdede82011-08-12 22:08:57 +00002393 llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00002394
Daniel Dunbar34c41872009-03-13 00:17:48 +00002395 if (!SuppressMissingInputWarning && Inputs.empty()) {
Daniel Dunbarbfeec742009-03-12 23:55:14 +00002396 Diag(clang::diag::err_drv_no_input_files);
2397 return;
2398 }
2399
Chad Rosier7742b5d2011-07-27 23:36:45 +00002400 Arg *FinalPhaseArg;
2401 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
Daniel Dunbarbfeec742009-03-12 23:55:14 +00002402
Bob Haarmanaaf51912017-02-27 19:40:19 +00002403 if (FinalPhase == phases::Link) {
2404 if (Args.hasArg(options::OPT_emit_llvm))
2405 Diag(clang::diag::err_drv_emit_llvm_link);
2406 if (IsCLMode() && LTOMode != LTOK_None &&
2407 !Args.getLastArgValue(options::OPT_fuse_ld_EQ).equals_lower("lld"))
2408 Diag(clang::diag::err_drv_lto_without_lld);
Rafael Espindolae8025642013-08-25 14:27:09 +00002409 }
2410
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002411 // Reject -Z* at the top level, these options should never have been exposed
2412 // by gcc.
Daniel Dunbardd765242009-03-26 16:12:09 +00002413 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
Daniel Dunbar0e759942009-03-20 06:14:23 +00002414 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
Daniel Dunbarbfeec742009-03-12 23:55:14 +00002415
Hans Wennborg13b7fe72013-08-12 23:26:25 +00002416 // Diagnose misuse of /Fo.
2417 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
Hans Wennborg13b7fe72013-08-12 23:26:25 +00002418 StringRef V = A->getValue();
Hans Wennborg61647532014-11-17 19:16:36 +00002419 if (Inputs.size() > 1 && !V.empty() &&
2420 !llvm::sys::path::is_separator(V.back())) {
Hans Wennborg13b7fe72013-08-12 23:26:25 +00002421 // Check whether /Fo tries to name an output file for multiple inputs.
Hans Wennborg9c1659b2013-10-18 22:49:04 +00002422 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002423 << A->getSpelling() << V;
Hans Wennborg13b7fe72013-08-12 23:26:25 +00002424 Args.eraseArg(options::OPT__SLASH_Fo);
2425 }
2426 }
2427
Hans Wennborg9c1659b2013-10-18 22:49:04 +00002428 // Diagnose misuse of /Fa.
2429 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
2430 StringRef V = A->getValue();
Hans Wennborg61647532014-11-17 19:16:36 +00002431 if (Inputs.size() > 1 && !V.empty() &&
2432 !llvm::sys::path::is_separator(V.back())) {
Hans Wennborg9c1659b2013-10-18 22:49:04 +00002433 // Check whether /Fa tries to name an asm file for multiple inputs.
2434 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002435 << A->getSpelling() << V;
Hans Wennborg9c1659b2013-10-18 22:49:04 +00002436 Args.eraseArg(options::OPT__SLASH_Fa);
2437 }
2438 }
2439
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00002440 // Diagnose misuse of /o.
2441 if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
2442 if (A->getValue()[0] == '\0') {
2443 // It has to have a value.
2444 Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
2445 Args.eraseArg(options::OPT__SLASH_o);
2446 }
2447 }
2448
Nico Weber2ca4be92016-03-01 23:16:44 +00002449 // Diagnose unsupported forms of /Yc /Yu. Ignore /Yc/Yu for now if:
2450 // * no filename after it
2451 // * both /Yc and /Yu passed but with different filenames
2452 // * corresponding file not also passed as /FI
2453 Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
2454 Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
2455 if (YcArg && YcArg->getValue()[0] == '\0') {
2456 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YcArg->getSpelling();
2457 Args.eraseArg(options::OPT__SLASH_Yc);
2458 YcArg = nullptr;
2459 }
2460 if (YuArg && YuArg->getValue()[0] == '\0') {
2461 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YuArg->getSpelling();
2462 Args.eraseArg(options::OPT__SLASH_Yu);
2463 YuArg = nullptr;
2464 }
2465 if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
2466 Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
2467 Args.eraseArg(options::OPT__SLASH_Yc);
2468 Args.eraseArg(options::OPT__SLASH_Yu);
2469 YcArg = YuArg = nullptr;
2470 }
2471 if (YcArg || YuArg) {
2472 StringRef Val = YcArg ? YcArg->getValue() : YuArg->getValue();
2473 bool FoundMatchingInclude = false;
2474 for (const Arg *Inc : Args.filtered(options::OPT_include)) {
2475 // FIXME: Do case-insensitive matching and consider / and \ as equal.
2476 if (Inc->getValue() == Val)
2477 FoundMatchingInclude = true;
2478 }
2479 if (!FoundMatchingInclude) {
2480 Diag(clang::diag::warn_drv_ycyu_no_fi_arg_clang_cl)
2481 << (YcArg ? YcArg : YuArg)->getSpelling();
2482 Args.eraseArg(options::OPT__SLASH_Yc);
2483 Args.eraseArg(options::OPT__SLASH_Yu);
2484 YcArg = YuArg = nullptr;
2485 }
2486 }
2487 if (YcArg && Inputs.size() > 1) {
2488 Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
2489 Args.eraseArg(options::OPT__SLASH_Yc);
2490 YcArg = nullptr;
2491 }
2492 if (Args.hasArg(options::OPT__SLASH_Y_)) {
2493 // /Y- disables all pch handling. Rather than check for it everywhere,
2494 // just remove clang-cl pch-related flags here.
2495 Args.eraseArg(options::OPT__SLASH_Fp);
2496 Args.eraseArg(options::OPT__SLASH_Yc);
2497 Args.eraseArg(options::OPT__SLASH_Yu);
2498 YcArg = YuArg = nullptr;
2499 }
Nico Weber2ca4be92016-03-01 23:16:44 +00002500
Samuel Antao64e965e2016-09-30 15:34:19 +00002501 // Builder to be used to build offloading actions.
2502 OffloadingActionBuilder OffloadBuilder(C, Args, Inputs);
Samuel Antaod06239d2016-07-15 23:13:27 +00002503
Daniel Dunbar65229332009-03-13 11:38:42 +00002504 // Construct the actions to perform.
2505 ActionList LinkerInputs;
Alp Toker965f8822013-11-27 05:22:15 +00002506
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002507 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL;
Artem Belevich5bde4e02015-07-20 20:02:54 +00002508 for (auto &I : Inputs) {
2509 types::ID InputType = I.first;
2510 const Arg *InputArg = I.second;
Daniel Dunbar65229332009-03-13 11:38:42 +00002511
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002512 PL.clear();
2513 types::getCompilationPhases(InputType, PL);
Daniel Dunbar65229332009-03-13 11:38:42 +00002514
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002515 // If the first step comes after the final phase we are doing as part of
2516 // this compilation, warn the user about it.
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002517 phases::ID InitialPhase = PL[0];
Daniel Dunbar65229332009-03-13 11:38:42 +00002518 if (InitialPhase > FinalPhase) {
Daniel Dunbaradc5c7c2009-03-19 07:57:08 +00002519 // Claim here to avoid the more general unused warning.
2520 InputArg->claim();
Daniel Dunbar07806ca2009-09-17 04:13:26 +00002521
Daniel Dunbar2db3e732011-04-20 15:44:48 +00002522 // Suppress all unused style warnings with -Qunused-arguments
2523 if (Args.hasArg(options::OPT_Qunused_arguments))
2524 continue;
2525
Richard Smith403f76e2012-08-06 04:09:06 +00002526 // Special case when final phase determined by binary name, rather than
2527 // by a command-line argument with a corresponding Arg.
Hans Wennborg70850d82013-07-18 20:29:38 +00002528 if (CCCIsCPP())
Richard Smith403f76e2012-08-06 04:09:06 +00002529 Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002530 << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
Daniel Dunbar07806ca2009-09-17 04:13:26 +00002531 // Special case '-E' warning on a previously preprocessed file to make
2532 // more sense.
Richard Smith403f76e2012-08-06 04:09:06 +00002533 else if (InitialPhase == phases::Compile &&
2534 FinalPhase == phases::Preprocess &&
2535 getPreprocessedType(InputType) == types::TY_INVALID)
Daniel Dunbar07806ca2009-09-17 04:13:26 +00002536 Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002537 << InputArg->getAsString(Args) << !!FinalPhaseArg
2538 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
Daniel Dunbar07806ca2009-09-17 04:13:26 +00002539 else
2540 Diag(clang::diag::warn_drv_input_file_unused)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002541 << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
2542 << !!FinalPhaseArg
2543 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
Daniel Dunbar65229332009-03-13 11:38:42 +00002544 continue;
2545 }
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002546
Nico Weberad2d8f32016-04-21 19:59:10 +00002547 if (YcArg) {
2548 // Add a separate precompile phase for the compile phase.
2549 if (FinalPhase >= phases::Compile) {
Richard Smith8cd452d2016-08-30 18:55:16 +00002550 const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType);
Nico Weberad2d8f32016-04-21 19:59:10 +00002551 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PCHPL;
Richard Smith8cd452d2016-08-30 18:55:16 +00002552 types::getCompilationPhases(HeaderType, PCHPL);
David Blaikie0aaa7622017-01-13 17:34:15 +00002553 Arg *PchInputArg = MakeInputArg(Args, *Opts, YcArg->getValue());
Nico Weberad2d8f32016-04-21 19:59:10 +00002554
2555 // Build the pipeline for the pch file.
Richard Smith8cd452d2016-08-30 18:55:16 +00002556 Action *ClangClPch =
2557 C.MakeAction<InputAction>(*PchInputArg, HeaderType);
Nico Weberad2d8f32016-04-21 19:59:10 +00002558 for (phases::ID Phase : PCHPL)
2559 ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
2560 assert(ClangClPch);
2561 Actions.push_back(ClangClPch);
2562 // The driver currently exits after the first failed command. This
2563 // relies on that behavior, to make sure if the pch generation fails,
2564 // the main compilation won't run.
2565 }
2566 }
2567
Daniel Dunbar65229332009-03-13 11:38:42 +00002568 // Build the pipeline for this file.
Justin Lebar41094612016-01-11 23:07:27 +00002569 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
Samuel Antao64e965e2016-09-30 15:34:19 +00002570
2571 // Use the current host action in any of the offloading actions, if
2572 // required.
2573 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
2574 break;
2575
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002576 for (SmallVectorImpl<phases::ID>::iterator i = PL.begin(), e = PL.end();
2577 i != e; ++i) {
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002578 phases::ID Phase = *i;
Daniel Dunbar65229332009-03-13 11:38:42 +00002579
2580 // We are done if this step is past what the user requested.
2581 if (Phase > FinalPhase)
2582 break;
2583
Samuel Antao64e965e2016-09-30 15:34:19 +00002584 // Add any offload action the host action depends on.
2585 Current = OffloadBuilder.addDeviceDependencesToHostAction(
2586 Current, InputArg, Phase, FinalPhase, PL);
2587 if (!Current)
2588 break;
2589
Daniel Dunbar65229332009-03-13 11:38:42 +00002590 // Queue linker inputs.
2591 if (Phase == phases::Link) {
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002592 assert((i + 1) == e && "linking must be final compilation step.");
Justin Lebar41094612016-01-11 23:07:27 +00002593 LinkerInputs.push_back(Current);
2594 Current = nullptr;
Daniel Dunbar65229332009-03-13 11:38:42 +00002595 break;
2596 }
2597
Samuel Antao64e965e2016-09-30 15:34:19 +00002598 // Otherwise construct the appropriate action.
2599 auto *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current);
2600
2601 // We didn't create a new action, so we will just move to the next phase.
2602 if (NewCurrent == Current)
Daniel Dunbar13864952009-03-24 20:17:30 +00002603 continue;
2604
Samuel Antao64e965e2016-09-30 15:34:19 +00002605 Current = NewCurrent;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002606
Samuel Antao64e965e2016-09-30 15:34:19 +00002607 // Use the current host action in any of the offloading actions, if
2608 // required.
2609 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
2610 break;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002611
Daniel Dunbar65229332009-03-13 11:38:42 +00002612 if (Current->getType() == types::TY_Nothing)
2613 break;
2614 }
2615
Samuel Antao64e965e2016-09-30 15:34:19 +00002616 // If we ended with something, add to the output list.
2617 if (Current)
Justin Lebar41094612016-01-11 23:07:27 +00002618 Actions.push_back(Current);
Samuel Antao64e965e2016-09-30 15:34:19 +00002619
2620 // Add any top level actions generated for offloading.
2621 OffloadBuilder.appendTopLevelActions(Actions, Current, InputArg);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002622 }
Daniel Dunbar65229332009-03-13 11:38:42 +00002623
Samuel Antao64e965e2016-09-30 15:34:19 +00002624 // Add a link action if necessary.
Samuel Antaod06239d2016-07-15 23:13:27 +00002625 if (!LinkerInputs.empty()) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002626 Action *LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image);
2627 LA = OffloadBuilder.processHostLinkAction(LA);
2628 Actions.push_back(LA);
Samuel Antaod06239d2016-07-15 23:13:27 +00002629 }
Daniel Dunbarc7a67b72009-12-22 23:19:32 +00002630
2631 // If we are linking, claim any options which are obviously only used for
2632 // compilation.
Hans Wennborga8ef14f2013-09-17 00:03:41 +00002633 if (FinalPhase == phases::Link && PL.size() == 1) {
Daniel Dunbarc7a67b72009-12-22 23:19:32 +00002634 Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
Hans Wennborga8ef14f2013-09-17 00:03:41 +00002635 Args.ClaimAllArgs(options::OPT_cl_compile_Group);
2636 }
2637
2638 // Claim ignored clang-cl options.
2639 Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
Artem Belevichbaae0932015-07-28 21:01:30 +00002640
Justin Lebardc3c5042016-04-19 02:27:07 +00002641 // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed
2642 // to non-CUDA compilations and should not trigger warnings there.
Artem Belevichbaae0932015-07-28 21:01:30 +00002643 Args.ClaimAllArgs(options::OPT_cuda_host_only);
Justin Lebardc3c5042016-04-19 02:27:07 +00002644 Args.ClaimAllArgs(options::OPT_cuda_compile_host_device);
Daniel Dunbar65229332009-03-13 11:38:42 +00002645}
2646
Justin Lebar0f3474c2016-02-11 02:00:50 +00002647Action *Driver::ConstructPhaseAction(Compilation &C, const ArgList &Args,
2648 phases::ID Phase, Action *Input) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00002649 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
Samuel Antao64e965e2016-09-30 15:34:19 +00002650
2651 // Some types skip the assembler phase (e.g., llvm-bc), but we can't
2652 // encode this in the steps because the intermediate type depends on
2653 // arguments. Just special case here.
2654 if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm)
2655 return Input;
2656
Daniel Dunbar65229332009-03-13 11:38:42 +00002657 // Build the appropriate action.
2658 switch (Phase) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002659 case phases::Link:
2660 llvm_unreachable("link action invalid here.");
Daniel Dunbar65229332009-03-13 11:38:42 +00002661 case phases::Preprocess: {
Daniel Dunbard67a3222009-03-30 06:36:42 +00002662 types::ID OutputTy;
2663 // -{M, MM} alter the output type.
Daniel Dunbar86aed7d2010-12-08 21:33:40 +00002664 if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
Daniel Dunbard67a3222009-03-30 06:36:42 +00002665 OutputTy = types::TY_Dependencies;
2666 } else {
David Blaikie5d577a22012-06-29 22:03:56 +00002667 OutputTy = Input->getType();
2668 if (!Args.hasFlag(options::OPT_frewrite_includes,
Justin Bognerce8245b2014-06-24 08:01:01 +00002669 options::OPT_fno_rewrite_includes, false) &&
2670 !CCGenDiagnostics)
David Blaikie5d577a22012-06-29 22:03:56 +00002671 OutputTy = types::getPreprocessedType(OutputTy);
Daniel Dunbard67a3222009-03-30 06:36:42 +00002672 assert(OutputTy != types::TY_INVALID &&
2673 "Cannot preprocess this input type!");
2674 }
Justin Lebar41094612016-01-11 23:07:27 +00002675 return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
Daniel Dunbar65229332009-03-13 11:38:42 +00002676 }
Aaron Ballman1f10cc52012-07-31 01:21:00 +00002677 case phases::Precompile: {
Richard Smithdd4ad3d2016-08-30 19:06:26 +00002678 types::ID OutputTy = getPrecompiledType(Input->getType());
2679 assert(OutputTy != types::TY_INVALID &&
2680 "Cannot precompile this input type!");
Aaron Ballman1f10cc52012-07-31 01:21:00 +00002681 if (Args.hasArg(options::OPT_fsyntax_only)) {
2682 // Syntax checks should not emit a PCH file
2683 OutputTy = types::TY_Nothing;
2684 }
Justin Lebar41094612016-01-11 23:07:27 +00002685 return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
Aaron Ballman1f10cc52012-07-31 01:21:00 +00002686 }
Daniel Dunbar65229332009-03-13 11:38:42 +00002687 case phases::Compile: {
David Blaikie486f4402014-08-29 07:25:23 +00002688 if (Args.hasArg(options::OPT_fsyntax_only))
Justin Lebar41094612016-01-11 23:07:27 +00002689 return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
David Blaikie486f4402014-08-29 07:25:23 +00002690 if (Args.hasArg(options::OPT_rewrite_objc))
Justin Lebar41094612016-01-11 23:07:27 +00002691 return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
David Blaikie486f4402014-08-29 07:25:23 +00002692 if (Args.hasArg(options::OPT_rewrite_legacy_objc))
Justin Lebar41094612016-01-11 23:07:27 +00002693 return C.MakeAction<CompileJobAction>(Input,
2694 types::TY_RewrittenLegacyObjC);
David Blaikie486f4402014-08-29 07:25:23 +00002695 if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto))
Justin Lebar41094612016-01-11 23:07:27 +00002696 return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
David Blaikie486f4402014-08-29 07:25:23 +00002697 if (Args.hasArg(options::OPT__migrate))
Justin Lebar41094612016-01-11 23:07:27 +00002698 return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
David Blaikie486f4402014-08-29 07:25:23 +00002699 if (Args.hasArg(options::OPT_emit_ast))
Justin Lebar41094612016-01-11 23:07:27 +00002700 return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
David Blaikie486f4402014-08-29 07:25:23 +00002701 if (Args.hasArg(options::OPT_module_file_info))
Justin Lebar41094612016-01-11 23:07:27 +00002702 return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
David Blaikie486f4402014-08-29 07:25:23 +00002703 if (Args.hasArg(options::OPT_verify_pch))
Justin Lebar41094612016-01-11 23:07:27 +00002704 return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
2705 return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
Bob Wilson23a55f12014-12-21 07:00:00 +00002706 }
2707 case phases::Backend: {
Teresa Johnson945bc502015-10-15 20:35:53 +00002708 if (isUsingLTO()) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002709 types::ID Output =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002710 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
Justin Lebar41094612016-01-11 23:07:27 +00002711 return C.MakeAction<BackendJobAction>(Input, Output);
David Blaikie486f4402014-08-29 07:25:23 +00002712 }
2713 if (Args.hasArg(options::OPT_emit_llvm)) {
Shuxin Yang4b3c7ff2013-08-23 21:34:57 +00002714 types::ID Output =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002715 Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
Justin Lebar41094612016-01-11 23:07:27 +00002716 return C.MakeAction<BackendJobAction>(Input, Output);
Daniel Dunbar65229332009-03-13 11:38:42 +00002717 }
Justin Lebar41094612016-01-11 23:07:27 +00002718 return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
Daniel Dunbar65229332009-03-13 11:38:42 +00002719 }
2720 case phases::Assemble:
Justin Lebar21e5d4f2016-01-14 21:41:27 +00002721 return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
Daniel Dunbar65229332009-03-13 11:38:42 +00002722 }
2723
David Blaikie83d382b2011-09-23 05:06:16 +00002724 llvm_unreachable("invalid phase in ConstructPhaseAction");
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002725}
2726
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00002727void Driver::BuildJobs(Compilation &C) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00002728 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
Daniel Dunbare75d8342009-03-16 06:56:51 +00002729
2730 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
2731
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002732 // It is an error to provide a -o option if we are making multiple output
2733 // files.
Daniel Dunbare75d8342009-03-16 06:56:51 +00002734 if (FinalOutput) {
2735 unsigned NumOutputs = 0;
Saleem Abdulrasoolda3f4e52014-12-29 21:02:47 +00002736 for (const Action *A : C.getActions())
2737 if (A->getType() != types::TY_Nothing)
Daniel Dunbare75d8342009-03-16 06:56:51 +00002738 ++NumOutputs;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002739
Daniel Dunbare75d8342009-03-16 06:56:51 +00002740 if (NumOutputs > 1) {
2741 Diag(clang::diag::err_drv_output_argument_with_multiple_files);
Craig Topper92fc2df2014-05-17 16:56:41 +00002742 FinalOutput = nullptr;
Daniel Dunbare75d8342009-03-16 06:56:51 +00002743 }
2744 }
2745
Chad Rosier35767232013-04-30 22:01:21 +00002746 // Collect the list of architectures.
2747 llvm::StringSet<> ArchNames;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00002748 if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO())
2749 for (const Arg *A : C.getArgs())
Chad Rosier35767232013-04-30 22:01:21 +00002750 if (A->getOption().matches(options::OPT_arch))
2751 ArchNames.insert(A->getValue());
Chad Rosier35767232013-04-30 22:01:21 +00002752
Justin Lebarb44f6fe2016-01-14 21:41:21 +00002753 // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
2754 std::map<std::pair<const Action *, std::string>, InputInfo> CachedResults;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00002755 for (Action *A : C.getActions()) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002756 // If we are linking an image for multiple archs then the linker wants
2757 // -arch_multiple and -final_output <final image name>. Unfortunately, this
2758 // doesn't fit in cleanly because we have to pass this information down.
Daniel Dunbare75d8342009-03-16 06:56:51 +00002759 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002760 // FIXME: This is a hack; find a cleaner way to integrate this into the
2761 // process.
Craig Topper92fc2df2014-05-17 16:56:41 +00002762 const char *LinkingOutput = nullptr;
Daniel Dunbardd765242009-03-26 16:12:09 +00002763 if (isa<LipoJobAction>(A)) {
Daniel Dunbare75d8342009-03-16 06:56:51 +00002764 if (FinalOutput)
Richard Smithbd55daf2012-11-01 04:30:05 +00002765 LinkingOutput = FinalOutput->getValue();
Daniel Dunbare75d8342009-03-16 06:56:51 +00002766 else
Hans Wennborga7707222015-01-09 17:38:53 +00002767 LinkingOutput = getDefaultImageName();
Daniel Dunbare75d8342009-03-16 06:56:51 +00002768 }
2769
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002770 BuildJobsForAction(C, A, &C.getDefaultToolChain(),
Mehdi Aminic50b1a22016-10-07 21:27:26 +00002771 /*BoundArch*/ StringRef(),
Daniel Dunbare75d8342009-03-16 06:56:51 +00002772 /*AtTopLevel*/ true,
Chad Rosier35767232013-04-30 22:01:21 +00002773 /*MultipleArchs*/ ArchNames.size() > 1,
Samuel Antaod06239d2016-07-15 23:13:27 +00002774 /*LinkingOutput*/ LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00002775 /*TargetDeviceOffloadKind*/ Action::OFK_None);
Daniel Dunbare75d8342009-03-16 06:56:51 +00002776 }
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00002777
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002778 // If the user passed -Qunused-arguments or there were errors, don't warn
2779 // about any unused arguments.
Argyrios Kyrtzidis31448a42010-11-18 21:47:07 +00002780 if (Diags.hasErrorOccurred() ||
Daniel Dunbara3cfbe32009-04-07 19:04:18 +00002781 C.getArgs().hasArg(options::OPT_Qunused_arguments))
Daniel Dunbard175d972009-03-18 18:03:46 +00002782 return;
2783
Daniel Dunbar58399ae2009-03-29 22:24:54 +00002784 // Claim -### here.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002785 (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002786
Nico Weber47bf5052016-04-25 21:15:49 +00002787 // Claim --driver-mode, --rsp-quoting, it was handled earlier.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002788 (void)C.getArgs().hasArg(options::OPT_driver_mode);
Nico Weber47bf5052016-04-25 21:15:49 +00002789 (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
Hans Wennborg70850d82013-07-18 20:29:38 +00002790
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00002791 for (Arg *A : C.getArgs()) {
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00002792 // FIXME: It would be nice to be able to send the argument to the
David Blaikie9c902b52011-09-25 23:23:43 +00002793 // DiagnosticsEngine, so that extra values, position, and so on could be
2794 // printed.
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00002795 if (!A->isClaimed()) {
Michael J. Spencer66e2b202012-10-19 22:37:06 +00002796 if (A->getOption().hasFlag(options::NoArgumentUnused))
Daniel Dunbara3cfbe32009-04-07 19:04:18 +00002797 continue;
2798
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002799 // Suppress the warning automatically if this is just a flag, and it is an
2800 // instance of an argument we already claimed.
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00002801 const Option &Opt = A->getOption();
Michael J. Spencerad3ccc32012-08-20 21:41:17 +00002802 if (Opt.getKind() == Option::FlagClass) {
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00002803 bool DuplicateClaimed = false;
2804
Sean Silva14facf32015-06-09 01:57:17 +00002805 for (const Arg *AA : C.getArgs().filtered(&Opt)) {
2806 if (AA->isClaimed()) {
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00002807 DuplicateClaimed = true;
2808 break;
2809 }
2810 }
2811
2812 if (DuplicateClaimed)
2813 continue;
2814 }
2815
Ehsan Akhgarid8518332016-01-25 21:14:52 +00002816 // In clang-cl, don't mention unknown arguments here since they have
2817 // already been warned about.
2818 if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN))
2819 Diag(clang::diag::warn_drv_unused_argument)
2820 << A->getAsString(C.getArgs());
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00002821 }
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00002822 }
Daniel Dunbar95e6b192009-03-13 22:12:33 +00002823}
Daniel Dunbarc4343942010-02-03 03:07:56 +00002824
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002825namespace {
2826/// Utility class to control the collapse of dependent actions and select the
2827/// tools accordingly.
2828class ToolSelector final {
2829 /// The tool chain this selector refers to.
2830 const ToolChain &TC;
Daniel Dunbarf9ff3502010-05-14 02:03:00 +00002831
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002832 /// The compilation this selector refers to.
2833 const Compilation &C;
Samuel Antaod06239d2016-07-15 23:13:27 +00002834
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002835 /// The base action this selector refers to.
2836 const JobAction *BaseAction;
Samuel Antaod06239d2016-07-15 23:13:27 +00002837
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002838 /// Set to true if the current toolchain refers to host actions.
2839 bool IsHostSelector;
Samuel Antaod06239d2016-07-15 23:13:27 +00002840
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002841 /// Set to true if save-temps and embed-bitcode functionalities are active.
2842 bool SaveTemps;
2843 bool EmbedBitcode;
2844
2845 /// Get previous dependent action or null if that does not exist. If
2846 /// \a CanBeCollapsed is false, that action must be legal to collapse or
2847 /// null will be returned.
2848 const JobAction *getPrevDependentAction(const ActionList &Inputs,
2849 ActionList &SavedOffloadAction,
2850 bool CanBeCollapsed = true) {
2851 // An option can be collapsed only if it has a single input.
2852 if (Inputs.size() != 1)
Craig Topper92fc2df2014-05-17 16:56:41 +00002853 return nullptr;
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002854
2855 Action *CurAction = *Inputs.begin();
2856 if (CanBeCollapsed &&
2857 !CurAction->isCollapsingWithNextDependentActionLegal())
2858 return nullptr;
2859
2860 // If the input action is an offload action. Look through it and save any
2861 // offload action that can be dropped in the event of a collapse.
2862 if (auto *OA = dyn_cast<OffloadAction>(CurAction)) {
2863 // If the dependent action is a device action, we will attempt to collapse
2864 // only with other device actions. Otherwise, we would do the same but
2865 // with host actions only.
2866 if (!IsHostSelector) {
2867 if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) {
2868 CurAction =
2869 OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
2870 if (CanBeCollapsed &&
2871 !CurAction->isCollapsingWithNextDependentActionLegal())
2872 return nullptr;
2873 SavedOffloadAction.push_back(OA);
2874 return dyn_cast<JobAction>(CurAction);
2875 }
2876 } else if (OA->hasHostDependence()) {
2877 CurAction = OA->getHostDependence();
2878 if (CanBeCollapsed &&
2879 !CurAction->isCollapsingWithNextDependentActionLegal())
2880 return nullptr;
2881 SavedOffloadAction.push_back(OA);
2882 return dyn_cast<JobAction>(CurAction);
2883 }
2884 return nullptr;
2885 }
2886
2887 return dyn_cast<JobAction>(CurAction);
2888 }
2889
2890 /// Return true if an assemble action can be collapsed.
2891 bool canCollapseAssembleAction() const {
2892 return TC.useIntegratedAs() && !SaveTemps &&
2893 !C.getArgs().hasArg(options::OPT_via_file_asm) &&
2894 !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
2895 !C.getArgs().hasArg(options::OPT__SLASH_Fa);
2896 }
2897
2898 /// Return true if a preprocessor action can be collapsed.
2899 bool canCollapsePreprocessorAction() const {
2900 return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
2901 !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
2902 !C.getArgs().hasArg(options::OPT_rewrite_objc);
2903 }
2904
2905 /// Struct that relates an action with the offload actions that would be
2906 /// collapsed with it.
2907 struct JobActionInfo final {
2908 /// The action this info refers to.
2909 const JobAction *JA = nullptr;
2910 /// The offload actions we need to take care off if this action is
2911 /// collapsed.
2912 ActionList SavedOffloadAction;
2913 };
2914
2915 /// Append collapsed offload actions from the give nnumber of elements in the
2916 /// action info array.
2917 static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction,
2918 ArrayRef<JobActionInfo> &ActionInfo,
2919 unsigned ElementNum) {
2920 assert(ElementNum <= ActionInfo.size() && "Invalid number of elements.");
2921 for (unsigned I = 0; I < ElementNum; ++I)
2922 CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(),
2923 ActionInfo[I].SavedOffloadAction.end());
2924 }
2925
2926 /// Functions that attempt to perform the combining. They detect if that is
2927 /// legal, and if so they update the inputs \a Inputs and the offload action
2928 /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with
2929 /// the combined action is returned. If the combining is not legal or if the
2930 /// tool does not exist, null is returned.
2931 /// Currently three kinds of collapsing are supported:
2932 /// - Assemble + Backend + Compile;
2933 /// - Assemble + Backend ;
2934 /// - Backend + Compile.
2935 const Tool *
2936 combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
2937 const ActionList *&Inputs,
2938 ActionList &CollapsedOffloadAction) {
2939 if (ActionInfo.size() < 3 || !canCollapseAssembleAction())
2940 return nullptr;
2941 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
2942 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
2943 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA);
2944 if (!AJ || !BJ || !CJ)
2945 return nullptr;
2946
2947 // Get compiler tool.
2948 const Tool *T = TC.SelectTool(*CJ);
2949 if (!T)
2950 return nullptr;
2951
Steven Wu574b0f22016-03-01 01:07:58 +00002952 // When using -fembed-bitcode, it is required to have the same tool (clang)
2953 // for both CompilerJA and BackendJA. Otherwise, combine two stages.
2954 if (EmbedBitcode) {
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002955 const Tool *BT = TC.SelectTool(*BJ);
2956 if (BT == T)
2957 return nullptr;
Steven Wu574b0f22016-03-01 01:07:58 +00002958 }
Bob Wilson23a55f12014-12-21 07:00:00 +00002959
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002960 if (!T->hasIntegratedAssembler())
Bob Wilson23a55f12014-12-21 07:00:00 +00002961 return nullptr;
Samuel Antaod06239d2016-07-15 23:13:27 +00002962
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002963 Inputs = &CJ->getInputs();
2964 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
2965 /*NumElements=*/3);
2966 return T;
2967 }
2968 const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo,
2969 const ActionList *&Inputs,
2970 ActionList &CollapsedOffloadAction) {
2971 if (ActionInfo.size() < 2 || !canCollapseAssembleAction())
2972 return nullptr;
2973 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
2974 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
2975 if (!AJ || !BJ)
2976 return nullptr;
2977
2978 // Retrieve the compile job, backend action must always be preceded by one.
2979 ActionList CompileJobOffloadActions;
2980 auto *CJ = getPrevDependentAction(BJ->getInputs(), CompileJobOffloadActions,
2981 /*CanBeCollapsed=*/false);
2982 if (!AJ || !BJ || !CJ)
2983 return nullptr;
2984
2985 assert(isa<CompileJobAction>(CJ) &&
2986 "Expecting compile job preceding backend job.");
2987
2988 // Get compiler tool.
2989 const Tool *T = TC.SelectTool(*CJ);
2990 if (!T)
2991 return nullptr;
2992
2993 if (!T->hasIntegratedAssembler())
2994 return nullptr;
2995
2996 Inputs = &BJ->getInputs();
2997 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
2998 /*NumElements=*/2);
2999 return T;
3000 }
3001 const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
3002 const ActionList *&Inputs,
3003 ActionList &CollapsedOffloadAction) {
3004 if (ActionInfo.size() < 2 || !canCollapsePreprocessorAction())
3005 return nullptr;
3006 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA);
3007 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA);
3008 if (!BJ || !CJ)
3009 return nullptr;
3010
3011 // Get compiler tool.
3012 const Tool *T = TC.SelectTool(*CJ);
3013 if (!T)
3014 return nullptr;
3015
3016 if (T->canEmitIR() && (SaveTemps || EmbedBitcode))
3017 return nullptr;
3018
3019 Inputs = &CJ->getInputs();
3020 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3021 /*NumElements=*/2);
3022 return T;
3023 }
3024
3025 /// Updates the inputs if the obtained tool supports combining with
3026 /// preprocessor action, and the current input is indeed a preprocessor
3027 /// action. If combining results in the collapse of offloading actions, those
3028 /// are appended to \a CollapsedOffloadAction.
3029 void combineWithPreprocessor(const Tool *T, const ActionList *&Inputs,
3030 ActionList &CollapsedOffloadAction) {
3031 if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP())
3032 return;
3033
3034 // Attempt to get a preprocessor action dependence.
3035 ActionList PreprocessJobOffloadActions;
3036 auto *PJ = getPrevDependentAction(*Inputs, PreprocessJobOffloadActions);
3037 if (!PJ || !isa<PreprocessJobAction>(PJ))
3038 return;
3039
3040 // This is legal to combine. Append any offload action we found and set the
3041 // current inputs to preprocessor inputs.
3042 CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(),
3043 PreprocessJobOffloadActions.end());
3044 Inputs = &PJ->getInputs();
3045 }
3046
3047public:
3048 ToolSelector(const JobAction *BaseAction, const ToolChain &TC,
3049 const Compilation &C, bool SaveTemps, bool EmbedBitcode)
3050 : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps),
3051 EmbedBitcode(EmbedBitcode) {
3052 assert(BaseAction && "Invalid base action.");
3053 IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None;
3054 }
3055
3056 /// Check if a chain of actions can be combined and return the tool that can
3057 /// handle the combination of actions. The pointer to the current inputs \a
3058 /// Inputs and the list of offload actions \a CollapsedOffloadActions
3059 /// connected to collapsed actions are updated accordingly. The latter enables
3060 /// the caller of the selector to process them afterwards instead of just
3061 /// dropping them. If no suitable tool is found, null will be returned.
3062 const Tool *getTool(const ActionList *&Inputs,
3063 ActionList &CollapsedOffloadAction) {
3064 //
3065 // Get the largest chain of actions that we could combine.
3066 //
3067
3068 SmallVector<JobActionInfo, 5> ActionChain(1);
3069 ActionChain.back().JA = BaseAction;
3070 while (ActionChain.back().JA) {
3071 const Action *CurAction = ActionChain.back().JA;
3072
3073 // Grow the chain by one element.
3074 ActionChain.resize(ActionChain.size() + 1);
3075 JobActionInfo &AI = ActionChain.back();
3076
3077 // Attempt to fill it with the
3078 AI.JA =
3079 getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction);
Daniel Dunbarc4343942010-02-03 03:07:56 +00003080 }
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003081
3082 // Pop the last action info as it could not be filled.
3083 ActionChain.pop_back();
3084
3085 //
3086 // Attempt to combine actions. If all combining attempts failed, just return
3087 // the tool of the provided action. At the end we attempt to combine the
3088 // action with any preprocessor action it may depend on.
3089 //
3090
3091 const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs,
3092 CollapsedOffloadAction);
3093 if (!T)
3094 T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction);
3095 if (!T)
3096 T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction);
3097 if (!T) {
3098 Inputs = &BaseAction->getInputs();
3099 T = TC.SelectTool(*BaseAction);
3100 }
3101
3102 combineWithPreprocessor(T, Inputs, CollapsedOffloadAction);
3103 return T;
Daniel Dunbarc4343942010-02-03 03:07:56 +00003104 }
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003105};
Daniel Dunbarc4343942010-02-03 03:07:56 +00003106}
3107
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003108/// Return a string that uniquely identifies the result of a job. The bound arch
3109/// is not necessarily represented in the toolchain's triple -- for example,
3110/// armv7 and armv7s both map to the same triple -- so we need both in our map.
3111/// Also, we need to add the offloading device kind, as the same tool chain can
3112/// be used for host and device for some programming models, e.g. OpenMP.
3113static std::string GetTriplePlusArchString(const ToolChain *TC,
3114 StringRef BoundArch,
3115 Action::OffloadKind OffloadKind) {
Justin Lebar55c83322016-01-16 03:30:08 +00003116 std::string TriplePlusArch = TC->getTriple().normalize();
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003117 if (!BoundArch.empty()) {
Justin Lebar55c83322016-01-16 03:30:08 +00003118 TriplePlusArch += "-";
3119 TriplePlusArch += BoundArch;
3120 }
Samuel Antao59efaed2016-10-27 17:31:22 +00003121 TriplePlusArch += "-";
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003122 TriplePlusArch += Action::GetOffloadKindName(OffloadKind);
3123 return TriplePlusArch;
3124}
3125
3126InputInfo Driver::BuildJobsForAction(
3127 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
3128 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
3129 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
3130 Action::OffloadKind TargetDeviceOffloadKind) const {
3131 std::pair<const Action *, std::string> ActionTC = {
3132 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003133 auto CachedResult = CachedResults.find(ActionTC);
3134 if (CachedResult != CachedResults.end()) {
3135 return CachedResult->second;
3136 }
Samuel Antaod06239d2016-07-15 23:13:27 +00003137 InputInfo Result = BuildJobsForActionNoCache(
3138 C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003139 CachedResults, TargetDeviceOffloadKind);
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003140 CachedResults[ActionTC] = Result;
3141 return Result;
3142}
3143
3144InputInfo Driver::BuildJobsForActionNoCache(
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003145 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003146 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
Samuel Antaod06239d2016-07-15 23:13:27 +00003147 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003148 Action::OffloadKind TargetDeviceOffloadKind) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003149 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
Daniel Dunbarc4acf9d2009-03-18 23:18:19 +00003150
Samuel Antaod06239d2016-07-15 23:13:27 +00003151 InputInfoList OffloadDependencesInputInfo;
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003152 bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None;
Samuel Antaod06239d2016-07-15 23:13:27 +00003153 if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
3154 // The offload action is expected to be used in four different situations.
3155 //
3156 // a) Set a toolchain/architecture/kind for a host action:
3157 // Host Action 1 -> OffloadAction -> Host Action 2
3158 //
3159 // b) Set a toolchain/architecture/kind for a device action;
3160 // Device Action 1 -> OffloadAction -> Device Action 2
3161 //
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003162 // c) Specify a device dependence to a host action;
Samuel Antaod06239d2016-07-15 23:13:27 +00003163 // Device Action 1 _
3164 // \
3165 // Host Action 1 ---> OffloadAction -> Host Action 2
3166 //
3167 // d) Specify a host dependence to a device action.
3168 // Host Action 1 _
3169 // \
3170 // Device Action 1 ---> OffloadAction -> Device Action 2
3171 //
3172 // For a) and b), we just return the job generated for the dependence. For
3173 // c) and d) we override the current action with the host/device dependence
3174 // if the current toolchain is host/device and set the offload dependences
3175 // info with the jobs obtained from the device/host dependence(s).
3176
3177 // If there is a single device option, just generate the job for it.
3178 if (OA->hasSingleDeviceDependence()) {
3179 InputInfo DevA;
3180 OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
3181 const char *DepBoundArch) {
3182 DevA =
3183 BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
3184 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003185 CachedResults, DepA->getOffloadingDeviceKind());
Samuel Antaod06239d2016-07-15 23:13:27 +00003186 });
3187 return DevA;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003188 }
Samuel Antaod06239d2016-07-15 23:13:27 +00003189
3190 // If 'Action 2' is host, we generate jobs for the device dependences and
3191 // override the current action with the host dependence. Otherwise, we
3192 // generate the host dependences and override the action with the device
3193 // dependence. The dependences can't therefore be a top-level action.
3194 OA->doOnEachDependence(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003195 /*IsHostDependence=*/BuildingForOffloadDevice,
Samuel Antaod06239d2016-07-15 23:13:27 +00003196 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3197 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
3198 C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false,
3199 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003200 DepA->getOffloadingDeviceKind()));
Samuel Antaod06239d2016-07-15 23:13:27 +00003201 });
3202
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003203 A = BuildingForOffloadDevice
Samuel Antaod06239d2016-07-15 23:13:27 +00003204 ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
3205 : OA->getHostDependence();
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003206 }
3207
Daniel Dunbare75d8342009-03-16 06:56:51 +00003208 if (const InputAction *IA = dyn_cast<InputAction>(A)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003209 // FIXME: It would be nice to not claim this here; maybe the old scheme of
3210 // just using Args was better?
Daniel Dunbar5cdf3e02009-03-19 07:29:38 +00003211 const Arg &Input = IA->getInputArg();
3212 Input.claim();
Daniel Dunbar35cbfeb2010-06-09 22:31:08 +00003213 if (Input.getOption().matches(options::OPT_INPUT)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00003214 const char *Name = Input.getValue();
Justin Lebard98cea82016-01-11 23:15:21 +00003215 return InputInfo(A, Name, /* BaseInput = */ Name);
Douglas Katzman678d0cb2015-06-16 18:01:24 +00003216 }
Justin Lebard98cea82016-01-11 23:15:21 +00003217 return InputInfo(A, &Input, /* BaseInput = */ "");
Daniel Dunbare75d8342009-03-16 06:56:51 +00003218 }
3219
3220 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
Chad Rosiera78a6eb2012-04-27 16:50:38 +00003221 const ToolChain *TC;
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003222 StringRef ArchName = BAA->getArchName();
Daniel Dunbar1ef3f2a2009-09-08 23:37:19 +00003223
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003224 if (!ArchName.empty())
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +00003225 TC = &getToolChain(C.getArgs(),
3226 computeTargetTriple(*this, DefaultTargetTriple,
3227 C.getArgs(), ArchName));
Chad Rosiera78a6eb2012-04-27 16:50:38 +00003228 else
3229 TC = &C.getDefaultToolChain();
Daniel Dunbar1ef3f2a2009-09-08 23:37:19 +00003230
Nico Weber5a459f82016-02-23 19:30:43 +00003231 return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
Samuel Antaod06239d2016-07-15 23:13:27 +00003232 MultipleArchs, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003233 TargetDeviceOffloadKind);
Daniel Dunbare75d8342009-03-16 06:56:51 +00003234 }
3235
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003236
Daniel Dunbare75d8342009-03-16 06:56:51 +00003237 const ActionList *Inputs = &A->getInputs();
Daniel Dunbarc4343942010-02-03 03:07:56 +00003238
3239 const JobAction *JA = cast<JobAction>(A);
Samuel Antaod06239d2016-07-15 23:13:27 +00003240 ActionList CollapsedOffloadActions;
3241
Mehdi Amini6683e222017-01-24 18:12:25 +00003242 ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(),
3243 embedBitcodeInObject() && !isUsingLTO());
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003244 const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions);
3245
Rafael Espindola79764462013-03-24 15:06:53 +00003246 if (!T)
Justin Lebar9eaa4892016-01-11 23:09:32 +00003247 return InputInfo();
Daniel Dunbare75d8342009-03-16 06:56:51 +00003248
Samuel Antaod06239d2016-07-15 23:13:27 +00003249 // If we've collapsed action list that contained OffloadAction we
3250 // need to build jobs for host/device-side inputs it may have held.
3251 for (const auto *OA : CollapsedOffloadActions)
3252 cast<OffloadAction>(OA)->doOnEachDependence(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003253 /*IsHostDependence=*/BuildingForOffloadDevice,
Samuel Antaod06239d2016-07-15 23:13:27 +00003254 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3255 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
Artem Belevichbee2f412016-08-22 18:50:34 +00003256 C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false,
Samuel Antaod06239d2016-07-15 23:13:27 +00003257 /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003258 DepA->getOffloadingDeviceKind()));
Samuel Antaod06239d2016-07-15 23:13:27 +00003259 });
Artem Belevichf8144ab2015-08-27 18:10:41 +00003260
Daniel Dunbare75d8342009-03-16 06:56:51 +00003261 // Only use pipes when there is exactly one input.
Daniel Dunbar1a093d22009-03-18 06:00:36 +00003262 InputInfoList InputInfos;
Saleem Abdulrasoolda3f4e52014-12-29 21:02:47 +00003263 for (const Action *Input : *Inputs) {
Eric Christopher14668dd2013-02-18 00:38:25 +00003264 // Treat dsymutil and verify sub-jobs as being at the top-level too, they
3265 // shouldn't get temporary output names.
Daniel Dunbar6beaf512010-06-04 18:28:41 +00003266 // FIXME: Clean this up.
Justin Lebar9eaa4892016-01-11 23:09:32 +00003267 bool SubJobAtTopLevel =
3268 AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
Samuel Antaod06239d2016-07-15 23:13:27 +00003269 InputInfos.push_back(BuildJobsForAction(
3270 C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003271 CachedResults, A->getOffloadingDeviceKind()));
Daniel Dunbare75d8342009-03-16 06:56:51 +00003272 }
3273
Daniel Dunbare75d8342009-03-16 06:56:51 +00003274 // Always use the first input as the base input.
3275 const char *BaseInput = InputInfos[0].getBaseInput();
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003276
Daniel Dunbar6beaf512010-06-04 18:28:41 +00003277 // ... except dsymutil actions, which use their actual input as the base
3278 // input.
3279 if (JA->getType() == types::TY_dSYM)
3280 BaseInput = InputInfos[0].getFilename();
3281
Samuel Antaod06239d2016-07-15 23:13:27 +00003282 // Append outputs of offload device jobs to the input list
3283 if (!OffloadDependencesInputInfo.empty())
3284 InputInfos.append(OffloadDependencesInputInfo.begin(),
3285 OffloadDependencesInputInfo.end());
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003286
Vedant Kumar18286cf2016-07-27 23:02:20 +00003287 // Set the effective triple of the toolchain for the duration of this job.
3288 llvm::Triple EffectiveTriple;
3289 const ToolChain &ToolTC = T->getToolChain();
Samuel Antao31fef982016-10-27 17:39:44 +00003290 const ArgList &Args =
3291 C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind());
Vedant Kumar18286cf2016-07-27 23:02:20 +00003292 if (InputInfos.size() != 1) {
3293 EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args));
3294 } else {
3295 // Pass along the input type if it can be unambiguously determined.
3296 EffectiveTriple = llvm::Triple(
3297 ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType()));
3298 }
3299 RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple);
3300
Daniel Dunbard00272f2010-08-02 02:38:15 +00003301 // Determine the place to write output to, if any.
Justin Lebar9eaa4892016-01-11 23:09:32 +00003302 InputInfo Result;
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003303 InputInfoList UnbundlingResults;
3304 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) {
3305 // If we have an unbundling job, we need to create results for all the
3306 // outputs. We also update the results cache so that other actions using
3307 // this unbundling action can get the right results.
3308 for (auto &UI : UA->getDependentActionsInfo()) {
3309 assert(UI.DependentOffloadKind != Action::OFK_None &&
3310 "Unbundling with no offloading??");
3311
3312 // Unbundling actions are never at the top level. When we generate the
3313 // offloading prefix, we also do that for the host file because the
3314 // unbundling action does not change the type of the output which can
3315 // cause a overwrite.
3316 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
3317 UI.DependentOffloadKind,
3318 UI.DependentToolChain->getTriple().normalize(),
3319 /*CreatePrefixForHost=*/true);
3320 auto CurI = InputInfo(
3321 UA, GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch,
3322 /*AtTopLevel=*/false, MultipleArchs,
3323 OffloadingPrefix),
3324 BaseInput);
3325 // Save the unbundling result.
3326 UnbundlingResults.push_back(CurI);
3327
3328 // Get the unique string identifier for this dependence and cache the
3329 // result.
3330 CachedResults[{A, GetTriplePlusArchString(
3331 UI.DependentToolChain, UI.DependentBoundArch,
3332 UI.DependentOffloadKind)}] = CurI;
3333 }
3334
3335 // Now that we have all the results generated, select the one that should be
3336 // returned for the current depending action.
3337 std::pair<const Action *, std::string> ActionTC = {
3338 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
3339 assert(CachedResults.find(ActionTC) != CachedResults.end() &&
3340 "Result does not exist??");
3341 Result = CachedResults[ActionTC];
3342 } else if (JA->getType() == types::TY_Nothing)
Justin Lebard98cea82016-01-11 23:15:21 +00003343 Result = InputInfo(A, BaseInput);
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003344 else {
3345 // We only have to generate a prefix for the host if this is not a top-level
3346 // action.
3347 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
3348 A->getOffloadingDeviceKind(), TC->getTriple().normalize(),
3349 /*CreatePrefixForHost=*/!!A->getOffloadingHostActiveKinds() &&
3350 !AtTopLevel);
Justin Lebard98cea82016-01-11 23:15:21 +00003351 Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
Samuel Antaod06239d2016-07-15 23:13:27 +00003352 AtTopLevel, MultipleArchs,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003353 OffloadingPrefix),
Justin Lebard98cea82016-01-11 23:15:21 +00003354 BaseInput);
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003355 }
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003356
Chad Rosierbe10f982011-08-02 17:58:04 +00003357 if (CCCPrintBindings && !CCGenDiagnostics) {
Rafael Espindola79764462013-03-24 15:06:53 +00003358 llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
3359 << " - \"" << T->getName() << "\", inputs: [";
Daniel Dunbarb39cc522009-03-17 22:47:06 +00003360 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
3361 llvm::errs() << InputInfos[i].getAsString();
3362 if (i + 1 != e)
3363 llvm::errs() << ", ";
3364 }
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003365 if (UnbundlingResults.empty())
3366 llvm::errs() << "], output: " << Result.getAsString() << "\n";
3367 else {
3368 llvm::errs() << "], outputs: [";
3369 for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) {
3370 llvm::errs() << UnbundlingResults[i].getAsString();
3371 if (i + 1 != e)
3372 llvm::errs() << ", ";
3373 }
3374 llvm::errs() << "] \n";
3375 }
Daniel Dunbarb39cc522009-03-17 22:47:06 +00003376 } else {
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003377 if (UnbundlingResults.empty())
3378 T->ConstructJob(
3379 C, *JA, Result, InputInfos,
3380 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
3381 LinkingOutput);
3382 else
Samuel Antao7108bf32016-11-03 15:41:50 +00003383 T->ConstructJobMultipleOutputs(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003384 C, *JA, UnbundlingResults, InputInfos,
3385 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
3386 LinkingOutput);
Daniel Dunbarb39cc522009-03-17 22:47:06 +00003387 }
Justin Lebar9eaa4892016-01-11 23:09:32 +00003388 return Result;
Daniel Dunbare75d8342009-03-16 06:56:51 +00003389}
3390
Hans Wennborga7707222015-01-09 17:38:53 +00003391const char *Driver::getDefaultImageName() const {
3392 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
3393 return Target.isOSWindows() ? "a.exe" : "a.out";
3394}
3395
Hans Wennborg2c21f742013-10-17 16:16:23 +00003396/// \brief Create output filename based on ArgValue, which could either be a
3397/// full filename, filename without extension, or a directory. If ArgValue
3398/// does not provide a filename, then use BaseName, and use the extension
3399/// suitable for FileType.
Hans Wennborg207fcf02013-08-12 21:56:42 +00003400static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003401 StringRef BaseName,
3402 types::ID FileType) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00003403 SmallString<128> Filename = ArgValue;
Justin Bogner5aaf2e72014-06-26 20:59:36 +00003404
Hans Wennborgf1a74252013-09-10 20:18:04 +00003405 if (ArgValue.empty()) {
3406 // If the argument is empty, output to BaseName in the current dir.
3407 Filename = BaseName;
3408 } else if (llvm::sys::path::is_separator(Filename.back())) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00003409 // If the argument is a directory, output to BaseName in that dir.
3410 llvm::sys::path::append(Filename, BaseName);
3411 }
3412
3413 if (!llvm::sys::path::has_extension(ArgValue)) {
3414 // If the argument didn't provide an extension, then set it.
3415 const char *Extension = types::getTypeTempSuffix(FileType, true);
Hans Wennborgf1a74252013-09-10 20:18:04 +00003416
3417 if (FileType == types::TY_Image &&
3418 Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
3419 // The output file is a dll.
3420 Extension = "dll";
3421 }
3422
Hans Wennborg207fcf02013-08-12 21:56:42 +00003423 llvm::sys::path::replace_extension(Filename, Extension);
3424 }
3425
3426 return Args.MakeArgString(Filename.c_str());
3427}
3428
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003429const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003430 const char *BaseInput,
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003431 StringRef BoundArch, bool AtTopLevel,
Samuel Antaod06239d2016-07-15 23:13:27 +00003432 bool MultipleArchs,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003433 StringRef OffloadingPrefix) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00003434 llvm::PrettyStackTraceString CrashInfo("Computing output path");
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003435 // Output to a user requested destination?
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003436 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003437 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
Chad Rosier633dcdc2013-01-24 19:14:47 +00003438 return C.addResultFile(FinalOutput->getValue(), &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003439 }
3440
Hans Wennborge0053472013-12-20 18:40:46 +00003441 // For /P, preprocess to file named after BaseInput.
3442 if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
3443 assert(AtTopLevel && isa<PreprocessJobAction>(JA));
3444 StringRef BaseName = llvm::sys::path::filename(BaseInput);
Hans Wennborg04c764f2014-06-17 00:19:12 +00003445 StringRef NameArg;
Greg Bedwell065f70a2015-06-09 10:24:06 +00003446 if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
Hans Wennborg04c764f2014-06-17 00:19:12 +00003447 NameArg = A->getValue();
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003448 return C.addResultFile(
3449 MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
3450 &JA);
Hans Wennborge0053472013-12-20 18:40:46 +00003451 }
3452
Nick Lewycky6e1ce292010-09-24 00:46:53 +00003453 // Default to writing to stdout?
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00003454 if (AtTopLevel && !CCGenDiagnostics &&
3455 (isa<PreprocessJobAction>(JA) || JA.getType() == types::TY_ModuleFile))
Nick Lewycky6e1ce292010-09-24 00:46:53 +00003456 return "-";
3457
Hans Wennborg2c21f742013-10-17 16:16:23 +00003458 // Is this the assembly listing for /FA?
3459 if (JA.getType() == types::TY_PP_Asm &&
3460 (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
3461 C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
3462 // Use /Fa and the input filename to determine the asm file name.
3463 StringRef BaseName = llvm::sys::path::filename(BaseInput);
3464 StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003465 return C.addResultFile(
3466 MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
3467 &JA);
Hans Wennborg2c21f742013-10-17 16:16:23 +00003468 }
3469
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003470 // Output to a temporary file?
Reid Kleckner68eb60b2015-02-02 22:41:48 +00003471 if ((!AtTopLevel && !isSaveTempsEnabled() &&
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003472 !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
Chad Rosierbe10f982011-08-02 17:58:04 +00003473 CCGenDiagnostics) {
Chad Rosier97c37372011-08-26 22:27:02 +00003474 StringRef Name = llvm::sys::path::filename(BaseInput);
3475 std::pair<StringRef, StringRef> Split = Name.split('.');
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003476 std::string TmpName = GetTemporaryPath(
3477 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00003478 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003479 }
3480
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003481 SmallString<128> BasePath(BaseInput);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003482 StringRef BaseName;
Daniel Dunbar67fea712011-03-25 18:16:51 +00003483
3484 // Dsymutil actions should use the full path.
Eric Christopher551ef452011-08-23 17:56:55 +00003485 if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
Daniel Dunbar67fea712011-03-25 18:16:51 +00003486 BaseName = BasePath;
3487 else
3488 BaseName = llvm::sys::path::filename(BasePath);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003489
3490 // Determine what the derived output name should be.
3491 const char *NamedOutput;
Hans Wennborg2b89a262013-08-06 22:11:28 +00003492
Hans Wennborg625fba82016-10-04 21:01:04 +00003493 if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) &&
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00003494 C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
3495 // The /Fo or /o flag decides the object filename.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003496 StringRef Val =
3497 C.getArgs()
3498 .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
3499 ->getValue();
3500 NamedOutput =
3501 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
Hans Wennborg207fcf02013-08-12 21:56:42 +00003502 } else if (JA.getType() == types::TY_Image &&
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003503 C.getArgs().hasArg(options::OPT__SLASH_Fe,
3504 options::OPT__SLASH_o)) {
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00003505 // The /Fe or /o flag names the linked file.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003506 StringRef Val =
3507 C.getArgs()
3508 .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
3509 ->getValue();
3510 NamedOutput =
3511 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
Hans Wennborgf1a74252013-09-10 20:18:04 +00003512 } else if (JA.getType() == types::TY_Image) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00003513 if (IsCLMode()) {
3514 // clang-cl uses BaseName for the executable name.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003515 NamedOutput =
3516 MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
Samuel Antao59efaed2016-10-27 17:31:22 +00003517 } else {
Hans Wennborga7707222015-01-09 17:38:53 +00003518 SmallString<128> Output(getDefaultImageName());
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003519 Output += OffloadingPrefix;
Samuel Antao59efaed2016-10-27 17:31:22 +00003520 if (MultipleArchs && !BoundArch.empty()) {
3521 Output += "-";
3522 Output.append(BoundArch);
3523 }
Chad Rosier35767232013-04-30 22:01:21 +00003524 NamedOutput = C.getArgs().MakeArgString(Output.c_str());
Nico Weber2ca4be92016-03-01 23:16:44 +00003525 }
3526 } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00003527 NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName));
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003528 } else {
Hans Wennborg0a096a02013-09-05 17:05:56 +00003529 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003530 assert(Suffix && "All types used for output should have a suffix.");
3531
3532 std::string::size_type End = std::string::npos;
3533 if (!types::appendSuffixForType(JA.getType()))
3534 End = BaseName.rfind('.');
Chad Rosier35767232013-04-30 22:01:21 +00003535 SmallString<128> Suffixed(BaseName.substr(0, End));
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003536 Suffixed += OffloadingPrefix;
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003537 if (MultipleArchs && !BoundArch.empty()) {
Chad Rosier35767232013-04-30 22:01:21 +00003538 Suffixed += "-";
3539 Suffixed.append(BoundArch);
3540 }
Bob Wilson23a55f12014-12-21 07:00:00 +00003541 // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
3542 // the unoptimized bitcode so that it does not get overwritten by the ".bc"
3543 // optimized bitcode output.
3544 if (!AtTopLevel && C.getArgs().hasArg(options::OPT_emit_llvm) &&
3545 JA.getType() == types::TY_LLVM_BC)
3546 Suffixed += ".tmp";
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003547 Suffixed += '.';
3548 Suffixed += Suffix;
3549 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
3550 }
3551
Reid Kleckner68eb60b2015-02-02 22:41:48 +00003552 // Prepend object file path if -save-temps=obj
3553 if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
3554 JA.getType() != types::TY_PCH) {
3555 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
3556 SmallString<128> TempPath(FinalOutput->getValue());
3557 llvm::sys::path::remove_filename(TempPath);
3558 StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
3559 llvm::sys::path::append(TempPath, OutputFileName);
3560 NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
3561 }
3562
Chad Rosier62135492012-07-09 17:31:28 +00003563 // If we're saving temps and the temp file conflicts with the input file,
Chad Rosier5b58af02012-04-20 20:05:08 +00003564 // then avoid overwriting input file.
Reid Kleckner68eb60b2015-02-02 22:41:48 +00003565 if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
Chad Rosier5b58af02012-04-20 20:05:08 +00003566 bool SameFile = false;
3567 SmallString<256> Result;
3568 llvm::sys::fs::current_path(Result);
3569 llvm::sys::path::append(Result, BaseName);
3570 llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
3571 // Must share the same path to conflict.
3572 if (SameFile) {
3573 StringRef Name = llvm::sys::path::filename(BaseInput);
3574 std::pair<StringRef, StringRef> Split = Name.split('.');
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003575 std::string TmpName = GetTemporaryPath(
3576 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00003577 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
Chad Rosier5b58af02012-04-20 20:05:08 +00003578 }
Chad Rosierf8412cd2011-07-15 21:54:29 +00003579 }
3580
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003581 // As an annoying special case, PCH generation doesn't strip the pathname.
Nico Weber8ab92192016-03-02 23:29:29 +00003582 if (JA.getType() == types::TY_PCH && !IsCLMode()) {
Michael J. Spencere1696752010-12-18 00:19:12 +00003583 llvm::sys::path::remove_filename(BasePath);
3584 if (BasePath.empty())
Daniel Dunbare6c83192009-03-18 09:58:30 +00003585 BasePath = NamedOutput;
3586 else
Michael J. Spencere1696752010-12-18 00:19:12 +00003587 llvm::sys::path::append(BasePath, NamedOutput);
Chad Rosier633dcdc2013-01-24 19:14:47 +00003588 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003589 } else {
Chad Rosier633dcdc2013-01-24 19:14:47 +00003590 return C.addResultFile(NamedOutput, &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003591 }
3592}
3593
Mehdi Amini12011172016-10-06 05:11:48 +00003594std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const {
Chandler Carruth84559242010-03-22 01:52:07 +00003595 // Respect a limited subset of the '-Bprefix' functionality in GCC by
Logan Chiencd679fd2012-10-04 08:08:56 +00003596 // attempting to use this prefix when looking for file paths.
Douglas Katzman26eabf62015-06-24 15:10:30 +00003597 for (const std::string &Dir : PrefixDirs) {
Joerg Sonnenberger6165ab12011-03-21 13:51:29 +00003598 if (Dir.empty())
3599 continue;
Douglas Katzman26eabf62015-06-24 15:10:30 +00003600 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
Rafael Espindola609a6642013-06-24 18:33:43 +00003601 llvm::sys::path::append(P, Name);
3602 if (llvm::sys::fs::exists(Twine(P)))
Chandler Carruth84559242010-03-22 01:52:07 +00003603 return P.str();
3604 }
3605
Rafael Espindola609a6642013-06-24 18:33:43 +00003606 SmallString<128> P(ResourceDir);
3607 llvm::sys::path::append(P, Name);
3608 if (llvm::sys::fs::exists(Twine(P)))
Peter Collingbournefa9771f2011-09-06 02:08:31 +00003609 return P.str();
3610
Douglas Katzman26eabf62015-06-24 15:10:30 +00003611 for (const std::string &Dir : TC.getFilePaths()) {
Joerg Sonnenberger6165ab12011-03-21 13:51:29 +00003612 if (Dir.empty())
3613 continue;
Douglas Katzman26eabf62015-06-24 15:10:30 +00003614 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
Rafael Espindola609a6642013-06-24 18:33:43 +00003615 llvm::sys::path::append(P, Name);
3616 if (llvm::sys::fs::exists(Twine(P)))
Daniel Dunbar1ce81532009-09-09 22:33:00 +00003617 return P.str();
Daniel Dunbar68b01a02009-03-18 20:26:19 +00003618 }
3619
Daniel Dunbar1ce81532009-09-09 22:33:00 +00003620 return Name;
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00003621}
3622
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003623void Driver::generatePrefixedToolNames(
Mehdi Amini12011172016-10-06 05:11:48 +00003624 StringRef Tool, const ToolChain &TC,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003625 SmallVectorImpl<std::string> &Names) const {
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00003626 // FIXME: Needs a better variable than DefaultTargetTriple
Mehdi Amini12011172016-10-06 05:11:48 +00003627 Names.emplace_back((DefaultTargetTriple + "-" + Tool).str());
Benjamin Kramer3204b152015-05-29 19:42:19 +00003628 Names.emplace_back(Tool);
Vasileios Kalintirisc744e122015-11-12 15:26:54 +00003629
3630 // Allow the discovery of tools prefixed with LLVM's default target triple.
3631 std::string LLVMDefaultTargetTriple = llvm::sys::getDefaultTargetTriple();
3632 if (LLVMDefaultTargetTriple != DefaultTargetTriple)
Mehdi Amini12011172016-10-06 05:11:48 +00003633 Names.emplace_back((LLVMDefaultTargetTriple + "-" + Tool).str());
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00003634}
3635
Benjamin Kramer7111b912014-11-04 20:26:01 +00003636static bool ScanDirForExecutable(SmallString<128> &Dir,
3637 ArrayRef<std::string> Names) {
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00003638 for (const auto &Name : Names) {
3639 llvm::sys::path::append(Dir, Name);
3640 if (llvm::sys::fs::can_execute(Twine(Dir)))
3641 return true;
3642 llvm::sys::path::remove_filename(Dir);
3643 }
3644 return false;
3645}
3646
Mehdi Amini12011172016-10-06 05:11:48 +00003647std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const {
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00003648 SmallVector<std::string, 2> TargetSpecificExecutables;
3649 generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
3650
Chandler Carruth84559242010-03-22 01:52:07 +00003651 // Respect a limited subset of the '-Bprefix' functionality in GCC by
Logan Chiencd679fd2012-10-04 08:08:56 +00003652 // attempting to use this prefix when looking for program paths.
Saleem Abdulrasool23d99b12014-09-16 03:48:32 +00003653 for (const auto &PrefixDir : PrefixDirs) {
3654 if (llvm::sys::fs::is_directory(PrefixDir)) {
3655 SmallString<128> P(PrefixDir);
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00003656 if (ScanDirForExecutable(P, TargetSpecificExecutables))
Rafael Espindola8be5c052013-06-19 13:24:29 +00003657 return P.str();
Simon Atanasyana47ba292012-10-31 14:39:28 +00003658 } else {
Mehdi Amini12011172016-10-06 05:11:48 +00003659 SmallString<128> P((PrefixDir + Name).str());
Rafael Espindola609a6642013-06-24 18:33:43 +00003660 if (llvm::sys::fs::can_execute(Twine(P)))
Rafael Espindola8be5c052013-06-19 13:24:29 +00003661 return P.str();
Simon Atanasyan86bdab72012-10-31 12:01:53 +00003662 }
Chandler Carruth84559242010-03-22 01:52:07 +00003663 }
3664
Daniel Dunbar68b01a02009-03-18 20:26:19 +00003665 const ToolChain::path_list &List = TC.getProgramPaths();
Saleem Abdulrasool23d99b12014-09-16 03:48:32 +00003666 for (const auto &Path : List) {
3667 SmallString<128> P(Path);
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00003668 if (ScanDirForExecutable(P, TargetSpecificExecutables))
Rafael Espindola8be5c052013-06-19 13:24:29 +00003669 return P.str();
Daniel Dunbar68b01a02009-03-18 20:26:19 +00003670 }
3671
Daniel Dunbar76ce7412009-03-23 16:15:50 +00003672 // If all else failed, search the path.
Michael J. Spencerb011d482014-11-07 21:30:32 +00003673 for (const auto &TargetSpecificExecutable : TargetSpecificExecutables)
3674 if (llvm::ErrorOr<std::string> P =
3675 llvm::sys::findProgramByName(TargetSpecificExecutable))
Michael J. Spencer04162ea2014-11-04 01:30:55 +00003676 return *P;
Daniel Dunbar6f668772009-03-18 21:34:08 +00003677
Daniel Dunbar1ce81532009-09-09 22:33:00 +00003678 return Name;
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00003679}
3680
Mehdi Amini12011172016-10-06 05:11:48 +00003681std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const {
Rafael Espindola37d229d2013-06-25 04:26:55 +00003682 SmallString<128> Path;
Rafael Espindolac0809172014-06-12 14:02:15 +00003683 std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
Rafael Espindola37d229d2013-06-25 04:26:55 +00003684 if (EC) {
3685 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
Daniel Dunbare627c1c2009-03-18 19:34:39 +00003686 return "";
3687 }
3688
Rafael Espindola37d229d2013-06-25 04:26:55 +00003689 return Path.str();
Daniel Dunbare627c1c2009-03-18 19:34:39 +00003690}
3691
Nico Weber2ca4be92016-03-01 23:16:44 +00003692std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
3693 SmallString<128> Output;
3694 if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
3695 // FIXME: If anybody needs it, implement this obscure rule:
3696 // "If you specify a directory without a file name, the default file name
3697 // is VCx0.pch., where x is the major version of Visual C++ in use."
3698 Output = FpArg->getValue();
3699
3700 // "If you do not specify an extension as part of the path name, an
3701 // extension of .pch is assumed. "
3702 if (!llvm::sys::path::has_extension(Output))
3703 Output += ".pch";
3704 } else {
3705 Output = BaseName;
3706 llvm::sys::path::replace_extension(Output, ".pch");
3707 }
3708 return Output.str();
3709}
3710
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003711const ToolChain &Driver::getToolChain(const ArgList &Args,
Artem Belevich959e0542015-07-10 19:47:55 +00003712 const llvm::Triple &Target) const {
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003713
David Blaikie6ad71012017-01-13 18:53:43 +00003714 auto &TC = ToolChains[Target.str()];
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003715 if (!TC) {
3716 switch (Target.getOS()) {
Reid Kleckner330fb172016-05-11 16:19:05 +00003717 case llvm::Triple::Haiku:
David Blaikie6ad71012017-01-13 18:53:43 +00003718 TC = llvm::make_unique<toolchains::Haiku>(*this, Target, Args);
Reid Kleckner330fb172016-05-11 16:19:05 +00003719 break;
Ed Schouten3c3e58c2015-03-26 11:13:44 +00003720 case llvm::Triple::CloudABI:
David Blaikie6ad71012017-01-13 18:53:43 +00003721 TC = llvm::make_unique<toolchains::CloudABI>(*this, Target, Args);
Ed Schouten3c3e58c2015-03-26 11:13:44 +00003722 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003723 case llvm::Triple::Darwin:
3724 case llvm::Triple::MacOSX:
3725 case llvm::Triple::IOS:
Tim Northover6f3ff222015-10-30 16:30:27 +00003726 case llvm::Triple::TvOS:
3727 case llvm::Triple::WatchOS:
David Blaikie6ad71012017-01-13 18:53:43 +00003728 TC = llvm::make_unique<toolchains::DarwinClang>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003729 break;
3730 case llvm::Triple::DragonFly:
David Blaikie6ad71012017-01-13 18:53:43 +00003731 TC = llvm::make_unique<toolchains::DragonFly>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003732 break;
3733 case llvm::Triple::OpenBSD:
David Blaikie6ad71012017-01-13 18:53:43 +00003734 TC = llvm::make_unique<toolchains::OpenBSD>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003735 break;
Eli Friedman9fa28852012-08-08 23:57:20 +00003736 case llvm::Triple::Bitrig:
David Blaikie6ad71012017-01-13 18:53:43 +00003737 TC = llvm::make_unique<toolchains::Bitrig>(*this, Target, Args);
Eli Friedman9fa28852012-08-08 23:57:20 +00003738 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003739 case llvm::Triple::NetBSD:
David Blaikie6ad71012017-01-13 18:53:43 +00003740 TC = llvm::make_unique<toolchains::NetBSD>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003741 break;
3742 case llvm::Triple::FreeBSD:
David Blaikie6ad71012017-01-13 18:53:43 +00003743 TC = llvm::make_unique<toolchains::FreeBSD>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003744 break;
3745 case llvm::Triple::Minix:
David Blaikie6ad71012017-01-13 18:53:43 +00003746 TC = llvm::make_unique<toolchains::Minix>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003747 break;
3748 case llvm::Triple::Linux:
Andrey Turetskiy4798eb62016-06-16 10:36:09 +00003749 case llvm::Triple::ELFIAMCU:
Chandler Carruthcf705b22012-01-25 21:03:58 +00003750 if (Target.getArch() == llvm::Triple::hexagon)
David Blaikie6ad71012017-01-13 18:53:43 +00003751 TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
3752 Args);
Vasileios Kalintirisc744e122015-11-12 15:26:54 +00003753 else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
3754 !Target.hasEnvironment())
David Blaikie6ad71012017-01-13 18:53:43 +00003755 TC = llvm::make_unique<toolchains::MipsLLVMToolChain>(*this, Target,
3756 Args);
Chandler Carruthcf705b22012-01-25 21:03:58 +00003757 else
David Blaikie6ad71012017-01-13 18:53:43 +00003758 TC = llvm::make_unique<toolchains::Linux>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003759 break;
Derek Schuff6ab52fa2015-03-30 20:31:33 +00003760 case llvm::Triple::NaCl:
David Blaikie6ad71012017-01-13 18:53:43 +00003761 TC = llvm::make_unique<toolchains::NaClToolChain>(*this, Target, Args);
Derek Schuff6ab52fa2015-03-30 20:31:33 +00003762 break;
Petr Hosek62e1d232016-10-06 06:08:09 +00003763 case llvm::Triple::Fuchsia:
David Blaikie6ad71012017-01-13 18:53:43 +00003764 TC = llvm::make_unique<toolchains::Fuchsia>(*this, Target, Args);
Petr Hosek62e1d232016-10-06 06:08:09 +00003765 break;
David Chisnallf571cde2012-02-15 13:39:01 +00003766 case llvm::Triple::Solaris:
David Blaikie6ad71012017-01-13 18:53:43 +00003767 TC = llvm::make_unique<toolchains::Solaris>(*this, Target, Args);
David Chisnallf571cde2012-02-15 13:39:01 +00003768 break;
Tom Stellard8fa33092015-07-18 01:49:05 +00003769 case llvm::Triple::AMDHSA:
David Blaikie6ad71012017-01-13 18:53:43 +00003770 TC = llvm::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args);
Tom Stellard8fa33092015-07-18 01:49:05 +00003771 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003772 case llvm::Triple::Win32:
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00003773 switch (Target.getEnvironment()) {
3774 default:
3775 if (Target.isOSBinFormatELF())
David Blaikie6ad71012017-01-13 18:53:43 +00003776 TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00003777 else if (Target.isOSBinFormatMachO())
David Blaikie6ad71012017-01-13 18:53:43 +00003778 TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00003779 else
David Blaikie6ad71012017-01-13 18:53:43 +00003780 TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00003781 break;
3782 case llvm::Triple::GNU:
David Blaikie6ad71012017-01-13 18:53:43 +00003783 TC = llvm::make_unique<toolchains::MinGW>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00003784 break;
Saleem Abdulrasool543a78b2014-10-24 03:13:37 +00003785 case llvm::Triple::Itanium:
David Blaikie6ad71012017-01-13 18:53:43 +00003786 TC = llvm::make_unique<toolchains::CrossWindowsToolChain>(*this, Target,
3787 Args);
Saleem Abdulrasool543a78b2014-10-24 03:13:37 +00003788 break;
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00003789 case llvm::Triple::MSVC:
3790 case llvm::Triple::UnknownEnvironment:
David Blaikie6ad71012017-01-13 18:53:43 +00003791 TC = llvm::make_unique<toolchains::MSVCToolChain>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00003792 break;
3793 }
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003794 break;
Filipe Cabecinhasc888e192015-10-14 12:25:43 +00003795 case llvm::Triple::PS4:
David Blaikie6ad71012017-01-13 18:53:43 +00003796 TC = llvm::make_unique<toolchains::PS4CPU>(*this, Target, Args);
Filipe Cabecinhasc888e192015-10-14 12:25:43 +00003797 break;
David L Kreitzerd397ea42016-10-14 20:44:33 +00003798 case llvm::Triple::Contiki:
David Blaikie6ad71012017-01-13 18:53:43 +00003799 TC = llvm::make_unique<toolchains::Contiki>(*this, Target, Args);
David L Kreitzerd397ea42016-10-14 20:44:33 +00003800 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003801 default:
Douglas Katzman9f5e70e2015-05-26 18:01:33 +00003802 // Of these targets, Hexagon is the only one that might have
3803 // an OS of Linux, in which case it got handled above already.
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003804 switch (Target.getArch()) {
3805 case llvm::Triple::tce:
David Blaikie6ad71012017-01-13 18:53:43 +00003806 TC = llvm::make_unique<toolchains::TCEToolChain>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003807 break;
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00003808 case llvm::Triple::tcele:
David Blaikie6ad71012017-01-13 18:53:43 +00003809 TC = llvm::make_unique<toolchains::TCELEToolChain>(*this, Target, Args);
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00003810 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003811 case llvm::Triple::hexagon:
David Blaikie6ad71012017-01-13 18:53:43 +00003812 TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
3813 Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003814 break;
Jacques Pienaard964cc22016-03-28 21:02:54 +00003815 case llvm::Triple::lanai:
David Blaikie6ad71012017-01-13 18:53:43 +00003816 TC = llvm::make_unique<toolchains::LanaiToolChain>(*this, Target, Args);
Jacques Pienaard964cc22016-03-28 21:02:54 +00003817 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003818 case llvm::Triple::xcore:
David Blaikie6ad71012017-01-13 18:53:43 +00003819 TC = llvm::make_unique<toolchains::XCoreToolChain>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003820 break;
Dan Gohmanc2853072015-09-03 22:51:53 +00003821 case llvm::Triple::wasm32:
3822 case llvm::Triple::wasm64:
David Blaikie6ad71012017-01-13 18:53:43 +00003823 TC = llvm::make_unique<toolchains::WebAssembly>(*this, Target, Args);
Dan Gohmanc2853072015-09-03 22:51:53 +00003824 break;
Dylan McKay924fa3a2017-01-05 05:20:27 +00003825 case llvm::Triple::avr:
David Blaikie6ad71012017-01-13 18:53:43 +00003826 TC = llvm::make_unique<toolchains::AVRToolChain>(*this, Target, Args);
Dylan McKay924fa3a2017-01-05 05:20:27 +00003827 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003828 default:
Douglas Katzmand6e597c2015-09-17 19:56:40 +00003829 if (Target.getVendor() == llvm::Triple::Myriad)
David Blaikie6ad71012017-01-13 18:53:43 +00003830 TC = llvm::make_unique<toolchains::MyriadToolChain>(*this, Target,
3831 Args);
Jonathan Roelofs901c7762017-05-25 15:42:13 +00003832 else if (toolchains::BareMetal::handlesTarget(Target))
3833 TC = llvm::make_unique<toolchains::BareMetal>(*this, Target, Args);
Douglas Katzmand6e597c2015-09-17 19:56:40 +00003834 else if (Target.isOSBinFormatELF())
David Blaikie6ad71012017-01-13 18:53:43 +00003835 TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003836 else if (Target.isOSBinFormatMachO())
David Blaikie6ad71012017-01-13 18:53:43 +00003837 TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003838 else
David Blaikie6ad71012017-01-13 18:53:43 +00003839 TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003840 }
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003841 }
3842 }
Justin Lebar66c4fd72016-11-18 00:41:22 +00003843
3844 // Intentionally omitted from the switch above: llvm::Triple::CUDA. CUDA
3845 // compiles always need two toolchains, the CUDA toolchain and the host
3846 // toolchain. So the only valid way to create a CUDA toolchain is via
3847 // CreateOffloadingDeviceToolChains.
3848
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003849 return *TC;
Daniel Dunbar4dff6a42009-03-10 23:41:59 +00003850}
Daniel Dunbar8fa879d2009-03-24 18:57:02 +00003851
Rafael Espindola2f69d402013-03-18 15:33:26 +00003852bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
Douglas Katzman00249092015-06-12 15:45:21 +00003853 // Say "no" if there is not exactly one input of a type clang understands.
Nico Weber5a459f82016-02-23 19:30:43 +00003854 if (JA.size() != 1 ||
3855 !types::isAcceptedByClang((*JA.input_begin())->getType()))
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00003856 return false;
3857
Douglas Katzman00249092015-06-12 15:45:21 +00003858 // And say "no" if this is not a kind of action clang understands.
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00003859 if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
Bob Wilson23a55f12014-12-21 07:00:00 +00003860 !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00003861 return false;
3862
3863 return true;
3864}
3865
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003866/// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
3867/// grouped values as integers. Numbers which are not provided are set to 0.
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003868///
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003869/// \return True if the entire string was parsed (9.2), or all groups were
3870/// parsed (10.3.5extrastuff).
Mehdi Amini12011172016-10-06 05:11:48 +00003871bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
3872 unsigned &Micro, bool &HadExtra) {
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003873 HadExtra = false;
3874
3875 Major = Minor = Micro = 0;
Mehdi Amini12011172016-10-06 05:11:48 +00003876 if (Str.empty())
Bob Wilson433cb312015-04-07 01:03:35 +00003877 return false;
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003878
Mehdi Amini12011172016-10-06 05:11:48 +00003879 if (Str.consumeInteger(10, Major))
3880 return false;
3881 if (Str.empty())
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003882 return true;
Mehdi Amini12011172016-10-06 05:11:48 +00003883 if (Str[0] != '.')
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003884 return false;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003885
Mehdi Amini12011172016-10-06 05:11:48 +00003886 Str = Str.drop_front(1);
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003887
Mehdi Amini12011172016-10-06 05:11:48 +00003888 if (Str.consumeInteger(10, Minor))
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003889 return false;
Mehdi Amini12011172016-10-06 05:11:48 +00003890 if (Str.empty())
3891 return true;
3892 if (Str[0] != '.')
3893 return false;
3894 Str = Str.drop_front(1);
3895
3896 if (Str.consumeInteger(10, Micro))
3897 return false;
3898 if (!Str.empty())
3899 HadExtra = true;
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003900 return true;
3901}
Hans Wennborg6ddc6902013-07-27 00:23:45 +00003902
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00003903/// Parse digits from a string \p Str and fulfill \p Digits with
3904/// the parsed numbers. This method assumes that the max number of
3905/// digits to look for is equal to Digits.size().
3906///
3907/// \return True if the entire string was parsed and there are
3908/// no extra characters remaining at the end.
Mehdi Amini12011172016-10-06 05:11:48 +00003909bool Driver::GetReleaseVersion(StringRef Str,
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00003910 MutableArrayRef<unsigned> Digits) {
Mehdi Amini12011172016-10-06 05:11:48 +00003911 if (Str.empty())
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00003912 return false;
3913
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00003914 unsigned CurDigit = 0;
3915 while (CurDigit < Digits.size()) {
Mehdi Amini12011172016-10-06 05:11:48 +00003916 unsigned Digit;
3917 if (Str.consumeInteger(10, Digit))
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00003918 return false;
Mehdi Amini12011172016-10-06 05:11:48 +00003919 Digits[CurDigit] = Digit;
3920 if (Str.empty())
3921 return true;
3922 if (Str[0] != '.')
3923 return false;
3924 Str = Str.drop_front(1);
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00003925 CurDigit++;
3926 }
3927
3928 // More digits than requested, bail out...
3929 return false;
3930}
3931
Hans Wennborg6ddc6902013-07-27 00:23:45 +00003932std::pair<unsigned, unsigned> Driver::getIncludeExcludeOptionFlagMasks() const {
3933 unsigned IncludedFlagsBitmask = 0;
Rafael Espindolacc707bc2013-09-25 15:54:41 +00003934 unsigned ExcludedFlagsBitmask = options::NoDriverOption;
Hans Wennborg6ddc6902013-07-27 00:23:45 +00003935
3936 if (Mode == CLMode) {
Hans Wennborg19076102013-07-31 20:51:53 +00003937 // Include CL and Core options.
3938 IncludedFlagsBitmask |= options::CLOption;
3939 IncludedFlagsBitmask |= options::CoreOption;
Hans Wennborg6ddc6902013-07-27 00:23:45 +00003940 } else {
3941 ExcludedFlagsBitmask |= options::CLOption;
3942 }
3943
3944 return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
3945}
Benjamin Kramerab88f622014-03-25 18:02:07 +00003946
Douglas Katzmanf08fadf2015-06-04 14:40:44 +00003947bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
Benjamin Kramerab88f622014-03-25 18:02:07 +00003948 return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);
3949}