blob: eb504fd4e54134cfd8df1845a897e1ba95cd0363 [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"
Dimitry Andric81c40422017-06-06 21:54:21 +000071#include "llvm/Support/TargetRegistry.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000072#include "llvm/Support/raw_ostream.h"
Dylan Noblesmith4f4e7452012-02-02 00:40:14 +000073#include <map>
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000074#include <memory>
Benjamin Kramercfeacf52016-05-27 14:27:13 +000075#include <utility>
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +000076#if LLVM_ON_UNIX
77#include <unistd.h> // getpid
78#endif
Dylan Noblesmith86780e92012-02-01 14:25:28 +000079
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000080using namespace clang::driver;
Chris Lattnerada1c912009-03-26 05:56:24 +000081using namespace clang;
Reid Kleckner898229a2013-06-14 17:17:23 +000082using namespace llvm::opt;
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000083
Reid Kleckner68eb60b2015-02-02 22:41:48 +000084Driver::Driver(StringRef ClangExecutable, StringRef DefaultTargetTriple,
Benjamin Kramerd45b2052015-10-07 15:48:01 +000085 DiagnosticsEngine &Diags,
86 IntrusiveRefCntPtr<vfs::FileSystem> VFS)
Benjamin Kramercfeacf52016-05-27 14:27:13 +000087 : Opts(createDriverOptTable()), Diags(Diags), VFS(std::move(VFS)),
88 Mode(GCCMode), SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
89 LTOMode(LTOK_None), ClangExecutable(ClangExecutable),
Reid Kleckner68eb60b2015-02-02 22:41:48 +000090 SysRoot(DEFAULT_SYSROOT), UseStdLib(true),
Reid Kleckner68eb60b2015-02-02 22:41:48 +000091 DriverTitle("clang LLVM compiler"), CCPrintOptionsFilename(nullptr),
92 CCPrintHeadersFilename(nullptr), CCLogDiagnosticsFilename(nullptr),
93 CCCPrintBindings(false), CCPrintHeaders(false), CCLogDiagnostics(false),
Vedant Kumarf2030b92016-07-18 19:56:33 +000094 CCGenDiagnostics(false), DefaultTargetTriple(DefaultTargetTriple),
95 CCCGenericGCCName(""), CheckInputsExist(true), CCCUsePCH(true),
Bruno Cardoso Lopes52dfe712017-04-12 21:46:20 +000096 GenReproducer(false), SuppressMissingInputWarning(false) {
Daniel Dunbar3f3e2cd2010-01-20 02:35:16 +000097
Benjamin Kramerd45b2052015-10-07 15:48:01 +000098 // Provide a sane fallback if no VFS is specified.
99 if (!this->VFS)
100 this->VFS = vfs::getRealFileSystem();
101
Sumanth Gundapaneni3a1592942015-03-03 20:43:12 +0000102 Name = llvm::sys::path::filename(ClangExecutable);
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000103 Dir = llvm::sys::path::parent_path(ClangExecutable);
Benjamin Kramerf420dda2015-10-13 15:19:32 +0000104 InstalledDir = Dir; // Provide a sensible default installed dir.
Bob Wilsona20a1da2013-03-23 05:17:59 +0000105
106 // Compute the path to the resource directory.
107 StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
108 SmallString<128> P(Dir);
Chandler Carruthfd3cc702014-12-29 12:09:08 +0000109 if (ClangResourceDir != "") {
Bob Wilsona20a1da2013-03-23 05:17:59 +0000110 llvm::sys::path::append(P, ClangResourceDir);
Chandler Carruthfd3cc702014-12-29 12:09:08 +0000111 } else {
112 StringRef ClangLibdirSuffix(CLANG_LIBDIR_SUFFIX);
Argyrios Kyrtzidisbcae0472017-02-25 18:14:35 +0000113 P = llvm::sys::path::parent_path(Dir);
114 llvm::sys::path::append(P, Twine("lib") + ClangLibdirSuffix, "clang",
Chandler Carruthfd3cc702014-12-29 12:09:08 +0000115 CLANG_VERSION_STRING);
116 }
Bob Wilsona20a1da2013-03-23 05:17:59 +0000117 ResourceDir = P.str();
Daniel Dunbar544ecd12009-03-02 19:59:07 +0000118}
119
Zachary Turneraff19c32016-08-12 17:47:52 +0000120void Driver::ParseDriverMode(StringRef ProgramName,
121 ArrayRef<const char *> Args) {
122 auto Default = ToolChain::getTargetAndModeFromProgramName(ProgramName);
123 StringRef DefaultMode(Default.second);
124 setDriverModeFromOption(DefaultMode);
Hans Wennborg70850d82013-07-18 20:29:38 +0000125
Douglas Katzman6bbffc42015-06-25 18:51:37 +0000126 for (const char *ArgPtr : Args) {
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000127 // Ingore nullptrs, they are response file's EOL markers
Douglas Katzman6bbffc42015-06-25 18:51:37 +0000128 if (ArgPtr == nullptr)
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000129 continue;
Douglas Katzman6bbffc42015-06-25 18:51:37 +0000130 const StringRef Arg = ArgPtr;
Zachary Turneraff19c32016-08-12 17:47:52 +0000131 setDriverModeFromOption(Arg);
Hans Wennborg70850d82013-07-18 20:29:38 +0000132 }
133}
134
Zachary Turneraff19c32016-08-12 17:47:52 +0000135void Driver::setDriverModeFromOption(StringRef Opt) {
136 const std::string OptName =
137 getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
138 if (!Opt.startswith(OptName))
139 return;
140 StringRef Value = Opt.drop_front(OptName.size());
141
142 const unsigned M = llvm::StringSwitch<unsigned>(Value)
143 .Case("gcc", GCCMode)
144 .Case("g++", GXXMode)
145 .Case("cpp", CPPMode)
146 .Case("cl", CLMode)
147 .Default(~0U);
148
149 if (M != ~0U)
150 Mode = static_cast<DriverMode>(M);
151 else
152 Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
153}
154
David Blaikie69a1d8c2015-06-22 22:07:27 +0000155InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings) {
Daniel Dunbar2608c542009-03-18 01:38:48 +0000156 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
Hans Wennborg6ddc6902013-07-27 00:23:45 +0000157
158 unsigned IncludedFlagsBitmask;
159 unsigned ExcludedFlagsBitmask;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000160 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000161 getIncludeExcludeOptionFlagMasks();
Hans Wennborg6ddc6902013-07-27 00:23:45 +0000162
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000163 unsigned MissingArgIndex, MissingArgCount;
David Blaikie69a1d8c2015-06-22 22:07:27 +0000164 InputArgList Args =
David Blaikie6d492ad2015-06-21 06:32:36 +0000165 getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
166 IncludedFlagsBitmask, ExcludedFlagsBitmask);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +0000167
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000168 // Check for missing argument error.
169 if (MissingArgCount)
170 Diag(clang::diag::err_drv_missing_argument)
David Blaikie69a1d8c2015-06-22 22:07:27 +0000171 << Args.getArgString(MissingArgIndex) << MissingArgCount;
Daniel Dunbar65229332009-03-13 11:38:42 +0000172
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000173 // Check for unsupported options.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000174 for (const Arg *A : Args) {
Michael J. Spencer66e2b202012-10-19 22:37:06 +0000175 if (A->getOption().hasFlag(options::Unsupported)) {
David Blaikie69a1d8c2015-06-22 22:07:27 +0000176 Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(Args);
Daniel Dunbard8500f32009-03-22 23:26:43 +0000177 continue;
178 }
Chad Rosierce975d92012-02-22 17:55:22 +0000179
180 // Warn about -mcpu= without an argument.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000181 if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
David Blaikie69a1d8c2015-06-22 22:07:27 +0000182 Diag(clang::diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
Chad Rosierce975d92012-02-22 17:55:22 +0000183 }
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000184 }
185
David Blaikie69a1d8c2015-06-22 22:07:27 +0000186 for (const Arg *A : Args.filtered(options::OPT_UNKNOWN))
Ehsan Akhgarid8518332016-01-25 21:14:52 +0000187 Diags.Report(IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl :
188 diag::err_drv_unknown_argument)
189 << A->getAsString(Args);
Rafael Espindola8a2d4962013-09-23 23:55:25 +0000190
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000191 return Args;
192}
193
Chad Rosier7742b5d2011-07-27 23:36:45 +0000194// Determine which compilation mode we are in. We look for options which
195// affect the phase, starting with the earliest phases, and record which
196// option we used to determine the final phase.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000197phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
198 Arg **FinalPhaseArg) const {
Craig Topper92fc2df2014-05-17 16:56:41 +0000199 Arg *PhaseArg = nullptr;
Chad Rosier7742b5d2011-07-27 23:36:45 +0000200 phases::ID FinalPhase;
Eric Christopherf901e852011-08-17 22:59:59 +0000201
Hans Wennborge50cec32014-06-13 20:59:54 +0000202 // -{E,EP,P,M,MM} only run the preprocessor.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000203 if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
Hans Wennborge50cec32014-06-13 20:59:54 +0000204 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
Hans Wennborge0053472013-12-20 18:40:46 +0000205 (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
206 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000207 FinalPhase = phases::Preprocess;
Eric Christopherf901e852011-08-17 22:59:59 +0000208
Richard Smithdd4ad3d2016-08-30 19:06:26 +0000209 // --precompile only runs up to precompilation.
210 } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile))) {
211 FinalPhase = phases::Precompile;
212
Bob Wilson23a55f12014-12-21 07:00:00 +0000213 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
Chad Rosier7742b5d2011-07-27 23:36:45 +0000214 } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000215 (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
Ben Langmuir2cb4a782014-02-05 22:21:15 +0000216 (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
Chad Rosier7742b5d2011-07-27 23:36:45 +0000217 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
Fariborz Jahanian73223bb2012-04-02 15:59:19 +0000218 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
Ted Kremenekf7639e12012-03-06 20:06:33 +0000219 (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
Chad Rosier7742b5d2011-07-27 23:36:45 +0000220 (PhaseArg = DAL.getLastArg(options::OPT__analyze,
Chad Rosier1aeb15a2012-03-06 23:14:35 +0000221 options::OPT__analyze_auto)) ||
Bob Wilson23a55f12014-12-21 07:00:00 +0000222 (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000223 FinalPhase = phases::Compile;
224
Bob Wilson23a55f12014-12-21 07:00:00 +0000225 // -S only runs up to the backend.
226 } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
227 FinalPhase = phases::Backend;
228
Artem Belevich4242f412015-07-28 21:01:21 +0000229 // -c compilation only runs up to the assembler.
230 } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000231 FinalPhase = phases::Assemble;
232
233 // Otherwise do everything.
234 } else
235 FinalPhase = phases::Link;
236
237 if (FinalPhaseArg)
238 *FinalPhaseArg = PhaseArg;
239
240 return FinalPhase;
241}
242
David Blaikie0aaa7622017-01-13 17:34:15 +0000243static Arg *MakeInputArg(DerivedArgList &Args, OptTable &Opts,
Hans Wennborged1d0722013-08-13 21:32:29 +0000244 StringRef Value) {
David Blaikie0aaa7622017-01-13 17:34:15 +0000245 Arg *A = new Arg(Opts.getOption(options::OPT_INPUT), Value,
Hans Wennborged1d0722013-08-13 21:32:29 +0000246 Args.getBaseArgs().MakeIndex(Value), Value.data());
Hans Wennborg55362852014-05-02 22:55:30 +0000247 Args.AddSynthesizedArg(A);
Hans Wennborged1d0722013-08-13 21:32:29 +0000248 A->claim();
249 return A;
250}
251
Daniel Dunbar775d4062010-06-11 22:00:26 +0000252DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
253 DerivedArgList *DAL = new DerivedArgList(Args);
254
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000255 bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
Nirav Daveb0bb6142015-11-24 16:07:21 +0000256 bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +0000257 for (Arg *A : Args) {
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000258 // Unfortunately, we have to parse some forwarding options (-Xassembler,
259 // -Xlinker, -Xpreprocessor) because we either integrate their functionality
260 // (assembler and preprocessor), or bypass a previous driver ('collect2').
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000261
262 // Rewrite linker options, to replace --no-demangle with a custom internal
263 // option.
264 if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
265 A->getOption().matches(options::OPT_Xlinker)) &&
266 A->containsValue("--no-demangle")) {
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000267 // Add the rewritten no-demangle argument.
268 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
269
270 // Add the remaining values as Xlinker arguments.
Benjamin Kramer72e64312015-09-24 14:48:49 +0000271 for (StringRef Val : A->getValues())
Douglas Katzmana34b7bf2015-06-30 19:32:57 +0000272 if (Val != "--no-demangle")
273 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), Val);
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000274
275 continue;
276 }
277
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000278 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
279 // some build systems. We don't try to be complete here because we don't
280 // care to encourage this usage model.
281 if (A->getOption().matches(options::OPT_Wp_COMMA) &&
Richard Smithbd55daf2012-11-01 04:30:05 +0000282 (A->getValue(0) == StringRef("-MD") ||
283 A->getValue(0) == StringRef("-MMD"))) {
Daniel Dunbar3648ba72010-06-15 20:30:18 +0000284 // Rewrite to -MD/-MMD along with -MF.
Richard Smithbd55daf2012-11-01 04:30:05 +0000285 if (A->getValue(0) == StringRef("-MD"))
Daniel Dunbar3648ba72010-06-15 20:30:18 +0000286 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
287 else
288 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
Michael J. Spencer70d85be2012-11-07 23:37:14 +0000289 if (A->getNumValues() == 2)
290 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
291 A->getValue(1));
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000292 continue;
293 }
294
Shantonu Senafeb03b2010-09-17 18:39:08 +0000295 // Rewrite reserved library names.
296 if (A->getOption().matches(options::OPT_l)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000297 StringRef Value = A->getValue();
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000298
Shantonu Senafeb03b2010-09-17 18:39:08 +0000299 // Rewrite unless -nostdlib is present.
Nirav Daveb0bb6142015-11-24 16:07:21 +0000300 if (!HasNostdlib && !HasNodefaultlib && Value == "stdc++") {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000301 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_stdcxx));
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000302 continue;
303 }
Shantonu Senafeb03b2010-09-17 18:39:08 +0000304
305 // Rewrite unconditionally.
306 if (Value == "cc_kext") {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000307 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_cckext));
Shantonu Senafeb03b2010-09-17 18:39:08 +0000308 continue;
309 }
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000310 }
311
Hans Wennborged1d0722013-08-13 21:32:29 +0000312 // Pick up inputs via the -- option.
313 if (A->getOption().matches(options::OPT__DASH_DASH)) {
314 A->claim();
Benjamin Kramer72e64312015-09-24 14:48:49 +0000315 for (StringRef Val : A->getValues())
David Blaikie0aaa7622017-01-13 17:34:15 +0000316 DAL->append(MakeInputArg(*DAL, *Opts, Val));
Hans Wennborged1d0722013-08-13 21:32:29 +0000317 continue;
318 }
319
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +0000320 DAL->append(A);
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000321 }
Daniel Dunbar775d4062010-06-11 22:00:26 +0000322
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000323 // Enforce -static if -miamcu is present.
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000324 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false))
325 DAL->AddFlagArg(0, Opts->getOption(options::OPT_static));
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000326
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000327// Add a default value of -mlinker-version=, if one was given and the user
328// didn't specify one.
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000329#if defined(HOST_LINK_VERSION)
Tim Northover018578c2015-06-12 19:21:35 +0000330 if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
331 strlen(HOST_LINK_VERSION) > 0) {
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000332 DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
333 HOST_LINK_VERSION);
Daniel Dunbarb613ffc2010-08-17 22:32:45 +0000334 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000335 }
336#endif
337
Daniel Dunbar775d4062010-06-11 22:00:26 +0000338 return DAL;
339}
340
Artem Belevich959e0542015-07-10 19:47:55 +0000341/// \brief Compute target triple from args.
342///
343/// This routine provides the logic to compute a target triple from various
344/// args passed to the driver and the default triple string.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000345static llvm::Triple computeTargetTriple(const Driver &D,
346 StringRef DefaultTargetTriple,
Artem Belevich959e0542015-07-10 19:47:55 +0000347 const ArgList &Args,
348 StringRef DarwinArchName = "") {
349 // FIXME: Already done in Compilation *Driver::BuildCompilation
350 if (const Arg *A = Args.getLastArg(options::OPT_target))
351 DefaultTargetTriple = A->getValue();
352
353 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
354
355 // Handle Apple-specific options available here.
356 if (Target.isOSBinFormatMachO()) {
357 // If an explict Darwin arch name is given, that trumps all.
358 if (!DarwinArchName.empty()) {
359 tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
360 return Target;
361 }
362
363 // Handle the Darwin '-arch' flag.
364 if (Arg *A = Args.getLastArg(options::OPT_arch)) {
365 StringRef ArchName = A->getValue();
366 tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
367 }
368 }
369
370 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
371 // '-mbig-endian'/'-EB'.
372 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
373 options::OPT_mbig_endian)) {
374 if (A->getOption().matches(options::OPT_mlittle_endian)) {
375 llvm::Triple LE = Target.getLittleEndianArchVariant();
376 if (LE.getArch() != llvm::Triple::UnknownArch)
377 Target = std::move(LE);
378 } else {
379 llvm::Triple BE = Target.getBigEndianArchVariant();
380 if (BE.getArch() != llvm::Triple::UnknownArch)
381 Target = std::move(BE);
382 }
383 }
384
385 // Skip further flag support on OSes which don't support '-m32' or '-m64'.
Douglas Katzman15a63ed2015-08-12 18:36:12 +0000386 if (Target.getArch() == llvm::Triple::tce ||
387 Target.getOS() == llvm::Triple::Minix)
Artem Belevich959e0542015-07-10 19:47:55 +0000388 return Target;
389
390 // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000391 Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
392 options::OPT_m32, options::OPT_m16);
393 if (A) {
Artem Belevich959e0542015-07-10 19:47:55 +0000394 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
395
396 if (A->getOption().matches(options::OPT_m64)) {
397 AT = Target.get64BitArchVariant().getArch();
398 if (Target.getEnvironment() == llvm::Triple::GNUX32)
399 Target.setEnvironment(llvm::Triple::GNU);
400 } else if (A->getOption().matches(options::OPT_mx32) &&
401 Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
402 AT = llvm::Triple::x86_64;
403 Target.setEnvironment(llvm::Triple::GNUX32);
404 } else if (A->getOption().matches(options::OPT_m32)) {
405 AT = Target.get32BitArchVariant().getArch();
406 if (Target.getEnvironment() == llvm::Triple::GNUX32)
407 Target.setEnvironment(llvm::Triple::GNU);
408 } else if (A->getOption().matches(options::OPT_m16) &&
409 Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
410 AT = llvm::Triple::x86;
411 Target.setEnvironment(llvm::Triple::CODE16);
412 }
413
414 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
415 Target.setArch(AT);
416 }
417
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000418 // Handle -miamcu flag.
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000419 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
420 if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
421 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
422 << Target.str();
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000423
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000424 if (A && !A->getOption().matches(options::OPT_m32))
425 D.Diag(diag::err_drv_argument_not_allowed_with)
426 << "-miamcu" << A->getBaseArg().getAsString(Args);
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000427
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000428 Target.setArch(llvm::Triple::x86);
429 Target.setArchName("i586");
430 Target.setEnvironment(llvm::Triple::UnknownEnvironment);
431 Target.setEnvironmentName("");
432 Target.setOS(llvm::Triple::ELFIAMCU);
433 Target.setVendor(llvm::Triple::UnknownVendor);
434 Target.setVendorName("intel");
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000435 }
436
Artem Belevich959e0542015-07-10 19:47:55 +0000437 return Target;
438}
439
Teresa Johnson945bc502015-10-15 20:35:53 +0000440// \brief Parse the LTO options and record the type of LTO compilation
441// based on which -f(no-)?lto(=.*)? option occurs last.
442void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
443 LTOMode = LTOK_None;
444 if (!Args.hasFlag(options::OPT_flto, options::OPT_flto_EQ,
445 options::OPT_fno_lto, false))
446 return;
447
448 StringRef LTOName("full");
449
450 const Arg *A = Args.getLastArg(options::OPT_flto_EQ);
Teresa Johnson6ef80dc2015-11-02 18:03:12 +0000451 if (A)
452 LTOName = A->getValue();
Teresa Johnson945bc502015-10-15 20:35:53 +0000453
454 LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
455 .Case("full", LTOK_Full)
456 .Case("thin", LTOK_Thin)
457 .Default(LTOK_Unknown);
458
459 if (LTOMode == LTOK_Unknown) {
460 assert(A);
461 Diag(diag::err_drv_unsupported_option_argument) << A->getOption().getName()
462 << A->getValue();
463 }
464}
465
Samuel Antao39f9da22016-10-27 16:38:05 +0000466/// Compute the desired OpenMP runtime from the flags provided.
467Driver::OpenMPRuntimeKind Driver::getOpenMPRuntime(const ArgList &Args) const {
468 StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
469
470 const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
471 if (A)
472 RuntimeName = A->getValue();
473
474 auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
475 .Case("libomp", OMPRT_OMP)
476 .Case("libgomp", OMPRT_GOMP)
477 .Case("libiomp5", OMPRT_IOMP5)
478 .Default(OMPRT_Unknown);
479
480 if (RT == OMPRT_Unknown) {
481 if (A)
482 Diag(diag::err_drv_unsupported_option_argument)
483 << A->getOption().getName() << A->getValue();
484 else
485 // FIXME: We could use a nicer diagnostic here.
486 Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
487 }
488
489 return RT;
490}
491
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000492void Driver::CreateOffloadingDeviceToolChains(Compilation &C,
493 InputList &Inputs) {
494
495 //
496 // CUDA
497 //
498 // We need to generate a CUDA toolchain if any of the inputs has a CUDA type.
499 if (llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
500 return types::isCuda(I.first);
501 })) {
Justin Lebar66c4fd72016-11-18 00:41:22 +0000502 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
503 const llvm::Triple &HostTriple = HostTC->getTriple();
504 llvm::Triple CudaTriple(HostTriple.isArch64Bit() ? "nvptx64-nvidia-cuda"
505 : "nvptx-nvidia-cuda");
506 // Use the CUDA and host triples as the key into the ToolChains map, because
507 // the device toolchain we create depends on both.
David Blaikie6ad71012017-01-13 18:53:43 +0000508 auto &CudaTC = ToolChains[CudaTriple.str() + "/" + HostTriple.str()];
Justin Lebar66c4fd72016-11-18 00:41:22 +0000509 if (!CudaTC) {
David Blaikie6ad71012017-01-13 18:53:43 +0000510 CudaTC = llvm::make_unique<toolchains::CudaToolChain>(
511 *this, CudaTriple, *HostTC, C.getInputArgs());
Justin Lebar66c4fd72016-11-18 00:41:22 +0000512 }
David Blaikie6ad71012017-01-13 18:53:43 +0000513 C.addOffloadDeviceToolChain(CudaTC.get(), Action::OFK_Cuda);
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000514 }
515
516 //
Samuel Antao39f9da22016-10-27 16:38:05 +0000517 // OpenMP
518 //
519 // We need to generate an OpenMP toolchain if the user specified targets with
520 // the -fopenmp-targets option.
521 if (Arg *OpenMPTargets =
522 C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
523 if (OpenMPTargets->getNumValues()) {
524 // We expect that -fopenmp-targets is always used in conjunction with the
525 // option -fopenmp specifying a valid runtime with offloading support,
526 // i.e. libomp or libiomp.
527 bool HasValidOpenMPRuntime = C.getInputArgs().hasFlag(
528 options::OPT_fopenmp, options::OPT_fopenmp_EQ,
529 options::OPT_fno_openmp, false);
530 if (HasValidOpenMPRuntime) {
531 OpenMPRuntimeKind OpenMPKind = getOpenMPRuntime(C.getInputArgs());
532 HasValidOpenMPRuntime =
533 OpenMPKind == OMPRT_OMP || OpenMPKind == OMPRT_IOMP5;
534 }
535
536 if (HasValidOpenMPRuntime) {
537 llvm::StringMap<const char *> FoundNormalizedTriples;
538 for (const char *Val : OpenMPTargets->getValues()) {
539 llvm::Triple TT(Val);
540 std::string NormalizedName = TT.normalize();
541
542 // Make sure we don't have a duplicate triple.
543 auto Duplicate = FoundNormalizedTriples.find(NormalizedName);
544 if (Duplicate != FoundNormalizedTriples.end()) {
545 Diag(clang::diag::warn_drv_omp_offload_target_duplicate)
546 << Val << Duplicate->second;
547 continue;
548 }
549
550 // Store the current triple so that we can check for duplicates in the
551 // following iterations.
552 FoundNormalizedTriples[NormalizedName] = Val;
553
554 // If the specified target is invalid, emit a diagnostic.
555 if (TT.getArch() == llvm::Triple::UnknownArch)
556 Diag(clang::diag::err_drv_invalid_omp_target) << Val;
557 else {
558 const ToolChain &TC = getToolChain(C.getInputArgs(), TT);
559 C.addOffloadDeviceToolChain(&TC, Action::OFK_OpenMP);
560 }
561 }
562 } else
563 Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
564 } else
565 Diag(clang::diag::warn_drv_empty_joined_argument)
566 << OpenMPTargets->getAsString(C.getInputArgs());
567 }
568
569 //
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000570 // TODO: Add support for other offloading programming models here.
571 //
572
573 return;
574}
575
Chris Lattner54b16772011-07-23 17:14:25 +0000576Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
Daniel Dunbar2608c542009-03-18 01:38:48 +0000577 llvm::PrettyStackTraceString CrashInfo("Compilation construction");
578
Eric Christopherf901e852011-08-17 22:59:59 +0000579 // FIXME: Handle environment options which affect driver behavior, somewhere
Bill Wendlingadbeb9f2012-03-12 21:24:57 +0000580 // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
Chad Rosier82301162011-09-14 00:47:55 +0000581
David Majnemer85c25b42016-07-24 17:44:03 +0000582 if (Optional<std::string> CompilerPathValue =
583 llvm::sys::Process::GetEnv("COMPILER_PATH")) {
584 StringRef CompilerPath = *CompilerPathValue;
Chad Rosier82301162011-09-14 00:47:55 +0000585 while (!CompilerPath.empty()) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000586 std::pair<StringRef, StringRef> Split =
587 CompilerPath.split(llvm::sys::EnvPathSeparator);
Chad Rosier82301162011-09-14 00:47:55 +0000588 PrefixDirs.push_back(Split.first);
589 CompilerPath = Split.second;
590 }
591 }
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +0000592
Hans Wennborg70850d82013-07-18 20:29:38 +0000593 // We look for the driver mode option early, because the mode can affect
594 // how other options are parsed.
Zachary Turneraff19c32016-08-12 17:47:52 +0000595 ParseDriverMode(ClangExecutable, ArgList.slice(1));
Hans Wennborg70850d82013-07-18 20:29:38 +0000596
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +0000597 // FIXME: What are we going to do with -V and -b?
598
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +0000599 // FIXME: This stuff needs to go into the Compilation, not the driver.
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +0000600 bool CCCPrintPhases;
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000601
David Blaikie69a1d8c2015-06-22 22:07:27 +0000602 InputArgList Args = ParseArgStrings(ArgList.slice(1));
Serge Pavlovb43573b2017-05-24 14:57:17 +0000603 if (Diags.hasErrorOccurred())
604 return nullptr;
Daniel Dunbaracd69572009-12-04 21:55:23 +0000605
Filipe Cabecinhas136f35e2015-07-18 06:35:24 +0000606 // Silence driver warnings if requested
607 Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w));
608
Rafael Espindola59ae7992009-12-07 18:28:29 +0000609 // -no-canonical-prefixes is used very early in main.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000610 Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
Rafael Espindola59ae7992009-12-07 18:28:29 +0000611
Daniel Dunbar926f81f2010-08-02 02:38:03 +0000612 // Ignore -pipe.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000613 Args.ClaimAllArgs(options::OPT_pipe);
Daniel Dunbar926f81f2010-08-02 02:38:03 +0000614
Daniel Dunbaracd69572009-12-04 21:55:23 +0000615 // Extract -ccc args.
Daniel Dunbaree66cf22009-03-10 20:52:46 +0000616 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +0000617 // FIXME: We need to figure out where this behavior should live. Most of it
618 // should be outside in the client; the parts that aren't should have proper
619 // options, either by introducing new ones or by overloading gcc ones like -V
620 // or -b.
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +0000621 CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
David Blaikie69a1d8c2015-06-22 22:07:27 +0000622 CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
623 if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
Richard Smithbd55daf2012-11-01 04:30:05 +0000624 CCCGenericGCCName = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000625 CCCUsePCH =
626 Args.hasFlag(options::OPT_ccc_pch_is_pch, options::OPT_ccc_pch_is_pth);
Bruno Cardoso Lopes52dfe712017-04-12 21:46:20 +0000627 GenReproducer = Args.hasFlag(options::OPT_gen_reproducer,
628 options::OPT_fno_crash_diagnostics,
629 !!::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH"));
Joerg Sonnenberger17d75512012-02-22 19:15:16 +0000630 // FIXME: DefaultTargetTriple is used by the target-prefixed calls to as/ld
631 // and getToolChain is const.
Hans Wennborg2e274592013-08-13 23:38:57 +0000632 if (IsCLMode()) {
Hans Wennborg73609a02014-03-28 01:19:04 +0000633 // clang-cl targets MSVC-style Win32.
Hans Wennborg2e274592013-08-13 23:38:57 +0000634 llvm::Triple T(DefaultTargetTriple);
Hans Wennborg9d9ce7a2014-03-28 20:49:28 +0000635 T.setOS(llvm::Triple::Win32);
Hans Wennborg0f0e8d62015-09-18 17:11:50 +0000636 T.setVendor(llvm::Triple::PC);
Hans Wennborg9d9ce7a2014-03-28 20:49:28 +0000637 T.setEnvironment(llvm::Triple::MSVC);
Hans Wennborg2e274592013-08-13 23:38:57 +0000638 DefaultTargetTriple = T.str();
639 }
David Blaikie69a1d8c2015-06-22 22:07:27 +0000640 if (const Arg *A = Args.getLastArg(options::OPT_target))
Richard Smithbd55daf2012-11-01 04:30:05 +0000641 DefaultTargetTriple = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000642 if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
Richard Smithbd55daf2012-11-01 04:30:05 +0000643 Dir = InstalledDir = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000644 for (const Arg *A : Args.filtered(options::OPT_B)) {
Benjamin Kramer1a648d12011-02-08 20:31:42 +0000645 A->claim();
Richard Smithbd55daf2012-11-01 04:30:05 +0000646 PrefixDirs.push_back(A->getValue(0));
Benjamin Kramer1a648d12011-02-08 20:31:42 +0000647 }
David Blaikie69a1d8c2015-06-22 22:07:27 +0000648 if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
Richard Smithbd55daf2012-11-01 04:30:05 +0000649 SysRoot = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000650 if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
Peter Collingbourne9d9e1fc2013-05-27 21:40:20 +0000651 DyldPrefix = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000652 if (Args.hasArg(options::OPT_nostdlib))
Joerg Sonnenbergerbc923f32011-03-21 13:59:26 +0000653 UseStdLib = false;
Daniel Dunbaree66cf22009-03-10 20:52:46 +0000654
David Blaikie69a1d8c2015-06-22 22:07:27 +0000655 if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
Bob Wilsona20a1da2013-03-23 05:17:59 +0000656 ResourceDir = A->getValue();
Jim Grosbach061dabf2013-03-12 20:17:58 +0000657
David Blaikie69a1d8c2015-06-22 22:07:27 +0000658 if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
Reid Kleckner68eb60b2015-02-02 22:41:48 +0000659 SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
660 .Case("cwd", SaveTempsCwd)
661 .Case("obj", SaveTempsObj)
662 .Default(SaveTempsCwd);
663 }
664
Steven Wu1257cd82016-05-18 17:04:52 +0000665 setLTOMode(Args);
666
Steven Wu844ab6a2016-11-16 06:06:44 +0000667 // Process -fembed-bitcode= flags.
668 if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
669 StringRef Name = A->getValue();
670 unsigned Model = llvm::StringSwitch<unsigned>(Name)
671 .Case("off", EmbedNone)
672 .Case("all", EmbedBitcode)
673 .Case("bitcode", EmbedBitcode)
674 .Case("marker", EmbedMarker)
675 .Default(~0U);
676 if (Model == ~0U) {
677 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
678 << Name;
679 } else
680 BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
Steven Wu574b0f22016-03-01 01:07:58 +0000681 }
682
David Blaikie69a1d8c2015-06-22 22:07:27 +0000683 std::unique_ptr<llvm::opt::InputArgList> UArgs =
684 llvm::make_unique<InputArgList>(std::move(Args));
685
Daniel Dunbar775d4062010-06-11 22:00:26 +0000686 // Perform the default argument translations.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000687 DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
Daniel Dunbar775d4062010-06-11 22:00:26 +0000688
Chandler Carruthcb916192012-01-25 08:49:21 +0000689 // Owned by the host.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000690 const ToolChain &TC = getToolChain(
691 *UArgs, computeTargetTriple(*this, DefaultTargetTriple, *UArgs));
Chandler Carruthcb916192012-01-25 08:49:21 +0000692
Daniel Dunbar3ce436d2009-03-16 06:42:30 +0000693 // The compilation takes ownership of Args.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000694 Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +0000695
Daniel Dunbarf0eddb82009-03-18 02:55:38 +0000696 if (!HandleImmediateArgs(*C))
697 return C;
698
Chad Rosierecdede82011-08-12 22:08:57 +0000699 // Construct the list of inputs.
700 InputList Inputs;
Hans Wennborged1d0722013-08-13 21:32:29 +0000701 BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
Chad Rosierecdede82011-08-12 22:08:57 +0000702
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000703 // Populate the tool chains for the offloading devices, if any.
704 CreateOffloadingDeviceToolChains(*C, Inputs);
Justin Lebar0e450a52016-03-30 23:30:25 +0000705
Chandler Carruth7f1417f2012-01-24 10:43:44 +0000706 // Construct the list of abstract actions to perform for this compilation. On
Tim Northover157d9112014-01-16 08:48:16 +0000707 // MachO targets this uses the driver-driver and universal actions.
708 if (TC.getTriple().isOSBinFormatMachO())
Artem Belevich5e2a3ec2015-11-17 22:28:40 +0000709 BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +0000710 else
Justin Lebar0f3474c2016-02-11 02:00:50 +0000711 BuildActions(*C, C->getArgs(), Inputs, C->getActions());
Daniel Dunbarf0eddb82009-03-18 02:55:38 +0000712
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +0000713 if (CCCPrintPhases) {
Daniel Dunbareb843be2009-03-18 03:13:20 +0000714 PrintActions(*C);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +0000715 return C;
716 }
717
718 BuildJobs(*C);
Daniel Dunbaradc91e62009-03-15 01:38:15 +0000719
720 return C;
Daniel Dunbaree66cf22009-03-10 20:52:46 +0000721}
722
Justin Bognered9cbe02015-07-09 06:58:31 +0000723static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
724 llvm::opt::ArgStringList ASL;
725 for (const auto *A : Args)
726 A->render(Args, ASL);
727
728 for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
729 if (I != ASL.begin())
730 OS << ' ';
731 Command::printArg(OS, *I, true);
732 }
733 OS << '\n';
734}
735
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +0000736bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename,
737 SmallString<128> &CrashDiagDir) {
738 using namespace llvm::sys;
739 assert(llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin() &&
740 "Only knows about .crash files on Darwin");
741
742 // The .crash file can be found on at ~/Library/Logs/DiagnosticReports/
743 // (or /Library/Logs/DiagnosticReports for root) and has the filename pattern
744 // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash.
745 path::home_directory(CrashDiagDir);
746 if (CrashDiagDir.startswith("/var/root"))
747 CrashDiagDir = "/";
748 path::append(CrashDiagDir, "Library/Logs/DiagnosticReports");
749 int PID =
750#if LLVM_ON_UNIX
751 getpid();
752#else
753 0;
754#endif
755 std::error_code EC;
756 fs::file_status FileStatus;
757 TimePoint<> LastAccessTime;
758 SmallString<128> CrashFilePath;
759 // Lookup the .crash files and get the one generated by a subprocess spawned
760 // by this driver invocation.
761 for (fs::directory_iterator File(CrashDiagDir, EC), FileEnd;
762 File != FileEnd && !EC; File.increment(EC)) {
763 StringRef FileName = path::filename(File->path());
764 if (!FileName.startswith(Name))
765 continue;
766 if (fs::status(File->path(), FileStatus))
767 continue;
768 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CrashFile =
769 llvm::MemoryBuffer::getFile(File->path());
770 if (!CrashFile)
771 continue;
772 // The first line should start with "Process:", otherwise this isn't a real
773 // .crash file.
774 StringRef Data = CrashFile.get()->getBuffer();
775 if (!Data.startswith("Process:"))
776 continue;
777 // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]"
778 size_t ParentProcPos = Data.find("Parent Process:");
779 if (ParentProcPos == StringRef::npos)
780 continue;
781 size_t LineEnd = Data.find_first_of("\n", ParentProcPos);
782 if (LineEnd == StringRef::npos)
783 continue;
784 StringRef ParentProcess = Data.slice(ParentProcPos+15, LineEnd).trim();
785 int OpenBracket = -1, CloseBracket = -1;
786 for (size_t i = 0, e = ParentProcess.size(); i < e; ++i) {
787 if (ParentProcess[i] == '[')
788 OpenBracket = i;
789 if (ParentProcess[i] == ']')
790 CloseBracket = i;
791 }
792 // Extract the parent process PID from the .crash file and check whether
793 // it matches this driver invocation pid.
794 int CrashPID;
795 if (OpenBracket < 0 || CloseBracket < 0 ||
796 ParentProcess.slice(OpenBracket + 1, CloseBracket)
797 .getAsInteger(10, CrashPID) || CrashPID != PID) {
798 continue;
799 }
800
801 // Found a .crash file matching the driver pid. To avoid getting an older
802 // and misleading crash file, continue looking for the most recent.
803 // FIXME: the driver can dispatch multiple cc1 invocations, leading to
804 // multiple crashes poiting to the same parent process. Since the driver
805 // does not collect pid information for the dispatched invocation there's
806 // currently no way to distinguish among them.
807 const auto FileAccessTime = FileStatus.getLastModificationTime();
808 if (FileAccessTime > LastAccessTime) {
809 CrashFilePath.assign(File->path());
810 LastAccessTime = FileAccessTime;
811 }
812 }
813
814 // If found, copy it over to the location of other reproducer files.
815 if (!CrashFilePath.empty()) {
816 EC = fs::copy_file(CrashFilePath, ReproCrashFilename);
817 if (EC)
818 return false;
819 return true;
820 }
821
822 return false;
823}
824
Eric Christopherf901e852011-08-17 22:59:59 +0000825// When clang crashes, produce diagnostic information including the fully
826// preprocessed source file(s). Request that the developer attach the
Chad Rosierbe10f982011-08-02 17:58:04 +0000827// diagnostic information to a bug report.
828void Driver::generateCompilationDiagnostics(Compilation &C,
Justin Bognere1a33d12014-10-20 21:02:05 +0000829 const Command &FailingCommand) {
Chad Rosier877c0a22012-02-22 00:30:39 +0000830 if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
Chad Rosier62135492012-07-09 17:31:28 +0000831 return;
Chad Rosierbee5a1d2012-03-07 00:30:40 +0000832
Chad Rosierdbf46a12013-02-01 18:30:26 +0000833 // Don't try to generate diagnostics for link or dsymutil jobs.
Justin Bognere1a33d12014-10-20 21:02:05 +0000834 if (FailingCommand.getCreator().isLinkJob() ||
835 FailingCommand.getCreator().isDsymutilJob())
Chad Rosier877c0a22012-02-22 00:30:39 +0000836 return;
837
Chad Rosier8179f112012-06-19 17:51:34 +0000838 // Print the version of the compiler.
839 PrintVersion(C, llvm::errs());
840
Chad Rosierbe10f982011-08-02 17:58:04 +0000841 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000842 << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the "
843 "crash backtrace, preprocessed source, and associated run script.";
Chad Rosierbe10f982011-08-02 17:58:04 +0000844
845 // Suppress driver output and emit preprocessor output to temp file.
Hans Wennborg70850d82013-07-18 20:29:38 +0000846 Mode = CPPMode;
Chad Rosierbe10f982011-08-02 17:58:04 +0000847 CCGenDiagnostics = true;
848
Chad Rosiercdb008d2011-11-02 21:29:05 +0000849 // Save the original job command(s).
Justin Bogner25645152014-10-21 17:24:44 +0000850 Command Cmd = FailingCommand;
Chad Rosiercdb008d2011-11-02 21:29:05 +0000851
Richard Smith5bb4cdf2012-12-20 02:22:15 +0000852 // Keep track of whether we produce any errors while trying to produce
853 // preprocessed sources.
854 DiagnosticErrorTrap Trap(Diags);
855
856 // Suppress tool output.
Chad Rosierbe10f982011-08-02 17:58:04 +0000857 C.initCompilationForDiagnostics();
Chad Rosierecdede82011-08-12 22:08:57 +0000858
859 // Construct the list of inputs.
860 InputList Inputs;
861 BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
Chad Rosierbe10f982011-08-02 17:58:04 +0000862
Chad Rosier4f81fc22011-08-12 23:30:05 +0000863 for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
Chad Rosierd57133d2011-08-18 00:22:25 +0000864 bool IgnoreInput = false;
865
866 // Ignore input from stdin or any inputs that cannot be preprocessed.
Paul Robinsonf44157d2014-04-28 22:24:44 +0000867 // Check type first as not all linker inputs have a value.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000868 if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
Paul Robinsonf44157d2014-04-28 22:24:44 +0000869 IgnoreInput = true;
870 } else if (!strcmp(it->second->getValue(), "-")) {
Chad Rosierd57133d2011-08-18 00:22:25 +0000871 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000872 << "Error generating preprocessed source(s) - "
873 "ignoring input from stdin.";
Chad Rosierd57133d2011-08-18 00:22:25 +0000874 IgnoreInput = true;
Chad Rosierd57133d2011-08-18 00:22:25 +0000875 }
876
877 if (IgnoreInput) {
Chad Rosier4f81fc22011-08-12 23:30:05 +0000878 it = Inputs.erase(it);
879 ie = Inputs.end();
Chad Rosier6fdf38b2011-08-17 23:08:45 +0000880 } else {
Chad Rosier4f81fc22011-08-12 23:30:05 +0000881 ++it;
Chad Rosier6fdf38b2011-08-17 23:08:45 +0000882 }
Chad Rosier4f81fc22011-08-12 23:30:05 +0000883 }
Chad Rosierd57133d2011-08-18 00:22:25 +0000884
Chad Rosierc5103c32013-01-29 23:57:10 +0000885 if (Inputs.empty()) {
886 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000887 << "Error generating preprocessed source(s) - "
888 "no preprocessable inputs.";
Chad Rosierc5103c32013-01-29 23:57:10 +0000889 return;
890 }
891
Chad Rosiere75ef402011-09-06 23:52:36 +0000892 // Don't attempt to generate preprocessed files if multiple -arch options are
Chad Rosier636d2832012-02-13 18:16:28 +0000893 // used, unless they're all duplicates.
894 llvm::StringSet<> ArchNames;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +0000895 for (const Arg *A : C.getArgs()) {
Chad Rosiere75ef402011-09-06 23:52:36 +0000896 if (A->getOption().matches(options::OPT_arch)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000897 StringRef ArchName = A->getValue();
Chad Rosier636d2832012-02-13 18:16:28 +0000898 ArchNames.insert(ArchName);
Chad Rosiere75ef402011-09-06 23:52:36 +0000899 }
900 }
Chad Rosier636d2832012-02-13 18:16:28 +0000901 if (ArchNames.size() > 1) {
902 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000903 << "Error generating preprocessed source(s) - cannot generate "
904 "preprocessed source with multiple -arch options.";
Chad Rosier636d2832012-02-13 18:16:28 +0000905 return;
906 }
Chad Rosiere75ef402011-09-06 23:52:36 +0000907
Chandler Carruth7f1417f2012-01-24 10:43:44 +0000908 // Construct the list of abstract actions to perform for this compilation. On
909 // Darwin OSes this uses the driver-driver and builds universal actions.
Chandler Carruthcb916192012-01-25 08:49:21 +0000910 const ToolChain &TC = C.getDefaultToolChain();
Tim Northover157d9112014-01-16 08:48:16 +0000911 if (TC.getTriple().isOSBinFormatMachO())
Artem Belevich5e2a3ec2015-11-17 22:28:40 +0000912 BuildUniversalActions(C, TC, Inputs);
Chad Rosierbe10f982011-08-02 17:58:04 +0000913 else
Justin Lebar0f3474c2016-02-11 02:00:50 +0000914 BuildActions(C, C.getArgs(), Inputs, C.getActions());
Chad Rosierbe10f982011-08-02 17:58:04 +0000915
916 BuildJobs(C);
917
918 // If there were errors building the compilation, quit now.
Richard Smith5bb4cdf2012-12-20 02:22:15 +0000919 if (Trap.hasErrorOccurred()) {
Chad Rosierbe10f982011-08-02 17:58:04 +0000920 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000921 << "Error generating preprocessed source(s).";
Chad Rosierbe10f982011-08-02 17:58:04 +0000922 return;
923 }
924
925 // Generate preprocessed output.
Chad Rosierdd60e092013-01-29 20:15:05 +0000926 SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
Justin Bogner0cd92482015-07-02 22:52:08 +0000927 C.ExecuteJobs(C.getJobs(), FailingCommands);
Chad Rosierbe10f982011-08-02 17:58:04 +0000928
Justin Bognerbc89b182014-10-20 21:20:27 +0000929 // If any of the preprocessing commands failed, clean up and exit.
930 if (!FailingCommands.empty()) {
Reid Kleckner68eb60b2015-02-02 22:41:48 +0000931 if (!isSaveTempsEnabled())
Chad Rosierbe10f982011-08-02 17:58:04 +0000932 C.CleanupFileList(C.getTempFiles(), true);
933
934 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000935 << "Error generating preprocessed source(s).";
Justin Bognerbc89b182014-10-20 21:20:27 +0000936 return;
Chad Rosierbe10f982011-08-02 17:58:04 +0000937 }
Justin Bognerbc89b182014-10-20 21:20:27 +0000938
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000939 const ArgStringList &TempFiles = C.getTempFiles();
940 if (TempFiles.empty()) {
941 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000942 << "Error generating preprocessed source(s).";
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000943 return;
944 }
945
Justin Bognerbc89b182014-10-20 21:20:27 +0000946 Diag(clang::diag::note_drv_command_failed_diag_msg)
947 << "\n********************\n\n"
948 "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
949 "Preprocessed source(s) and associated run script(s) are located at:";
Justin Bognerbc89b182014-10-20 21:20:27 +0000950
Justin Bogner659ecc32014-10-20 22:47:23 +0000951 SmallString<128> VFS;
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +0000952 SmallString<128> ReproCrashFilename;
Justin Bogner659ecc32014-10-20 22:47:23 +0000953 for (const char *TempFile : TempFiles) {
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000954 Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +0000955 if (ReproCrashFilename.empty()) {
956 ReproCrashFilename = TempFile;
957 llvm::sys::path::replace_extension(ReproCrashFilename, ".crash");
958 }
Justin Bogner659ecc32014-10-20 22:47:23 +0000959 if (StringRef(TempFile).endswith(".cache")) {
960 // In some cases (modules) we'll dump extra data to help with reproducing
961 // the crash into a directory next to the output.
962 VFS = llvm::sys::path::filename(TempFile);
963 llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
964 }
965 }
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000966
967 // Assume associated files are based off of the first temporary file.
Justin Bogner25645152014-10-21 17:24:44 +0000968 CrashReportInfo CrashInfo(TempFiles[0], VFS);
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000969
Justin Bogner25645152014-10-21 17:24:44 +0000970 std::string Script = CrashInfo.Filename.rsplit('.').first.str() + ".sh";
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000971 std::error_code EC;
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000972 llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::F_Excl);
973 if (EC) {
974 Diag(clang::diag::note_drv_command_failed_diag_msg)
975 << "Error generating run script: " + Script + " " + EC.message();
976 } else {
Justin Bogner42220ed2015-03-12 00:14:35 +0000977 ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
Justin Bognered9cbe02015-07-09 06:58:31 +0000978 << "# Driver args: ";
979 printArgList(ScriptOS, C.getInputArgs());
980 ScriptOS << "# Original command: ";
Justin Bogner42220ed2015-03-12 00:14:35 +0000981 Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
Justin Bogner33bdbc62014-10-21 18:03:08 +0000982 Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000983 Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
Justin Bognerbc89b182014-10-20 21:20:27 +0000984 }
Saleem Abdulrasool3661a822015-01-12 02:33:09 +0000985
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +0000986 // On darwin, provide information about the .crash diagnostic report.
987 if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) {
988 SmallString<128> CrashDiagDir;
989 if (getCrashDiagnosticFile(ReproCrashFilename, CrashDiagDir)) {
990 Diag(clang::diag::note_drv_command_failed_diag_msg)
991 << ReproCrashFilename.str();
992 } else { // Suggest a directory for the user to look for .crash files.
993 llvm::sys::path::append(CrashDiagDir, Name);
994 CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash";
995 Diag(clang::diag::note_drv_command_failed_diag_msg)
996 << "Crash backtrace is located in";
997 Diag(clang::diag::note_drv_command_failed_diag_msg)
998 << CrashDiagDir.str();
999 Diag(clang::diag::note_drv_command_failed_diag_msg)
1000 << "(choose the .crash file that corresponds to your crash)";
1001 }
1002 }
1003
Saleem Abdulrasool3661a822015-01-12 02:33:09 +00001004 for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file,
1005 options::OPT_frewrite_map_file_EQ))
1006 Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
1007
Justin Bognerbc89b182014-10-20 21:20:27 +00001008 Diag(clang::diag::note_drv_command_failed_diag_msg)
1009 << "\n\n********************";
Chad Rosierbe10f982011-08-02 17:58:04 +00001010}
1011
Justin Bogner0cd92482015-07-02 22:52:08 +00001012void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
Oleg Ranevskyycd516372016-01-05 19:54:39 +00001013 // Since commandLineFitsWithinSystemLimits() may underestimate system's capacity
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001014 // if the tool does not support response files, there is a chance/ that things
1015 // will just work without a response file, so we silently just skip it.
Justin Bogner0cd92482015-07-02 22:52:08 +00001016 if (Cmd.getCreator().getResponseFilesSupport() == Tool::RF_None ||
Oleg Ranevskyycd516372016-01-05 19:54:39 +00001017 llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(), Cmd.getArguments()))
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001018 return;
1019
1020 std::string TmpName = GetTemporaryPath("response", "txt");
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00001021 Cmd.setResponseFile(C.addTempFile(C.getArgs().MakeArgString(TmpName)));
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001022}
1023
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001024int Driver::ExecuteCompilation(
1025 Compilation &C,
1026 SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001027 // Just print if -### was present.
1028 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
Hans Wennborgb212b342013-09-12 18:23:34 +00001029 C.getJobs().Print(llvm::errs(), "\n", true);
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001030 return 0;
1031 }
1032
1033 // If there were errors building the compilation, quit now.
Chad Rosierbe10f982011-08-02 17:58:04 +00001034 if (Diags.hasErrorOccurred())
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001035 return 1;
1036
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001037 // Set up response file names for each command, if necessary
Justin Bogner0cd92482015-07-02 22:52:08 +00001038 for (auto &Job : C.getJobs())
1039 setUpResponseFiles(C, Job);
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001040
Justin Bogner0cd92482015-07-02 22:52:08 +00001041 C.ExecuteJobs(C.getJobs(), FailingCommands);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001042
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001043 // Remove temp files.
1044 C.CleanupFileList(C.getTempFiles());
1045
Daniel Dunbar07494792010-05-22 00:37:20 +00001046 // If the command succeeded, we are done.
Chad Rosierdd60e092013-01-29 20:15:05 +00001047 if (FailingCommands.empty())
1048 return 0;
Daniel Dunbar07494792010-05-22 00:37:20 +00001049
Chad Rosierdd60e092013-01-29 20:15:05 +00001050 // Otherwise, remove result files and print extra information about abnormal
1051 // failures.
Douglas Katzman6bbffc42015-06-25 18:51:37 +00001052 for (const auto &CmdPair : FailingCommands) {
1053 int Res = CmdPair.first;
1054 const Command *FailingCommand = CmdPair.second;
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001055
Chad Rosierdd60e092013-01-29 20:15:05 +00001056 // Remove result files if we're not saving temps.
Reid Kleckner68eb60b2015-02-02 22:41:48 +00001057 if (!isSaveTempsEnabled()) {
Chad Rosierdd60e092013-01-29 20:15:05 +00001058 const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
1059 C.CleanupFileMap(C.getResultFiles(), JA, true);
1060
1061 // Failure result files are valid unless we crashed.
1062 if (Res < 0)
1063 C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
1064 }
1065
1066 // Print extra information about abnormal failures, if possible.
1067 //
1068 // This is ad-hoc, but we don't want to be excessively noisy. If the result
Justin Bogner5aaf2e72014-06-26 20:59:36 +00001069 // status was 1, assume the command failed normally. In particular, if it
Chad Rosierdd60e092013-01-29 20:15:05 +00001070 // was the compiler then assume it gave a reasonable error code. Failures
1071 // in other tools are less common, and they generally have worse
1072 // diagnostics, so always print the diagnostic there.
1073 const Tool &FailingTool = FailingCommand->getCreator();
1074
1075 if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
1076 // FIXME: See FIXME above regarding result code interpretation.
1077 if (Res < 0)
1078 Diag(clang::diag::err_drv_command_signalled)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001079 << FailingTool.getShortName();
Chad Rosierdd60e092013-01-29 20:15:05 +00001080 else
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001081 Diag(clang::diag::err_drv_command_failed) << FailingTool.getShortName()
1082 << Res;
Chad Rosierdd60e092013-01-29 20:15:05 +00001083 }
Peter Collingbourne119cfaa2011-11-21 00:01:05 +00001084 }
Chad Rosierdd60e092013-01-29 20:15:05 +00001085 return 0;
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001086}
1087
Daniel Dunbara7b5e212009-04-15 16:34:29 +00001088void Driver::PrintHelp(bool ShowHidden) const {
Hans Wennborg6ddc6902013-07-27 00:23:45 +00001089 unsigned IncludedFlagsBitmask;
1090 unsigned ExcludedFlagsBitmask;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001091 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001092 getIncludeExcludeOptionFlagMasks();
Hans Wennborg6ddc6902013-07-27 00:23:45 +00001093
1094 ExcludedFlagsBitmask |= options::NoDriverOption;
1095 if (!ShowHidden)
1096 ExcludedFlagsBitmask |= HelpHidden;
1097
1098 getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
1099 IncludedFlagsBitmask, ExcludedFlagsBitmask);
Daniel Dunbar7c925282009-03-31 21:38:17 +00001100}
1101
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001102void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001103 // FIXME: The following handlers should use a callback mechanism, we don't
1104 // know what the client would like to do.
Ted Kremenek4c0df3d2010-01-23 02:11:34 +00001105 OS << getClangFullVersion() << '\n';
Daniel Dunbarb10248802009-03-26 16:09:13 +00001106 const ToolChain &TC = C.getDefaultToolChain();
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001107 OS << "Target: " << TC.getTripleString() << '\n';
Daniel Dunbar10978e42009-06-16 23:32:58 +00001108
1109 // Print the threading model.
Jonathan Roelofsb140a102014-10-03 21:57:44 +00001110 if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
1111 // Don't print if the ToolChain would have barfed on it already
1112 if (TC.isThreadModelSupported(A->getValue()))
1113 OS << "Thread model: " << A->getValue();
1114 } else
1115 OS << "Thread model: " << TC.getThreadModel();
1116 OS << '\n';
Chandler Carruth9ade6a92015-08-05 17:07:33 +00001117
1118 // Print out the install directory.
1119 OS << "InstalledDir: " << InstalledDir << '\n';
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001120}
1121
Chris Lattner86ed5b02010-05-05 05:53:24 +00001122/// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
1123/// option.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001124static void PrintDiagnosticCategories(raw_ostream &OS) {
Argyrios Kyrtzidis0e37afa2011-05-25 05:05:01 +00001125 // Skip the empty category.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001126 for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
1127 ++i)
Argyrios Kyrtzidis0e37afa2011-05-25 05:05:01 +00001128 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
Chris Lattner86ed5b02010-05-05 05:53:24 +00001129}
1130
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001131bool Driver::HandleImmediateArgs(const Compilation &C) {
Daniel Dunbar18974bd2010-06-11 22:00:19 +00001132 // The order these options are handled in gcc is all over the place, but we
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001133 // don't expect inconsistencies w.r.t. that to matter in practice.
Daniel Dunbar7c925282009-03-31 21:38:17 +00001134
Daniel Dunbar1b09e042010-09-17 02:47:28 +00001135 if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
1136 llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
1137 return false;
1138 }
1139
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001140 if (C.getArgs().hasArg(options::OPT_dumpversion)) {
Daniel Dunbare26e5002011-01-12 00:43:47 +00001141 // Since -dumpversion is only implemented for pedantic GCC compatibility, we
1142 // return an answer which matches our definition of __VERSION__.
1143 //
1144 // If we want to return a more correct answer some day, then we should
1145 // introduce a non-pedantically GCC compatible mode to Clang in which we
1146 // provide sensible definitions for -dumpversion, __VERSION__, etc.
1147 llvm::outs() << "4.2.1\n";
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001148 return false;
1149 }
Daniel Dunbarfb3d7472010-06-14 21:23:12 +00001150
Chris Lattner86ed5b02010-05-05 05:53:24 +00001151 if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
1152 PrintDiagnosticCategories(llvm::outs());
1153 return false;
1154 }
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001155
James Molloya3c85b82012-05-01 14:57:16 +00001156 if (C.getArgs().hasArg(options::OPT_help) ||
Daniel Dunbara7b5e212009-04-15 16:34:29 +00001157 C.getArgs().hasArg(options::OPT__help_hidden)) {
1158 PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
Daniel Dunbar7c925282009-03-31 21:38:17 +00001159 return false;
1160 }
1161
Daniel Dunbarb0006ae2009-04-02 15:05:41 +00001162 if (C.getArgs().hasArg(options::OPT__version)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001163 // Follow gcc behavior and use stdout for --version and stderr for -v.
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001164 PrintVersion(C, llvm::outs());
Dimitry Andric0527c322017-06-07 12:05:41 +00001165
1166 // Print registered targets.
1167 llvm::outs() << '\n';
1168 llvm::TargetRegistry::printRegisteredTargetsForVersion(llvm::outs());
Daniel Dunbarb0006ae2009-04-02 15:05:41 +00001169 return false;
1170 }
1171
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001172 if (C.getArgs().hasArg(options::OPT_v) ||
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001173 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001174 PrintVersion(C, llvm::errs());
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001175 SuppressMissingInputWarning = true;
1176 }
1177
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001178 const ToolChain &TC = C.getDefaultToolChain();
Chandler Carruth0ae39aa2013-07-30 17:57:09 +00001179
1180 if (C.getArgs().hasArg(options::OPT_v))
1181 TC.printVerboseInfo(llvm::errs());
1182
Meador Inge51208a32017-04-04 21:46:50 +00001183 if (C.getArgs().hasArg(options::OPT_print_resource_dir)) {
Meador Ingea9113952017-04-05 22:27:20 +00001184 llvm::outs() << ResourceDir << '\n';
Meador Inge51208a32017-04-04 21:46:50 +00001185 return false;
1186 }
1187
Daniel Dunbard972e222009-03-20 04:37:21 +00001188 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
1189 llvm::outs() << "programs: =";
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001190 bool separator = false;
1191 for (const std::string &Path : TC.getProgramPaths()) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001192 if (separator)
1193 llvm::outs() << ':';
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001194 llvm::outs() << Path;
1195 separator = true;
Daniel Dunbard972e222009-03-20 04:37:21 +00001196 }
1197 llvm::outs() << "\n";
Peter Collingbournefa9771f2011-09-06 02:08:31 +00001198 llvm::outs() << "libraries: =" << ResourceDir;
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001199
Sebastian Pop980920a2012-04-16 04:16:43 +00001200 StringRef sysroot = C.getSysRoot();
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001201
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001202 for (const std::string &Path : TC.getFilePaths()) {
1203 // Always print a separator. ResourceDir was the first item shown.
Peter Collingbournefa9771f2011-09-06 02:08:31 +00001204 llvm::outs() << ':';
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001205 // Interpretation of leading '=' is needed only for NetBSD.
1206 if (Path[0] == '=')
Douglas Katzman26eabf62015-06-24 15:10:30 +00001207 llvm::outs() << sysroot << Path.substr(1);
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001208 else
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001209 llvm::outs() << Path;
Daniel Dunbard972e222009-03-20 04:37:21 +00001210 }
1211 llvm::outs() << "\n";
Daniel Dunbar7c925282009-03-31 21:38:17 +00001212 return false;
Daniel Dunbard972e222009-03-20 04:37:21 +00001213 }
1214
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001215 // FIXME: The following handlers should use a callback mechanism, we don't
1216 // know what the client would like to do.
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001217 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001218 llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001219 return false;
1220 }
1221
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001222 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001223 llvm::outs() << GetProgramPath(A->getValue(), TC) << "\n";
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001224 return false;
1225 }
1226
Yuka Takahashic8068db2017-05-23 18:39:08 +00001227 if (Arg *A = C.getArgs().getLastArg(options::OPT_autocomplete)) {
1228 // Print out all options that start with a given argument. This is used for
1229 // shell autocompletion.
1230 llvm::outs() << llvm::join(Opts->findByPrefix(A->getValue()), " ") << '\n';
1231 return false;
1232 }
1233
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001234 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
Michal Gorny7cfe4802016-10-10 12:23:40 +00001235 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(C.getArgs());
1236 switch (RLT) {
1237 case ToolChain::RLT_CompilerRT:
1238 llvm::outs() << TC.getCompilerRT(C.getArgs(), "builtins") << "\n";
1239 break;
1240 case ToolChain::RLT_Libgcc:
1241 llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
1242 break;
1243 }
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001244 return false;
1245 }
1246
Daniel Dunbar1b3ec3a2009-06-16 23:25:22 +00001247 if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
Douglas Katzmana34b7bf2015-06-30 19:32:57 +00001248 for (const Multilib &Multilib : TC.getMultilibs())
1249 llvm::outs() << Multilib << "\n";
Daniel Dunbar1b3ec3a2009-06-16 23:25:22 +00001250 return false;
1251 }
1252
Jonathan Roelofs2cea1be2014-02-12 03:21:20 +00001253 if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
Douglas Katzmana34b7bf2015-06-30 19:32:57 +00001254 for (const Multilib &Multilib : TC.getMultilibs()) {
Douglas Katzman6bbffc42015-06-25 18:51:37 +00001255 if (Multilib.gccSuffix().empty())
Jonathan Roelofs2cea1be2014-02-12 03:21:20 +00001256 llvm::outs() << ".\n";
1257 else {
Douglas Katzman6bbffc42015-06-25 18:51:37 +00001258 StringRef Suffix(Multilib.gccSuffix());
Jonathan Roelofs2cea1be2014-02-12 03:21:20 +00001259 assert(Suffix.front() == '/');
1260 llvm::outs() << Suffix.substr(1) << "\n";
1261 }
Jonathan Roelofs3fa96d82014-02-12 01:36:51 +00001262 }
Jonathan Roelofs0e7ec602014-02-12 01:29:25 +00001263 return false;
1264 }
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001265 return true;
1266}
1267
Douglas Katzmanfd528672015-06-11 15:05:22 +00001268// Display an action graph human-readably. Action A is the "sink" node
1269// and latest-occuring action. Traversal is in pre-order, visiting the
1270// inputs to each action before printing the action itself.
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001271static unsigned PrintActions1(const Compilation &C, Action *A,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001272 std::map<Action *, unsigned> &Ids) {
Douglas Katzmanfd528672015-06-11 15:05:22 +00001273 if (Ids.count(A)) // A was already visited.
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001274 return Ids[A];
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001275
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001276 std::string str;
1277 llvm::raw_string_ostream os(str);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001278
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001279 os << Action::getClassName(A->getKind()) << ", ";
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001280 if (InputAction *IA = dyn_cast<InputAction>(A)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001281 os << "\"" << IA->getInputArg().getValue() << "\"";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001282 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001283 os << '"' << BIA->getArchName() << '"' << ", {"
Nico Weber5a459f82016-02-23 19:30:43 +00001284 << PrintActions1(C, *BIA->input_begin(), Ids) << "}";
Samuel Antaod06239d2016-07-15 23:13:27 +00001285 } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
1286 bool IsFirst = true;
1287 OA->doOnEachDependence(
1288 [&](Action *A, const ToolChain *TC, const char *BoundArch) {
1289 // E.g. for two CUDA device dependences whose bound arch is sm_20 and
1290 // sm_35 this will generate:
1291 // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
1292 // (nvptx64-nvidia-cuda:sm_35) {#ID}
1293 if (!IsFirst)
1294 os << ", ";
1295 os << '"';
1296 if (TC)
1297 os << A->getOffloadingKindPrefix();
1298 else
1299 os << "host";
1300 os << " (";
1301 os << TC->getTriple().normalize();
1302
1303 if (BoundArch)
1304 os << ":" << BoundArch;
1305 os << ")";
1306 os << '"';
1307 os << " {" << PrintActions1(C, A, Ids) << "}";
1308 IsFirst = false;
1309 });
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001310 } else {
Samuel Antaod06239d2016-07-15 23:13:27 +00001311 const ActionList *AL = &A->getInputs();
Artem Belevich0ff05cd2015-07-13 23:27:56 +00001312
Artem Belevich23256752015-09-22 17:23:09 +00001313 if (AL->size()) {
1314 const char *Prefix = "{";
1315 for (Action *PreRequisite : *AL) {
1316 os << Prefix << PrintActions1(C, PreRequisite, Ids);
1317 Prefix = ", ";
1318 }
1319 os << "}";
1320 } else
1321 os << "{}";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001322 }
1323
Samuel Antaod06239d2016-07-15 23:13:27 +00001324 // Append offload info for all options other than the offloading action
1325 // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
1326 std::string offload_str;
1327 llvm::raw_string_ostream offload_os(offload_str);
1328 if (!isa<OffloadAction>(A)) {
1329 auto S = A->getOffloadingKindPrefix();
1330 if (!S.empty()) {
1331 offload_os << ", (" << S;
1332 if (A->getOffloadingArch())
1333 offload_os << ", " << A->getOffloadingArch();
1334 offload_os << ")";
1335 }
1336 }
1337
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001338 unsigned Id = Ids.size();
1339 Ids[A] = Id;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001340 llvm::errs() << Id << ": " << os.str() << ", "
Samuel Antaod06239d2016-07-15 23:13:27 +00001341 << types::getTypeName(A->getType()) << offload_os.str() << "\n";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001342
1343 return Id;
1344}
1345
Douglas Katzmanfd528672015-06-11 15:05:22 +00001346// Print the action graphs in a compilation C.
1347// For example "clang -c file1.c file2.c" is composed of two subgraphs.
Daniel Dunbareb843be2009-03-18 03:13:20 +00001348void Driver::PrintActions(const Compilation &C) const {
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001349 std::map<Action *, unsigned> Ids;
1350 for (Action *A : C.getActions())
1351 PrintActions1(C, A, Ids);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001352}
1353
Joerg Sonnenberger5fe4a7d2011-05-06 14:05:11 +00001354/// \brief Check whether the given input tree contains any compilation or
1355/// assembly actions.
1356static bool ContainsCompileOrAssembleAction(const Action *A) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001357 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
Bob Wilson23a55f12014-12-21 07:00:00 +00001358 isa<AssembleJobAction>(A))
Daniel Dunbar00d3d8e2010-06-29 16:38:33 +00001359 return true;
1360
Nico Weber5a459f82016-02-23 19:30:43 +00001361 for (const Action *Input : A->inputs())
Nico Weberfb80f962015-09-19 21:36:51 +00001362 if (ContainsCompileOrAssembleAction(Input))
Daniel Dunbar00d3d8e2010-06-29 16:38:33 +00001363 return true;
1364
1365 return false;
1366}
1367
Artem Belevich5e2a3ec2015-11-17 22:28:40 +00001368void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
1369 const InputList &BAInputs) const {
1370 DerivedArgList &Args = C.getArgs();
1371 ActionList &Actions = C.getActions();
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001372 llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
1373 // Collect the list of architectures. Duplicates are allowed, but should only
1374 // be handled once (in the order seen).
Daniel Dunbare5dc4822009-03-13 20:33:35 +00001375 llvm::StringSet<> ArchNames;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001376 SmallVector<const char *, 4> Archs;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00001377 for (Arg *A : Args) {
Daniel Dunbar0bfb21e2009-11-19 03:26:40 +00001378 if (A->getOption().matches(options::OPT_arch)) {
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001379 // Validate the option here; we don't save the type here because its
1380 // particular spelling may participate in other driver choices.
1381 llvm::Triple::ArchType Arch =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001382 tools::darwin::getArchTypeForMachOArchName(A->getValue());
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001383 if (Arch == llvm::Triple::UnknownArch) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001384 Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001385 continue;
1386 }
1387
Daniel Dunbar2da02722009-03-19 07:55:12 +00001388 A->claim();
David Blaikie61b86d42014-11-19 02:56:13 +00001389 if (ArchNames.insert(A->getValue()).second)
Richard Smithbd55daf2012-11-01 04:30:05 +00001390 Archs.push_back(A->getValue());
Daniel Dunbarf479c122009-03-12 18:40:18 +00001391 }
1392 }
1393
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001394 // When there is no explicit arch for this platform, make sure we still bind
1395 // the architecture (to the default) so that -Xarch_ is handled correctly.
Daniel Dunbareb843be2009-03-18 03:13:20 +00001396 if (!Archs.size())
Daniel Dunbarc3bd9f52012-11-08 03:38:26 +00001397 Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
Daniel Dunbarf479c122009-03-12 18:40:18 +00001398
Daniel Dunbarf479c122009-03-12 18:40:18 +00001399 ActionList SingleActions;
Justin Lebar0f3474c2016-02-11 02:00:50 +00001400 BuildActions(C, Args, BAInputs, SingleActions);
Daniel Dunbarf479c122009-03-12 18:40:18 +00001401
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001402 // Add in arch bindings for every top level action, as well as lipo and
1403 // dsymutil steps if needed.
Nico Weberfb80f962015-09-19 21:36:51 +00001404 for (Action* Act : SingleActions) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001405 // Make sure we can lipo this kind of output. If not (and it is an actual
1406 // output) then we disallow, since we can't create an output file with the
1407 // right name without overwriting it. We could remove this oddity by just
1408 // changing the output names to include the arch, which would also fix
Daniel Dunbarf479c122009-03-12 18:40:18 +00001409 // -save-temps. Compatibility wins for now.
1410
Daniel Dunbare2ca3bd2009-03-13 17:46:02 +00001411 if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
Daniel Dunbarf479c122009-03-12 18:40:18 +00001412 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001413 << types::getTypeName(Act->getType());
Daniel Dunbarf479c122009-03-12 18:40:18 +00001414
1415 ActionList Inputs;
Justin Lebar41094612016-01-11 23:07:27 +00001416 for (unsigned i = 0, e = Archs.size(); i != e; ++i)
1417 Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
Daniel Dunbarf479c122009-03-12 18:40:18 +00001418
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001419 // Lipo if necessary, we do it this way because we need to set the arch flag
1420 // so that -Xarch_ gets overwritten.
Daniel Dunbarf479c122009-03-12 18:40:18 +00001421 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
1422 Actions.append(Inputs.begin(), Inputs.end());
1423 else
Justin Lebar41094612016-01-11 23:07:27 +00001424 Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001425
Eric Christopher65c05fa2012-02-06 19:43:51 +00001426 // Handle debug info queries.
1427 Arg *A = Args.getLastArg(options::OPT_g_Group);
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001428 if (A && !A->getOption().matches(options::OPT_g0) &&
1429 !A->getOption().matches(options::OPT_gstabs) &&
1430 ContainsCompileOrAssembleAction(Actions.back())) {
Chad Rosier62135492012-07-09 17:31:28 +00001431
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001432 // Add a 'dsymutil' step if necessary, when debug info is enabled and we
1433 // have a compile input. We need to run 'dsymutil' ourselves in such cases
Eric Christopher776c26f2013-01-28 17:39:03 +00001434 // because the debug info will refer to a temporary object file which
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001435 // will be removed at the end of the compilation process.
1436 if (Act->getType() == types::TY_Image) {
1437 ActionList Inputs;
1438 Inputs.push_back(Actions.back());
1439 Actions.pop_back();
Justin Lebar41094612016-01-11 23:07:27 +00001440 Actions.push_back(
1441 C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001442 }
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001443
Ben Langmuir9b9a8d32014-02-06 18:53:25 +00001444 // Verify the debug info output.
Alp Tokere9d2bfc2014-01-17 02:06:23 +00001445 if (Args.hasArg(options::OPT_verify_debug_info)) {
Justin Lebar41094612016-01-11 23:07:27 +00001446 Action* LastAction = Actions.back();
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001447 Actions.pop_back();
Justin Lebar41094612016-01-11 23:07:27 +00001448 Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
1449 LastAction, types::TY_Nothing));
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001450 }
1451 }
Daniel Dunbarf479c122009-03-12 18:40:18 +00001452 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001453}
1454
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001455/// \brief Check that the file referenced by Value exists. If it doesn't,
1456/// issue a diagnostic and return false.
Alp Toker8c8a8752013-12-03 06:53:35 +00001457static bool DiagnoseInputExistence(const Driver &D, const DerivedArgList &Args,
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001458 StringRef Value, types::ID Ty) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001459 if (!D.getCheckInputsExist())
1460 return true;
1461
1462 // stdin always exists.
1463 if (Value == "-")
1464 return true;
1465
1466 SmallString<64> Path(Value);
1467 if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
Yaron Keren92e1b622015-03-18 10:17:07 +00001468 if (!llvm::sys::path::is_absolute(Path)) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001469 SmallString<64> Directory(WorkDir->getValue());
1470 llvm::sys::path::append(Directory, Value);
1471 Path.assign(Directory);
1472 }
1473 }
1474
1475 if (llvm::sys::fs::exists(Twine(Path)))
1476 return true;
1477
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001478 if (D.IsCLMode()) {
1479 if (!llvm::sys::path::is_absolute(Twine(Path)) &&
1480 llvm::sys::Process::FindInEnvPath("LIB", Value))
1481 return true;
1482
1483 if (Args.hasArg(options::OPT__SLASH_link) && Ty == types::TY_Object) {
1484 // Arguments to the /link flag might cause the linker to search for object
1485 // and library files in paths we don't know about. Don't error in such
1486 // cases.
1487 return true;
1488 }
1489 }
Hans Wennborg23d26a32014-06-18 17:21:50 +00001490
Yaron Keren92e1b622015-03-18 10:17:07 +00001491 D.Diag(clang::diag::err_drv_no_such_file) << Path;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001492 return false;
1493}
1494
Chad Rosierecdede82011-08-12 22:08:57 +00001495// Construct a the list of inputs and their types.
Hans Wennborg55362852014-05-02 22:55:30 +00001496void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
Chad Rosierecdede82011-08-12 22:08:57 +00001497 InputList &Inputs) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001498 // Track the current user specified (-x) input. We also explicitly track the
1499 // argument used to set the type; we only want to claim the type when we
1500 // actually use it, so we warn about unused -x arguments.
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00001501 types::ID InputType = types::TY_Nothing;
Craig Topper92fc2df2014-05-17 16:56:41 +00001502 Arg *InputTypeArg = nullptr;
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00001503
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001504 // The last /TC or /TP option sets the input type to C or C++ globally.
Ehsan Akhgaric249abb2014-09-12 21:44:24 +00001505 if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
1506 options::OPT__SLASH_TP)) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001507 InputTypeArg = TCTP;
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001508 InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001509 ? types::TY_C
1510 : types::TY_CXX;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001511
Richard Smith0aef3052017-02-18 01:14:43 +00001512 Arg *Previous = nullptr;
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001513 bool ShowNote = false;
Richard Smith0aef3052017-02-18 01:14:43 +00001514 for (Arg *A : Args.filtered(options::OPT__SLASH_TC, options::OPT__SLASH_TP)) {
1515 if (Previous) {
1516 Diag(clang::diag::warn_drv_overriding_flag_option)
1517 << Previous->getSpelling() << A->getSpelling();
1518 ShowNote = true;
1519 }
1520 Previous = A;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001521 }
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001522 if (ShowNote)
1523 Diag(clang::diag::note_drv_t_option_is_global);
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001524
1525 // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
1526 assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
1527 }
1528
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00001529 for (Arg *A : Args) {
Michael J. Spencerad3ccc32012-08-20 21:41:17 +00001530 if (A->getOption().getKind() == Option::InputClass) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001531 const char *Value = A->getValue();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001532 types::ID Ty = types::TY_INVALID;
1533
1534 // Infer the input type if necessary.
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00001535 if (InputType == types::TY_Nothing) {
1536 // If there was an explicit arg for this, claim it.
1537 if (InputTypeArg)
1538 InputTypeArg->claim();
1539
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001540 // stdin must be handled specially.
1541 if (memcmp(Value, "-", 2) == 0) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001542 // If running with -E, treat as a C input (this changes the builtin
1543 // macros, for example). This may be overridden by -ObjC below.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001544 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001545 // Otherwise emit an error but still use a valid type to avoid
1546 // spurious errors (e.g., no inputs).
Hans Wennborg70850d82013-07-18 20:29:38 +00001547 if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
Hans Wennborgcfdd8b52014-01-29 01:04:40 +00001548 Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
1549 : clang::diag::err_drv_unknown_stdin_type);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001550 Ty = types::TY_C;
1551 } else {
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00001552 // Otherwise lookup by extension.
1553 // Fallback is C if invoked as C preprocessor or Object otherwise.
1554 // We use a host hook here because Darwin at least has its own
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001555 // idea of what .s is.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001556 if (const char *Ext = strrchr(Value, '.'))
Daniel Dunbarcc7df6c2010-08-02 05:43:56 +00001557 Ty = TC.LookupTypeForExtension(Ext + 1);
Daniel Dunbarea9f0322009-03-20 23:39:23 +00001558
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00001559 if (Ty == types::TY_INVALID) {
Hans Wennborg70850d82013-07-18 20:29:38 +00001560 if (CCCIsCPP())
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00001561 Ty = types::TY_C;
1562 else
1563 Ty = types::TY_Object;
1564 }
Daniel Dunbar0ac94452010-02-17 20:32:58 +00001565
1566 // If the driver is invoked as C++ compiler (like clang++ or c++) it
1567 // should autodetect some input files as C++ for g++ compatibility.
Hans Wennborg70850d82013-07-18 20:29:38 +00001568 if (CCCIsCXX()) {
Daniel Dunbar0ac94452010-02-17 20:32:58 +00001569 types::ID OldTy = Ty;
1570 Ty = types::lookupCXXTypeForCType(Ty);
1571
1572 if (Ty != OldTy)
1573 Diag(clang::diag::warn_drv_treating_input_as_cxx)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001574 << getTypeName(OldTy) << getTypeName(Ty);
Daniel Dunbar0ac94452010-02-17 20:32:58 +00001575 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001576 }
1577
Daniel Dunbar82b22102009-05-18 21:47:54 +00001578 // -ObjC and -ObjC++ override the default language, but only for "source
1579 // files". We just treat everything that isn't a linker input as a
1580 // source file.
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001581 //
Daniel Dunbar82b22102009-05-18 21:47:54 +00001582 // FIXME: Clean this up if we move the phase sequence into the type.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001583 if (Ty != types::TY_Object) {
1584 if (Args.hasArg(options::OPT_ObjC))
1585 Ty = types::TY_ObjC;
1586 else if (Args.hasArg(options::OPT_ObjCXX))
1587 Ty = types::TY_ObjCXX;
1588 }
1589 } else {
1590 assert(InputTypeArg && "InputType set w/o InputTypeArg");
Ehsan Akhgari7e954ea2014-09-12 18:15:10 +00001591 if (!InputTypeArg->getOption().matches(options::OPT_x)) {
1592 // If emulating cl.exe, make sure that /TC and /TP don't affect input
1593 // object files.
1594 const char *Ext = strrchr(Value, '.');
1595 if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
1596 Ty = types::TY_Object;
1597 }
1598 if (Ty == types::TY_INVALID) {
1599 Ty = InputType;
1600 InputTypeArg->claim();
1601 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001602 }
1603
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001604 if (DiagnoseInputExistence(*this, Args, Value, Ty))
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001605 Inputs.push_back(std::make_pair(Ty, A));
1606
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001607 } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
1608 StringRef Value = A->getValue();
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001609 if (DiagnoseInputExistence(*this, Args, Value, types::TY_C)) {
David Blaikie0aaa7622017-01-13 17:34:15 +00001610 Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001611 Inputs.push_back(std::make_pair(types::TY_C, InputArg));
1612 }
1613 A->claim();
1614 } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
1615 StringRef Value = A->getValue();
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001616 if (DiagnoseInputExistence(*this, Args, Value, types::TY_CXX)) {
David Blaikie0aaa7622017-01-13 17:34:15 +00001617 Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001618 Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
1619 }
1620 A->claim();
Michael J. Spencer66e2b202012-10-19 22:37:06 +00001621 } else if (A->getOption().hasFlag(options::LinkerInput)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001622 // Just treat as object type, we could make a special type for this if
1623 // necessary.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001624 Inputs.push_back(std::make_pair(types::TY_Object, A));
1625
Daniel Dunbar0bfb21e2009-11-19 03:26:40 +00001626 } else if (A->getOption().matches(options::OPT_x)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001627 InputTypeArg = A;
Richard Smithbd55daf2012-11-01 04:30:05 +00001628 InputType = types::lookupTypeForTypeSpecifier(A->getValue());
Chad Rosier706c2352012-04-07 00:01:31 +00001629 A->claim();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001630
1631 // Follow gcc behavior and treat as linker input for invalid -x
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001632 // options. Its not clear why we shouldn't just revert to unknown; but
Michael J. Spencer1a4fe8c2010-12-17 21:22:33 +00001633 // this isn't very important, we might as well be bug compatible.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001634 if (!InputType) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001635 Diag(clang::diag::err_drv_unknown_language) << A->getValue();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001636 InputType = types::TY_Object;
1637 }
Hans Wennborg091f1b62017-01-27 17:09:41 +00001638 } else if (A->getOption().getID() == options::OPT__SLASH_U) {
1639 assert(A->getNumValues() == 1 && "The /U option has one value.");
1640 StringRef Val = A->getValue(0);
1641 if (Val.find_first_of("/\\") != StringRef::npos) {
1642 // Warn about e.g. "/Users/me/myfile.c".
1643 Diag(diag::warn_slash_u_filename) << Val;
1644 Diag(diag::note_use_dashdash);
1645 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001646 }
1647 }
Hans Wennborg70850d82013-07-18 20:29:38 +00001648 if (CCCIsCPP() && Inputs.empty()) {
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00001649 // If called as standalone preprocessor, stdin is processed
1650 // if no other input is present.
David Blaikie0aaa7622017-01-13 17:34:15 +00001651 Arg *A = MakeInputArg(Args, *Opts, "-");
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00001652 Inputs.push_back(std::make_pair(types::TY_C, A));
1653 }
Chad Rosierecdede82011-08-12 22:08:57 +00001654}
1655
Samuel Antao64e965e2016-09-30 15:34:19 +00001656namespace {
1657/// Provides a convenient interface for different programming models to generate
1658/// the required device actions.
1659class OffloadingActionBuilder final {
1660 /// Flag used to trace errors in the builder.
1661 bool IsValid = false;
1662
1663 /// The compilation that is using this builder.
1664 Compilation &C;
1665
Samuel Antao64e965e2016-09-30 15:34:19 +00001666 /// Map between an input argument and the offload kinds used to process it.
1667 std::map<const Arg *, unsigned> InputArgToOffloadKindMap;
1668
1669 /// Builder interface. It doesn't build anything or keep any state.
1670 class DeviceActionBuilder {
1671 public:
1672 typedef llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PhasesTy;
1673
1674 enum ActionBuilderReturnCode {
1675 // The builder acted successfully on the current action.
1676 ABRT_Success,
1677 // The builder didn't have to act on the current action.
1678 ABRT_Inactive,
1679 // The builder was successful and requested the host action to not be
1680 // generated.
1681 ABRT_Ignore_Host,
1682 };
1683
1684 protected:
1685 /// Compilation associated with this builder.
1686 Compilation &C;
1687
1688 /// Tool chains associated with this builder. The same programming
1689 /// model may have associated one or more tool chains.
1690 SmallVector<const ToolChain *, 2> ToolChains;
1691
1692 /// The derived arguments associated with this builder.
1693 DerivedArgList &Args;
1694
1695 /// The inputs associated with this builder.
1696 const Driver::InputList &Inputs;
1697
1698 /// The associated offload kind.
1699 Action::OffloadKind AssociatedOffloadKind = Action::OFK_None;
1700
1701 public:
1702 DeviceActionBuilder(Compilation &C, DerivedArgList &Args,
1703 const Driver::InputList &Inputs,
1704 Action::OffloadKind AssociatedOffloadKind)
1705 : C(C), Args(Args), Inputs(Inputs),
1706 AssociatedOffloadKind(AssociatedOffloadKind) {}
1707 virtual ~DeviceActionBuilder() {}
1708
1709 /// Fill up the array \a DA with all the device dependences that should be
1710 /// added to the provided host action \a HostAction. By default it is
1711 /// inactive.
1712 virtual ActionBuilderReturnCode
Samuel Antao28c4f182016-10-27 17:08:03 +00001713 getDeviceDependences(OffloadAction::DeviceDependences &DA,
1714 phases::ID CurPhase, phases::ID FinalPhase,
1715 PhasesTy &Phases) {
Samuel Antao64e965e2016-09-30 15:34:19 +00001716 return ABRT_Inactive;
1717 }
1718
1719 /// Update the state to include the provided host action \a HostAction as a
1720 /// dependency of the current device action. By default it is inactive.
1721 virtual ActionBuilderReturnCode addDeviceDepences(Action *HostAction) {
1722 return ABRT_Inactive;
1723 }
1724
1725 /// Append top level actions generated by the builder. Return true if errors
1726 /// were found.
1727 virtual void appendTopLevelActions(ActionList &AL) {}
1728
1729 /// Append linker actions generated by the builder. Return true if errors
1730 /// were found.
1731 virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {}
1732
1733 /// Initialize the builder. Return true if any initialization errors are
1734 /// found.
1735 virtual bool initialize() { return false; }
1736
Samuel Antao69d6f312016-10-27 17:50:43 +00001737 /// Return true if the builder can use bundling/unbundling.
1738 virtual bool canUseBundlerUnbundler() const { return false; }
1739
Samuel Antao64e965e2016-09-30 15:34:19 +00001740 /// Return true if this builder is valid. We have a valid builder if we have
1741 /// associated device tool chains.
1742 bool isValid() { return !ToolChains.empty(); }
1743
1744 /// Return the associated offload kind.
1745 Action::OffloadKind getAssociatedOffloadKind() {
1746 return AssociatedOffloadKind;
1747 }
1748 };
1749
1750 /// \brief CUDA action builder. It injects device code in the host backend
1751 /// action.
1752 class CudaActionBuilder final : public DeviceActionBuilder {
1753 /// Flags to signal if the user requested host-only or device-only
1754 /// compilation.
1755 bool CompileHostOnly = false;
1756 bool CompileDeviceOnly = false;
1757
1758 /// List of GPU architectures to use in this compilation.
1759 SmallVector<CudaArch, 4> GpuArchList;
1760
1761 /// The CUDA actions for the current input.
1762 ActionList CudaDeviceActions;
1763
1764 /// The CUDA fat binary if it was generated for the current input.
1765 Action *CudaFatBinary = nullptr;
1766
1767 /// Flag that is set to true if this builder acted on the current input.
1768 bool IsActive = false;
1769
1770 public:
1771 CudaActionBuilder(Compilation &C, DerivedArgList &Args,
1772 const Driver::InputList &Inputs)
1773 : DeviceActionBuilder(C, Args, Inputs, Action::OFK_Cuda) {}
1774
1775 ActionBuilderReturnCode
Samuel Antao28c4f182016-10-27 17:08:03 +00001776 getDeviceDependences(OffloadAction::DeviceDependences &DA,
1777 phases::ID CurPhase, phases::ID FinalPhase,
1778 PhasesTy &Phases) override {
Samuel Antao64e965e2016-09-30 15:34:19 +00001779 if (!IsActive)
1780 return ABRT_Inactive;
1781
1782 // If we don't have more CUDA actions, we don't have any dependences to
1783 // create for the host.
1784 if (CudaDeviceActions.empty())
1785 return ABRT_Success;
1786
1787 assert(CudaDeviceActions.size() == GpuArchList.size() &&
1788 "Expecting one action per GPU architecture.");
1789 assert(!CompileHostOnly &&
1790 "Not expecting CUDA actions in host-only compilation.");
1791
1792 // If we are generating code for the device or we are in a backend phase,
1793 // we attempt to generate the fat binary. We compile each arch to ptx and
1794 // assemble to cubin, then feed the cubin *and* the ptx into a device
1795 // "link" action, which uses fatbinary to combine these cubins into one
1796 // fatbin. The fatbin is then an input to the host action if not in
1797 // device-only mode.
1798 if (CompileDeviceOnly || CurPhase == phases::Backend) {
1799 ActionList DeviceActions;
1800 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
1801 // Produce the device action from the current phase up to the assemble
1802 // phase.
1803 for (auto Ph : Phases) {
1804 // Skip the phases that were already dealt with.
1805 if (Ph < CurPhase)
1806 continue;
1807 // We have to be consistent with the host final phase.
1808 if (Ph > FinalPhase)
1809 break;
1810
1811 CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction(
1812 C, Args, Ph, CudaDeviceActions[I]);
1813
1814 if (Ph == phases::Assemble)
1815 break;
1816 }
1817
1818 // If we didn't reach the assemble phase, we can't generate the fat
1819 // binary. We don't need to generate the fat binary if we are not in
1820 // device-only mode.
1821 if (!isa<AssembleJobAction>(CudaDeviceActions[I]) ||
1822 CompileDeviceOnly)
1823 continue;
1824
1825 Action *AssembleAction = CudaDeviceActions[I];
1826 assert(AssembleAction->getType() == types::TY_Object);
1827 assert(AssembleAction->getInputs().size() == 1);
1828
1829 Action *BackendAction = AssembleAction->getInputs()[0];
1830 assert(BackendAction->getType() == types::TY_PP_Asm);
1831
1832 for (auto &A : {AssembleAction, BackendAction}) {
1833 OffloadAction::DeviceDependences DDep;
1834 DDep.add(*A, *ToolChains.front(), CudaArchToString(GpuArchList[I]),
1835 Action::OFK_Cuda);
1836 DeviceActions.push_back(
1837 C.MakeAction<OffloadAction>(DDep, A->getType()));
1838 }
1839 }
1840
1841 // We generate the fat binary if we have device input actions.
1842 if (!DeviceActions.empty()) {
1843 CudaFatBinary =
1844 C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN);
1845
1846 if (!CompileDeviceOnly) {
1847 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
1848 Action::OFK_Cuda);
1849 // Clear the fat binary, it is already a dependence to an host
1850 // action.
1851 CudaFatBinary = nullptr;
1852 }
1853
1854 // Remove the CUDA actions as they are already connected to an host
1855 // action or fat binary.
1856 CudaDeviceActions.clear();
1857 }
1858
1859 // We avoid creating host action in device-only mode.
1860 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
Samuel Antao5b1a89a2016-10-27 00:53:34 +00001861 } else if (CurPhase > phases::Backend) {
1862 // If we are past the backend phase and still have a device action, we
1863 // don't have to do anything as this action is already a device
1864 // top-level action.
1865 return ABRT_Success;
Samuel Antao64e965e2016-09-30 15:34:19 +00001866 }
1867
1868 assert(CurPhase < phases::Backend && "Generating single CUDA "
1869 "instructions should only occur "
1870 "before the backend phase!");
1871
1872 // By default, we produce an action for each device arch.
1873 for (Action *&A : CudaDeviceActions)
1874 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
1875
1876 return ABRT_Success;
1877 }
1878
1879 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
1880 // While generating code for CUDA, we only depend on the host input action
1881 // to trigger the creation of all the CUDA device actions.
1882
1883 // If we are dealing with an input action, replicate it for each GPU
1884 // architecture. If we are in host-only mode we return 'success' so that
1885 // the host uses the CUDA offload kind.
1886 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
1887 assert(!GpuArchList.empty() &&
1888 "We should have at least one GPU architecture.");
1889
1890 // If the host input is not CUDA, we don't need to bother about this
1891 // input.
1892 if (IA->getType() != types::TY_CUDA) {
1893 // The builder will ignore this input.
1894 IsActive = false;
1895 return ABRT_Inactive;
1896 }
1897
1898 // Set the flag to true, so that the builder acts on the current input.
1899 IsActive = true;
1900
1901 if (CompileHostOnly)
1902 return ABRT_Success;
1903
1904 // Replicate inputs for each GPU architecture.
1905 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
1906 CudaDeviceActions.push_back(C.MakeAction<InputAction>(
1907 IA->getInputArg(), types::TY_CUDA_DEVICE));
1908
1909 return ABRT_Success;
1910 }
1911
1912 return IsActive ? ABRT_Success : ABRT_Inactive;
1913 }
1914
1915 void appendTopLevelActions(ActionList &AL) override {
1916 // Utility to append actions to the top level list.
1917 auto AddTopLevel = [&](Action *A, CudaArch BoundArch) {
1918 OffloadAction::DeviceDependences Dep;
1919 Dep.add(*A, *ToolChains.front(), CudaArchToString(BoundArch),
1920 Action::OFK_Cuda);
1921 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
1922 };
1923
1924 // If we have a fat binary, add it to the list.
1925 if (CudaFatBinary) {
1926 AddTopLevel(CudaFatBinary, CudaArch::UNKNOWN);
1927 CudaDeviceActions.clear();
1928 CudaFatBinary = nullptr;
1929 return;
1930 }
1931
1932 if (CudaDeviceActions.empty())
1933 return;
1934
1935 // If we have CUDA actions at this point, that's because we have a have
1936 // partial compilation, so we should have an action for each GPU
1937 // architecture.
1938 assert(CudaDeviceActions.size() == GpuArchList.size() &&
1939 "Expecting one action per GPU architecture.");
1940 assert(ToolChains.size() == 1 &&
1941 "Expecting to have a sing CUDA toolchain.");
1942 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
1943 AddTopLevel(CudaDeviceActions[I], GpuArchList[I]);
1944
1945 CudaDeviceActions.clear();
1946 }
1947
1948 bool initialize() override {
1949 // We don't need to support CUDA.
1950 if (!C.hasOffloadToolChain<Action::OFK_Cuda>())
1951 return false;
1952
1953 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
1954 assert(HostTC && "No toolchain for host compilation.");
1955 if (HostTC->getTriple().isNVPTX()) {
1956 // We do not support targeting NVPTX for host compilation. Throw
1957 // an error and abort pipeline construction early so we don't trip
1958 // asserts that assume device-side compilation.
1959 C.getDriver().Diag(diag::err_drv_cuda_nvptx_host);
1960 return true;
1961 }
1962
1963 ToolChains.push_back(C.getSingleOffloadToolChain<Action::OFK_Cuda>());
1964
1965 Arg *PartialCompilationArg = Args.getLastArg(
1966 options::OPT_cuda_host_only, options::OPT_cuda_device_only,
1967 options::OPT_cuda_compile_host_device);
1968 CompileHostOnly = PartialCompilationArg &&
1969 PartialCompilationArg->getOption().matches(
1970 options::OPT_cuda_host_only);
1971 CompileDeviceOnly = PartialCompilationArg &&
1972 PartialCompilationArg->getOption().matches(
1973 options::OPT_cuda_device_only);
1974
1975 // Collect all cuda_gpu_arch parameters, removing duplicates.
Artem Belevicha424e882016-12-09 22:59:17 +00001976 std::set<CudaArch> GpuArchs;
Samuel Antao64e965e2016-09-30 15:34:19 +00001977 bool Error = false;
1978 for (Arg *A : Args) {
Artem Belevicha424e882016-12-09 22:59:17 +00001979 if (!(A->getOption().matches(options::OPT_cuda_gpu_arch_EQ) ||
1980 A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ)))
Samuel Antao64e965e2016-09-30 15:34:19 +00001981 continue;
1982 A->claim();
1983
Artem Belevicha424e882016-12-09 22:59:17 +00001984 const StringRef ArchStr = A->getValue();
1985 if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ) &&
1986 ArchStr == "all") {
1987 GpuArchs.clear();
1988 continue;
1989 }
Samuel Antao64e965e2016-09-30 15:34:19 +00001990 CudaArch Arch = StringToCudaArch(ArchStr);
1991 if (Arch == CudaArch::UNKNOWN) {
1992 C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
1993 Error = true;
Artem Belevicha424e882016-12-09 22:59:17 +00001994 } else if (A->getOption().matches(options::OPT_cuda_gpu_arch_EQ))
1995 GpuArchs.insert(Arch);
1996 else if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ))
1997 GpuArchs.erase(Arch);
1998 else
1999 llvm_unreachable("Unexpected option.");
Samuel Antao64e965e2016-09-30 15:34:19 +00002000 }
2001
Artem Belevicha424e882016-12-09 22:59:17 +00002002 // Collect list of GPUs remaining in the set.
2003 for (CudaArch Arch : GpuArchs)
2004 GpuArchList.push_back(Arch);
2005
2006 // Default to sm_20 which is the lowest common denominator for
2007 // supported GPUs. sm_20 code should work correctly, if
2008 // suboptimally, on all newer GPUs.
Samuel Antao64e965e2016-09-30 15:34:19 +00002009 if (GpuArchList.empty())
2010 GpuArchList.push_back(CudaArch::SM_20);
2011
2012 return Error;
2013 }
2014 };
2015
Samuel Antao28c4f182016-10-27 17:08:03 +00002016 /// OpenMP action builder. The host bitcode is passed to the device frontend
2017 /// and all the device linked images are passed to the host link phase.
2018 class OpenMPActionBuilder final : public DeviceActionBuilder {
2019 /// The OpenMP actions for the current input.
2020 ActionList OpenMPDeviceActions;
2021
2022 /// The linker inputs obtained for each toolchain.
2023 SmallVector<ActionList, 8> DeviceLinkerInputs;
2024
2025 public:
2026 OpenMPActionBuilder(Compilation &C, DerivedArgList &Args,
2027 const Driver::InputList &Inputs)
2028 : DeviceActionBuilder(C, Args, Inputs, Action::OFK_OpenMP) {}
2029
2030 ActionBuilderReturnCode
2031 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2032 phases::ID CurPhase, phases::ID FinalPhase,
2033 PhasesTy &Phases) override {
2034
2035 // We should always have an action for each input.
2036 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2037 "Number of OpenMP actions and toolchains do not match.");
2038
2039 // The host only depends on device action in the linking phase, when all
2040 // the device images have to be embedded in the host image.
2041 if (CurPhase == phases::Link) {
2042 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2043 "Toolchains and linker inputs sizes do not match.");
2044 auto LI = DeviceLinkerInputs.begin();
2045 for (auto *A : OpenMPDeviceActions) {
2046 LI->push_back(A);
2047 ++LI;
2048 }
2049
2050 // We passed the device action as a host dependence, so we don't need to
2051 // do anything else with them.
2052 OpenMPDeviceActions.clear();
2053 return ABRT_Success;
2054 }
2055
2056 // By default, we produce an action for each device arch.
2057 for (Action *&A : OpenMPDeviceActions)
2058 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2059
2060 return ABRT_Success;
2061 }
2062
2063 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2064
2065 // If this is an input action replicate it for each OpenMP toolchain.
2066 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2067 OpenMPDeviceActions.clear();
2068 for (unsigned I = 0; I < ToolChains.size(); ++I)
2069 OpenMPDeviceActions.push_back(
2070 C.MakeAction<InputAction>(IA->getInputArg(), IA->getType()));
2071 return ABRT_Success;
2072 }
2073
Samuel Antaofab4f372016-10-27 18:00:51 +00002074 // If this is an unbundling action use it as is for each OpenMP toolchain.
2075 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2076 OpenMPDeviceActions.clear();
2077 for (unsigned I = 0; I < ToolChains.size(); ++I) {
2078 OpenMPDeviceActions.push_back(UA);
2079 UA->registerDependentActionInfo(
2080 ToolChains[I], /*BoundArch=*/StringRef(), Action::OFK_OpenMP);
2081 }
2082 return ABRT_Success;
2083 }
2084
Samuel Antao28c4f182016-10-27 17:08:03 +00002085 // When generating code for OpenMP we use the host compile phase result as
2086 // a dependence to the device compile phase so that it can learn what
2087 // declarations should be emitted. However, this is not the only use for
2088 // the host action, so we prevent it from being collapsed.
2089 if (isa<CompileJobAction>(HostAction)) {
2090 HostAction->setCannotBeCollapsedWithNextDependentAction();
2091 assert(ToolChains.size() == OpenMPDeviceActions.size() &&
2092 "Toolchains and device action sizes do not match.");
2093 OffloadAction::HostDependence HDep(
2094 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2095 /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2096 auto TC = ToolChains.begin();
2097 for (Action *&A : OpenMPDeviceActions) {
2098 assert(isa<CompileJobAction>(A));
2099 OffloadAction::DeviceDependences DDep;
2100 DDep.add(*A, **TC, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2101 A = C.MakeAction<OffloadAction>(HDep, DDep);
2102 ++TC;
2103 }
2104 }
2105 return ABRT_Success;
2106 }
2107
Samuel Antao69d6f312016-10-27 17:50:43 +00002108 void appendTopLevelActions(ActionList &AL) override {
2109 if (OpenMPDeviceActions.empty())
2110 return;
2111
2112 // We should always have an action for each input.
2113 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2114 "Number of OpenMP actions and toolchains do not match.");
2115
2116 // Append all device actions followed by the proper offload action.
2117 auto TI = ToolChains.begin();
2118 for (auto *A : OpenMPDeviceActions) {
2119 OffloadAction::DeviceDependences Dep;
2120 Dep.add(*A, **TI, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2121 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2122 ++TI;
2123 }
2124 // We no longer need the action stored in this builder.
2125 OpenMPDeviceActions.clear();
2126 }
2127
Samuel Antao28c4f182016-10-27 17:08:03 +00002128 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {
2129 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2130 "Toolchains and linker inputs sizes do not match.");
2131
2132 // Append a new link action for each device.
2133 auto TC = ToolChains.begin();
2134 for (auto &LI : DeviceLinkerInputs) {
2135 auto *DeviceLinkAction =
2136 C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2137 DA.add(*DeviceLinkAction, **TC, /*BoundArch=*/nullptr,
2138 Action::OFK_OpenMP);
2139 ++TC;
2140 }
2141 }
2142
2143 bool initialize() override {
2144 // Get the OpenMP toolchains. If we don't get any, the action builder will
2145 // know there is nothing to do related to OpenMP offloading.
2146 auto OpenMPTCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
2147 for (auto TI = OpenMPTCRange.first, TE = OpenMPTCRange.second; TI != TE;
2148 ++TI)
2149 ToolChains.push_back(TI->second);
2150
2151 DeviceLinkerInputs.resize(ToolChains.size());
2152 return false;
2153 }
Samuel Antao69d6f312016-10-27 17:50:43 +00002154
2155 bool canUseBundlerUnbundler() const override {
2156 // OpenMP should use bundled files whenever possible.
2157 return true;
2158 }
Samuel Antao28c4f182016-10-27 17:08:03 +00002159 };
2160
2161 ///
2162 /// TODO: Add the implementation for other specialized builders here.
2163 ///
Samuel Antao64e965e2016-09-30 15:34:19 +00002164
2165 /// Specialized builders being used by this offloading action builder.
2166 SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders;
2167
Samuel Antao69d6f312016-10-27 17:50:43 +00002168 /// Flag set to true if all valid builders allow file bundling/unbundling.
2169 bool CanUseBundler;
2170
Samuel Antao64e965e2016-09-30 15:34:19 +00002171public:
2172 OffloadingActionBuilder(Compilation &C, DerivedArgList &Args,
2173 const Driver::InputList &Inputs)
Samuel Antao10e905c2016-10-27 01:08:58 +00002174 : C(C) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002175 // Create a specialized builder for each device toolchain.
2176
2177 IsValid = true;
2178
2179 // Create a specialized builder for CUDA.
2180 SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs));
2181
Samuel Antao28c4f182016-10-27 17:08:03 +00002182 // Create a specialized builder for OpenMP.
2183 SpecializedBuilders.push_back(new OpenMPActionBuilder(C, Args, Inputs));
2184
Samuel Antao64e965e2016-09-30 15:34:19 +00002185 //
2186 // TODO: Build other specialized builders here.
2187 //
2188
Samuel Antao69d6f312016-10-27 17:50:43 +00002189 // Initialize all the builders, keeping track of errors. If all valid
2190 // builders agree that we can use bundling, set the flag to true.
2191 unsigned ValidBuilders = 0u;
2192 unsigned ValidBuildersSupportingBundling = 0u;
2193 for (auto *SB : SpecializedBuilders) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002194 IsValid = IsValid && !SB->initialize();
Samuel Antao69d6f312016-10-27 17:50:43 +00002195
2196 // Update the counters if the builder is valid.
2197 if (SB->isValid()) {
2198 ++ValidBuilders;
2199 if (SB->canUseBundlerUnbundler())
2200 ++ValidBuildersSupportingBundling;
2201 }
2202 }
2203 CanUseBundler =
2204 ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling;
Artem Belevichf981e30b2016-08-02 22:37:47 +00002205 }
Justin Lebardc3c5042016-04-19 02:27:07 +00002206
Samuel Antao64e965e2016-09-30 15:34:19 +00002207 ~OffloadingActionBuilder() {
2208 for (auto *SB : SpecializedBuilders)
2209 delete SB;
Samuel Antaod06239d2016-07-15 23:13:27 +00002210 }
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002211
Samuel Antao64e965e2016-09-30 15:34:19 +00002212 /// Generate an action that adds device dependences (if any) to a host action.
2213 /// If no device dependence actions exist, just return the host action \a
2214 /// HostAction. If an error is found or if no builder requires the host action
2215 /// to be generated, return nullptr.
2216 Action *
2217 addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg,
2218 phases::ID CurPhase, phases::ID FinalPhase,
2219 DeviceActionBuilder::PhasesTy &Phases) {
2220 if (!IsValid)
2221 return nullptr;
Justin Lebar7bf77982016-01-11 23:27:13 +00002222
Samuel Antao64e965e2016-09-30 15:34:19 +00002223 if (SpecializedBuilders.empty())
2224 return HostAction;
2225
2226 assert(HostAction && "Invalid host action!");
2227
2228 OffloadAction::DeviceDependences DDeps;
2229 // Check if all the programming models agree we should not emit the host
2230 // action. Also, keep track of the offloading kinds employed.
2231 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2232 unsigned InactiveBuilders = 0u;
2233 unsigned IgnoringBuilders = 0u;
2234 for (auto *SB : SpecializedBuilders) {
2235 if (!SB->isValid()) {
2236 ++InactiveBuilders;
2237 continue;
2238 }
2239
Samuel Antao28c4f182016-10-27 17:08:03 +00002240 auto RetCode =
2241 SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases);
Samuel Antao64e965e2016-09-30 15:34:19 +00002242
2243 // If the builder explicitly says the host action should be ignored,
2244 // we need to increment the variable that tracks the builders that request
2245 // the host object to be ignored.
2246 if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host)
2247 ++IgnoringBuilders;
2248
2249 // Unless the builder was inactive for this action, we have to record the
2250 // offload kind because the host will have to use it.
2251 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2252 OffloadKind |= SB->getAssociatedOffloadKind();
2253 }
2254
2255 // If all builders agree that the host object should be ignored, just return
2256 // nullptr.
2257 if (IgnoringBuilders &&
2258 SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders))
2259 return nullptr;
2260
2261 if (DDeps.getActions().empty())
2262 return HostAction;
2263
2264 // We have dependences we need to bundle together. We use an offload action
2265 // for that.
2266 OffloadAction::HostDependence HDep(
2267 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2268 /*BoundArch=*/nullptr, DDeps);
2269 return C.MakeAction<OffloadAction>(HDep, DDeps);
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002270 }
2271
Samuel Antao64e965e2016-09-30 15:34:19 +00002272 /// Generate an action that adds a host dependence to a device action. The
2273 /// results will be kept in this action builder. Return true if an error was
2274 /// found.
Samuel Antaofab4f372016-10-27 18:00:51 +00002275 bool addHostDependenceToDeviceActions(Action *&HostAction,
Samuel Antao64e965e2016-09-30 15:34:19 +00002276 const Arg *InputArg) {
2277 if (!IsValid)
2278 return true;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002279
Samuel Antaofab4f372016-10-27 18:00:51 +00002280 // If we are supporting bundling/unbundling and the current action is an
2281 // input action of non-source file, we replace the host action by the
2282 // unbundling action. The bundler tool has the logic to detect if an input
2283 // is a bundle or not and if the input is not a bundle it assumes it is a
2284 // host file. Therefore it is safe to create an unbundling action even if
2285 // the input is not a bundle.
2286 if (CanUseBundler && isa<InputAction>(HostAction) &&
2287 InputArg->getOption().getKind() == llvm::opt::Option::InputClass &&
2288 !types::isSrcFile(HostAction->getType())) {
2289 auto UnbundlingHostAction =
2290 C.MakeAction<OffloadUnbundlingJobAction>(HostAction);
2291 UnbundlingHostAction->registerDependentActionInfo(
2292 C.getSingleOffloadToolChain<Action::OFK_Host>(),
2293 /*BoundArch=*/StringRef(), Action::OFK_Host);
2294 HostAction = UnbundlingHostAction;
2295 }
2296
Samuel Antao64e965e2016-09-30 15:34:19 +00002297 assert(HostAction && "Invalid host action!");
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002298
Samuel Antao64e965e2016-09-30 15:34:19 +00002299 // Register the offload kinds that are used.
2300 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2301 for (auto *SB : SpecializedBuilders) {
2302 if (!SB->isValid())
2303 continue;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002304
Samuel Antao64e965e2016-09-30 15:34:19 +00002305 auto RetCode = SB->addDeviceDepences(HostAction);
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002306
Samuel Antao64e965e2016-09-30 15:34:19 +00002307 // Host dependences for device actions are not compatible with that same
2308 // action being ignored.
2309 assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host &&
2310 "Host dependence not expected to be ignored.!");
Samuel Antaod06239d2016-07-15 23:13:27 +00002311
Samuel Antao64e965e2016-09-30 15:34:19 +00002312 // Unless the builder was inactive for this action, we have to record the
2313 // offload kind because the host will have to use it.
2314 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2315 OffloadKind |= SB->getAssociatedOffloadKind();
2316 }
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002317
Samuel Antao64e965e2016-09-30 15:34:19 +00002318 return false;
2319 }
2320
Samuel Antao69d6f312016-10-27 17:50:43 +00002321 /// Add the offloading top level actions to the provided action list. This
2322 /// function can replace the host action by a bundling action if the
2323 /// programming models allow it.
Samuel Antao64e965e2016-09-30 15:34:19 +00002324 bool appendTopLevelActions(ActionList &AL, Action *HostAction,
2325 const Arg *InputArg) {
Samuel Antao69d6f312016-10-27 17:50:43 +00002326 // Get the device actions to be appended.
2327 ActionList OffloadAL;
Samuel Antao64e965e2016-09-30 15:34:19 +00002328 for (auto *SB : SpecializedBuilders) {
2329 if (!SB->isValid())
2330 continue;
Samuel Antao69d6f312016-10-27 17:50:43 +00002331 SB->appendTopLevelActions(OffloadAL);
Samuel Antao64e965e2016-09-30 15:34:19 +00002332 }
2333
Samuel Antao69d6f312016-10-27 17:50:43 +00002334 // If we can use the bundler, replace the host action by the bundling one in
2335 // the resulting list. Otherwise, just append the device actions.
2336 if (CanUseBundler && !OffloadAL.empty()) {
2337 // Add the host action to the list in order to create the bundling action.
2338 OffloadAL.push_back(HostAction);
2339
2340 // We expect that the host action was just appended to the action list
2341 // before this method was called.
2342 assert(HostAction == AL.back() && "Host action not in the list??");
2343 HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL);
2344 AL.back() = HostAction;
2345 } else
2346 AL.append(OffloadAL.begin(), OffloadAL.end());
2347
Samuel Antao64e965e2016-09-30 15:34:19 +00002348 // Propagate to the current host action (if any) the offload information
2349 // associated with the current input.
2350 if (HostAction)
2351 HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg],
2352 /*BoundArch=*/nullptr);
Samuel Antao64e965e2016-09-30 15:34:19 +00002353 return false;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002354 }
Artem Belevich5bde4e02015-07-20 20:02:54 +00002355
Samuel Antao64e965e2016-09-30 15:34:19 +00002356 /// Processes the host linker action. This currently consists of replacing it
2357 /// with an offload action if there are device link objects and propagate to
2358 /// the host action all the offload kinds used in the current compilation. The
2359 /// resulting action is returned.
2360 Action *processHostLinkAction(Action *HostAction) {
2361 // Add all the dependences from the device linking actions.
2362 OffloadAction::DeviceDependences DDeps;
2363 for (auto *SB : SpecializedBuilders) {
2364 if (!SB->isValid())
2365 continue;
Justin Lebar21e5d4f2016-01-14 21:41:27 +00002366
Samuel Antao64e965e2016-09-30 15:34:19 +00002367 SB->appendLinkDependences(DDeps);
Justin Lebar21e5d4f2016-01-14 21:41:27 +00002368 }
Samuel Antaod06239d2016-07-15 23:13:27 +00002369
Samuel Antao64e965e2016-09-30 15:34:19 +00002370 // Calculate all the offload kinds used in the current compilation.
2371 unsigned ActiveOffloadKinds = 0u;
2372 for (auto &I : InputArgToOffloadKindMap)
2373 ActiveOffloadKinds |= I.second;
2374
2375 // If we don't have device dependencies, we don't have to create an offload
2376 // action.
2377 if (DDeps.getActions().empty()) {
2378 // Propagate all the active kinds to host action. Given that it is a link
2379 // action it is assumed to depend on all actions generated so far.
2380 HostAction->propagateHostOffloadInfo(ActiveOffloadKinds,
2381 /*BoundArch=*/nullptr);
2382 return HostAction;
2383 }
2384
2385 // Create the offload action with all dependences. When an offload action
2386 // is created the kinds are propagated to the host action, so we don't have
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002387 // to do that explicitly here.
Samuel Antao64e965e2016-09-30 15:34:19 +00002388 OffloadAction::HostDependence HDep(
2389 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2390 /*BoundArch*/ nullptr, ActiveOffloadKinds);
2391 return C.MakeAction<OffloadAction>(HDep, DDeps);
2392 }
2393};
2394} // anonymous namespace.
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002395
Justin Lebar0f3474c2016-02-11 02:00:50 +00002396void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
2397 const InputList &Inputs, ActionList &Actions) const {
Chad Rosierecdede82011-08-12 22:08:57 +00002398 llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00002399
Daniel Dunbar34c41872009-03-13 00:17:48 +00002400 if (!SuppressMissingInputWarning && Inputs.empty()) {
Daniel Dunbarbfeec742009-03-12 23:55:14 +00002401 Diag(clang::diag::err_drv_no_input_files);
2402 return;
2403 }
2404
Chad Rosier7742b5d2011-07-27 23:36:45 +00002405 Arg *FinalPhaseArg;
2406 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
Daniel Dunbarbfeec742009-03-12 23:55:14 +00002407
Bob Haarmanaaf51912017-02-27 19:40:19 +00002408 if (FinalPhase == phases::Link) {
2409 if (Args.hasArg(options::OPT_emit_llvm))
2410 Diag(clang::diag::err_drv_emit_llvm_link);
2411 if (IsCLMode() && LTOMode != LTOK_None &&
2412 !Args.getLastArgValue(options::OPT_fuse_ld_EQ).equals_lower("lld"))
2413 Diag(clang::diag::err_drv_lto_without_lld);
Rafael Espindolae8025642013-08-25 14:27:09 +00002414 }
2415
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002416 // Reject -Z* at the top level, these options should never have been exposed
2417 // by gcc.
Daniel Dunbardd765242009-03-26 16:12:09 +00002418 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
Daniel Dunbar0e759942009-03-20 06:14:23 +00002419 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
Daniel Dunbarbfeec742009-03-12 23:55:14 +00002420
Hans Wennborg13b7fe72013-08-12 23:26:25 +00002421 // Diagnose misuse of /Fo.
2422 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
Hans Wennborg13b7fe72013-08-12 23:26:25 +00002423 StringRef V = A->getValue();
Hans Wennborg61647532014-11-17 19:16:36 +00002424 if (Inputs.size() > 1 && !V.empty() &&
2425 !llvm::sys::path::is_separator(V.back())) {
Hans Wennborg13b7fe72013-08-12 23:26:25 +00002426 // Check whether /Fo tries to name an output file for multiple inputs.
Hans Wennborg9c1659b2013-10-18 22:49:04 +00002427 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002428 << A->getSpelling() << V;
Hans Wennborg13b7fe72013-08-12 23:26:25 +00002429 Args.eraseArg(options::OPT__SLASH_Fo);
2430 }
2431 }
2432
Hans Wennborg9c1659b2013-10-18 22:49:04 +00002433 // Diagnose misuse of /Fa.
2434 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
2435 StringRef V = A->getValue();
Hans Wennborg61647532014-11-17 19:16:36 +00002436 if (Inputs.size() > 1 && !V.empty() &&
2437 !llvm::sys::path::is_separator(V.back())) {
Hans Wennborg9c1659b2013-10-18 22:49:04 +00002438 // Check whether /Fa tries to name an asm file for multiple inputs.
2439 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002440 << A->getSpelling() << V;
Hans Wennborg9c1659b2013-10-18 22:49:04 +00002441 Args.eraseArg(options::OPT__SLASH_Fa);
2442 }
2443 }
2444
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00002445 // Diagnose misuse of /o.
2446 if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
2447 if (A->getValue()[0] == '\0') {
2448 // It has to have a value.
2449 Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
2450 Args.eraseArg(options::OPT__SLASH_o);
2451 }
2452 }
2453
Nico Weber2ca4be92016-03-01 23:16:44 +00002454 // Diagnose unsupported forms of /Yc /Yu. Ignore /Yc/Yu for now if:
2455 // * no filename after it
2456 // * both /Yc and /Yu passed but with different filenames
2457 // * corresponding file not also passed as /FI
2458 Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
2459 Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
2460 if (YcArg && YcArg->getValue()[0] == '\0') {
2461 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YcArg->getSpelling();
2462 Args.eraseArg(options::OPT__SLASH_Yc);
2463 YcArg = nullptr;
2464 }
2465 if (YuArg && YuArg->getValue()[0] == '\0') {
2466 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YuArg->getSpelling();
2467 Args.eraseArg(options::OPT__SLASH_Yu);
2468 YuArg = nullptr;
2469 }
2470 if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
2471 Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
2472 Args.eraseArg(options::OPT__SLASH_Yc);
2473 Args.eraseArg(options::OPT__SLASH_Yu);
2474 YcArg = YuArg = nullptr;
2475 }
2476 if (YcArg || YuArg) {
2477 StringRef Val = YcArg ? YcArg->getValue() : YuArg->getValue();
2478 bool FoundMatchingInclude = false;
2479 for (const Arg *Inc : Args.filtered(options::OPT_include)) {
2480 // FIXME: Do case-insensitive matching and consider / and \ as equal.
2481 if (Inc->getValue() == Val)
2482 FoundMatchingInclude = true;
2483 }
2484 if (!FoundMatchingInclude) {
2485 Diag(clang::diag::warn_drv_ycyu_no_fi_arg_clang_cl)
2486 << (YcArg ? YcArg : YuArg)->getSpelling();
2487 Args.eraseArg(options::OPT__SLASH_Yc);
2488 Args.eraseArg(options::OPT__SLASH_Yu);
2489 YcArg = YuArg = nullptr;
2490 }
2491 }
2492 if (YcArg && Inputs.size() > 1) {
2493 Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
2494 Args.eraseArg(options::OPT__SLASH_Yc);
2495 YcArg = nullptr;
2496 }
2497 if (Args.hasArg(options::OPT__SLASH_Y_)) {
2498 // /Y- disables all pch handling. Rather than check for it everywhere,
2499 // just remove clang-cl pch-related flags here.
2500 Args.eraseArg(options::OPT__SLASH_Fp);
2501 Args.eraseArg(options::OPT__SLASH_Yc);
2502 Args.eraseArg(options::OPT__SLASH_Yu);
2503 YcArg = YuArg = nullptr;
2504 }
Nico Weber2ca4be92016-03-01 23:16:44 +00002505
Samuel Antao64e965e2016-09-30 15:34:19 +00002506 // Builder to be used to build offloading actions.
2507 OffloadingActionBuilder OffloadBuilder(C, Args, Inputs);
Samuel Antaod06239d2016-07-15 23:13:27 +00002508
Daniel Dunbar65229332009-03-13 11:38:42 +00002509 // Construct the actions to perform.
2510 ActionList LinkerInputs;
Alp Toker965f8822013-11-27 05:22:15 +00002511
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002512 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL;
Artem Belevich5bde4e02015-07-20 20:02:54 +00002513 for (auto &I : Inputs) {
2514 types::ID InputType = I.first;
2515 const Arg *InputArg = I.second;
Daniel Dunbar65229332009-03-13 11:38:42 +00002516
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002517 PL.clear();
2518 types::getCompilationPhases(InputType, PL);
Daniel Dunbar65229332009-03-13 11:38:42 +00002519
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002520 // If the first step comes after the final phase we are doing as part of
2521 // this compilation, warn the user about it.
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002522 phases::ID InitialPhase = PL[0];
Daniel Dunbar65229332009-03-13 11:38:42 +00002523 if (InitialPhase > FinalPhase) {
Daniel Dunbaradc5c7c2009-03-19 07:57:08 +00002524 // Claim here to avoid the more general unused warning.
2525 InputArg->claim();
Daniel Dunbar07806ca2009-09-17 04:13:26 +00002526
Daniel Dunbar2db3e732011-04-20 15:44:48 +00002527 // Suppress all unused style warnings with -Qunused-arguments
2528 if (Args.hasArg(options::OPT_Qunused_arguments))
2529 continue;
2530
Richard Smith403f76e2012-08-06 04:09:06 +00002531 // Special case when final phase determined by binary name, rather than
2532 // by a command-line argument with a corresponding Arg.
Hans Wennborg70850d82013-07-18 20:29:38 +00002533 if (CCCIsCPP())
Richard Smith403f76e2012-08-06 04:09:06 +00002534 Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002535 << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
Daniel Dunbar07806ca2009-09-17 04:13:26 +00002536 // Special case '-E' warning on a previously preprocessed file to make
2537 // more sense.
Richard Smith403f76e2012-08-06 04:09:06 +00002538 else if (InitialPhase == phases::Compile &&
2539 FinalPhase == phases::Preprocess &&
2540 getPreprocessedType(InputType) == types::TY_INVALID)
Daniel Dunbar07806ca2009-09-17 04:13:26 +00002541 Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002542 << InputArg->getAsString(Args) << !!FinalPhaseArg
2543 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
Daniel Dunbar07806ca2009-09-17 04:13:26 +00002544 else
2545 Diag(clang::diag::warn_drv_input_file_unused)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002546 << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
2547 << !!FinalPhaseArg
2548 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
Daniel Dunbar65229332009-03-13 11:38:42 +00002549 continue;
2550 }
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002551
Nico Weberad2d8f32016-04-21 19:59:10 +00002552 if (YcArg) {
2553 // Add a separate precompile phase for the compile phase.
2554 if (FinalPhase >= phases::Compile) {
Richard Smith8cd452d2016-08-30 18:55:16 +00002555 const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType);
Nico Weberad2d8f32016-04-21 19:59:10 +00002556 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PCHPL;
Richard Smith8cd452d2016-08-30 18:55:16 +00002557 types::getCompilationPhases(HeaderType, PCHPL);
David Blaikie0aaa7622017-01-13 17:34:15 +00002558 Arg *PchInputArg = MakeInputArg(Args, *Opts, YcArg->getValue());
Nico Weberad2d8f32016-04-21 19:59:10 +00002559
2560 // Build the pipeline for the pch file.
Richard Smith8cd452d2016-08-30 18:55:16 +00002561 Action *ClangClPch =
2562 C.MakeAction<InputAction>(*PchInputArg, HeaderType);
Nico Weberad2d8f32016-04-21 19:59:10 +00002563 for (phases::ID Phase : PCHPL)
2564 ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
2565 assert(ClangClPch);
2566 Actions.push_back(ClangClPch);
2567 // The driver currently exits after the first failed command. This
2568 // relies on that behavior, to make sure if the pch generation fails,
2569 // the main compilation won't run.
2570 }
2571 }
2572
Daniel Dunbar65229332009-03-13 11:38:42 +00002573 // Build the pipeline for this file.
Justin Lebar41094612016-01-11 23:07:27 +00002574 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
Samuel Antao64e965e2016-09-30 15:34:19 +00002575
2576 // Use the current host action in any of the offloading actions, if
2577 // required.
2578 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
2579 break;
2580
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002581 for (SmallVectorImpl<phases::ID>::iterator i = PL.begin(), e = PL.end();
2582 i != e; ++i) {
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002583 phases::ID Phase = *i;
Daniel Dunbar65229332009-03-13 11:38:42 +00002584
2585 // We are done if this step is past what the user requested.
2586 if (Phase > FinalPhase)
2587 break;
2588
Samuel Antao64e965e2016-09-30 15:34:19 +00002589 // Add any offload action the host action depends on.
2590 Current = OffloadBuilder.addDeviceDependencesToHostAction(
2591 Current, InputArg, Phase, FinalPhase, PL);
2592 if (!Current)
2593 break;
2594
Daniel Dunbar65229332009-03-13 11:38:42 +00002595 // Queue linker inputs.
2596 if (Phase == phases::Link) {
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002597 assert((i + 1) == e && "linking must be final compilation step.");
Justin Lebar41094612016-01-11 23:07:27 +00002598 LinkerInputs.push_back(Current);
2599 Current = nullptr;
Daniel Dunbar65229332009-03-13 11:38:42 +00002600 break;
2601 }
2602
Samuel Antao64e965e2016-09-30 15:34:19 +00002603 // Otherwise construct the appropriate action.
2604 auto *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current);
2605
2606 // We didn't create a new action, so we will just move to the next phase.
2607 if (NewCurrent == Current)
Daniel Dunbar13864952009-03-24 20:17:30 +00002608 continue;
2609
Samuel Antao64e965e2016-09-30 15:34:19 +00002610 Current = NewCurrent;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002611
Samuel Antao64e965e2016-09-30 15:34:19 +00002612 // Use the current host action in any of the offloading actions, if
2613 // required.
2614 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
2615 break;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002616
Daniel Dunbar65229332009-03-13 11:38:42 +00002617 if (Current->getType() == types::TY_Nothing)
2618 break;
2619 }
2620
Samuel Antao64e965e2016-09-30 15:34:19 +00002621 // If we ended with something, add to the output list.
2622 if (Current)
Justin Lebar41094612016-01-11 23:07:27 +00002623 Actions.push_back(Current);
Samuel Antao64e965e2016-09-30 15:34:19 +00002624
2625 // Add any top level actions generated for offloading.
2626 OffloadBuilder.appendTopLevelActions(Actions, Current, InputArg);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002627 }
Daniel Dunbar65229332009-03-13 11:38:42 +00002628
Samuel Antao64e965e2016-09-30 15:34:19 +00002629 // Add a link action if necessary.
Samuel Antaod06239d2016-07-15 23:13:27 +00002630 if (!LinkerInputs.empty()) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002631 Action *LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image);
2632 LA = OffloadBuilder.processHostLinkAction(LA);
2633 Actions.push_back(LA);
Samuel Antaod06239d2016-07-15 23:13:27 +00002634 }
Daniel Dunbarc7a67b72009-12-22 23:19:32 +00002635
2636 // If we are linking, claim any options which are obviously only used for
2637 // compilation.
Hans Wennborga8ef14f2013-09-17 00:03:41 +00002638 if (FinalPhase == phases::Link && PL.size() == 1) {
Daniel Dunbarc7a67b72009-12-22 23:19:32 +00002639 Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
Hans Wennborga8ef14f2013-09-17 00:03:41 +00002640 Args.ClaimAllArgs(options::OPT_cl_compile_Group);
2641 }
2642
2643 // Claim ignored clang-cl options.
2644 Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
Artem Belevichbaae0932015-07-28 21:01:30 +00002645
Justin Lebardc3c5042016-04-19 02:27:07 +00002646 // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed
2647 // to non-CUDA compilations and should not trigger warnings there.
Artem Belevichbaae0932015-07-28 21:01:30 +00002648 Args.ClaimAllArgs(options::OPT_cuda_host_only);
Justin Lebardc3c5042016-04-19 02:27:07 +00002649 Args.ClaimAllArgs(options::OPT_cuda_compile_host_device);
Daniel Dunbar65229332009-03-13 11:38:42 +00002650}
2651
Justin Lebar0f3474c2016-02-11 02:00:50 +00002652Action *Driver::ConstructPhaseAction(Compilation &C, const ArgList &Args,
2653 phases::ID Phase, Action *Input) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00002654 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
Samuel Antao64e965e2016-09-30 15:34:19 +00002655
2656 // Some types skip the assembler phase (e.g., llvm-bc), but we can't
2657 // encode this in the steps because the intermediate type depends on
2658 // arguments. Just special case here.
2659 if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm)
2660 return Input;
2661
Daniel Dunbar65229332009-03-13 11:38:42 +00002662 // Build the appropriate action.
2663 switch (Phase) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002664 case phases::Link:
2665 llvm_unreachable("link action invalid here.");
Daniel Dunbar65229332009-03-13 11:38:42 +00002666 case phases::Preprocess: {
Daniel Dunbard67a3222009-03-30 06:36:42 +00002667 types::ID OutputTy;
2668 // -{M, MM} alter the output type.
Daniel Dunbar86aed7d2010-12-08 21:33:40 +00002669 if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
Daniel Dunbard67a3222009-03-30 06:36:42 +00002670 OutputTy = types::TY_Dependencies;
2671 } else {
David Blaikie5d577a22012-06-29 22:03:56 +00002672 OutputTy = Input->getType();
2673 if (!Args.hasFlag(options::OPT_frewrite_includes,
Justin Bognerce8245b2014-06-24 08:01:01 +00002674 options::OPT_fno_rewrite_includes, false) &&
Richard Smith86a3ef52017-06-09 21:24:02 +00002675 !Args.hasFlag(options::OPT_frewrite_imports,
2676 options::OPT_fno_rewrite_imports, false) &&
Justin Bognerce8245b2014-06-24 08:01:01 +00002677 !CCGenDiagnostics)
David Blaikie5d577a22012-06-29 22:03:56 +00002678 OutputTy = types::getPreprocessedType(OutputTy);
Daniel Dunbard67a3222009-03-30 06:36:42 +00002679 assert(OutputTy != types::TY_INVALID &&
2680 "Cannot preprocess this input type!");
2681 }
Justin Lebar41094612016-01-11 23:07:27 +00002682 return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
Daniel Dunbar65229332009-03-13 11:38:42 +00002683 }
Aaron Ballman1f10cc52012-07-31 01:21:00 +00002684 case phases::Precompile: {
Richard Smithdd4ad3d2016-08-30 19:06:26 +00002685 types::ID OutputTy = getPrecompiledType(Input->getType());
2686 assert(OutputTy != types::TY_INVALID &&
2687 "Cannot precompile this input type!");
Aaron Ballman1f10cc52012-07-31 01:21:00 +00002688 if (Args.hasArg(options::OPT_fsyntax_only)) {
2689 // Syntax checks should not emit a PCH file
2690 OutputTy = types::TY_Nothing;
2691 }
Justin Lebar41094612016-01-11 23:07:27 +00002692 return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
Aaron Ballman1f10cc52012-07-31 01:21:00 +00002693 }
Daniel Dunbar65229332009-03-13 11:38:42 +00002694 case phases::Compile: {
David Blaikie486f4402014-08-29 07:25:23 +00002695 if (Args.hasArg(options::OPT_fsyntax_only))
Justin Lebar41094612016-01-11 23:07:27 +00002696 return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
David Blaikie486f4402014-08-29 07:25:23 +00002697 if (Args.hasArg(options::OPT_rewrite_objc))
Justin Lebar41094612016-01-11 23:07:27 +00002698 return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
David Blaikie486f4402014-08-29 07:25:23 +00002699 if (Args.hasArg(options::OPT_rewrite_legacy_objc))
Justin Lebar41094612016-01-11 23:07:27 +00002700 return C.MakeAction<CompileJobAction>(Input,
2701 types::TY_RewrittenLegacyObjC);
David Blaikie486f4402014-08-29 07:25:23 +00002702 if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto))
Justin Lebar41094612016-01-11 23:07:27 +00002703 return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
David Blaikie486f4402014-08-29 07:25:23 +00002704 if (Args.hasArg(options::OPT__migrate))
Justin Lebar41094612016-01-11 23:07:27 +00002705 return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
David Blaikie486f4402014-08-29 07:25:23 +00002706 if (Args.hasArg(options::OPT_emit_ast))
Justin Lebar41094612016-01-11 23:07:27 +00002707 return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
David Blaikie486f4402014-08-29 07:25:23 +00002708 if (Args.hasArg(options::OPT_module_file_info))
Justin Lebar41094612016-01-11 23:07:27 +00002709 return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
David Blaikie486f4402014-08-29 07:25:23 +00002710 if (Args.hasArg(options::OPT_verify_pch))
Justin Lebar41094612016-01-11 23:07:27 +00002711 return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
2712 return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
Bob Wilson23a55f12014-12-21 07:00:00 +00002713 }
2714 case phases::Backend: {
Teresa Johnson945bc502015-10-15 20:35:53 +00002715 if (isUsingLTO()) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002716 types::ID Output =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002717 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
Justin Lebar41094612016-01-11 23:07:27 +00002718 return C.MakeAction<BackendJobAction>(Input, Output);
David Blaikie486f4402014-08-29 07:25:23 +00002719 }
2720 if (Args.hasArg(options::OPT_emit_llvm)) {
Shuxin Yang4b3c7ff2013-08-23 21:34:57 +00002721 types::ID Output =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002722 Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
Justin Lebar41094612016-01-11 23:07:27 +00002723 return C.MakeAction<BackendJobAction>(Input, Output);
Daniel Dunbar65229332009-03-13 11:38:42 +00002724 }
Justin Lebar41094612016-01-11 23:07:27 +00002725 return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
Daniel Dunbar65229332009-03-13 11:38:42 +00002726 }
2727 case phases::Assemble:
Justin Lebar21e5d4f2016-01-14 21:41:27 +00002728 return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
Daniel Dunbar65229332009-03-13 11:38:42 +00002729 }
2730
David Blaikie83d382b2011-09-23 05:06:16 +00002731 llvm_unreachable("invalid phase in ConstructPhaseAction");
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002732}
2733
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00002734void Driver::BuildJobs(Compilation &C) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00002735 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
Daniel Dunbare75d8342009-03-16 06:56:51 +00002736
2737 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
2738
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002739 // It is an error to provide a -o option if we are making multiple output
2740 // files.
Daniel Dunbare75d8342009-03-16 06:56:51 +00002741 if (FinalOutput) {
2742 unsigned NumOutputs = 0;
Saleem Abdulrasoolda3f4e52014-12-29 21:02:47 +00002743 for (const Action *A : C.getActions())
2744 if (A->getType() != types::TY_Nothing)
Daniel Dunbare75d8342009-03-16 06:56:51 +00002745 ++NumOutputs;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002746
Daniel Dunbare75d8342009-03-16 06:56:51 +00002747 if (NumOutputs > 1) {
2748 Diag(clang::diag::err_drv_output_argument_with_multiple_files);
Craig Topper92fc2df2014-05-17 16:56:41 +00002749 FinalOutput = nullptr;
Daniel Dunbare75d8342009-03-16 06:56:51 +00002750 }
2751 }
2752
Chad Rosier35767232013-04-30 22:01:21 +00002753 // Collect the list of architectures.
2754 llvm::StringSet<> ArchNames;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00002755 if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO())
2756 for (const Arg *A : C.getArgs())
Chad Rosier35767232013-04-30 22:01:21 +00002757 if (A->getOption().matches(options::OPT_arch))
2758 ArchNames.insert(A->getValue());
Chad Rosier35767232013-04-30 22:01:21 +00002759
Justin Lebarb44f6fe2016-01-14 21:41:21 +00002760 // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
2761 std::map<std::pair<const Action *, std::string>, InputInfo> CachedResults;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00002762 for (Action *A : C.getActions()) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002763 // If we are linking an image for multiple archs then the linker wants
2764 // -arch_multiple and -final_output <final image name>. Unfortunately, this
2765 // doesn't fit in cleanly because we have to pass this information down.
Daniel Dunbare75d8342009-03-16 06:56:51 +00002766 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002767 // FIXME: This is a hack; find a cleaner way to integrate this into the
2768 // process.
Craig Topper92fc2df2014-05-17 16:56:41 +00002769 const char *LinkingOutput = nullptr;
Daniel Dunbardd765242009-03-26 16:12:09 +00002770 if (isa<LipoJobAction>(A)) {
Daniel Dunbare75d8342009-03-16 06:56:51 +00002771 if (FinalOutput)
Richard Smithbd55daf2012-11-01 04:30:05 +00002772 LinkingOutput = FinalOutput->getValue();
Daniel Dunbare75d8342009-03-16 06:56:51 +00002773 else
Hans Wennborga7707222015-01-09 17:38:53 +00002774 LinkingOutput = getDefaultImageName();
Daniel Dunbare75d8342009-03-16 06:56:51 +00002775 }
2776
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002777 BuildJobsForAction(C, A, &C.getDefaultToolChain(),
Mehdi Aminic50b1a22016-10-07 21:27:26 +00002778 /*BoundArch*/ StringRef(),
Daniel Dunbare75d8342009-03-16 06:56:51 +00002779 /*AtTopLevel*/ true,
Chad Rosier35767232013-04-30 22:01:21 +00002780 /*MultipleArchs*/ ArchNames.size() > 1,
Samuel Antaod06239d2016-07-15 23:13:27 +00002781 /*LinkingOutput*/ LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00002782 /*TargetDeviceOffloadKind*/ Action::OFK_None);
Daniel Dunbare75d8342009-03-16 06:56:51 +00002783 }
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00002784
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002785 // If the user passed -Qunused-arguments or there were errors, don't warn
2786 // about any unused arguments.
Argyrios Kyrtzidis31448a42010-11-18 21:47:07 +00002787 if (Diags.hasErrorOccurred() ||
Daniel Dunbara3cfbe32009-04-07 19:04:18 +00002788 C.getArgs().hasArg(options::OPT_Qunused_arguments))
Daniel Dunbard175d972009-03-18 18:03:46 +00002789 return;
2790
Daniel Dunbar58399ae2009-03-29 22:24:54 +00002791 // Claim -### here.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002792 (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002793
Nico Weber47bf5052016-04-25 21:15:49 +00002794 // Claim --driver-mode, --rsp-quoting, it was handled earlier.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002795 (void)C.getArgs().hasArg(options::OPT_driver_mode);
Nico Weber47bf5052016-04-25 21:15:49 +00002796 (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
Hans Wennborg70850d82013-07-18 20:29:38 +00002797
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00002798 for (Arg *A : C.getArgs()) {
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00002799 // FIXME: It would be nice to be able to send the argument to the
David Blaikie9c902b52011-09-25 23:23:43 +00002800 // DiagnosticsEngine, so that extra values, position, and so on could be
2801 // printed.
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00002802 if (!A->isClaimed()) {
Michael J. Spencer66e2b202012-10-19 22:37:06 +00002803 if (A->getOption().hasFlag(options::NoArgumentUnused))
Daniel Dunbara3cfbe32009-04-07 19:04:18 +00002804 continue;
2805
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002806 // Suppress the warning automatically if this is just a flag, and it is an
2807 // instance of an argument we already claimed.
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00002808 const Option &Opt = A->getOption();
Michael J. Spencerad3ccc32012-08-20 21:41:17 +00002809 if (Opt.getKind() == Option::FlagClass) {
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00002810 bool DuplicateClaimed = false;
2811
Sean Silva14facf32015-06-09 01:57:17 +00002812 for (const Arg *AA : C.getArgs().filtered(&Opt)) {
2813 if (AA->isClaimed()) {
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00002814 DuplicateClaimed = true;
2815 break;
2816 }
2817 }
2818
2819 if (DuplicateClaimed)
2820 continue;
2821 }
2822
Ehsan Akhgarid8518332016-01-25 21:14:52 +00002823 // In clang-cl, don't mention unknown arguments here since they have
2824 // already been warned about.
2825 if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN))
2826 Diag(clang::diag::warn_drv_unused_argument)
2827 << A->getAsString(C.getArgs());
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00002828 }
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00002829 }
Daniel Dunbar95e6b192009-03-13 22:12:33 +00002830}
Daniel Dunbarc4343942010-02-03 03:07:56 +00002831
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002832namespace {
2833/// Utility class to control the collapse of dependent actions and select the
2834/// tools accordingly.
2835class ToolSelector final {
2836 /// The tool chain this selector refers to.
2837 const ToolChain &TC;
Daniel Dunbarf9ff3502010-05-14 02:03:00 +00002838
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002839 /// The compilation this selector refers to.
2840 const Compilation &C;
Samuel Antaod06239d2016-07-15 23:13:27 +00002841
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002842 /// The base action this selector refers to.
2843 const JobAction *BaseAction;
Samuel Antaod06239d2016-07-15 23:13:27 +00002844
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002845 /// Set to true if the current toolchain refers to host actions.
2846 bool IsHostSelector;
Samuel Antaod06239d2016-07-15 23:13:27 +00002847
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002848 /// Set to true if save-temps and embed-bitcode functionalities are active.
2849 bool SaveTemps;
2850 bool EmbedBitcode;
2851
2852 /// Get previous dependent action or null if that does not exist. If
2853 /// \a CanBeCollapsed is false, that action must be legal to collapse or
2854 /// null will be returned.
2855 const JobAction *getPrevDependentAction(const ActionList &Inputs,
2856 ActionList &SavedOffloadAction,
2857 bool CanBeCollapsed = true) {
2858 // An option can be collapsed only if it has a single input.
2859 if (Inputs.size() != 1)
Craig Topper92fc2df2014-05-17 16:56:41 +00002860 return nullptr;
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002861
2862 Action *CurAction = *Inputs.begin();
2863 if (CanBeCollapsed &&
2864 !CurAction->isCollapsingWithNextDependentActionLegal())
2865 return nullptr;
2866
2867 // If the input action is an offload action. Look through it and save any
2868 // offload action that can be dropped in the event of a collapse.
2869 if (auto *OA = dyn_cast<OffloadAction>(CurAction)) {
2870 // If the dependent action is a device action, we will attempt to collapse
2871 // only with other device actions. Otherwise, we would do the same but
2872 // with host actions only.
2873 if (!IsHostSelector) {
2874 if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) {
2875 CurAction =
2876 OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
2877 if (CanBeCollapsed &&
2878 !CurAction->isCollapsingWithNextDependentActionLegal())
2879 return nullptr;
2880 SavedOffloadAction.push_back(OA);
2881 return dyn_cast<JobAction>(CurAction);
2882 }
2883 } else if (OA->hasHostDependence()) {
2884 CurAction = OA->getHostDependence();
2885 if (CanBeCollapsed &&
2886 !CurAction->isCollapsingWithNextDependentActionLegal())
2887 return nullptr;
2888 SavedOffloadAction.push_back(OA);
2889 return dyn_cast<JobAction>(CurAction);
2890 }
2891 return nullptr;
2892 }
2893
2894 return dyn_cast<JobAction>(CurAction);
2895 }
2896
2897 /// Return true if an assemble action can be collapsed.
2898 bool canCollapseAssembleAction() const {
2899 return TC.useIntegratedAs() && !SaveTemps &&
2900 !C.getArgs().hasArg(options::OPT_via_file_asm) &&
2901 !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
2902 !C.getArgs().hasArg(options::OPT__SLASH_Fa);
2903 }
2904
2905 /// Return true if a preprocessor action can be collapsed.
2906 bool canCollapsePreprocessorAction() const {
2907 return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
2908 !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
2909 !C.getArgs().hasArg(options::OPT_rewrite_objc);
2910 }
2911
2912 /// Struct that relates an action with the offload actions that would be
2913 /// collapsed with it.
2914 struct JobActionInfo final {
2915 /// The action this info refers to.
2916 const JobAction *JA = nullptr;
2917 /// The offload actions we need to take care off if this action is
2918 /// collapsed.
2919 ActionList SavedOffloadAction;
2920 };
2921
2922 /// Append collapsed offload actions from the give nnumber of elements in the
2923 /// action info array.
2924 static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction,
2925 ArrayRef<JobActionInfo> &ActionInfo,
2926 unsigned ElementNum) {
2927 assert(ElementNum <= ActionInfo.size() && "Invalid number of elements.");
2928 for (unsigned I = 0; I < ElementNum; ++I)
2929 CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(),
2930 ActionInfo[I].SavedOffloadAction.end());
2931 }
2932
2933 /// Functions that attempt to perform the combining. They detect if that is
2934 /// legal, and if so they update the inputs \a Inputs and the offload action
2935 /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with
2936 /// the combined action is returned. If the combining is not legal or if the
2937 /// tool does not exist, null is returned.
2938 /// Currently three kinds of collapsing are supported:
2939 /// - Assemble + Backend + Compile;
2940 /// - Assemble + Backend ;
2941 /// - Backend + Compile.
2942 const Tool *
2943 combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
2944 const ActionList *&Inputs,
2945 ActionList &CollapsedOffloadAction) {
2946 if (ActionInfo.size() < 3 || !canCollapseAssembleAction())
2947 return nullptr;
2948 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
2949 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
2950 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA);
2951 if (!AJ || !BJ || !CJ)
2952 return nullptr;
2953
2954 // Get compiler tool.
2955 const Tool *T = TC.SelectTool(*CJ);
2956 if (!T)
2957 return nullptr;
2958
Steven Wu574b0f22016-03-01 01:07:58 +00002959 // When using -fembed-bitcode, it is required to have the same tool (clang)
2960 // for both CompilerJA and BackendJA. Otherwise, combine two stages.
2961 if (EmbedBitcode) {
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002962 const Tool *BT = TC.SelectTool(*BJ);
2963 if (BT == T)
2964 return nullptr;
Steven Wu574b0f22016-03-01 01:07:58 +00002965 }
Bob Wilson23a55f12014-12-21 07:00:00 +00002966
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002967 if (!T->hasIntegratedAssembler())
Bob Wilson23a55f12014-12-21 07:00:00 +00002968 return nullptr;
Samuel Antaod06239d2016-07-15 23:13:27 +00002969
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002970 Inputs = &CJ->getInputs();
2971 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
2972 /*NumElements=*/3);
2973 return T;
2974 }
2975 const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo,
2976 const ActionList *&Inputs,
2977 ActionList &CollapsedOffloadAction) {
2978 if (ActionInfo.size() < 2 || !canCollapseAssembleAction())
2979 return nullptr;
2980 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
2981 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
2982 if (!AJ || !BJ)
2983 return nullptr;
2984
2985 // Retrieve the compile job, backend action must always be preceded by one.
2986 ActionList CompileJobOffloadActions;
2987 auto *CJ = getPrevDependentAction(BJ->getInputs(), CompileJobOffloadActions,
2988 /*CanBeCollapsed=*/false);
2989 if (!AJ || !BJ || !CJ)
2990 return nullptr;
2991
2992 assert(isa<CompileJobAction>(CJ) &&
2993 "Expecting compile job preceding backend job.");
2994
2995 // Get compiler tool.
2996 const Tool *T = TC.SelectTool(*CJ);
2997 if (!T)
2998 return nullptr;
2999
3000 if (!T->hasIntegratedAssembler())
3001 return nullptr;
3002
3003 Inputs = &BJ->getInputs();
3004 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3005 /*NumElements=*/2);
3006 return T;
3007 }
3008 const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
3009 const ActionList *&Inputs,
3010 ActionList &CollapsedOffloadAction) {
3011 if (ActionInfo.size() < 2 || !canCollapsePreprocessorAction())
3012 return nullptr;
3013 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA);
3014 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA);
3015 if (!BJ || !CJ)
3016 return nullptr;
3017
3018 // Get compiler tool.
3019 const Tool *T = TC.SelectTool(*CJ);
3020 if (!T)
3021 return nullptr;
3022
3023 if (T->canEmitIR() && (SaveTemps || EmbedBitcode))
3024 return nullptr;
3025
3026 Inputs = &CJ->getInputs();
3027 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3028 /*NumElements=*/2);
3029 return T;
3030 }
3031
3032 /// Updates the inputs if the obtained tool supports combining with
3033 /// preprocessor action, and the current input is indeed a preprocessor
3034 /// action. If combining results in the collapse of offloading actions, those
3035 /// are appended to \a CollapsedOffloadAction.
3036 void combineWithPreprocessor(const Tool *T, const ActionList *&Inputs,
3037 ActionList &CollapsedOffloadAction) {
3038 if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP())
3039 return;
3040
3041 // Attempt to get a preprocessor action dependence.
3042 ActionList PreprocessJobOffloadActions;
3043 auto *PJ = getPrevDependentAction(*Inputs, PreprocessJobOffloadActions);
3044 if (!PJ || !isa<PreprocessJobAction>(PJ))
3045 return;
3046
3047 // This is legal to combine. Append any offload action we found and set the
3048 // current inputs to preprocessor inputs.
3049 CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(),
3050 PreprocessJobOffloadActions.end());
3051 Inputs = &PJ->getInputs();
3052 }
3053
3054public:
3055 ToolSelector(const JobAction *BaseAction, const ToolChain &TC,
3056 const Compilation &C, bool SaveTemps, bool EmbedBitcode)
3057 : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps),
3058 EmbedBitcode(EmbedBitcode) {
3059 assert(BaseAction && "Invalid base action.");
3060 IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None;
3061 }
3062
3063 /// Check if a chain of actions can be combined and return the tool that can
3064 /// handle the combination of actions. The pointer to the current inputs \a
3065 /// Inputs and the list of offload actions \a CollapsedOffloadActions
3066 /// connected to collapsed actions are updated accordingly. The latter enables
3067 /// the caller of the selector to process them afterwards instead of just
3068 /// dropping them. If no suitable tool is found, null will be returned.
3069 const Tool *getTool(const ActionList *&Inputs,
3070 ActionList &CollapsedOffloadAction) {
3071 //
3072 // Get the largest chain of actions that we could combine.
3073 //
3074
3075 SmallVector<JobActionInfo, 5> ActionChain(1);
3076 ActionChain.back().JA = BaseAction;
3077 while (ActionChain.back().JA) {
3078 const Action *CurAction = ActionChain.back().JA;
3079
3080 // Grow the chain by one element.
3081 ActionChain.resize(ActionChain.size() + 1);
3082 JobActionInfo &AI = ActionChain.back();
3083
3084 // Attempt to fill it with the
3085 AI.JA =
3086 getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction);
Daniel Dunbarc4343942010-02-03 03:07:56 +00003087 }
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003088
3089 // Pop the last action info as it could not be filled.
3090 ActionChain.pop_back();
3091
3092 //
3093 // Attempt to combine actions. If all combining attempts failed, just return
3094 // the tool of the provided action. At the end we attempt to combine the
3095 // action with any preprocessor action it may depend on.
3096 //
3097
3098 const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs,
3099 CollapsedOffloadAction);
3100 if (!T)
3101 T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction);
3102 if (!T)
3103 T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction);
3104 if (!T) {
3105 Inputs = &BaseAction->getInputs();
3106 T = TC.SelectTool(*BaseAction);
3107 }
3108
3109 combineWithPreprocessor(T, Inputs, CollapsedOffloadAction);
3110 return T;
Daniel Dunbarc4343942010-02-03 03:07:56 +00003111 }
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003112};
Daniel Dunbarc4343942010-02-03 03:07:56 +00003113}
3114
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003115/// Return a string that uniquely identifies the result of a job. The bound arch
3116/// is not necessarily represented in the toolchain's triple -- for example,
3117/// armv7 and armv7s both map to the same triple -- so we need both in our map.
3118/// Also, we need to add the offloading device kind, as the same tool chain can
3119/// be used for host and device for some programming models, e.g. OpenMP.
3120static std::string GetTriplePlusArchString(const ToolChain *TC,
3121 StringRef BoundArch,
3122 Action::OffloadKind OffloadKind) {
Justin Lebar55c83322016-01-16 03:30:08 +00003123 std::string TriplePlusArch = TC->getTriple().normalize();
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003124 if (!BoundArch.empty()) {
Justin Lebar55c83322016-01-16 03:30:08 +00003125 TriplePlusArch += "-";
3126 TriplePlusArch += BoundArch;
3127 }
Samuel Antao59efaed2016-10-27 17:31:22 +00003128 TriplePlusArch += "-";
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003129 TriplePlusArch += Action::GetOffloadKindName(OffloadKind);
3130 return TriplePlusArch;
3131}
3132
3133InputInfo Driver::BuildJobsForAction(
3134 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
3135 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
3136 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
3137 Action::OffloadKind TargetDeviceOffloadKind) const {
3138 std::pair<const Action *, std::string> ActionTC = {
3139 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003140 auto CachedResult = CachedResults.find(ActionTC);
3141 if (CachedResult != CachedResults.end()) {
3142 return CachedResult->second;
3143 }
Samuel Antaod06239d2016-07-15 23:13:27 +00003144 InputInfo Result = BuildJobsForActionNoCache(
3145 C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003146 CachedResults, TargetDeviceOffloadKind);
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003147 CachedResults[ActionTC] = Result;
3148 return Result;
3149}
3150
3151InputInfo Driver::BuildJobsForActionNoCache(
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003152 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003153 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
Samuel Antaod06239d2016-07-15 23:13:27 +00003154 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003155 Action::OffloadKind TargetDeviceOffloadKind) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003156 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
Daniel Dunbarc4acf9d2009-03-18 23:18:19 +00003157
Samuel Antaod06239d2016-07-15 23:13:27 +00003158 InputInfoList OffloadDependencesInputInfo;
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003159 bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None;
Samuel Antaod06239d2016-07-15 23:13:27 +00003160 if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
3161 // The offload action is expected to be used in four different situations.
3162 //
3163 // a) Set a toolchain/architecture/kind for a host action:
3164 // Host Action 1 -> OffloadAction -> Host Action 2
3165 //
3166 // b) Set a toolchain/architecture/kind for a device action;
3167 // Device Action 1 -> OffloadAction -> Device Action 2
3168 //
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003169 // c) Specify a device dependence to a host action;
Samuel Antaod06239d2016-07-15 23:13:27 +00003170 // Device Action 1 _
3171 // \
3172 // Host Action 1 ---> OffloadAction -> Host Action 2
3173 //
3174 // d) Specify a host dependence to a device action.
3175 // Host Action 1 _
3176 // \
3177 // Device Action 1 ---> OffloadAction -> Device Action 2
3178 //
3179 // For a) and b), we just return the job generated for the dependence. For
3180 // c) and d) we override the current action with the host/device dependence
3181 // if the current toolchain is host/device and set the offload dependences
3182 // info with the jobs obtained from the device/host dependence(s).
3183
3184 // If there is a single device option, just generate the job for it.
3185 if (OA->hasSingleDeviceDependence()) {
3186 InputInfo DevA;
3187 OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
3188 const char *DepBoundArch) {
3189 DevA =
3190 BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
3191 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003192 CachedResults, DepA->getOffloadingDeviceKind());
Samuel Antaod06239d2016-07-15 23:13:27 +00003193 });
3194 return DevA;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003195 }
Samuel Antaod06239d2016-07-15 23:13:27 +00003196
3197 // If 'Action 2' is host, we generate jobs for the device dependences and
3198 // override the current action with the host dependence. Otherwise, we
3199 // generate the host dependences and override the action with the device
3200 // dependence. The dependences can't therefore be a top-level action.
3201 OA->doOnEachDependence(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003202 /*IsHostDependence=*/BuildingForOffloadDevice,
Samuel Antaod06239d2016-07-15 23:13:27 +00003203 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3204 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
3205 C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false,
3206 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003207 DepA->getOffloadingDeviceKind()));
Samuel Antaod06239d2016-07-15 23:13:27 +00003208 });
3209
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003210 A = BuildingForOffloadDevice
Samuel Antaod06239d2016-07-15 23:13:27 +00003211 ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
3212 : OA->getHostDependence();
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003213 }
3214
Daniel Dunbare75d8342009-03-16 06:56:51 +00003215 if (const InputAction *IA = dyn_cast<InputAction>(A)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003216 // FIXME: It would be nice to not claim this here; maybe the old scheme of
3217 // just using Args was better?
Daniel Dunbar5cdf3e02009-03-19 07:29:38 +00003218 const Arg &Input = IA->getInputArg();
3219 Input.claim();
Daniel Dunbar35cbfeb2010-06-09 22:31:08 +00003220 if (Input.getOption().matches(options::OPT_INPUT)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00003221 const char *Name = Input.getValue();
Justin Lebard98cea82016-01-11 23:15:21 +00003222 return InputInfo(A, Name, /* BaseInput = */ Name);
Douglas Katzman678d0cb2015-06-16 18:01:24 +00003223 }
Justin Lebard98cea82016-01-11 23:15:21 +00003224 return InputInfo(A, &Input, /* BaseInput = */ "");
Daniel Dunbare75d8342009-03-16 06:56:51 +00003225 }
3226
3227 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
Chad Rosiera78a6eb2012-04-27 16:50:38 +00003228 const ToolChain *TC;
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003229 StringRef ArchName = BAA->getArchName();
Daniel Dunbar1ef3f2a2009-09-08 23:37:19 +00003230
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003231 if (!ArchName.empty())
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +00003232 TC = &getToolChain(C.getArgs(),
3233 computeTargetTriple(*this, DefaultTargetTriple,
3234 C.getArgs(), ArchName));
Chad Rosiera78a6eb2012-04-27 16:50:38 +00003235 else
3236 TC = &C.getDefaultToolChain();
Daniel Dunbar1ef3f2a2009-09-08 23:37:19 +00003237
Nico Weber5a459f82016-02-23 19:30:43 +00003238 return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
Samuel Antaod06239d2016-07-15 23:13:27 +00003239 MultipleArchs, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003240 TargetDeviceOffloadKind);
Daniel Dunbare75d8342009-03-16 06:56:51 +00003241 }
3242
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003243
Daniel Dunbare75d8342009-03-16 06:56:51 +00003244 const ActionList *Inputs = &A->getInputs();
Daniel Dunbarc4343942010-02-03 03:07:56 +00003245
3246 const JobAction *JA = cast<JobAction>(A);
Samuel Antaod06239d2016-07-15 23:13:27 +00003247 ActionList CollapsedOffloadActions;
3248
Mehdi Amini6683e222017-01-24 18:12:25 +00003249 ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(),
3250 embedBitcodeInObject() && !isUsingLTO());
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003251 const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions);
3252
Rafael Espindola79764462013-03-24 15:06:53 +00003253 if (!T)
Justin Lebar9eaa4892016-01-11 23:09:32 +00003254 return InputInfo();
Daniel Dunbare75d8342009-03-16 06:56:51 +00003255
Samuel Antaod06239d2016-07-15 23:13:27 +00003256 // If we've collapsed action list that contained OffloadAction we
3257 // need to build jobs for host/device-side inputs it may have held.
3258 for (const auto *OA : CollapsedOffloadActions)
3259 cast<OffloadAction>(OA)->doOnEachDependence(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003260 /*IsHostDependence=*/BuildingForOffloadDevice,
Samuel Antaod06239d2016-07-15 23:13:27 +00003261 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3262 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
Artem Belevichbee2f412016-08-22 18:50:34 +00003263 C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false,
Samuel Antaod06239d2016-07-15 23:13:27 +00003264 /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003265 DepA->getOffloadingDeviceKind()));
Samuel Antaod06239d2016-07-15 23:13:27 +00003266 });
Artem Belevichf8144ab2015-08-27 18:10:41 +00003267
Daniel Dunbare75d8342009-03-16 06:56:51 +00003268 // Only use pipes when there is exactly one input.
Daniel Dunbar1a093d22009-03-18 06:00:36 +00003269 InputInfoList InputInfos;
Saleem Abdulrasoolda3f4e52014-12-29 21:02:47 +00003270 for (const Action *Input : *Inputs) {
Eric Christopher14668dd2013-02-18 00:38:25 +00003271 // Treat dsymutil and verify sub-jobs as being at the top-level too, they
3272 // shouldn't get temporary output names.
Daniel Dunbar6beaf512010-06-04 18:28:41 +00003273 // FIXME: Clean this up.
Justin Lebar9eaa4892016-01-11 23:09:32 +00003274 bool SubJobAtTopLevel =
3275 AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
Samuel Antaod06239d2016-07-15 23:13:27 +00003276 InputInfos.push_back(BuildJobsForAction(
3277 C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003278 CachedResults, A->getOffloadingDeviceKind()));
Daniel Dunbare75d8342009-03-16 06:56:51 +00003279 }
3280
Daniel Dunbare75d8342009-03-16 06:56:51 +00003281 // Always use the first input as the base input.
3282 const char *BaseInput = InputInfos[0].getBaseInput();
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003283
Daniel Dunbar6beaf512010-06-04 18:28:41 +00003284 // ... except dsymutil actions, which use their actual input as the base
3285 // input.
3286 if (JA->getType() == types::TY_dSYM)
3287 BaseInput = InputInfos[0].getFilename();
3288
Samuel Antaod06239d2016-07-15 23:13:27 +00003289 // Append outputs of offload device jobs to the input list
3290 if (!OffloadDependencesInputInfo.empty())
3291 InputInfos.append(OffloadDependencesInputInfo.begin(),
3292 OffloadDependencesInputInfo.end());
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003293
Vedant Kumar18286cf2016-07-27 23:02:20 +00003294 // Set the effective triple of the toolchain for the duration of this job.
3295 llvm::Triple EffectiveTriple;
3296 const ToolChain &ToolTC = T->getToolChain();
Samuel Antao31fef982016-10-27 17:39:44 +00003297 const ArgList &Args =
3298 C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind());
Vedant Kumar18286cf2016-07-27 23:02:20 +00003299 if (InputInfos.size() != 1) {
3300 EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args));
3301 } else {
3302 // Pass along the input type if it can be unambiguously determined.
3303 EffectiveTriple = llvm::Triple(
3304 ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType()));
3305 }
3306 RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple);
3307
Daniel Dunbard00272f2010-08-02 02:38:15 +00003308 // Determine the place to write output to, if any.
Justin Lebar9eaa4892016-01-11 23:09:32 +00003309 InputInfo Result;
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003310 InputInfoList UnbundlingResults;
3311 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) {
3312 // If we have an unbundling job, we need to create results for all the
3313 // outputs. We also update the results cache so that other actions using
3314 // this unbundling action can get the right results.
3315 for (auto &UI : UA->getDependentActionsInfo()) {
3316 assert(UI.DependentOffloadKind != Action::OFK_None &&
3317 "Unbundling with no offloading??");
3318
3319 // Unbundling actions are never at the top level. When we generate the
3320 // offloading prefix, we also do that for the host file because the
3321 // unbundling action does not change the type of the output which can
3322 // cause a overwrite.
3323 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
3324 UI.DependentOffloadKind,
3325 UI.DependentToolChain->getTriple().normalize(),
3326 /*CreatePrefixForHost=*/true);
3327 auto CurI = InputInfo(
3328 UA, GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch,
3329 /*AtTopLevel=*/false, MultipleArchs,
3330 OffloadingPrefix),
3331 BaseInput);
3332 // Save the unbundling result.
3333 UnbundlingResults.push_back(CurI);
3334
3335 // Get the unique string identifier for this dependence and cache the
3336 // result.
3337 CachedResults[{A, GetTriplePlusArchString(
3338 UI.DependentToolChain, UI.DependentBoundArch,
3339 UI.DependentOffloadKind)}] = CurI;
3340 }
3341
3342 // Now that we have all the results generated, select the one that should be
3343 // returned for the current depending action.
3344 std::pair<const Action *, std::string> ActionTC = {
3345 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
3346 assert(CachedResults.find(ActionTC) != CachedResults.end() &&
3347 "Result does not exist??");
3348 Result = CachedResults[ActionTC];
3349 } else if (JA->getType() == types::TY_Nothing)
Justin Lebard98cea82016-01-11 23:15:21 +00003350 Result = InputInfo(A, BaseInput);
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003351 else {
3352 // We only have to generate a prefix for the host if this is not a top-level
3353 // action.
3354 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
3355 A->getOffloadingDeviceKind(), TC->getTriple().normalize(),
3356 /*CreatePrefixForHost=*/!!A->getOffloadingHostActiveKinds() &&
3357 !AtTopLevel);
Justin Lebard98cea82016-01-11 23:15:21 +00003358 Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
Samuel Antaod06239d2016-07-15 23:13:27 +00003359 AtTopLevel, MultipleArchs,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003360 OffloadingPrefix),
Justin Lebard98cea82016-01-11 23:15:21 +00003361 BaseInput);
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003362 }
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003363
Chad Rosierbe10f982011-08-02 17:58:04 +00003364 if (CCCPrintBindings && !CCGenDiagnostics) {
Rafael Espindola79764462013-03-24 15:06:53 +00003365 llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
3366 << " - \"" << T->getName() << "\", inputs: [";
Daniel Dunbarb39cc522009-03-17 22:47:06 +00003367 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
3368 llvm::errs() << InputInfos[i].getAsString();
3369 if (i + 1 != e)
3370 llvm::errs() << ", ";
3371 }
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003372 if (UnbundlingResults.empty())
3373 llvm::errs() << "], output: " << Result.getAsString() << "\n";
3374 else {
3375 llvm::errs() << "], outputs: [";
3376 for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) {
3377 llvm::errs() << UnbundlingResults[i].getAsString();
3378 if (i + 1 != e)
3379 llvm::errs() << ", ";
3380 }
3381 llvm::errs() << "] \n";
3382 }
Daniel Dunbarb39cc522009-03-17 22:47:06 +00003383 } else {
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003384 if (UnbundlingResults.empty())
3385 T->ConstructJob(
3386 C, *JA, Result, InputInfos,
3387 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
3388 LinkingOutput);
3389 else
Samuel Antao7108bf32016-11-03 15:41:50 +00003390 T->ConstructJobMultipleOutputs(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003391 C, *JA, UnbundlingResults, InputInfos,
3392 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
3393 LinkingOutput);
Daniel Dunbarb39cc522009-03-17 22:47:06 +00003394 }
Justin Lebar9eaa4892016-01-11 23:09:32 +00003395 return Result;
Daniel Dunbare75d8342009-03-16 06:56:51 +00003396}
3397
Hans Wennborga7707222015-01-09 17:38:53 +00003398const char *Driver::getDefaultImageName() const {
3399 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
3400 return Target.isOSWindows() ? "a.exe" : "a.out";
3401}
3402
Hans Wennborg2c21f742013-10-17 16:16:23 +00003403/// \brief Create output filename based on ArgValue, which could either be a
3404/// full filename, filename without extension, or a directory. If ArgValue
3405/// does not provide a filename, then use BaseName, and use the extension
3406/// suitable for FileType.
Hans Wennborg207fcf02013-08-12 21:56:42 +00003407static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003408 StringRef BaseName,
3409 types::ID FileType) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00003410 SmallString<128> Filename = ArgValue;
Justin Bogner5aaf2e72014-06-26 20:59:36 +00003411
Hans Wennborgf1a74252013-09-10 20:18:04 +00003412 if (ArgValue.empty()) {
3413 // If the argument is empty, output to BaseName in the current dir.
3414 Filename = BaseName;
3415 } else if (llvm::sys::path::is_separator(Filename.back())) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00003416 // If the argument is a directory, output to BaseName in that dir.
3417 llvm::sys::path::append(Filename, BaseName);
3418 }
3419
3420 if (!llvm::sys::path::has_extension(ArgValue)) {
3421 // If the argument didn't provide an extension, then set it.
3422 const char *Extension = types::getTypeTempSuffix(FileType, true);
Hans Wennborgf1a74252013-09-10 20:18:04 +00003423
3424 if (FileType == types::TY_Image &&
3425 Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
3426 // The output file is a dll.
3427 Extension = "dll";
3428 }
3429
Hans Wennborg207fcf02013-08-12 21:56:42 +00003430 llvm::sys::path::replace_extension(Filename, Extension);
3431 }
3432
3433 return Args.MakeArgString(Filename.c_str());
3434}
3435
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003436const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003437 const char *BaseInput,
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003438 StringRef BoundArch, bool AtTopLevel,
Samuel Antaod06239d2016-07-15 23:13:27 +00003439 bool MultipleArchs,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003440 StringRef OffloadingPrefix) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00003441 llvm::PrettyStackTraceString CrashInfo("Computing output path");
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003442 // Output to a user requested destination?
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003443 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003444 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
Chad Rosier633dcdc2013-01-24 19:14:47 +00003445 return C.addResultFile(FinalOutput->getValue(), &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003446 }
3447
Hans Wennborge0053472013-12-20 18:40:46 +00003448 // For /P, preprocess to file named after BaseInput.
3449 if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
3450 assert(AtTopLevel && isa<PreprocessJobAction>(JA));
3451 StringRef BaseName = llvm::sys::path::filename(BaseInput);
Hans Wennborg04c764f2014-06-17 00:19:12 +00003452 StringRef NameArg;
Greg Bedwell065f70a2015-06-09 10:24:06 +00003453 if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
Hans Wennborg04c764f2014-06-17 00:19:12 +00003454 NameArg = A->getValue();
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003455 return C.addResultFile(
3456 MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
3457 &JA);
Hans Wennborge0053472013-12-20 18:40:46 +00003458 }
3459
Nick Lewycky6e1ce292010-09-24 00:46:53 +00003460 // Default to writing to stdout?
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00003461 if (AtTopLevel && !CCGenDiagnostics &&
3462 (isa<PreprocessJobAction>(JA) || JA.getType() == types::TY_ModuleFile))
Nick Lewycky6e1ce292010-09-24 00:46:53 +00003463 return "-";
3464
Hans Wennborg2c21f742013-10-17 16:16:23 +00003465 // Is this the assembly listing for /FA?
3466 if (JA.getType() == types::TY_PP_Asm &&
3467 (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
3468 C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
3469 // Use /Fa and the input filename to determine the asm file name.
3470 StringRef BaseName = llvm::sys::path::filename(BaseInput);
3471 StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003472 return C.addResultFile(
3473 MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
3474 &JA);
Hans Wennborg2c21f742013-10-17 16:16:23 +00003475 }
3476
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003477 // Output to a temporary file?
Reid Kleckner68eb60b2015-02-02 22:41:48 +00003478 if ((!AtTopLevel && !isSaveTempsEnabled() &&
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003479 !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
Chad Rosierbe10f982011-08-02 17:58:04 +00003480 CCGenDiagnostics) {
Chad Rosier97c37372011-08-26 22:27:02 +00003481 StringRef Name = llvm::sys::path::filename(BaseInput);
3482 std::pair<StringRef, StringRef> Split = Name.split('.');
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003483 std::string TmpName = GetTemporaryPath(
3484 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00003485 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003486 }
3487
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003488 SmallString<128> BasePath(BaseInput);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003489 StringRef BaseName;
Daniel Dunbar67fea712011-03-25 18:16:51 +00003490
3491 // Dsymutil actions should use the full path.
Eric Christopher551ef452011-08-23 17:56:55 +00003492 if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
Daniel Dunbar67fea712011-03-25 18:16:51 +00003493 BaseName = BasePath;
3494 else
3495 BaseName = llvm::sys::path::filename(BasePath);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003496
3497 // Determine what the derived output name should be.
3498 const char *NamedOutput;
Hans Wennborg2b89a262013-08-06 22:11:28 +00003499
Hans Wennborg625fba82016-10-04 21:01:04 +00003500 if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) &&
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00003501 C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
3502 // The /Fo or /o flag decides the object filename.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003503 StringRef Val =
3504 C.getArgs()
3505 .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
3506 ->getValue();
3507 NamedOutput =
3508 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
Hans Wennborg207fcf02013-08-12 21:56:42 +00003509 } else if (JA.getType() == types::TY_Image &&
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003510 C.getArgs().hasArg(options::OPT__SLASH_Fe,
3511 options::OPT__SLASH_o)) {
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00003512 // The /Fe or /o flag names the linked file.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003513 StringRef Val =
3514 C.getArgs()
3515 .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
3516 ->getValue();
3517 NamedOutput =
3518 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
Hans Wennborgf1a74252013-09-10 20:18:04 +00003519 } else if (JA.getType() == types::TY_Image) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00003520 if (IsCLMode()) {
3521 // clang-cl uses BaseName for the executable name.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003522 NamedOutput =
3523 MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
Samuel Antao59efaed2016-10-27 17:31:22 +00003524 } else {
Hans Wennborga7707222015-01-09 17:38:53 +00003525 SmallString<128> Output(getDefaultImageName());
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003526 Output += OffloadingPrefix;
Samuel Antao59efaed2016-10-27 17:31:22 +00003527 if (MultipleArchs && !BoundArch.empty()) {
3528 Output += "-";
3529 Output.append(BoundArch);
3530 }
Chad Rosier35767232013-04-30 22:01:21 +00003531 NamedOutput = C.getArgs().MakeArgString(Output.c_str());
Nico Weber2ca4be92016-03-01 23:16:44 +00003532 }
3533 } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00003534 NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName));
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003535 } else {
Hans Wennborg0a096a02013-09-05 17:05:56 +00003536 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003537 assert(Suffix && "All types used for output should have a suffix.");
3538
3539 std::string::size_type End = std::string::npos;
3540 if (!types::appendSuffixForType(JA.getType()))
3541 End = BaseName.rfind('.');
Chad Rosier35767232013-04-30 22:01:21 +00003542 SmallString<128> Suffixed(BaseName.substr(0, End));
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003543 Suffixed += OffloadingPrefix;
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003544 if (MultipleArchs && !BoundArch.empty()) {
Chad Rosier35767232013-04-30 22:01:21 +00003545 Suffixed += "-";
3546 Suffixed.append(BoundArch);
3547 }
Bob Wilson23a55f12014-12-21 07:00:00 +00003548 // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
3549 // the unoptimized bitcode so that it does not get overwritten by the ".bc"
3550 // optimized bitcode output.
3551 if (!AtTopLevel && C.getArgs().hasArg(options::OPT_emit_llvm) &&
3552 JA.getType() == types::TY_LLVM_BC)
3553 Suffixed += ".tmp";
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003554 Suffixed += '.';
3555 Suffixed += Suffix;
3556 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
3557 }
3558
Reid Kleckner68eb60b2015-02-02 22:41:48 +00003559 // Prepend object file path if -save-temps=obj
3560 if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
3561 JA.getType() != types::TY_PCH) {
3562 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
3563 SmallString<128> TempPath(FinalOutput->getValue());
3564 llvm::sys::path::remove_filename(TempPath);
3565 StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
3566 llvm::sys::path::append(TempPath, OutputFileName);
3567 NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
3568 }
3569
Chad Rosier62135492012-07-09 17:31:28 +00003570 // If we're saving temps and the temp file conflicts with the input file,
Chad Rosier5b58af02012-04-20 20:05:08 +00003571 // then avoid overwriting input file.
Reid Kleckner68eb60b2015-02-02 22:41:48 +00003572 if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
Chad Rosier5b58af02012-04-20 20:05:08 +00003573 bool SameFile = false;
3574 SmallString<256> Result;
3575 llvm::sys::fs::current_path(Result);
3576 llvm::sys::path::append(Result, BaseName);
3577 llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
3578 // Must share the same path to conflict.
3579 if (SameFile) {
3580 StringRef Name = llvm::sys::path::filename(BaseInput);
3581 std::pair<StringRef, StringRef> Split = Name.split('.');
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003582 std::string TmpName = GetTemporaryPath(
3583 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00003584 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
Chad Rosier5b58af02012-04-20 20:05:08 +00003585 }
Chad Rosierf8412cd2011-07-15 21:54:29 +00003586 }
3587
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003588 // As an annoying special case, PCH generation doesn't strip the pathname.
Nico Weber8ab92192016-03-02 23:29:29 +00003589 if (JA.getType() == types::TY_PCH && !IsCLMode()) {
Michael J. Spencere1696752010-12-18 00:19:12 +00003590 llvm::sys::path::remove_filename(BasePath);
3591 if (BasePath.empty())
Daniel Dunbare6c83192009-03-18 09:58:30 +00003592 BasePath = NamedOutput;
3593 else
Michael J. Spencere1696752010-12-18 00:19:12 +00003594 llvm::sys::path::append(BasePath, NamedOutput);
Chad Rosier633dcdc2013-01-24 19:14:47 +00003595 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003596 } else {
Chad Rosier633dcdc2013-01-24 19:14:47 +00003597 return C.addResultFile(NamedOutput, &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003598 }
3599}
3600
Mehdi Amini12011172016-10-06 05:11:48 +00003601std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const {
Chandler Carruth84559242010-03-22 01:52:07 +00003602 // Respect a limited subset of the '-Bprefix' functionality in GCC by
Logan Chiencd679fd2012-10-04 08:08:56 +00003603 // attempting to use this prefix when looking for file paths.
Douglas Katzman26eabf62015-06-24 15:10:30 +00003604 for (const std::string &Dir : PrefixDirs) {
Joerg Sonnenberger6165ab12011-03-21 13:51:29 +00003605 if (Dir.empty())
3606 continue;
Douglas Katzman26eabf62015-06-24 15:10:30 +00003607 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
Rafael Espindola609a6642013-06-24 18:33:43 +00003608 llvm::sys::path::append(P, Name);
3609 if (llvm::sys::fs::exists(Twine(P)))
Chandler Carruth84559242010-03-22 01:52:07 +00003610 return P.str();
3611 }
3612
Rafael Espindola609a6642013-06-24 18:33:43 +00003613 SmallString<128> P(ResourceDir);
3614 llvm::sys::path::append(P, Name);
3615 if (llvm::sys::fs::exists(Twine(P)))
Peter Collingbournefa9771f2011-09-06 02:08:31 +00003616 return P.str();
3617
Douglas Katzman26eabf62015-06-24 15:10:30 +00003618 for (const std::string &Dir : TC.getFilePaths()) {
Joerg Sonnenberger6165ab12011-03-21 13:51:29 +00003619 if (Dir.empty())
3620 continue;
Douglas Katzman26eabf62015-06-24 15:10:30 +00003621 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
Rafael Espindola609a6642013-06-24 18:33:43 +00003622 llvm::sys::path::append(P, Name);
3623 if (llvm::sys::fs::exists(Twine(P)))
Daniel Dunbar1ce81532009-09-09 22:33:00 +00003624 return P.str();
Daniel Dunbar68b01a02009-03-18 20:26:19 +00003625 }
3626
Daniel Dunbar1ce81532009-09-09 22:33:00 +00003627 return Name;
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00003628}
3629
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003630void Driver::generatePrefixedToolNames(
Mehdi Amini12011172016-10-06 05:11:48 +00003631 StringRef Tool, const ToolChain &TC,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003632 SmallVectorImpl<std::string> &Names) const {
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00003633 // FIXME: Needs a better variable than DefaultTargetTriple
Mehdi Amini12011172016-10-06 05:11:48 +00003634 Names.emplace_back((DefaultTargetTriple + "-" + Tool).str());
Benjamin Kramer3204b152015-05-29 19:42:19 +00003635 Names.emplace_back(Tool);
Vasileios Kalintirisc744e122015-11-12 15:26:54 +00003636
3637 // Allow the discovery of tools prefixed with LLVM's default target triple.
3638 std::string LLVMDefaultTargetTriple = llvm::sys::getDefaultTargetTriple();
3639 if (LLVMDefaultTargetTriple != DefaultTargetTriple)
Mehdi Amini12011172016-10-06 05:11:48 +00003640 Names.emplace_back((LLVMDefaultTargetTriple + "-" + Tool).str());
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00003641}
3642
Benjamin Kramer7111b912014-11-04 20:26:01 +00003643static bool ScanDirForExecutable(SmallString<128> &Dir,
3644 ArrayRef<std::string> Names) {
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00003645 for (const auto &Name : Names) {
3646 llvm::sys::path::append(Dir, Name);
3647 if (llvm::sys::fs::can_execute(Twine(Dir)))
3648 return true;
3649 llvm::sys::path::remove_filename(Dir);
3650 }
3651 return false;
3652}
3653
Mehdi Amini12011172016-10-06 05:11:48 +00003654std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const {
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00003655 SmallVector<std::string, 2> TargetSpecificExecutables;
3656 generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
3657
Chandler Carruth84559242010-03-22 01:52:07 +00003658 // Respect a limited subset of the '-Bprefix' functionality in GCC by
Logan Chiencd679fd2012-10-04 08:08:56 +00003659 // attempting to use this prefix when looking for program paths.
Saleem Abdulrasool23d99b12014-09-16 03:48:32 +00003660 for (const auto &PrefixDir : PrefixDirs) {
3661 if (llvm::sys::fs::is_directory(PrefixDir)) {
3662 SmallString<128> P(PrefixDir);
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00003663 if (ScanDirForExecutable(P, TargetSpecificExecutables))
Rafael Espindola8be5c052013-06-19 13:24:29 +00003664 return P.str();
Simon Atanasyana47ba292012-10-31 14:39:28 +00003665 } else {
Mehdi Amini12011172016-10-06 05:11:48 +00003666 SmallString<128> P((PrefixDir + Name).str());
Rafael Espindola609a6642013-06-24 18:33:43 +00003667 if (llvm::sys::fs::can_execute(Twine(P)))
Rafael Espindola8be5c052013-06-19 13:24:29 +00003668 return P.str();
Simon Atanasyan86bdab72012-10-31 12:01:53 +00003669 }
Chandler Carruth84559242010-03-22 01:52:07 +00003670 }
3671
Daniel Dunbar68b01a02009-03-18 20:26:19 +00003672 const ToolChain::path_list &List = TC.getProgramPaths();
Saleem Abdulrasool23d99b12014-09-16 03:48:32 +00003673 for (const auto &Path : List) {
3674 SmallString<128> P(Path);
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00003675 if (ScanDirForExecutable(P, TargetSpecificExecutables))
Rafael Espindola8be5c052013-06-19 13:24:29 +00003676 return P.str();
Daniel Dunbar68b01a02009-03-18 20:26:19 +00003677 }
3678
Daniel Dunbar76ce7412009-03-23 16:15:50 +00003679 // If all else failed, search the path.
Michael J. Spencerb011d482014-11-07 21:30:32 +00003680 for (const auto &TargetSpecificExecutable : TargetSpecificExecutables)
3681 if (llvm::ErrorOr<std::string> P =
3682 llvm::sys::findProgramByName(TargetSpecificExecutable))
Michael J. Spencer04162ea2014-11-04 01:30:55 +00003683 return *P;
Daniel Dunbar6f668772009-03-18 21:34:08 +00003684
Daniel Dunbar1ce81532009-09-09 22:33:00 +00003685 return Name;
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00003686}
3687
Mehdi Amini12011172016-10-06 05:11:48 +00003688std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const {
Rafael Espindola37d229d2013-06-25 04:26:55 +00003689 SmallString<128> Path;
Rafael Espindolac0809172014-06-12 14:02:15 +00003690 std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
Rafael Espindola37d229d2013-06-25 04:26:55 +00003691 if (EC) {
3692 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
Daniel Dunbare627c1c2009-03-18 19:34:39 +00003693 return "";
3694 }
3695
Rafael Espindola37d229d2013-06-25 04:26:55 +00003696 return Path.str();
Daniel Dunbare627c1c2009-03-18 19:34:39 +00003697}
3698
Nico Weber2ca4be92016-03-01 23:16:44 +00003699std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
3700 SmallString<128> Output;
3701 if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
3702 // FIXME: If anybody needs it, implement this obscure rule:
3703 // "If you specify a directory without a file name, the default file name
3704 // is VCx0.pch., where x is the major version of Visual C++ in use."
3705 Output = FpArg->getValue();
3706
3707 // "If you do not specify an extension as part of the path name, an
3708 // extension of .pch is assumed. "
3709 if (!llvm::sys::path::has_extension(Output))
3710 Output += ".pch";
3711 } else {
3712 Output = BaseName;
3713 llvm::sys::path::replace_extension(Output, ".pch");
3714 }
3715 return Output.str();
3716}
3717
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003718const ToolChain &Driver::getToolChain(const ArgList &Args,
Artem Belevich959e0542015-07-10 19:47:55 +00003719 const llvm::Triple &Target) const {
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003720
David Blaikie6ad71012017-01-13 18:53:43 +00003721 auto &TC = ToolChains[Target.str()];
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003722 if (!TC) {
3723 switch (Target.getOS()) {
Reid Kleckner330fb172016-05-11 16:19:05 +00003724 case llvm::Triple::Haiku:
David Blaikie6ad71012017-01-13 18:53:43 +00003725 TC = llvm::make_unique<toolchains::Haiku>(*this, Target, Args);
Reid Kleckner330fb172016-05-11 16:19:05 +00003726 break;
Ed Schouten3c3e58c2015-03-26 11:13:44 +00003727 case llvm::Triple::CloudABI:
David Blaikie6ad71012017-01-13 18:53:43 +00003728 TC = llvm::make_unique<toolchains::CloudABI>(*this, Target, Args);
Ed Schouten3c3e58c2015-03-26 11:13:44 +00003729 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003730 case llvm::Triple::Darwin:
3731 case llvm::Triple::MacOSX:
3732 case llvm::Triple::IOS:
Tim Northover6f3ff222015-10-30 16:30:27 +00003733 case llvm::Triple::TvOS:
3734 case llvm::Triple::WatchOS:
David Blaikie6ad71012017-01-13 18:53:43 +00003735 TC = llvm::make_unique<toolchains::DarwinClang>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003736 break;
3737 case llvm::Triple::DragonFly:
David Blaikie6ad71012017-01-13 18:53:43 +00003738 TC = llvm::make_unique<toolchains::DragonFly>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003739 break;
3740 case llvm::Triple::OpenBSD:
David Blaikie6ad71012017-01-13 18:53:43 +00003741 TC = llvm::make_unique<toolchains::OpenBSD>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003742 break;
Eli Friedman9fa28852012-08-08 23:57:20 +00003743 case llvm::Triple::Bitrig:
David Blaikie6ad71012017-01-13 18:53:43 +00003744 TC = llvm::make_unique<toolchains::Bitrig>(*this, Target, Args);
Eli Friedman9fa28852012-08-08 23:57:20 +00003745 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003746 case llvm::Triple::NetBSD:
David Blaikie6ad71012017-01-13 18:53:43 +00003747 TC = llvm::make_unique<toolchains::NetBSD>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003748 break;
3749 case llvm::Triple::FreeBSD:
David Blaikie6ad71012017-01-13 18:53:43 +00003750 TC = llvm::make_unique<toolchains::FreeBSD>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003751 break;
3752 case llvm::Triple::Minix:
David Blaikie6ad71012017-01-13 18:53:43 +00003753 TC = llvm::make_unique<toolchains::Minix>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003754 break;
3755 case llvm::Triple::Linux:
Andrey Turetskiy4798eb62016-06-16 10:36:09 +00003756 case llvm::Triple::ELFIAMCU:
Chandler Carruthcf705b22012-01-25 21:03:58 +00003757 if (Target.getArch() == llvm::Triple::hexagon)
David Blaikie6ad71012017-01-13 18:53:43 +00003758 TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
3759 Args);
Vasileios Kalintirisc744e122015-11-12 15:26:54 +00003760 else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
3761 !Target.hasEnvironment())
David Blaikie6ad71012017-01-13 18:53:43 +00003762 TC = llvm::make_unique<toolchains::MipsLLVMToolChain>(*this, Target,
3763 Args);
Chandler Carruthcf705b22012-01-25 21:03:58 +00003764 else
David Blaikie6ad71012017-01-13 18:53:43 +00003765 TC = llvm::make_unique<toolchains::Linux>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003766 break;
Derek Schuff6ab52fa2015-03-30 20:31:33 +00003767 case llvm::Triple::NaCl:
David Blaikie6ad71012017-01-13 18:53:43 +00003768 TC = llvm::make_unique<toolchains::NaClToolChain>(*this, Target, Args);
Derek Schuff6ab52fa2015-03-30 20:31:33 +00003769 break;
Petr Hosek62e1d232016-10-06 06:08:09 +00003770 case llvm::Triple::Fuchsia:
David Blaikie6ad71012017-01-13 18:53:43 +00003771 TC = llvm::make_unique<toolchains::Fuchsia>(*this, Target, Args);
Petr Hosek62e1d232016-10-06 06:08:09 +00003772 break;
David Chisnallf571cde2012-02-15 13:39:01 +00003773 case llvm::Triple::Solaris:
David Blaikie6ad71012017-01-13 18:53:43 +00003774 TC = llvm::make_unique<toolchains::Solaris>(*this, Target, Args);
David Chisnallf571cde2012-02-15 13:39:01 +00003775 break;
Tom Stellard8fa33092015-07-18 01:49:05 +00003776 case llvm::Triple::AMDHSA:
David Blaikie6ad71012017-01-13 18:53:43 +00003777 TC = llvm::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args);
Tom Stellard8fa33092015-07-18 01:49:05 +00003778 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003779 case llvm::Triple::Win32:
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00003780 switch (Target.getEnvironment()) {
3781 default:
3782 if (Target.isOSBinFormatELF())
David Blaikie6ad71012017-01-13 18:53:43 +00003783 TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00003784 else if (Target.isOSBinFormatMachO())
David Blaikie6ad71012017-01-13 18:53:43 +00003785 TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00003786 else
David Blaikie6ad71012017-01-13 18:53:43 +00003787 TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00003788 break;
3789 case llvm::Triple::GNU:
David Blaikie6ad71012017-01-13 18:53:43 +00003790 TC = llvm::make_unique<toolchains::MinGW>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00003791 break;
Saleem Abdulrasool543a78b2014-10-24 03:13:37 +00003792 case llvm::Triple::Itanium:
David Blaikie6ad71012017-01-13 18:53:43 +00003793 TC = llvm::make_unique<toolchains::CrossWindowsToolChain>(*this, Target,
3794 Args);
Saleem Abdulrasool543a78b2014-10-24 03:13:37 +00003795 break;
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00003796 case llvm::Triple::MSVC:
3797 case llvm::Triple::UnknownEnvironment:
David Blaikie6ad71012017-01-13 18:53:43 +00003798 TC = llvm::make_unique<toolchains::MSVCToolChain>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00003799 break;
3800 }
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003801 break;
Filipe Cabecinhasc888e192015-10-14 12:25:43 +00003802 case llvm::Triple::PS4:
David Blaikie6ad71012017-01-13 18:53:43 +00003803 TC = llvm::make_unique<toolchains::PS4CPU>(*this, Target, Args);
Filipe Cabecinhasc888e192015-10-14 12:25:43 +00003804 break;
David L Kreitzerd397ea42016-10-14 20:44:33 +00003805 case llvm::Triple::Contiki:
David Blaikie6ad71012017-01-13 18:53:43 +00003806 TC = llvm::make_unique<toolchains::Contiki>(*this, Target, Args);
David L Kreitzerd397ea42016-10-14 20:44:33 +00003807 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003808 default:
Douglas Katzman9f5e70e2015-05-26 18:01:33 +00003809 // Of these targets, Hexagon is the only one that might have
3810 // an OS of Linux, in which case it got handled above already.
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003811 switch (Target.getArch()) {
3812 case llvm::Triple::tce:
David Blaikie6ad71012017-01-13 18:53:43 +00003813 TC = llvm::make_unique<toolchains::TCEToolChain>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003814 break;
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00003815 case llvm::Triple::tcele:
David Blaikie6ad71012017-01-13 18:53:43 +00003816 TC = llvm::make_unique<toolchains::TCELEToolChain>(*this, Target, Args);
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00003817 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003818 case llvm::Triple::hexagon:
David Blaikie6ad71012017-01-13 18:53:43 +00003819 TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
3820 Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003821 break;
Jacques Pienaard964cc22016-03-28 21:02:54 +00003822 case llvm::Triple::lanai:
David Blaikie6ad71012017-01-13 18:53:43 +00003823 TC = llvm::make_unique<toolchains::LanaiToolChain>(*this, Target, Args);
Jacques Pienaard964cc22016-03-28 21:02:54 +00003824 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003825 case llvm::Triple::xcore:
David Blaikie6ad71012017-01-13 18:53:43 +00003826 TC = llvm::make_unique<toolchains::XCoreToolChain>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003827 break;
Dan Gohmanc2853072015-09-03 22:51:53 +00003828 case llvm::Triple::wasm32:
3829 case llvm::Triple::wasm64:
David Blaikie6ad71012017-01-13 18:53:43 +00003830 TC = llvm::make_unique<toolchains::WebAssembly>(*this, Target, Args);
Dan Gohmanc2853072015-09-03 22:51:53 +00003831 break;
Dylan McKay924fa3a2017-01-05 05:20:27 +00003832 case llvm::Triple::avr:
David Blaikie6ad71012017-01-13 18:53:43 +00003833 TC = llvm::make_unique<toolchains::AVRToolChain>(*this, Target, Args);
Dylan McKay924fa3a2017-01-05 05:20:27 +00003834 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003835 default:
Douglas Katzmand6e597c2015-09-17 19:56:40 +00003836 if (Target.getVendor() == llvm::Triple::Myriad)
David Blaikie6ad71012017-01-13 18:53:43 +00003837 TC = llvm::make_unique<toolchains::MyriadToolChain>(*this, Target,
3838 Args);
Jonathan Roelofs901c7762017-05-25 15:42:13 +00003839 else if (toolchains::BareMetal::handlesTarget(Target))
3840 TC = llvm::make_unique<toolchains::BareMetal>(*this, Target, Args);
Douglas Katzmand6e597c2015-09-17 19:56:40 +00003841 else if (Target.isOSBinFormatELF())
David Blaikie6ad71012017-01-13 18:53:43 +00003842 TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003843 else if (Target.isOSBinFormatMachO())
David Blaikie6ad71012017-01-13 18:53:43 +00003844 TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003845 else
David Blaikie6ad71012017-01-13 18:53:43 +00003846 TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003847 }
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003848 }
3849 }
Justin Lebar66c4fd72016-11-18 00:41:22 +00003850
3851 // Intentionally omitted from the switch above: llvm::Triple::CUDA. CUDA
3852 // compiles always need two toolchains, the CUDA toolchain and the host
3853 // toolchain. So the only valid way to create a CUDA toolchain is via
3854 // CreateOffloadingDeviceToolChains.
3855
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003856 return *TC;
Daniel Dunbar4dff6a42009-03-10 23:41:59 +00003857}
Daniel Dunbar8fa879d2009-03-24 18:57:02 +00003858
Rafael Espindola2f69d402013-03-18 15:33:26 +00003859bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
Douglas Katzman00249092015-06-12 15:45:21 +00003860 // Say "no" if there is not exactly one input of a type clang understands.
Nico Weber5a459f82016-02-23 19:30:43 +00003861 if (JA.size() != 1 ||
3862 !types::isAcceptedByClang((*JA.input_begin())->getType()))
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00003863 return false;
3864
Douglas Katzman00249092015-06-12 15:45:21 +00003865 // And say "no" if this is not a kind of action clang understands.
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00003866 if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
Bob Wilson23a55f12014-12-21 07:00:00 +00003867 !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00003868 return false;
3869
3870 return true;
3871}
3872
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003873/// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
3874/// grouped values as integers. Numbers which are not provided are set to 0.
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003875///
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003876/// \return True if the entire string was parsed (9.2), or all groups were
3877/// parsed (10.3.5extrastuff).
Mehdi Amini12011172016-10-06 05:11:48 +00003878bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
3879 unsigned &Micro, bool &HadExtra) {
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003880 HadExtra = false;
3881
3882 Major = Minor = Micro = 0;
Mehdi Amini12011172016-10-06 05:11:48 +00003883 if (Str.empty())
Bob Wilson433cb312015-04-07 01:03:35 +00003884 return false;
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003885
Mehdi Amini12011172016-10-06 05:11:48 +00003886 if (Str.consumeInteger(10, Major))
3887 return false;
3888 if (Str.empty())
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003889 return true;
Mehdi Amini12011172016-10-06 05:11:48 +00003890 if (Str[0] != '.')
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003891 return false;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003892
Mehdi Amini12011172016-10-06 05:11:48 +00003893 Str = Str.drop_front(1);
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003894
Mehdi Amini12011172016-10-06 05:11:48 +00003895 if (Str.consumeInteger(10, Minor))
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003896 return false;
Mehdi Amini12011172016-10-06 05:11:48 +00003897 if (Str.empty())
3898 return true;
3899 if (Str[0] != '.')
3900 return false;
3901 Str = Str.drop_front(1);
3902
3903 if (Str.consumeInteger(10, Micro))
3904 return false;
3905 if (!Str.empty())
3906 HadExtra = true;
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003907 return true;
3908}
Hans Wennborg6ddc6902013-07-27 00:23:45 +00003909
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00003910/// Parse digits from a string \p Str and fulfill \p Digits with
3911/// the parsed numbers. This method assumes that the max number of
3912/// digits to look for is equal to Digits.size().
3913///
3914/// \return True if the entire string was parsed and there are
3915/// no extra characters remaining at the end.
Mehdi Amini12011172016-10-06 05:11:48 +00003916bool Driver::GetReleaseVersion(StringRef Str,
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00003917 MutableArrayRef<unsigned> Digits) {
Mehdi Amini12011172016-10-06 05:11:48 +00003918 if (Str.empty())
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00003919 return false;
3920
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00003921 unsigned CurDigit = 0;
3922 while (CurDigit < Digits.size()) {
Mehdi Amini12011172016-10-06 05:11:48 +00003923 unsigned Digit;
3924 if (Str.consumeInteger(10, Digit))
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00003925 return false;
Mehdi Amini12011172016-10-06 05:11:48 +00003926 Digits[CurDigit] = Digit;
3927 if (Str.empty())
3928 return true;
3929 if (Str[0] != '.')
3930 return false;
3931 Str = Str.drop_front(1);
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00003932 CurDigit++;
3933 }
3934
3935 // More digits than requested, bail out...
3936 return false;
3937}
3938
Hans Wennborg6ddc6902013-07-27 00:23:45 +00003939std::pair<unsigned, unsigned> Driver::getIncludeExcludeOptionFlagMasks() const {
3940 unsigned IncludedFlagsBitmask = 0;
Rafael Espindolacc707bc2013-09-25 15:54:41 +00003941 unsigned ExcludedFlagsBitmask = options::NoDriverOption;
Hans Wennborg6ddc6902013-07-27 00:23:45 +00003942
3943 if (Mode == CLMode) {
Hans Wennborg19076102013-07-31 20:51:53 +00003944 // Include CL and Core options.
3945 IncludedFlagsBitmask |= options::CLOption;
3946 IncludedFlagsBitmask |= options::CoreOption;
Hans Wennborg6ddc6902013-07-27 00:23:45 +00003947 } else {
3948 ExcludedFlagsBitmask |= options::CLOption;
3949 }
3950
3951 return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
3952}
Benjamin Kramerab88f622014-03-25 18:02:07 +00003953
Douglas Katzmanf08fadf2015-06-04 14:40:44 +00003954bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
Benjamin Kramerab88f622014-03-25 18:02:07 +00003955 return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);
3956}