blob: 15f830d029ebf5080481c093c5d7b983c5ff37ec [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"
12#include "ToolChains.h"
13#include "clang/Basic/Version.h"
Benjamin Kramerd45b2052015-10-07 15:48:01 +000014#include "clang/Basic/VirtualFileSystem.h"
Alp Toker1d257e12014-06-04 03:28:55 +000015#include "clang/Config/config.h"
Daniel Dunbar1688f1a2009-03-12 07:58:46 +000016#include "clang/Driver/Action.h"
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000017#include "clang/Driver/Compilation.h"
Daniel Dunbarc0b3e952009-03-12 08:55:43 +000018#include "clang/Driver/DriverDiagnostic.h"
Daniel Dunbare75d8342009-03-16 06:56:51 +000019#include "clang/Driver/Job.h"
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000020#include "clang/Driver/Options.h"
Peter Collingbournea4ccff32015-02-20 20:30:56 +000021#include "clang/Driver/SanitizerArgs.h"
Daniel Dunbare75d8342009-03-16 06:56:51 +000022#include "clang/Driver/Tool.h"
23#include "clang/Driver/ToolChain.h"
Chris Lattnerce6c42f2011-03-23 04:04:01 +000024#include "llvm/ADT/ArrayRef.h"
Hans Wennborg6ddc6902013-07-27 00:23:45 +000025#include "llvm/ADT/STLExtras.h"
Justin Lebar62907612016-07-06 21:21:39 +000026#include "llvm/ADT/SmallSet.h"
Hans Wennborg23d26a32014-06-18 17:21:50 +000027#include "llvm/ADT/StringExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000028#include "llvm/ADT/StringSet.h"
Hans Wennborg70850d82013-07-18 20:29:38 +000029#include "llvm/ADT/StringSwitch.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000030#include "llvm/Option/Arg.h"
31#include "llvm/Option/ArgList.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000032#include "llvm/Option/OptSpecifier.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000033#include "llvm/Option/OptTable.h"
34#include "llvm/Option/Option.h"
David Blaikie79000202011-09-23 05:57:42 +000035#include "llvm/Support/ErrorHandling.h"
Michael J. Spencerf28df4c2010-12-17 21:22:22 +000036#include "llvm/Support/FileSystem.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000037#include "llvm/Support/Path.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000038#include "llvm/Support/PrettyStackTrace.h"
Hans Wennborg23d26a32014-06-18 17:21:50 +000039#include "llvm/Support/Process.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000040#include "llvm/Support/Program.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000041#include "llvm/Support/raw_ostream.h"
Dylan Noblesmith4f4e7452012-02-02 00:40:14 +000042#include <map>
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000043#include <memory>
Benjamin Kramercfeacf52016-05-27 14:27:13 +000044#include <utility>
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +000045#if LLVM_ON_UNIX
46#include <unistd.h> // getpid
47#endif
Dylan Noblesmith86780e92012-02-01 14:25:28 +000048
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000049using namespace clang::driver;
Chris Lattnerada1c912009-03-26 05:56:24 +000050using namespace clang;
Reid Kleckner898229a2013-06-14 17:17:23 +000051using namespace llvm::opt;
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000052
Reid Kleckner68eb60b2015-02-02 22:41:48 +000053Driver::Driver(StringRef ClangExecutable, StringRef DefaultTargetTriple,
Benjamin Kramerd45b2052015-10-07 15:48:01 +000054 DiagnosticsEngine &Diags,
55 IntrusiveRefCntPtr<vfs::FileSystem> VFS)
Benjamin Kramercfeacf52016-05-27 14:27:13 +000056 : Opts(createDriverOptTable()), Diags(Diags), VFS(std::move(VFS)),
57 Mode(GCCMode), SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
58 LTOMode(LTOK_None), ClangExecutable(ClangExecutable),
Reid Kleckner68eb60b2015-02-02 22:41:48 +000059 SysRoot(DEFAULT_SYSROOT), UseStdLib(true),
Reid Kleckner68eb60b2015-02-02 22:41:48 +000060 DriverTitle("clang LLVM compiler"), CCPrintOptionsFilename(nullptr),
61 CCPrintHeadersFilename(nullptr), CCLogDiagnosticsFilename(nullptr),
62 CCCPrintBindings(false), CCPrintHeaders(false), CCLogDiagnostics(false),
Vedant Kumarf2030b92016-07-18 19:56:33 +000063 CCGenDiagnostics(false), DefaultTargetTriple(DefaultTargetTriple),
64 CCCGenericGCCName(""), CheckInputsExist(true), CCCUsePCH(true),
65 SuppressMissingInputWarning(false) {
Daniel Dunbar3f3e2cd2010-01-20 02:35:16 +000066
Benjamin Kramerd45b2052015-10-07 15:48:01 +000067 // Provide a sane fallback if no VFS is specified.
68 if (!this->VFS)
69 this->VFS = vfs::getRealFileSystem();
70
Sumanth Gundapaneni3a1592942015-03-03 20:43:12 +000071 Name = llvm::sys::path::filename(ClangExecutable);
Douglas Katzmana67e50c2015-06-26 15:47:46 +000072 Dir = llvm::sys::path::parent_path(ClangExecutable);
Benjamin Kramerf420dda2015-10-13 15:19:32 +000073 InstalledDir = Dir; // Provide a sensible default installed dir.
Bob Wilsona20a1da2013-03-23 05:17:59 +000074
75 // Compute the path to the resource directory.
76 StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
77 SmallString<128> P(Dir);
Chandler Carruthfd3cc702014-12-29 12:09:08 +000078 if (ClangResourceDir != "") {
Bob Wilsona20a1da2013-03-23 05:17:59 +000079 llvm::sys::path::append(P, ClangResourceDir);
Chandler Carruthfd3cc702014-12-29 12:09:08 +000080 } else {
81 StringRef ClangLibdirSuffix(CLANG_LIBDIR_SUFFIX);
82 llvm::sys::path::append(P, "..", Twine("lib") + ClangLibdirSuffix, "clang",
83 CLANG_VERSION_STRING);
84 }
Bob Wilsona20a1da2013-03-23 05:17:59 +000085 ResourceDir = P.str();
Daniel Dunbar544ecd12009-03-02 19:59:07 +000086}
87
88Driver::~Driver() {
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000089 delete Opts;
Chandler Carruth2ad5de12012-01-25 11:01:57 +000090
Reid Kleckner588c9372014-02-19 23:44:52 +000091 llvm::DeleteContainerSeconds(ToolChains);
Daniel Dunbar544ecd12009-03-02 19:59:07 +000092}
93
Zachary Turneraff19c32016-08-12 17:47:52 +000094void Driver::ParseDriverMode(StringRef ProgramName,
95 ArrayRef<const char *> Args) {
96 auto Default = ToolChain::getTargetAndModeFromProgramName(ProgramName);
97 StringRef DefaultMode(Default.second);
98 setDriverModeFromOption(DefaultMode);
Hans Wennborg70850d82013-07-18 20:29:38 +000099
Douglas Katzman6bbffc42015-06-25 18:51:37 +0000100 for (const char *ArgPtr : Args) {
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000101 // Ingore nullptrs, they are response file's EOL markers
Douglas Katzman6bbffc42015-06-25 18:51:37 +0000102 if (ArgPtr == nullptr)
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000103 continue;
Douglas Katzman6bbffc42015-06-25 18:51:37 +0000104 const StringRef Arg = ArgPtr;
Zachary Turneraff19c32016-08-12 17:47:52 +0000105 setDriverModeFromOption(Arg);
Hans Wennborg70850d82013-07-18 20:29:38 +0000106 }
107}
108
Zachary Turneraff19c32016-08-12 17:47:52 +0000109void Driver::setDriverModeFromOption(StringRef Opt) {
110 const std::string OptName =
111 getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
112 if (!Opt.startswith(OptName))
113 return;
114 StringRef Value = Opt.drop_front(OptName.size());
115
116 const unsigned M = llvm::StringSwitch<unsigned>(Value)
117 .Case("gcc", GCCMode)
118 .Case("g++", GXXMode)
119 .Case("cpp", CPPMode)
120 .Case("cl", CLMode)
121 .Default(~0U);
122
123 if (M != ~0U)
124 Mode = static_cast<DriverMode>(M);
125 else
126 Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
127}
128
David Blaikie69a1d8c2015-06-22 22:07:27 +0000129InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings) {
Daniel Dunbar2608c542009-03-18 01:38:48 +0000130 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
Hans Wennborg6ddc6902013-07-27 00:23:45 +0000131
132 unsigned IncludedFlagsBitmask;
133 unsigned ExcludedFlagsBitmask;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000134 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000135 getIncludeExcludeOptionFlagMasks();
Hans Wennborg6ddc6902013-07-27 00:23:45 +0000136
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000137 unsigned MissingArgIndex, MissingArgCount;
David Blaikie69a1d8c2015-06-22 22:07:27 +0000138 InputArgList Args =
David Blaikie6d492ad2015-06-21 06:32:36 +0000139 getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
140 IncludedFlagsBitmask, ExcludedFlagsBitmask);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +0000141
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000142 // Check for missing argument error.
143 if (MissingArgCount)
144 Diag(clang::diag::err_drv_missing_argument)
David Blaikie69a1d8c2015-06-22 22:07:27 +0000145 << Args.getArgString(MissingArgIndex) << MissingArgCount;
Daniel Dunbar65229332009-03-13 11:38:42 +0000146
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000147 // Check for unsupported options.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000148 for (const Arg *A : Args) {
Michael J. Spencer66e2b202012-10-19 22:37:06 +0000149 if (A->getOption().hasFlag(options::Unsupported)) {
David Blaikie69a1d8c2015-06-22 22:07:27 +0000150 Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(Args);
Daniel Dunbard8500f32009-03-22 23:26:43 +0000151 continue;
152 }
Chad Rosierce975d92012-02-22 17:55:22 +0000153
154 // Warn about -mcpu= without an argument.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000155 if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
David Blaikie69a1d8c2015-06-22 22:07:27 +0000156 Diag(clang::diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
Chad Rosierce975d92012-02-22 17:55:22 +0000157 }
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000158 }
159
David Blaikie69a1d8c2015-06-22 22:07:27 +0000160 for (const Arg *A : Args.filtered(options::OPT_UNKNOWN))
Ehsan Akhgarid8518332016-01-25 21:14:52 +0000161 Diags.Report(IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl :
162 diag::err_drv_unknown_argument)
163 << A->getAsString(Args);
Rafael Espindola8a2d4962013-09-23 23:55:25 +0000164
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000165 return Args;
166}
167
Chad Rosier7742b5d2011-07-27 23:36:45 +0000168// Determine which compilation mode we are in. We look for options which
169// affect the phase, starting with the earliest phases, and record which
170// option we used to determine the final phase.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000171phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
172 Arg **FinalPhaseArg) const {
Craig Topper92fc2df2014-05-17 16:56:41 +0000173 Arg *PhaseArg = nullptr;
Chad Rosier7742b5d2011-07-27 23:36:45 +0000174 phases::ID FinalPhase;
Eric Christopherf901e852011-08-17 22:59:59 +0000175
Hans Wennborge50cec32014-06-13 20:59:54 +0000176 // -{E,EP,P,M,MM} only run the preprocessor.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000177 if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
Hans Wennborge50cec32014-06-13 20:59:54 +0000178 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
Hans Wennborge0053472013-12-20 18:40:46 +0000179 (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
180 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000181 FinalPhase = phases::Preprocess;
Eric Christopherf901e852011-08-17 22:59:59 +0000182
Richard Smithdd4ad3d2016-08-30 19:06:26 +0000183 // --precompile only runs up to precompilation.
184 } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile))) {
185 FinalPhase = phases::Precompile;
186
Bob Wilson23a55f12014-12-21 07:00:00 +0000187 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
Chad Rosier7742b5d2011-07-27 23:36:45 +0000188 } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000189 (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
Ben Langmuir2cb4a782014-02-05 22:21:15 +0000190 (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
Chad Rosier7742b5d2011-07-27 23:36:45 +0000191 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
Fariborz Jahanian73223bb2012-04-02 15:59:19 +0000192 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
Ted Kremenekf7639e12012-03-06 20:06:33 +0000193 (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
Chad Rosier7742b5d2011-07-27 23:36:45 +0000194 (PhaseArg = DAL.getLastArg(options::OPT__analyze,
Chad Rosier1aeb15a2012-03-06 23:14:35 +0000195 options::OPT__analyze_auto)) ||
Bob Wilson23a55f12014-12-21 07:00:00 +0000196 (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000197 FinalPhase = phases::Compile;
198
Bob Wilson23a55f12014-12-21 07:00:00 +0000199 // -S only runs up to the backend.
200 } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
201 FinalPhase = phases::Backend;
202
Artem Belevich4242f412015-07-28 21:01:21 +0000203 // -c compilation only runs up to the assembler.
204 } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000205 FinalPhase = phases::Assemble;
206
207 // Otherwise do everything.
208 } else
209 FinalPhase = phases::Link;
210
211 if (FinalPhaseArg)
212 *FinalPhaseArg = PhaseArg;
213
214 return FinalPhase;
215}
216
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000217static Arg *MakeInputArg(DerivedArgList &Args, OptTable *Opts,
Hans Wennborged1d0722013-08-13 21:32:29 +0000218 StringRef Value) {
219 Arg *A = new Arg(Opts->getOption(options::OPT_INPUT), Value,
220 Args.getBaseArgs().MakeIndex(Value), Value.data());
Hans Wennborg55362852014-05-02 22:55:30 +0000221 Args.AddSynthesizedArg(A);
Hans Wennborged1d0722013-08-13 21:32:29 +0000222 A->claim();
223 return A;
224}
225
Daniel Dunbar775d4062010-06-11 22:00:26 +0000226DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
227 DerivedArgList *DAL = new DerivedArgList(Args);
228
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000229 bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
Nirav Daveb0bb6142015-11-24 16:07:21 +0000230 bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +0000231 for (Arg *A : Args) {
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000232 // Unfortunately, we have to parse some forwarding options (-Xassembler,
233 // -Xlinker, -Xpreprocessor) because we either integrate their functionality
234 // (assembler and preprocessor), or bypass a previous driver ('collect2').
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000235
236 // Rewrite linker options, to replace --no-demangle with a custom internal
237 // option.
238 if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
239 A->getOption().matches(options::OPT_Xlinker)) &&
240 A->containsValue("--no-demangle")) {
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000241 // Add the rewritten no-demangle argument.
242 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
243
244 // Add the remaining values as Xlinker arguments.
Benjamin Kramer72e64312015-09-24 14:48:49 +0000245 for (StringRef Val : A->getValues())
Douglas Katzmana34b7bf2015-06-30 19:32:57 +0000246 if (Val != "--no-demangle")
247 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), Val);
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000248
249 continue;
250 }
251
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000252 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
253 // some build systems. We don't try to be complete here because we don't
254 // care to encourage this usage model.
255 if (A->getOption().matches(options::OPT_Wp_COMMA) &&
Richard Smithbd55daf2012-11-01 04:30:05 +0000256 (A->getValue(0) == StringRef("-MD") ||
257 A->getValue(0) == StringRef("-MMD"))) {
Daniel Dunbar3648ba72010-06-15 20:30:18 +0000258 // Rewrite to -MD/-MMD along with -MF.
Richard Smithbd55daf2012-11-01 04:30:05 +0000259 if (A->getValue(0) == StringRef("-MD"))
Daniel Dunbar3648ba72010-06-15 20:30:18 +0000260 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
261 else
262 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
Michael J. Spencer70d85be2012-11-07 23:37:14 +0000263 if (A->getNumValues() == 2)
264 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
265 A->getValue(1));
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000266 continue;
267 }
268
Shantonu Senafeb03b2010-09-17 18:39:08 +0000269 // Rewrite reserved library names.
270 if (A->getOption().matches(options::OPT_l)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000271 StringRef Value = A->getValue();
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000272
Shantonu Senafeb03b2010-09-17 18:39:08 +0000273 // Rewrite unless -nostdlib is present.
Nirav Daveb0bb6142015-11-24 16:07:21 +0000274 if (!HasNostdlib && !HasNodefaultlib && Value == "stdc++") {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000275 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_stdcxx));
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000276 continue;
277 }
Shantonu Senafeb03b2010-09-17 18:39:08 +0000278
279 // Rewrite unconditionally.
280 if (Value == "cc_kext") {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000281 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_cckext));
Shantonu Senafeb03b2010-09-17 18:39:08 +0000282 continue;
283 }
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000284 }
285
Hans Wennborged1d0722013-08-13 21:32:29 +0000286 // Pick up inputs via the -- option.
287 if (A->getOption().matches(options::OPT__DASH_DASH)) {
288 A->claim();
Benjamin Kramer72e64312015-09-24 14:48:49 +0000289 for (StringRef Val : A->getValues())
Douglas Katzmana34b7bf2015-06-30 19:32:57 +0000290 DAL->append(MakeInputArg(*DAL, Opts, Val));
Hans Wennborged1d0722013-08-13 21:32:29 +0000291 continue;
292 }
293
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +0000294 DAL->append(A);
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000295 }
Daniel Dunbar775d4062010-06-11 22:00:26 +0000296
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000297 // Enforce -static if -miamcu is present.
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000298 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false))
299 DAL->AddFlagArg(0, Opts->getOption(options::OPT_static));
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000300
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000301// Add a default value of -mlinker-version=, if one was given and the user
302// didn't specify one.
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000303#if defined(HOST_LINK_VERSION)
Tim Northover018578c2015-06-12 19:21:35 +0000304 if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
305 strlen(HOST_LINK_VERSION) > 0) {
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000306 DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
307 HOST_LINK_VERSION);
Daniel Dunbarb613ffc2010-08-17 22:32:45 +0000308 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000309 }
310#endif
311
Daniel Dunbar775d4062010-06-11 22:00:26 +0000312 return DAL;
313}
314
Artem Belevich959e0542015-07-10 19:47:55 +0000315/// \brief Compute target triple from args.
316///
317/// This routine provides the logic to compute a target triple from various
318/// args passed to the driver and the default triple string.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000319static llvm::Triple computeTargetTriple(const Driver &D,
320 StringRef DefaultTargetTriple,
Artem Belevich959e0542015-07-10 19:47:55 +0000321 const ArgList &Args,
322 StringRef DarwinArchName = "") {
323 // FIXME: Already done in Compilation *Driver::BuildCompilation
324 if (const Arg *A = Args.getLastArg(options::OPT_target))
325 DefaultTargetTriple = A->getValue();
326
327 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
328
329 // Handle Apple-specific options available here.
330 if (Target.isOSBinFormatMachO()) {
331 // If an explict Darwin arch name is given, that trumps all.
332 if (!DarwinArchName.empty()) {
333 tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
334 return Target;
335 }
336
337 // Handle the Darwin '-arch' flag.
338 if (Arg *A = Args.getLastArg(options::OPT_arch)) {
339 StringRef ArchName = A->getValue();
340 tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
341 }
342 }
343
344 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
345 // '-mbig-endian'/'-EB'.
346 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
347 options::OPT_mbig_endian)) {
348 if (A->getOption().matches(options::OPT_mlittle_endian)) {
349 llvm::Triple LE = Target.getLittleEndianArchVariant();
350 if (LE.getArch() != llvm::Triple::UnknownArch)
351 Target = std::move(LE);
352 } else {
353 llvm::Triple BE = Target.getBigEndianArchVariant();
354 if (BE.getArch() != llvm::Triple::UnknownArch)
355 Target = std::move(BE);
356 }
357 }
358
359 // Skip further flag support on OSes which don't support '-m32' or '-m64'.
Douglas Katzman15a63ed2015-08-12 18:36:12 +0000360 if (Target.getArch() == llvm::Triple::tce ||
361 Target.getOS() == llvm::Triple::Minix)
Artem Belevich959e0542015-07-10 19:47:55 +0000362 return Target;
363
364 // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000365 Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
366 options::OPT_m32, options::OPT_m16);
367 if (A) {
Artem Belevich959e0542015-07-10 19:47:55 +0000368 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
369
370 if (A->getOption().matches(options::OPT_m64)) {
371 AT = Target.get64BitArchVariant().getArch();
372 if (Target.getEnvironment() == llvm::Triple::GNUX32)
373 Target.setEnvironment(llvm::Triple::GNU);
374 } else if (A->getOption().matches(options::OPT_mx32) &&
375 Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
376 AT = llvm::Triple::x86_64;
377 Target.setEnvironment(llvm::Triple::GNUX32);
378 } else if (A->getOption().matches(options::OPT_m32)) {
379 AT = Target.get32BitArchVariant().getArch();
380 if (Target.getEnvironment() == llvm::Triple::GNUX32)
381 Target.setEnvironment(llvm::Triple::GNU);
382 } else if (A->getOption().matches(options::OPT_m16) &&
383 Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
384 AT = llvm::Triple::x86;
385 Target.setEnvironment(llvm::Triple::CODE16);
386 }
387
388 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
389 Target.setArch(AT);
390 }
391
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000392 // Handle -miamcu flag.
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000393 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
394 if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
395 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
396 << Target.str();
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000397
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000398 if (A && !A->getOption().matches(options::OPT_m32))
399 D.Diag(diag::err_drv_argument_not_allowed_with)
400 << "-miamcu" << A->getBaseArg().getAsString(Args);
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000401
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000402 Target.setArch(llvm::Triple::x86);
403 Target.setArchName("i586");
404 Target.setEnvironment(llvm::Triple::UnknownEnvironment);
405 Target.setEnvironmentName("");
406 Target.setOS(llvm::Triple::ELFIAMCU);
407 Target.setVendor(llvm::Triple::UnknownVendor);
408 Target.setVendorName("intel");
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000409 }
410
Artem Belevich959e0542015-07-10 19:47:55 +0000411 return Target;
412}
413
Teresa Johnson945bc502015-10-15 20:35:53 +0000414// \brief Parse the LTO options and record the type of LTO compilation
415// based on which -f(no-)?lto(=.*)? option occurs last.
416void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
417 LTOMode = LTOK_None;
418 if (!Args.hasFlag(options::OPT_flto, options::OPT_flto_EQ,
419 options::OPT_fno_lto, false))
420 return;
421
422 StringRef LTOName("full");
423
424 const Arg *A = Args.getLastArg(options::OPT_flto_EQ);
Teresa Johnson6ef80dc2015-11-02 18:03:12 +0000425 if (A)
426 LTOName = A->getValue();
Teresa Johnson945bc502015-10-15 20:35:53 +0000427
428 LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
429 .Case("full", LTOK_Full)
430 .Case("thin", LTOK_Thin)
431 .Default(LTOK_Unknown);
432
433 if (LTOMode == LTOK_Unknown) {
434 assert(A);
435 Diag(diag::err_drv_unsupported_option_argument) << A->getOption().getName()
436 << A->getValue();
437 }
438}
439
Samuel Antao39f9da22016-10-27 16:38:05 +0000440/// Compute the desired OpenMP runtime from the flags provided.
441Driver::OpenMPRuntimeKind Driver::getOpenMPRuntime(const ArgList &Args) const {
442 StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
443
444 const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
445 if (A)
446 RuntimeName = A->getValue();
447
448 auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
449 .Case("libomp", OMPRT_OMP)
450 .Case("libgomp", OMPRT_GOMP)
451 .Case("libiomp5", OMPRT_IOMP5)
452 .Default(OMPRT_Unknown);
453
454 if (RT == OMPRT_Unknown) {
455 if (A)
456 Diag(diag::err_drv_unsupported_option_argument)
457 << A->getOption().getName() << A->getValue();
458 else
459 // FIXME: We could use a nicer diagnostic here.
460 Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
461 }
462
463 return RT;
464}
465
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000466void Driver::CreateOffloadingDeviceToolChains(Compilation &C,
467 InputList &Inputs) {
468
469 //
470 // CUDA
471 //
472 // We need to generate a CUDA toolchain if any of the inputs has a CUDA type.
473 if (llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
474 return types::isCuda(I.first);
475 })) {
Justin Lebar66c4fd72016-11-18 00:41:22 +0000476 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
477 const llvm::Triple &HostTriple = HostTC->getTriple();
478 llvm::Triple CudaTriple(HostTriple.isArch64Bit() ? "nvptx64-nvidia-cuda"
479 : "nvptx-nvidia-cuda");
480 // Use the CUDA and host triples as the key into the ToolChains map, because
481 // the device toolchain we create depends on both.
482 ToolChain *&CudaTC = ToolChains[CudaTriple.str() + "/" + HostTriple.str()];
483 if (!CudaTC) {
484 CudaTC = new toolchains::CudaToolChain(*this, CudaTriple, *HostTC,
485 C.getInputArgs());
486 }
487 C.addOffloadDeviceToolChain(CudaTC, Action::OFK_Cuda);
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000488 }
489
490 //
Samuel Antao39f9da22016-10-27 16:38:05 +0000491 // OpenMP
492 //
493 // We need to generate an OpenMP toolchain if the user specified targets with
494 // the -fopenmp-targets option.
495 if (Arg *OpenMPTargets =
496 C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
497 if (OpenMPTargets->getNumValues()) {
498 // We expect that -fopenmp-targets is always used in conjunction with the
499 // option -fopenmp specifying a valid runtime with offloading support,
500 // i.e. libomp or libiomp.
501 bool HasValidOpenMPRuntime = C.getInputArgs().hasFlag(
502 options::OPT_fopenmp, options::OPT_fopenmp_EQ,
503 options::OPT_fno_openmp, false);
504 if (HasValidOpenMPRuntime) {
505 OpenMPRuntimeKind OpenMPKind = getOpenMPRuntime(C.getInputArgs());
506 HasValidOpenMPRuntime =
507 OpenMPKind == OMPRT_OMP || OpenMPKind == OMPRT_IOMP5;
508 }
509
510 if (HasValidOpenMPRuntime) {
511 llvm::StringMap<const char *> FoundNormalizedTriples;
512 for (const char *Val : OpenMPTargets->getValues()) {
513 llvm::Triple TT(Val);
514 std::string NormalizedName = TT.normalize();
515
516 // Make sure we don't have a duplicate triple.
517 auto Duplicate = FoundNormalizedTriples.find(NormalizedName);
518 if (Duplicate != FoundNormalizedTriples.end()) {
519 Diag(clang::diag::warn_drv_omp_offload_target_duplicate)
520 << Val << Duplicate->second;
521 continue;
522 }
523
524 // Store the current triple so that we can check for duplicates in the
525 // following iterations.
526 FoundNormalizedTriples[NormalizedName] = Val;
527
528 // If the specified target is invalid, emit a diagnostic.
529 if (TT.getArch() == llvm::Triple::UnknownArch)
530 Diag(clang::diag::err_drv_invalid_omp_target) << Val;
531 else {
532 const ToolChain &TC = getToolChain(C.getInputArgs(), TT);
533 C.addOffloadDeviceToolChain(&TC, Action::OFK_OpenMP);
534 }
535 }
536 } else
537 Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
538 } else
539 Diag(clang::diag::warn_drv_empty_joined_argument)
540 << OpenMPTargets->getAsString(C.getInputArgs());
541 }
542
543 //
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000544 // TODO: Add support for other offloading programming models here.
545 //
546
547 return;
548}
549
Chris Lattner54b16772011-07-23 17:14:25 +0000550Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
Daniel Dunbar2608c542009-03-18 01:38:48 +0000551 llvm::PrettyStackTraceString CrashInfo("Compilation construction");
552
Eric Christopherf901e852011-08-17 22:59:59 +0000553 // FIXME: Handle environment options which affect driver behavior, somewhere
Bill Wendlingadbeb9f2012-03-12 21:24:57 +0000554 // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
Chad Rosier82301162011-09-14 00:47:55 +0000555
David Majnemer85c25b42016-07-24 17:44:03 +0000556 if (Optional<std::string> CompilerPathValue =
557 llvm::sys::Process::GetEnv("COMPILER_PATH")) {
558 StringRef CompilerPath = *CompilerPathValue;
Chad Rosier82301162011-09-14 00:47:55 +0000559 while (!CompilerPath.empty()) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000560 std::pair<StringRef, StringRef> Split =
561 CompilerPath.split(llvm::sys::EnvPathSeparator);
Chad Rosier82301162011-09-14 00:47:55 +0000562 PrefixDirs.push_back(Split.first);
563 CompilerPath = Split.second;
564 }
565 }
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +0000566
Hans Wennborg70850d82013-07-18 20:29:38 +0000567 // We look for the driver mode option early, because the mode can affect
568 // how other options are parsed.
Zachary Turneraff19c32016-08-12 17:47:52 +0000569 ParseDriverMode(ClangExecutable, ArgList.slice(1));
Hans Wennborg70850d82013-07-18 20:29:38 +0000570
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +0000571 // FIXME: What are we going to do with -V and -b?
572
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +0000573 // FIXME: This stuff needs to go into the Compilation, not the driver.
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +0000574 bool CCCPrintPhases;
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000575
David Blaikie69a1d8c2015-06-22 22:07:27 +0000576 InputArgList Args = ParseArgStrings(ArgList.slice(1));
Daniel Dunbaracd69572009-12-04 21:55:23 +0000577
Filipe Cabecinhas136f35e2015-07-18 06:35:24 +0000578 // Silence driver warnings if requested
579 Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w));
580
Rafael Espindola59ae7992009-12-07 18:28:29 +0000581 // -no-canonical-prefixes is used very early in main.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000582 Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
Rafael Espindola59ae7992009-12-07 18:28:29 +0000583
Daniel Dunbar926f81f2010-08-02 02:38:03 +0000584 // Ignore -pipe.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000585 Args.ClaimAllArgs(options::OPT_pipe);
Daniel Dunbar926f81f2010-08-02 02:38:03 +0000586
Daniel Dunbaracd69572009-12-04 21:55:23 +0000587 // Extract -ccc args.
Daniel Dunbaree66cf22009-03-10 20:52:46 +0000588 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +0000589 // FIXME: We need to figure out where this behavior should live. Most of it
590 // should be outside in the client; the parts that aren't should have proper
591 // options, either by introducing new ones or by overloading gcc ones like -V
592 // or -b.
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +0000593 CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
David Blaikie69a1d8c2015-06-22 22:07:27 +0000594 CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
595 if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
Richard Smithbd55daf2012-11-01 04:30:05 +0000596 CCCGenericGCCName = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000597 CCCUsePCH =
598 Args.hasFlag(options::OPT_ccc_pch_is_pch, options::OPT_ccc_pch_is_pth);
Joerg Sonnenberger17d75512012-02-22 19:15:16 +0000599 // FIXME: DefaultTargetTriple is used by the target-prefixed calls to as/ld
600 // and getToolChain is const.
Hans Wennborg2e274592013-08-13 23:38:57 +0000601 if (IsCLMode()) {
Hans Wennborg73609a02014-03-28 01:19:04 +0000602 // clang-cl targets MSVC-style Win32.
Hans Wennborg2e274592013-08-13 23:38:57 +0000603 llvm::Triple T(DefaultTargetTriple);
Hans Wennborg9d9ce7a2014-03-28 20:49:28 +0000604 T.setOS(llvm::Triple::Win32);
Hans Wennborg0f0e8d62015-09-18 17:11:50 +0000605 T.setVendor(llvm::Triple::PC);
Hans Wennborg9d9ce7a2014-03-28 20:49:28 +0000606 T.setEnvironment(llvm::Triple::MSVC);
Hans Wennborg2e274592013-08-13 23:38:57 +0000607 DefaultTargetTriple = T.str();
608 }
David Blaikie69a1d8c2015-06-22 22:07:27 +0000609 if (const Arg *A = Args.getLastArg(options::OPT_target))
Richard Smithbd55daf2012-11-01 04:30:05 +0000610 DefaultTargetTriple = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000611 if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
Richard Smithbd55daf2012-11-01 04:30:05 +0000612 Dir = InstalledDir = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000613 for (const Arg *A : Args.filtered(options::OPT_B)) {
Benjamin Kramer1a648d12011-02-08 20:31:42 +0000614 A->claim();
Richard Smithbd55daf2012-11-01 04:30:05 +0000615 PrefixDirs.push_back(A->getValue(0));
Benjamin Kramer1a648d12011-02-08 20:31:42 +0000616 }
David Blaikie69a1d8c2015-06-22 22:07:27 +0000617 if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
Richard Smithbd55daf2012-11-01 04:30:05 +0000618 SysRoot = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000619 if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
Peter Collingbourne9d9e1fc2013-05-27 21:40:20 +0000620 DyldPrefix = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000621 if (Args.hasArg(options::OPT_nostdlib))
Joerg Sonnenbergerbc923f32011-03-21 13:59:26 +0000622 UseStdLib = false;
Daniel Dunbaree66cf22009-03-10 20:52:46 +0000623
David Blaikie69a1d8c2015-06-22 22:07:27 +0000624 if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
Bob Wilsona20a1da2013-03-23 05:17:59 +0000625 ResourceDir = A->getValue();
Jim Grosbach061dabf2013-03-12 20:17:58 +0000626
David Blaikie69a1d8c2015-06-22 22:07:27 +0000627 if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
Reid Kleckner68eb60b2015-02-02 22:41:48 +0000628 SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
629 .Case("cwd", SaveTempsCwd)
630 .Case("obj", SaveTempsObj)
631 .Default(SaveTempsCwd);
632 }
633
Steven Wu1257cd82016-05-18 17:04:52 +0000634 setLTOMode(Args);
635
Steven Wu844ab6a2016-11-16 06:06:44 +0000636 // Process -fembed-bitcode= flags.
637 if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
638 StringRef Name = A->getValue();
639 unsigned Model = llvm::StringSwitch<unsigned>(Name)
640 .Case("off", EmbedNone)
641 .Case("all", EmbedBitcode)
642 .Case("bitcode", EmbedBitcode)
643 .Case("marker", EmbedMarker)
644 .Default(~0U);
645 if (Model == ~0U) {
646 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
647 << Name;
648 } else
649 BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
Steven Wu574b0f22016-03-01 01:07:58 +0000650 }
651
David Blaikie69a1d8c2015-06-22 22:07:27 +0000652 std::unique_ptr<llvm::opt::InputArgList> UArgs =
653 llvm::make_unique<InputArgList>(std::move(Args));
654
Daniel Dunbar775d4062010-06-11 22:00:26 +0000655 // Perform the default argument translations.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000656 DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
Daniel Dunbar775d4062010-06-11 22:00:26 +0000657
Chandler Carruthcb916192012-01-25 08:49:21 +0000658 // Owned by the host.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000659 const ToolChain &TC = getToolChain(
660 *UArgs, computeTargetTriple(*this, DefaultTargetTriple, *UArgs));
Chandler Carruthcb916192012-01-25 08:49:21 +0000661
Daniel Dunbar3ce436d2009-03-16 06:42:30 +0000662 // The compilation takes ownership of Args.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000663 Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +0000664
Daniel Dunbarf0eddb82009-03-18 02:55:38 +0000665 if (!HandleImmediateArgs(*C))
666 return C;
667
Chad Rosierecdede82011-08-12 22:08:57 +0000668 // Construct the list of inputs.
669 InputList Inputs;
Hans Wennborged1d0722013-08-13 21:32:29 +0000670 BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
Chad Rosierecdede82011-08-12 22:08:57 +0000671
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000672 // Populate the tool chains for the offloading devices, if any.
673 CreateOffloadingDeviceToolChains(*C, Inputs);
Justin Lebar0e450a52016-03-30 23:30:25 +0000674
Chandler Carruth7f1417f2012-01-24 10:43:44 +0000675 // Construct the list of abstract actions to perform for this compilation. On
Tim Northover157d9112014-01-16 08:48:16 +0000676 // MachO targets this uses the driver-driver and universal actions.
677 if (TC.getTriple().isOSBinFormatMachO())
Artem Belevich5e2a3ec2015-11-17 22:28:40 +0000678 BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +0000679 else
Justin Lebar0f3474c2016-02-11 02:00:50 +0000680 BuildActions(*C, C->getArgs(), Inputs, C->getActions());
Daniel Dunbarf0eddb82009-03-18 02:55:38 +0000681
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +0000682 if (CCCPrintPhases) {
Daniel Dunbareb843be2009-03-18 03:13:20 +0000683 PrintActions(*C);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +0000684 return C;
685 }
686
687 BuildJobs(*C);
Daniel Dunbaradc91e62009-03-15 01:38:15 +0000688
689 return C;
Daniel Dunbaree66cf22009-03-10 20:52:46 +0000690}
691
Justin Bognered9cbe02015-07-09 06:58:31 +0000692static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
693 llvm::opt::ArgStringList ASL;
694 for (const auto *A : Args)
695 A->render(Args, ASL);
696
697 for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
698 if (I != ASL.begin())
699 OS << ' ';
700 Command::printArg(OS, *I, true);
701 }
702 OS << '\n';
703}
704
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +0000705bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename,
706 SmallString<128> &CrashDiagDir) {
707 using namespace llvm::sys;
708 assert(llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin() &&
709 "Only knows about .crash files on Darwin");
710
711 // The .crash file can be found on at ~/Library/Logs/DiagnosticReports/
712 // (or /Library/Logs/DiagnosticReports for root) and has the filename pattern
713 // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash.
714 path::home_directory(CrashDiagDir);
715 if (CrashDiagDir.startswith("/var/root"))
716 CrashDiagDir = "/";
717 path::append(CrashDiagDir, "Library/Logs/DiagnosticReports");
718 int PID =
719#if LLVM_ON_UNIX
720 getpid();
721#else
722 0;
723#endif
724 std::error_code EC;
725 fs::file_status FileStatus;
726 TimePoint<> LastAccessTime;
727 SmallString<128> CrashFilePath;
728 // Lookup the .crash files and get the one generated by a subprocess spawned
729 // by this driver invocation.
730 for (fs::directory_iterator File(CrashDiagDir, EC), FileEnd;
731 File != FileEnd && !EC; File.increment(EC)) {
732 StringRef FileName = path::filename(File->path());
733 if (!FileName.startswith(Name))
734 continue;
735 if (fs::status(File->path(), FileStatus))
736 continue;
737 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CrashFile =
738 llvm::MemoryBuffer::getFile(File->path());
739 if (!CrashFile)
740 continue;
741 // The first line should start with "Process:", otherwise this isn't a real
742 // .crash file.
743 StringRef Data = CrashFile.get()->getBuffer();
744 if (!Data.startswith("Process:"))
745 continue;
746 // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]"
747 size_t ParentProcPos = Data.find("Parent Process:");
748 if (ParentProcPos == StringRef::npos)
749 continue;
750 size_t LineEnd = Data.find_first_of("\n", ParentProcPos);
751 if (LineEnd == StringRef::npos)
752 continue;
753 StringRef ParentProcess = Data.slice(ParentProcPos+15, LineEnd).trim();
754 int OpenBracket = -1, CloseBracket = -1;
755 for (size_t i = 0, e = ParentProcess.size(); i < e; ++i) {
756 if (ParentProcess[i] == '[')
757 OpenBracket = i;
758 if (ParentProcess[i] == ']')
759 CloseBracket = i;
760 }
761 // Extract the parent process PID from the .crash file and check whether
762 // it matches this driver invocation pid.
763 int CrashPID;
764 if (OpenBracket < 0 || CloseBracket < 0 ||
765 ParentProcess.slice(OpenBracket + 1, CloseBracket)
766 .getAsInteger(10, CrashPID) || CrashPID != PID) {
767 continue;
768 }
769
770 // Found a .crash file matching the driver pid. To avoid getting an older
771 // and misleading crash file, continue looking for the most recent.
772 // FIXME: the driver can dispatch multiple cc1 invocations, leading to
773 // multiple crashes poiting to the same parent process. Since the driver
774 // does not collect pid information for the dispatched invocation there's
775 // currently no way to distinguish among them.
776 const auto FileAccessTime = FileStatus.getLastModificationTime();
777 if (FileAccessTime > LastAccessTime) {
778 CrashFilePath.assign(File->path());
779 LastAccessTime = FileAccessTime;
780 }
781 }
782
783 // If found, copy it over to the location of other reproducer files.
784 if (!CrashFilePath.empty()) {
785 EC = fs::copy_file(CrashFilePath, ReproCrashFilename);
786 if (EC)
787 return false;
788 return true;
789 }
790
791 return false;
792}
793
Eric Christopherf901e852011-08-17 22:59:59 +0000794// When clang crashes, produce diagnostic information including the fully
795// preprocessed source file(s). Request that the developer attach the
Chad Rosierbe10f982011-08-02 17:58:04 +0000796// diagnostic information to a bug report.
797void Driver::generateCompilationDiagnostics(Compilation &C,
Justin Bognere1a33d12014-10-20 21:02:05 +0000798 const Command &FailingCommand) {
Chad Rosier877c0a22012-02-22 00:30:39 +0000799 if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
Chad Rosier62135492012-07-09 17:31:28 +0000800 return;
Chad Rosierbee5a1d2012-03-07 00:30:40 +0000801
Chad Rosierdbf46a12013-02-01 18:30:26 +0000802 // Don't try to generate diagnostics for link or dsymutil jobs.
Justin Bognere1a33d12014-10-20 21:02:05 +0000803 if (FailingCommand.getCreator().isLinkJob() ||
804 FailingCommand.getCreator().isDsymutilJob())
Chad Rosier877c0a22012-02-22 00:30:39 +0000805 return;
806
Chad Rosier8179f112012-06-19 17:51:34 +0000807 // Print the version of the compiler.
808 PrintVersion(C, llvm::errs());
809
Chad Rosierbe10f982011-08-02 17:58:04 +0000810 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000811 << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the "
812 "crash backtrace, preprocessed source, and associated run script.";
Chad Rosierbe10f982011-08-02 17:58:04 +0000813
814 // Suppress driver output and emit preprocessor output to temp file.
Hans Wennborg70850d82013-07-18 20:29:38 +0000815 Mode = CPPMode;
Chad Rosierbe10f982011-08-02 17:58:04 +0000816 CCGenDiagnostics = true;
817
Chad Rosiercdb008d2011-11-02 21:29:05 +0000818 // Save the original job command(s).
Justin Bogner25645152014-10-21 17:24:44 +0000819 Command Cmd = FailingCommand;
Chad Rosiercdb008d2011-11-02 21:29:05 +0000820
Richard Smith5bb4cdf2012-12-20 02:22:15 +0000821 // Keep track of whether we produce any errors while trying to produce
822 // preprocessed sources.
823 DiagnosticErrorTrap Trap(Diags);
824
825 // Suppress tool output.
Chad Rosierbe10f982011-08-02 17:58:04 +0000826 C.initCompilationForDiagnostics();
Chad Rosierecdede82011-08-12 22:08:57 +0000827
828 // Construct the list of inputs.
829 InputList Inputs;
830 BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
Chad Rosierbe10f982011-08-02 17:58:04 +0000831
Chad Rosier4f81fc22011-08-12 23:30:05 +0000832 for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
Chad Rosierd57133d2011-08-18 00:22:25 +0000833 bool IgnoreInput = false;
834
835 // Ignore input from stdin or any inputs that cannot be preprocessed.
Paul Robinsonf44157d2014-04-28 22:24:44 +0000836 // Check type first as not all linker inputs have a value.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000837 if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
Paul Robinsonf44157d2014-04-28 22:24:44 +0000838 IgnoreInput = true;
839 } else if (!strcmp(it->second->getValue(), "-")) {
Chad Rosierd57133d2011-08-18 00:22:25 +0000840 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000841 << "Error generating preprocessed source(s) - "
842 "ignoring input from stdin.";
Chad Rosierd57133d2011-08-18 00:22:25 +0000843 IgnoreInput = true;
Chad Rosierd57133d2011-08-18 00:22:25 +0000844 }
845
846 if (IgnoreInput) {
Chad Rosier4f81fc22011-08-12 23:30:05 +0000847 it = Inputs.erase(it);
848 ie = Inputs.end();
Chad Rosier6fdf38b2011-08-17 23:08:45 +0000849 } else {
Chad Rosier4f81fc22011-08-12 23:30:05 +0000850 ++it;
Chad Rosier6fdf38b2011-08-17 23:08:45 +0000851 }
Chad Rosier4f81fc22011-08-12 23:30:05 +0000852 }
Chad Rosierd57133d2011-08-18 00:22:25 +0000853
Chad Rosierc5103c32013-01-29 23:57:10 +0000854 if (Inputs.empty()) {
855 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000856 << "Error generating preprocessed source(s) - "
857 "no preprocessable inputs.";
Chad Rosierc5103c32013-01-29 23:57:10 +0000858 return;
859 }
860
Chad Rosiere75ef402011-09-06 23:52:36 +0000861 // Don't attempt to generate preprocessed files if multiple -arch options are
Chad Rosier636d2832012-02-13 18:16:28 +0000862 // used, unless they're all duplicates.
863 llvm::StringSet<> ArchNames;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +0000864 for (const Arg *A : C.getArgs()) {
Chad Rosiere75ef402011-09-06 23:52:36 +0000865 if (A->getOption().matches(options::OPT_arch)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000866 StringRef ArchName = A->getValue();
Chad Rosier636d2832012-02-13 18:16:28 +0000867 ArchNames.insert(ArchName);
Chad Rosiere75ef402011-09-06 23:52:36 +0000868 }
869 }
Chad Rosier636d2832012-02-13 18:16:28 +0000870 if (ArchNames.size() > 1) {
871 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000872 << "Error generating preprocessed source(s) - cannot generate "
873 "preprocessed source with multiple -arch options.";
Chad Rosier636d2832012-02-13 18:16:28 +0000874 return;
875 }
Chad Rosiere75ef402011-09-06 23:52:36 +0000876
Chandler Carruth7f1417f2012-01-24 10:43:44 +0000877 // Construct the list of abstract actions to perform for this compilation. On
878 // Darwin OSes this uses the driver-driver and builds universal actions.
Chandler Carruthcb916192012-01-25 08:49:21 +0000879 const ToolChain &TC = C.getDefaultToolChain();
Tim Northover157d9112014-01-16 08:48:16 +0000880 if (TC.getTriple().isOSBinFormatMachO())
Artem Belevich5e2a3ec2015-11-17 22:28:40 +0000881 BuildUniversalActions(C, TC, Inputs);
Chad Rosierbe10f982011-08-02 17:58:04 +0000882 else
Justin Lebar0f3474c2016-02-11 02:00:50 +0000883 BuildActions(C, C.getArgs(), Inputs, C.getActions());
Chad Rosierbe10f982011-08-02 17:58:04 +0000884
885 BuildJobs(C);
886
887 // If there were errors building the compilation, quit now.
Richard Smith5bb4cdf2012-12-20 02:22:15 +0000888 if (Trap.hasErrorOccurred()) {
Chad Rosierbe10f982011-08-02 17:58:04 +0000889 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000890 << "Error generating preprocessed source(s).";
Chad Rosierbe10f982011-08-02 17:58:04 +0000891 return;
892 }
893
894 // Generate preprocessed output.
Chad Rosierdd60e092013-01-29 20:15:05 +0000895 SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
Justin Bogner0cd92482015-07-02 22:52:08 +0000896 C.ExecuteJobs(C.getJobs(), FailingCommands);
Chad Rosierbe10f982011-08-02 17:58:04 +0000897
Justin Bognerbc89b182014-10-20 21:20:27 +0000898 // If any of the preprocessing commands failed, clean up and exit.
899 if (!FailingCommands.empty()) {
Reid Kleckner68eb60b2015-02-02 22:41:48 +0000900 if (!isSaveTempsEnabled())
Chad Rosierbe10f982011-08-02 17:58:04 +0000901 C.CleanupFileList(C.getTempFiles(), true);
902
903 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000904 << "Error generating preprocessed source(s).";
Justin Bognerbc89b182014-10-20 21:20:27 +0000905 return;
Chad Rosierbe10f982011-08-02 17:58:04 +0000906 }
Justin Bognerbc89b182014-10-20 21:20:27 +0000907
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000908 const ArgStringList &TempFiles = C.getTempFiles();
909 if (TempFiles.empty()) {
910 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000911 << "Error generating preprocessed source(s).";
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000912 return;
913 }
914
Justin Bognerbc89b182014-10-20 21:20:27 +0000915 Diag(clang::diag::note_drv_command_failed_diag_msg)
916 << "\n********************\n\n"
917 "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
918 "Preprocessed source(s) and associated run script(s) are located at:";
Justin Bognerbc89b182014-10-20 21:20:27 +0000919
Justin Bogner659ecc32014-10-20 22:47:23 +0000920 SmallString<128> VFS;
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +0000921 SmallString<128> ReproCrashFilename;
Justin Bogner659ecc32014-10-20 22:47:23 +0000922 for (const char *TempFile : TempFiles) {
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000923 Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +0000924 if (ReproCrashFilename.empty()) {
925 ReproCrashFilename = TempFile;
926 llvm::sys::path::replace_extension(ReproCrashFilename, ".crash");
927 }
Justin Bogner659ecc32014-10-20 22:47:23 +0000928 if (StringRef(TempFile).endswith(".cache")) {
929 // In some cases (modules) we'll dump extra data to help with reproducing
930 // the crash into a directory next to the output.
931 VFS = llvm::sys::path::filename(TempFile);
932 llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
933 }
934 }
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000935
936 // Assume associated files are based off of the first temporary file.
Justin Bogner25645152014-10-21 17:24:44 +0000937 CrashReportInfo CrashInfo(TempFiles[0], VFS);
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000938
Justin Bogner25645152014-10-21 17:24:44 +0000939 std::string Script = CrashInfo.Filename.rsplit('.').first.str() + ".sh";
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000940 std::error_code EC;
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000941 llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::F_Excl);
942 if (EC) {
943 Diag(clang::diag::note_drv_command_failed_diag_msg)
944 << "Error generating run script: " + Script + " " + EC.message();
945 } else {
Justin Bogner42220ed2015-03-12 00:14:35 +0000946 ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
Justin Bognered9cbe02015-07-09 06:58:31 +0000947 << "# Driver args: ";
948 printArgList(ScriptOS, C.getInputArgs());
949 ScriptOS << "# Original command: ";
Justin Bogner42220ed2015-03-12 00:14:35 +0000950 Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
Justin Bogner33bdbc62014-10-21 18:03:08 +0000951 Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000952 Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
Justin Bognerbc89b182014-10-20 21:20:27 +0000953 }
Saleem Abdulrasool3661a822015-01-12 02:33:09 +0000954
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +0000955 // On darwin, provide information about the .crash diagnostic report.
956 if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) {
957 SmallString<128> CrashDiagDir;
958 if (getCrashDiagnosticFile(ReproCrashFilename, CrashDiagDir)) {
959 Diag(clang::diag::note_drv_command_failed_diag_msg)
960 << ReproCrashFilename.str();
961 } else { // Suggest a directory for the user to look for .crash files.
962 llvm::sys::path::append(CrashDiagDir, Name);
963 CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash";
964 Diag(clang::diag::note_drv_command_failed_diag_msg)
965 << "Crash backtrace is located in";
966 Diag(clang::diag::note_drv_command_failed_diag_msg)
967 << CrashDiagDir.str();
968 Diag(clang::diag::note_drv_command_failed_diag_msg)
969 << "(choose the .crash file that corresponds to your crash)";
970 }
971 }
972
Saleem Abdulrasool3661a822015-01-12 02:33:09 +0000973 for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file,
974 options::OPT_frewrite_map_file_EQ))
975 Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
976
Justin Bognerbc89b182014-10-20 21:20:27 +0000977 Diag(clang::diag::note_drv_command_failed_diag_msg)
978 << "\n\n********************";
Chad Rosierbe10f982011-08-02 17:58:04 +0000979}
980
Justin Bogner0cd92482015-07-02 22:52:08 +0000981void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
Oleg Ranevskyycd516372016-01-05 19:54:39 +0000982 // Since commandLineFitsWithinSystemLimits() may underestimate system's capacity
Reid Kleckner0290c9c2014-09-15 17:45:39 +0000983 // if the tool does not support response files, there is a chance/ that things
984 // will just work without a response file, so we silently just skip it.
Justin Bogner0cd92482015-07-02 22:52:08 +0000985 if (Cmd.getCreator().getResponseFilesSupport() == Tool::RF_None ||
Oleg Ranevskyycd516372016-01-05 19:54:39 +0000986 llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(), Cmd.getArguments()))
Reid Kleckner0290c9c2014-09-15 17:45:39 +0000987 return;
988
989 std::string TmpName = GetTemporaryPath("response", "txt");
Malcolm Parsonsf76f6502016-11-02 10:39:27 +0000990 Cmd.setResponseFile(C.addTempFile(C.getArgs().MakeArgString(TmpName)));
Reid Kleckner0290c9c2014-09-15 17:45:39 +0000991}
992
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000993int Driver::ExecuteCompilation(
994 Compilation &C,
995 SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
Daniel Dunbar38bfda62009-07-01 20:03:04 +0000996 // Just print if -### was present.
997 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
Hans Wennborgb212b342013-09-12 18:23:34 +0000998 C.getJobs().Print(llvm::errs(), "\n", true);
Daniel Dunbar38bfda62009-07-01 20:03:04 +0000999 return 0;
1000 }
1001
1002 // If there were errors building the compilation, quit now.
Chad Rosierbe10f982011-08-02 17:58:04 +00001003 if (Diags.hasErrorOccurred())
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001004 return 1;
1005
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001006 // Set up response file names for each command, if necessary
Justin Bogner0cd92482015-07-02 22:52:08 +00001007 for (auto &Job : C.getJobs())
1008 setUpResponseFiles(C, Job);
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001009
Justin Bogner0cd92482015-07-02 22:52:08 +00001010 C.ExecuteJobs(C.getJobs(), FailingCommands);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001011
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001012 // Remove temp files.
1013 C.CleanupFileList(C.getTempFiles());
1014
Daniel Dunbar07494792010-05-22 00:37:20 +00001015 // If the command succeeded, we are done.
Chad Rosierdd60e092013-01-29 20:15:05 +00001016 if (FailingCommands.empty())
1017 return 0;
Daniel Dunbar07494792010-05-22 00:37:20 +00001018
Chad Rosierdd60e092013-01-29 20:15:05 +00001019 // Otherwise, remove result files and print extra information about abnormal
1020 // failures.
Douglas Katzman6bbffc42015-06-25 18:51:37 +00001021 for (const auto &CmdPair : FailingCommands) {
1022 int Res = CmdPair.first;
1023 const Command *FailingCommand = CmdPair.second;
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001024
Chad Rosierdd60e092013-01-29 20:15:05 +00001025 // Remove result files if we're not saving temps.
Reid Kleckner68eb60b2015-02-02 22:41:48 +00001026 if (!isSaveTempsEnabled()) {
Chad Rosierdd60e092013-01-29 20:15:05 +00001027 const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
1028 C.CleanupFileMap(C.getResultFiles(), JA, true);
1029
1030 // Failure result files are valid unless we crashed.
1031 if (Res < 0)
1032 C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
1033 }
1034
1035 // Print extra information about abnormal failures, if possible.
1036 //
1037 // This is ad-hoc, but we don't want to be excessively noisy. If the result
Justin Bogner5aaf2e72014-06-26 20:59:36 +00001038 // status was 1, assume the command failed normally. In particular, if it
Chad Rosierdd60e092013-01-29 20:15:05 +00001039 // was the compiler then assume it gave a reasonable error code. Failures
1040 // in other tools are less common, and they generally have worse
1041 // diagnostics, so always print the diagnostic there.
1042 const Tool &FailingTool = FailingCommand->getCreator();
1043
1044 if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
1045 // FIXME: See FIXME above regarding result code interpretation.
1046 if (Res < 0)
1047 Diag(clang::diag::err_drv_command_signalled)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001048 << FailingTool.getShortName();
Chad Rosierdd60e092013-01-29 20:15:05 +00001049 else
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001050 Diag(clang::diag::err_drv_command_failed) << FailingTool.getShortName()
1051 << Res;
Chad Rosierdd60e092013-01-29 20:15:05 +00001052 }
Peter Collingbourne119cfaa2011-11-21 00:01:05 +00001053 }
Chad Rosierdd60e092013-01-29 20:15:05 +00001054 return 0;
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001055}
1056
Daniel Dunbara7b5e212009-04-15 16:34:29 +00001057void Driver::PrintHelp(bool ShowHidden) const {
Hans Wennborg6ddc6902013-07-27 00:23:45 +00001058 unsigned IncludedFlagsBitmask;
1059 unsigned ExcludedFlagsBitmask;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001060 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001061 getIncludeExcludeOptionFlagMasks();
Hans Wennborg6ddc6902013-07-27 00:23:45 +00001062
1063 ExcludedFlagsBitmask |= options::NoDriverOption;
1064 if (!ShowHidden)
1065 ExcludedFlagsBitmask |= HelpHidden;
1066
1067 getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
1068 IncludedFlagsBitmask, ExcludedFlagsBitmask);
Daniel Dunbar7c925282009-03-31 21:38:17 +00001069}
1070
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001071void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001072 // FIXME: The following handlers should use a callback mechanism, we don't
1073 // know what the client would like to do.
Ted Kremenek4c0df3d2010-01-23 02:11:34 +00001074 OS << getClangFullVersion() << '\n';
Daniel Dunbarb10248802009-03-26 16:09:13 +00001075 const ToolChain &TC = C.getDefaultToolChain();
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001076 OS << "Target: " << TC.getTripleString() << '\n';
Daniel Dunbar10978e42009-06-16 23:32:58 +00001077
1078 // Print the threading model.
Jonathan Roelofsb140a102014-10-03 21:57:44 +00001079 if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
1080 // Don't print if the ToolChain would have barfed on it already
1081 if (TC.isThreadModelSupported(A->getValue()))
1082 OS << "Thread model: " << A->getValue();
1083 } else
1084 OS << "Thread model: " << TC.getThreadModel();
1085 OS << '\n';
Chandler Carruth9ade6a92015-08-05 17:07:33 +00001086
1087 // Print out the install directory.
1088 OS << "InstalledDir: " << InstalledDir << '\n';
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001089}
1090
Chris Lattner86ed5b02010-05-05 05:53:24 +00001091/// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
1092/// option.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001093static void PrintDiagnosticCategories(raw_ostream &OS) {
Argyrios Kyrtzidis0e37afa2011-05-25 05:05:01 +00001094 // Skip the empty category.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001095 for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
1096 ++i)
Argyrios Kyrtzidis0e37afa2011-05-25 05:05:01 +00001097 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
Chris Lattner86ed5b02010-05-05 05:53:24 +00001098}
1099
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001100bool Driver::HandleImmediateArgs(const Compilation &C) {
Daniel Dunbar18974bd2010-06-11 22:00:19 +00001101 // The order these options are handled in gcc is all over the place, but we
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001102 // don't expect inconsistencies w.r.t. that to matter in practice.
Daniel Dunbar7c925282009-03-31 21:38:17 +00001103
Daniel Dunbar1b09e042010-09-17 02:47:28 +00001104 if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
1105 llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
1106 return false;
1107 }
1108
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001109 if (C.getArgs().hasArg(options::OPT_dumpversion)) {
Daniel Dunbare26e5002011-01-12 00:43:47 +00001110 // Since -dumpversion is only implemented for pedantic GCC compatibility, we
1111 // return an answer which matches our definition of __VERSION__.
1112 //
1113 // If we want to return a more correct answer some day, then we should
1114 // introduce a non-pedantically GCC compatible mode to Clang in which we
1115 // provide sensible definitions for -dumpversion, __VERSION__, etc.
1116 llvm::outs() << "4.2.1\n";
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001117 return false;
1118 }
Daniel Dunbarfb3d7472010-06-14 21:23:12 +00001119
Chris Lattner86ed5b02010-05-05 05:53:24 +00001120 if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
1121 PrintDiagnosticCategories(llvm::outs());
1122 return false;
1123 }
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001124
James Molloya3c85b82012-05-01 14:57:16 +00001125 if (C.getArgs().hasArg(options::OPT_help) ||
Daniel Dunbara7b5e212009-04-15 16:34:29 +00001126 C.getArgs().hasArg(options::OPT__help_hidden)) {
1127 PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
Daniel Dunbar7c925282009-03-31 21:38:17 +00001128 return false;
1129 }
1130
Daniel Dunbarb0006ae2009-04-02 15:05:41 +00001131 if (C.getArgs().hasArg(options::OPT__version)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001132 // Follow gcc behavior and use stdout for --version and stderr for -v.
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001133 PrintVersion(C, llvm::outs());
Daniel Dunbarb0006ae2009-04-02 15:05:41 +00001134 return false;
1135 }
1136
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001137 if (C.getArgs().hasArg(options::OPT_v) ||
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001138 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001139 PrintVersion(C, llvm::errs());
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001140 SuppressMissingInputWarning = true;
1141 }
1142
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001143 const ToolChain &TC = C.getDefaultToolChain();
Chandler Carruth0ae39aa2013-07-30 17:57:09 +00001144
1145 if (C.getArgs().hasArg(options::OPT_v))
1146 TC.printVerboseInfo(llvm::errs());
1147
Daniel Dunbard972e222009-03-20 04:37:21 +00001148 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
1149 llvm::outs() << "programs: =";
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001150 bool separator = false;
1151 for (const std::string &Path : TC.getProgramPaths()) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001152 if (separator)
1153 llvm::outs() << ':';
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001154 llvm::outs() << Path;
1155 separator = true;
Daniel Dunbard972e222009-03-20 04:37:21 +00001156 }
1157 llvm::outs() << "\n";
Peter Collingbournefa9771f2011-09-06 02:08:31 +00001158 llvm::outs() << "libraries: =" << ResourceDir;
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001159
Sebastian Pop980920a2012-04-16 04:16:43 +00001160 StringRef sysroot = C.getSysRoot();
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001161
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001162 for (const std::string &Path : TC.getFilePaths()) {
1163 // Always print a separator. ResourceDir was the first item shown.
Peter Collingbournefa9771f2011-09-06 02:08:31 +00001164 llvm::outs() << ':';
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001165 // Interpretation of leading '=' is needed only for NetBSD.
1166 if (Path[0] == '=')
Douglas Katzman26eabf62015-06-24 15:10:30 +00001167 llvm::outs() << sysroot << Path.substr(1);
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001168 else
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001169 llvm::outs() << Path;
Daniel Dunbard972e222009-03-20 04:37:21 +00001170 }
1171 llvm::outs() << "\n";
Daniel Dunbar7c925282009-03-31 21:38:17 +00001172 return false;
Daniel Dunbard972e222009-03-20 04:37:21 +00001173 }
1174
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001175 // FIXME: The following handlers should use a callback mechanism, we don't
1176 // know what the client would like to do.
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001177 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001178 llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001179 return false;
1180 }
1181
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001182 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001183 llvm::outs() << GetProgramPath(A->getValue(), TC) << "\n";
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001184 return false;
1185 }
1186
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001187 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
Michal Gorny7cfe4802016-10-10 12:23:40 +00001188 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(C.getArgs());
1189 switch (RLT) {
1190 case ToolChain::RLT_CompilerRT:
1191 llvm::outs() << TC.getCompilerRT(C.getArgs(), "builtins") << "\n";
1192 break;
1193 case ToolChain::RLT_Libgcc:
1194 llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
1195 break;
1196 }
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001197 return false;
1198 }
1199
Daniel Dunbar1b3ec3a2009-06-16 23:25:22 +00001200 if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
Douglas Katzmana34b7bf2015-06-30 19:32:57 +00001201 for (const Multilib &Multilib : TC.getMultilibs())
1202 llvm::outs() << Multilib << "\n";
Daniel Dunbar1b3ec3a2009-06-16 23:25:22 +00001203 return false;
1204 }
1205
Jonathan Roelofs2cea1be2014-02-12 03:21:20 +00001206 if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
Douglas Katzmana34b7bf2015-06-30 19:32:57 +00001207 for (const Multilib &Multilib : TC.getMultilibs()) {
Douglas Katzman6bbffc42015-06-25 18:51:37 +00001208 if (Multilib.gccSuffix().empty())
Jonathan Roelofs2cea1be2014-02-12 03:21:20 +00001209 llvm::outs() << ".\n";
1210 else {
Douglas Katzman6bbffc42015-06-25 18:51:37 +00001211 StringRef Suffix(Multilib.gccSuffix());
Jonathan Roelofs2cea1be2014-02-12 03:21:20 +00001212 assert(Suffix.front() == '/');
1213 llvm::outs() << Suffix.substr(1) << "\n";
1214 }
Jonathan Roelofs3fa96d82014-02-12 01:36:51 +00001215 }
Jonathan Roelofs0e7ec602014-02-12 01:29:25 +00001216 return false;
1217 }
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001218 return true;
1219}
1220
Douglas Katzmanfd528672015-06-11 15:05:22 +00001221// Display an action graph human-readably. Action A is the "sink" node
1222// and latest-occuring action. Traversal is in pre-order, visiting the
1223// inputs to each action before printing the action itself.
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001224static unsigned PrintActions1(const Compilation &C, Action *A,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001225 std::map<Action *, unsigned> &Ids) {
Douglas Katzmanfd528672015-06-11 15:05:22 +00001226 if (Ids.count(A)) // A was already visited.
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001227 return Ids[A];
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001228
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001229 std::string str;
1230 llvm::raw_string_ostream os(str);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001231
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001232 os << Action::getClassName(A->getKind()) << ", ";
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001233 if (InputAction *IA = dyn_cast<InputAction>(A)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001234 os << "\"" << IA->getInputArg().getValue() << "\"";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001235 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001236 os << '"' << BIA->getArchName() << '"' << ", {"
Nico Weber5a459f82016-02-23 19:30:43 +00001237 << PrintActions1(C, *BIA->input_begin(), Ids) << "}";
Samuel Antaod06239d2016-07-15 23:13:27 +00001238 } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
1239 bool IsFirst = true;
1240 OA->doOnEachDependence(
1241 [&](Action *A, const ToolChain *TC, const char *BoundArch) {
1242 // E.g. for two CUDA device dependences whose bound arch is sm_20 and
1243 // sm_35 this will generate:
1244 // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
1245 // (nvptx64-nvidia-cuda:sm_35) {#ID}
1246 if (!IsFirst)
1247 os << ", ";
1248 os << '"';
1249 if (TC)
1250 os << A->getOffloadingKindPrefix();
1251 else
1252 os << "host";
1253 os << " (";
1254 os << TC->getTriple().normalize();
1255
1256 if (BoundArch)
1257 os << ":" << BoundArch;
1258 os << ")";
1259 os << '"';
1260 os << " {" << PrintActions1(C, A, Ids) << "}";
1261 IsFirst = false;
1262 });
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001263 } else {
Samuel Antaod06239d2016-07-15 23:13:27 +00001264 const ActionList *AL = &A->getInputs();
Artem Belevich0ff05cd2015-07-13 23:27:56 +00001265
Artem Belevich23256752015-09-22 17:23:09 +00001266 if (AL->size()) {
1267 const char *Prefix = "{";
1268 for (Action *PreRequisite : *AL) {
1269 os << Prefix << PrintActions1(C, PreRequisite, Ids);
1270 Prefix = ", ";
1271 }
1272 os << "}";
1273 } else
1274 os << "{}";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001275 }
1276
Samuel Antaod06239d2016-07-15 23:13:27 +00001277 // Append offload info for all options other than the offloading action
1278 // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
1279 std::string offload_str;
1280 llvm::raw_string_ostream offload_os(offload_str);
1281 if (!isa<OffloadAction>(A)) {
1282 auto S = A->getOffloadingKindPrefix();
1283 if (!S.empty()) {
1284 offload_os << ", (" << S;
1285 if (A->getOffloadingArch())
1286 offload_os << ", " << A->getOffloadingArch();
1287 offload_os << ")";
1288 }
1289 }
1290
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001291 unsigned Id = Ids.size();
1292 Ids[A] = Id;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001293 llvm::errs() << Id << ": " << os.str() << ", "
Samuel Antaod06239d2016-07-15 23:13:27 +00001294 << types::getTypeName(A->getType()) << offload_os.str() << "\n";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001295
1296 return Id;
1297}
1298
Douglas Katzmanfd528672015-06-11 15:05:22 +00001299// Print the action graphs in a compilation C.
1300// For example "clang -c file1.c file2.c" is composed of two subgraphs.
Daniel Dunbareb843be2009-03-18 03:13:20 +00001301void Driver::PrintActions(const Compilation &C) const {
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001302 std::map<Action *, unsigned> Ids;
1303 for (Action *A : C.getActions())
1304 PrintActions1(C, A, Ids);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001305}
1306
Joerg Sonnenberger5fe4a7d2011-05-06 14:05:11 +00001307/// \brief Check whether the given input tree contains any compilation or
1308/// assembly actions.
1309static bool ContainsCompileOrAssembleAction(const Action *A) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001310 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
Bob Wilson23a55f12014-12-21 07:00:00 +00001311 isa<AssembleJobAction>(A))
Daniel Dunbar00d3d8e2010-06-29 16:38:33 +00001312 return true;
1313
Nico Weber5a459f82016-02-23 19:30:43 +00001314 for (const Action *Input : A->inputs())
Nico Weberfb80f962015-09-19 21:36:51 +00001315 if (ContainsCompileOrAssembleAction(Input))
Daniel Dunbar00d3d8e2010-06-29 16:38:33 +00001316 return true;
1317
1318 return false;
1319}
1320
Artem Belevich5e2a3ec2015-11-17 22:28:40 +00001321void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
1322 const InputList &BAInputs) const {
1323 DerivedArgList &Args = C.getArgs();
1324 ActionList &Actions = C.getActions();
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001325 llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
1326 // Collect the list of architectures. Duplicates are allowed, but should only
1327 // be handled once (in the order seen).
Daniel Dunbare5dc4822009-03-13 20:33:35 +00001328 llvm::StringSet<> ArchNames;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001329 SmallVector<const char *, 4> Archs;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00001330 for (Arg *A : Args) {
Daniel Dunbar0bfb21e2009-11-19 03:26:40 +00001331 if (A->getOption().matches(options::OPT_arch)) {
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001332 // Validate the option here; we don't save the type here because its
1333 // particular spelling may participate in other driver choices.
1334 llvm::Triple::ArchType Arch =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001335 tools::darwin::getArchTypeForMachOArchName(A->getValue());
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001336 if (Arch == llvm::Triple::UnknownArch) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001337 Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001338 continue;
1339 }
1340
Daniel Dunbar2da02722009-03-19 07:55:12 +00001341 A->claim();
David Blaikie61b86d42014-11-19 02:56:13 +00001342 if (ArchNames.insert(A->getValue()).second)
Richard Smithbd55daf2012-11-01 04:30:05 +00001343 Archs.push_back(A->getValue());
Daniel Dunbarf479c122009-03-12 18:40:18 +00001344 }
1345 }
1346
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001347 // When there is no explicit arch for this platform, make sure we still bind
1348 // the architecture (to the default) so that -Xarch_ is handled correctly.
Daniel Dunbareb843be2009-03-18 03:13:20 +00001349 if (!Archs.size())
Daniel Dunbarc3bd9f52012-11-08 03:38:26 +00001350 Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
Daniel Dunbarf479c122009-03-12 18:40:18 +00001351
Daniel Dunbarf479c122009-03-12 18:40:18 +00001352 ActionList SingleActions;
Justin Lebar0f3474c2016-02-11 02:00:50 +00001353 BuildActions(C, Args, BAInputs, SingleActions);
Daniel Dunbarf479c122009-03-12 18:40:18 +00001354
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001355 // Add in arch bindings for every top level action, as well as lipo and
1356 // dsymutil steps if needed.
Nico Weberfb80f962015-09-19 21:36:51 +00001357 for (Action* Act : SingleActions) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001358 // Make sure we can lipo this kind of output. If not (and it is an actual
1359 // output) then we disallow, since we can't create an output file with the
1360 // right name without overwriting it. We could remove this oddity by just
1361 // changing the output names to include the arch, which would also fix
Daniel Dunbarf479c122009-03-12 18:40:18 +00001362 // -save-temps. Compatibility wins for now.
1363
Daniel Dunbare2ca3bd2009-03-13 17:46:02 +00001364 if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
Daniel Dunbarf479c122009-03-12 18:40:18 +00001365 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001366 << types::getTypeName(Act->getType());
Daniel Dunbarf479c122009-03-12 18:40:18 +00001367
1368 ActionList Inputs;
Justin Lebar41094612016-01-11 23:07:27 +00001369 for (unsigned i = 0, e = Archs.size(); i != e; ++i)
1370 Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
Daniel Dunbarf479c122009-03-12 18:40:18 +00001371
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001372 // Lipo if necessary, we do it this way because we need to set the arch flag
1373 // so that -Xarch_ gets overwritten.
Daniel Dunbarf479c122009-03-12 18:40:18 +00001374 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
1375 Actions.append(Inputs.begin(), Inputs.end());
1376 else
Justin Lebar41094612016-01-11 23:07:27 +00001377 Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001378
Eric Christopher65c05fa2012-02-06 19:43:51 +00001379 // Handle debug info queries.
1380 Arg *A = Args.getLastArg(options::OPT_g_Group);
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001381 if (A && !A->getOption().matches(options::OPT_g0) &&
1382 !A->getOption().matches(options::OPT_gstabs) &&
1383 ContainsCompileOrAssembleAction(Actions.back())) {
Chad Rosier62135492012-07-09 17:31:28 +00001384
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001385 // Add a 'dsymutil' step if necessary, when debug info is enabled and we
1386 // have a compile input. We need to run 'dsymutil' ourselves in such cases
Eric Christopher776c26f2013-01-28 17:39:03 +00001387 // because the debug info will refer to a temporary object file which
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001388 // will be removed at the end of the compilation process.
1389 if (Act->getType() == types::TY_Image) {
1390 ActionList Inputs;
1391 Inputs.push_back(Actions.back());
1392 Actions.pop_back();
Justin Lebar41094612016-01-11 23:07:27 +00001393 Actions.push_back(
1394 C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001395 }
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001396
Ben Langmuir9b9a8d32014-02-06 18:53:25 +00001397 // Verify the debug info output.
Alp Tokere9d2bfc2014-01-17 02:06:23 +00001398 if (Args.hasArg(options::OPT_verify_debug_info)) {
Justin Lebar41094612016-01-11 23:07:27 +00001399 Action* LastAction = Actions.back();
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001400 Actions.pop_back();
Justin Lebar41094612016-01-11 23:07:27 +00001401 Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
1402 LastAction, types::TY_Nothing));
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001403 }
1404 }
Daniel Dunbarf479c122009-03-12 18:40:18 +00001405 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001406}
1407
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001408/// \brief Check that the file referenced by Value exists. If it doesn't,
1409/// issue a diagnostic and return false.
Alp Toker8c8a8752013-12-03 06:53:35 +00001410static bool DiagnoseInputExistence(const Driver &D, const DerivedArgList &Args,
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001411 StringRef Value, types::ID Ty) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001412 if (!D.getCheckInputsExist())
1413 return true;
1414
1415 // stdin always exists.
1416 if (Value == "-")
1417 return true;
1418
1419 SmallString<64> Path(Value);
1420 if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
Yaron Keren92e1b622015-03-18 10:17:07 +00001421 if (!llvm::sys::path::is_absolute(Path)) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001422 SmallString<64> Directory(WorkDir->getValue());
1423 llvm::sys::path::append(Directory, Value);
1424 Path.assign(Directory);
1425 }
1426 }
1427
1428 if (llvm::sys::fs::exists(Twine(Path)))
1429 return true;
1430
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001431 if (D.IsCLMode()) {
1432 if (!llvm::sys::path::is_absolute(Twine(Path)) &&
1433 llvm::sys::Process::FindInEnvPath("LIB", Value))
1434 return true;
1435
1436 if (Args.hasArg(options::OPT__SLASH_link) && Ty == types::TY_Object) {
1437 // Arguments to the /link flag might cause the linker to search for object
1438 // and library files in paths we don't know about. Don't error in such
1439 // cases.
1440 return true;
1441 }
1442 }
Hans Wennborg23d26a32014-06-18 17:21:50 +00001443
Yaron Keren92e1b622015-03-18 10:17:07 +00001444 D.Diag(clang::diag::err_drv_no_such_file) << Path;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001445 return false;
1446}
1447
Chad Rosierecdede82011-08-12 22:08:57 +00001448// Construct a the list of inputs and their types.
Hans Wennborg55362852014-05-02 22:55:30 +00001449void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
Chad Rosierecdede82011-08-12 22:08:57 +00001450 InputList &Inputs) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001451 // Track the current user specified (-x) input. We also explicitly track the
1452 // argument used to set the type; we only want to claim the type when we
1453 // actually use it, so we warn about unused -x arguments.
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00001454 types::ID InputType = types::TY_Nothing;
Craig Topper92fc2df2014-05-17 16:56:41 +00001455 Arg *InputTypeArg = nullptr;
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00001456
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001457 // The last /TC or /TP option sets the input type to C or C++ globally.
Ehsan Akhgaric249abb2014-09-12 21:44:24 +00001458 if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
1459 options::OPT__SLASH_TP)) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001460 InputTypeArg = TCTP;
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001461 InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001462 ? types::TY_C
1463 : types::TY_CXX;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001464
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001465 arg_iterator it =
1466 Args.filtered_begin(options::OPT__SLASH_TC, options::OPT__SLASH_TP);
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001467 const arg_iterator ie = Args.filtered_end();
1468 Arg *Previous = *it++;
1469 bool ShowNote = false;
1470 while (it != ie) {
Hans Wennborgd9ad0682013-09-11 16:38:41 +00001471 Diag(clang::diag::warn_drv_overriding_flag_option)
1472 << Previous->getSpelling() << (*it)->getSpelling();
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001473 Previous = *it++;
1474 ShowNote = true;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001475 }
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001476 if (ShowNote)
1477 Diag(clang::diag::note_drv_t_option_is_global);
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001478
1479 // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
1480 assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
1481 }
1482
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00001483 for (Arg *A : Args) {
Michael J. Spencerad3ccc32012-08-20 21:41:17 +00001484 if (A->getOption().getKind() == Option::InputClass) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001485 const char *Value = A->getValue();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001486 types::ID Ty = types::TY_INVALID;
1487
1488 // Infer the input type if necessary.
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00001489 if (InputType == types::TY_Nothing) {
1490 // If there was an explicit arg for this, claim it.
1491 if (InputTypeArg)
1492 InputTypeArg->claim();
1493
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001494 // stdin must be handled specially.
1495 if (memcmp(Value, "-", 2) == 0) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001496 // If running with -E, treat as a C input (this changes the builtin
1497 // macros, for example). This may be overridden by -ObjC below.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001498 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001499 // Otherwise emit an error but still use a valid type to avoid
1500 // spurious errors (e.g., no inputs).
Hans Wennborg70850d82013-07-18 20:29:38 +00001501 if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
Hans Wennborgcfdd8b52014-01-29 01:04:40 +00001502 Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
1503 : clang::diag::err_drv_unknown_stdin_type);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001504 Ty = types::TY_C;
1505 } else {
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00001506 // Otherwise lookup by extension.
1507 // Fallback is C if invoked as C preprocessor or Object otherwise.
1508 // We use a host hook here because Darwin at least has its own
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001509 // idea of what .s is.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001510 if (const char *Ext = strrchr(Value, '.'))
Daniel Dunbarcc7df6c2010-08-02 05:43:56 +00001511 Ty = TC.LookupTypeForExtension(Ext + 1);
Daniel Dunbarea9f0322009-03-20 23:39:23 +00001512
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00001513 if (Ty == types::TY_INVALID) {
Hans Wennborg70850d82013-07-18 20:29:38 +00001514 if (CCCIsCPP())
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00001515 Ty = types::TY_C;
1516 else
1517 Ty = types::TY_Object;
1518 }
Daniel Dunbar0ac94452010-02-17 20:32:58 +00001519
1520 // If the driver is invoked as C++ compiler (like clang++ or c++) it
1521 // should autodetect some input files as C++ for g++ compatibility.
Hans Wennborg70850d82013-07-18 20:29:38 +00001522 if (CCCIsCXX()) {
Daniel Dunbar0ac94452010-02-17 20:32:58 +00001523 types::ID OldTy = Ty;
1524 Ty = types::lookupCXXTypeForCType(Ty);
1525
1526 if (Ty != OldTy)
1527 Diag(clang::diag::warn_drv_treating_input_as_cxx)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001528 << getTypeName(OldTy) << getTypeName(Ty);
Daniel Dunbar0ac94452010-02-17 20:32:58 +00001529 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001530 }
1531
Daniel Dunbar82b22102009-05-18 21:47:54 +00001532 // -ObjC and -ObjC++ override the default language, but only for "source
1533 // files". We just treat everything that isn't a linker input as a
1534 // source file.
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001535 //
Daniel Dunbar82b22102009-05-18 21:47:54 +00001536 // FIXME: Clean this up if we move the phase sequence into the type.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001537 if (Ty != types::TY_Object) {
1538 if (Args.hasArg(options::OPT_ObjC))
1539 Ty = types::TY_ObjC;
1540 else if (Args.hasArg(options::OPT_ObjCXX))
1541 Ty = types::TY_ObjCXX;
1542 }
1543 } else {
1544 assert(InputTypeArg && "InputType set w/o InputTypeArg");
Ehsan Akhgari7e954ea2014-09-12 18:15:10 +00001545 if (!InputTypeArg->getOption().matches(options::OPT_x)) {
1546 // If emulating cl.exe, make sure that /TC and /TP don't affect input
1547 // object files.
1548 const char *Ext = strrchr(Value, '.');
1549 if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
1550 Ty = types::TY_Object;
1551 }
1552 if (Ty == types::TY_INVALID) {
1553 Ty = InputType;
1554 InputTypeArg->claim();
1555 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001556 }
1557
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001558 if (DiagnoseInputExistence(*this, Args, Value, Ty))
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001559 Inputs.push_back(std::make_pair(Ty, A));
1560
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001561 } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
1562 StringRef Value = A->getValue();
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001563 if (DiagnoseInputExistence(*this, Args, Value, types::TY_C)) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001564 Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
1565 Inputs.push_back(std::make_pair(types::TY_C, InputArg));
1566 }
1567 A->claim();
1568 } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
1569 StringRef Value = A->getValue();
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001570 if (DiagnoseInputExistence(*this, Args, Value, types::TY_CXX)) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001571 Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
1572 Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
1573 }
1574 A->claim();
Michael J. Spencer66e2b202012-10-19 22:37:06 +00001575 } else if (A->getOption().hasFlag(options::LinkerInput)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001576 // Just treat as object type, we could make a special type for this if
1577 // necessary.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001578 Inputs.push_back(std::make_pair(types::TY_Object, A));
1579
Daniel Dunbar0bfb21e2009-11-19 03:26:40 +00001580 } else if (A->getOption().matches(options::OPT_x)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001581 InputTypeArg = A;
Richard Smithbd55daf2012-11-01 04:30:05 +00001582 InputType = types::lookupTypeForTypeSpecifier(A->getValue());
Chad Rosier706c2352012-04-07 00:01:31 +00001583 A->claim();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001584
1585 // Follow gcc behavior and treat as linker input for invalid -x
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001586 // options. Its not clear why we shouldn't just revert to unknown; but
Michael J. Spencer1a4fe8c2010-12-17 21:22:33 +00001587 // this isn't very important, we might as well be bug compatible.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001588 if (!InputType) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001589 Diag(clang::diag::err_drv_unknown_language) << A->getValue();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001590 InputType = types::TY_Object;
1591 }
1592 }
1593 }
Hans Wennborg70850d82013-07-18 20:29:38 +00001594 if (CCCIsCPP() && Inputs.empty()) {
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00001595 // If called as standalone preprocessor, stdin is processed
1596 // if no other input is present.
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001597 Arg *A = MakeInputArg(Args, Opts, "-");
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00001598 Inputs.push_back(std::make_pair(types::TY_C, A));
1599 }
Chad Rosierecdede82011-08-12 22:08:57 +00001600}
1601
Samuel Antao64e965e2016-09-30 15:34:19 +00001602namespace {
1603/// Provides a convenient interface for different programming models to generate
1604/// the required device actions.
1605class OffloadingActionBuilder final {
1606 /// Flag used to trace errors in the builder.
1607 bool IsValid = false;
1608
1609 /// The compilation that is using this builder.
1610 Compilation &C;
1611
Samuel Antao64e965e2016-09-30 15:34:19 +00001612 /// Map between an input argument and the offload kinds used to process it.
1613 std::map<const Arg *, unsigned> InputArgToOffloadKindMap;
1614
1615 /// Builder interface. It doesn't build anything or keep any state.
1616 class DeviceActionBuilder {
1617 public:
1618 typedef llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PhasesTy;
1619
1620 enum ActionBuilderReturnCode {
1621 // The builder acted successfully on the current action.
1622 ABRT_Success,
1623 // The builder didn't have to act on the current action.
1624 ABRT_Inactive,
1625 // The builder was successful and requested the host action to not be
1626 // generated.
1627 ABRT_Ignore_Host,
1628 };
1629
1630 protected:
1631 /// Compilation associated with this builder.
1632 Compilation &C;
1633
1634 /// Tool chains associated with this builder. The same programming
1635 /// model may have associated one or more tool chains.
1636 SmallVector<const ToolChain *, 2> ToolChains;
1637
1638 /// The derived arguments associated with this builder.
1639 DerivedArgList &Args;
1640
1641 /// The inputs associated with this builder.
1642 const Driver::InputList &Inputs;
1643
1644 /// The associated offload kind.
1645 Action::OffloadKind AssociatedOffloadKind = Action::OFK_None;
1646
1647 public:
1648 DeviceActionBuilder(Compilation &C, DerivedArgList &Args,
1649 const Driver::InputList &Inputs,
1650 Action::OffloadKind AssociatedOffloadKind)
1651 : C(C), Args(Args), Inputs(Inputs),
1652 AssociatedOffloadKind(AssociatedOffloadKind) {}
1653 virtual ~DeviceActionBuilder() {}
1654
1655 /// Fill up the array \a DA with all the device dependences that should be
1656 /// added to the provided host action \a HostAction. By default it is
1657 /// inactive.
1658 virtual ActionBuilderReturnCode
Samuel Antao28c4f182016-10-27 17:08:03 +00001659 getDeviceDependences(OffloadAction::DeviceDependences &DA,
1660 phases::ID CurPhase, phases::ID FinalPhase,
1661 PhasesTy &Phases) {
Samuel Antao64e965e2016-09-30 15:34:19 +00001662 return ABRT_Inactive;
1663 }
1664
1665 /// Update the state to include the provided host action \a HostAction as a
1666 /// dependency of the current device action. By default it is inactive.
1667 virtual ActionBuilderReturnCode addDeviceDepences(Action *HostAction) {
1668 return ABRT_Inactive;
1669 }
1670
1671 /// Append top level actions generated by the builder. Return true if errors
1672 /// were found.
1673 virtual void appendTopLevelActions(ActionList &AL) {}
1674
1675 /// Append linker actions generated by the builder. Return true if errors
1676 /// were found.
1677 virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {}
1678
1679 /// Initialize the builder. Return true if any initialization errors are
1680 /// found.
1681 virtual bool initialize() { return false; }
1682
Samuel Antao69d6f312016-10-27 17:50:43 +00001683 /// Return true if the builder can use bundling/unbundling.
1684 virtual bool canUseBundlerUnbundler() const { return false; }
1685
Samuel Antao64e965e2016-09-30 15:34:19 +00001686 /// Return true if this builder is valid. We have a valid builder if we have
1687 /// associated device tool chains.
1688 bool isValid() { return !ToolChains.empty(); }
1689
1690 /// Return the associated offload kind.
1691 Action::OffloadKind getAssociatedOffloadKind() {
1692 return AssociatedOffloadKind;
1693 }
1694 };
1695
1696 /// \brief CUDA action builder. It injects device code in the host backend
1697 /// action.
1698 class CudaActionBuilder final : public DeviceActionBuilder {
1699 /// Flags to signal if the user requested host-only or device-only
1700 /// compilation.
1701 bool CompileHostOnly = false;
1702 bool CompileDeviceOnly = false;
1703
1704 /// List of GPU architectures to use in this compilation.
1705 SmallVector<CudaArch, 4> GpuArchList;
1706
1707 /// The CUDA actions for the current input.
1708 ActionList CudaDeviceActions;
1709
1710 /// The CUDA fat binary if it was generated for the current input.
1711 Action *CudaFatBinary = nullptr;
1712
1713 /// Flag that is set to true if this builder acted on the current input.
1714 bool IsActive = false;
1715
1716 public:
1717 CudaActionBuilder(Compilation &C, DerivedArgList &Args,
1718 const Driver::InputList &Inputs)
1719 : DeviceActionBuilder(C, Args, Inputs, Action::OFK_Cuda) {}
1720
1721 ActionBuilderReturnCode
Samuel Antao28c4f182016-10-27 17:08:03 +00001722 getDeviceDependences(OffloadAction::DeviceDependences &DA,
1723 phases::ID CurPhase, phases::ID FinalPhase,
1724 PhasesTy &Phases) override {
Samuel Antao64e965e2016-09-30 15:34:19 +00001725 if (!IsActive)
1726 return ABRT_Inactive;
1727
1728 // If we don't have more CUDA actions, we don't have any dependences to
1729 // create for the host.
1730 if (CudaDeviceActions.empty())
1731 return ABRT_Success;
1732
1733 assert(CudaDeviceActions.size() == GpuArchList.size() &&
1734 "Expecting one action per GPU architecture.");
1735 assert(!CompileHostOnly &&
1736 "Not expecting CUDA actions in host-only compilation.");
1737
1738 // If we are generating code for the device or we are in a backend phase,
1739 // we attempt to generate the fat binary. We compile each arch to ptx and
1740 // assemble to cubin, then feed the cubin *and* the ptx into a device
1741 // "link" action, which uses fatbinary to combine these cubins into one
1742 // fatbin. The fatbin is then an input to the host action if not in
1743 // device-only mode.
1744 if (CompileDeviceOnly || CurPhase == phases::Backend) {
1745 ActionList DeviceActions;
1746 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
1747 // Produce the device action from the current phase up to the assemble
1748 // phase.
1749 for (auto Ph : Phases) {
1750 // Skip the phases that were already dealt with.
1751 if (Ph < CurPhase)
1752 continue;
1753 // We have to be consistent with the host final phase.
1754 if (Ph > FinalPhase)
1755 break;
1756
1757 CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction(
1758 C, Args, Ph, CudaDeviceActions[I]);
1759
1760 if (Ph == phases::Assemble)
1761 break;
1762 }
1763
1764 // If we didn't reach the assemble phase, we can't generate the fat
1765 // binary. We don't need to generate the fat binary if we are not in
1766 // device-only mode.
1767 if (!isa<AssembleJobAction>(CudaDeviceActions[I]) ||
1768 CompileDeviceOnly)
1769 continue;
1770
1771 Action *AssembleAction = CudaDeviceActions[I];
1772 assert(AssembleAction->getType() == types::TY_Object);
1773 assert(AssembleAction->getInputs().size() == 1);
1774
1775 Action *BackendAction = AssembleAction->getInputs()[0];
1776 assert(BackendAction->getType() == types::TY_PP_Asm);
1777
1778 for (auto &A : {AssembleAction, BackendAction}) {
1779 OffloadAction::DeviceDependences DDep;
1780 DDep.add(*A, *ToolChains.front(), CudaArchToString(GpuArchList[I]),
1781 Action::OFK_Cuda);
1782 DeviceActions.push_back(
1783 C.MakeAction<OffloadAction>(DDep, A->getType()));
1784 }
1785 }
1786
1787 // We generate the fat binary if we have device input actions.
1788 if (!DeviceActions.empty()) {
1789 CudaFatBinary =
1790 C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN);
1791
1792 if (!CompileDeviceOnly) {
1793 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
1794 Action::OFK_Cuda);
1795 // Clear the fat binary, it is already a dependence to an host
1796 // action.
1797 CudaFatBinary = nullptr;
1798 }
1799
1800 // Remove the CUDA actions as they are already connected to an host
1801 // action or fat binary.
1802 CudaDeviceActions.clear();
1803 }
1804
1805 // We avoid creating host action in device-only mode.
1806 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
Samuel Antao5b1a89a2016-10-27 00:53:34 +00001807 } else if (CurPhase > phases::Backend) {
1808 // If we are past the backend phase and still have a device action, we
1809 // don't have to do anything as this action is already a device
1810 // top-level action.
1811 return ABRT_Success;
Samuel Antao64e965e2016-09-30 15:34:19 +00001812 }
1813
1814 assert(CurPhase < phases::Backend && "Generating single CUDA "
1815 "instructions should only occur "
1816 "before the backend phase!");
1817
1818 // By default, we produce an action for each device arch.
1819 for (Action *&A : CudaDeviceActions)
1820 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
1821
1822 return ABRT_Success;
1823 }
1824
1825 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
1826 // While generating code for CUDA, we only depend on the host input action
1827 // to trigger the creation of all the CUDA device actions.
1828
1829 // If we are dealing with an input action, replicate it for each GPU
1830 // architecture. If we are in host-only mode we return 'success' so that
1831 // the host uses the CUDA offload kind.
1832 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
1833 assert(!GpuArchList.empty() &&
1834 "We should have at least one GPU architecture.");
1835
1836 // If the host input is not CUDA, we don't need to bother about this
1837 // input.
1838 if (IA->getType() != types::TY_CUDA) {
1839 // The builder will ignore this input.
1840 IsActive = false;
1841 return ABRT_Inactive;
1842 }
1843
1844 // Set the flag to true, so that the builder acts on the current input.
1845 IsActive = true;
1846
1847 if (CompileHostOnly)
1848 return ABRT_Success;
1849
1850 // Replicate inputs for each GPU architecture.
1851 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
1852 CudaDeviceActions.push_back(C.MakeAction<InputAction>(
1853 IA->getInputArg(), types::TY_CUDA_DEVICE));
1854
1855 return ABRT_Success;
1856 }
1857
1858 return IsActive ? ABRT_Success : ABRT_Inactive;
1859 }
1860
1861 void appendTopLevelActions(ActionList &AL) override {
1862 // Utility to append actions to the top level list.
1863 auto AddTopLevel = [&](Action *A, CudaArch BoundArch) {
1864 OffloadAction::DeviceDependences Dep;
1865 Dep.add(*A, *ToolChains.front(), CudaArchToString(BoundArch),
1866 Action::OFK_Cuda);
1867 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
1868 };
1869
1870 // If we have a fat binary, add it to the list.
1871 if (CudaFatBinary) {
1872 AddTopLevel(CudaFatBinary, CudaArch::UNKNOWN);
1873 CudaDeviceActions.clear();
1874 CudaFatBinary = nullptr;
1875 return;
1876 }
1877
1878 if (CudaDeviceActions.empty())
1879 return;
1880
1881 // If we have CUDA actions at this point, that's because we have a have
1882 // partial compilation, so we should have an action for each GPU
1883 // architecture.
1884 assert(CudaDeviceActions.size() == GpuArchList.size() &&
1885 "Expecting one action per GPU architecture.");
1886 assert(ToolChains.size() == 1 &&
1887 "Expecting to have a sing CUDA toolchain.");
1888 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
1889 AddTopLevel(CudaDeviceActions[I], GpuArchList[I]);
1890
1891 CudaDeviceActions.clear();
1892 }
1893
1894 bool initialize() override {
1895 // We don't need to support CUDA.
1896 if (!C.hasOffloadToolChain<Action::OFK_Cuda>())
1897 return false;
1898
1899 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
1900 assert(HostTC && "No toolchain for host compilation.");
1901 if (HostTC->getTriple().isNVPTX()) {
1902 // We do not support targeting NVPTX for host compilation. Throw
1903 // an error and abort pipeline construction early so we don't trip
1904 // asserts that assume device-side compilation.
1905 C.getDriver().Diag(diag::err_drv_cuda_nvptx_host);
1906 return true;
1907 }
1908
1909 ToolChains.push_back(C.getSingleOffloadToolChain<Action::OFK_Cuda>());
1910
1911 Arg *PartialCompilationArg = Args.getLastArg(
1912 options::OPT_cuda_host_only, options::OPT_cuda_device_only,
1913 options::OPT_cuda_compile_host_device);
1914 CompileHostOnly = PartialCompilationArg &&
1915 PartialCompilationArg->getOption().matches(
1916 options::OPT_cuda_host_only);
1917 CompileDeviceOnly = PartialCompilationArg &&
1918 PartialCompilationArg->getOption().matches(
1919 options::OPT_cuda_device_only);
1920
1921 // Collect all cuda_gpu_arch parameters, removing duplicates.
Artem Belevicha424e882016-12-09 22:59:17 +00001922 std::set<CudaArch> GpuArchs;
Samuel Antao64e965e2016-09-30 15:34:19 +00001923 bool Error = false;
1924 for (Arg *A : Args) {
Artem Belevicha424e882016-12-09 22:59:17 +00001925 if (!(A->getOption().matches(options::OPT_cuda_gpu_arch_EQ) ||
1926 A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ)))
Samuel Antao64e965e2016-09-30 15:34:19 +00001927 continue;
1928 A->claim();
1929
Artem Belevicha424e882016-12-09 22:59:17 +00001930 const StringRef ArchStr = A->getValue();
1931 if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ) &&
1932 ArchStr == "all") {
1933 GpuArchs.clear();
1934 continue;
1935 }
Samuel Antao64e965e2016-09-30 15:34:19 +00001936 CudaArch Arch = StringToCudaArch(ArchStr);
1937 if (Arch == CudaArch::UNKNOWN) {
1938 C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
1939 Error = true;
Artem Belevicha424e882016-12-09 22:59:17 +00001940 } else if (A->getOption().matches(options::OPT_cuda_gpu_arch_EQ))
1941 GpuArchs.insert(Arch);
1942 else if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ))
1943 GpuArchs.erase(Arch);
1944 else
1945 llvm_unreachable("Unexpected option.");
Samuel Antao64e965e2016-09-30 15:34:19 +00001946 }
1947
Artem Belevicha424e882016-12-09 22:59:17 +00001948 // Collect list of GPUs remaining in the set.
1949 for (CudaArch Arch : GpuArchs)
1950 GpuArchList.push_back(Arch);
1951
1952 // Default to sm_20 which is the lowest common denominator for
1953 // supported GPUs. sm_20 code should work correctly, if
1954 // suboptimally, on all newer GPUs.
Samuel Antao64e965e2016-09-30 15:34:19 +00001955 if (GpuArchList.empty())
1956 GpuArchList.push_back(CudaArch::SM_20);
1957
1958 return Error;
1959 }
1960 };
1961
Samuel Antao28c4f182016-10-27 17:08:03 +00001962 /// OpenMP action builder. The host bitcode is passed to the device frontend
1963 /// and all the device linked images are passed to the host link phase.
1964 class OpenMPActionBuilder final : public DeviceActionBuilder {
1965 /// The OpenMP actions for the current input.
1966 ActionList OpenMPDeviceActions;
1967
1968 /// The linker inputs obtained for each toolchain.
1969 SmallVector<ActionList, 8> DeviceLinkerInputs;
1970
1971 public:
1972 OpenMPActionBuilder(Compilation &C, DerivedArgList &Args,
1973 const Driver::InputList &Inputs)
1974 : DeviceActionBuilder(C, Args, Inputs, Action::OFK_OpenMP) {}
1975
1976 ActionBuilderReturnCode
1977 getDeviceDependences(OffloadAction::DeviceDependences &DA,
1978 phases::ID CurPhase, phases::ID FinalPhase,
1979 PhasesTy &Phases) override {
1980
1981 // We should always have an action for each input.
1982 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
1983 "Number of OpenMP actions and toolchains do not match.");
1984
1985 // The host only depends on device action in the linking phase, when all
1986 // the device images have to be embedded in the host image.
1987 if (CurPhase == phases::Link) {
1988 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
1989 "Toolchains and linker inputs sizes do not match.");
1990 auto LI = DeviceLinkerInputs.begin();
1991 for (auto *A : OpenMPDeviceActions) {
1992 LI->push_back(A);
1993 ++LI;
1994 }
1995
1996 // We passed the device action as a host dependence, so we don't need to
1997 // do anything else with them.
1998 OpenMPDeviceActions.clear();
1999 return ABRT_Success;
2000 }
2001
2002 // By default, we produce an action for each device arch.
2003 for (Action *&A : OpenMPDeviceActions)
2004 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2005
2006 return ABRT_Success;
2007 }
2008
2009 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2010
2011 // If this is an input action replicate it for each OpenMP toolchain.
2012 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2013 OpenMPDeviceActions.clear();
2014 for (unsigned I = 0; I < ToolChains.size(); ++I)
2015 OpenMPDeviceActions.push_back(
2016 C.MakeAction<InputAction>(IA->getInputArg(), IA->getType()));
2017 return ABRT_Success;
2018 }
2019
Samuel Antaofab4f372016-10-27 18:00:51 +00002020 // If this is an unbundling action use it as is for each OpenMP toolchain.
2021 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2022 OpenMPDeviceActions.clear();
2023 for (unsigned I = 0; I < ToolChains.size(); ++I) {
2024 OpenMPDeviceActions.push_back(UA);
2025 UA->registerDependentActionInfo(
2026 ToolChains[I], /*BoundArch=*/StringRef(), Action::OFK_OpenMP);
2027 }
2028 return ABRT_Success;
2029 }
2030
Samuel Antao28c4f182016-10-27 17:08:03 +00002031 // When generating code for OpenMP we use the host compile phase result as
2032 // a dependence to the device compile phase so that it can learn what
2033 // declarations should be emitted. However, this is not the only use for
2034 // the host action, so we prevent it from being collapsed.
2035 if (isa<CompileJobAction>(HostAction)) {
2036 HostAction->setCannotBeCollapsedWithNextDependentAction();
2037 assert(ToolChains.size() == OpenMPDeviceActions.size() &&
2038 "Toolchains and device action sizes do not match.");
2039 OffloadAction::HostDependence HDep(
2040 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2041 /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2042 auto TC = ToolChains.begin();
2043 for (Action *&A : OpenMPDeviceActions) {
2044 assert(isa<CompileJobAction>(A));
2045 OffloadAction::DeviceDependences DDep;
2046 DDep.add(*A, **TC, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2047 A = C.MakeAction<OffloadAction>(HDep, DDep);
2048 ++TC;
2049 }
2050 }
2051 return ABRT_Success;
2052 }
2053
Samuel Antao69d6f312016-10-27 17:50:43 +00002054 void appendTopLevelActions(ActionList &AL) override {
2055 if (OpenMPDeviceActions.empty())
2056 return;
2057
2058 // We should always have an action for each input.
2059 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2060 "Number of OpenMP actions and toolchains do not match.");
2061
2062 // Append all device actions followed by the proper offload action.
2063 auto TI = ToolChains.begin();
2064 for (auto *A : OpenMPDeviceActions) {
2065 OffloadAction::DeviceDependences Dep;
2066 Dep.add(*A, **TI, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2067 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2068 ++TI;
2069 }
2070 // We no longer need the action stored in this builder.
2071 OpenMPDeviceActions.clear();
2072 }
2073
Samuel Antao28c4f182016-10-27 17:08:03 +00002074 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {
2075 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2076 "Toolchains and linker inputs sizes do not match.");
2077
2078 // Append a new link action for each device.
2079 auto TC = ToolChains.begin();
2080 for (auto &LI : DeviceLinkerInputs) {
2081 auto *DeviceLinkAction =
2082 C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2083 DA.add(*DeviceLinkAction, **TC, /*BoundArch=*/nullptr,
2084 Action::OFK_OpenMP);
2085 ++TC;
2086 }
2087 }
2088
2089 bool initialize() override {
2090 // Get the OpenMP toolchains. If we don't get any, the action builder will
2091 // know there is nothing to do related to OpenMP offloading.
2092 auto OpenMPTCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
2093 for (auto TI = OpenMPTCRange.first, TE = OpenMPTCRange.second; TI != TE;
2094 ++TI)
2095 ToolChains.push_back(TI->second);
2096
2097 DeviceLinkerInputs.resize(ToolChains.size());
2098 return false;
2099 }
Samuel Antao69d6f312016-10-27 17:50:43 +00002100
2101 bool canUseBundlerUnbundler() const override {
2102 // OpenMP should use bundled files whenever possible.
2103 return true;
2104 }
Samuel Antao28c4f182016-10-27 17:08:03 +00002105 };
2106
2107 ///
2108 /// TODO: Add the implementation for other specialized builders here.
2109 ///
Samuel Antao64e965e2016-09-30 15:34:19 +00002110
2111 /// Specialized builders being used by this offloading action builder.
2112 SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders;
2113
Samuel Antao69d6f312016-10-27 17:50:43 +00002114 /// Flag set to true if all valid builders allow file bundling/unbundling.
2115 bool CanUseBundler;
2116
Samuel Antao64e965e2016-09-30 15:34:19 +00002117public:
2118 OffloadingActionBuilder(Compilation &C, DerivedArgList &Args,
2119 const Driver::InputList &Inputs)
Samuel Antao10e905c2016-10-27 01:08:58 +00002120 : C(C) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002121 // Create a specialized builder for each device toolchain.
2122
2123 IsValid = true;
2124
2125 // Create a specialized builder for CUDA.
2126 SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs));
2127
Samuel Antao28c4f182016-10-27 17:08:03 +00002128 // Create a specialized builder for OpenMP.
2129 SpecializedBuilders.push_back(new OpenMPActionBuilder(C, Args, Inputs));
2130
Samuel Antao64e965e2016-09-30 15:34:19 +00002131 //
2132 // TODO: Build other specialized builders here.
2133 //
2134
Samuel Antao69d6f312016-10-27 17:50:43 +00002135 // Initialize all the builders, keeping track of errors. If all valid
2136 // builders agree that we can use bundling, set the flag to true.
2137 unsigned ValidBuilders = 0u;
2138 unsigned ValidBuildersSupportingBundling = 0u;
2139 for (auto *SB : SpecializedBuilders) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002140 IsValid = IsValid && !SB->initialize();
Samuel Antao69d6f312016-10-27 17:50:43 +00002141
2142 // Update the counters if the builder is valid.
2143 if (SB->isValid()) {
2144 ++ValidBuilders;
2145 if (SB->canUseBundlerUnbundler())
2146 ++ValidBuildersSupportingBundling;
2147 }
2148 }
2149 CanUseBundler =
2150 ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling;
Artem Belevichf981e30b2016-08-02 22:37:47 +00002151 }
Justin Lebardc3c5042016-04-19 02:27:07 +00002152
Samuel Antao64e965e2016-09-30 15:34:19 +00002153 ~OffloadingActionBuilder() {
2154 for (auto *SB : SpecializedBuilders)
2155 delete SB;
Samuel Antaod06239d2016-07-15 23:13:27 +00002156 }
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002157
Samuel Antao64e965e2016-09-30 15:34:19 +00002158 /// Generate an action that adds device dependences (if any) to a host action.
2159 /// If no device dependence actions exist, just return the host action \a
2160 /// HostAction. If an error is found or if no builder requires the host action
2161 /// to be generated, return nullptr.
2162 Action *
2163 addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg,
2164 phases::ID CurPhase, phases::ID FinalPhase,
2165 DeviceActionBuilder::PhasesTy &Phases) {
2166 if (!IsValid)
2167 return nullptr;
Justin Lebar7bf77982016-01-11 23:27:13 +00002168
Samuel Antao64e965e2016-09-30 15:34:19 +00002169 if (SpecializedBuilders.empty())
2170 return HostAction;
2171
2172 assert(HostAction && "Invalid host action!");
2173
2174 OffloadAction::DeviceDependences DDeps;
2175 // Check if all the programming models agree we should not emit the host
2176 // action. Also, keep track of the offloading kinds employed.
2177 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2178 unsigned InactiveBuilders = 0u;
2179 unsigned IgnoringBuilders = 0u;
2180 for (auto *SB : SpecializedBuilders) {
2181 if (!SB->isValid()) {
2182 ++InactiveBuilders;
2183 continue;
2184 }
2185
Samuel Antao28c4f182016-10-27 17:08:03 +00002186 auto RetCode =
2187 SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases);
Samuel Antao64e965e2016-09-30 15:34:19 +00002188
2189 // If the builder explicitly says the host action should be ignored,
2190 // we need to increment the variable that tracks the builders that request
2191 // the host object to be ignored.
2192 if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host)
2193 ++IgnoringBuilders;
2194
2195 // Unless the builder was inactive for this action, we have to record the
2196 // offload kind because the host will have to use it.
2197 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2198 OffloadKind |= SB->getAssociatedOffloadKind();
2199 }
2200
2201 // If all builders agree that the host object should be ignored, just return
2202 // nullptr.
2203 if (IgnoringBuilders &&
2204 SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders))
2205 return nullptr;
2206
2207 if (DDeps.getActions().empty())
2208 return HostAction;
2209
2210 // We have dependences we need to bundle together. We use an offload action
2211 // for that.
2212 OffloadAction::HostDependence HDep(
2213 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2214 /*BoundArch=*/nullptr, DDeps);
2215 return C.MakeAction<OffloadAction>(HDep, DDeps);
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002216 }
2217
Samuel Antao64e965e2016-09-30 15:34:19 +00002218 /// Generate an action that adds a host dependence to a device action. The
2219 /// results will be kept in this action builder. Return true if an error was
2220 /// found.
Samuel Antaofab4f372016-10-27 18:00:51 +00002221 bool addHostDependenceToDeviceActions(Action *&HostAction,
Samuel Antao64e965e2016-09-30 15:34:19 +00002222 const Arg *InputArg) {
2223 if (!IsValid)
2224 return true;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002225
Samuel Antaofab4f372016-10-27 18:00:51 +00002226 // If we are supporting bundling/unbundling and the current action is an
2227 // input action of non-source file, we replace the host action by the
2228 // unbundling action. The bundler tool has the logic to detect if an input
2229 // is a bundle or not and if the input is not a bundle it assumes it is a
2230 // host file. Therefore it is safe to create an unbundling action even if
2231 // the input is not a bundle.
2232 if (CanUseBundler && isa<InputAction>(HostAction) &&
2233 InputArg->getOption().getKind() == llvm::opt::Option::InputClass &&
2234 !types::isSrcFile(HostAction->getType())) {
2235 auto UnbundlingHostAction =
2236 C.MakeAction<OffloadUnbundlingJobAction>(HostAction);
2237 UnbundlingHostAction->registerDependentActionInfo(
2238 C.getSingleOffloadToolChain<Action::OFK_Host>(),
2239 /*BoundArch=*/StringRef(), Action::OFK_Host);
2240 HostAction = UnbundlingHostAction;
2241 }
2242
Samuel Antao64e965e2016-09-30 15:34:19 +00002243 assert(HostAction && "Invalid host action!");
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002244
Samuel Antao64e965e2016-09-30 15:34:19 +00002245 // Register the offload kinds that are used.
2246 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2247 for (auto *SB : SpecializedBuilders) {
2248 if (!SB->isValid())
2249 continue;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002250
Samuel Antao64e965e2016-09-30 15:34:19 +00002251 auto RetCode = SB->addDeviceDepences(HostAction);
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002252
Samuel Antao64e965e2016-09-30 15:34:19 +00002253 // Host dependences for device actions are not compatible with that same
2254 // action being ignored.
2255 assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host &&
2256 "Host dependence not expected to be ignored.!");
Samuel Antaod06239d2016-07-15 23:13:27 +00002257
Samuel Antao64e965e2016-09-30 15:34:19 +00002258 // Unless the builder was inactive for this action, we have to record the
2259 // offload kind because the host will have to use it.
2260 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2261 OffloadKind |= SB->getAssociatedOffloadKind();
2262 }
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002263
Samuel Antao64e965e2016-09-30 15:34:19 +00002264 return false;
2265 }
2266
Samuel Antao69d6f312016-10-27 17:50:43 +00002267 /// Add the offloading top level actions to the provided action list. This
2268 /// function can replace the host action by a bundling action if the
2269 /// programming models allow it.
Samuel Antao64e965e2016-09-30 15:34:19 +00002270 bool appendTopLevelActions(ActionList &AL, Action *HostAction,
2271 const Arg *InputArg) {
Samuel Antao69d6f312016-10-27 17:50:43 +00002272 // Get the device actions to be appended.
2273 ActionList OffloadAL;
Samuel Antao64e965e2016-09-30 15:34:19 +00002274 for (auto *SB : SpecializedBuilders) {
2275 if (!SB->isValid())
2276 continue;
Samuel Antao69d6f312016-10-27 17:50:43 +00002277 SB->appendTopLevelActions(OffloadAL);
Samuel Antao64e965e2016-09-30 15:34:19 +00002278 }
2279
Samuel Antao69d6f312016-10-27 17:50:43 +00002280 // If we can use the bundler, replace the host action by the bundling one in
2281 // the resulting list. Otherwise, just append the device actions.
2282 if (CanUseBundler && !OffloadAL.empty()) {
2283 // Add the host action to the list in order to create the bundling action.
2284 OffloadAL.push_back(HostAction);
2285
2286 // We expect that the host action was just appended to the action list
2287 // before this method was called.
2288 assert(HostAction == AL.back() && "Host action not in the list??");
2289 HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL);
2290 AL.back() = HostAction;
2291 } else
2292 AL.append(OffloadAL.begin(), OffloadAL.end());
2293
Samuel Antao64e965e2016-09-30 15:34:19 +00002294 // Propagate to the current host action (if any) the offload information
2295 // associated with the current input.
2296 if (HostAction)
2297 HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg],
2298 /*BoundArch=*/nullptr);
Samuel Antao64e965e2016-09-30 15:34:19 +00002299 return false;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002300 }
Artem Belevich5bde4e02015-07-20 20:02:54 +00002301
Samuel Antao64e965e2016-09-30 15:34:19 +00002302 /// Processes the host linker action. This currently consists of replacing it
2303 /// with an offload action if there are device link objects and propagate to
2304 /// the host action all the offload kinds used in the current compilation. The
2305 /// resulting action is returned.
2306 Action *processHostLinkAction(Action *HostAction) {
2307 // Add all the dependences from the device linking actions.
2308 OffloadAction::DeviceDependences DDeps;
2309 for (auto *SB : SpecializedBuilders) {
2310 if (!SB->isValid())
2311 continue;
Justin Lebar21e5d4f2016-01-14 21:41:27 +00002312
Samuel Antao64e965e2016-09-30 15:34:19 +00002313 SB->appendLinkDependences(DDeps);
Justin Lebar21e5d4f2016-01-14 21:41:27 +00002314 }
Samuel Antaod06239d2016-07-15 23:13:27 +00002315
Samuel Antao64e965e2016-09-30 15:34:19 +00002316 // Calculate all the offload kinds used in the current compilation.
2317 unsigned ActiveOffloadKinds = 0u;
2318 for (auto &I : InputArgToOffloadKindMap)
2319 ActiveOffloadKinds |= I.second;
2320
2321 // If we don't have device dependencies, we don't have to create an offload
2322 // action.
2323 if (DDeps.getActions().empty()) {
2324 // Propagate all the active kinds to host action. Given that it is a link
2325 // action it is assumed to depend on all actions generated so far.
2326 HostAction->propagateHostOffloadInfo(ActiveOffloadKinds,
2327 /*BoundArch=*/nullptr);
2328 return HostAction;
2329 }
2330
2331 // Create the offload action with all dependences. When an offload action
2332 // is created the kinds are propagated to the host action, so we don't have
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002333 // to do that explicitly here.
Samuel Antao64e965e2016-09-30 15:34:19 +00002334 OffloadAction::HostDependence HDep(
2335 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2336 /*BoundArch*/ nullptr, ActiveOffloadKinds);
2337 return C.MakeAction<OffloadAction>(HDep, DDeps);
2338 }
2339};
2340} // anonymous namespace.
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002341
Justin Lebar0f3474c2016-02-11 02:00:50 +00002342void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
2343 const InputList &Inputs, ActionList &Actions) const {
Chad Rosierecdede82011-08-12 22:08:57 +00002344 llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00002345
Daniel Dunbar34c41872009-03-13 00:17:48 +00002346 if (!SuppressMissingInputWarning && Inputs.empty()) {
Daniel Dunbarbfeec742009-03-12 23:55:14 +00002347 Diag(clang::diag::err_drv_no_input_files);
2348 return;
2349 }
2350
Chad Rosier7742b5d2011-07-27 23:36:45 +00002351 Arg *FinalPhaseArg;
2352 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
Daniel Dunbarbfeec742009-03-12 23:55:14 +00002353
Rafael Espindolae8025642013-08-25 14:27:09 +00002354 if (FinalPhase == phases::Link && Args.hasArg(options::OPT_emit_llvm)) {
2355 Diag(clang::diag::err_drv_emit_llvm_link);
2356 }
2357
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002358 // Reject -Z* at the top level, these options should never have been exposed
2359 // by gcc.
Daniel Dunbardd765242009-03-26 16:12:09 +00002360 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
Daniel Dunbar0e759942009-03-20 06:14:23 +00002361 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
Daniel Dunbarbfeec742009-03-12 23:55:14 +00002362
Hans Wennborg13b7fe72013-08-12 23:26:25 +00002363 // Diagnose misuse of /Fo.
2364 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
Hans Wennborg13b7fe72013-08-12 23:26:25 +00002365 StringRef V = A->getValue();
Hans Wennborg61647532014-11-17 19:16:36 +00002366 if (Inputs.size() > 1 && !V.empty() &&
2367 !llvm::sys::path::is_separator(V.back())) {
Hans Wennborg13b7fe72013-08-12 23:26:25 +00002368 // Check whether /Fo tries to name an output file for multiple inputs.
Hans Wennborg9c1659b2013-10-18 22:49:04 +00002369 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002370 << A->getSpelling() << V;
Hans Wennborg13b7fe72013-08-12 23:26:25 +00002371 Args.eraseArg(options::OPT__SLASH_Fo);
2372 }
2373 }
2374
Hans Wennborg9c1659b2013-10-18 22:49:04 +00002375 // Diagnose misuse of /Fa.
2376 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
2377 StringRef V = A->getValue();
Hans Wennborg61647532014-11-17 19:16:36 +00002378 if (Inputs.size() > 1 && !V.empty() &&
2379 !llvm::sys::path::is_separator(V.back())) {
Hans Wennborg9c1659b2013-10-18 22:49:04 +00002380 // Check whether /Fa tries to name an asm file for multiple inputs.
2381 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002382 << A->getSpelling() << V;
Hans Wennborg9c1659b2013-10-18 22:49:04 +00002383 Args.eraseArg(options::OPT__SLASH_Fa);
2384 }
2385 }
2386
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00002387 // Diagnose misuse of /o.
2388 if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
2389 if (A->getValue()[0] == '\0') {
2390 // It has to have a value.
2391 Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
2392 Args.eraseArg(options::OPT__SLASH_o);
2393 }
2394 }
2395
Nico Weber2ca4be92016-03-01 23:16:44 +00002396 // Diagnose unsupported forms of /Yc /Yu. Ignore /Yc/Yu for now if:
2397 // * no filename after it
2398 // * both /Yc and /Yu passed but with different filenames
2399 // * corresponding file not also passed as /FI
2400 Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
2401 Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
2402 if (YcArg && YcArg->getValue()[0] == '\0') {
2403 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YcArg->getSpelling();
2404 Args.eraseArg(options::OPT__SLASH_Yc);
2405 YcArg = nullptr;
2406 }
2407 if (YuArg && YuArg->getValue()[0] == '\0') {
2408 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YuArg->getSpelling();
2409 Args.eraseArg(options::OPT__SLASH_Yu);
2410 YuArg = nullptr;
2411 }
2412 if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
2413 Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
2414 Args.eraseArg(options::OPT__SLASH_Yc);
2415 Args.eraseArg(options::OPT__SLASH_Yu);
2416 YcArg = YuArg = nullptr;
2417 }
2418 if (YcArg || YuArg) {
2419 StringRef Val = YcArg ? YcArg->getValue() : YuArg->getValue();
2420 bool FoundMatchingInclude = false;
2421 for (const Arg *Inc : Args.filtered(options::OPT_include)) {
2422 // FIXME: Do case-insensitive matching and consider / and \ as equal.
2423 if (Inc->getValue() == Val)
2424 FoundMatchingInclude = true;
2425 }
2426 if (!FoundMatchingInclude) {
2427 Diag(clang::diag::warn_drv_ycyu_no_fi_arg_clang_cl)
2428 << (YcArg ? YcArg : YuArg)->getSpelling();
2429 Args.eraseArg(options::OPT__SLASH_Yc);
2430 Args.eraseArg(options::OPT__SLASH_Yu);
2431 YcArg = YuArg = nullptr;
2432 }
2433 }
2434 if (YcArg && Inputs.size() > 1) {
2435 Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
2436 Args.eraseArg(options::OPT__SLASH_Yc);
2437 YcArg = nullptr;
2438 }
2439 if (Args.hasArg(options::OPT__SLASH_Y_)) {
2440 // /Y- disables all pch handling. Rather than check for it everywhere,
2441 // just remove clang-cl pch-related flags here.
2442 Args.eraseArg(options::OPT__SLASH_Fp);
2443 Args.eraseArg(options::OPT__SLASH_Yc);
2444 Args.eraseArg(options::OPT__SLASH_Yu);
2445 YcArg = YuArg = nullptr;
2446 }
Nico Weber2ca4be92016-03-01 23:16:44 +00002447
Samuel Antao64e965e2016-09-30 15:34:19 +00002448 // Builder to be used to build offloading actions.
2449 OffloadingActionBuilder OffloadBuilder(C, Args, Inputs);
Samuel Antaod06239d2016-07-15 23:13:27 +00002450
Daniel Dunbar65229332009-03-13 11:38:42 +00002451 // Construct the actions to perform.
2452 ActionList LinkerInputs;
Alp Toker965f8822013-11-27 05:22:15 +00002453
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002454 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL;
Artem Belevich5bde4e02015-07-20 20:02:54 +00002455 for (auto &I : Inputs) {
2456 types::ID InputType = I.first;
2457 const Arg *InputArg = I.second;
Daniel Dunbar65229332009-03-13 11:38:42 +00002458
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002459 PL.clear();
2460 types::getCompilationPhases(InputType, PL);
Daniel Dunbar65229332009-03-13 11:38:42 +00002461
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002462 // If the first step comes after the final phase we are doing as part of
2463 // this compilation, warn the user about it.
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002464 phases::ID InitialPhase = PL[0];
Daniel Dunbar65229332009-03-13 11:38:42 +00002465 if (InitialPhase > FinalPhase) {
Daniel Dunbaradc5c7c2009-03-19 07:57:08 +00002466 // Claim here to avoid the more general unused warning.
2467 InputArg->claim();
Daniel Dunbar07806ca2009-09-17 04:13:26 +00002468
Daniel Dunbar2db3e732011-04-20 15:44:48 +00002469 // Suppress all unused style warnings with -Qunused-arguments
2470 if (Args.hasArg(options::OPT_Qunused_arguments))
2471 continue;
2472
Richard Smith403f76e2012-08-06 04:09:06 +00002473 // Special case when final phase determined by binary name, rather than
2474 // by a command-line argument with a corresponding Arg.
Hans Wennborg70850d82013-07-18 20:29:38 +00002475 if (CCCIsCPP())
Richard Smith403f76e2012-08-06 04:09:06 +00002476 Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002477 << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
Daniel Dunbar07806ca2009-09-17 04:13:26 +00002478 // Special case '-E' warning on a previously preprocessed file to make
2479 // more sense.
Richard Smith403f76e2012-08-06 04:09:06 +00002480 else if (InitialPhase == phases::Compile &&
2481 FinalPhase == phases::Preprocess &&
2482 getPreprocessedType(InputType) == types::TY_INVALID)
Daniel Dunbar07806ca2009-09-17 04:13:26 +00002483 Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002484 << InputArg->getAsString(Args) << !!FinalPhaseArg
2485 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
Daniel Dunbar07806ca2009-09-17 04:13:26 +00002486 else
2487 Diag(clang::diag::warn_drv_input_file_unused)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002488 << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
2489 << !!FinalPhaseArg
2490 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
Daniel Dunbar65229332009-03-13 11:38:42 +00002491 continue;
2492 }
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002493
Nico Weberad2d8f32016-04-21 19:59:10 +00002494 if (YcArg) {
2495 // Add a separate precompile phase for the compile phase.
2496 if (FinalPhase >= phases::Compile) {
Richard Smith8cd452d2016-08-30 18:55:16 +00002497 const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType);
Nico Weberad2d8f32016-04-21 19:59:10 +00002498 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PCHPL;
Richard Smith8cd452d2016-08-30 18:55:16 +00002499 types::getCompilationPhases(HeaderType, PCHPL);
Nico Weberad2d8f32016-04-21 19:59:10 +00002500 Arg *PchInputArg = MakeInputArg(Args, Opts, YcArg->getValue());
2501
2502 // Build the pipeline for the pch file.
Richard Smith8cd452d2016-08-30 18:55:16 +00002503 Action *ClangClPch =
2504 C.MakeAction<InputAction>(*PchInputArg, HeaderType);
Nico Weberad2d8f32016-04-21 19:59:10 +00002505 for (phases::ID Phase : PCHPL)
2506 ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
2507 assert(ClangClPch);
2508 Actions.push_back(ClangClPch);
2509 // The driver currently exits after the first failed command. This
2510 // relies on that behavior, to make sure if the pch generation fails,
2511 // the main compilation won't run.
2512 }
2513 }
2514
Daniel Dunbar65229332009-03-13 11:38:42 +00002515 // Build the pipeline for this file.
Justin Lebar41094612016-01-11 23:07:27 +00002516 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
Samuel Antao64e965e2016-09-30 15:34:19 +00002517
2518 // Use the current host action in any of the offloading actions, if
2519 // required.
2520 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
2521 break;
2522
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002523 for (SmallVectorImpl<phases::ID>::iterator i = PL.begin(), e = PL.end();
2524 i != e; ++i) {
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002525 phases::ID Phase = *i;
Daniel Dunbar65229332009-03-13 11:38:42 +00002526
2527 // We are done if this step is past what the user requested.
2528 if (Phase > FinalPhase)
2529 break;
2530
Samuel Antao64e965e2016-09-30 15:34:19 +00002531 // Add any offload action the host action depends on.
2532 Current = OffloadBuilder.addDeviceDependencesToHostAction(
2533 Current, InputArg, Phase, FinalPhase, PL);
2534 if (!Current)
2535 break;
2536
Daniel Dunbar65229332009-03-13 11:38:42 +00002537 // Queue linker inputs.
2538 if (Phase == phases::Link) {
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002539 assert((i + 1) == e && "linking must be final compilation step.");
Justin Lebar41094612016-01-11 23:07:27 +00002540 LinkerInputs.push_back(Current);
2541 Current = nullptr;
Daniel Dunbar65229332009-03-13 11:38:42 +00002542 break;
2543 }
2544
Samuel Antao64e965e2016-09-30 15:34:19 +00002545 // Otherwise construct the appropriate action.
2546 auto *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current);
2547
2548 // We didn't create a new action, so we will just move to the next phase.
2549 if (NewCurrent == Current)
Daniel Dunbar13864952009-03-24 20:17:30 +00002550 continue;
2551
Samuel Antao64e965e2016-09-30 15:34:19 +00002552 Current = NewCurrent;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002553
Samuel Antao64e965e2016-09-30 15:34:19 +00002554 // Use the current host action in any of the offloading actions, if
2555 // required.
2556 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
2557 break;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002558
Daniel Dunbar65229332009-03-13 11:38:42 +00002559 if (Current->getType() == types::TY_Nothing)
2560 break;
2561 }
2562
Samuel Antao64e965e2016-09-30 15:34:19 +00002563 // If we ended with something, add to the output list.
2564 if (Current)
Justin Lebar41094612016-01-11 23:07:27 +00002565 Actions.push_back(Current);
Samuel Antao64e965e2016-09-30 15:34:19 +00002566
2567 // Add any top level actions generated for offloading.
2568 OffloadBuilder.appendTopLevelActions(Actions, Current, InputArg);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002569 }
Daniel Dunbar65229332009-03-13 11:38:42 +00002570
Samuel Antao64e965e2016-09-30 15:34:19 +00002571 // Add a link action if necessary.
Samuel Antaod06239d2016-07-15 23:13:27 +00002572 if (!LinkerInputs.empty()) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002573 Action *LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image);
2574 LA = OffloadBuilder.processHostLinkAction(LA);
2575 Actions.push_back(LA);
Samuel Antaod06239d2016-07-15 23:13:27 +00002576 }
Daniel Dunbarc7a67b72009-12-22 23:19:32 +00002577
2578 // If we are linking, claim any options which are obviously only used for
2579 // compilation.
Hans Wennborga8ef14f2013-09-17 00:03:41 +00002580 if (FinalPhase == phases::Link && PL.size() == 1) {
Daniel Dunbarc7a67b72009-12-22 23:19:32 +00002581 Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
Hans Wennborga8ef14f2013-09-17 00:03:41 +00002582 Args.ClaimAllArgs(options::OPT_cl_compile_Group);
2583 }
2584
2585 // Claim ignored clang-cl options.
2586 Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
Artem Belevichbaae0932015-07-28 21:01:30 +00002587
Justin Lebardc3c5042016-04-19 02:27:07 +00002588 // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed
2589 // to non-CUDA compilations and should not trigger warnings there.
Artem Belevichbaae0932015-07-28 21:01:30 +00002590 Args.ClaimAllArgs(options::OPT_cuda_host_only);
Justin Lebardc3c5042016-04-19 02:27:07 +00002591 Args.ClaimAllArgs(options::OPT_cuda_compile_host_device);
Daniel Dunbar65229332009-03-13 11:38:42 +00002592}
2593
Justin Lebar0f3474c2016-02-11 02:00:50 +00002594Action *Driver::ConstructPhaseAction(Compilation &C, const ArgList &Args,
2595 phases::ID Phase, Action *Input) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00002596 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
Samuel Antao64e965e2016-09-30 15:34:19 +00002597
2598 // Some types skip the assembler phase (e.g., llvm-bc), but we can't
2599 // encode this in the steps because the intermediate type depends on
2600 // arguments. Just special case here.
2601 if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm)
2602 return Input;
2603
Daniel Dunbar65229332009-03-13 11:38:42 +00002604 // Build the appropriate action.
2605 switch (Phase) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002606 case phases::Link:
2607 llvm_unreachable("link action invalid here.");
Daniel Dunbar65229332009-03-13 11:38:42 +00002608 case phases::Preprocess: {
Daniel Dunbard67a3222009-03-30 06:36:42 +00002609 types::ID OutputTy;
2610 // -{M, MM} alter the output type.
Daniel Dunbar86aed7d2010-12-08 21:33:40 +00002611 if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
Daniel Dunbard67a3222009-03-30 06:36:42 +00002612 OutputTy = types::TY_Dependencies;
2613 } else {
David Blaikie5d577a22012-06-29 22:03:56 +00002614 OutputTy = Input->getType();
2615 if (!Args.hasFlag(options::OPT_frewrite_includes,
Justin Bognerce8245b2014-06-24 08:01:01 +00002616 options::OPT_fno_rewrite_includes, false) &&
2617 !CCGenDiagnostics)
David Blaikie5d577a22012-06-29 22:03:56 +00002618 OutputTy = types::getPreprocessedType(OutputTy);
Daniel Dunbard67a3222009-03-30 06:36:42 +00002619 assert(OutputTy != types::TY_INVALID &&
2620 "Cannot preprocess this input type!");
2621 }
Justin Lebar41094612016-01-11 23:07:27 +00002622 return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
Daniel Dunbar65229332009-03-13 11:38:42 +00002623 }
Aaron Ballman1f10cc52012-07-31 01:21:00 +00002624 case phases::Precompile: {
Richard Smithdd4ad3d2016-08-30 19:06:26 +00002625 types::ID OutputTy = getPrecompiledType(Input->getType());
2626 assert(OutputTy != types::TY_INVALID &&
2627 "Cannot precompile this input type!");
Aaron Ballman1f10cc52012-07-31 01:21:00 +00002628 if (Args.hasArg(options::OPT_fsyntax_only)) {
2629 // Syntax checks should not emit a PCH file
2630 OutputTy = types::TY_Nothing;
2631 }
Justin Lebar41094612016-01-11 23:07:27 +00002632 return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
Aaron Ballman1f10cc52012-07-31 01:21:00 +00002633 }
Daniel Dunbar65229332009-03-13 11:38:42 +00002634 case phases::Compile: {
David Blaikie486f4402014-08-29 07:25:23 +00002635 if (Args.hasArg(options::OPT_fsyntax_only))
Justin Lebar41094612016-01-11 23:07:27 +00002636 return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
David Blaikie486f4402014-08-29 07:25:23 +00002637 if (Args.hasArg(options::OPT_rewrite_objc))
Justin Lebar41094612016-01-11 23:07:27 +00002638 return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
David Blaikie486f4402014-08-29 07:25:23 +00002639 if (Args.hasArg(options::OPT_rewrite_legacy_objc))
Justin Lebar41094612016-01-11 23:07:27 +00002640 return C.MakeAction<CompileJobAction>(Input,
2641 types::TY_RewrittenLegacyObjC);
David Blaikie486f4402014-08-29 07:25:23 +00002642 if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto))
Justin Lebar41094612016-01-11 23:07:27 +00002643 return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
David Blaikie486f4402014-08-29 07:25:23 +00002644 if (Args.hasArg(options::OPT__migrate))
Justin Lebar41094612016-01-11 23:07:27 +00002645 return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
David Blaikie486f4402014-08-29 07:25:23 +00002646 if (Args.hasArg(options::OPT_emit_ast))
Justin Lebar41094612016-01-11 23:07:27 +00002647 return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
David Blaikie486f4402014-08-29 07:25:23 +00002648 if (Args.hasArg(options::OPT_module_file_info))
Justin Lebar41094612016-01-11 23:07:27 +00002649 return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
David Blaikie486f4402014-08-29 07:25:23 +00002650 if (Args.hasArg(options::OPT_verify_pch))
Justin Lebar41094612016-01-11 23:07:27 +00002651 return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
2652 return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
Bob Wilson23a55f12014-12-21 07:00:00 +00002653 }
2654 case phases::Backend: {
Teresa Johnson945bc502015-10-15 20:35:53 +00002655 if (isUsingLTO()) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002656 types::ID Output =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002657 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
Justin Lebar41094612016-01-11 23:07:27 +00002658 return C.MakeAction<BackendJobAction>(Input, Output);
David Blaikie486f4402014-08-29 07:25:23 +00002659 }
2660 if (Args.hasArg(options::OPT_emit_llvm)) {
Shuxin Yang4b3c7ff2013-08-23 21:34:57 +00002661 types::ID Output =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002662 Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
Justin Lebar41094612016-01-11 23:07:27 +00002663 return C.MakeAction<BackendJobAction>(Input, Output);
Daniel Dunbar65229332009-03-13 11:38:42 +00002664 }
Justin Lebar41094612016-01-11 23:07:27 +00002665 return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
Daniel Dunbar65229332009-03-13 11:38:42 +00002666 }
2667 case phases::Assemble:
Justin Lebar21e5d4f2016-01-14 21:41:27 +00002668 return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
Daniel Dunbar65229332009-03-13 11:38:42 +00002669 }
2670
David Blaikie83d382b2011-09-23 05:06:16 +00002671 llvm_unreachable("invalid phase in ConstructPhaseAction");
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002672}
2673
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00002674void Driver::BuildJobs(Compilation &C) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00002675 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
Daniel Dunbare75d8342009-03-16 06:56:51 +00002676
2677 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
2678
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002679 // It is an error to provide a -o option if we are making multiple output
2680 // files.
Daniel Dunbare75d8342009-03-16 06:56:51 +00002681 if (FinalOutput) {
2682 unsigned NumOutputs = 0;
Saleem Abdulrasoolda3f4e52014-12-29 21:02:47 +00002683 for (const Action *A : C.getActions())
2684 if (A->getType() != types::TY_Nothing)
Daniel Dunbare75d8342009-03-16 06:56:51 +00002685 ++NumOutputs;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002686
Daniel Dunbare75d8342009-03-16 06:56:51 +00002687 if (NumOutputs > 1) {
2688 Diag(clang::diag::err_drv_output_argument_with_multiple_files);
Craig Topper92fc2df2014-05-17 16:56:41 +00002689 FinalOutput = nullptr;
Daniel Dunbare75d8342009-03-16 06:56:51 +00002690 }
2691 }
2692
Chad Rosier35767232013-04-30 22:01:21 +00002693 // Collect the list of architectures.
2694 llvm::StringSet<> ArchNames;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00002695 if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO())
2696 for (const Arg *A : C.getArgs())
Chad Rosier35767232013-04-30 22:01:21 +00002697 if (A->getOption().matches(options::OPT_arch))
2698 ArchNames.insert(A->getValue());
Chad Rosier35767232013-04-30 22:01:21 +00002699
Justin Lebarb44f6fe2016-01-14 21:41:21 +00002700 // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
2701 std::map<std::pair<const Action *, std::string>, InputInfo> CachedResults;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00002702 for (Action *A : C.getActions()) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002703 // If we are linking an image for multiple archs then the linker wants
2704 // -arch_multiple and -final_output <final image name>. Unfortunately, this
2705 // doesn't fit in cleanly because we have to pass this information down.
Daniel Dunbare75d8342009-03-16 06:56:51 +00002706 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002707 // FIXME: This is a hack; find a cleaner way to integrate this into the
2708 // process.
Craig Topper92fc2df2014-05-17 16:56:41 +00002709 const char *LinkingOutput = nullptr;
Daniel Dunbardd765242009-03-26 16:12:09 +00002710 if (isa<LipoJobAction>(A)) {
Daniel Dunbare75d8342009-03-16 06:56:51 +00002711 if (FinalOutput)
Richard Smithbd55daf2012-11-01 04:30:05 +00002712 LinkingOutput = FinalOutput->getValue();
Daniel Dunbare75d8342009-03-16 06:56:51 +00002713 else
Hans Wennborga7707222015-01-09 17:38:53 +00002714 LinkingOutput = getDefaultImageName();
Daniel Dunbare75d8342009-03-16 06:56:51 +00002715 }
2716
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002717 BuildJobsForAction(C, A, &C.getDefaultToolChain(),
Mehdi Aminic50b1a22016-10-07 21:27:26 +00002718 /*BoundArch*/ StringRef(),
Daniel Dunbare75d8342009-03-16 06:56:51 +00002719 /*AtTopLevel*/ true,
Chad Rosier35767232013-04-30 22:01:21 +00002720 /*MultipleArchs*/ ArchNames.size() > 1,
Samuel Antaod06239d2016-07-15 23:13:27 +00002721 /*LinkingOutput*/ LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00002722 /*TargetDeviceOffloadKind*/ Action::OFK_None);
Daniel Dunbare75d8342009-03-16 06:56:51 +00002723 }
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00002724
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002725 // If the user passed -Qunused-arguments or there were errors, don't warn
2726 // about any unused arguments.
Argyrios Kyrtzidis31448a42010-11-18 21:47:07 +00002727 if (Diags.hasErrorOccurred() ||
Daniel Dunbara3cfbe32009-04-07 19:04:18 +00002728 C.getArgs().hasArg(options::OPT_Qunused_arguments))
Daniel Dunbard175d972009-03-18 18:03:46 +00002729 return;
2730
Daniel Dunbar58399ae2009-03-29 22:24:54 +00002731 // Claim -### here.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002732 (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002733
Nico Weber47bf5052016-04-25 21:15:49 +00002734 // Claim --driver-mode, --rsp-quoting, it was handled earlier.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002735 (void)C.getArgs().hasArg(options::OPT_driver_mode);
Nico Weber47bf5052016-04-25 21:15:49 +00002736 (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
Hans Wennborg70850d82013-07-18 20:29:38 +00002737
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00002738 for (Arg *A : C.getArgs()) {
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00002739 // FIXME: It would be nice to be able to send the argument to the
David Blaikie9c902b52011-09-25 23:23:43 +00002740 // DiagnosticsEngine, so that extra values, position, and so on could be
2741 // printed.
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00002742 if (!A->isClaimed()) {
Michael J. Spencer66e2b202012-10-19 22:37:06 +00002743 if (A->getOption().hasFlag(options::NoArgumentUnused))
Daniel Dunbara3cfbe32009-04-07 19:04:18 +00002744 continue;
2745
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002746 // Suppress the warning automatically if this is just a flag, and it is an
2747 // instance of an argument we already claimed.
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00002748 const Option &Opt = A->getOption();
Michael J. Spencerad3ccc32012-08-20 21:41:17 +00002749 if (Opt.getKind() == Option::FlagClass) {
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00002750 bool DuplicateClaimed = false;
2751
Sean Silva14facf32015-06-09 01:57:17 +00002752 for (const Arg *AA : C.getArgs().filtered(&Opt)) {
2753 if (AA->isClaimed()) {
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00002754 DuplicateClaimed = true;
2755 break;
2756 }
2757 }
2758
2759 if (DuplicateClaimed)
2760 continue;
2761 }
2762
Ehsan Akhgarid8518332016-01-25 21:14:52 +00002763 // In clang-cl, don't mention unknown arguments here since they have
2764 // already been warned about.
2765 if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN))
2766 Diag(clang::diag::warn_drv_unused_argument)
2767 << A->getAsString(C.getArgs());
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00002768 }
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00002769 }
Daniel Dunbar95e6b192009-03-13 22:12:33 +00002770}
Daniel Dunbarc4343942010-02-03 03:07:56 +00002771
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002772namespace {
2773/// Utility class to control the collapse of dependent actions and select the
2774/// tools accordingly.
2775class ToolSelector final {
2776 /// The tool chain this selector refers to.
2777 const ToolChain &TC;
Daniel Dunbarf9ff3502010-05-14 02:03:00 +00002778
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002779 /// The compilation this selector refers to.
2780 const Compilation &C;
Samuel Antaod06239d2016-07-15 23:13:27 +00002781
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002782 /// The base action this selector refers to.
2783 const JobAction *BaseAction;
Samuel Antaod06239d2016-07-15 23:13:27 +00002784
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002785 /// Set to true if the current toolchain refers to host actions.
2786 bool IsHostSelector;
Samuel Antaod06239d2016-07-15 23:13:27 +00002787
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002788 /// Set to true if save-temps and embed-bitcode functionalities are active.
2789 bool SaveTemps;
2790 bool EmbedBitcode;
2791
2792 /// Get previous dependent action or null if that does not exist. If
2793 /// \a CanBeCollapsed is false, that action must be legal to collapse or
2794 /// null will be returned.
2795 const JobAction *getPrevDependentAction(const ActionList &Inputs,
2796 ActionList &SavedOffloadAction,
2797 bool CanBeCollapsed = true) {
2798 // An option can be collapsed only if it has a single input.
2799 if (Inputs.size() != 1)
Craig Topper92fc2df2014-05-17 16:56:41 +00002800 return nullptr;
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002801
2802 Action *CurAction = *Inputs.begin();
2803 if (CanBeCollapsed &&
2804 !CurAction->isCollapsingWithNextDependentActionLegal())
2805 return nullptr;
2806
2807 // If the input action is an offload action. Look through it and save any
2808 // offload action that can be dropped in the event of a collapse.
2809 if (auto *OA = dyn_cast<OffloadAction>(CurAction)) {
2810 // If the dependent action is a device action, we will attempt to collapse
2811 // only with other device actions. Otherwise, we would do the same but
2812 // with host actions only.
2813 if (!IsHostSelector) {
2814 if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) {
2815 CurAction =
2816 OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
2817 if (CanBeCollapsed &&
2818 !CurAction->isCollapsingWithNextDependentActionLegal())
2819 return nullptr;
2820 SavedOffloadAction.push_back(OA);
2821 return dyn_cast<JobAction>(CurAction);
2822 }
2823 } else if (OA->hasHostDependence()) {
2824 CurAction = OA->getHostDependence();
2825 if (CanBeCollapsed &&
2826 !CurAction->isCollapsingWithNextDependentActionLegal())
2827 return nullptr;
2828 SavedOffloadAction.push_back(OA);
2829 return dyn_cast<JobAction>(CurAction);
2830 }
2831 return nullptr;
2832 }
2833
2834 return dyn_cast<JobAction>(CurAction);
2835 }
2836
2837 /// Return true if an assemble action can be collapsed.
2838 bool canCollapseAssembleAction() const {
2839 return TC.useIntegratedAs() && !SaveTemps &&
2840 !C.getArgs().hasArg(options::OPT_via_file_asm) &&
2841 !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
2842 !C.getArgs().hasArg(options::OPT__SLASH_Fa);
2843 }
2844
2845 /// Return true if a preprocessor action can be collapsed.
2846 bool canCollapsePreprocessorAction() const {
2847 return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
2848 !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
2849 !C.getArgs().hasArg(options::OPT_rewrite_objc);
2850 }
2851
2852 /// Struct that relates an action with the offload actions that would be
2853 /// collapsed with it.
2854 struct JobActionInfo final {
2855 /// The action this info refers to.
2856 const JobAction *JA = nullptr;
2857 /// The offload actions we need to take care off if this action is
2858 /// collapsed.
2859 ActionList SavedOffloadAction;
2860 };
2861
2862 /// Append collapsed offload actions from the give nnumber of elements in the
2863 /// action info array.
2864 static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction,
2865 ArrayRef<JobActionInfo> &ActionInfo,
2866 unsigned ElementNum) {
2867 assert(ElementNum <= ActionInfo.size() && "Invalid number of elements.");
2868 for (unsigned I = 0; I < ElementNum; ++I)
2869 CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(),
2870 ActionInfo[I].SavedOffloadAction.end());
2871 }
2872
2873 /// Functions that attempt to perform the combining. They detect if that is
2874 /// legal, and if so they update the inputs \a Inputs and the offload action
2875 /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with
2876 /// the combined action is returned. If the combining is not legal or if the
2877 /// tool does not exist, null is returned.
2878 /// Currently three kinds of collapsing are supported:
2879 /// - Assemble + Backend + Compile;
2880 /// - Assemble + Backend ;
2881 /// - Backend + Compile.
2882 const Tool *
2883 combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
2884 const ActionList *&Inputs,
2885 ActionList &CollapsedOffloadAction) {
2886 if (ActionInfo.size() < 3 || !canCollapseAssembleAction())
2887 return nullptr;
2888 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
2889 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
2890 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA);
2891 if (!AJ || !BJ || !CJ)
2892 return nullptr;
2893
2894 // Get compiler tool.
2895 const Tool *T = TC.SelectTool(*CJ);
2896 if (!T)
2897 return nullptr;
2898
Steven Wu574b0f22016-03-01 01:07:58 +00002899 // When using -fembed-bitcode, it is required to have the same tool (clang)
2900 // for both CompilerJA and BackendJA. Otherwise, combine two stages.
2901 if (EmbedBitcode) {
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002902 const Tool *BT = TC.SelectTool(*BJ);
2903 if (BT == T)
2904 return nullptr;
Steven Wu574b0f22016-03-01 01:07:58 +00002905 }
Bob Wilson23a55f12014-12-21 07:00:00 +00002906
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002907 if (!T->hasIntegratedAssembler())
Bob Wilson23a55f12014-12-21 07:00:00 +00002908 return nullptr;
Samuel Antaod06239d2016-07-15 23:13:27 +00002909
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002910 Inputs = &CJ->getInputs();
2911 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
2912 /*NumElements=*/3);
2913 return T;
2914 }
2915 const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo,
2916 const ActionList *&Inputs,
2917 ActionList &CollapsedOffloadAction) {
2918 if (ActionInfo.size() < 2 || !canCollapseAssembleAction())
2919 return nullptr;
2920 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
2921 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
2922 if (!AJ || !BJ)
2923 return nullptr;
2924
2925 // Retrieve the compile job, backend action must always be preceded by one.
2926 ActionList CompileJobOffloadActions;
2927 auto *CJ = getPrevDependentAction(BJ->getInputs(), CompileJobOffloadActions,
2928 /*CanBeCollapsed=*/false);
2929 if (!AJ || !BJ || !CJ)
2930 return nullptr;
2931
2932 assert(isa<CompileJobAction>(CJ) &&
2933 "Expecting compile job preceding backend job.");
2934
2935 // Get compiler tool.
2936 const Tool *T = TC.SelectTool(*CJ);
2937 if (!T)
2938 return nullptr;
2939
2940 if (!T->hasIntegratedAssembler())
2941 return nullptr;
2942
2943 Inputs = &BJ->getInputs();
2944 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
2945 /*NumElements=*/2);
2946 return T;
2947 }
2948 const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
2949 const ActionList *&Inputs,
2950 ActionList &CollapsedOffloadAction) {
2951 if (ActionInfo.size() < 2 || !canCollapsePreprocessorAction())
2952 return nullptr;
2953 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA);
2954 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA);
2955 if (!BJ || !CJ)
2956 return nullptr;
2957
2958 // Get compiler tool.
2959 const Tool *T = TC.SelectTool(*CJ);
2960 if (!T)
2961 return nullptr;
2962
2963 if (T->canEmitIR() && (SaveTemps || EmbedBitcode))
2964 return nullptr;
2965
2966 Inputs = &CJ->getInputs();
2967 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
2968 /*NumElements=*/2);
2969 return T;
2970 }
2971
2972 /// Updates the inputs if the obtained tool supports combining with
2973 /// preprocessor action, and the current input is indeed a preprocessor
2974 /// action. If combining results in the collapse of offloading actions, those
2975 /// are appended to \a CollapsedOffloadAction.
2976 void combineWithPreprocessor(const Tool *T, const ActionList *&Inputs,
2977 ActionList &CollapsedOffloadAction) {
2978 if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP())
2979 return;
2980
2981 // Attempt to get a preprocessor action dependence.
2982 ActionList PreprocessJobOffloadActions;
2983 auto *PJ = getPrevDependentAction(*Inputs, PreprocessJobOffloadActions);
2984 if (!PJ || !isa<PreprocessJobAction>(PJ))
2985 return;
2986
2987 // This is legal to combine. Append any offload action we found and set the
2988 // current inputs to preprocessor inputs.
2989 CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(),
2990 PreprocessJobOffloadActions.end());
2991 Inputs = &PJ->getInputs();
2992 }
2993
2994public:
2995 ToolSelector(const JobAction *BaseAction, const ToolChain &TC,
2996 const Compilation &C, bool SaveTemps, bool EmbedBitcode)
2997 : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps),
2998 EmbedBitcode(EmbedBitcode) {
2999 assert(BaseAction && "Invalid base action.");
3000 IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None;
3001 }
3002
3003 /// Check if a chain of actions can be combined and return the tool that can
3004 /// handle the combination of actions. The pointer to the current inputs \a
3005 /// Inputs and the list of offload actions \a CollapsedOffloadActions
3006 /// connected to collapsed actions are updated accordingly. The latter enables
3007 /// the caller of the selector to process them afterwards instead of just
3008 /// dropping them. If no suitable tool is found, null will be returned.
3009 const Tool *getTool(const ActionList *&Inputs,
3010 ActionList &CollapsedOffloadAction) {
3011 //
3012 // Get the largest chain of actions that we could combine.
3013 //
3014
3015 SmallVector<JobActionInfo, 5> ActionChain(1);
3016 ActionChain.back().JA = BaseAction;
3017 while (ActionChain.back().JA) {
3018 const Action *CurAction = ActionChain.back().JA;
3019
3020 // Grow the chain by one element.
3021 ActionChain.resize(ActionChain.size() + 1);
3022 JobActionInfo &AI = ActionChain.back();
3023
3024 // Attempt to fill it with the
3025 AI.JA =
3026 getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction);
Daniel Dunbarc4343942010-02-03 03:07:56 +00003027 }
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003028
3029 // Pop the last action info as it could not be filled.
3030 ActionChain.pop_back();
3031
3032 //
3033 // Attempt to combine actions. If all combining attempts failed, just return
3034 // the tool of the provided action. At the end we attempt to combine the
3035 // action with any preprocessor action it may depend on.
3036 //
3037
3038 const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs,
3039 CollapsedOffloadAction);
3040 if (!T)
3041 T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction);
3042 if (!T)
3043 T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction);
3044 if (!T) {
3045 Inputs = &BaseAction->getInputs();
3046 T = TC.SelectTool(*BaseAction);
3047 }
3048
3049 combineWithPreprocessor(T, Inputs, CollapsedOffloadAction);
3050 return T;
Daniel Dunbarc4343942010-02-03 03:07:56 +00003051 }
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003052};
Daniel Dunbarc4343942010-02-03 03:07:56 +00003053}
3054
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003055/// Return a string that uniquely identifies the result of a job. The bound arch
3056/// is not necessarily represented in the toolchain's triple -- for example,
3057/// armv7 and armv7s both map to the same triple -- so we need both in our map.
3058/// Also, we need to add the offloading device kind, as the same tool chain can
3059/// be used for host and device for some programming models, e.g. OpenMP.
3060static std::string GetTriplePlusArchString(const ToolChain *TC,
3061 StringRef BoundArch,
3062 Action::OffloadKind OffloadKind) {
Justin Lebar55c83322016-01-16 03:30:08 +00003063 std::string TriplePlusArch = TC->getTriple().normalize();
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003064 if (!BoundArch.empty()) {
Justin Lebar55c83322016-01-16 03:30:08 +00003065 TriplePlusArch += "-";
3066 TriplePlusArch += BoundArch;
3067 }
Samuel Antao59efaed2016-10-27 17:31:22 +00003068 TriplePlusArch += "-";
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003069 TriplePlusArch += Action::GetOffloadKindName(OffloadKind);
3070 return TriplePlusArch;
3071}
3072
3073InputInfo Driver::BuildJobsForAction(
3074 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
3075 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
3076 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
3077 Action::OffloadKind TargetDeviceOffloadKind) const {
3078 std::pair<const Action *, std::string> ActionTC = {
3079 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003080 auto CachedResult = CachedResults.find(ActionTC);
3081 if (CachedResult != CachedResults.end()) {
3082 return CachedResult->second;
3083 }
Samuel Antaod06239d2016-07-15 23:13:27 +00003084 InputInfo Result = BuildJobsForActionNoCache(
3085 C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003086 CachedResults, TargetDeviceOffloadKind);
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003087 CachedResults[ActionTC] = Result;
3088 return Result;
3089}
3090
3091InputInfo Driver::BuildJobsForActionNoCache(
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003092 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003093 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
Samuel Antaod06239d2016-07-15 23:13:27 +00003094 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003095 Action::OffloadKind TargetDeviceOffloadKind) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003096 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
Daniel Dunbarc4acf9d2009-03-18 23:18:19 +00003097
Samuel Antaod06239d2016-07-15 23:13:27 +00003098 InputInfoList OffloadDependencesInputInfo;
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003099 bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None;
Samuel Antaod06239d2016-07-15 23:13:27 +00003100 if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
3101 // The offload action is expected to be used in four different situations.
3102 //
3103 // a) Set a toolchain/architecture/kind for a host action:
3104 // Host Action 1 -> OffloadAction -> Host Action 2
3105 //
3106 // b) Set a toolchain/architecture/kind for a device action;
3107 // Device Action 1 -> OffloadAction -> Device Action 2
3108 //
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003109 // c) Specify a device dependence to a host action;
Samuel Antaod06239d2016-07-15 23:13:27 +00003110 // Device Action 1 _
3111 // \
3112 // Host Action 1 ---> OffloadAction -> Host Action 2
3113 //
3114 // d) Specify a host dependence to a device action.
3115 // Host Action 1 _
3116 // \
3117 // Device Action 1 ---> OffloadAction -> Device Action 2
3118 //
3119 // For a) and b), we just return the job generated for the dependence. For
3120 // c) and d) we override the current action with the host/device dependence
3121 // if the current toolchain is host/device and set the offload dependences
3122 // info with the jobs obtained from the device/host dependence(s).
3123
3124 // If there is a single device option, just generate the job for it.
3125 if (OA->hasSingleDeviceDependence()) {
3126 InputInfo DevA;
3127 OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
3128 const char *DepBoundArch) {
3129 DevA =
3130 BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
3131 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003132 CachedResults, DepA->getOffloadingDeviceKind());
Samuel Antaod06239d2016-07-15 23:13:27 +00003133 });
3134 return DevA;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003135 }
Samuel Antaod06239d2016-07-15 23:13:27 +00003136
3137 // If 'Action 2' is host, we generate jobs for the device dependences and
3138 // override the current action with the host dependence. Otherwise, we
3139 // generate the host dependences and override the action with the device
3140 // dependence. The dependences can't therefore be a top-level action.
3141 OA->doOnEachDependence(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003142 /*IsHostDependence=*/BuildingForOffloadDevice,
Samuel Antaod06239d2016-07-15 23:13:27 +00003143 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3144 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
3145 C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false,
3146 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003147 DepA->getOffloadingDeviceKind()));
Samuel Antaod06239d2016-07-15 23:13:27 +00003148 });
3149
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003150 A = BuildingForOffloadDevice
Samuel Antaod06239d2016-07-15 23:13:27 +00003151 ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
3152 : OA->getHostDependence();
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003153 }
3154
Daniel Dunbare75d8342009-03-16 06:56:51 +00003155 if (const InputAction *IA = dyn_cast<InputAction>(A)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003156 // FIXME: It would be nice to not claim this here; maybe the old scheme of
3157 // just using Args was better?
Daniel Dunbar5cdf3e02009-03-19 07:29:38 +00003158 const Arg &Input = IA->getInputArg();
3159 Input.claim();
Daniel Dunbar35cbfeb2010-06-09 22:31:08 +00003160 if (Input.getOption().matches(options::OPT_INPUT)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00003161 const char *Name = Input.getValue();
Justin Lebard98cea82016-01-11 23:15:21 +00003162 return InputInfo(A, Name, /* BaseInput = */ Name);
Douglas Katzman678d0cb2015-06-16 18:01:24 +00003163 }
Justin Lebard98cea82016-01-11 23:15:21 +00003164 return InputInfo(A, &Input, /* BaseInput = */ "");
Daniel Dunbare75d8342009-03-16 06:56:51 +00003165 }
3166
3167 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
Chad Rosiera78a6eb2012-04-27 16:50:38 +00003168 const ToolChain *TC;
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003169 StringRef ArchName = BAA->getArchName();
Daniel Dunbar1ef3f2a2009-09-08 23:37:19 +00003170
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003171 if (!ArchName.empty())
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +00003172 TC = &getToolChain(C.getArgs(),
3173 computeTargetTriple(*this, DefaultTargetTriple,
3174 C.getArgs(), ArchName));
Chad Rosiera78a6eb2012-04-27 16:50:38 +00003175 else
3176 TC = &C.getDefaultToolChain();
Daniel Dunbar1ef3f2a2009-09-08 23:37:19 +00003177
Nico Weber5a459f82016-02-23 19:30:43 +00003178 return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
Samuel Antaod06239d2016-07-15 23:13:27 +00003179 MultipleArchs, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003180 TargetDeviceOffloadKind);
Daniel Dunbare75d8342009-03-16 06:56:51 +00003181 }
3182
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003183
Daniel Dunbare75d8342009-03-16 06:56:51 +00003184 const ActionList *Inputs = &A->getInputs();
Daniel Dunbarc4343942010-02-03 03:07:56 +00003185
3186 const JobAction *JA = cast<JobAction>(A);
Samuel Antaod06239d2016-07-15 23:13:27 +00003187 ActionList CollapsedOffloadActions;
3188
Steven Wu844ab6a2016-11-16 06:06:44 +00003189 ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(), embedBitcodeInObject());
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003190 const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions);
3191
Rafael Espindola79764462013-03-24 15:06:53 +00003192 if (!T)
Justin Lebar9eaa4892016-01-11 23:09:32 +00003193 return InputInfo();
Daniel Dunbare75d8342009-03-16 06:56:51 +00003194
Samuel Antaod06239d2016-07-15 23:13:27 +00003195 // If we've collapsed action list that contained OffloadAction we
3196 // need to build jobs for host/device-side inputs it may have held.
3197 for (const auto *OA : CollapsedOffloadActions)
3198 cast<OffloadAction>(OA)->doOnEachDependence(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003199 /*IsHostDependence=*/BuildingForOffloadDevice,
Samuel Antaod06239d2016-07-15 23:13:27 +00003200 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3201 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
Artem Belevichbee2f412016-08-22 18:50:34 +00003202 C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false,
Samuel Antaod06239d2016-07-15 23:13:27 +00003203 /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003204 DepA->getOffloadingDeviceKind()));
Samuel Antaod06239d2016-07-15 23:13:27 +00003205 });
Artem Belevichf8144ab2015-08-27 18:10:41 +00003206
Daniel Dunbare75d8342009-03-16 06:56:51 +00003207 // Only use pipes when there is exactly one input.
Daniel Dunbar1a093d22009-03-18 06:00:36 +00003208 InputInfoList InputInfos;
Saleem Abdulrasoolda3f4e52014-12-29 21:02:47 +00003209 for (const Action *Input : *Inputs) {
Eric Christopher14668dd2013-02-18 00:38:25 +00003210 // Treat dsymutil and verify sub-jobs as being at the top-level too, they
3211 // shouldn't get temporary output names.
Daniel Dunbar6beaf512010-06-04 18:28:41 +00003212 // FIXME: Clean this up.
Justin Lebar9eaa4892016-01-11 23:09:32 +00003213 bool SubJobAtTopLevel =
3214 AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
Samuel Antaod06239d2016-07-15 23:13:27 +00003215 InputInfos.push_back(BuildJobsForAction(
3216 C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003217 CachedResults, A->getOffloadingDeviceKind()));
Daniel Dunbare75d8342009-03-16 06:56:51 +00003218 }
3219
Daniel Dunbare75d8342009-03-16 06:56:51 +00003220 // Always use the first input as the base input.
3221 const char *BaseInput = InputInfos[0].getBaseInput();
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003222
Daniel Dunbar6beaf512010-06-04 18:28:41 +00003223 // ... except dsymutil actions, which use their actual input as the base
3224 // input.
3225 if (JA->getType() == types::TY_dSYM)
3226 BaseInput = InputInfos[0].getFilename();
3227
Samuel Antaod06239d2016-07-15 23:13:27 +00003228 // Append outputs of offload device jobs to the input list
3229 if (!OffloadDependencesInputInfo.empty())
3230 InputInfos.append(OffloadDependencesInputInfo.begin(),
3231 OffloadDependencesInputInfo.end());
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003232
Vedant Kumar18286cf2016-07-27 23:02:20 +00003233 // Set the effective triple of the toolchain for the duration of this job.
3234 llvm::Triple EffectiveTriple;
3235 const ToolChain &ToolTC = T->getToolChain();
Samuel Antao31fef982016-10-27 17:39:44 +00003236 const ArgList &Args =
3237 C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind());
Vedant Kumar18286cf2016-07-27 23:02:20 +00003238 if (InputInfos.size() != 1) {
3239 EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args));
3240 } else {
3241 // Pass along the input type if it can be unambiguously determined.
3242 EffectiveTriple = llvm::Triple(
3243 ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType()));
3244 }
3245 RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple);
3246
Daniel Dunbard00272f2010-08-02 02:38:15 +00003247 // Determine the place to write output to, if any.
Justin Lebar9eaa4892016-01-11 23:09:32 +00003248 InputInfo Result;
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003249 InputInfoList UnbundlingResults;
3250 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) {
3251 // If we have an unbundling job, we need to create results for all the
3252 // outputs. We also update the results cache so that other actions using
3253 // this unbundling action can get the right results.
3254 for (auto &UI : UA->getDependentActionsInfo()) {
3255 assert(UI.DependentOffloadKind != Action::OFK_None &&
3256 "Unbundling with no offloading??");
3257
3258 // Unbundling actions are never at the top level. When we generate the
3259 // offloading prefix, we also do that for the host file because the
3260 // unbundling action does not change the type of the output which can
3261 // cause a overwrite.
3262 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
3263 UI.DependentOffloadKind,
3264 UI.DependentToolChain->getTriple().normalize(),
3265 /*CreatePrefixForHost=*/true);
3266 auto CurI = InputInfo(
3267 UA, GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch,
3268 /*AtTopLevel=*/false, MultipleArchs,
3269 OffloadingPrefix),
3270 BaseInput);
3271 // Save the unbundling result.
3272 UnbundlingResults.push_back(CurI);
3273
3274 // Get the unique string identifier for this dependence and cache the
3275 // result.
3276 CachedResults[{A, GetTriplePlusArchString(
3277 UI.DependentToolChain, UI.DependentBoundArch,
3278 UI.DependentOffloadKind)}] = CurI;
3279 }
3280
3281 // Now that we have all the results generated, select the one that should be
3282 // returned for the current depending action.
3283 std::pair<const Action *, std::string> ActionTC = {
3284 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
3285 assert(CachedResults.find(ActionTC) != CachedResults.end() &&
3286 "Result does not exist??");
3287 Result = CachedResults[ActionTC];
3288 } else if (JA->getType() == types::TY_Nothing)
Justin Lebard98cea82016-01-11 23:15:21 +00003289 Result = InputInfo(A, BaseInput);
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003290 else {
3291 // We only have to generate a prefix for the host if this is not a top-level
3292 // action.
3293 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
3294 A->getOffloadingDeviceKind(), TC->getTriple().normalize(),
3295 /*CreatePrefixForHost=*/!!A->getOffloadingHostActiveKinds() &&
3296 !AtTopLevel);
Justin Lebard98cea82016-01-11 23:15:21 +00003297 Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
Samuel Antaod06239d2016-07-15 23:13:27 +00003298 AtTopLevel, MultipleArchs,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003299 OffloadingPrefix),
Justin Lebard98cea82016-01-11 23:15:21 +00003300 BaseInput);
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003301 }
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003302
Chad Rosierbe10f982011-08-02 17:58:04 +00003303 if (CCCPrintBindings && !CCGenDiagnostics) {
Rafael Espindola79764462013-03-24 15:06:53 +00003304 llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
3305 << " - \"" << T->getName() << "\", inputs: [";
Daniel Dunbarb39cc522009-03-17 22:47:06 +00003306 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
3307 llvm::errs() << InputInfos[i].getAsString();
3308 if (i + 1 != e)
3309 llvm::errs() << ", ";
3310 }
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003311 if (UnbundlingResults.empty())
3312 llvm::errs() << "], output: " << Result.getAsString() << "\n";
3313 else {
3314 llvm::errs() << "], outputs: [";
3315 for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) {
3316 llvm::errs() << UnbundlingResults[i].getAsString();
3317 if (i + 1 != e)
3318 llvm::errs() << ", ";
3319 }
3320 llvm::errs() << "] \n";
3321 }
Daniel Dunbarb39cc522009-03-17 22:47:06 +00003322 } else {
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003323 if (UnbundlingResults.empty())
3324 T->ConstructJob(
3325 C, *JA, Result, InputInfos,
3326 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
3327 LinkingOutput);
3328 else
Samuel Antao7108bf32016-11-03 15:41:50 +00003329 T->ConstructJobMultipleOutputs(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003330 C, *JA, UnbundlingResults, InputInfos,
3331 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
3332 LinkingOutput);
Daniel Dunbarb39cc522009-03-17 22:47:06 +00003333 }
Justin Lebar9eaa4892016-01-11 23:09:32 +00003334 return Result;
Daniel Dunbare75d8342009-03-16 06:56:51 +00003335}
3336
Hans Wennborga7707222015-01-09 17:38:53 +00003337const char *Driver::getDefaultImageName() const {
3338 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
3339 return Target.isOSWindows() ? "a.exe" : "a.out";
3340}
3341
Hans Wennborg2c21f742013-10-17 16:16:23 +00003342/// \brief Create output filename based on ArgValue, which could either be a
3343/// full filename, filename without extension, or a directory. If ArgValue
3344/// does not provide a filename, then use BaseName, and use the extension
3345/// suitable for FileType.
Hans Wennborg207fcf02013-08-12 21:56:42 +00003346static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003347 StringRef BaseName,
3348 types::ID FileType) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00003349 SmallString<128> Filename = ArgValue;
Justin Bogner5aaf2e72014-06-26 20:59:36 +00003350
Hans Wennborgf1a74252013-09-10 20:18:04 +00003351 if (ArgValue.empty()) {
3352 // If the argument is empty, output to BaseName in the current dir.
3353 Filename = BaseName;
3354 } else if (llvm::sys::path::is_separator(Filename.back())) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00003355 // If the argument is a directory, output to BaseName in that dir.
3356 llvm::sys::path::append(Filename, BaseName);
3357 }
3358
3359 if (!llvm::sys::path::has_extension(ArgValue)) {
3360 // If the argument didn't provide an extension, then set it.
3361 const char *Extension = types::getTypeTempSuffix(FileType, true);
Hans Wennborgf1a74252013-09-10 20:18:04 +00003362
3363 if (FileType == types::TY_Image &&
3364 Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
3365 // The output file is a dll.
3366 Extension = "dll";
3367 }
3368
Hans Wennborg207fcf02013-08-12 21:56:42 +00003369 llvm::sys::path::replace_extension(Filename, Extension);
3370 }
3371
3372 return Args.MakeArgString(Filename.c_str());
3373}
3374
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003375const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003376 const char *BaseInput,
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003377 StringRef BoundArch, bool AtTopLevel,
Samuel Antaod06239d2016-07-15 23:13:27 +00003378 bool MultipleArchs,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003379 StringRef OffloadingPrefix) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00003380 llvm::PrettyStackTraceString CrashInfo("Computing output path");
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003381 // Output to a user requested destination?
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003382 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003383 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
Chad Rosier633dcdc2013-01-24 19:14:47 +00003384 return C.addResultFile(FinalOutput->getValue(), &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003385 }
3386
Hans Wennborge0053472013-12-20 18:40:46 +00003387 // For /P, preprocess to file named after BaseInput.
3388 if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
3389 assert(AtTopLevel && isa<PreprocessJobAction>(JA));
3390 StringRef BaseName = llvm::sys::path::filename(BaseInput);
Hans Wennborg04c764f2014-06-17 00:19:12 +00003391 StringRef NameArg;
Greg Bedwell065f70a2015-06-09 10:24:06 +00003392 if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
Hans Wennborg04c764f2014-06-17 00:19:12 +00003393 NameArg = A->getValue();
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003394 return C.addResultFile(
3395 MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
3396 &JA);
Hans Wennborge0053472013-12-20 18:40:46 +00003397 }
3398
Nick Lewycky6e1ce292010-09-24 00:46:53 +00003399 // Default to writing to stdout?
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00003400 if (AtTopLevel && !CCGenDiagnostics &&
3401 (isa<PreprocessJobAction>(JA) || JA.getType() == types::TY_ModuleFile))
Nick Lewycky6e1ce292010-09-24 00:46:53 +00003402 return "-";
3403
Hans Wennborg2c21f742013-10-17 16:16:23 +00003404 // Is this the assembly listing for /FA?
3405 if (JA.getType() == types::TY_PP_Asm &&
3406 (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
3407 C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
3408 // Use /Fa and the input filename to determine the asm file name.
3409 StringRef BaseName = llvm::sys::path::filename(BaseInput);
3410 StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003411 return C.addResultFile(
3412 MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
3413 &JA);
Hans Wennborg2c21f742013-10-17 16:16:23 +00003414 }
3415
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003416 // Output to a temporary file?
Reid Kleckner68eb60b2015-02-02 22:41:48 +00003417 if ((!AtTopLevel && !isSaveTempsEnabled() &&
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003418 !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
Chad Rosierbe10f982011-08-02 17:58:04 +00003419 CCGenDiagnostics) {
Chad Rosier97c37372011-08-26 22:27:02 +00003420 StringRef Name = llvm::sys::path::filename(BaseInput);
3421 std::pair<StringRef, StringRef> Split = Name.split('.');
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003422 std::string TmpName = GetTemporaryPath(
3423 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00003424 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003425 }
3426
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003427 SmallString<128> BasePath(BaseInput);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003428 StringRef BaseName;
Daniel Dunbar67fea712011-03-25 18:16:51 +00003429
3430 // Dsymutil actions should use the full path.
Eric Christopher551ef452011-08-23 17:56:55 +00003431 if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
Daniel Dunbar67fea712011-03-25 18:16:51 +00003432 BaseName = BasePath;
3433 else
3434 BaseName = llvm::sys::path::filename(BasePath);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003435
3436 // Determine what the derived output name should be.
3437 const char *NamedOutput;
Hans Wennborg2b89a262013-08-06 22:11:28 +00003438
Hans Wennborg625fba82016-10-04 21:01:04 +00003439 if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) &&
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00003440 C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
3441 // The /Fo or /o flag decides the object filename.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003442 StringRef Val =
3443 C.getArgs()
3444 .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
3445 ->getValue();
3446 NamedOutput =
3447 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
Hans Wennborg207fcf02013-08-12 21:56:42 +00003448 } else if (JA.getType() == types::TY_Image &&
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003449 C.getArgs().hasArg(options::OPT__SLASH_Fe,
3450 options::OPT__SLASH_o)) {
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00003451 // The /Fe or /o flag names the linked file.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003452 StringRef Val =
3453 C.getArgs()
3454 .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
3455 ->getValue();
3456 NamedOutput =
3457 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
Hans Wennborgf1a74252013-09-10 20:18:04 +00003458 } else if (JA.getType() == types::TY_Image) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00003459 if (IsCLMode()) {
3460 // clang-cl uses BaseName for the executable name.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003461 NamedOutput =
3462 MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
Samuel Antao59efaed2016-10-27 17:31:22 +00003463 } else {
Hans Wennborga7707222015-01-09 17:38:53 +00003464 SmallString<128> Output(getDefaultImageName());
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003465 Output += OffloadingPrefix;
Samuel Antao59efaed2016-10-27 17:31:22 +00003466 if (MultipleArchs && !BoundArch.empty()) {
3467 Output += "-";
3468 Output.append(BoundArch);
3469 }
Chad Rosier35767232013-04-30 22:01:21 +00003470 NamedOutput = C.getArgs().MakeArgString(Output.c_str());
Nico Weber2ca4be92016-03-01 23:16:44 +00003471 }
3472 } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00003473 NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName));
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003474 } else {
Hans Wennborg0a096a02013-09-05 17:05:56 +00003475 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003476 assert(Suffix && "All types used for output should have a suffix.");
3477
3478 std::string::size_type End = std::string::npos;
3479 if (!types::appendSuffixForType(JA.getType()))
3480 End = BaseName.rfind('.');
Chad Rosier35767232013-04-30 22:01:21 +00003481 SmallString<128> Suffixed(BaseName.substr(0, End));
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003482 Suffixed += OffloadingPrefix;
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003483 if (MultipleArchs && !BoundArch.empty()) {
Chad Rosier35767232013-04-30 22:01:21 +00003484 Suffixed += "-";
3485 Suffixed.append(BoundArch);
3486 }
Bob Wilson23a55f12014-12-21 07:00:00 +00003487 // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
3488 // the unoptimized bitcode so that it does not get overwritten by the ".bc"
3489 // optimized bitcode output.
3490 if (!AtTopLevel && C.getArgs().hasArg(options::OPT_emit_llvm) &&
3491 JA.getType() == types::TY_LLVM_BC)
3492 Suffixed += ".tmp";
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003493 Suffixed += '.';
3494 Suffixed += Suffix;
3495 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
3496 }
3497
Reid Kleckner68eb60b2015-02-02 22:41:48 +00003498 // Prepend object file path if -save-temps=obj
3499 if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
3500 JA.getType() != types::TY_PCH) {
3501 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
3502 SmallString<128> TempPath(FinalOutput->getValue());
3503 llvm::sys::path::remove_filename(TempPath);
3504 StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
3505 llvm::sys::path::append(TempPath, OutputFileName);
3506 NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
3507 }
3508
Chad Rosier62135492012-07-09 17:31:28 +00003509 // If we're saving temps and the temp file conflicts with the input file,
Chad Rosier5b58af02012-04-20 20:05:08 +00003510 // then avoid overwriting input file.
Reid Kleckner68eb60b2015-02-02 22:41:48 +00003511 if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
Chad Rosier5b58af02012-04-20 20:05:08 +00003512 bool SameFile = false;
3513 SmallString<256> Result;
3514 llvm::sys::fs::current_path(Result);
3515 llvm::sys::path::append(Result, BaseName);
3516 llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
3517 // Must share the same path to conflict.
3518 if (SameFile) {
3519 StringRef Name = llvm::sys::path::filename(BaseInput);
3520 std::pair<StringRef, StringRef> Split = Name.split('.');
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003521 std::string TmpName = GetTemporaryPath(
3522 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00003523 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
Chad Rosier5b58af02012-04-20 20:05:08 +00003524 }
Chad Rosierf8412cd2011-07-15 21:54:29 +00003525 }
3526
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003527 // As an annoying special case, PCH generation doesn't strip the pathname.
Nico Weber8ab92192016-03-02 23:29:29 +00003528 if (JA.getType() == types::TY_PCH && !IsCLMode()) {
Michael J. Spencere1696752010-12-18 00:19:12 +00003529 llvm::sys::path::remove_filename(BasePath);
3530 if (BasePath.empty())
Daniel Dunbare6c83192009-03-18 09:58:30 +00003531 BasePath = NamedOutput;
3532 else
Michael J. Spencere1696752010-12-18 00:19:12 +00003533 llvm::sys::path::append(BasePath, NamedOutput);
Chad Rosier633dcdc2013-01-24 19:14:47 +00003534 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003535 } else {
Chad Rosier633dcdc2013-01-24 19:14:47 +00003536 return C.addResultFile(NamedOutput, &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003537 }
3538}
3539
Mehdi Amini12011172016-10-06 05:11:48 +00003540std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const {
Chandler Carruth84559242010-03-22 01:52:07 +00003541 // Respect a limited subset of the '-Bprefix' functionality in GCC by
Logan Chiencd679fd2012-10-04 08:08:56 +00003542 // attempting to use this prefix when looking for file paths.
Douglas Katzman26eabf62015-06-24 15:10:30 +00003543 for (const std::string &Dir : PrefixDirs) {
Joerg Sonnenberger6165ab12011-03-21 13:51:29 +00003544 if (Dir.empty())
3545 continue;
Douglas Katzman26eabf62015-06-24 15:10:30 +00003546 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
Rafael Espindola609a6642013-06-24 18:33:43 +00003547 llvm::sys::path::append(P, Name);
3548 if (llvm::sys::fs::exists(Twine(P)))
Chandler Carruth84559242010-03-22 01:52:07 +00003549 return P.str();
3550 }
3551
Rafael Espindola609a6642013-06-24 18:33:43 +00003552 SmallString<128> P(ResourceDir);
3553 llvm::sys::path::append(P, Name);
3554 if (llvm::sys::fs::exists(Twine(P)))
Peter Collingbournefa9771f2011-09-06 02:08:31 +00003555 return P.str();
3556
Douglas Katzman26eabf62015-06-24 15:10:30 +00003557 for (const std::string &Dir : TC.getFilePaths()) {
Joerg Sonnenberger6165ab12011-03-21 13:51:29 +00003558 if (Dir.empty())
3559 continue;
Douglas Katzman26eabf62015-06-24 15:10:30 +00003560 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
Rafael Espindola609a6642013-06-24 18:33:43 +00003561 llvm::sys::path::append(P, Name);
3562 if (llvm::sys::fs::exists(Twine(P)))
Daniel Dunbar1ce81532009-09-09 22:33:00 +00003563 return P.str();
Daniel Dunbar68b01a02009-03-18 20:26:19 +00003564 }
3565
Daniel Dunbar1ce81532009-09-09 22:33:00 +00003566 return Name;
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00003567}
3568
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003569void Driver::generatePrefixedToolNames(
Mehdi Amini12011172016-10-06 05:11:48 +00003570 StringRef Tool, const ToolChain &TC,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003571 SmallVectorImpl<std::string> &Names) const {
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00003572 // FIXME: Needs a better variable than DefaultTargetTriple
Mehdi Amini12011172016-10-06 05:11:48 +00003573 Names.emplace_back((DefaultTargetTriple + "-" + Tool).str());
Benjamin Kramer3204b152015-05-29 19:42:19 +00003574 Names.emplace_back(Tool);
Vasileios Kalintirisc744e122015-11-12 15:26:54 +00003575
3576 // Allow the discovery of tools prefixed with LLVM's default target triple.
3577 std::string LLVMDefaultTargetTriple = llvm::sys::getDefaultTargetTriple();
3578 if (LLVMDefaultTargetTriple != DefaultTargetTriple)
Mehdi Amini12011172016-10-06 05:11:48 +00003579 Names.emplace_back((LLVMDefaultTargetTriple + "-" + Tool).str());
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00003580}
3581
Benjamin Kramer7111b912014-11-04 20:26:01 +00003582static bool ScanDirForExecutable(SmallString<128> &Dir,
3583 ArrayRef<std::string> Names) {
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00003584 for (const auto &Name : Names) {
3585 llvm::sys::path::append(Dir, Name);
3586 if (llvm::sys::fs::can_execute(Twine(Dir)))
3587 return true;
3588 llvm::sys::path::remove_filename(Dir);
3589 }
3590 return false;
3591}
3592
Mehdi Amini12011172016-10-06 05:11:48 +00003593std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const {
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00003594 SmallVector<std::string, 2> TargetSpecificExecutables;
3595 generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
3596
Chandler Carruth84559242010-03-22 01:52:07 +00003597 // Respect a limited subset of the '-Bprefix' functionality in GCC by
Logan Chiencd679fd2012-10-04 08:08:56 +00003598 // attempting to use this prefix when looking for program paths.
Saleem Abdulrasool23d99b12014-09-16 03:48:32 +00003599 for (const auto &PrefixDir : PrefixDirs) {
3600 if (llvm::sys::fs::is_directory(PrefixDir)) {
3601 SmallString<128> P(PrefixDir);
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00003602 if (ScanDirForExecutable(P, TargetSpecificExecutables))
Rafael Espindola8be5c052013-06-19 13:24:29 +00003603 return P.str();
Simon Atanasyana47ba292012-10-31 14:39:28 +00003604 } else {
Mehdi Amini12011172016-10-06 05:11:48 +00003605 SmallString<128> P((PrefixDir + Name).str());
Rafael Espindola609a6642013-06-24 18:33:43 +00003606 if (llvm::sys::fs::can_execute(Twine(P)))
Rafael Espindola8be5c052013-06-19 13:24:29 +00003607 return P.str();
Simon Atanasyan86bdab72012-10-31 12:01:53 +00003608 }
Chandler Carruth84559242010-03-22 01:52:07 +00003609 }
3610
Daniel Dunbar68b01a02009-03-18 20:26:19 +00003611 const ToolChain::path_list &List = TC.getProgramPaths();
Saleem Abdulrasool23d99b12014-09-16 03:48:32 +00003612 for (const auto &Path : List) {
3613 SmallString<128> P(Path);
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00003614 if (ScanDirForExecutable(P, TargetSpecificExecutables))
Rafael Espindola8be5c052013-06-19 13:24:29 +00003615 return P.str();
Daniel Dunbar68b01a02009-03-18 20:26:19 +00003616 }
3617
Daniel Dunbar76ce7412009-03-23 16:15:50 +00003618 // If all else failed, search the path.
Michael J. Spencerb011d482014-11-07 21:30:32 +00003619 for (const auto &TargetSpecificExecutable : TargetSpecificExecutables)
3620 if (llvm::ErrorOr<std::string> P =
3621 llvm::sys::findProgramByName(TargetSpecificExecutable))
Michael J. Spencer04162ea2014-11-04 01:30:55 +00003622 return *P;
Daniel Dunbar6f668772009-03-18 21:34:08 +00003623
Daniel Dunbar1ce81532009-09-09 22:33:00 +00003624 return Name;
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00003625}
3626
Mehdi Amini12011172016-10-06 05:11:48 +00003627std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const {
Rafael Espindola37d229d2013-06-25 04:26:55 +00003628 SmallString<128> Path;
Rafael Espindolac0809172014-06-12 14:02:15 +00003629 std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
Rafael Espindola37d229d2013-06-25 04:26:55 +00003630 if (EC) {
3631 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
Daniel Dunbare627c1c2009-03-18 19:34:39 +00003632 return "";
3633 }
3634
Rafael Espindola37d229d2013-06-25 04:26:55 +00003635 return Path.str();
Daniel Dunbare627c1c2009-03-18 19:34:39 +00003636}
3637
Nico Weber2ca4be92016-03-01 23:16:44 +00003638std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
3639 SmallString<128> Output;
3640 if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
3641 // FIXME: If anybody needs it, implement this obscure rule:
3642 // "If you specify a directory without a file name, the default file name
3643 // is VCx0.pch., where x is the major version of Visual C++ in use."
3644 Output = FpArg->getValue();
3645
3646 // "If you do not specify an extension as part of the path name, an
3647 // extension of .pch is assumed. "
3648 if (!llvm::sys::path::has_extension(Output))
3649 Output += ".pch";
3650 } else {
3651 Output = BaseName;
3652 llvm::sys::path::replace_extension(Output, ".pch");
3653 }
3654 return Output.str();
3655}
3656
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003657const ToolChain &Driver::getToolChain(const ArgList &Args,
Artem Belevich959e0542015-07-10 19:47:55 +00003658 const llvm::Triple &Target) const {
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003659
Chandler Carruthd7fa2e02012-01-31 02:21:20 +00003660 ToolChain *&TC = ToolChains[Target.str()];
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003661 if (!TC) {
3662 switch (Target.getOS()) {
Reid Kleckner330fb172016-05-11 16:19:05 +00003663 case llvm::Triple::Haiku:
3664 TC = new toolchains::Haiku(*this, Target, Args);
3665 break;
Ed Schouten3c3e58c2015-03-26 11:13:44 +00003666 case llvm::Triple::CloudABI:
3667 TC = new toolchains::CloudABI(*this, Target, Args);
3668 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003669 case llvm::Triple::Darwin:
3670 case llvm::Triple::MacOSX:
3671 case llvm::Triple::IOS:
Tim Northover6f3ff222015-10-30 16:30:27 +00003672 case llvm::Triple::TvOS:
3673 case llvm::Triple::WatchOS:
Rafael Espindola14627962013-11-24 23:28:23 +00003674 TC = new toolchains::DarwinClang(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003675 break;
3676 case llvm::Triple::DragonFly:
Rafael Espindola1af7c212012-02-19 01:38:32 +00003677 TC = new toolchains::DragonFly(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003678 break;
3679 case llvm::Triple::OpenBSD:
Rafael Espindola1af7c212012-02-19 01:38:32 +00003680 TC = new toolchains::OpenBSD(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003681 break;
Eli Friedman9fa28852012-08-08 23:57:20 +00003682 case llvm::Triple::Bitrig:
3683 TC = new toolchains::Bitrig(*this, Target, Args);
3684 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003685 case llvm::Triple::NetBSD:
Rafael Espindola1af7c212012-02-19 01:38:32 +00003686 TC = new toolchains::NetBSD(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003687 break;
3688 case llvm::Triple::FreeBSD:
Rafael Espindola1af7c212012-02-19 01:38:32 +00003689 TC = new toolchains::FreeBSD(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003690 break;
3691 case llvm::Triple::Minix:
Rafael Espindola1af7c212012-02-19 01:38:32 +00003692 TC = new toolchains::Minix(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003693 break;
3694 case llvm::Triple::Linux:
Andrey Turetskiy4798eb62016-06-16 10:36:09 +00003695 case llvm::Triple::ELFIAMCU:
Chandler Carruthcf705b22012-01-25 21:03:58 +00003696 if (Target.getArch() == llvm::Triple::hexagon)
Douglas Katzman54366072015-07-27 16:53:08 +00003697 TC = new toolchains::HexagonToolChain(*this, Target, Args);
Vasileios Kalintirisc744e122015-11-12 15:26:54 +00003698 else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
3699 !Target.hasEnvironment())
3700 TC = new toolchains::MipsLLVMToolChain(*this, Target, Args);
Chandler Carruthcf705b22012-01-25 21:03:58 +00003701 else
Rafael Espindola1af7c212012-02-19 01:38:32 +00003702 TC = new toolchains::Linux(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003703 break;
Derek Schuff6ab52fa2015-03-30 20:31:33 +00003704 case llvm::Triple::NaCl:
Douglas Katzman54366072015-07-27 16:53:08 +00003705 TC = new toolchains::NaClToolChain(*this, Target, Args);
Derek Schuff6ab52fa2015-03-30 20:31:33 +00003706 break;
Petr Hosek62e1d232016-10-06 06:08:09 +00003707 case llvm::Triple::Fuchsia:
3708 TC = new toolchains::Fuchsia(*this, Target, Args);
3709 break;
David Chisnallf571cde2012-02-15 13:39:01 +00003710 case llvm::Triple::Solaris:
Rafael Espindola1af7c212012-02-19 01:38:32 +00003711 TC = new toolchains::Solaris(*this, Target, Args);
David Chisnallf571cde2012-02-15 13:39:01 +00003712 break;
Tom Stellard8fa33092015-07-18 01:49:05 +00003713 case llvm::Triple::AMDHSA:
3714 TC = new toolchains::AMDGPUToolChain(*this, Target, Args);
3715 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003716 case llvm::Triple::Win32:
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00003717 switch (Target.getEnvironment()) {
3718 default:
3719 if (Target.isOSBinFormatELF())
3720 TC = new toolchains::Generic_ELF(*this, Target, Args);
3721 else if (Target.isOSBinFormatMachO())
3722 TC = new toolchains::MachO(*this, Target, Args);
3723 else
3724 TC = new toolchains::Generic_GCC(*this, Target, Args);
3725 break;
3726 case llvm::Triple::GNU:
Yaron Keren1c0070c2015-07-02 04:45:27 +00003727 TC = new toolchains::MinGW(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00003728 break;
Saleem Abdulrasool543a78b2014-10-24 03:13:37 +00003729 case llvm::Triple::Itanium:
3730 TC = new toolchains::CrossWindowsToolChain(*this, Target, Args);
3731 break;
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00003732 case llvm::Triple::MSVC:
3733 case llvm::Triple::UnknownEnvironment:
Saleem Abdulrasool819f3912014-10-22 02:37:29 +00003734 TC = new toolchains::MSVCToolChain(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00003735 break;
3736 }
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003737 break;
Filipe Cabecinhasc888e192015-10-14 12:25:43 +00003738 case llvm::Triple::PS4:
3739 TC = new toolchains::PS4CPU(*this, Target, Args);
3740 break;
David L Kreitzerd397ea42016-10-14 20:44:33 +00003741 case llvm::Triple::Contiki:
3742 TC = new toolchains::Contiki(*this, Target, Args);
3743 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003744 default:
Douglas Katzman9f5e70e2015-05-26 18:01:33 +00003745 // Of these targets, Hexagon is the only one that might have
3746 // an OS of Linux, in which case it got handled above already.
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003747 switch (Target.getArch()) {
3748 case llvm::Triple::tce:
Rafael Espindola84b588b2013-03-18 18:10:27 +00003749 TC = new toolchains::TCEToolChain(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003750 break;
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00003751 case llvm::Triple::tcele:
3752 TC = new toolchains::TCELEToolChain(*this, Target, Args);
3753 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003754 case llvm::Triple::hexagon:
Douglas Katzman54366072015-07-27 16:53:08 +00003755 TC = new toolchains::HexagonToolChain(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003756 break;
Jacques Pienaard964cc22016-03-28 21:02:54 +00003757 case llvm::Triple::lanai:
3758 TC = new toolchains::LanaiToolChain(*this, Target, Args);
3759 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003760 case llvm::Triple::xcore:
Douglas Katzman54366072015-07-27 16:53:08 +00003761 TC = new toolchains::XCoreToolChain(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003762 break;
Dan Gohmanc2853072015-09-03 22:51:53 +00003763 case llvm::Triple::wasm32:
3764 case llvm::Triple::wasm64:
3765 TC = new toolchains::WebAssembly(*this, Target, Args);
3766 break;
Dylan McKay924fa3a2017-01-05 05:20:27 +00003767 case llvm::Triple::avr:
3768 TC = new toolchains::AVRToolChain(*this, Target, Args);
3769 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003770 default:
Douglas Katzmand6e597c2015-09-17 19:56:40 +00003771 if (Target.getVendor() == llvm::Triple::Myriad)
3772 TC = new toolchains::MyriadToolChain(*this, Target, Args);
3773 else if (Target.isOSBinFormatELF())
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003774 TC = new toolchains::Generic_ELF(*this, Target, Args);
3775 else if (Target.isOSBinFormatMachO())
3776 TC = new toolchains::MachO(*this, Target, Args);
3777 else
3778 TC = new toolchains::Generic_GCC(*this, Target, Args);
3779 }
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003780 }
3781 }
Justin Lebar66c4fd72016-11-18 00:41:22 +00003782
3783 // Intentionally omitted from the switch above: llvm::Triple::CUDA. CUDA
3784 // compiles always need two toolchains, the CUDA toolchain and the host
3785 // toolchain. So the only valid way to create a CUDA toolchain is via
3786 // CreateOffloadingDeviceToolChains.
3787
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003788 return *TC;
Daniel Dunbar4dff6a42009-03-10 23:41:59 +00003789}
Daniel Dunbar8fa879d2009-03-24 18:57:02 +00003790
Rafael Espindola2f69d402013-03-18 15:33:26 +00003791bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
Douglas Katzman00249092015-06-12 15:45:21 +00003792 // Say "no" if there is not exactly one input of a type clang understands.
Nico Weber5a459f82016-02-23 19:30:43 +00003793 if (JA.size() != 1 ||
3794 !types::isAcceptedByClang((*JA.input_begin())->getType()))
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00003795 return false;
3796
Douglas Katzman00249092015-06-12 15:45:21 +00003797 // And say "no" if this is not a kind of action clang understands.
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00003798 if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
Bob Wilson23a55f12014-12-21 07:00:00 +00003799 !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00003800 return false;
3801
3802 return true;
3803}
3804
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003805/// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
3806/// grouped values as integers. Numbers which are not provided are set to 0.
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003807///
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003808/// \return True if the entire string was parsed (9.2), or all groups were
3809/// parsed (10.3.5extrastuff).
Mehdi Amini12011172016-10-06 05:11:48 +00003810bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
3811 unsigned &Micro, bool &HadExtra) {
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003812 HadExtra = false;
3813
3814 Major = Minor = Micro = 0;
Mehdi Amini12011172016-10-06 05:11:48 +00003815 if (Str.empty())
Bob Wilson433cb312015-04-07 01:03:35 +00003816 return false;
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003817
Mehdi Amini12011172016-10-06 05:11:48 +00003818 if (Str.consumeInteger(10, Major))
3819 return false;
3820 if (Str.empty())
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003821 return true;
Mehdi Amini12011172016-10-06 05:11:48 +00003822 if (Str[0] != '.')
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003823 return false;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003824
Mehdi Amini12011172016-10-06 05:11:48 +00003825 Str = Str.drop_front(1);
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003826
Mehdi Amini12011172016-10-06 05:11:48 +00003827 if (Str.consumeInteger(10, Minor))
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003828 return false;
Mehdi Amini12011172016-10-06 05:11:48 +00003829 if (Str.empty())
3830 return true;
3831 if (Str[0] != '.')
3832 return false;
3833 Str = Str.drop_front(1);
3834
3835 if (Str.consumeInteger(10, Micro))
3836 return false;
3837 if (!Str.empty())
3838 HadExtra = true;
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003839 return true;
3840}
Hans Wennborg6ddc6902013-07-27 00:23:45 +00003841
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00003842/// Parse digits from a string \p Str and fulfill \p Digits with
3843/// the parsed numbers. This method assumes that the max number of
3844/// digits to look for is equal to Digits.size().
3845///
3846/// \return True if the entire string was parsed and there are
3847/// no extra characters remaining at the end.
Mehdi Amini12011172016-10-06 05:11:48 +00003848bool Driver::GetReleaseVersion(StringRef Str,
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00003849 MutableArrayRef<unsigned> Digits) {
Mehdi Amini12011172016-10-06 05:11:48 +00003850 if (Str.empty())
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00003851 return false;
3852
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00003853 unsigned CurDigit = 0;
3854 while (CurDigit < Digits.size()) {
Mehdi Amini12011172016-10-06 05:11:48 +00003855 unsigned Digit;
3856 if (Str.consumeInteger(10, Digit))
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00003857 return false;
Mehdi Amini12011172016-10-06 05:11:48 +00003858 Digits[CurDigit] = Digit;
3859 if (Str.empty())
3860 return true;
3861 if (Str[0] != '.')
3862 return false;
3863 Str = Str.drop_front(1);
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00003864 CurDigit++;
3865 }
3866
3867 // More digits than requested, bail out...
3868 return false;
3869}
3870
Hans Wennborg6ddc6902013-07-27 00:23:45 +00003871std::pair<unsigned, unsigned> Driver::getIncludeExcludeOptionFlagMasks() const {
3872 unsigned IncludedFlagsBitmask = 0;
Rafael Espindolacc707bc2013-09-25 15:54:41 +00003873 unsigned ExcludedFlagsBitmask = options::NoDriverOption;
Hans Wennborg6ddc6902013-07-27 00:23:45 +00003874
3875 if (Mode == CLMode) {
Hans Wennborg19076102013-07-31 20:51:53 +00003876 // Include CL and Core options.
3877 IncludedFlagsBitmask |= options::CLOption;
3878 IncludedFlagsBitmask |= options::CoreOption;
Hans Wennborg6ddc6902013-07-27 00:23:45 +00003879 } else {
3880 ExcludedFlagsBitmask |= options::CLOption;
3881 }
3882
3883 return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
3884}
Benjamin Kramerab88f622014-03-25 18:02:07 +00003885
Douglas Katzmanf08fadf2015-06-04 14:40:44 +00003886bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
Benjamin Kramerab88f622014-03-25 18:02:07 +00003887 return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);
3888}