blob: 583803de575bbbcaf6188c55e16b68201fceab43 [file] [log] [blame]
Nick Lewyckye47c2452010-09-23 23:48:20 +00001//===--- Driver.cpp - Clang GCC Compatible Driver -------------------------===//
Daniel Dunbar544ecd12009-03-02 19:59:07 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Daniel Dunbar544ecd12009-03-02 19:59:07 +000010#include "clang/Driver/Driver.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000011#include "InputInfo.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000012#include "ToolChains/AMDGPU.h"
13#include "ToolChains/AVR.h"
Ed Schouten4dabea22017-06-25 08:29:09 +000014#include "ToolChains/Ananas.h"
Yaxun Liuf6144222018-05-30 00:53:50 +000015#include "ToolChains/BareMetal.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000016#include "ToolChains/Clang.h"
17#include "ToolChains/CloudABI.h"
18#include "ToolChains/Contiki.h"
19#include "ToolChains/CrossWindows.h"
20#include "ToolChains/Cuda.h"
21#include "ToolChains/Darwin.h"
22#include "ToolChains/DragonFly.h"
23#include "ToolChains/FreeBSD.h"
24#include "ToolChains/Fuchsia.h"
25#include "ToolChains/Gnu.h"
Yaxun Liuf6144222018-05-30 00:53:50 +000026#include "ToolChains/HIP.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000027#include "ToolChains/Haiku.h"
28#include "ToolChains/Hexagon.h"
29#include "ToolChains/Lanai.h"
30#include "ToolChains/Linux.h"
Yaxun Liuf6144222018-05-30 00:53:50 +000031#include "ToolChains/MSVC.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000032#include "ToolChains/MinGW.h"
33#include "ToolChains/Minix.h"
Konstantin Zhuravlyove37b32c2017-03-08 22:36:04 +000034#include "ToolChains/MipsLinux.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000035#include "ToolChains/Myriad.h"
36#include "ToolChains/NaCl.h"
37#include "ToolChains/NetBSD.h"
38#include "ToolChains/OpenBSD.h"
39#include "ToolChains/PS4CPU.h"
Erik Pilkington46420b62018-09-27 20:36:28 +000040#include "ToolChains/RISCVToolchain.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000041#include "ToolChains/Solaris.h"
42#include "ToolChains/TCE.h"
43#include "ToolChains/WebAssembly.h"
44#include "ToolChains/XCore.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000045#include "clang/Basic/Version.h"
Alp Toker1d257e12014-06-04 03:28:55 +000046#include "clang/Config/config.h"
Daniel Dunbar1688f1a2009-03-12 07:58:46 +000047#include "clang/Driver/Action.h"
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000048#include "clang/Driver/Compilation.h"
Daniel Dunbarc0b3e952009-03-12 08:55:43 +000049#include "clang/Driver/DriverDiagnostic.h"
Daniel Dunbare75d8342009-03-16 06:56:51 +000050#include "clang/Driver/Job.h"
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000051#include "clang/Driver/Options.h"
Peter Collingbournea4ccff32015-02-20 20:30:56 +000052#include "clang/Driver/SanitizerArgs.h"
Daniel Dunbare75d8342009-03-16 06:56:51 +000053#include "clang/Driver/Tool.h"
54#include "clang/Driver/ToolChain.h"
Chris Lattnerce6c42f2011-03-23 04:04:01 +000055#include "llvm/ADT/ArrayRef.h"
Hans Wennborg6ddc6902013-07-27 00:23:45 +000056#include "llvm/ADT/STLExtras.h"
Justin Lebar62907612016-07-06 21:21:39 +000057#include "llvm/ADT/SmallSet.h"
Hans Wennborg23d26a32014-06-18 17:21:50 +000058#include "llvm/ADT/StringExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000059#include "llvm/ADT/StringSet.h"
Hans Wennborg70850d82013-07-18 20:29:38 +000060#include "llvm/ADT/StringSwitch.h"
Nico Weberd637c052018-04-30 13:52:15 +000061#include "llvm/Config/llvm-config.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000062#include "llvm/Option/Arg.h"
63#include "llvm/Option/ArgList.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000064#include "llvm/Option/OptSpecifier.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000065#include "llvm/Option/OptTable.h"
66#include "llvm/Option/Option.h"
Serge Pavlov208ac652018-01-01 13:27:01 +000067#include "llvm/Support/CommandLine.h"
David Blaikie79000202011-09-23 05:57:42 +000068#include "llvm/Support/ErrorHandling.h"
Michael J. Spencerf28df4c2010-12-17 21:22:22 +000069#include "llvm/Support/FileSystem.h"
Fangrui Songd0028232018-10-10 00:15:33 +000070#include "llvm/Support/FormatVariadic.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000071#include "llvm/Support/Path.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000072#include "llvm/Support/PrettyStackTrace.h"
Hans Wennborg23d26a32014-06-18 17:21:50 +000073#include "llvm/Support/Process.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000074#include "llvm/Support/Program.h"
Yaxun Liuf6144222018-05-30 00:53:50 +000075#include "llvm/Support/StringSaver.h"
Dimitry Andric81c40422017-06-06 21:54:21 +000076#include "llvm/Support/TargetRegistry.h"
Jonas Devliegherefc514902018-10-10 13:27:25 +000077#include "llvm/Support/VirtualFileSystem.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000078#include "llvm/Support/raw_ostream.h"
Dylan Noblesmith4f4e7452012-02-02 00:40:14 +000079#include <map>
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000080#include <memory>
Benjamin Kramercfeacf52016-05-27 14:27:13 +000081#include <utility>
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +000082#if LLVM_ON_UNIX
83#include <unistd.h> // getpid
Nick Desaulniers9d0df312018-10-15 17:39:00 +000084#include <sysexits.h> // EX_IOERR
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +000085#endif
Dylan Noblesmith86780e92012-02-01 14:25:28 +000086
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000087using namespace clang::driver;
Chris Lattnerada1c912009-03-26 05:56:24 +000088using namespace clang;
Reid Kleckner898229a2013-06-14 17:17:23 +000089using namespace llvm::opt;
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000090
Petr Hosekdd38d932018-05-29 22:35:39 +000091Driver::Driver(StringRef ClangExecutable, StringRef TargetTriple,
Benjamin Kramerd45b2052015-10-07 15:48:01 +000092 DiagnosticsEngine &Diags,
Jonas Devliegherefc514902018-10-10 13:27:25 +000093 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)
Benjamin Kramercfeacf52016-05-27 14:27:13 +000094 : Opts(createDriverOptTable()), Diags(Diags), VFS(std::move(VFS)),
95 Mode(GCCMode), SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
96 LTOMode(LTOK_None), ClangExecutable(ClangExecutable),
Alex Lorenz045c5142018-04-07 00:03:27 +000097 SysRoot(DEFAULT_SYSROOT), DriverTitle("clang LLVM compiler"),
98 CCPrintOptionsFilename(nullptr), CCPrintHeadersFilename(nullptr),
99 CCLogDiagnosticsFilename(nullptr), CCCPrintBindings(false),
100 CCPrintOptions(false), CCPrintHeaders(false), CCLogDiagnostics(false),
Petr Hosekdd38d932018-05-29 22:35:39 +0000101 CCGenDiagnostics(false), TargetTriple(TargetTriple),
Alex Lorenz045c5142018-04-07 00:03:27 +0000102 CCCGenericGCCName(""), Saver(Alloc), CheckInputsExist(true),
103 CCCUsePCH(true), GenReproducer(false),
104 SuppressMissingInputWarning(false) {
Daniel Dunbar3f3e2cd2010-01-20 02:35:16 +0000105
Benjamin Kramerd45b2052015-10-07 15:48:01 +0000106 // Provide a sane fallback if no VFS is specified.
107 if (!this->VFS)
Jonas Devliegherefc514902018-10-10 13:27:25 +0000108 this->VFS = llvm::vfs::getRealFileSystem();
Benjamin Kramerd45b2052015-10-07 15:48:01 +0000109
Sumanth Gundapaneni3a1592942015-03-03 20:43:12 +0000110 Name = llvm::sys::path::filename(ClangExecutable);
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000111 Dir = llvm::sys::path::parent_path(ClangExecutable);
Benjamin Kramerf420dda2015-10-13 15:19:32 +0000112 InstalledDir = Dir; // Provide a sensible default installed dir.
Bob Wilsona20a1da2013-03-23 05:17:59 +0000113
Serge Pavlov208ac652018-01-01 13:27:01 +0000114#if defined(CLANG_CONFIG_FILE_SYSTEM_DIR)
115 SystemConfigDir = CLANG_CONFIG_FILE_SYSTEM_DIR;
116#endif
117#if defined(CLANG_CONFIG_FILE_USER_DIR)
118 UserConfigDir = CLANG_CONFIG_FILE_USER_DIR;
119#endif
120
Bob Wilsona20a1da2013-03-23 05:17:59 +0000121 // Compute the path to the resource directory.
122 StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
123 SmallString<128> P(Dir);
Chandler Carruthfd3cc702014-12-29 12:09:08 +0000124 if (ClangResourceDir != "") {
Bob Wilsona20a1da2013-03-23 05:17:59 +0000125 llvm::sys::path::append(P, ClangResourceDir);
Chandler Carruthfd3cc702014-12-29 12:09:08 +0000126 } else {
127 StringRef ClangLibdirSuffix(CLANG_LIBDIR_SUFFIX);
Argyrios Kyrtzidisbcae0472017-02-25 18:14:35 +0000128 P = llvm::sys::path::parent_path(Dir);
129 llvm::sys::path::append(P, Twine("lib") + ClangLibdirSuffix, "clang",
Chandler Carruthfd3cc702014-12-29 12:09:08 +0000130 CLANG_VERSION_STRING);
131 }
Bob Wilsona20a1da2013-03-23 05:17:59 +0000132 ResourceDir = P.str();
Daniel Dunbar544ecd12009-03-02 19:59:07 +0000133}
134
Zachary Turneraff19c32016-08-12 17:47:52 +0000135void Driver::ParseDriverMode(StringRef ProgramName,
136 ArrayRef<const char *> Args) {
Martin Storsjo1fab23d2018-04-25 21:23:59 +0000137 if (ClangNameParts.isEmpty())
138 ClangNameParts = ToolChain::getTargetAndModeFromProgramName(ProgramName);
Serge Pavlov4e769842017-08-29 05:22:26 +0000139 setDriverModeFromOption(ClangNameParts.DriverMode);
Hans Wennborg70850d82013-07-18 20:29:38 +0000140
Douglas Katzman6bbffc42015-06-25 18:51:37 +0000141 for (const char *ArgPtr : Args) {
Erich Keane258f0592018-02-07 00:19:58 +0000142 // Ignore nullptrs, they are the response file's EOL markers.
Douglas Katzman6bbffc42015-06-25 18:51:37 +0000143 if (ArgPtr == nullptr)
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000144 continue;
Douglas Katzman6bbffc42015-06-25 18:51:37 +0000145 const StringRef Arg = ArgPtr;
Zachary Turneraff19c32016-08-12 17:47:52 +0000146 setDriverModeFromOption(Arg);
Hans Wennborg70850d82013-07-18 20:29:38 +0000147 }
148}
149
Zachary Turneraff19c32016-08-12 17:47:52 +0000150void Driver::setDriverModeFromOption(StringRef Opt) {
151 const std::string OptName =
152 getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
153 if (!Opt.startswith(OptName))
154 return;
155 StringRef Value = Opt.drop_front(OptName.size());
156
Erich Keane2908a042018-02-12 17:47:01 +0000157 if (auto M = llvm::StringSwitch<llvm::Optional<DriverMode>>(Value)
158 .Case("gcc", GCCMode)
159 .Case("g++", GXXMode)
160 .Case("cpp", CPPMode)
161 .Case("cl", CLMode)
162 .Default(None))
163 Mode = *M;
Zachary Turneraff19c32016-08-12 17:47:52 +0000164 else
165 Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
166}
167
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000168InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings,
169 bool &ContainsError) {
Daniel Dunbar2608c542009-03-18 01:38:48 +0000170 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000171 ContainsError = false;
Hans Wennborg6ddc6902013-07-27 00:23:45 +0000172
173 unsigned IncludedFlagsBitmask;
174 unsigned ExcludedFlagsBitmask;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000175 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000176 getIncludeExcludeOptionFlagMasks();
Hans Wennborg6ddc6902013-07-27 00:23:45 +0000177
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000178 unsigned MissingArgIndex, MissingArgCount;
David Blaikie69a1d8c2015-06-22 22:07:27 +0000179 InputArgList Args =
David Blaikie6d492ad2015-06-21 06:32:36 +0000180 getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
181 IncludedFlagsBitmask, ExcludedFlagsBitmask);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +0000182
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000183 // Check for missing argument error.
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000184 if (MissingArgCount) {
185 Diag(diag::err_drv_missing_argument)
David Blaikie69a1d8c2015-06-22 22:07:27 +0000186 << Args.getArgString(MissingArgIndex) << MissingArgCount;
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000187 ContainsError |=
188 Diags.getDiagnosticLevel(diag::err_drv_missing_argument,
189 SourceLocation()) > DiagnosticsEngine::Warning;
190 }
Daniel Dunbar65229332009-03-13 11:38:42 +0000191
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000192 // Check for unsupported options.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000193 for (const Arg *A : Args) {
Michael J. Spencer66e2b202012-10-19 22:37:06 +0000194 if (A->getOption().hasFlag(options::Unsupported)) {
Brian Gesiak24910762018-01-06 00:25:40 +0000195 unsigned DiagID;
196 auto ArgString = A->getAsString(Args);
197 std::string Nearest;
198 if (getOpts().findNearest(
199 ArgString, Nearest, IncludedFlagsBitmask,
200 ExcludedFlagsBitmask | options::Unsupported) > 1) {
201 DiagID = diag::err_drv_unsupported_opt;
202 Diag(DiagID) << ArgString;
203 } else {
204 DiagID = diag::err_drv_unsupported_opt_with_suggestion;
205 Diag(DiagID) << ArgString << Nearest;
206 }
207 ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000208 DiagnosticsEngine::Warning;
Daniel Dunbard8500f32009-03-22 23:26:43 +0000209 continue;
210 }
Chad Rosierce975d92012-02-22 17:55:22 +0000211
212 // Warn about -mcpu= without an argument.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000213 if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000214 Diag(diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
215 ContainsError |= Diags.getDiagnosticLevel(
216 diag::warn_drv_empty_joined_argument,
217 SourceLocation()) > DiagnosticsEngine::Warning;
Chad Rosierce975d92012-02-22 17:55:22 +0000218 }
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000219 }
220
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000221 for (const Arg *A : Args.filtered(options::OPT_UNKNOWN)) {
Brian Gesiak24910762018-01-06 00:25:40 +0000222 unsigned DiagID;
223 auto ArgString = A->getAsString(Args);
224 std::string Nearest;
225 if (getOpts().findNearest(
226 ArgString, Nearest, IncludedFlagsBitmask, ExcludedFlagsBitmask) > 1) {
227 DiagID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl
228 : diag::err_drv_unknown_argument;
229 Diags.Report(DiagID) << ArgString;
230 } else {
231 DiagID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl_with_suggestion
232 : diag::err_drv_unknown_argument_with_suggestion;
233 Diags.Report(DiagID) << ArgString << Nearest;
234 }
235 ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000236 DiagnosticsEngine::Warning;
237 }
Rafael Espindola8a2d4962013-09-23 23:55:25 +0000238
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000239 return Args;
240}
241
Chad Rosier7742b5d2011-07-27 23:36:45 +0000242// Determine which compilation mode we are in. We look for options which
243// affect the phase, starting with the earliest phases, and record which
244// option we used to determine the final phase.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000245phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
246 Arg **FinalPhaseArg) const {
Craig Topper92fc2df2014-05-17 16:56:41 +0000247 Arg *PhaseArg = nullptr;
Chad Rosier7742b5d2011-07-27 23:36:45 +0000248 phases::ID FinalPhase;
Eric Christopherf901e852011-08-17 22:59:59 +0000249
Hans Wennborge50cec32014-06-13 20:59:54 +0000250 // -{E,EP,P,M,MM} only run the preprocessor.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000251 if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
Hans Wennborge50cec32014-06-13 20:59:54 +0000252 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
Hans Wennborge0053472013-12-20 18:40:46 +0000253 (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
254 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000255 FinalPhase = phases::Preprocess;
Eric Christopherf901e852011-08-17 22:59:59 +0000256
Richard Smithdd4ad3d2016-08-30 19:06:26 +0000257 // --precompile only runs up to precompilation.
258 } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile))) {
259 FinalPhase = phases::Precompile;
260
Bob Wilson23a55f12014-12-21 07:00:00 +0000261 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
Chad Rosier7742b5d2011-07-27 23:36:45 +0000262 } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000263 (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
Ben Langmuir2cb4a782014-02-05 22:21:15 +0000264 (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
Chad Rosier7742b5d2011-07-27 23:36:45 +0000265 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
Fariborz Jahanian73223bb2012-04-02 15:59:19 +0000266 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
Ted Kremenekf7639e12012-03-06 20:06:33 +0000267 (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
Chad Rosier7742b5d2011-07-27 23:36:45 +0000268 (PhaseArg = DAL.getLastArg(options::OPT__analyze,
Chad Rosier1aeb15a2012-03-06 23:14:35 +0000269 options::OPT__analyze_auto)) ||
Bob Wilson23a55f12014-12-21 07:00:00 +0000270 (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000271 FinalPhase = phases::Compile;
272
Bob Wilson23a55f12014-12-21 07:00:00 +0000273 // -S only runs up to the backend.
274 } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
275 FinalPhase = phases::Backend;
276
Artem Belevich4242f412015-07-28 21:01:21 +0000277 // -c compilation only runs up to the assembler.
278 } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000279 FinalPhase = phases::Assemble;
280
281 // Otherwise do everything.
282 } else
283 FinalPhase = phases::Link;
284
285 if (FinalPhaseArg)
286 *FinalPhaseArg = PhaseArg;
287
288 return FinalPhase;
289}
290
David Blaikie0aaa7622017-01-13 17:34:15 +0000291static Arg *MakeInputArg(DerivedArgList &Args, OptTable &Opts,
Martin Storsjo665c7a42018-05-04 06:05:58 +0000292 StringRef Value, bool Claim = true) {
David Blaikie0aaa7622017-01-13 17:34:15 +0000293 Arg *A = new Arg(Opts.getOption(options::OPT_INPUT), Value,
Hans Wennborged1d0722013-08-13 21:32:29 +0000294 Args.getBaseArgs().MakeIndex(Value), Value.data());
Hans Wennborg55362852014-05-02 22:55:30 +0000295 Args.AddSynthesizedArg(A);
Martin Storsjo665c7a42018-05-04 06:05:58 +0000296 if (Claim)
297 A->claim();
Hans Wennborged1d0722013-08-13 21:32:29 +0000298 return A;
299}
300
Daniel Dunbar775d4062010-06-11 22:00:26 +0000301DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
302 DerivedArgList *DAL = new DerivedArgList(Args);
303
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000304 bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
Nirav Daveb0bb6142015-11-24 16:07:21 +0000305 bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +0000306 for (Arg *A : Args) {
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000307 // Unfortunately, we have to parse some forwarding options (-Xassembler,
308 // -Xlinker, -Xpreprocessor) because we either integrate their functionality
309 // (assembler and preprocessor), or bypass a previous driver ('collect2').
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000310
311 // Rewrite linker options, to replace --no-demangle with a custom internal
312 // option.
313 if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
314 A->getOption().matches(options::OPT_Xlinker)) &&
315 A->containsValue("--no-demangle")) {
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000316 // Add the rewritten no-demangle argument.
317 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
318
319 // Add the remaining values as Xlinker arguments.
Benjamin Kramer72e64312015-09-24 14:48:49 +0000320 for (StringRef Val : A->getValues())
Douglas Katzmana34b7bf2015-06-30 19:32:57 +0000321 if (Val != "--no-demangle")
322 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), Val);
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000323
324 continue;
325 }
326
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000327 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
328 // some build systems. We don't try to be complete here because we don't
329 // care to encourage this usage model.
330 if (A->getOption().matches(options::OPT_Wp_COMMA) &&
Richard Smithbd55daf2012-11-01 04:30:05 +0000331 (A->getValue(0) == StringRef("-MD") ||
332 A->getValue(0) == StringRef("-MMD"))) {
Daniel Dunbar3648ba72010-06-15 20:30:18 +0000333 // Rewrite to -MD/-MMD along with -MF.
Richard Smithbd55daf2012-11-01 04:30:05 +0000334 if (A->getValue(0) == StringRef("-MD"))
Daniel Dunbar3648ba72010-06-15 20:30:18 +0000335 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
336 else
337 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
Michael J. Spencer70d85be2012-11-07 23:37:14 +0000338 if (A->getNumValues() == 2)
339 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
340 A->getValue(1));
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000341 continue;
342 }
343
Shantonu Senafeb03b2010-09-17 18:39:08 +0000344 // Rewrite reserved library names.
345 if (A->getOption().matches(options::OPT_l)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000346 StringRef Value = A->getValue();
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000347
Shantonu Senafeb03b2010-09-17 18:39:08 +0000348 // Rewrite unless -nostdlib is present.
Nirav Daveb0bb6142015-11-24 16:07:21 +0000349 if (!HasNostdlib && !HasNodefaultlib && Value == "stdc++") {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000350 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_stdcxx));
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000351 continue;
352 }
Shantonu Senafeb03b2010-09-17 18:39:08 +0000353
354 // Rewrite unconditionally.
355 if (Value == "cc_kext") {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000356 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_cckext));
Shantonu Senafeb03b2010-09-17 18:39:08 +0000357 continue;
358 }
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000359 }
360
Hans Wennborged1d0722013-08-13 21:32:29 +0000361 // Pick up inputs via the -- option.
362 if (A->getOption().matches(options::OPT__DASH_DASH)) {
363 A->claim();
Benjamin Kramer72e64312015-09-24 14:48:49 +0000364 for (StringRef Val : A->getValues())
Martin Storsjo665c7a42018-05-04 06:05:58 +0000365 DAL->append(MakeInputArg(*DAL, *Opts, Val, false));
Hans Wennborged1d0722013-08-13 21:32:29 +0000366 continue;
367 }
368
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +0000369 DAL->append(A);
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000370 }
Daniel Dunbar775d4062010-06-11 22:00:26 +0000371
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000372 // Enforce -static if -miamcu is present.
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000373 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false))
374 DAL->AddFlagArg(0, Opts->getOption(options::OPT_static));
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000375
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000376// Add a default value of -mlinker-version=, if one was given and the user
377// didn't specify one.
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000378#if defined(HOST_LINK_VERSION)
Tim Northover018578c2015-06-12 19:21:35 +0000379 if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
380 strlen(HOST_LINK_VERSION) > 0) {
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000381 DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
382 HOST_LINK_VERSION);
Daniel Dunbarb613ffc2010-08-17 22:32:45 +0000383 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000384 }
385#endif
386
Daniel Dunbar775d4062010-06-11 22:00:26 +0000387 return DAL;
388}
389
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000390/// Compute target triple from args.
Artem Belevich959e0542015-07-10 19:47:55 +0000391///
392/// This routine provides the logic to compute a target triple from various
393/// args passed to the driver and the default triple string.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000394static llvm::Triple computeTargetTriple(const Driver &D,
Petr Hosekdd38d932018-05-29 22:35:39 +0000395 StringRef TargetTriple,
Artem Belevich959e0542015-07-10 19:47:55 +0000396 const ArgList &Args,
397 StringRef DarwinArchName = "") {
398 // FIXME: Already done in Compilation *Driver::BuildCompilation
399 if (const Arg *A = Args.getLastArg(options::OPT_target))
Petr Hosekdd38d932018-05-29 22:35:39 +0000400 TargetTriple = A->getValue();
Artem Belevich959e0542015-07-10 19:47:55 +0000401
Petr Hosekdd38d932018-05-29 22:35:39 +0000402 llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
Artem Belevich959e0542015-07-10 19:47:55 +0000403
404 // Handle Apple-specific options available here.
405 if (Target.isOSBinFormatMachO()) {
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000406 // If an explicit Darwin arch name is given, that trumps all.
Artem Belevich959e0542015-07-10 19:47:55 +0000407 if (!DarwinArchName.empty()) {
408 tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
409 return Target;
410 }
411
412 // Handle the Darwin '-arch' flag.
413 if (Arg *A = Args.getLastArg(options::OPT_arch)) {
414 StringRef ArchName = A->getValue();
415 tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
416 }
417 }
418
419 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
420 // '-mbig-endian'/'-EB'.
421 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
422 options::OPT_mbig_endian)) {
423 if (A->getOption().matches(options::OPT_mlittle_endian)) {
424 llvm::Triple LE = Target.getLittleEndianArchVariant();
425 if (LE.getArch() != llvm::Triple::UnknownArch)
426 Target = std::move(LE);
427 } else {
428 llvm::Triple BE = Target.getBigEndianArchVariant();
429 if (BE.getArch() != llvm::Triple::UnknownArch)
430 Target = std::move(BE);
431 }
432 }
433
434 // Skip further flag support on OSes which don't support '-m32' or '-m64'.
Douglas Katzman15a63ed2015-08-12 18:36:12 +0000435 if (Target.getArch() == llvm::Triple::tce ||
436 Target.getOS() == llvm::Triple::Minix)
Artem Belevich959e0542015-07-10 19:47:55 +0000437 return Target;
438
439 // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000440 Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
441 options::OPT_m32, options::OPT_m16);
442 if (A) {
Artem Belevich959e0542015-07-10 19:47:55 +0000443 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
444
445 if (A->getOption().matches(options::OPT_m64)) {
446 AT = Target.get64BitArchVariant().getArch();
447 if (Target.getEnvironment() == llvm::Triple::GNUX32)
448 Target.setEnvironment(llvm::Triple::GNU);
449 } else if (A->getOption().matches(options::OPT_mx32) &&
450 Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
451 AT = llvm::Triple::x86_64;
452 Target.setEnvironment(llvm::Triple::GNUX32);
453 } else if (A->getOption().matches(options::OPT_m32)) {
454 AT = Target.get32BitArchVariant().getArch();
455 if (Target.getEnvironment() == llvm::Triple::GNUX32)
456 Target.setEnvironment(llvm::Triple::GNU);
457 } else if (A->getOption().matches(options::OPT_m16) &&
458 Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
459 AT = llvm::Triple::x86;
460 Target.setEnvironment(llvm::Triple::CODE16);
461 }
462
463 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
464 Target.setArch(AT);
465 }
466
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000467 // Handle -miamcu flag.
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000468 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
469 if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
470 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
471 << Target.str();
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000472
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000473 if (A && !A->getOption().matches(options::OPT_m32))
474 D.Diag(diag::err_drv_argument_not_allowed_with)
475 << "-miamcu" << A->getBaseArg().getAsString(Args);
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000476
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000477 Target.setArch(llvm::Triple::x86);
478 Target.setArchName("i586");
479 Target.setEnvironment(llvm::Triple::UnknownEnvironment);
480 Target.setEnvironmentName("");
481 Target.setOS(llvm::Triple::ELFIAMCU);
482 Target.setVendor(llvm::Triple::UnknownVendor);
483 Target.setVendorName("intel");
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000484 }
485
Simon Atanasyan0c0fb4b2018-09-27 05:04:50 +0000486 // If target is MIPS adjust the target triple
487 // accordingly to provided ABI name.
488 A = Args.getLastArg(options::OPT_mabi_EQ);
Simon Atanasyane60eae42018-10-16 10:19:06 +0000489 if (A && Target.isMIPS()) {
490 StringRef ABIName = A->getValue();
491 if (ABIName == "32") {
492 Target = Target.get32BitArchVariant();
493 if (Target.getEnvironment() == llvm::Triple::GNUABI64 ||
494 Target.getEnvironment() == llvm::Triple::GNUABIN32)
495 Target.setEnvironment(llvm::Triple::GNU);
496 } else if (ABIName == "n32") {
497 Target = Target.get64BitArchVariant();
498 if (Target.getEnvironment() == llvm::Triple::GNU ||
499 Target.getEnvironment() == llvm::Triple::GNUABI64)
500 Target.setEnvironment(llvm::Triple::GNUABIN32);
501 } else if (ABIName == "64") {
502 Target = Target.get64BitArchVariant();
503 if (Target.getEnvironment() == llvm::Triple::GNU ||
504 Target.getEnvironment() == llvm::Triple::GNUABIN32)
505 Target.setEnvironment(llvm::Triple::GNUABI64);
506 }
507 }
Simon Atanasyan0c0fb4b2018-09-27 05:04:50 +0000508
Artem Belevich959e0542015-07-10 19:47:55 +0000509 return Target;
510}
511
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000512// Parse the LTO options and record the type of LTO compilation
Teresa Johnson945bc502015-10-15 20:35:53 +0000513// based on which -f(no-)?lto(=.*)? option occurs last.
514void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
515 LTOMode = LTOK_None;
516 if (!Args.hasFlag(options::OPT_flto, options::OPT_flto_EQ,
517 options::OPT_fno_lto, false))
518 return;
519
520 StringRef LTOName("full");
521
522 const Arg *A = Args.getLastArg(options::OPT_flto_EQ);
Teresa Johnson6ef80dc2015-11-02 18:03:12 +0000523 if (A)
524 LTOName = A->getValue();
Teresa Johnson945bc502015-10-15 20:35:53 +0000525
526 LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
527 .Case("full", LTOK_Full)
528 .Case("thin", LTOK_Thin)
529 .Default(LTOK_Unknown);
530
531 if (LTOMode == LTOK_Unknown) {
532 assert(A);
533 Diag(diag::err_drv_unsupported_option_argument) << A->getOption().getName()
534 << A->getValue();
535 }
536}
537
Samuel Antao39f9da22016-10-27 16:38:05 +0000538/// Compute the desired OpenMP runtime from the flags provided.
539Driver::OpenMPRuntimeKind Driver::getOpenMPRuntime(const ArgList &Args) const {
540 StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
541
542 const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
543 if (A)
544 RuntimeName = A->getValue();
545
546 auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
547 .Case("libomp", OMPRT_OMP)
548 .Case("libgomp", OMPRT_GOMP)
549 .Case("libiomp5", OMPRT_IOMP5)
550 .Default(OMPRT_Unknown);
551
552 if (RT == OMPRT_Unknown) {
553 if (A)
554 Diag(diag::err_drv_unsupported_option_argument)
555 << A->getOption().getName() << A->getValue();
556 else
557 // FIXME: We could use a nicer diagnostic here.
558 Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
559 }
560
561 return RT;
562}
563
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000564void Driver::CreateOffloadingDeviceToolChains(Compilation &C,
565 InputList &Inputs) {
566
567 //
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000568 // CUDA/HIP
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000569 //
Yaxun Liuf6144222018-05-30 00:53:50 +0000570 // We need to generate a CUDA/HIP toolchain if any of the inputs has a CUDA
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000571 // or HIP type. However, mixed CUDA/HIP compilation is not supported.
572 bool IsCuda =
573 llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000574 return types::isCuda(I.first);
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000575 });
576 bool IsHIP =
577 llvm::any_of(Inputs,
578 [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
579 return types::isHIP(I.first);
580 }) ||
581 C.getInputArgs().hasArg(options::OPT_hip_link);
582 if (IsCuda && IsHIP) {
583 Diag(clang::diag::err_drv_mix_cuda_hip);
584 return;
585 }
Yaxun Liuf6144222018-05-30 00:53:50 +0000586 if (IsCuda) {
Justin Lebar66c4fd72016-11-18 00:41:22 +0000587 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
588 const llvm::Triple &HostTriple = HostTC->getTriple();
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000589 StringRef DeviceTripleStr;
Yaxun Liuf6144222018-05-30 00:53:50 +0000590 auto OFK = Action::OFK_Cuda;
591 DeviceTripleStr =
592 HostTriple.isArch64Bit() ? "nvptx64-nvidia-cuda" : "nvptx-nvidia-cuda";
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000593 llvm::Triple CudaTriple(DeviceTripleStr);
Yaxun Liuf6144222018-05-30 00:53:50 +0000594 // Use the CUDA and host triples as the key into the ToolChains map,
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000595 // because the device toolchain we create depends on both.
David Blaikie6ad71012017-01-13 18:53:43 +0000596 auto &CudaTC = ToolChains[CudaTriple.str() + "/" + HostTriple.str()];
Justin Lebar66c4fd72016-11-18 00:41:22 +0000597 if (!CudaTC) {
David Blaikie6ad71012017-01-13 18:53:43 +0000598 CudaTC = llvm::make_unique<toolchains::CudaToolChain>(
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000599 *this, CudaTriple, *HostTC, C.getInputArgs(), OFK);
Justin Lebar66c4fd72016-11-18 00:41:22 +0000600 }
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000601 C.addOffloadDeviceToolChain(CudaTC.get(), OFK);
Yaxun Liuf6144222018-05-30 00:53:50 +0000602 } else if (IsHIP) {
603 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
604 const llvm::Triple &HostTriple = HostTC->getTriple();
605 StringRef DeviceTripleStr;
606 auto OFK = Action::OFK_HIP;
607 DeviceTripleStr = "amdgcn-amd-amdhsa";
608 llvm::Triple HIPTriple(DeviceTripleStr);
609 // Use the HIP and host triples as the key into the ToolChains map,
610 // because the device toolchain we create depends on both.
611 auto &HIPTC = ToolChains[HIPTriple.str() + "/" + HostTriple.str()];
612 if (!HIPTC) {
613 HIPTC = llvm::make_unique<toolchains::HIPToolChain>(
614 *this, HIPTriple, *HostTC, C.getInputArgs());
615 }
616 C.addOffloadDeviceToolChain(HIPTC.get(), OFK);
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000617 }
618
619 //
Samuel Antao39f9da22016-10-27 16:38:05 +0000620 // OpenMP
621 //
622 // We need to generate an OpenMP toolchain if the user specified targets with
623 // the -fopenmp-targets option.
624 if (Arg *OpenMPTargets =
625 C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
626 if (OpenMPTargets->getNumValues()) {
627 // We expect that -fopenmp-targets is always used in conjunction with the
628 // option -fopenmp specifying a valid runtime with offloading support,
629 // i.e. libomp or libiomp.
630 bool HasValidOpenMPRuntime = C.getInputArgs().hasFlag(
631 options::OPT_fopenmp, options::OPT_fopenmp_EQ,
632 options::OPT_fno_openmp, false);
633 if (HasValidOpenMPRuntime) {
634 OpenMPRuntimeKind OpenMPKind = getOpenMPRuntime(C.getInputArgs());
635 HasValidOpenMPRuntime =
636 OpenMPKind == OMPRT_OMP || OpenMPKind == OMPRT_IOMP5;
637 }
638
639 if (HasValidOpenMPRuntime) {
640 llvm::StringMap<const char *> FoundNormalizedTriples;
641 for (const char *Val : OpenMPTargets->getValues()) {
642 llvm::Triple TT(Val);
643 std::string NormalizedName = TT.normalize();
644
645 // Make sure we don't have a duplicate triple.
646 auto Duplicate = FoundNormalizedTriples.find(NormalizedName);
647 if (Duplicate != FoundNormalizedTriples.end()) {
648 Diag(clang::diag::warn_drv_omp_offload_target_duplicate)
649 << Val << Duplicate->second;
650 continue;
651 }
652
653 // Store the current triple so that we can check for duplicates in the
654 // following iterations.
655 FoundNormalizedTriples[NormalizedName] = Val;
656
657 // If the specified target is invalid, emit a diagnostic.
658 if (TT.getArch() == llvm::Triple::UnknownArch)
659 Diag(clang::diag::err_drv_invalid_omp_target) << Val;
660 else {
Gheorghe-Teodor Bercea6a5df722017-07-06 16:08:15 +0000661 const ToolChain *TC;
662 // CUDA toolchains have to be selected differently. They pair host
663 // and device in their implementation.
664 if (TT.isNVPTX()) {
665 const ToolChain *HostTC =
666 C.getSingleOffloadToolChain<Action::OFK_Host>();
667 assert(HostTC && "Host toolchain should be always defined.");
668 auto &CudaTC =
Gheorghe-Teodor Bercea52898432017-08-09 01:02:19 +0000669 ToolChains[TT.str() + "/" + HostTC->getTriple().normalize()];
Gheorghe-Teodor Bercea6a5df722017-07-06 16:08:15 +0000670 if (!CudaTC)
671 CudaTC = llvm::make_unique<toolchains::CudaToolChain>(
Gheorghe-Teodor Bercea2c926932017-08-08 14:33:05 +0000672 *this, TT, *HostTC, C.getInputArgs(), Action::OFK_OpenMP);
Gheorghe-Teodor Bercea6a5df722017-07-06 16:08:15 +0000673 TC = CudaTC.get();
674 } else
675 TC = &getToolChain(C.getInputArgs(), TT);
676 C.addOffloadDeviceToolChain(TC, Action::OFK_OpenMP);
Samuel Antao39f9da22016-10-27 16:38:05 +0000677 }
678 }
679 } else
680 Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
681 } else
682 Diag(clang::diag::warn_drv_empty_joined_argument)
683 << OpenMPTargets->getAsString(C.getInputArgs());
684 }
685
686 //
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000687 // TODO: Add support for other offloading programming models here.
688 //
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000689}
690
Serge Pavlov208ac652018-01-01 13:27:01 +0000691/// Looks the given directories for the specified file.
692///
693/// \param[out] FilePath File path, if the file was found.
694/// \param[in] Dirs Directories used for the search.
695/// \param[in] FileName Name of the file to search for.
696/// \return True if file was found.
697///
698/// Looks for file specified by FileName sequentially in directories specified
699/// by Dirs.
700///
701static bool searchForFile(SmallVectorImpl<char> &FilePath,
702 ArrayRef<std::string> Dirs,
703 StringRef FileName) {
704 SmallString<128> WPath;
705 for (const StringRef &Dir : Dirs) {
706 if (Dir.empty())
707 continue;
708 WPath.clear();
709 llvm::sys::path::append(WPath, Dir, FileName);
710 llvm::sys::path::native(WPath);
711 if (llvm::sys::fs::is_regular_file(WPath)) {
712 FilePath = std::move(WPath);
713 return true;
714 }
715 }
716 return false;
717}
718
719bool Driver::readConfigFile(StringRef FileName) {
720 // Try reading the given file.
721 SmallVector<const char *, 32> NewCfgArgs;
722 if (!llvm::cl::readConfigFile(FileName, Saver, NewCfgArgs)) {
723 Diag(diag::err_drv_cannot_read_config_file) << FileName;
724 return true;
725 }
726
727 // Read options from config file.
728 llvm::SmallString<128> CfgFileName(FileName);
729 llvm::sys::path::native(CfgFileName);
730 ConfigFile = CfgFileName.str();
731 bool ContainErrors;
732 CfgOptions = llvm::make_unique<InputArgList>(
733 ParseArgStrings(NewCfgArgs, ContainErrors));
734 if (ContainErrors) {
735 CfgOptions.reset();
736 return true;
737 }
738
739 if (CfgOptions->hasArg(options::OPT_config)) {
740 CfgOptions.reset();
741 Diag(diag::err_drv_nested_config_file);
742 return true;
743 }
744
745 // Claim all arguments that come from a configuration file so that the driver
746 // does not warn on any that is unused.
747 for (Arg *A : *CfgOptions)
748 A->claim();
749 return false;
750}
751
752bool Driver::loadConfigFile() {
753 std::string CfgFileName;
754 bool FileSpecifiedExplicitly = false;
755
756 // Process options that change search path for config files.
757 if (CLOptions) {
758 if (CLOptions->hasArg(options::OPT_config_system_dir_EQ)) {
759 SmallString<128> CfgDir;
760 CfgDir.append(
761 CLOptions->getLastArgValue(options::OPT_config_system_dir_EQ));
762 if (!CfgDir.empty()) {
Sam McCall296d8322018-01-02 09:35:10 +0000763 if (llvm::sys::fs::make_absolute(CfgDir).value() != 0)
Serge Pavlov208ac652018-01-01 13:27:01 +0000764 SystemConfigDir.clear();
765 else
766 SystemConfigDir = std::string(CfgDir.begin(), CfgDir.end());
767 }
768 }
769 if (CLOptions->hasArg(options::OPT_config_user_dir_EQ)) {
770 SmallString<128> CfgDir;
771 CfgDir.append(
772 CLOptions->getLastArgValue(options::OPT_config_user_dir_EQ));
773 if (!CfgDir.empty()) {
Sam McCall296d8322018-01-02 09:35:10 +0000774 if (llvm::sys::fs::make_absolute(CfgDir).value() != 0)
Serge Pavlov208ac652018-01-01 13:27:01 +0000775 UserConfigDir.clear();
776 else
777 UserConfigDir = std::string(CfgDir.begin(), CfgDir.end());
778 }
779 }
780 }
781
782 // First try to find config file specified in command line.
783 if (CLOptions) {
784 std::vector<std::string> ConfigFiles =
785 CLOptions->getAllArgValues(options::OPT_config);
786 if (ConfigFiles.size() > 1) {
787 Diag(diag::err_drv_duplicate_config);
788 return true;
789 }
790
791 if (!ConfigFiles.empty()) {
792 CfgFileName = ConfigFiles.front();
793 assert(!CfgFileName.empty());
794
795 // If argument contains directory separator, treat it as a path to
796 // configuration file.
797 if (llvm::sys::path::has_parent_path(CfgFileName)) {
798 SmallString<128> CfgFilePath;
799 if (llvm::sys::path::is_relative(CfgFileName))
800 llvm::sys::fs::current_path(CfgFilePath);
801 llvm::sys::path::append(CfgFilePath, CfgFileName);
802 if (!llvm::sys::fs::is_regular_file(CfgFilePath)) {
803 Diag(diag::err_drv_config_file_not_exist) << CfgFilePath;
804 return true;
805 }
806 return readConfigFile(CfgFilePath);
807 }
808
809 FileSpecifiedExplicitly = true;
810 }
811 }
812
813 // If config file is not specified explicitly, try to deduce configuration
814 // from executable name. For instance, an executable 'armv7l-clang' will
815 // search for config file 'armv7l-clang.cfg'.
816 if (CfgFileName.empty() && !ClangNameParts.TargetPrefix.empty())
817 CfgFileName = ClangNameParts.TargetPrefix + '-' + ClangNameParts.ModeSuffix;
818
819 if (CfgFileName.empty())
820 return false;
821
822 // Determine architecture part of the file name, if it is present.
823 StringRef CfgFileArch = CfgFileName;
824 size_t ArchPrefixLen = CfgFileArch.find('-');
825 if (ArchPrefixLen == StringRef::npos)
826 ArchPrefixLen = CfgFileArch.size();
827 llvm::Triple CfgTriple;
828 CfgFileArch = CfgFileArch.take_front(ArchPrefixLen);
829 CfgTriple = llvm::Triple(llvm::Triple::normalize(CfgFileArch));
830 if (CfgTriple.getArch() == llvm::Triple::ArchType::UnknownArch)
831 ArchPrefixLen = 0;
832
833 if (!StringRef(CfgFileName).endswith(".cfg"))
834 CfgFileName += ".cfg";
835
836 // If config file starts with architecture name and command line options
837 // redefine architecture (with options like -m32 -LE etc), try finding new
838 // config file with that architecture.
839 SmallString<128> FixedConfigFile;
840 size_t FixedArchPrefixLen = 0;
841 if (ArchPrefixLen) {
842 // Get architecture name from config file name like 'i386.cfg' or
843 // 'armv7l-clang.cfg'.
844 // Check if command line options changes effective triple.
845 llvm::Triple EffectiveTriple = computeTargetTriple(*this,
846 CfgTriple.getTriple(), *CLOptions);
847 if (CfgTriple.getArch() != EffectiveTriple.getArch()) {
848 FixedConfigFile = EffectiveTriple.getArchName();
849 FixedArchPrefixLen = FixedConfigFile.size();
850 // Append the rest of original file name so that file name transforms
851 // like: i386-clang.cfg -> x86_64-clang.cfg.
852 if (ArchPrefixLen < CfgFileName.size())
853 FixedConfigFile += CfgFileName.substr(ArchPrefixLen);
854 }
855 }
856
857 // Prepare list of directories where config file is searched for.
858 SmallVector<std::string, 3> CfgFileSearchDirs;
859 CfgFileSearchDirs.push_back(UserConfigDir);
860 CfgFileSearchDirs.push_back(SystemConfigDir);
861 CfgFileSearchDirs.push_back(Dir);
862
863 // Try to find config file. First try file with corrected architecture.
864 llvm::SmallString<128> CfgFilePath;
865 if (!FixedConfigFile.empty()) {
866 if (searchForFile(CfgFilePath, CfgFileSearchDirs, FixedConfigFile))
867 return readConfigFile(CfgFilePath);
868 // If 'x86_64-clang.cfg' was not found, try 'x86_64.cfg'.
869 FixedConfigFile.resize(FixedArchPrefixLen);
870 FixedConfigFile.append(".cfg");
871 if (searchForFile(CfgFilePath, CfgFileSearchDirs, FixedConfigFile))
872 return readConfigFile(CfgFilePath);
873 }
874
875 // Then try original file name.
876 if (searchForFile(CfgFilePath, CfgFileSearchDirs, CfgFileName))
877 return readConfigFile(CfgFilePath);
878
879 // Finally try removing driver mode part: 'x86_64-clang.cfg' -> 'x86_64.cfg'.
880 if (!ClangNameParts.ModeSuffix.empty() &&
881 !ClangNameParts.TargetPrefix.empty()) {
882 CfgFileName.assign(ClangNameParts.TargetPrefix);
883 CfgFileName.append(".cfg");
884 if (searchForFile(CfgFilePath, CfgFileSearchDirs, CfgFileName))
885 return readConfigFile(CfgFilePath);
886 }
887
888 // Report error but only if config file was specified explicitly, by option
889 // --config. If it was deduced from executable name, it is not an error.
890 if (FileSpecifiedExplicitly) {
891 Diag(diag::err_drv_config_file_not_found) << CfgFileName;
892 for (const std::string &SearchDir : CfgFileSearchDirs)
893 if (!SearchDir.empty())
894 Diag(diag::note_drv_config_file_searched_in) << SearchDir;
895 return true;
896 }
897
898 return false;
899}
900
Chris Lattner54b16772011-07-23 17:14:25 +0000901Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
Daniel Dunbar2608c542009-03-18 01:38:48 +0000902 llvm::PrettyStackTraceString CrashInfo("Compilation construction");
903
Eric Christopherf901e852011-08-17 22:59:59 +0000904 // FIXME: Handle environment options which affect driver behavior, somewhere
Bill Wendlingadbeb9f2012-03-12 21:24:57 +0000905 // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
Chad Rosier82301162011-09-14 00:47:55 +0000906
David Majnemer85c25b42016-07-24 17:44:03 +0000907 if (Optional<std::string> CompilerPathValue =
908 llvm::sys::Process::GetEnv("COMPILER_PATH")) {
909 StringRef CompilerPath = *CompilerPathValue;
Chad Rosier82301162011-09-14 00:47:55 +0000910 while (!CompilerPath.empty()) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000911 std::pair<StringRef, StringRef> Split =
912 CompilerPath.split(llvm::sys::EnvPathSeparator);
Chad Rosier82301162011-09-14 00:47:55 +0000913 PrefixDirs.push_back(Split.first);
914 CompilerPath = Split.second;
915 }
916 }
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +0000917
Hans Wennborg70850d82013-07-18 20:29:38 +0000918 // We look for the driver mode option early, because the mode can affect
919 // how other options are parsed.
Zachary Turneraff19c32016-08-12 17:47:52 +0000920 ParseDriverMode(ClangExecutable, ArgList.slice(1));
Hans Wennborg70850d82013-07-18 20:29:38 +0000921
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +0000922 // FIXME: What are we going to do with -V and -b?
923
Serge Pavlov208ac652018-01-01 13:27:01 +0000924 // Arguments specified in command line.
925 bool ContainsError;
926 CLOptions = llvm::make_unique<InputArgList>(
927 ParseArgStrings(ArgList.slice(1), ContainsError));
928
929 // Try parsing configuration file.
930 if (!ContainsError)
931 ContainsError = loadConfigFile();
932 bool HasConfigFile = !ContainsError && (CfgOptions.get() != nullptr);
933
934 // All arguments, from both config file and command line.
935 InputArgList Args = std::move(HasConfigFile ? std::move(*CfgOptions)
936 : std::move(*CLOptions));
937 if (HasConfigFile)
938 for (auto *Opt : *CLOptions) {
Serge Pavlovf015a562018-04-26 06:28:47 +0000939 if (Opt->getOption().matches(options::OPT_config))
940 continue;
941 unsigned Index = Args.MakeIndex(Opt->getSpelling());
Serge Pavlov208ac652018-01-01 13:27:01 +0000942 const Arg *BaseArg = &Opt->getBaseArg();
943 if (BaseArg == Opt)
944 BaseArg = nullptr;
945 Arg *Copy = new llvm::opt::Arg(Opt->getOption(), Opt->getSpelling(),
Serge Pavlovf015a562018-04-26 06:28:47 +0000946 Index, BaseArg);
Serge Pavlov208ac652018-01-01 13:27:01 +0000947 Copy->getValues() = Opt->getValues();
948 if (Opt->isClaimed())
949 Copy->claim();
950 Args.append(Copy);
951 }
952
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +0000953 // FIXME: This stuff needs to go into the Compilation, not the driver.
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +0000954 bool CCCPrintPhases;
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000955
Filipe Cabecinhas136f35e2015-07-18 06:35:24 +0000956 // Silence driver warnings if requested
957 Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w));
958
Rafael Espindola59ae7992009-12-07 18:28:29 +0000959 // -no-canonical-prefixes is used very early in main.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000960 Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
Rafael Espindola59ae7992009-12-07 18:28:29 +0000961
Daniel Dunbar926f81f2010-08-02 02:38:03 +0000962 // Ignore -pipe.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000963 Args.ClaimAllArgs(options::OPT_pipe);
Daniel Dunbar926f81f2010-08-02 02:38:03 +0000964
Daniel Dunbaracd69572009-12-04 21:55:23 +0000965 // Extract -ccc args.
Daniel Dunbaree66cf22009-03-10 20:52:46 +0000966 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +0000967 // FIXME: We need to figure out where this behavior should live. Most of it
968 // should be outside in the client; the parts that aren't should have proper
969 // options, either by introducing new ones or by overloading gcc ones like -V
970 // or -b.
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +0000971 CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
David Blaikie69a1d8c2015-06-22 22:07:27 +0000972 CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
973 if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
Richard Smithbd55daf2012-11-01 04:30:05 +0000974 CCCGenericGCCName = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000975 CCCUsePCH =
976 Args.hasFlag(options::OPT_ccc_pch_is_pch, options::OPT_ccc_pch_is_pth);
Bruno Cardoso Lopes52dfe712017-04-12 21:46:20 +0000977 GenReproducer = Args.hasFlag(options::OPT_gen_reproducer,
978 options::OPT_fno_crash_diagnostics,
979 !!::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH"));
Petr Hosekdd38d932018-05-29 22:35:39 +0000980 // FIXME: TargetTriple is used by the target-prefixed calls to as/ld
Joerg Sonnenberger17d75512012-02-22 19:15:16 +0000981 // and getToolChain is const.
Hans Wennborg2e274592013-08-13 23:38:57 +0000982 if (IsCLMode()) {
Hans Wennborg73609a02014-03-28 01:19:04 +0000983 // clang-cl targets MSVC-style Win32.
Petr Hosekdd38d932018-05-29 22:35:39 +0000984 llvm::Triple T(TargetTriple);
Hans Wennborg9d9ce7a2014-03-28 20:49:28 +0000985 T.setOS(llvm::Triple::Win32);
Hans Wennborg0f0e8d62015-09-18 17:11:50 +0000986 T.setVendor(llvm::Triple::PC);
Hans Wennborg9d9ce7a2014-03-28 20:49:28 +0000987 T.setEnvironment(llvm::Triple::MSVC);
Oleg Ranevskyy80523182017-08-31 20:31:30 +0000988 T.setObjectFormat(llvm::Triple::COFF);
Petr Hosekdd38d932018-05-29 22:35:39 +0000989 TargetTriple = T.str();
Hans Wennborg2e274592013-08-13 23:38:57 +0000990 }
David Blaikie69a1d8c2015-06-22 22:07:27 +0000991 if (const Arg *A = Args.getLastArg(options::OPT_target))
Petr Hosekdd38d932018-05-29 22:35:39 +0000992 TargetTriple = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000993 if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
Richard Smithbd55daf2012-11-01 04:30:05 +0000994 Dir = InstalledDir = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000995 for (const Arg *A : Args.filtered(options::OPT_B)) {
Benjamin Kramer1a648d12011-02-08 20:31:42 +0000996 A->claim();
Richard Smithbd55daf2012-11-01 04:30:05 +0000997 PrefixDirs.push_back(A->getValue(0));
Benjamin Kramer1a648d12011-02-08 20:31:42 +0000998 }
David Blaikie69a1d8c2015-06-22 22:07:27 +0000999 if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
Richard Smithbd55daf2012-11-01 04:30:05 +00001000 SysRoot = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +00001001 if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
Peter Collingbourne9d9e1fc2013-05-27 21:40:20 +00001002 DyldPrefix = A->getValue();
Daniel Dunbaree66cf22009-03-10 20:52:46 +00001003
David Blaikie69a1d8c2015-06-22 22:07:27 +00001004 if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
Bob Wilsona20a1da2013-03-23 05:17:59 +00001005 ResourceDir = A->getValue();
Jim Grosbach061dabf2013-03-12 20:17:58 +00001006
David Blaikie69a1d8c2015-06-22 22:07:27 +00001007 if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
Reid Kleckner68eb60b2015-02-02 22:41:48 +00001008 SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
1009 .Case("cwd", SaveTempsCwd)
1010 .Case("obj", SaveTempsObj)
1011 .Default(SaveTempsCwd);
1012 }
1013
Steven Wu1257cd82016-05-18 17:04:52 +00001014 setLTOMode(Args);
1015
Steven Wu844ab6a2016-11-16 06:06:44 +00001016 // Process -fembed-bitcode= flags.
1017 if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
1018 StringRef Name = A->getValue();
1019 unsigned Model = llvm::StringSwitch<unsigned>(Name)
1020 .Case("off", EmbedNone)
1021 .Case("all", EmbedBitcode)
1022 .Case("bitcode", EmbedBitcode)
1023 .Case("marker", EmbedMarker)
1024 .Default(~0U);
1025 if (Model == ~0U) {
1026 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
1027 << Name;
1028 } else
1029 BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
Steven Wu574b0f22016-03-01 01:07:58 +00001030 }
1031
David Blaikie69a1d8c2015-06-22 22:07:27 +00001032 std::unique_ptr<llvm::opt::InputArgList> UArgs =
1033 llvm::make_unique<InputArgList>(std::move(Args));
1034
Daniel Dunbar775d4062010-06-11 22:00:26 +00001035 // Perform the default argument translations.
David Blaikie69a1d8c2015-06-22 22:07:27 +00001036 DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
Daniel Dunbar775d4062010-06-11 22:00:26 +00001037
Chandler Carruthcb916192012-01-25 08:49:21 +00001038 // Owned by the host.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +00001039 const ToolChain &TC = getToolChain(
Petr Hosekdd38d932018-05-29 22:35:39 +00001040 *UArgs, computeTargetTriple(*this, TargetTriple, *UArgs));
Chandler Carruthcb916192012-01-25 08:49:21 +00001041
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00001042 // The compilation takes ownership of Args.
Benjamin Kramer43c0f482017-06-30 13:21:27 +00001043 Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs,
1044 ContainsError);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001045
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001046 if (!HandleImmediateArgs(*C))
1047 return C;
1048
Chad Rosierecdede82011-08-12 22:08:57 +00001049 // Construct the list of inputs.
1050 InputList Inputs;
Hans Wennborged1d0722013-08-13 21:32:29 +00001051 BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
Chad Rosierecdede82011-08-12 22:08:57 +00001052
Samuel Antaoc1ffba52016-06-13 18:10:57 +00001053 // Populate the tool chains for the offloading devices, if any.
1054 CreateOffloadingDeviceToolChains(*C, Inputs);
Justin Lebar0e450a52016-03-30 23:30:25 +00001055
Chandler Carruth7f1417f2012-01-24 10:43:44 +00001056 // Construct the list of abstract actions to perform for this compilation. On
Tim Northover157d9112014-01-16 08:48:16 +00001057 // MachO targets this uses the driver-driver and universal actions.
1058 if (TC.getTriple().isOSBinFormatMachO())
Artem Belevich5e2a3ec2015-11-17 22:28:40 +00001059 BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001060 else
Justin Lebar0f3474c2016-02-11 02:00:50 +00001061 BuildActions(*C, C->getArgs(), Inputs, C->getActions());
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001062
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001063 if (CCCPrintPhases) {
Daniel Dunbareb843be2009-03-18 03:13:20 +00001064 PrintActions(*C);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001065 return C;
1066 }
1067
1068 BuildJobs(*C);
Daniel Dunbaradc91e62009-03-15 01:38:15 +00001069
1070 return C;
Daniel Dunbaree66cf22009-03-10 20:52:46 +00001071}
1072
Justin Bognered9cbe02015-07-09 06:58:31 +00001073static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
1074 llvm::opt::ArgStringList ASL;
1075 for (const auto *A : Args)
1076 A->render(Args, ASL);
1077
1078 for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
1079 if (I != ASL.begin())
1080 OS << ' ';
1081 Command::printArg(OS, *I, true);
1082 }
1083 OS << '\n';
1084}
1085
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +00001086bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename,
1087 SmallString<128> &CrashDiagDir) {
1088 using namespace llvm::sys;
1089 assert(llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin() &&
1090 "Only knows about .crash files on Darwin");
1091
1092 // The .crash file can be found on at ~/Library/Logs/DiagnosticReports/
1093 // (or /Library/Logs/DiagnosticReports for root) and has the filename pattern
1094 // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash.
1095 path::home_directory(CrashDiagDir);
1096 if (CrashDiagDir.startswith("/var/root"))
1097 CrashDiagDir = "/";
1098 path::append(CrashDiagDir, "Library/Logs/DiagnosticReports");
1099 int PID =
1100#if LLVM_ON_UNIX
1101 getpid();
1102#else
1103 0;
1104#endif
1105 std::error_code EC;
1106 fs::file_status FileStatus;
1107 TimePoint<> LastAccessTime;
1108 SmallString<128> CrashFilePath;
1109 // Lookup the .crash files and get the one generated by a subprocess spawned
1110 // by this driver invocation.
1111 for (fs::directory_iterator File(CrashDiagDir, EC), FileEnd;
1112 File != FileEnd && !EC; File.increment(EC)) {
1113 StringRef FileName = path::filename(File->path());
1114 if (!FileName.startswith(Name))
1115 continue;
1116 if (fs::status(File->path(), FileStatus))
1117 continue;
1118 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CrashFile =
1119 llvm::MemoryBuffer::getFile(File->path());
1120 if (!CrashFile)
1121 continue;
1122 // The first line should start with "Process:", otherwise this isn't a real
1123 // .crash file.
1124 StringRef Data = CrashFile.get()->getBuffer();
1125 if (!Data.startswith("Process:"))
1126 continue;
1127 // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]"
1128 size_t ParentProcPos = Data.find("Parent Process:");
1129 if (ParentProcPos == StringRef::npos)
1130 continue;
1131 size_t LineEnd = Data.find_first_of("\n", ParentProcPos);
1132 if (LineEnd == StringRef::npos)
1133 continue;
1134 StringRef ParentProcess = Data.slice(ParentProcPos+15, LineEnd).trim();
1135 int OpenBracket = -1, CloseBracket = -1;
1136 for (size_t i = 0, e = ParentProcess.size(); i < e; ++i) {
1137 if (ParentProcess[i] == '[')
1138 OpenBracket = i;
1139 if (ParentProcess[i] == ']')
1140 CloseBracket = i;
1141 }
1142 // Extract the parent process PID from the .crash file and check whether
1143 // it matches this driver invocation pid.
1144 int CrashPID;
1145 if (OpenBracket < 0 || CloseBracket < 0 ||
1146 ParentProcess.slice(OpenBracket + 1, CloseBracket)
1147 .getAsInteger(10, CrashPID) || CrashPID != PID) {
1148 continue;
1149 }
1150
1151 // Found a .crash file matching the driver pid. To avoid getting an older
1152 // and misleading crash file, continue looking for the most recent.
1153 // FIXME: the driver can dispatch multiple cc1 invocations, leading to
1154 // multiple crashes poiting to the same parent process. Since the driver
1155 // does not collect pid information for the dispatched invocation there's
1156 // currently no way to distinguish among them.
1157 const auto FileAccessTime = FileStatus.getLastModificationTime();
1158 if (FileAccessTime > LastAccessTime) {
1159 CrashFilePath.assign(File->path());
1160 LastAccessTime = FileAccessTime;
1161 }
1162 }
1163
1164 // If found, copy it over to the location of other reproducer files.
1165 if (!CrashFilePath.empty()) {
1166 EC = fs::copy_file(CrashFilePath, ReproCrashFilename);
1167 if (EC)
1168 return false;
1169 return true;
1170 }
1171
1172 return false;
1173}
1174
Eric Christopherf901e852011-08-17 22:59:59 +00001175// When clang crashes, produce diagnostic information including the fully
1176// preprocessed source file(s). Request that the developer attach the
Chad Rosierbe10f982011-08-02 17:58:04 +00001177// diagnostic information to a bug report.
Alex Lorenz045c5142018-04-07 00:03:27 +00001178void Driver::generateCompilationDiagnostics(
1179 Compilation &C, const Command &FailingCommand,
1180 StringRef AdditionalInformation, CompilationDiagnosticReport *Report) {
Chad Rosier877c0a22012-02-22 00:30:39 +00001181 if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
Chad Rosier62135492012-07-09 17:31:28 +00001182 return;
Chad Rosierbee5a1d2012-03-07 00:30:40 +00001183
Chad Rosierdbf46a12013-02-01 18:30:26 +00001184 // Don't try to generate diagnostics for link or dsymutil jobs.
Justin Bognere1a33d12014-10-20 21:02:05 +00001185 if (FailingCommand.getCreator().isLinkJob() ||
1186 FailingCommand.getCreator().isDsymutilJob())
Chad Rosier877c0a22012-02-22 00:30:39 +00001187 return;
1188
Chad Rosier8179f112012-06-19 17:51:34 +00001189 // Print the version of the compiler.
1190 PrintVersion(C, llvm::errs());
1191
Chad Rosierbe10f982011-08-02 17:58:04 +00001192 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001193 << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the "
1194 "crash backtrace, preprocessed source, and associated run script.";
Chad Rosierbe10f982011-08-02 17:58:04 +00001195
1196 // Suppress driver output and emit preprocessor output to temp file.
Hans Wennborg70850d82013-07-18 20:29:38 +00001197 Mode = CPPMode;
Chad Rosierbe10f982011-08-02 17:58:04 +00001198 CCGenDiagnostics = true;
1199
Chad Rosiercdb008d2011-11-02 21:29:05 +00001200 // Save the original job command(s).
Justin Bogner25645152014-10-21 17:24:44 +00001201 Command Cmd = FailingCommand;
Chad Rosiercdb008d2011-11-02 21:29:05 +00001202
Richard Smith5bb4cdf2012-12-20 02:22:15 +00001203 // Keep track of whether we produce any errors while trying to produce
1204 // preprocessed sources.
1205 DiagnosticErrorTrap Trap(Diags);
1206
1207 // Suppress tool output.
Chad Rosierbe10f982011-08-02 17:58:04 +00001208 C.initCompilationForDiagnostics();
Chad Rosierecdede82011-08-12 22:08:57 +00001209
1210 // Construct the list of inputs.
1211 InputList Inputs;
1212 BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
Chad Rosierbe10f982011-08-02 17:58:04 +00001213
Chad Rosier4f81fc22011-08-12 23:30:05 +00001214 for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
Chad Rosierd57133d2011-08-18 00:22:25 +00001215 bool IgnoreInput = false;
1216
1217 // Ignore input from stdin or any inputs that cannot be preprocessed.
Paul Robinsonf44157d2014-04-28 22:24:44 +00001218 // Check type first as not all linker inputs have a value.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001219 if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
Paul Robinsonf44157d2014-04-28 22:24:44 +00001220 IgnoreInput = true;
1221 } else if (!strcmp(it->second->getValue(), "-")) {
Chad Rosierd57133d2011-08-18 00:22:25 +00001222 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001223 << "Error generating preprocessed source(s) - "
1224 "ignoring input from stdin.";
Chad Rosierd57133d2011-08-18 00:22:25 +00001225 IgnoreInput = true;
Chad Rosierd57133d2011-08-18 00:22:25 +00001226 }
1227
1228 if (IgnoreInput) {
Chad Rosier4f81fc22011-08-12 23:30:05 +00001229 it = Inputs.erase(it);
1230 ie = Inputs.end();
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001231 } else {
Chad Rosier4f81fc22011-08-12 23:30:05 +00001232 ++it;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001233 }
Chad Rosier4f81fc22011-08-12 23:30:05 +00001234 }
Chad Rosierd57133d2011-08-18 00:22:25 +00001235
Chad Rosierc5103c32013-01-29 23:57:10 +00001236 if (Inputs.empty()) {
1237 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001238 << "Error generating preprocessed source(s) - "
1239 "no preprocessable inputs.";
Chad Rosierc5103c32013-01-29 23:57:10 +00001240 return;
1241 }
1242
Chad Rosiere75ef402011-09-06 23:52:36 +00001243 // Don't attempt to generate preprocessed files if multiple -arch options are
Chad Rosier636d2832012-02-13 18:16:28 +00001244 // used, unless they're all duplicates.
1245 llvm::StringSet<> ArchNames;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00001246 for (const Arg *A : C.getArgs()) {
Chad Rosiere75ef402011-09-06 23:52:36 +00001247 if (A->getOption().matches(options::OPT_arch)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001248 StringRef ArchName = A->getValue();
Chad Rosier636d2832012-02-13 18:16:28 +00001249 ArchNames.insert(ArchName);
Chad Rosiere75ef402011-09-06 23:52:36 +00001250 }
1251 }
Chad Rosier636d2832012-02-13 18:16:28 +00001252 if (ArchNames.size() > 1) {
1253 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001254 << "Error generating preprocessed source(s) - cannot generate "
1255 "preprocessed source with multiple -arch options.";
Chad Rosier636d2832012-02-13 18:16:28 +00001256 return;
1257 }
Chad Rosiere75ef402011-09-06 23:52:36 +00001258
Chandler Carruth7f1417f2012-01-24 10:43:44 +00001259 // Construct the list of abstract actions to perform for this compilation. On
1260 // Darwin OSes this uses the driver-driver and builds universal actions.
Chandler Carruthcb916192012-01-25 08:49:21 +00001261 const ToolChain &TC = C.getDefaultToolChain();
Tim Northover157d9112014-01-16 08:48:16 +00001262 if (TC.getTriple().isOSBinFormatMachO())
Artem Belevich5e2a3ec2015-11-17 22:28:40 +00001263 BuildUniversalActions(C, TC, Inputs);
Chad Rosierbe10f982011-08-02 17:58:04 +00001264 else
Justin Lebar0f3474c2016-02-11 02:00:50 +00001265 BuildActions(C, C.getArgs(), Inputs, C.getActions());
Chad Rosierbe10f982011-08-02 17:58:04 +00001266
1267 BuildJobs(C);
1268
1269 // If there were errors building the compilation, quit now.
Richard Smith5bb4cdf2012-12-20 02:22:15 +00001270 if (Trap.hasErrorOccurred()) {
Chad Rosierbe10f982011-08-02 17:58:04 +00001271 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001272 << "Error generating preprocessed source(s).";
Chad Rosierbe10f982011-08-02 17:58:04 +00001273 return;
1274 }
1275
1276 // Generate preprocessed output.
Chad Rosierdd60e092013-01-29 20:15:05 +00001277 SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
Justin Bogner0cd92482015-07-02 22:52:08 +00001278 C.ExecuteJobs(C.getJobs(), FailingCommands);
Chad Rosierbe10f982011-08-02 17:58:04 +00001279
Justin Bognerbc89b182014-10-20 21:20:27 +00001280 // If any of the preprocessing commands failed, clean up and exit.
1281 if (!FailingCommands.empty()) {
Chad Rosierbe10f982011-08-02 17:58:04 +00001282 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001283 << "Error generating preprocessed source(s).";
Justin Bognerbc89b182014-10-20 21:20:27 +00001284 return;
Chad Rosierbe10f982011-08-02 17:58:04 +00001285 }
Justin Bognerbc89b182014-10-20 21:20:27 +00001286
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001287 const ArgStringList &TempFiles = C.getTempFiles();
1288 if (TempFiles.empty()) {
1289 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001290 << "Error generating preprocessed source(s).";
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001291 return;
1292 }
1293
Justin Bognerbc89b182014-10-20 21:20:27 +00001294 Diag(clang::diag::note_drv_command_failed_diag_msg)
1295 << "\n********************\n\n"
1296 "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
1297 "Preprocessed source(s) and associated run script(s) are located at:";
Justin Bognerbc89b182014-10-20 21:20:27 +00001298
Justin Bogner659ecc32014-10-20 22:47:23 +00001299 SmallString<128> VFS;
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +00001300 SmallString<128> ReproCrashFilename;
Justin Bogner659ecc32014-10-20 22:47:23 +00001301 for (const char *TempFile : TempFiles) {
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001302 Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
Alex Lorenz045c5142018-04-07 00:03:27 +00001303 if (Report)
1304 Report->TemporaryFiles.push_back(TempFile);
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +00001305 if (ReproCrashFilename.empty()) {
1306 ReproCrashFilename = TempFile;
1307 llvm::sys::path::replace_extension(ReproCrashFilename, ".crash");
1308 }
Justin Bogner659ecc32014-10-20 22:47:23 +00001309 if (StringRef(TempFile).endswith(".cache")) {
1310 // In some cases (modules) we'll dump extra data to help with reproducing
1311 // the crash into a directory next to the output.
1312 VFS = llvm::sys::path::filename(TempFile);
1313 llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
1314 }
1315 }
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001316
1317 // Assume associated files are based off of the first temporary file.
Justin Bogner25645152014-10-21 17:24:44 +00001318 CrashReportInfo CrashInfo(TempFiles[0], VFS);
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001319
Bob Haarman7e4d3ff2018-07-09 21:07:20 +00001320 llvm::SmallString<128> Script(CrashInfo.Filename);
1321 llvm::sys::path::replace_extension(Script, "sh");
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001322 std::error_code EC;
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001323 llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::CD_CreateNew);
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001324 if (EC) {
1325 Diag(clang::diag::note_drv_command_failed_diag_msg)
Bob Haarman7e4d3ff2018-07-09 21:07:20 +00001326 << "Error generating run script: " << Script << " " << EC.message();
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001327 } else {
Justin Bogner42220ed2015-03-12 00:14:35 +00001328 ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
Justin Bognered9cbe02015-07-09 06:58:31 +00001329 << "# Driver args: ";
1330 printArgList(ScriptOS, C.getInputArgs());
1331 ScriptOS << "# Original command: ";
Justin Bogner42220ed2015-03-12 00:14:35 +00001332 Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
Justin Bogner33bdbc62014-10-21 18:03:08 +00001333 Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
Alex Lorenz045c5142018-04-07 00:03:27 +00001334 if (!AdditionalInformation.empty())
1335 ScriptOS << "\n# Additional information: " << AdditionalInformation
1336 << "\n";
1337 if (Report)
Bob Haarman7e4d3ff2018-07-09 21:07:20 +00001338 Report->TemporaryFiles.push_back(Script.str());
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001339 Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
Justin Bognerbc89b182014-10-20 21:20:27 +00001340 }
Saleem Abdulrasool3661a822015-01-12 02:33:09 +00001341
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +00001342 // On darwin, provide information about the .crash diagnostic report.
1343 if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) {
1344 SmallString<128> CrashDiagDir;
1345 if (getCrashDiagnosticFile(ReproCrashFilename, CrashDiagDir)) {
1346 Diag(clang::diag::note_drv_command_failed_diag_msg)
1347 << ReproCrashFilename.str();
1348 } else { // Suggest a directory for the user to look for .crash files.
1349 llvm::sys::path::append(CrashDiagDir, Name);
1350 CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash";
1351 Diag(clang::diag::note_drv_command_failed_diag_msg)
1352 << "Crash backtrace is located in";
1353 Diag(clang::diag::note_drv_command_failed_diag_msg)
1354 << CrashDiagDir.str();
1355 Diag(clang::diag::note_drv_command_failed_diag_msg)
1356 << "(choose the .crash file that corresponds to your crash)";
1357 }
1358 }
1359
Saleem Abdulrasool3661a822015-01-12 02:33:09 +00001360 for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file,
1361 options::OPT_frewrite_map_file_EQ))
1362 Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
1363
Justin Bognerbc89b182014-10-20 21:20:27 +00001364 Diag(clang::diag::note_drv_command_failed_diag_msg)
1365 << "\n\n********************";
Chad Rosierbe10f982011-08-02 17:58:04 +00001366}
1367
Justin Bogner0cd92482015-07-02 22:52:08 +00001368void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
Oleg Ranevskyycd516372016-01-05 19:54:39 +00001369 // Since commandLineFitsWithinSystemLimits() may underestimate system's capacity
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001370 // if the tool does not support response files, there is a chance/ that things
1371 // will just work without a response file, so we silently just skip it.
Justin Bogner0cd92482015-07-02 22:52:08 +00001372 if (Cmd.getCreator().getResponseFilesSupport() == Tool::RF_None ||
Oleg Ranevskyycd516372016-01-05 19:54:39 +00001373 llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(), Cmd.getArguments()))
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001374 return;
1375
1376 std::string TmpName = GetTemporaryPath("response", "txt");
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00001377 Cmd.setResponseFile(C.addTempFile(C.getArgs().MakeArgString(TmpName)));
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001378}
1379
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001380int Driver::ExecuteCompilation(
1381 Compilation &C,
1382 SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001383 // Just print if -### was present.
1384 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
Hans Wennborgb212b342013-09-12 18:23:34 +00001385 C.getJobs().Print(llvm::errs(), "\n", true);
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001386 return 0;
1387 }
1388
1389 // If there were errors building the compilation, quit now.
Chad Rosierbe10f982011-08-02 17:58:04 +00001390 if (Diags.hasErrorOccurred())
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001391 return 1;
1392
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001393 // Set up response file names for each command, if necessary
Justin Bogner0cd92482015-07-02 22:52:08 +00001394 for (auto &Job : C.getJobs())
1395 setUpResponseFiles(C, Job);
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001396
Justin Bogner0cd92482015-07-02 22:52:08 +00001397 C.ExecuteJobs(C.getJobs(), FailingCommands);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001398
Daniel Dunbar07494792010-05-22 00:37:20 +00001399 // If the command succeeded, we are done.
Chad Rosierdd60e092013-01-29 20:15:05 +00001400 if (FailingCommands.empty())
1401 return 0;
Daniel Dunbar07494792010-05-22 00:37:20 +00001402
Chad Rosierdd60e092013-01-29 20:15:05 +00001403 // Otherwise, remove result files and print extra information about abnormal
1404 // failures.
Nick Desaulniers9d0df312018-10-15 17:39:00 +00001405 int Res = 0;
Douglas Katzman6bbffc42015-06-25 18:51:37 +00001406 for (const auto &CmdPair : FailingCommands) {
Nick Desaulniers9d0df312018-10-15 17:39:00 +00001407 int CommandRes = CmdPair.first;
Douglas Katzman6bbffc42015-06-25 18:51:37 +00001408 const Command *FailingCommand = CmdPair.second;
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001409
Chad Rosierdd60e092013-01-29 20:15:05 +00001410 // Remove result files if we're not saving temps.
Reid Kleckner68eb60b2015-02-02 22:41:48 +00001411 if (!isSaveTempsEnabled()) {
Chad Rosierdd60e092013-01-29 20:15:05 +00001412 const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
1413 C.CleanupFileMap(C.getResultFiles(), JA, true);
1414
1415 // Failure result files are valid unless we crashed.
Nick Desaulniers9d0df312018-10-15 17:39:00 +00001416 if (CommandRes < 0)
Chad Rosierdd60e092013-01-29 20:15:05 +00001417 C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
1418 }
1419
Nick Desaulniers9d0df312018-10-15 17:39:00 +00001420#if LLVM_ON_UNIX
1421 // llvm/lib/Support/Unix/Signals.inc will exit with a special return code
1422 // for SIGPIPE. Do not print diagnostics for this case.
1423 if (CommandRes == EX_IOERR) {
1424 Res = CommandRes;
1425 continue;
1426 }
1427#endif
1428
Chad Rosierdd60e092013-01-29 20:15:05 +00001429 // Print extra information about abnormal failures, if possible.
1430 //
1431 // This is ad-hoc, but we don't want to be excessively noisy. If the result
Justin Bogner5aaf2e72014-06-26 20:59:36 +00001432 // status was 1, assume the command failed normally. In particular, if it
Chad Rosierdd60e092013-01-29 20:15:05 +00001433 // was the compiler then assume it gave a reasonable error code. Failures
1434 // in other tools are less common, and they generally have worse
1435 // diagnostics, so always print the diagnostic there.
1436 const Tool &FailingTool = FailingCommand->getCreator();
1437
Nick Desaulniers9d0df312018-10-15 17:39:00 +00001438 if (!FailingCommand->getCreator().hasGoodDiagnostics() || CommandRes != 1) {
Chad Rosierdd60e092013-01-29 20:15:05 +00001439 // FIXME: See FIXME above regarding result code interpretation.
Nick Desaulniers9d0df312018-10-15 17:39:00 +00001440 if (CommandRes < 0)
Chad Rosierdd60e092013-01-29 20:15:05 +00001441 Diag(clang::diag::err_drv_command_signalled)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001442 << FailingTool.getShortName();
Chad Rosierdd60e092013-01-29 20:15:05 +00001443 else
Nick Desaulniers9d0df312018-10-15 17:39:00 +00001444 Diag(clang::diag::err_drv_command_failed)
1445 << FailingTool.getShortName() << CommandRes;
Chad Rosierdd60e092013-01-29 20:15:05 +00001446 }
Peter Collingbourne119cfaa2011-11-21 00:01:05 +00001447 }
Nick Desaulniers9d0df312018-10-15 17:39:00 +00001448 return Res;
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001449}
1450
Daniel Dunbara7b5e212009-04-15 16:34:29 +00001451void Driver::PrintHelp(bool ShowHidden) const {
Hans Wennborg6ddc6902013-07-27 00:23:45 +00001452 unsigned IncludedFlagsBitmask;
1453 unsigned ExcludedFlagsBitmask;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001454 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001455 getIncludeExcludeOptionFlagMasks();
Hans Wennborg6ddc6902013-07-27 00:23:45 +00001456
1457 ExcludedFlagsBitmask |= options::NoDriverOption;
1458 if (!ShowHidden)
1459 ExcludedFlagsBitmask |= HelpHidden;
1460
Fangrui Songd0028232018-10-10 00:15:33 +00001461 std::string Usage = llvm::formatv("{0} [options] file...", Name).str();
1462 getOpts().PrintHelp(llvm::outs(), Usage.c_str(), DriverTitle.c_str(),
George Rimar5dbfa4e2017-07-26 09:10:17 +00001463 IncludedFlagsBitmask, ExcludedFlagsBitmask,
1464 /*ShowAllAliases=*/false);
Daniel Dunbar7c925282009-03-31 21:38:17 +00001465}
1466
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001467void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001468 // FIXME: The following handlers should use a callback mechanism, we don't
1469 // know what the client would like to do.
Ted Kremenek4c0df3d2010-01-23 02:11:34 +00001470 OS << getClangFullVersion() << '\n';
Daniel Dunbarb10248802009-03-26 16:09:13 +00001471 const ToolChain &TC = C.getDefaultToolChain();
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001472 OS << "Target: " << TC.getTripleString() << '\n';
Daniel Dunbar10978e42009-06-16 23:32:58 +00001473
1474 // Print the threading model.
Jonathan Roelofsb140a102014-10-03 21:57:44 +00001475 if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
1476 // Don't print if the ToolChain would have barfed on it already
1477 if (TC.isThreadModelSupported(A->getValue()))
1478 OS << "Thread model: " << A->getValue();
1479 } else
1480 OS << "Thread model: " << TC.getThreadModel();
1481 OS << '\n';
Chandler Carruth9ade6a92015-08-05 17:07:33 +00001482
1483 // Print out the install directory.
1484 OS << "InstalledDir: " << InstalledDir << '\n';
Serge Pavlov208ac652018-01-01 13:27:01 +00001485
1486 // If configuration file was used, print its path.
1487 if (!ConfigFile.empty())
1488 OS << "Configuration file: " << ConfigFile << '\n';
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001489}
1490
Chris Lattner86ed5b02010-05-05 05:53:24 +00001491/// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
1492/// option.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001493static void PrintDiagnosticCategories(raw_ostream &OS) {
Argyrios Kyrtzidis0e37afa2011-05-25 05:05:01 +00001494 // Skip the empty category.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001495 for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
1496 ++i)
Argyrios Kyrtzidis0e37afa2011-05-25 05:05:01 +00001497 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
Chris Lattner86ed5b02010-05-05 05:53:24 +00001498}
1499
Yuka Takahashi41789e42018-03-05 08:54:20 +00001500void Driver::HandleAutocompletions(StringRef PassedFlags) const {
Yuka Takahashi503da8f2018-03-05 09:01:31 +00001501 if (PassedFlags == "")
1502 return;
Yuka Takahashi1a895202017-08-29 17:46:46 +00001503 // Print out all options that start with a given argument. This is used for
1504 // shell autocompletion.
1505 std::vector<std::string> SuggestedCompletions;
Yuka Takahashi41789e42018-03-05 08:54:20 +00001506 std::vector<std::string> Flags;
Yuka Takahashi1a895202017-08-29 17:46:46 +00001507
1508 unsigned short DisableFlags =
1509 options::NoDriverOption | options::Unsupported | options::Ignored;
Yuka Takahashi41789e42018-03-05 08:54:20 +00001510
1511 // Parse PassedFlags by "," as all the command-line flags are passed to this
1512 // function separated by ","
1513 StringRef TargetFlags = PassedFlags;
1514 while (TargetFlags != "") {
1515 StringRef CurFlag;
1516 std::tie(CurFlag, TargetFlags) = TargetFlags.split(",");
1517 Flags.push_back(std::string(CurFlag));
Yuka Takahashi1a895202017-08-29 17:46:46 +00001518 }
1519
Yuka Takahashi41789e42018-03-05 08:54:20 +00001520 // We want to show cc1-only options only when clang is invoked with -cc1 or
1521 // -Xclang.
Yuka Takahashi503da8f2018-03-05 09:01:31 +00001522 if (std::find(Flags.begin(), Flags.end(), "-Xclang") != Flags.end() ||
1523 std::find(Flags.begin(), Flags.end(), "-cc1") != Flags.end())
Yuka Takahashi41789e42018-03-05 08:54:20 +00001524 DisableFlags &= ~options::NoDriverOption;
1525
1526 StringRef Cur;
1527 Cur = Flags.at(Flags.size() - 1);
1528 StringRef Prev;
1529 if (Flags.size() >= 2) {
1530 Prev = Flags.at(Flags.size() - 2);
1531 SuggestedCompletions = Opts->suggestValueCompletions(Prev, Cur);
1532 }
1533
1534 if (SuggestedCompletions.empty())
1535 SuggestedCompletions = Opts->suggestValueCompletions(Cur, "");
1536
Yuka Takahashidf9c7e32018-10-24 08:24:16 +00001537 // When flag ends with '=' and there was no value completion, return empty
1538 // string and fall back to the file autocompletion.
1539 if (SuggestedCompletions.empty() && !Cur.endswith("=")) {
Yuka Takahashi1a895202017-08-29 17:46:46 +00001540 // If the flag is in the form of "--autocomplete=-foo",
1541 // we were requested to print out all option names that start with "-foo".
1542 // For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only".
Yuka Takahashi41789e42018-03-05 08:54:20 +00001543 SuggestedCompletions = Opts->findByPrefix(Cur, DisableFlags);
Yuka Takahashi1a895202017-08-29 17:46:46 +00001544
1545 // We have to query the -W flags manually as they're not in the OptTable.
1546 // TODO: Find a good way to add them to OptTable instead and them remove
1547 // this code.
1548 for (StringRef S : DiagnosticIDs::getDiagnosticFlags())
Yuka Takahashi41789e42018-03-05 08:54:20 +00001549 if (S.startswith(Cur))
Yuka Takahashi1a895202017-08-29 17:46:46 +00001550 SuggestedCompletions.push_back(S);
Yuka Takahashi1a895202017-08-29 17:46:46 +00001551 }
1552
1553 // Sort the autocomplete candidates so that shells print them out in a
1554 // deterministic order. We could sort in any way, but we chose
1555 // case-insensitive sorting for consistency with the -help option
1556 // which prints out options in the case-insensitive alphabetical order.
Fangrui Song55fab262018-09-26 22:16:28 +00001557 llvm::sort(SuggestedCompletions, [](StringRef A, StringRef B) {
1558 if (int X = A.compare_lower(B))
1559 return X < 0;
1560 return A.compare(B) > 0;
1561 });
Yuka Takahashi1a895202017-08-29 17:46:46 +00001562
1563 llvm::outs() << llvm::join(SuggestedCompletions, "\n") << '\n';
1564}
1565
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001566bool Driver::HandleImmediateArgs(const Compilation &C) {
Daniel Dunbar18974bd2010-06-11 22:00:19 +00001567 // The order these options are handled in gcc is all over the place, but we
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001568 // don't expect inconsistencies w.r.t. that to matter in practice.
Daniel Dunbar7c925282009-03-31 21:38:17 +00001569
Daniel Dunbar1b09e042010-09-17 02:47:28 +00001570 if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
1571 llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
1572 return false;
1573 }
1574
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001575 if (C.getArgs().hasArg(options::OPT_dumpversion)) {
Daniel Dunbare26e5002011-01-12 00:43:47 +00001576 // Since -dumpversion is only implemented for pedantic GCC compatibility, we
1577 // return an answer which matches our definition of __VERSION__.
1578 //
1579 // If we want to return a more correct answer some day, then we should
1580 // introduce a non-pedantically GCC compatible mode to Clang in which we
1581 // provide sensible definitions for -dumpversion, __VERSION__, etc.
1582 llvm::outs() << "4.2.1\n";
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001583 return false;
1584 }
Daniel Dunbarfb3d7472010-06-14 21:23:12 +00001585
Chris Lattner86ed5b02010-05-05 05:53:24 +00001586 if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
1587 PrintDiagnosticCategories(llvm::outs());
1588 return false;
1589 }
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001590
James Molloya3c85b82012-05-01 14:57:16 +00001591 if (C.getArgs().hasArg(options::OPT_help) ||
Daniel Dunbara7b5e212009-04-15 16:34:29 +00001592 C.getArgs().hasArg(options::OPT__help_hidden)) {
1593 PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
Daniel Dunbar7c925282009-03-31 21:38:17 +00001594 return false;
1595 }
1596
Daniel Dunbarb0006ae2009-04-02 15:05:41 +00001597 if (C.getArgs().hasArg(options::OPT__version)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001598 // Follow gcc behavior and use stdout for --version and stderr for -v.
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001599 PrintVersion(C, llvm::outs());
Daniel Dunbarb0006ae2009-04-02 15:05:41 +00001600 return false;
1601 }
1602
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001603 if (C.getArgs().hasArg(options::OPT_v) ||
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001604 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001605 PrintVersion(C, llvm::errs());
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001606 SuppressMissingInputWarning = true;
1607 }
1608
Serge Pavlov208ac652018-01-01 13:27:01 +00001609 if (C.getArgs().hasArg(options::OPT_v)) {
1610 if (!SystemConfigDir.empty())
1611 llvm::errs() << "System configuration file directory: "
1612 << SystemConfigDir << "\n";
1613 if (!UserConfigDir.empty())
1614 llvm::errs() << "User configuration file directory: "
1615 << UserConfigDir << "\n";
1616 }
1617
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001618 const ToolChain &TC = C.getDefaultToolChain();
Chandler Carruth0ae39aa2013-07-30 17:57:09 +00001619
1620 if (C.getArgs().hasArg(options::OPT_v))
1621 TC.printVerboseInfo(llvm::errs());
1622
Meador Inge51208a32017-04-04 21:46:50 +00001623 if (C.getArgs().hasArg(options::OPT_print_resource_dir)) {
Meador Ingea9113952017-04-05 22:27:20 +00001624 llvm::outs() << ResourceDir << '\n';
Meador Inge51208a32017-04-04 21:46:50 +00001625 return false;
1626 }
1627
Daniel Dunbard972e222009-03-20 04:37:21 +00001628 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
1629 llvm::outs() << "programs: =";
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001630 bool separator = false;
1631 for (const std::string &Path : TC.getProgramPaths()) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001632 if (separator)
1633 llvm::outs() << ':';
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001634 llvm::outs() << Path;
1635 separator = true;
Daniel Dunbard972e222009-03-20 04:37:21 +00001636 }
1637 llvm::outs() << "\n";
Peter Collingbournefa9771f2011-09-06 02:08:31 +00001638 llvm::outs() << "libraries: =" << ResourceDir;
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001639
Sebastian Pop980920a2012-04-16 04:16:43 +00001640 StringRef sysroot = C.getSysRoot();
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001641
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001642 for (const std::string &Path : TC.getFilePaths()) {
1643 // Always print a separator. ResourceDir was the first item shown.
Peter Collingbournefa9771f2011-09-06 02:08:31 +00001644 llvm::outs() << ':';
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001645 // Interpretation of leading '=' is needed only for NetBSD.
1646 if (Path[0] == '=')
Douglas Katzman26eabf62015-06-24 15:10:30 +00001647 llvm::outs() << sysroot << Path.substr(1);
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001648 else
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001649 llvm::outs() << Path;
Daniel Dunbard972e222009-03-20 04:37:21 +00001650 }
1651 llvm::outs() << "\n";
Daniel Dunbar7c925282009-03-31 21:38:17 +00001652 return false;
Daniel Dunbard972e222009-03-20 04:37:21 +00001653 }
1654
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001655 // FIXME: The following handlers should use a callback mechanism, we don't
1656 // know what the client would like to do.
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001657 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001658 llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001659 return false;
1660 }
1661
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001662 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
Saleem Abdulrasoole5f3cf82018-05-01 18:40:42 +00001663 StringRef ProgName = A->getValue();
1664
1665 // Null program name cannot have a path.
1666 if (! ProgName.empty())
1667 llvm::outs() << GetProgramPath(ProgName, TC);
1668
1669 llvm::outs() << "\n";
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001670 return false;
1671 }
1672
Yuka Takahashic8068db2017-05-23 18:39:08 +00001673 if (Arg *A = C.getArgs().getLastArg(options::OPT_autocomplete)) {
Yuka Takahashiba5d4af2017-06-20 16:31:31 +00001674 StringRef PassedFlags = A->getValue();
Yuka Takahashi41789e42018-03-05 08:54:20 +00001675 HandleAutocompletions(PassedFlags);
Yuka Takahashic8068db2017-05-23 18:39:08 +00001676 return false;
1677 }
1678
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001679 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
Michal Gorny7cfe4802016-10-10 12:23:40 +00001680 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(C.getArgs());
Leo Li23bb21c2017-08-24 01:51:51 +00001681 const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
1682 RegisterEffectiveTriple TripleRAII(TC, Triple);
Michal Gorny7cfe4802016-10-10 12:23:40 +00001683 switch (RLT) {
1684 case ToolChain::RLT_CompilerRT:
1685 llvm::outs() << TC.getCompilerRT(C.getArgs(), "builtins") << "\n";
1686 break;
1687 case ToolChain::RLT_Libgcc:
1688 llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
1689 break;
1690 }
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001691 return false;
1692 }
1693
Daniel Dunbar1b3ec3a2009-06-16 23:25:22 +00001694 if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
Douglas Katzmana34b7bf2015-06-30 19:32:57 +00001695 for (const Multilib &Multilib : TC.getMultilibs())
1696 llvm::outs() << Multilib << "\n";
Daniel Dunbar1b3ec3a2009-06-16 23:25:22 +00001697 return false;
1698 }
1699
Jonathan Roelofs2cea1be2014-02-12 03:21:20 +00001700 if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
Christian Bruel6ccc4a72018-09-06 14:03:44 +00001701 const Multilib &Multilib = TC.getMultilib();
1702 if (Multilib.gccSuffix().empty())
1703 llvm::outs() << ".\n";
1704 else {
1705 StringRef Suffix(Multilib.gccSuffix());
1706 assert(Suffix.front() == '/');
1707 llvm::outs() << Suffix.substr(1) << "\n";
Jonathan Roelofs3fa96d82014-02-12 01:36:51 +00001708 }
Jonathan Roelofs0e7ec602014-02-12 01:29:25 +00001709 return false;
1710 }
Petr Hosekbc86a992018-08-16 00:22:03 +00001711
1712 if (C.getArgs().hasArg(options::OPT_print_target_triple)) {
1713 llvm::outs() << TC.getTripleString() << "\n";
1714 return false;
1715 }
1716
1717 if (C.getArgs().hasArg(options::OPT_print_effective_triple)) {
1718 const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
1719 llvm::outs() << Triple.getTriple() << "\n";
1720 return false;
1721 }
1722
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001723 return true;
1724}
1725
Douglas Katzmanfd528672015-06-11 15:05:22 +00001726// Display an action graph human-readably. Action A is the "sink" node
1727// and latest-occuring action. Traversal is in pre-order, visiting the
1728// inputs to each action before printing the action itself.
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001729static unsigned PrintActions1(const Compilation &C, Action *A,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001730 std::map<Action *, unsigned> &Ids) {
Douglas Katzmanfd528672015-06-11 15:05:22 +00001731 if (Ids.count(A)) // A was already visited.
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001732 return Ids[A];
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001733
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001734 std::string str;
1735 llvm::raw_string_ostream os(str);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001736
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001737 os << Action::getClassName(A->getKind()) << ", ";
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001738 if (InputAction *IA = dyn_cast<InputAction>(A)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001739 os << "\"" << IA->getInputArg().getValue() << "\"";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001740 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001741 os << '"' << BIA->getArchName() << '"' << ", {"
Nico Weber5a459f82016-02-23 19:30:43 +00001742 << PrintActions1(C, *BIA->input_begin(), Ids) << "}";
Samuel Antaod06239d2016-07-15 23:13:27 +00001743 } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
1744 bool IsFirst = true;
1745 OA->doOnEachDependence(
1746 [&](Action *A, const ToolChain *TC, const char *BoundArch) {
1747 // E.g. for two CUDA device dependences whose bound arch is sm_20 and
1748 // sm_35 this will generate:
1749 // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
1750 // (nvptx64-nvidia-cuda:sm_35) {#ID}
1751 if (!IsFirst)
1752 os << ", ";
1753 os << '"';
1754 if (TC)
1755 os << A->getOffloadingKindPrefix();
1756 else
1757 os << "host";
1758 os << " (";
1759 os << TC->getTriple().normalize();
1760
1761 if (BoundArch)
1762 os << ":" << BoundArch;
1763 os << ")";
1764 os << '"';
1765 os << " {" << PrintActions1(C, A, Ids) << "}";
1766 IsFirst = false;
1767 });
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001768 } else {
Samuel Antaod06239d2016-07-15 23:13:27 +00001769 const ActionList *AL = &A->getInputs();
Artem Belevich0ff05cd2015-07-13 23:27:56 +00001770
Artem Belevich23256752015-09-22 17:23:09 +00001771 if (AL->size()) {
1772 const char *Prefix = "{";
1773 for (Action *PreRequisite : *AL) {
1774 os << Prefix << PrintActions1(C, PreRequisite, Ids);
1775 Prefix = ", ";
1776 }
1777 os << "}";
1778 } else
1779 os << "{}";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001780 }
1781
Samuel Antaod06239d2016-07-15 23:13:27 +00001782 // Append offload info for all options other than the offloading action
1783 // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
1784 std::string offload_str;
1785 llvm::raw_string_ostream offload_os(offload_str);
1786 if (!isa<OffloadAction>(A)) {
1787 auto S = A->getOffloadingKindPrefix();
1788 if (!S.empty()) {
1789 offload_os << ", (" << S;
1790 if (A->getOffloadingArch())
1791 offload_os << ", " << A->getOffloadingArch();
1792 offload_os << ")";
1793 }
1794 }
1795
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001796 unsigned Id = Ids.size();
1797 Ids[A] = Id;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001798 llvm::errs() << Id << ": " << os.str() << ", "
Samuel Antaod06239d2016-07-15 23:13:27 +00001799 << types::getTypeName(A->getType()) << offload_os.str() << "\n";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001800
1801 return Id;
1802}
1803
Douglas Katzmanfd528672015-06-11 15:05:22 +00001804// Print the action graphs in a compilation C.
1805// For example "clang -c file1.c file2.c" is composed of two subgraphs.
Daniel Dunbareb843be2009-03-18 03:13:20 +00001806void Driver::PrintActions(const Compilation &C) const {
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001807 std::map<Action *, unsigned> Ids;
1808 for (Action *A : C.getActions())
1809 PrintActions1(C, A, Ids);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001810}
1811
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001812/// Check whether the given input tree contains any compilation or
Joerg Sonnenberger5fe4a7d2011-05-06 14:05:11 +00001813/// assembly actions.
1814static bool ContainsCompileOrAssembleAction(const Action *A) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001815 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
Bob Wilson23a55f12014-12-21 07:00:00 +00001816 isa<AssembleJobAction>(A))
Daniel Dunbar00d3d8e2010-06-29 16:38:33 +00001817 return true;
1818
Nico Weber5a459f82016-02-23 19:30:43 +00001819 for (const Action *Input : A->inputs())
Nico Weberfb80f962015-09-19 21:36:51 +00001820 if (ContainsCompileOrAssembleAction(Input))
Daniel Dunbar00d3d8e2010-06-29 16:38:33 +00001821 return true;
1822
1823 return false;
1824}
1825
Artem Belevich5e2a3ec2015-11-17 22:28:40 +00001826void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
1827 const InputList &BAInputs) const {
1828 DerivedArgList &Args = C.getArgs();
1829 ActionList &Actions = C.getActions();
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001830 llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
1831 // Collect the list of architectures. Duplicates are allowed, but should only
1832 // be handled once (in the order seen).
Daniel Dunbare5dc4822009-03-13 20:33:35 +00001833 llvm::StringSet<> ArchNames;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001834 SmallVector<const char *, 4> Archs;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00001835 for (Arg *A : Args) {
Daniel Dunbar0bfb21e2009-11-19 03:26:40 +00001836 if (A->getOption().matches(options::OPT_arch)) {
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001837 // Validate the option here; we don't save the type here because its
1838 // particular spelling may participate in other driver choices.
1839 llvm::Triple::ArchType Arch =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001840 tools::darwin::getArchTypeForMachOArchName(A->getValue());
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001841 if (Arch == llvm::Triple::UnknownArch) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001842 Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001843 continue;
1844 }
1845
Daniel Dunbar2da02722009-03-19 07:55:12 +00001846 A->claim();
David Blaikie61b86d42014-11-19 02:56:13 +00001847 if (ArchNames.insert(A->getValue()).second)
Richard Smithbd55daf2012-11-01 04:30:05 +00001848 Archs.push_back(A->getValue());
Daniel Dunbarf479c122009-03-12 18:40:18 +00001849 }
1850 }
1851
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001852 // When there is no explicit arch for this platform, make sure we still bind
1853 // the architecture (to the default) so that -Xarch_ is handled correctly.
Daniel Dunbareb843be2009-03-18 03:13:20 +00001854 if (!Archs.size())
Daniel Dunbarc3bd9f52012-11-08 03:38:26 +00001855 Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
Daniel Dunbarf479c122009-03-12 18:40:18 +00001856
Daniel Dunbarf479c122009-03-12 18:40:18 +00001857 ActionList SingleActions;
Justin Lebar0f3474c2016-02-11 02:00:50 +00001858 BuildActions(C, Args, BAInputs, SingleActions);
Daniel Dunbarf479c122009-03-12 18:40:18 +00001859
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001860 // Add in arch bindings for every top level action, as well as lipo and
1861 // dsymutil steps if needed.
Nico Weberfb80f962015-09-19 21:36:51 +00001862 for (Action* Act : SingleActions) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001863 // Make sure we can lipo this kind of output. If not (and it is an actual
1864 // output) then we disallow, since we can't create an output file with the
1865 // right name without overwriting it. We could remove this oddity by just
1866 // changing the output names to include the arch, which would also fix
Daniel Dunbarf479c122009-03-12 18:40:18 +00001867 // -save-temps. Compatibility wins for now.
1868
Daniel Dunbare2ca3bd2009-03-13 17:46:02 +00001869 if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
Daniel Dunbarf479c122009-03-12 18:40:18 +00001870 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001871 << types::getTypeName(Act->getType());
Daniel Dunbarf479c122009-03-12 18:40:18 +00001872
1873 ActionList Inputs;
Justin Lebar41094612016-01-11 23:07:27 +00001874 for (unsigned i = 0, e = Archs.size(); i != e; ++i)
1875 Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
Daniel Dunbarf479c122009-03-12 18:40:18 +00001876
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001877 // Lipo if necessary, we do it this way because we need to set the arch flag
1878 // so that -Xarch_ gets overwritten.
Daniel Dunbarf479c122009-03-12 18:40:18 +00001879 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
1880 Actions.append(Inputs.begin(), Inputs.end());
1881 else
Justin Lebar41094612016-01-11 23:07:27 +00001882 Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001883
Eric Christopher65c05fa2012-02-06 19:43:51 +00001884 // Handle debug info queries.
1885 Arg *A = Args.getLastArg(options::OPT_g_Group);
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001886 if (A && !A->getOption().matches(options::OPT_g0) &&
1887 !A->getOption().matches(options::OPT_gstabs) &&
1888 ContainsCompileOrAssembleAction(Actions.back())) {
Chad Rosier62135492012-07-09 17:31:28 +00001889
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001890 // Add a 'dsymutil' step if necessary, when debug info is enabled and we
1891 // have a compile input. We need to run 'dsymutil' ourselves in such cases
Eric Christopher776c26f2013-01-28 17:39:03 +00001892 // because the debug info will refer to a temporary object file which
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001893 // will be removed at the end of the compilation process.
1894 if (Act->getType() == types::TY_Image) {
1895 ActionList Inputs;
1896 Inputs.push_back(Actions.back());
1897 Actions.pop_back();
Justin Lebar41094612016-01-11 23:07:27 +00001898 Actions.push_back(
1899 C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001900 }
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001901
Ben Langmuir9b9a8d32014-02-06 18:53:25 +00001902 // Verify the debug info output.
Alp Tokere9d2bfc2014-01-17 02:06:23 +00001903 if (Args.hasArg(options::OPT_verify_debug_info)) {
Justin Lebar41094612016-01-11 23:07:27 +00001904 Action* LastAction = Actions.back();
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001905 Actions.pop_back();
Justin Lebar41094612016-01-11 23:07:27 +00001906 Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
1907 LastAction, types::TY_Nothing));
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001908 }
1909 }
Daniel Dunbarf479c122009-03-12 18:40:18 +00001910 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001911}
1912
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001913/// Check that the file referenced by Value exists. If it doesn't,
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001914/// issue a diagnostic and return false.
Alp Toker8c8a8752013-12-03 06:53:35 +00001915static bool DiagnoseInputExistence(const Driver &D, const DerivedArgList &Args,
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001916 StringRef Value, types::ID Ty) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001917 if (!D.getCheckInputsExist())
1918 return true;
1919
1920 // stdin always exists.
1921 if (Value == "-")
1922 return true;
1923
1924 SmallString<64> Path(Value);
1925 if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
Yaron Keren92e1b622015-03-18 10:17:07 +00001926 if (!llvm::sys::path::is_absolute(Path)) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001927 SmallString<64> Directory(WorkDir->getValue());
1928 llvm::sys::path::append(Directory, Value);
1929 Path.assign(Directory);
1930 }
1931 }
1932
1933 if (llvm::sys::fs::exists(Twine(Path)))
1934 return true;
1935
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001936 if (D.IsCLMode()) {
1937 if (!llvm::sys::path::is_absolute(Twine(Path)) &&
1938 llvm::sys::Process::FindInEnvPath("LIB", Value))
1939 return true;
1940
1941 if (Args.hasArg(options::OPT__SLASH_link) && Ty == types::TY_Object) {
1942 // Arguments to the /link flag might cause the linker to search for object
1943 // and library files in paths we don't know about. Don't error in such
1944 // cases.
1945 return true;
1946 }
1947 }
Hans Wennborg23d26a32014-06-18 17:21:50 +00001948
Yaron Keren92e1b622015-03-18 10:17:07 +00001949 D.Diag(clang::diag::err_drv_no_such_file) << Path;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001950 return false;
1951}
1952
Chad Rosierecdede82011-08-12 22:08:57 +00001953// Construct a the list of inputs and their types.
Hans Wennborg55362852014-05-02 22:55:30 +00001954void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
Chad Rosierecdede82011-08-12 22:08:57 +00001955 InputList &Inputs) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001956 // Track the current user specified (-x) input. We also explicitly track the
1957 // argument used to set the type; we only want to claim the type when we
1958 // actually use it, so we warn about unused -x arguments.
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00001959 types::ID InputType = types::TY_Nothing;
Craig Topper92fc2df2014-05-17 16:56:41 +00001960 Arg *InputTypeArg = nullptr;
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00001961
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001962 // The last /TC or /TP option sets the input type to C or C++ globally.
Ehsan Akhgaric249abb2014-09-12 21:44:24 +00001963 if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
1964 options::OPT__SLASH_TP)) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001965 InputTypeArg = TCTP;
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001966 InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001967 ? types::TY_C
1968 : types::TY_CXX;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001969
Richard Smith0aef3052017-02-18 01:14:43 +00001970 Arg *Previous = nullptr;
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001971 bool ShowNote = false;
Richard Smith0aef3052017-02-18 01:14:43 +00001972 for (Arg *A : Args.filtered(options::OPT__SLASH_TC, options::OPT__SLASH_TP)) {
1973 if (Previous) {
1974 Diag(clang::diag::warn_drv_overriding_flag_option)
1975 << Previous->getSpelling() << A->getSpelling();
1976 ShowNote = true;
1977 }
1978 Previous = A;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001979 }
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001980 if (ShowNote)
1981 Diag(clang::diag::note_drv_t_option_is_global);
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001982
1983 // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
1984 assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
1985 }
1986
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00001987 for (Arg *A : Args) {
Michael J. Spencerad3ccc32012-08-20 21:41:17 +00001988 if (A->getOption().getKind() == Option::InputClass) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001989 const char *Value = A->getValue();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001990 types::ID Ty = types::TY_INVALID;
1991
1992 // Infer the input type if necessary.
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00001993 if (InputType == types::TY_Nothing) {
1994 // If there was an explicit arg for this, claim it.
1995 if (InputTypeArg)
1996 InputTypeArg->claim();
1997
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001998 // stdin must be handled specially.
1999 if (memcmp(Value, "-", 2) == 0) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002000 // If running with -E, treat as a C input (this changes the builtin
2001 // macros, for example). This may be overridden by -ObjC below.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002002 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002003 // Otherwise emit an error but still use a valid type to avoid
2004 // spurious errors (e.g., no inputs).
Hans Wennborg70850d82013-07-18 20:29:38 +00002005 if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
Hans Wennborgcfdd8b52014-01-29 01:04:40 +00002006 Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
2007 : clang::diag::err_drv_unknown_stdin_type);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002008 Ty = types::TY_C;
2009 } else {
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00002010 // Otherwise lookup by extension.
2011 // Fallback is C if invoked as C preprocessor or Object otherwise.
2012 // We use a host hook here because Darwin at least has its own
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002013 // idea of what .s is.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002014 if (const char *Ext = strrchr(Value, '.'))
Daniel Dunbarcc7df6c2010-08-02 05:43:56 +00002015 Ty = TC.LookupTypeForExtension(Ext + 1);
Daniel Dunbarea9f0322009-03-20 23:39:23 +00002016
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00002017 if (Ty == types::TY_INVALID) {
Hans Wennborg70850d82013-07-18 20:29:38 +00002018 if (CCCIsCPP())
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00002019 Ty = types::TY_C;
2020 else
2021 Ty = types::TY_Object;
2022 }
Daniel Dunbar0ac94452010-02-17 20:32:58 +00002023
2024 // If the driver is invoked as C++ compiler (like clang++ or c++) it
2025 // should autodetect some input files as C++ for g++ compatibility.
Hans Wennborg70850d82013-07-18 20:29:38 +00002026 if (CCCIsCXX()) {
Daniel Dunbar0ac94452010-02-17 20:32:58 +00002027 types::ID OldTy = Ty;
2028 Ty = types::lookupCXXTypeForCType(Ty);
2029
2030 if (Ty != OldTy)
2031 Diag(clang::diag::warn_drv_treating_input_as_cxx)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002032 << getTypeName(OldTy) << getTypeName(Ty);
Daniel Dunbar0ac94452010-02-17 20:32:58 +00002033 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002034 }
2035
Daniel Dunbar82b22102009-05-18 21:47:54 +00002036 // -ObjC and -ObjC++ override the default language, but only for "source
2037 // files". We just treat everything that isn't a linker input as a
2038 // source file.
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002039 //
Daniel Dunbar82b22102009-05-18 21:47:54 +00002040 // FIXME: Clean this up if we move the phase sequence into the type.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002041 if (Ty != types::TY_Object) {
2042 if (Args.hasArg(options::OPT_ObjC))
2043 Ty = types::TY_ObjC;
2044 else if (Args.hasArg(options::OPT_ObjCXX))
2045 Ty = types::TY_ObjCXX;
2046 }
2047 } else {
2048 assert(InputTypeArg && "InputType set w/o InputTypeArg");
Ehsan Akhgari7e954ea2014-09-12 18:15:10 +00002049 if (!InputTypeArg->getOption().matches(options::OPT_x)) {
2050 // If emulating cl.exe, make sure that /TC and /TP don't affect input
2051 // object files.
2052 const char *Ext = strrchr(Value, '.');
2053 if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
2054 Ty = types::TY_Object;
2055 }
2056 if (Ty == types::TY_INVALID) {
2057 Ty = InputType;
2058 InputTypeArg->claim();
2059 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002060 }
2061
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00002062 if (DiagnoseInputExistence(*this, Args, Value, Ty))
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002063 Inputs.push_back(std::make_pair(Ty, A));
2064
Hans Wennborg6ee64d52013-08-06 00:20:31 +00002065 } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
2066 StringRef Value = A->getValue();
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00002067 if (DiagnoseInputExistence(*this, Args, Value, types::TY_C)) {
David Blaikie0aaa7622017-01-13 17:34:15 +00002068 Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
Hans Wennborg6ee64d52013-08-06 00:20:31 +00002069 Inputs.push_back(std::make_pair(types::TY_C, InputArg));
2070 }
2071 A->claim();
2072 } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
2073 StringRef Value = A->getValue();
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00002074 if (DiagnoseInputExistence(*this, Args, Value, types::TY_CXX)) {
David Blaikie0aaa7622017-01-13 17:34:15 +00002075 Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
Hans Wennborg6ee64d52013-08-06 00:20:31 +00002076 Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
2077 }
2078 A->claim();
Michael J. Spencer66e2b202012-10-19 22:37:06 +00002079 } else if (A->getOption().hasFlag(options::LinkerInput)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002080 // Just treat as object type, we could make a special type for this if
2081 // necessary.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002082 Inputs.push_back(std::make_pair(types::TY_Object, A));
2083
Daniel Dunbar0bfb21e2009-11-19 03:26:40 +00002084 } else if (A->getOption().matches(options::OPT_x)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002085 InputTypeArg = A;
Richard Smithbd55daf2012-11-01 04:30:05 +00002086 InputType = types::lookupTypeForTypeSpecifier(A->getValue());
Chad Rosier706c2352012-04-07 00:01:31 +00002087 A->claim();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002088
2089 // Follow gcc behavior and treat as linker input for invalid -x
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002090 // options. Its not clear why we shouldn't just revert to unknown; but
Michael J. Spencer1a4fe8c2010-12-17 21:22:33 +00002091 // this isn't very important, we might as well be bug compatible.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002092 if (!InputType) {
Richard Smithbd55daf2012-11-01 04:30:05 +00002093 Diag(clang::diag::err_drv_unknown_language) << A->getValue();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002094 InputType = types::TY_Object;
2095 }
Hans Wennborg091f1b62017-01-27 17:09:41 +00002096 } else if (A->getOption().getID() == options::OPT__SLASH_U) {
2097 assert(A->getNumValues() == 1 && "The /U option has one value.");
2098 StringRef Val = A->getValue(0);
2099 if (Val.find_first_of("/\\") != StringRef::npos) {
2100 // Warn about e.g. "/Users/me/myfile.c".
2101 Diag(diag::warn_slash_u_filename) << Val;
2102 Diag(diag::note_use_dashdash);
2103 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002104 }
2105 }
Hans Wennborg70850d82013-07-18 20:29:38 +00002106 if (CCCIsCPP() && Inputs.empty()) {
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00002107 // If called as standalone preprocessor, stdin is processed
2108 // if no other input is present.
David Blaikie0aaa7622017-01-13 17:34:15 +00002109 Arg *A = MakeInputArg(Args, *Opts, "-");
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00002110 Inputs.push_back(std::make_pair(types::TY_C, A));
2111 }
Chad Rosierecdede82011-08-12 22:08:57 +00002112}
2113
Samuel Antao64e965e2016-09-30 15:34:19 +00002114namespace {
2115/// Provides a convenient interface for different programming models to generate
2116/// the required device actions.
2117class OffloadingActionBuilder final {
2118 /// Flag used to trace errors in the builder.
2119 bool IsValid = false;
2120
2121 /// The compilation that is using this builder.
2122 Compilation &C;
2123
Samuel Antao64e965e2016-09-30 15:34:19 +00002124 /// Map between an input argument and the offload kinds used to process it.
2125 std::map<const Arg *, unsigned> InputArgToOffloadKindMap;
2126
2127 /// Builder interface. It doesn't build anything or keep any state.
2128 class DeviceActionBuilder {
2129 public:
2130 typedef llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PhasesTy;
2131
2132 enum ActionBuilderReturnCode {
2133 // The builder acted successfully on the current action.
2134 ABRT_Success,
2135 // The builder didn't have to act on the current action.
2136 ABRT_Inactive,
2137 // The builder was successful and requested the host action to not be
2138 // generated.
2139 ABRT_Ignore_Host,
2140 };
2141
2142 protected:
2143 /// Compilation associated with this builder.
2144 Compilation &C;
2145
2146 /// Tool chains associated with this builder. The same programming
2147 /// model may have associated one or more tool chains.
2148 SmallVector<const ToolChain *, 2> ToolChains;
2149
2150 /// The derived arguments associated with this builder.
2151 DerivedArgList &Args;
2152
2153 /// The inputs associated with this builder.
2154 const Driver::InputList &Inputs;
2155
2156 /// The associated offload kind.
2157 Action::OffloadKind AssociatedOffloadKind = Action::OFK_None;
2158
2159 public:
2160 DeviceActionBuilder(Compilation &C, DerivedArgList &Args,
2161 const Driver::InputList &Inputs,
2162 Action::OffloadKind AssociatedOffloadKind)
2163 : C(C), Args(Args), Inputs(Inputs),
2164 AssociatedOffloadKind(AssociatedOffloadKind) {}
2165 virtual ~DeviceActionBuilder() {}
2166
2167 /// Fill up the array \a DA with all the device dependences that should be
2168 /// added to the provided host action \a HostAction. By default it is
2169 /// inactive.
2170 virtual ActionBuilderReturnCode
Samuel Antao28c4f182016-10-27 17:08:03 +00002171 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2172 phases::ID CurPhase, phases::ID FinalPhase,
2173 PhasesTy &Phases) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002174 return ABRT_Inactive;
2175 }
2176
2177 /// Update the state to include the provided host action \a HostAction as a
2178 /// dependency of the current device action. By default it is inactive.
2179 virtual ActionBuilderReturnCode addDeviceDepences(Action *HostAction) {
2180 return ABRT_Inactive;
2181 }
2182
2183 /// Append top level actions generated by the builder. Return true if errors
2184 /// were found.
2185 virtual void appendTopLevelActions(ActionList &AL) {}
2186
2187 /// Append linker actions generated by the builder. Return true if errors
2188 /// were found.
2189 virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {}
2190
2191 /// Initialize the builder. Return true if any initialization errors are
2192 /// found.
2193 virtual bool initialize() { return false; }
2194
Samuel Antao69d6f312016-10-27 17:50:43 +00002195 /// Return true if the builder can use bundling/unbundling.
2196 virtual bool canUseBundlerUnbundler() const { return false; }
2197
Samuel Antao64e965e2016-09-30 15:34:19 +00002198 /// Return true if this builder is valid. We have a valid builder if we have
2199 /// associated device tool chains.
2200 bool isValid() { return !ToolChains.empty(); }
2201
2202 /// Return the associated offload kind.
2203 Action::OffloadKind getAssociatedOffloadKind() {
2204 return AssociatedOffloadKind;
2205 }
2206 };
2207
Yaxun Liu3af038b2018-05-30 00:49:10 +00002208 /// Base class for CUDA/HIP action builder. It injects device code in
2209 /// the host backend action.
2210 class CudaActionBuilderBase : public DeviceActionBuilder {
2211 protected:
Samuel Antao64e965e2016-09-30 15:34:19 +00002212 /// Flags to signal if the user requested host-only or device-only
2213 /// compilation.
2214 bool CompileHostOnly = false;
2215 bool CompileDeviceOnly = false;
2216
2217 /// List of GPU architectures to use in this compilation.
2218 SmallVector<CudaArch, 4> GpuArchList;
2219
2220 /// The CUDA actions for the current input.
2221 ActionList CudaDeviceActions;
2222
2223 /// The CUDA fat binary if it was generated for the current input.
2224 Action *CudaFatBinary = nullptr;
2225
2226 /// Flag that is set to true if this builder acted on the current input.
2227 bool IsActive = false;
Yaxun Liu3af038b2018-05-30 00:49:10 +00002228 public:
2229 CudaActionBuilderBase(Compilation &C, DerivedArgList &Args,
2230 const Driver::InputList &Inputs,
2231 Action::OffloadKind OFKind)
2232 : DeviceActionBuilder(C, Args, Inputs, OFKind) {}
Samuel Antao64e965e2016-09-30 15:34:19 +00002233
Yaxun Liu3af038b2018-05-30 00:49:10 +00002234 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2235 // While generating code for CUDA, we only depend on the host input action
2236 // to trigger the creation of all the CUDA device actions.
2237
2238 // If we are dealing with an input action, replicate it for each GPU
2239 // architecture. If we are in host-only mode we return 'success' so that
2240 // the host uses the CUDA offload kind.
2241 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2242 assert(!GpuArchList.empty() &&
2243 "We should have at least one GPU architecture.");
2244
2245 // If the host input is not CUDA or HIP, we don't need to bother about
2246 // this input.
2247 if (IA->getType() != types::TY_CUDA &&
2248 IA->getType() != types::TY_HIP) {
2249 // The builder will ignore this input.
2250 IsActive = false;
2251 return ABRT_Inactive;
2252 }
2253
2254 // Set the flag to true, so that the builder acts on the current input.
2255 IsActive = true;
2256
2257 if (CompileHostOnly)
2258 return ABRT_Success;
2259
2260 // Replicate inputs for each GPU architecture.
2261 auto Ty = IA->getType() == types::TY_HIP ? types::TY_HIP_DEVICE
2262 : types::TY_CUDA_DEVICE;
2263 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2264 CudaDeviceActions.push_back(
2265 C.MakeAction<InputAction>(IA->getInputArg(), Ty));
2266 }
2267
2268 return ABRT_Success;
2269 }
2270
2271 // If this is an unbundling action use it as is for each CUDA toolchain.
2272 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2273 CudaDeviceActions.clear();
2274 for (auto Arch : GpuArchList) {
2275 CudaDeviceActions.push_back(UA);
2276 UA->registerDependentActionInfo(ToolChains[0], CudaArchToString(Arch),
2277 AssociatedOffloadKind);
2278 }
2279 return ABRT_Success;
2280 }
2281
2282 return IsActive ? ABRT_Success : ABRT_Inactive;
2283 }
2284
2285 void appendTopLevelActions(ActionList &AL) override {
2286 // Utility to append actions to the top level list.
2287 auto AddTopLevel = [&](Action *A, CudaArch BoundArch) {
2288 OffloadAction::DeviceDependences Dep;
2289 Dep.add(*A, *ToolChains.front(), CudaArchToString(BoundArch),
2290 AssociatedOffloadKind);
2291 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2292 };
2293
2294 // If we have a fat binary, add it to the list.
2295 if (CudaFatBinary) {
2296 AddTopLevel(CudaFatBinary, CudaArch::UNKNOWN);
2297 CudaDeviceActions.clear();
2298 CudaFatBinary = nullptr;
2299 return;
2300 }
2301
2302 if (CudaDeviceActions.empty())
2303 return;
2304
2305 // If we have CUDA actions at this point, that's because we have a have
2306 // partial compilation, so we should have an action for each GPU
2307 // architecture.
2308 assert(CudaDeviceActions.size() == GpuArchList.size() &&
2309 "Expecting one action per GPU architecture.");
2310 assert(ToolChains.size() == 1 &&
2311 "Expecting to have a sing CUDA toolchain.");
2312 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
2313 AddTopLevel(CudaDeviceActions[I], GpuArchList[I]);
2314
2315 CudaDeviceActions.clear();
2316 }
2317
2318 bool initialize() override {
2319 assert(AssociatedOffloadKind == Action::OFK_Cuda ||
2320 AssociatedOffloadKind == Action::OFK_HIP);
2321
2322 // We don't need to support CUDA.
2323 if (AssociatedOffloadKind == Action::OFK_Cuda &&
2324 !C.hasOffloadToolChain<Action::OFK_Cuda>())
2325 return false;
2326
2327 // We don't need to support HIP.
2328 if (AssociatedOffloadKind == Action::OFK_HIP &&
2329 !C.hasOffloadToolChain<Action::OFK_HIP>())
2330 return false;
2331
2332 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
2333 assert(HostTC && "No toolchain for host compilation.");
2334 if (HostTC->getTriple().isNVPTX() ||
2335 HostTC->getTriple().getArch() == llvm::Triple::amdgcn) {
2336 // We do not support targeting NVPTX/AMDGCN for host compilation. Throw
2337 // an error and abort pipeline construction early so we don't trip
2338 // asserts that assume device-side compilation.
2339 C.getDriver().Diag(diag::err_drv_cuda_host_arch)
2340 << HostTC->getTriple().getArchName();
2341 return true;
2342 }
2343
2344 ToolChains.push_back(
2345 AssociatedOffloadKind == Action::OFK_Cuda
2346 ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
2347 : C.getSingleOffloadToolChain<Action::OFK_HIP>());
2348
2349 Arg *PartialCompilationArg = Args.getLastArg(
2350 options::OPT_cuda_host_only, options::OPT_cuda_device_only,
2351 options::OPT_cuda_compile_host_device);
2352 CompileHostOnly = PartialCompilationArg &&
2353 PartialCompilationArg->getOption().matches(
2354 options::OPT_cuda_host_only);
2355 CompileDeviceOnly = PartialCompilationArg &&
2356 PartialCompilationArg->getOption().matches(
2357 options::OPT_cuda_device_only);
2358
2359 // Collect all cuda_gpu_arch parameters, removing duplicates.
2360 std::set<CudaArch> GpuArchs;
2361 bool Error = false;
2362 for (Arg *A : Args) {
2363 if (!(A->getOption().matches(options::OPT_cuda_gpu_arch_EQ) ||
2364 A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ)))
2365 continue;
2366 A->claim();
2367
2368 const StringRef ArchStr = A->getValue();
2369 if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ) &&
2370 ArchStr == "all") {
2371 GpuArchs.clear();
2372 continue;
2373 }
2374 CudaArch Arch = StringToCudaArch(ArchStr);
2375 if (Arch == CudaArch::UNKNOWN) {
2376 C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
2377 Error = true;
2378 } else if (A->getOption().matches(options::OPT_cuda_gpu_arch_EQ))
2379 GpuArchs.insert(Arch);
2380 else if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ))
2381 GpuArchs.erase(Arch);
2382 else
2383 llvm_unreachable("Unexpected option.");
2384 }
2385
2386 // Collect list of GPUs remaining in the set.
2387 for (CudaArch Arch : GpuArchs)
2388 GpuArchList.push_back(Arch);
2389
2390 // Default to sm_20 which is the lowest common denominator for
2391 // supported GPUs. sm_20 code should work correctly, if
2392 // suboptimally, on all newer GPUs.
2393 if (GpuArchList.empty())
2394 GpuArchList.push_back(CudaArch::SM_20);
2395
2396 return Error;
2397 }
2398 };
2399
2400 /// \brief CUDA action builder. It injects device code in the host backend
2401 /// action.
2402 class CudaActionBuilder final : public CudaActionBuilderBase {
Samuel Antao64e965e2016-09-30 15:34:19 +00002403 public:
2404 CudaActionBuilder(Compilation &C, DerivedArgList &Args,
2405 const Driver::InputList &Inputs)
Yaxun Liu3af038b2018-05-30 00:49:10 +00002406 : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_Cuda) {}
Samuel Antao64e965e2016-09-30 15:34:19 +00002407
2408 ActionBuilderReturnCode
Samuel Antao28c4f182016-10-27 17:08:03 +00002409 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2410 phases::ID CurPhase, phases::ID FinalPhase,
2411 PhasesTy &Phases) override {
Samuel Antao64e965e2016-09-30 15:34:19 +00002412 if (!IsActive)
2413 return ABRT_Inactive;
2414
2415 // If we don't have more CUDA actions, we don't have any dependences to
2416 // create for the host.
2417 if (CudaDeviceActions.empty())
2418 return ABRT_Success;
2419
2420 assert(CudaDeviceActions.size() == GpuArchList.size() &&
2421 "Expecting one action per GPU architecture.");
2422 assert(!CompileHostOnly &&
2423 "Not expecting CUDA actions in host-only compilation.");
2424
2425 // If we are generating code for the device or we are in a backend phase,
2426 // we attempt to generate the fat binary. We compile each arch to ptx and
2427 // assemble to cubin, then feed the cubin *and* the ptx into a device
2428 // "link" action, which uses fatbinary to combine these cubins into one
2429 // fatbin. The fatbin is then an input to the host action if not in
2430 // device-only mode.
2431 if (CompileDeviceOnly || CurPhase == phases::Backend) {
2432 ActionList DeviceActions;
2433 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2434 // Produce the device action from the current phase up to the assemble
2435 // phase.
2436 for (auto Ph : Phases) {
2437 // Skip the phases that were already dealt with.
2438 if (Ph < CurPhase)
2439 continue;
2440 // We have to be consistent with the host final phase.
2441 if (Ph > FinalPhase)
2442 break;
2443
2444 CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction(
Artem Belevichecb178b2018-03-21 22:22:59 +00002445 C, Args, Ph, CudaDeviceActions[I], Action::OFK_Cuda);
Samuel Antao64e965e2016-09-30 15:34:19 +00002446
2447 if (Ph == phases::Assemble)
2448 break;
2449 }
2450
2451 // If we didn't reach the assemble phase, we can't generate the fat
2452 // binary. We don't need to generate the fat binary if we are not in
2453 // device-only mode.
2454 if (!isa<AssembleJobAction>(CudaDeviceActions[I]) ||
2455 CompileDeviceOnly)
2456 continue;
2457
2458 Action *AssembleAction = CudaDeviceActions[I];
2459 assert(AssembleAction->getType() == types::TY_Object);
2460 assert(AssembleAction->getInputs().size() == 1);
2461
2462 Action *BackendAction = AssembleAction->getInputs()[0];
2463 assert(BackendAction->getType() == types::TY_PP_Asm);
2464
2465 for (auto &A : {AssembleAction, BackendAction}) {
2466 OffloadAction::DeviceDependences DDep;
2467 DDep.add(*A, *ToolChains.front(), CudaArchToString(GpuArchList[I]),
2468 Action::OFK_Cuda);
2469 DeviceActions.push_back(
2470 C.MakeAction<OffloadAction>(DDep, A->getType()));
2471 }
2472 }
2473
2474 // We generate the fat binary if we have device input actions.
2475 if (!DeviceActions.empty()) {
2476 CudaFatBinary =
2477 C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN);
2478
2479 if (!CompileDeviceOnly) {
2480 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
2481 Action::OFK_Cuda);
2482 // Clear the fat binary, it is already a dependence to an host
2483 // action.
2484 CudaFatBinary = nullptr;
2485 }
2486
2487 // Remove the CUDA actions as they are already connected to an host
2488 // action or fat binary.
2489 CudaDeviceActions.clear();
2490 }
2491
2492 // We avoid creating host action in device-only mode.
2493 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
Samuel Antao5b1a89a2016-10-27 00:53:34 +00002494 } else if (CurPhase > phases::Backend) {
2495 // If we are past the backend phase and still have a device action, we
2496 // don't have to do anything as this action is already a device
2497 // top-level action.
2498 return ABRT_Success;
Samuel Antao64e965e2016-09-30 15:34:19 +00002499 }
2500
2501 assert(CurPhase < phases::Backend && "Generating single CUDA "
2502 "instructions should only occur "
2503 "before the backend phase!");
2504
2505 // By default, we produce an action for each device arch.
2506 for (Action *&A : CudaDeviceActions)
2507 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2508
2509 return ABRT_Success;
2510 }
Yaxun Liu3af038b2018-05-30 00:49:10 +00002511 };
2512 /// \brief HIP action builder. It injects device code in the host backend
2513 /// action.
2514 class HIPActionBuilder final : public CudaActionBuilderBase {
2515 /// The linker inputs obtained for each device arch.
2516 SmallVector<ActionList, 8> DeviceLinkerInputs;
Yaxun Liu97670892018-10-02 17:48:54 +00002517 bool Relocatable;
Samuel Antao64e965e2016-09-30 15:34:19 +00002518
Yaxun Liu3af038b2018-05-30 00:49:10 +00002519 public:
2520 HIPActionBuilder(Compilation &C, DerivedArgList &Args,
2521 const Driver::InputList &Inputs)
Yaxun Liu97670892018-10-02 17:48:54 +00002522 : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_HIP),
2523 Relocatable(false) {}
Samuel Antao64e965e2016-09-30 15:34:19 +00002524
Yaxun Liu3af038b2018-05-30 00:49:10 +00002525 bool canUseBundlerUnbundler() const override { return true; }
Samuel Antao64e965e2016-09-30 15:34:19 +00002526
Yaxun Liu3af038b2018-05-30 00:49:10 +00002527 ActionBuilderReturnCode
2528 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2529 phases::ID CurPhase, phases::ID FinalPhase,
2530 PhasesTy &Phases) override {
2531 // amdgcn does not support linking of object files, therefore we skip
Yaxun Liu97670892018-10-02 17:48:54 +00002532 // backend and assemble phases to output LLVM IR. Except for generating
2533 // non-relocatable device coee, where we generate fat binary for device
2534 // code and pass to host in Backend phase.
2535 if (CudaDeviceActions.empty() ||
2536 (CurPhase == phases::Backend && Relocatable) ||
Yaxun Liu3af038b2018-05-30 00:49:10 +00002537 CurPhase == phases::Assemble)
2538 return ABRT_Success;
2539
Yaxun Liu97670892018-10-02 17:48:54 +00002540 assert(((CurPhase == phases::Link && Relocatable) ||
Yaxun Liu3af038b2018-05-30 00:49:10 +00002541 CudaDeviceActions.size() == GpuArchList.size()) &&
2542 "Expecting one action per GPU architecture.");
2543 assert(!CompileHostOnly &&
2544 "Not expecting CUDA actions in host-only compilation.");
2545
Yaxun Liu97670892018-10-02 17:48:54 +00002546 if (!Relocatable && CurPhase == phases::Backend) {
2547 // If we are in backend phase, we attempt to generate the fat binary.
2548 // We compile each arch to IR and use a link action to generate code
2549 // object containing ISA. Then we use a special "link" action to create
2550 // a fat binary containing all the code objects for different GPU's.
2551 // The fat binary is then an input to the host action.
2552 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2553 // Create a link action to link device IR with device library
2554 // and generate ISA.
2555 ActionList AL;
2556 AL.push_back(CudaDeviceActions[I]);
2557 CudaDeviceActions[I] =
2558 C.MakeAction<LinkJobAction>(AL, types::TY_Image);
2559
2560 // OffloadingActionBuilder propagates device arch until an offload
2561 // action. Since the next action for creating fatbin does
2562 // not have device arch, whereas the above link action and its input
2563 // have device arch, an offload action is needed to stop the null
2564 // device arch of the next action being propagated to the above link
2565 // action.
2566 OffloadAction::DeviceDependences DDep;
2567 DDep.add(*CudaDeviceActions[I], *ToolChains.front(),
2568 CudaArchToString(GpuArchList[I]), AssociatedOffloadKind);
2569 CudaDeviceActions[I] = C.MakeAction<OffloadAction>(
2570 DDep, CudaDeviceActions[I]->getType());
2571 }
2572 // Create HIP fat binary with a special "link" action.
2573 CudaFatBinary =
2574 C.MakeAction<LinkJobAction>(CudaDeviceActions,
2575 types::TY_HIP_FATBIN);
2576
2577 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
2578 AssociatedOffloadKind);
2579 // Clear the fat binary, it is already a dependence to an host
2580 // action.
2581 CudaFatBinary = nullptr;
2582
2583 // Remove the CUDA actions as they are already connected to an host
2584 // action or fat binary.
2585 CudaDeviceActions.clear();
2586
2587 return ABRT_Success;
2588 } else if (CurPhase == phases::Link) {
2589 // Save CudaDeviceActions to DeviceLinkerInputs for each GPU subarch.
2590 // This happens to each device action originated from each input file.
2591 // Later on, device actions in DeviceLinkerInputs are used to create
2592 // device link actions in appendLinkDependences and the created device
2593 // link actions are passed to the offload action as device dependence.
Yaxun Liu3af038b2018-05-30 00:49:10 +00002594 DeviceLinkerInputs.resize(CudaDeviceActions.size());
2595 auto LI = DeviceLinkerInputs.begin();
2596 for (auto *A : CudaDeviceActions) {
2597 LI->push_back(A);
2598 ++LI;
Samuel Antao64e965e2016-09-30 15:34:19 +00002599 }
2600
Yaxun Liu3af038b2018-05-30 00:49:10 +00002601 // We will pass the device action as a host dependence, so we don't
2602 // need to do anything else with them.
2603 CudaDeviceActions.clear();
Samuel Antao64e965e2016-09-30 15:34:19 +00002604 return ABRT_Success;
2605 }
2606
Yaxun Liu3af038b2018-05-30 00:49:10 +00002607 // By default, we produce an action for each device arch.
2608 for (Action *&A : CudaDeviceActions)
2609 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A,
2610 AssociatedOffloadKind);
2611
2612 return ABRT_Success;
Samuel Antao64e965e2016-09-30 15:34:19 +00002613 }
2614
Yaxun Liu3af038b2018-05-30 00:49:10 +00002615 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {
2616 // Append a new link action for each device.
2617 unsigned I = 0;
2618 for (auto &LI : DeviceLinkerInputs) {
2619 auto *DeviceLinkAction =
2620 C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2621 DA.add(*DeviceLinkAction, *ToolChains[0],
2622 CudaArchToString(GpuArchList[I]), AssociatedOffloadKind);
2623 ++I;
Samuel Antao64e965e2016-09-30 15:34:19 +00002624 }
Samuel Antao64e965e2016-09-30 15:34:19 +00002625 }
Yaxun Liu97670892018-10-02 17:48:54 +00002626
2627 bool initialize() override {
2628 Relocatable = Args.hasFlag(options::OPT_fgpu_rdc,
2629 options::OPT_fno_gpu_rdc, /*Default=*/false);
2630
2631 return CudaActionBuilderBase::initialize();
2632 }
Samuel Antao64e965e2016-09-30 15:34:19 +00002633 };
2634
Samuel Antao28c4f182016-10-27 17:08:03 +00002635 /// OpenMP action builder. The host bitcode is passed to the device frontend
2636 /// and all the device linked images are passed to the host link phase.
2637 class OpenMPActionBuilder final : public DeviceActionBuilder {
2638 /// The OpenMP actions for the current input.
2639 ActionList OpenMPDeviceActions;
2640
2641 /// The linker inputs obtained for each toolchain.
2642 SmallVector<ActionList, 8> DeviceLinkerInputs;
2643
2644 public:
2645 OpenMPActionBuilder(Compilation &C, DerivedArgList &Args,
2646 const Driver::InputList &Inputs)
2647 : DeviceActionBuilder(C, Args, Inputs, Action::OFK_OpenMP) {}
2648
2649 ActionBuilderReturnCode
2650 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2651 phases::ID CurPhase, phases::ID FinalPhase,
2652 PhasesTy &Phases) override {
Alexey Bataeva5178f52018-09-28 16:17:59 +00002653 if (OpenMPDeviceActions.empty())
2654 return ABRT_Inactive;
Samuel Antao28c4f182016-10-27 17:08:03 +00002655
2656 // We should always have an action for each input.
2657 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2658 "Number of OpenMP actions and toolchains do not match.");
2659
2660 // The host only depends on device action in the linking phase, when all
2661 // the device images have to be embedded in the host image.
2662 if (CurPhase == phases::Link) {
2663 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2664 "Toolchains and linker inputs sizes do not match.");
2665 auto LI = DeviceLinkerInputs.begin();
2666 for (auto *A : OpenMPDeviceActions) {
2667 LI->push_back(A);
2668 ++LI;
2669 }
2670
2671 // We passed the device action as a host dependence, so we don't need to
2672 // do anything else with them.
2673 OpenMPDeviceActions.clear();
2674 return ABRT_Success;
2675 }
2676
2677 // By default, we produce an action for each device arch.
2678 for (Action *&A : OpenMPDeviceActions)
2679 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2680
2681 return ABRT_Success;
2682 }
2683
2684 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2685
2686 // If this is an input action replicate it for each OpenMP toolchain.
2687 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2688 OpenMPDeviceActions.clear();
2689 for (unsigned I = 0; I < ToolChains.size(); ++I)
2690 OpenMPDeviceActions.push_back(
2691 C.MakeAction<InputAction>(IA->getInputArg(), IA->getType()));
2692 return ABRT_Success;
2693 }
2694
Samuel Antaofab4f372016-10-27 18:00:51 +00002695 // If this is an unbundling action use it as is for each OpenMP toolchain.
2696 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2697 OpenMPDeviceActions.clear();
Alexey Bataeva5178f52018-09-28 16:17:59 +00002698 auto *IA = cast<InputAction>(UA->getInputs().back());
2699 std::string FileName = IA->getInputArg().getAsString(Args);
2700 // Check if the type of the file is the same as the action. Do not
2701 // unbundle it if it is not. Do not unbundle .so files, for example,
2702 // which are not object files.
2703 if (IA->getType() == types::TY_Object &&
2704 (!llvm::sys::path::has_extension(FileName) ||
2705 types::lookupTypeForExtension(
2706 llvm::sys::path::extension(FileName).drop_front()) !=
2707 types::TY_Object))
2708 return ABRT_Inactive;
Samuel Antaofab4f372016-10-27 18:00:51 +00002709 for (unsigned I = 0; I < ToolChains.size(); ++I) {
2710 OpenMPDeviceActions.push_back(UA);
2711 UA->registerDependentActionInfo(
2712 ToolChains[I], /*BoundArch=*/StringRef(), Action::OFK_OpenMP);
2713 }
2714 return ABRT_Success;
2715 }
2716
Samuel Antao28c4f182016-10-27 17:08:03 +00002717 // When generating code for OpenMP we use the host compile phase result as
2718 // a dependence to the device compile phase so that it can learn what
2719 // declarations should be emitted. However, this is not the only use for
2720 // the host action, so we prevent it from being collapsed.
2721 if (isa<CompileJobAction>(HostAction)) {
2722 HostAction->setCannotBeCollapsedWithNextDependentAction();
2723 assert(ToolChains.size() == OpenMPDeviceActions.size() &&
2724 "Toolchains and device action sizes do not match.");
2725 OffloadAction::HostDependence HDep(
2726 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2727 /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2728 auto TC = ToolChains.begin();
2729 for (Action *&A : OpenMPDeviceActions) {
2730 assert(isa<CompileJobAction>(A));
2731 OffloadAction::DeviceDependences DDep;
2732 DDep.add(*A, **TC, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2733 A = C.MakeAction<OffloadAction>(HDep, DDep);
2734 ++TC;
2735 }
2736 }
2737 return ABRT_Success;
2738 }
2739
Samuel Antao69d6f312016-10-27 17:50:43 +00002740 void appendTopLevelActions(ActionList &AL) override {
2741 if (OpenMPDeviceActions.empty())
2742 return;
2743
2744 // We should always have an action for each input.
2745 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2746 "Number of OpenMP actions and toolchains do not match.");
2747
2748 // Append all device actions followed by the proper offload action.
2749 auto TI = ToolChains.begin();
2750 for (auto *A : OpenMPDeviceActions) {
2751 OffloadAction::DeviceDependences Dep;
2752 Dep.add(*A, **TI, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2753 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2754 ++TI;
2755 }
2756 // We no longer need the action stored in this builder.
2757 OpenMPDeviceActions.clear();
2758 }
2759
Samuel Antao28c4f182016-10-27 17:08:03 +00002760 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {
2761 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2762 "Toolchains and linker inputs sizes do not match.");
2763
2764 // Append a new link action for each device.
2765 auto TC = ToolChains.begin();
2766 for (auto &LI : DeviceLinkerInputs) {
2767 auto *DeviceLinkAction =
2768 C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2769 DA.add(*DeviceLinkAction, **TC, /*BoundArch=*/nullptr,
2770 Action::OFK_OpenMP);
2771 ++TC;
2772 }
2773 }
2774
2775 bool initialize() override {
2776 // Get the OpenMP toolchains. If we don't get any, the action builder will
2777 // know there is nothing to do related to OpenMP offloading.
2778 auto OpenMPTCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
2779 for (auto TI = OpenMPTCRange.first, TE = OpenMPTCRange.second; TI != TE;
2780 ++TI)
2781 ToolChains.push_back(TI->second);
2782
2783 DeviceLinkerInputs.resize(ToolChains.size());
2784 return false;
2785 }
Samuel Antao69d6f312016-10-27 17:50:43 +00002786
2787 bool canUseBundlerUnbundler() const override {
2788 // OpenMP should use bundled files whenever possible.
2789 return true;
2790 }
Samuel Antao28c4f182016-10-27 17:08:03 +00002791 };
2792
2793 ///
2794 /// TODO: Add the implementation for other specialized builders here.
2795 ///
Samuel Antao64e965e2016-09-30 15:34:19 +00002796
2797 /// Specialized builders being used by this offloading action builder.
2798 SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders;
2799
Samuel Antao69d6f312016-10-27 17:50:43 +00002800 /// Flag set to true if all valid builders allow file bundling/unbundling.
2801 bool CanUseBundler;
2802
Samuel Antao64e965e2016-09-30 15:34:19 +00002803public:
2804 OffloadingActionBuilder(Compilation &C, DerivedArgList &Args,
2805 const Driver::InputList &Inputs)
Samuel Antao10e905c2016-10-27 01:08:58 +00002806 : C(C) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002807 // Create a specialized builder for each device toolchain.
2808
2809 IsValid = true;
2810
2811 // Create a specialized builder for CUDA.
2812 SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs));
2813
Yaxun Liu3af038b2018-05-30 00:49:10 +00002814 // Create a specialized builder for HIP.
2815 SpecializedBuilders.push_back(new HIPActionBuilder(C, Args, Inputs));
2816
Samuel Antao28c4f182016-10-27 17:08:03 +00002817 // Create a specialized builder for OpenMP.
2818 SpecializedBuilders.push_back(new OpenMPActionBuilder(C, Args, Inputs));
2819
Samuel Antao64e965e2016-09-30 15:34:19 +00002820 //
2821 // TODO: Build other specialized builders here.
2822 //
2823
Samuel Antao69d6f312016-10-27 17:50:43 +00002824 // Initialize all the builders, keeping track of errors. If all valid
2825 // builders agree that we can use bundling, set the flag to true.
2826 unsigned ValidBuilders = 0u;
2827 unsigned ValidBuildersSupportingBundling = 0u;
2828 for (auto *SB : SpecializedBuilders) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002829 IsValid = IsValid && !SB->initialize();
Samuel Antao69d6f312016-10-27 17:50:43 +00002830
2831 // Update the counters if the builder is valid.
2832 if (SB->isValid()) {
2833 ++ValidBuilders;
2834 if (SB->canUseBundlerUnbundler())
2835 ++ValidBuildersSupportingBundling;
2836 }
2837 }
2838 CanUseBundler =
2839 ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling;
Artem Belevichf981e30b2016-08-02 22:37:47 +00002840 }
Justin Lebardc3c5042016-04-19 02:27:07 +00002841
Samuel Antao64e965e2016-09-30 15:34:19 +00002842 ~OffloadingActionBuilder() {
2843 for (auto *SB : SpecializedBuilders)
2844 delete SB;
Samuel Antaod06239d2016-07-15 23:13:27 +00002845 }
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002846
Samuel Antao64e965e2016-09-30 15:34:19 +00002847 /// Generate an action that adds device dependences (if any) to a host action.
2848 /// If no device dependence actions exist, just return the host action \a
2849 /// HostAction. If an error is found or if no builder requires the host action
2850 /// to be generated, return nullptr.
2851 Action *
2852 addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg,
2853 phases::ID CurPhase, phases::ID FinalPhase,
2854 DeviceActionBuilder::PhasesTy &Phases) {
2855 if (!IsValid)
2856 return nullptr;
Justin Lebar7bf77982016-01-11 23:27:13 +00002857
Samuel Antao64e965e2016-09-30 15:34:19 +00002858 if (SpecializedBuilders.empty())
2859 return HostAction;
2860
2861 assert(HostAction && "Invalid host action!");
2862
2863 OffloadAction::DeviceDependences DDeps;
2864 // Check if all the programming models agree we should not emit the host
2865 // action. Also, keep track of the offloading kinds employed.
2866 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2867 unsigned InactiveBuilders = 0u;
2868 unsigned IgnoringBuilders = 0u;
2869 for (auto *SB : SpecializedBuilders) {
2870 if (!SB->isValid()) {
2871 ++InactiveBuilders;
2872 continue;
2873 }
2874
Samuel Antao28c4f182016-10-27 17:08:03 +00002875 auto RetCode =
2876 SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases);
Samuel Antao64e965e2016-09-30 15:34:19 +00002877
2878 // If the builder explicitly says the host action should be ignored,
2879 // we need to increment the variable that tracks the builders that request
2880 // the host object to be ignored.
2881 if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host)
2882 ++IgnoringBuilders;
2883
2884 // Unless the builder was inactive for this action, we have to record the
2885 // offload kind because the host will have to use it.
2886 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2887 OffloadKind |= SB->getAssociatedOffloadKind();
2888 }
2889
2890 // If all builders agree that the host object should be ignored, just return
2891 // nullptr.
2892 if (IgnoringBuilders &&
2893 SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders))
2894 return nullptr;
2895
2896 if (DDeps.getActions().empty())
2897 return HostAction;
2898
2899 // We have dependences we need to bundle together. We use an offload action
2900 // for that.
2901 OffloadAction::HostDependence HDep(
2902 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2903 /*BoundArch=*/nullptr, DDeps);
2904 return C.MakeAction<OffloadAction>(HDep, DDeps);
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002905 }
2906
Samuel Antao64e965e2016-09-30 15:34:19 +00002907 /// Generate an action that adds a host dependence to a device action. The
2908 /// results will be kept in this action builder. Return true if an error was
2909 /// found.
Samuel Antaofab4f372016-10-27 18:00:51 +00002910 bool addHostDependenceToDeviceActions(Action *&HostAction,
Samuel Antao64e965e2016-09-30 15:34:19 +00002911 const Arg *InputArg) {
2912 if (!IsValid)
2913 return true;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002914
Samuel Antaofab4f372016-10-27 18:00:51 +00002915 // If we are supporting bundling/unbundling and the current action is an
2916 // input action of non-source file, we replace the host action by the
2917 // unbundling action. The bundler tool has the logic to detect if an input
2918 // is a bundle or not and if the input is not a bundle it assumes it is a
2919 // host file. Therefore it is safe to create an unbundling action even if
2920 // the input is not a bundle.
2921 if (CanUseBundler && isa<InputAction>(HostAction) &&
2922 InputArg->getOption().getKind() == llvm::opt::Option::InputClass &&
2923 !types::isSrcFile(HostAction->getType())) {
2924 auto UnbundlingHostAction =
2925 C.MakeAction<OffloadUnbundlingJobAction>(HostAction);
2926 UnbundlingHostAction->registerDependentActionInfo(
2927 C.getSingleOffloadToolChain<Action::OFK_Host>(),
Yaxun Liuf37b50a2018-07-24 01:03:44 +00002928 /*BoundArch=*/StringRef(), Action::OFK_Host);
Samuel Antaofab4f372016-10-27 18:00:51 +00002929 HostAction = UnbundlingHostAction;
2930 }
2931
Samuel Antao64e965e2016-09-30 15:34:19 +00002932 assert(HostAction && "Invalid host action!");
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002933
Samuel Antao64e965e2016-09-30 15:34:19 +00002934 // Register the offload kinds that are used.
2935 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2936 for (auto *SB : SpecializedBuilders) {
2937 if (!SB->isValid())
2938 continue;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002939
Samuel Antao64e965e2016-09-30 15:34:19 +00002940 auto RetCode = SB->addDeviceDepences(HostAction);
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002941
Samuel Antao64e965e2016-09-30 15:34:19 +00002942 // Host dependences for device actions are not compatible with that same
2943 // action being ignored.
2944 assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host &&
2945 "Host dependence not expected to be ignored.!");
Samuel Antaod06239d2016-07-15 23:13:27 +00002946
Samuel Antao64e965e2016-09-30 15:34:19 +00002947 // Unless the builder was inactive for this action, we have to record the
2948 // offload kind because the host will have to use it.
2949 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2950 OffloadKind |= SB->getAssociatedOffloadKind();
2951 }
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002952
Alexey Bataeva5178f52018-09-28 16:17:59 +00002953 // Do not use unbundler if the Host does not depend on device action.
2954 if (OffloadKind == Action::OFK_None && CanUseBundler)
2955 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction))
2956 HostAction = UA->getInputs().back();
2957
Samuel Antao64e965e2016-09-30 15:34:19 +00002958 return false;
2959 }
2960
Samuel Antao69d6f312016-10-27 17:50:43 +00002961 /// Add the offloading top level actions to the provided action list. This
2962 /// function can replace the host action by a bundling action if the
2963 /// programming models allow it.
Samuel Antao64e965e2016-09-30 15:34:19 +00002964 bool appendTopLevelActions(ActionList &AL, Action *HostAction,
2965 const Arg *InputArg) {
Samuel Antao69d6f312016-10-27 17:50:43 +00002966 // Get the device actions to be appended.
2967 ActionList OffloadAL;
Samuel Antao64e965e2016-09-30 15:34:19 +00002968 for (auto *SB : SpecializedBuilders) {
2969 if (!SB->isValid())
2970 continue;
Samuel Antao69d6f312016-10-27 17:50:43 +00002971 SB->appendTopLevelActions(OffloadAL);
Samuel Antao64e965e2016-09-30 15:34:19 +00002972 }
2973
Samuel Antao69d6f312016-10-27 17:50:43 +00002974 // If we can use the bundler, replace the host action by the bundling one in
2975 // the resulting list. Otherwise, just append the device actions.
2976 if (CanUseBundler && !OffloadAL.empty()) {
2977 // Add the host action to the list in order to create the bundling action.
2978 OffloadAL.push_back(HostAction);
2979
2980 // We expect that the host action was just appended to the action list
2981 // before this method was called.
2982 assert(HostAction == AL.back() && "Host action not in the list??");
2983 HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL);
2984 AL.back() = HostAction;
2985 } else
2986 AL.append(OffloadAL.begin(), OffloadAL.end());
2987
Samuel Antao64e965e2016-09-30 15:34:19 +00002988 // Propagate to the current host action (if any) the offload information
2989 // associated with the current input.
2990 if (HostAction)
2991 HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg],
2992 /*BoundArch=*/nullptr);
Samuel Antao64e965e2016-09-30 15:34:19 +00002993 return false;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002994 }
Artem Belevich5bde4e02015-07-20 20:02:54 +00002995
Samuel Antao64e965e2016-09-30 15:34:19 +00002996 /// Processes the host linker action. This currently consists of replacing it
2997 /// with an offload action if there are device link objects and propagate to
2998 /// the host action all the offload kinds used in the current compilation. The
2999 /// resulting action is returned.
3000 Action *processHostLinkAction(Action *HostAction) {
3001 // Add all the dependences from the device linking actions.
3002 OffloadAction::DeviceDependences DDeps;
3003 for (auto *SB : SpecializedBuilders) {
3004 if (!SB->isValid())
3005 continue;
Justin Lebar21e5d4f2016-01-14 21:41:27 +00003006
Samuel Antao64e965e2016-09-30 15:34:19 +00003007 SB->appendLinkDependences(DDeps);
Justin Lebar21e5d4f2016-01-14 21:41:27 +00003008 }
Samuel Antaod06239d2016-07-15 23:13:27 +00003009
Samuel Antao64e965e2016-09-30 15:34:19 +00003010 // Calculate all the offload kinds used in the current compilation.
3011 unsigned ActiveOffloadKinds = 0u;
3012 for (auto &I : InputArgToOffloadKindMap)
3013 ActiveOffloadKinds |= I.second;
3014
3015 // If we don't have device dependencies, we don't have to create an offload
3016 // action.
3017 if (DDeps.getActions().empty()) {
3018 // Propagate all the active kinds to host action. Given that it is a link
3019 // action it is assumed to depend on all actions generated so far.
3020 HostAction->propagateHostOffloadInfo(ActiveOffloadKinds,
3021 /*BoundArch=*/nullptr);
3022 return HostAction;
3023 }
3024
3025 // Create the offload action with all dependences. When an offload action
3026 // is created the kinds are propagated to the host action, so we don't have
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003027 // to do that explicitly here.
Samuel Antao64e965e2016-09-30 15:34:19 +00003028 OffloadAction::HostDependence HDep(
3029 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
3030 /*BoundArch*/ nullptr, ActiveOffloadKinds);
3031 return C.MakeAction<OffloadAction>(HDep, DDeps);
3032 }
3033};
3034} // anonymous namespace.
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003035
Justin Lebar0f3474c2016-02-11 02:00:50 +00003036void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
3037 const InputList &Inputs, ActionList &Actions) const {
Chad Rosierecdede82011-08-12 22:08:57 +00003038 llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00003039
Daniel Dunbar34c41872009-03-13 00:17:48 +00003040 if (!SuppressMissingInputWarning && Inputs.empty()) {
Daniel Dunbarbfeec742009-03-12 23:55:14 +00003041 Diag(clang::diag::err_drv_no_input_files);
3042 return;
3043 }
3044
Chad Rosier7742b5d2011-07-27 23:36:45 +00003045 Arg *FinalPhaseArg;
3046 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
Daniel Dunbarbfeec742009-03-12 23:55:14 +00003047
Bob Haarmanaaf51912017-02-27 19:40:19 +00003048 if (FinalPhase == phases::Link) {
3049 if (Args.hasArg(options::OPT_emit_llvm))
3050 Diag(clang::diag::err_drv_emit_llvm_link);
3051 if (IsCLMode() && LTOMode != LTOK_None &&
3052 !Args.getLastArgValue(options::OPT_fuse_ld_EQ).equals_lower("lld"))
3053 Diag(clang::diag::err_drv_lto_without_lld);
Rafael Espindolae8025642013-08-25 14:27:09 +00003054 }
3055
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003056 // Reject -Z* at the top level, these options should never have been exposed
3057 // by gcc.
Daniel Dunbardd765242009-03-26 16:12:09 +00003058 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
Daniel Dunbar0e759942009-03-20 06:14:23 +00003059 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
Daniel Dunbarbfeec742009-03-12 23:55:14 +00003060
Hans Wennborg13b7fe72013-08-12 23:26:25 +00003061 // Diagnose misuse of /Fo.
3062 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
Hans Wennborg13b7fe72013-08-12 23:26:25 +00003063 StringRef V = A->getValue();
Hans Wennborg61647532014-11-17 19:16:36 +00003064 if (Inputs.size() > 1 && !V.empty() &&
3065 !llvm::sys::path::is_separator(V.back())) {
Hans Wennborg13b7fe72013-08-12 23:26:25 +00003066 // Check whether /Fo tries to name an output file for multiple inputs.
Hans Wennborg9c1659b2013-10-18 22:49:04 +00003067 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003068 << A->getSpelling() << V;
Hans Wennborg13b7fe72013-08-12 23:26:25 +00003069 Args.eraseArg(options::OPT__SLASH_Fo);
3070 }
3071 }
3072
Hans Wennborg9c1659b2013-10-18 22:49:04 +00003073 // Diagnose misuse of /Fa.
3074 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
3075 StringRef V = A->getValue();
Hans Wennborg61647532014-11-17 19:16:36 +00003076 if (Inputs.size() > 1 && !V.empty() &&
3077 !llvm::sys::path::is_separator(V.back())) {
Hans Wennborg9c1659b2013-10-18 22:49:04 +00003078 // Check whether /Fa tries to name an asm file for multiple inputs.
3079 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003080 << A->getSpelling() << V;
Hans Wennborg9c1659b2013-10-18 22:49:04 +00003081 Args.eraseArg(options::OPT__SLASH_Fa);
3082 }
3083 }
3084
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00003085 // Diagnose misuse of /o.
3086 if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
3087 if (A->getValue()[0] == '\0') {
3088 // It has to have a value.
3089 Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
3090 Args.eraseArg(options::OPT__SLASH_o);
3091 }
3092 }
3093
Mike Rice58df1af2018-09-11 17:10:44 +00003094 // Ignore /Yc/Yu if both /Yc and /Yu passed but with different filenames.
Nico Weber2ca4be92016-03-01 23:16:44 +00003095 Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
3096 Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
Nico Weber2ca4be92016-03-01 23:16:44 +00003097 if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
3098 Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
3099 Args.eraseArg(options::OPT__SLASH_Yc);
3100 Args.eraseArg(options::OPT__SLASH_Yu);
3101 YcArg = YuArg = nullptr;
3102 }
Nico Weber2ca4be92016-03-01 23:16:44 +00003103 if (YcArg && Inputs.size() > 1) {
3104 Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
3105 Args.eraseArg(options::OPT__SLASH_Yc);
3106 YcArg = nullptr;
3107 }
Erich Keaneeaca3882018-08-17 13:43:39 +00003108 if (FinalPhase == phases::Preprocess || Args.hasArg(options::OPT__SLASH_Y_)) {
3109 // If only preprocessing or /Y- is used, all pch handling is disabled.
3110 // Rather than check for it everywhere, just remove clang-cl pch-related
3111 // flags here.
Nico Weber2ca4be92016-03-01 23:16:44 +00003112 Args.eraseArg(options::OPT__SLASH_Fp);
3113 Args.eraseArg(options::OPT__SLASH_Yc);
3114 Args.eraseArg(options::OPT__SLASH_Yu);
3115 YcArg = YuArg = nullptr;
3116 }
Nico Weber2ca4be92016-03-01 23:16:44 +00003117
Samuel Antao64e965e2016-09-30 15:34:19 +00003118 // Builder to be used to build offloading actions.
3119 OffloadingActionBuilder OffloadBuilder(C, Args, Inputs);
Samuel Antaod06239d2016-07-15 23:13:27 +00003120
Daniel Dunbar65229332009-03-13 11:38:42 +00003121 // Construct the actions to perform.
Richard Smithcd35eff2018-09-15 01:21:16 +00003122 HeaderModulePrecompileJobAction *HeaderModuleAction = nullptr;
Daniel Dunbar65229332009-03-13 11:38:42 +00003123 ActionList LinkerInputs;
Alp Toker965f8822013-11-27 05:22:15 +00003124
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00003125 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL;
Artem Belevich5bde4e02015-07-20 20:02:54 +00003126 for (auto &I : Inputs) {
3127 types::ID InputType = I.first;
3128 const Arg *InputArg = I.second;
Daniel Dunbar65229332009-03-13 11:38:42 +00003129
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00003130 PL.clear();
3131 types::getCompilationPhases(InputType, PL);
Daniel Dunbar65229332009-03-13 11:38:42 +00003132
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003133 // If the first step comes after the final phase we are doing as part of
3134 // this compilation, warn the user about it.
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00003135 phases::ID InitialPhase = PL[0];
Daniel Dunbar65229332009-03-13 11:38:42 +00003136 if (InitialPhase > FinalPhase) {
Martin Storsjo665c7a42018-05-04 06:05:58 +00003137 if (InputArg->isClaimed())
3138 continue;
3139
Daniel Dunbaradc5c7c2009-03-19 07:57:08 +00003140 // Claim here to avoid the more general unused warning.
3141 InputArg->claim();
Daniel Dunbar07806ca2009-09-17 04:13:26 +00003142
Daniel Dunbar2db3e732011-04-20 15:44:48 +00003143 // Suppress all unused style warnings with -Qunused-arguments
3144 if (Args.hasArg(options::OPT_Qunused_arguments))
3145 continue;
3146
Richard Smith403f76e2012-08-06 04:09:06 +00003147 // Special case when final phase determined by binary name, rather than
3148 // by a command-line argument with a corresponding Arg.
Hans Wennborg70850d82013-07-18 20:29:38 +00003149 if (CCCIsCPP())
Richard Smith403f76e2012-08-06 04:09:06 +00003150 Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003151 << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
Daniel Dunbar07806ca2009-09-17 04:13:26 +00003152 // Special case '-E' warning on a previously preprocessed file to make
3153 // more sense.
Richard Smith403f76e2012-08-06 04:09:06 +00003154 else if (InitialPhase == phases::Compile &&
3155 FinalPhase == phases::Preprocess &&
3156 getPreprocessedType(InputType) == types::TY_INVALID)
Daniel Dunbar07806ca2009-09-17 04:13:26 +00003157 Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003158 << InputArg->getAsString(Args) << !!FinalPhaseArg
3159 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
Daniel Dunbar07806ca2009-09-17 04:13:26 +00003160 else
3161 Diag(clang::diag::warn_drv_input_file_unused)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003162 << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
3163 << !!FinalPhaseArg
3164 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
Daniel Dunbar65229332009-03-13 11:38:42 +00003165 continue;
3166 }
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003167
Nico Weberad2d8f32016-04-21 19:59:10 +00003168 if (YcArg) {
3169 // Add a separate precompile phase for the compile phase.
3170 if (FinalPhase >= phases::Compile) {
Richard Smith8cd452d2016-08-30 18:55:16 +00003171 const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType);
Nico Weberad2d8f32016-04-21 19:59:10 +00003172 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PCHPL;
Richard Smith8cd452d2016-08-30 18:55:16 +00003173 types::getCompilationPhases(HeaderType, PCHPL);
Nico Weberad2d8f32016-04-21 19:59:10 +00003174 // Build the pipeline for the pch file.
Richard Smith8cd452d2016-08-30 18:55:16 +00003175 Action *ClangClPch =
Erich Keane76675de2018-07-05 17:22:13 +00003176 C.MakeAction<InputAction>(*InputArg, HeaderType);
Nico Weberad2d8f32016-04-21 19:59:10 +00003177 for (phases::ID Phase : PCHPL)
3178 ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
3179 assert(ClangClPch);
3180 Actions.push_back(ClangClPch);
3181 // The driver currently exits after the first failed command. This
3182 // relies on that behavior, to make sure if the pch generation fails,
3183 // the main compilation won't run.
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00003184 // FIXME: If the main compilation fails, the PCH generation should
3185 // probably not be considered successful either.
Nico Weberad2d8f32016-04-21 19:59:10 +00003186 }
3187 }
3188
Daniel Dunbar65229332009-03-13 11:38:42 +00003189 // Build the pipeline for this file.
Justin Lebar41094612016-01-11 23:07:27 +00003190 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
Samuel Antao64e965e2016-09-30 15:34:19 +00003191
3192 // Use the current host action in any of the offloading actions, if
3193 // required.
3194 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
3195 break;
3196
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003197 for (SmallVectorImpl<phases::ID>::iterator i = PL.begin(), e = PL.end();
3198 i != e; ++i) {
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00003199 phases::ID Phase = *i;
Daniel Dunbar65229332009-03-13 11:38:42 +00003200
3201 // We are done if this step is past what the user requested.
3202 if (Phase > FinalPhase)
3203 break;
3204
Samuel Antao64e965e2016-09-30 15:34:19 +00003205 // Add any offload action the host action depends on.
3206 Current = OffloadBuilder.addDeviceDependencesToHostAction(
3207 Current, InputArg, Phase, FinalPhase, PL);
3208 if (!Current)
3209 break;
3210
Daniel Dunbar65229332009-03-13 11:38:42 +00003211 // Queue linker inputs.
3212 if (Phase == phases::Link) {
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00003213 assert((i + 1) == e && "linking must be final compilation step.");
Justin Lebar41094612016-01-11 23:07:27 +00003214 LinkerInputs.push_back(Current);
3215 Current = nullptr;
Daniel Dunbar65229332009-03-13 11:38:42 +00003216 break;
3217 }
3218
Richard Smithcd35eff2018-09-15 01:21:16 +00003219 // Each precompiled header file after a module file action is a module
3220 // header of that same module file, rather than being compiled to a
3221 // separate PCH.
3222 if (Phase == phases::Precompile && HeaderModuleAction &&
3223 getPrecompiledType(InputType) == types::TY_PCH) {
3224 HeaderModuleAction->addModuleHeaderInput(Current);
3225 Current = nullptr;
3226 break;
3227 }
3228
3229 // FIXME: Should we include any prior module file outputs as inputs of
3230 // later actions in the same command line?
3231
Samuel Antao64e965e2016-09-30 15:34:19 +00003232 // Otherwise construct the appropriate action.
Richard Smithcd35eff2018-09-15 01:21:16 +00003233 Action *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current);
Samuel Antao64e965e2016-09-30 15:34:19 +00003234
3235 // We didn't create a new action, so we will just move to the next phase.
3236 if (NewCurrent == Current)
Daniel Dunbar13864952009-03-24 20:17:30 +00003237 continue;
3238
Richard Smithcd35eff2018-09-15 01:21:16 +00003239 if (auto *HMA = dyn_cast<HeaderModulePrecompileJobAction>(NewCurrent))
3240 HeaderModuleAction = HMA;
3241
Samuel Antao64e965e2016-09-30 15:34:19 +00003242 Current = NewCurrent;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003243
Samuel Antao64e965e2016-09-30 15:34:19 +00003244 // Use the current host action in any of the offloading actions, if
3245 // required.
3246 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
3247 break;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003248
Daniel Dunbar65229332009-03-13 11:38:42 +00003249 if (Current->getType() == types::TY_Nothing)
3250 break;
3251 }
3252
Samuel Antao64e965e2016-09-30 15:34:19 +00003253 // If we ended with something, add to the output list.
3254 if (Current)
Justin Lebar41094612016-01-11 23:07:27 +00003255 Actions.push_back(Current);
Samuel Antao64e965e2016-09-30 15:34:19 +00003256
3257 // Add any top level actions generated for offloading.
3258 OffloadBuilder.appendTopLevelActions(Actions, Current, InputArg);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00003259 }
Daniel Dunbar65229332009-03-13 11:38:42 +00003260
Samuel Antao64e965e2016-09-30 15:34:19 +00003261 // Add a link action if necessary.
Samuel Antaod06239d2016-07-15 23:13:27 +00003262 if (!LinkerInputs.empty()) {
Samuel Antao64e965e2016-09-30 15:34:19 +00003263 Action *LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image);
3264 LA = OffloadBuilder.processHostLinkAction(LA);
3265 Actions.push_back(LA);
Samuel Antaod06239d2016-07-15 23:13:27 +00003266 }
Daniel Dunbarc7a67b72009-12-22 23:19:32 +00003267
3268 // If we are linking, claim any options which are obviously only used for
3269 // compilation.
Hans Wennborga8ef14f2013-09-17 00:03:41 +00003270 if (FinalPhase == phases::Link && PL.size() == 1) {
Daniel Dunbarc7a67b72009-12-22 23:19:32 +00003271 Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
Hans Wennborga8ef14f2013-09-17 00:03:41 +00003272 Args.ClaimAllArgs(options::OPT_cl_compile_Group);
3273 }
3274
3275 // Claim ignored clang-cl options.
3276 Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
Artem Belevichbaae0932015-07-28 21:01:30 +00003277
Justin Lebardc3c5042016-04-19 02:27:07 +00003278 // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed
3279 // to non-CUDA compilations and should not trigger warnings there.
Artem Belevichbaae0932015-07-28 21:01:30 +00003280 Args.ClaimAllArgs(options::OPT_cuda_host_only);
Justin Lebardc3c5042016-04-19 02:27:07 +00003281 Args.ClaimAllArgs(options::OPT_cuda_compile_host_device);
Daniel Dunbar65229332009-03-13 11:38:42 +00003282}
3283
Artem Belevichecb178b2018-03-21 22:22:59 +00003284Action *Driver::ConstructPhaseAction(
3285 Compilation &C, const ArgList &Args, phases::ID Phase, Action *Input,
3286 Action::OffloadKind TargetDeviceOffloadKind) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00003287 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
Samuel Antao64e965e2016-09-30 15:34:19 +00003288
3289 // Some types skip the assembler phase (e.g., llvm-bc), but we can't
3290 // encode this in the steps because the intermediate type depends on
3291 // arguments. Just special case here.
3292 if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm)
3293 return Input;
3294
Daniel Dunbar65229332009-03-13 11:38:42 +00003295 // Build the appropriate action.
3296 switch (Phase) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003297 case phases::Link:
3298 llvm_unreachable("link action invalid here.");
Daniel Dunbar65229332009-03-13 11:38:42 +00003299 case phases::Preprocess: {
Daniel Dunbard67a3222009-03-30 06:36:42 +00003300 types::ID OutputTy;
3301 // -{M, MM} alter the output type.
Daniel Dunbar86aed7d2010-12-08 21:33:40 +00003302 if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
Daniel Dunbard67a3222009-03-30 06:36:42 +00003303 OutputTy = types::TY_Dependencies;
3304 } else {
David Blaikie5d577a22012-06-29 22:03:56 +00003305 OutputTy = Input->getType();
3306 if (!Args.hasFlag(options::OPT_frewrite_includes,
Justin Bognerce8245b2014-06-24 08:01:01 +00003307 options::OPT_fno_rewrite_includes, false) &&
Richard Smith86a3ef52017-06-09 21:24:02 +00003308 !Args.hasFlag(options::OPT_frewrite_imports,
3309 options::OPT_fno_rewrite_imports, false) &&
Justin Bognerce8245b2014-06-24 08:01:01 +00003310 !CCGenDiagnostics)
David Blaikie5d577a22012-06-29 22:03:56 +00003311 OutputTy = types::getPreprocessedType(OutputTy);
Daniel Dunbard67a3222009-03-30 06:36:42 +00003312 assert(OutputTy != types::TY_INVALID &&
3313 "Cannot preprocess this input type!");
3314 }
Justin Lebar41094612016-01-11 23:07:27 +00003315 return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
Daniel Dunbar65229332009-03-13 11:38:42 +00003316 }
Aaron Ballman1f10cc52012-07-31 01:21:00 +00003317 case phases::Precompile: {
Richard Smithdd4ad3d2016-08-30 19:06:26 +00003318 types::ID OutputTy = getPrecompiledType(Input->getType());
3319 assert(OutputTy != types::TY_INVALID &&
3320 "Cannot precompile this input type!");
Richard Smithcd35eff2018-09-15 01:21:16 +00003321
3322 // If we're given a module name, precompile header file inputs as a
3323 // module, not as a precompiled header.
3324 const char *ModName = nullptr;
3325 if (OutputTy == types::TY_PCH) {
3326 if (Arg *A = Args.getLastArg(options::OPT_fmodule_name_EQ))
3327 ModName = A->getValue();
3328 if (ModName)
3329 OutputTy = types::TY_ModuleFile;
3330 }
3331
Aaron Ballman1f10cc52012-07-31 01:21:00 +00003332 if (Args.hasArg(options::OPT_fsyntax_only)) {
3333 // Syntax checks should not emit a PCH file
3334 OutputTy = types::TY_Nothing;
3335 }
Richard Smithcd35eff2018-09-15 01:21:16 +00003336
3337 if (ModName)
3338 return C.MakeAction<HeaderModulePrecompileJobAction>(Input, OutputTy,
3339 ModName);
Justin Lebar41094612016-01-11 23:07:27 +00003340 return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
Aaron Ballman1f10cc52012-07-31 01:21:00 +00003341 }
Daniel Dunbar65229332009-03-13 11:38:42 +00003342 case phases::Compile: {
David Blaikie486f4402014-08-29 07:25:23 +00003343 if (Args.hasArg(options::OPT_fsyntax_only))
Justin Lebar41094612016-01-11 23:07:27 +00003344 return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
David Blaikie486f4402014-08-29 07:25:23 +00003345 if (Args.hasArg(options::OPT_rewrite_objc))
Justin Lebar41094612016-01-11 23:07:27 +00003346 return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
David Blaikie486f4402014-08-29 07:25:23 +00003347 if (Args.hasArg(options::OPT_rewrite_legacy_objc))
Justin Lebar41094612016-01-11 23:07:27 +00003348 return C.MakeAction<CompileJobAction>(Input,
3349 types::TY_RewrittenLegacyObjC);
David Blaikie486f4402014-08-29 07:25:23 +00003350 if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto))
Justin Lebar41094612016-01-11 23:07:27 +00003351 return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
David Blaikie486f4402014-08-29 07:25:23 +00003352 if (Args.hasArg(options::OPT__migrate))
Justin Lebar41094612016-01-11 23:07:27 +00003353 return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
David Blaikie486f4402014-08-29 07:25:23 +00003354 if (Args.hasArg(options::OPT_emit_ast))
Justin Lebar41094612016-01-11 23:07:27 +00003355 return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
David Blaikie486f4402014-08-29 07:25:23 +00003356 if (Args.hasArg(options::OPT_module_file_info))
Justin Lebar41094612016-01-11 23:07:27 +00003357 return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
David Blaikie486f4402014-08-29 07:25:23 +00003358 if (Args.hasArg(options::OPT_verify_pch))
Justin Lebar41094612016-01-11 23:07:27 +00003359 return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
3360 return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
Bob Wilson23a55f12014-12-21 07:00:00 +00003361 }
3362 case phases::Backend: {
Artem Belevichecb178b2018-03-21 22:22:59 +00003363 if (isUsingLTO() && TargetDeviceOffloadKind == Action::OFK_None) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003364 types::ID Output =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003365 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
Justin Lebar41094612016-01-11 23:07:27 +00003366 return C.MakeAction<BackendJobAction>(Input, Output);
David Blaikie486f4402014-08-29 07:25:23 +00003367 }
3368 if (Args.hasArg(options::OPT_emit_llvm)) {
Shuxin Yang4b3c7ff2013-08-23 21:34:57 +00003369 types::ID Output =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003370 Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
Justin Lebar41094612016-01-11 23:07:27 +00003371 return C.MakeAction<BackendJobAction>(Input, Output);
Daniel Dunbar65229332009-03-13 11:38:42 +00003372 }
Justin Lebar41094612016-01-11 23:07:27 +00003373 return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
Daniel Dunbar65229332009-03-13 11:38:42 +00003374 }
3375 case phases::Assemble:
Justin Lebar21e5d4f2016-01-14 21:41:27 +00003376 return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
Daniel Dunbar65229332009-03-13 11:38:42 +00003377 }
3378
David Blaikie83d382b2011-09-23 05:06:16 +00003379 llvm_unreachable("invalid phase in ConstructPhaseAction");
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00003380}
3381
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00003382void Driver::BuildJobs(Compilation &C) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00003383 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
Daniel Dunbare75d8342009-03-16 06:56:51 +00003384
3385 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
3386
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003387 // It is an error to provide a -o option if we are making multiple output
3388 // files.
Daniel Dunbare75d8342009-03-16 06:56:51 +00003389 if (FinalOutput) {
3390 unsigned NumOutputs = 0;
Saleem Abdulrasoolda3f4e52014-12-29 21:02:47 +00003391 for (const Action *A : C.getActions())
3392 if (A->getType() != types::TY_Nothing)
Daniel Dunbare75d8342009-03-16 06:56:51 +00003393 ++NumOutputs;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003394
Daniel Dunbare75d8342009-03-16 06:56:51 +00003395 if (NumOutputs > 1) {
3396 Diag(clang::diag::err_drv_output_argument_with_multiple_files);
Craig Topper92fc2df2014-05-17 16:56:41 +00003397 FinalOutput = nullptr;
Daniel Dunbare75d8342009-03-16 06:56:51 +00003398 }
3399 }
3400
Chad Rosier35767232013-04-30 22:01:21 +00003401 // Collect the list of architectures.
3402 llvm::StringSet<> ArchNames;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00003403 if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO())
3404 for (const Arg *A : C.getArgs())
Chad Rosier35767232013-04-30 22:01:21 +00003405 if (A->getOption().matches(options::OPT_arch))
3406 ArchNames.insert(A->getValue());
Chad Rosier35767232013-04-30 22:01:21 +00003407
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003408 // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
3409 std::map<std::pair<const Action *, std::string>, InputInfo> CachedResults;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00003410 for (Action *A : C.getActions()) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003411 // If we are linking an image for multiple archs then the linker wants
3412 // -arch_multiple and -final_output <final image name>. Unfortunately, this
3413 // doesn't fit in cleanly because we have to pass this information down.
Daniel Dunbare75d8342009-03-16 06:56:51 +00003414 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003415 // FIXME: This is a hack; find a cleaner way to integrate this into the
3416 // process.
Craig Topper92fc2df2014-05-17 16:56:41 +00003417 const char *LinkingOutput = nullptr;
Daniel Dunbardd765242009-03-26 16:12:09 +00003418 if (isa<LipoJobAction>(A)) {
Daniel Dunbare75d8342009-03-16 06:56:51 +00003419 if (FinalOutput)
Richard Smithbd55daf2012-11-01 04:30:05 +00003420 LinkingOutput = FinalOutput->getValue();
Daniel Dunbare75d8342009-03-16 06:56:51 +00003421 else
Hans Wennborga7707222015-01-09 17:38:53 +00003422 LinkingOutput = getDefaultImageName();
Daniel Dunbare75d8342009-03-16 06:56:51 +00003423 }
3424
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003425 BuildJobsForAction(C, A, &C.getDefaultToolChain(),
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003426 /*BoundArch*/ StringRef(),
Daniel Dunbare75d8342009-03-16 06:56:51 +00003427 /*AtTopLevel*/ true,
Chad Rosier35767232013-04-30 22:01:21 +00003428 /*MultipleArchs*/ ArchNames.size() > 1,
Samuel Antaod06239d2016-07-15 23:13:27 +00003429 /*LinkingOutput*/ LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003430 /*TargetDeviceOffloadKind*/ Action::OFK_None);
Daniel Dunbare75d8342009-03-16 06:56:51 +00003431 }
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00003432
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003433 // If the user passed -Qunused-arguments or there were errors, don't warn
3434 // about any unused arguments.
Argyrios Kyrtzidis31448a42010-11-18 21:47:07 +00003435 if (Diags.hasErrorOccurred() ||
Daniel Dunbara3cfbe32009-04-07 19:04:18 +00003436 C.getArgs().hasArg(options::OPT_Qunused_arguments))
Daniel Dunbard175d972009-03-18 18:03:46 +00003437 return;
3438
Daniel Dunbar58399ae2009-03-29 22:24:54 +00003439 // Claim -### here.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003440 (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003441
Nico Weber47bf5052016-04-25 21:15:49 +00003442 // Claim --driver-mode, --rsp-quoting, it was handled earlier.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003443 (void)C.getArgs().hasArg(options::OPT_driver_mode);
Nico Weber47bf5052016-04-25 21:15:49 +00003444 (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
Hans Wennborg70850d82013-07-18 20:29:38 +00003445
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00003446 for (Arg *A : C.getArgs()) {
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00003447 // FIXME: It would be nice to be able to send the argument to the
David Blaikie9c902b52011-09-25 23:23:43 +00003448 // DiagnosticsEngine, so that extra values, position, and so on could be
3449 // printed.
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003450 if (!A->isClaimed()) {
Michael J. Spencer66e2b202012-10-19 22:37:06 +00003451 if (A->getOption().hasFlag(options::NoArgumentUnused))
Daniel Dunbara3cfbe32009-04-07 19:04:18 +00003452 continue;
3453
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003454 // Suppress the warning automatically if this is just a flag, and it is an
3455 // instance of an argument we already claimed.
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003456 const Option &Opt = A->getOption();
Michael J. Spencerad3ccc32012-08-20 21:41:17 +00003457 if (Opt.getKind() == Option::FlagClass) {
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003458 bool DuplicateClaimed = false;
3459
Sean Silva14facf32015-06-09 01:57:17 +00003460 for (const Arg *AA : C.getArgs().filtered(&Opt)) {
3461 if (AA->isClaimed()) {
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003462 DuplicateClaimed = true;
3463 break;
3464 }
3465 }
3466
3467 if (DuplicateClaimed)
3468 continue;
3469 }
3470
Ehsan Akhgarid8518332016-01-25 21:14:52 +00003471 // In clang-cl, don't mention unknown arguments here since they have
3472 // already been warned about.
3473 if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN))
3474 Diag(clang::diag::warn_drv_unused_argument)
3475 << A->getAsString(C.getArgs());
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003476 }
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00003477 }
Daniel Dunbar95e6b192009-03-13 22:12:33 +00003478}
Daniel Dunbarc4343942010-02-03 03:07:56 +00003479
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003480namespace {
3481/// Utility class to control the collapse of dependent actions and select the
3482/// tools accordingly.
3483class ToolSelector final {
3484 /// The tool chain this selector refers to.
3485 const ToolChain &TC;
Daniel Dunbarf9ff3502010-05-14 02:03:00 +00003486
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003487 /// The compilation this selector refers to.
3488 const Compilation &C;
Samuel Antaod06239d2016-07-15 23:13:27 +00003489
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003490 /// The base action this selector refers to.
3491 const JobAction *BaseAction;
Samuel Antaod06239d2016-07-15 23:13:27 +00003492
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003493 /// Set to true if the current toolchain refers to host actions.
3494 bool IsHostSelector;
Samuel Antaod06239d2016-07-15 23:13:27 +00003495
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003496 /// Set to true if save-temps and embed-bitcode functionalities are active.
3497 bool SaveTemps;
3498 bool EmbedBitcode;
3499
3500 /// Get previous dependent action or null if that does not exist. If
3501 /// \a CanBeCollapsed is false, that action must be legal to collapse or
3502 /// null will be returned.
3503 const JobAction *getPrevDependentAction(const ActionList &Inputs,
3504 ActionList &SavedOffloadAction,
3505 bool CanBeCollapsed = true) {
3506 // An option can be collapsed only if it has a single input.
3507 if (Inputs.size() != 1)
Craig Topper92fc2df2014-05-17 16:56:41 +00003508 return nullptr;
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003509
3510 Action *CurAction = *Inputs.begin();
3511 if (CanBeCollapsed &&
3512 !CurAction->isCollapsingWithNextDependentActionLegal())
3513 return nullptr;
3514
3515 // If the input action is an offload action. Look through it and save any
3516 // offload action that can be dropped in the event of a collapse.
3517 if (auto *OA = dyn_cast<OffloadAction>(CurAction)) {
3518 // If the dependent action is a device action, we will attempt to collapse
3519 // only with other device actions. Otherwise, we would do the same but
3520 // with host actions only.
3521 if (!IsHostSelector) {
3522 if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) {
3523 CurAction =
3524 OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
3525 if (CanBeCollapsed &&
3526 !CurAction->isCollapsingWithNextDependentActionLegal())
3527 return nullptr;
3528 SavedOffloadAction.push_back(OA);
3529 return dyn_cast<JobAction>(CurAction);
3530 }
3531 } else if (OA->hasHostDependence()) {
3532 CurAction = OA->getHostDependence();
3533 if (CanBeCollapsed &&
3534 !CurAction->isCollapsingWithNextDependentActionLegal())
3535 return nullptr;
3536 SavedOffloadAction.push_back(OA);
3537 return dyn_cast<JobAction>(CurAction);
3538 }
3539 return nullptr;
3540 }
3541
3542 return dyn_cast<JobAction>(CurAction);
3543 }
3544
3545 /// Return true if an assemble action can be collapsed.
3546 bool canCollapseAssembleAction() const {
3547 return TC.useIntegratedAs() && !SaveTemps &&
3548 !C.getArgs().hasArg(options::OPT_via_file_asm) &&
3549 !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
3550 !C.getArgs().hasArg(options::OPT__SLASH_Fa);
3551 }
3552
3553 /// Return true if a preprocessor action can be collapsed.
3554 bool canCollapsePreprocessorAction() const {
3555 return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
3556 !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
3557 !C.getArgs().hasArg(options::OPT_rewrite_objc);
3558 }
3559
3560 /// Struct that relates an action with the offload actions that would be
3561 /// collapsed with it.
3562 struct JobActionInfo final {
3563 /// The action this info refers to.
3564 const JobAction *JA = nullptr;
3565 /// The offload actions we need to take care off if this action is
3566 /// collapsed.
3567 ActionList SavedOffloadAction;
3568 };
3569
3570 /// Append collapsed offload actions from the give nnumber of elements in the
3571 /// action info array.
3572 static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction,
3573 ArrayRef<JobActionInfo> &ActionInfo,
3574 unsigned ElementNum) {
3575 assert(ElementNum <= ActionInfo.size() && "Invalid number of elements.");
3576 for (unsigned I = 0; I < ElementNum; ++I)
3577 CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(),
3578 ActionInfo[I].SavedOffloadAction.end());
3579 }
3580
3581 /// Functions that attempt to perform the combining. They detect if that is
3582 /// legal, and if so they update the inputs \a Inputs and the offload action
3583 /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with
3584 /// the combined action is returned. If the combining is not legal or if the
3585 /// tool does not exist, null is returned.
3586 /// Currently three kinds of collapsing are supported:
3587 /// - Assemble + Backend + Compile;
3588 /// - Assemble + Backend ;
3589 /// - Backend + Compile.
3590 const Tool *
3591 combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
Richard Smithcd35eff2018-09-15 01:21:16 +00003592 ActionList &Inputs,
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003593 ActionList &CollapsedOffloadAction) {
3594 if (ActionInfo.size() < 3 || !canCollapseAssembleAction())
3595 return nullptr;
3596 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
3597 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
3598 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA);
3599 if (!AJ || !BJ || !CJ)
3600 return nullptr;
3601
3602 // Get compiler tool.
3603 const Tool *T = TC.SelectTool(*CJ);
3604 if (!T)
3605 return nullptr;
3606
Steven Wu574b0f22016-03-01 01:07:58 +00003607 // When using -fembed-bitcode, it is required to have the same tool (clang)
3608 // for both CompilerJA and BackendJA. Otherwise, combine two stages.
3609 if (EmbedBitcode) {
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003610 const Tool *BT = TC.SelectTool(*BJ);
3611 if (BT == T)
3612 return nullptr;
Steven Wu574b0f22016-03-01 01:07:58 +00003613 }
Bob Wilson23a55f12014-12-21 07:00:00 +00003614
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003615 if (!T->hasIntegratedAssembler())
Bob Wilson23a55f12014-12-21 07:00:00 +00003616 return nullptr;
Samuel Antaod06239d2016-07-15 23:13:27 +00003617
Richard Smithcd35eff2018-09-15 01:21:16 +00003618 Inputs = CJ->getInputs();
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003619 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3620 /*NumElements=*/3);
3621 return T;
3622 }
3623 const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo,
Richard Smithcd35eff2018-09-15 01:21:16 +00003624 ActionList &Inputs,
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003625 ActionList &CollapsedOffloadAction) {
3626 if (ActionInfo.size() < 2 || !canCollapseAssembleAction())
3627 return nullptr;
3628 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
3629 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
3630 if (!AJ || !BJ)
3631 return nullptr;
3632
3633 // Retrieve the compile job, backend action must always be preceded by one.
3634 ActionList CompileJobOffloadActions;
3635 auto *CJ = getPrevDependentAction(BJ->getInputs(), CompileJobOffloadActions,
3636 /*CanBeCollapsed=*/false);
3637 if (!AJ || !BJ || !CJ)
3638 return nullptr;
3639
3640 assert(isa<CompileJobAction>(CJ) &&
3641 "Expecting compile job preceding backend job.");
3642
3643 // Get compiler tool.
3644 const Tool *T = TC.SelectTool(*CJ);
3645 if (!T)
3646 return nullptr;
3647
3648 if (!T->hasIntegratedAssembler())
3649 return nullptr;
3650
Richard Smithcd35eff2018-09-15 01:21:16 +00003651 Inputs = BJ->getInputs();
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003652 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3653 /*NumElements=*/2);
3654 return T;
3655 }
3656 const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
Richard Smithcd35eff2018-09-15 01:21:16 +00003657 ActionList &Inputs,
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003658 ActionList &CollapsedOffloadAction) {
Teresa Johnson9e4321c2018-04-17 16:39:25 +00003659 if (ActionInfo.size() < 2)
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003660 return nullptr;
3661 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA);
3662 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA);
3663 if (!BJ || !CJ)
3664 return nullptr;
3665
Teresa Johnson9e4321c2018-04-17 16:39:25 +00003666 // Check if the initial input (to the compile job or its predessor if one
3667 // exists) is LLVM bitcode. In that case, no preprocessor step is required
3668 // and we can still collapse the compile and backend jobs when we have
3669 // -save-temps. I.e. there is no need for a separate compile job just to
3670 // emit unoptimized bitcode.
3671 bool InputIsBitcode = true;
3672 for (size_t i = 1; i < ActionInfo.size(); i++)
3673 if (ActionInfo[i].JA->getType() != types::TY_LLVM_BC &&
3674 ActionInfo[i].JA->getType() != types::TY_LTO_BC) {
3675 InputIsBitcode = false;
3676 break;
3677 }
3678 if (!InputIsBitcode && !canCollapsePreprocessorAction())
3679 return nullptr;
3680
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003681 // Get compiler tool.
3682 const Tool *T = TC.SelectTool(*CJ);
3683 if (!T)
3684 return nullptr;
3685
Teresa Johnson9e4321c2018-04-17 16:39:25 +00003686 if (T->canEmitIR() && ((SaveTemps && !InputIsBitcode) || EmbedBitcode))
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003687 return nullptr;
3688
Richard Smithcd35eff2018-09-15 01:21:16 +00003689 Inputs = CJ->getInputs();
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003690 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3691 /*NumElements=*/2);
3692 return T;
3693 }
3694
3695 /// Updates the inputs if the obtained tool supports combining with
3696 /// preprocessor action, and the current input is indeed a preprocessor
3697 /// action. If combining results in the collapse of offloading actions, those
3698 /// are appended to \a CollapsedOffloadAction.
Richard Smithcd35eff2018-09-15 01:21:16 +00003699 void combineWithPreprocessor(const Tool *T, ActionList &Inputs,
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003700 ActionList &CollapsedOffloadAction) {
3701 if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP())
3702 return;
3703
3704 // Attempt to get a preprocessor action dependence.
3705 ActionList PreprocessJobOffloadActions;
Richard Smithcd35eff2018-09-15 01:21:16 +00003706 ActionList NewInputs;
3707 for (Action *A : Inputs) {
3708 auto *PJ = getPrevDependentAction({A}, PreprocessJobOffloadActions);
3709 if (!PJ || !isa<PreprocessJobAction>(PJ)) {
3710 NewInputs.push_back(A);
3711 continue;
3712 }
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003713
Richard Smithcd35eff2018-09-15 01:21:16 +00003714 // This is legal to combine. Append any offload action we found and add the
3715 // current input to preprocessor inputs.
3716 CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(),
3717 PreprocessJobOffloadActions.end());
3718 NewInputs.append(PJ->input_begin(), PJ->input_end());
3719 }
3720 Inputs = NewInputs;
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003721 }
3722
3723public:
3724 ToolSelector(const JobAction *BaseAction, const ToolChain &TC,
3725 const Compilation &C, bool SaveTemps, bool EmbedBitcode)
3726 : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps),
3727 EmbedBitcode(EmbedBitcode) {
3728 assert(BaseAction && "Invalid base action.");
3729 IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None;
3730 }
3731
3732 /// Check if a chain of actions can be combined and return the tool that can
3733 /// handle the combination of actions. The pointer to the current inputs \a
3734 /// Inputs and the list of offload actions \a CollapsedOffloadActions
3735 /// connected to collapsed actions are updated accordingly. The latter enables
3736 /// the caller of the selector to process them afterwards instead of just
3737 /// dropping them. If no suitable tool is found, null will be returned.
Richard Smithcd35eff2018-09-15 01:21:16 +00003738 const Tool *getTool(ActionList &Inputs,
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003739 ActionList &CollapsedOffloadAction) {
3740 //
3741 // Get the largest chain of actions that we could combine.
3742 //
3743
3744 SmallVector<JobActionInfo, 5> ActionChain(1);
3745 ActionChain.back().JA = BaseAction;
3746 while (ActionChain.back().JA) {
3747 const Action *CurAction = ActionChain.back().JA;
3748
3749 // Grow the chain by one element.
3750 ActionChain.resize(ActionChain.size() + 1);
3751 JobActionInfo &AI = ActionChain.back();
3752
3753 // Attempt to fill it with the
3754 AI.JA =
3755 getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction);
Daniel Dunbarc4343942010-02-03 03:07:56 +00003756 }
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003757
3758 // Pop the last action info as it could not be filled.
3759 ActionChain.pop_back();
3760
3761 //
3762 // Attempt to combine actions. If all combining attempts failed, just return
3763 // the tool of the provided action. At the end we attempt to combine the
3764 // action with any preprocessor action it may depend on.
3765 //
3766
3767 const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs,
3768 CollapsedOffloadAction);
3769 if (!T)
3770 T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction);
3771 if (!T)
3772 T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction);
3773 if (!T) {
Richard Smithcd35eff2018-09-15 01:21:16 +00003774 Inputs = BaseAction->getInputs();
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003775 T = TC.SelectTool(*BaseAction);
3776 }
3777
3778 combineWithPreprocessor(T, Inputs, CollapsedOffloadAction);
3779 return T;
Daniel Dunbarc4343942010-02-03 03:07:56 +00003780 }
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003781};
Daniel Dunbarc4343942010-02-03 03:07:56 +00003782}
3783
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003784/// Return a string that uniquely identifies the result of a job. The bound arch
3785/// is not necessarily represented in the toolchain's triple -- for example,
3786/// armv7 and armv7s both map to the same triple -- so we need both in our map.
3787/// Also, we need to add the offloading device kind, as the same tool chain can
3788/// be used for host and device for some programming models, e.g. OpenMP.
3789static std::string GetTriplePlusArchString(const ToolChain *TC,
3790 StringRef BoundArch,
3791 Action::OffloadKind OffloadKind) {
Justin Lebar55c83322016-01-16 03:30:08 +00003792 std::string TriplePlusArch = TC->getTriple().normalize();
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003793 if (!BoundArch.empty()) {
Justin Lebar55c83322016-01-16 03:30:08 +00003794 TriplePlusArch += "-";
3795 TriplePlusArch += BoundArch;
3796 }
Samuel Antao59efaed2016-10-27 17:31:22 +00003797 TriplePlusArch += "-";
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003798 TriplePlusArch += Action::GetOffloadKindName(OffloadKind);
3799 return TriplePlusArch;
3800}
3801
3802InputInfo Driver::BuildJobsForAction(
3803 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
3804 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
3805 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
3806 Action::OffloadKind TargetDeviceOffloadKind) const {
3807 std::pair<const Action *, std::string> ActionTC = {
3808 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003809 auto CachedResult = CachedResults.find(ActionTC);
3810 if (CachedResult != CachedResults.end()) {
3811 return CachedResult->second;
3812 }
Samuel Antaod06239d2016-07-15 23:13:27 +00003813 InputInfo Result = BuildJobsForActionNoCache(
3814 C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003815 CachedResults, TargetDeviceOffloadKind);
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003816 CachedResults[ActionTC] = Result;
3817 return Result;
3818}
3819
3820InputInfo Driver::BuildJobsForActionNoCache(
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003821 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003822 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
Samuel Antaod06239d2016-07-15 23:13:27 +00003823 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003824 Action::OffloadKind TargetDeviceOffloadKind) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003825 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
Daniel Dunbarc4acf9d2009-03-18 23:18:19 +00003826
Samuel Antaod06239d2016-07-15 23:13:27 +00003827 InputInfoList OffloadDependencesInputInfo;
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003828 bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None;
Samuel Antaod06239d2016-07-15 23:13:27 +00003829 if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
Alex Lorenz4003a982017-08-08 11:22:21 +00003830 // The 'Darwin' toolchain is initialized only when its arguments are
3831 // computed. Get the default arguments for OFK_None to ensure that
3832 // initialization is performed before processing the offload action.
3833 // FIXME: Remove when darwin's toolchain is initialized during construction.
3834 C.getArgsForToolChain(TC, BoundArch, Action::OFK_None);
3835
Samuel Antaod06239d2016-07-15 23:13:27 +00003836 // The offload action is expected to be used in four different situations.
3837 //
3838 // a) Set a toolchain/architecture/kind for a host action:
3839 // Host Action 1 -> OffloadAction -> Host Action 2
3840 //
3841 // b) Set a toolchain/architecture/kind for a device action;
3842 // Device Action 1 -> OffloadAction -> Device Action 2
3843 //
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003844 // c) Specify a device dependence to a host action;
Samuel Antaod06239d2016-07-15 23:13:27 +00003845 // Device Action 1 _
3846 // \
3847 // Host Action 1 ---> OffloadAction -> Host Action 2
3848 //
3849 // d) Specify a host dependence to a device action.
3850 // Host Action 1 _
3851 // \
3852 // Device Action 1 ---> OffloadAction -> Device Action 2
3853 //
3854 // For a) and b), we just return the job generated for the dependence. For
3855 // c) and d) we override the current action with the host/device dependence
3856 // if the current toolchain is host/device and set the offload dependences
3857 // info with the jobs obtained from the device/host dependence(s).
3858
3859 // If there is a single device option, just generate the job for it.
3860 if (OA->hasSingleDeviceDependence()) {
3861 InputInfo DevA;
3862 OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
3863 const char *DepBoundArch) {
3864 DevA =
3865 BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
3866 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003867 CachedResults, DepA->getOffloadingDeviceKind());
Samuel Antaod06239d2016-07-15 23:13:27 +00003868 });
3869 return DevA;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003870 }
Samuel Antaod06239d2016-07-15 23:13:27 +00003871
3872 // If 'Action 2' is host, we generate jobs for the device dependences and
3873 // override the current action with the host dependence. Otherwise, we
3874 // generate the host dependences and override the action with the device
3875 // dependence. The dependences can't therefore be a top-level action.
3876 OA->doOnEachDependence(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003877 /*IsHostDependence=*/BuildingForOffloadDevice,
Samuel Antaod06239d2016-07-15 23:13:27 +00003878 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3879 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
3880 C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false,
3881 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003882 DepA->getOffloadingDeviceKind()));
Samuel Antaod06239d2016-07-15 23:13:27 +00003883 });
3884
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003885 A = BuildingForOffloadDevice
Samuel Antaod06239d2016-07-15 23:13:27 +00003886 ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
3887 : OA->getHostDependence();
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003888 }
3889
Daniel Dunbare75d8342009-03-16 06:56:51 +00003890 if (const InputAction *IA = dyn_cast<InputAction>(A)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003891 // FIXME: It would be nice to not claim this here; maybe the old scheme of
3892 // just using Args was better?
Daniel Dunbar5cdf3e02009-03-19 07:29:38 +00003893 const Arg &Input = IA->getInputArg();
3894 Input.claim();
Daniel Dunbar35cbfeb2010-06-09 22:31:08 +00003895 if (Input.getOption().matches(options::OPT_INPUT)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00003896 const char *Name = Input.getValue();
Justin Lebard98cea82016-01-11 23:15:21 +00003897 return InputInfo(A, Name, /* BaseInput = */ Name);
Douglas Katzman678d0cb2015-06-16 18:01:24 +00003898 }
Justin Lebard98cea82016-01-11 23:15:21 +00003899 return InputInfo(A, &Input, /* BaseInput = */ "");
Daniel Dunbare75d8342009-03-16 06:56:51 +00003900 }
3901
3902 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
Chad Rosiera78a6eb2012-04-27 16:50:38 +00003903 const ToolChain *TC;
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003904 StringRef ArchName = BAA->getArchName();
Daniel Dunbar1ef3f2a2009-09-08 23:37:19 +00003905
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003906 if (!ArchName.empty())
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +00003907 TC = &getToolChain(C.getArgs(),
Petr Hosekdd38d932018-05-29 22:35:39 +00003908 computeTargetTriple(*this, TargetTriple,
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +00003909 C.getArgs(), ArchName));
Chad Rosiera78a6eb2012-04-27 16:50:38 +00003910 else
3911 TC = &C.getDefaultToolChain();
Daniel Dunbar1ef3f2a2009-09-08 23:37:19 +00003912
Nico Weber5a459f82016-02-23 19:30:43 +00003913 return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
Samuel Antaod06239d2016-07-15 23:13:27 +00003914 MultipleArchs, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003915 TargetDeviceOffloadKind);
Daniel Dunbare75d8342009-03-16 06:56:51 +00003916 }
3917
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003918
Richard Smithcd35eff2018-09-15 01:21:16 +00003919 ActionList Inputs = A->getInputs();
Daniel Dunbarc4343942010-02-03 03:07:56 +00003920
3921 const JobAction *JA = cast<JobAction>(A);
Samuel Antaod06239d2016-07-15 23:13:27 +00003922 ActionList CollapsedOffloadActions;
3923
Mehdi Amini6683e222017-01-24 18:12:25 +00003924 ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(),
3925 embedBitcodeInObject() && !isUsingLTO());
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003926 const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions);
3927
Rafael Espindola79764462013-03-24 15:06:53 +00003928 if (!T)
Justin Lebar9eaa4892016-01-11 23:09:32 +00003929 return InputInfo();
Daniel Dunbare75d8342009-03-16 06:56:51 +00003930
Samuel Antaod06239d2016-07-15 23:13:27 +00003931 // If we've collapsed action list that contained OffloadAction we
3932 // need to build jobs for host/device-side inputs it may have held.
3933 for (const auto *OA : CollapsedOffloadActions)
3934 cast<OffloadAction>(OA)->doOnEachDependence(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003935 /*IsHostDependence=*/BuildingForOffloadDevice,
Samuel Antaod06239d2016-07-15 23:13:27 +00003936 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3937 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
Artem Belevichbee2f412016-08-22 18:50:34 +00003938 C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false,
Samuel Antaod06239d2016-07-15 23:13:27 +00003939 /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003940 DepA->getOffloadingDeviceKind()));
Samuel Antaod06239d2016-07-15 23:13:27 +00003941 });
Artem Belevichf8144ab2015-08-27 18:10:41 +00003942
Daniel Dunbare75d8342009-03-16 06:56:51 +00003943 // Only use pipes when there is exactly one input.
Daniel Dunbar1a093d22009-03-18 06:00:36 +00003944 InputInfoList InputInfos;
Richard Smithcd35eff2018-09-15 01:21:16 +00003945 for (const Action *Input : Inputs) {
Eric Christopher14668dd2013-02-18 00:38:25 +00003946 // Treat dsymutil and verify sub-jobs as being at the top-level too, they
3947 // shouldn't get temporary output names.
Daniel Dunbar6beaf512010-06-04 18:28:41 +00003948 // FIXME: Clean this up.
Justin Lebar9eaa4892016-01-11 23:09:32 +00003949 bool SubJobAtTopLevel =
3950 AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
Samuel Antaod06239d2016-07-15 23:13:27 +00003951 InputInfos.push_back(BuildJobsForAction(
3952 C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003953 CachedResults, A->getOffloadingDeviceKind()));
Daniel Dunbare75d8342009-03-16 06:56:51 +00003954 }
3955
Daniel Dunbare75d8342009-03-16 06:56:51 +00003956 // Always use the first input as the base input.
3957 const char *BaseInput = InputInfos[0].getBaseInput();
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003958
Daniel Dunbar6beaf512010-06-04 18:28:41 +00003959 // ... except dsymutil actions, which use their actual input as the base
3960 // input.
3961 if (JA->getType() == types::TY_dSYM)
3962 BaseInput = InputInfos[0].getFilename();
3963
Richard Smithcd35eff2018-09-15 01:21:16 +00003964 // ... and in header module compilations, which use the module name.
3965 if (auto *ModuleJA = dyn_cast<HeaderModulePrecompileJobAction>(JA))
3966 BaseInput = ModuleJA->getModuleName();
3967
Samuel Antaod06239d2016-07-15 23:13:27 +00003968 // Append outputs of offload device jobs to the input list
3969 if (!OffloadDependencesInputInfo.empty())
3970 InputInfos.append(OffloadDependencesInputInfo.begin(),
3971 OffloadDependencesInputInfo.end());
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003972
Vedant Kumar18286cf2016-07-27 23:02:20 +00003973 // Set the effective triple of the toolchain for the duration of this job.
3974 llvm::Triple EffectiveTriple;
3975 const ToolChain &ToolTC = T->getToolChain();
Samuel Antao31fef982016-10-27 17:39:44 +00003976 const ArgList &Args =
3977 C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind());
Vedant Kumar18286cf2016-07-27 23:02:20 +00003978 if (InputInfos.size() != 1) {
3979 EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args));
3980 } else {
3981 // Pass along the input type if it can be unambiguously determined.
3982 EffectiveTriple = llvm::Triple(
3983 ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType()));
3984 }
3985 RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple);
3986
Daniel Dunbard00272f2010-08-02 02:38:15 +00003987 // Determine the place to write output to, if any.
Justin Lebar9eaa4892016-01-11 23:09:32 +00003988 InputInfo Result;
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003989 InputInfoList UnbundlingResults;
3990 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) {
3991 // If we have an unbundling job, we need to create results for all the
3992 // outputs. We also update the results cache so that other actions using
3993 // this unbundling action can get the right results.
3994 for (auto &UI : UA->getDependentActionsInfo()) {
3995 assert(UI.DependentOffloadKind != Action::OFK_None &&
3996 "Unbundling with no offloading??");
3997
3998 // Unbundling actions are never at the top level. When we generate the
3999 // offloading prefix, we also do that for the host file because the
4000 // unbundling action does not change the type of the output which can
4001 // cause a overwrite.
4002 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
4003 UI.DependentOffloadKind,
4004 UI.DependentToolChain->getTriple().normalize(),
4005 /*CreatePrefixForHost=*/true);
4006 auto CurI = InputInfo(
Yaxun Liu609f7522018-05-11 19:02:18 +00004007 UA,
4008 GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch,
4009 /*AtTopLevel=*/false,
4010 MultipleArchs ||
4011 UI.DependentOffloadKind == Action::OFK_HIP,
4012 OffloadingPrefix),
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004013 BaseInput);
4014 // Save the unbundling result.
4015 UnbundlingResults.push_back(CurI);
4016
4017 // Get the unique string identifier for this dependence and cache the
4018 // result.
Yaxun Liu470b8332018-06-06 19:44:10 +00004019 StringRef Arch;
4020 if (TargetDeviceOffloadKind == Action::OFK_HIP) {
4021 if (UI.DependentOffloadKind == Action::OFK_Host)
Yaxun Liuf37b50a2018-07-24 01:03:44 +00004022 Arch = StringRef();
Yaxun Liu470b8332018-06-06 19:44:10 +00004023 else
4024 Arch = UI.DependentBoundArch;
4025 } else
4026 Arch = BoundArch;
4027
4028 CachedResults[{A, GetTriplePlusArchString(UI.DependentToolChain, Arch,
4029 UI.DependentOffloadKind)}] =
4030 CurI;
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004031 }
4032
4033 // Now that we have all the results generated, select the one that should be
4034 // returned for the current depending action.
4035 std::pair<const Action *, std::string> ActionTC = {
4036 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
4037 assert(CachedResults.find(ActionTC) != CachedResults.end() &&
4038 "Result does not exist??");
4039 Result = CachedResults[ActionTC];
4040 } else if (JA->getType() == types::TY_Nothing)
Justin Lebard98cea82016-01-11 23:15:21 +00004041 Result = InputInfo(A, BaseInput);
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004042 else {
4043 // We only have to generate a prefix for the host if this is not a top-level
4044 // action.
4045 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
4046 A->getOffloadingDeviceKind(), TC->getTriple().normalize(),
4047 /*CreatePrefixForHost=*/!!A->getOffloadingHostActiveKinds() &&
4048 !AtTopLevel);
Justin Lebard98cea82016-01-11 23:15:21 +00004049 Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
Samuel Antaod06239d2016-07-15 23:13:27 +00004050 AtTopLevel, MultipleArchs,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004051 OffloadingPrefix),
Justin Lebard98cea82016-01-11 23:15:21 +00004052 BaseInput);
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004053 }
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004054
Chad Rosierbe10f982011-08-02 17:58:04 +00004055 if (CCCPrintBindings && !CCGenDiagnostics) {
Rafael Espindola79764462013-03-24 15:06:53 +00004056 llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
4057 << " - \"" << T->getName() << "\", inputs: [";
Daniel Dunbarb39cc522009-03-17 22:47:06 +00004058 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
4059 llvm::errs() << InputInfos[i].getAsString();
4060 if (i + 1 != e)
4061 llvm::errs() << ", ";
4062 }
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004063 if (UnbundlingResults.empty())
4064 llvm::errs() << "], output: " << Result.getAsString() << "\n";
4065 else {
4066 llvm::errs() << "], outputs: [";
4067 for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) {
4068 llvm::errs() << UnbundlingResults[i].getAsString();
4069 if (i + 1 != e)
4070 llvm::errs() << ", ";
4071 }
4072 llvm::errs() << "] \n";
4073 }
Daniel Dunbarb39cc522009-03-17 22:47:06 +00004074 } else {
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004075 if (UnbundlingResults.empty())
4076 T->ConstructJob(
4077 C, *JA, Result, InputInfos,
4078 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
4079 LinkingOutput);
4080 else
Samuel Antao7108bf32016-11-03 15:41:50 +00004081 T->ConstructJobMultipleOutputs(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004082 C, *JA, UnbundlingResults, InputInfos,
4083 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
4084 LinkingOutput);
Daniel Dunbarb39cc522009-03-17 22:47:06 +00004085 }
Justin Lebar9eaa4892016-01-11 23:09:32 +00004086 return Result;
Daniel Dunbare75d8342009-03-16 06:56:51 +00004087}
4088
Hans Wennborga7707222015-01-09 17:38:53 +00004089const char *Driver::getDefaultImageName() const {
Petr Hosekdd38d932018-05-29 22:35:39 +00004090 llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
Hans Wennborga7707222015-01-09 17:38:53 +00004091 return Target.isOSWindows() ? "a.exe" : "a.out";
4092}
4093
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004094/// Create output filename based on ArgValue, which could either be a
Hans Wennborg2c21f742013-10-17 16:16:23 +00004095/// full filename, filename without extension, or a directory. If ArgValue
4096/// does not provide a filename, then use BaseName, and use the extension
4097/// suitable for FileType.
Hans Wennborg207fcf02013-08-12 21:56:42 +00004098static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004099 StringRef BaseName,
4100 types::ID FileType) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00004101 SmallString<128> Filename = ArgValue;
Justin Bogner5aaf2e72014-06-26 20:59:36 +00004102
Hans Wennborgf1a74252013-09-10 20:18:04 +00004103 if (ArgValue.empty()) {
4104 // If the argument is empty, output to BaseName in the current dir.
4105 Filename = BaseName;
4106 } else if (llvm::sys::path::is_separator(Filename.back())) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00004107 // If the argument is a directory, output to BaseName in that dir.
4108 llvm::sys::path::append(Filename, BaseName);
4109 }
4110
4111 if (!llvm::sys::path::has_extension(ArgValue)) {
4112 // If the argument didn't provide an extension, then set it.
4113 const char *Extension = types::getTypeTempSuffix(FileType, true);
Hans Wennborgf1a74252013-09-10 20:18:04 +00004114
4115 if (FileType == types::TY_Image &&
4116 Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
4117 // The output file is a dll.
4118 Extension = "dll";
4119 }
4120
Hans Wennborg207fcf02013-08-12 21:56:42 +00004121 llvm::sys::path::replace_extension(Filename, Extension);
4122 }
4123
4124 return Args.MakeArgString(Filename.c_str());
4125}
4126
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004127const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004128 const char *BaseInput,
Mehdi Aminic50b1a22016-10-07 21:27:26 +00004129 StringRef BoundArch, bool AtTopLevel,
Samuel Antaod06239d2016-07-15 23:13:27 +00004130 bool MultipleArchs,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004131 StringRef OffloadingPrefix) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00004132 llvm::PrettyStackTraceString CrashInfo("Computing output path");
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004133 // Output to a user requested destination?
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004134 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004135 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
Chad Rosier633dcdc2013-01-24 19:14:47 +00004136 return C.addResultFile(FinalOutput->getValue(), &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004137 }
4138
Hans Wennborge0053472013-12-20 18:40:46 +00004139 // For /P, preprocess to file named after BaseInput.
4140 if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
4141 assert(AtTopLevel && isa<PreprocessJobAction>(JA));
4142 StringRef BaseName = llvm::sys::path::filename(BaseInput);
Hans Wennborg04c764f2014-06-17 00:19:12 +00004143 StringRef NameArg;
Greg Bedwell065f70a2015-06-09 10:24:06 +00004144 if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
Hans Wennborg04c764f2014-06-17 00:19:12 +00004145 NameArg = A->getValue();
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004146 return C.addResultFile(
4147 MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
4148 &JA);
Hans Wennborge0053472013-12-20 18:40:46 +00004149 }
4150
Nick Lewycky6e1ce292010-09-24 00:46:53 +00004151 // Default to writing to stdout?
David Blaikiebc023c92018-06-14 23:09:06 +00004152 if (AtTopLevel && !CCGenDiagnostics && isa<PreprocessJobAction>(JA))
Nick Lewycky6e1ce292010-09-24 00:46:53 +00004153 return "-";
4154
Hans Wennborg2c21f742013-10-17 16:16:23 +00004155 // Is this the assembly listing for /FA?
4156 if (JA.getType() == types::TY_PP_Asm &&
4157 (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
4158 C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
4159 // Use /Fa and the input filename to determine the asm file name.
4160 StringRef BaseName = llvm::sys::path::filename(BaseInput);
4161 StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004162 return C.addResultFile(
4163 MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
4164 &JA);
Hans Wennborg2c21f742013-10-17 16:16:23 +00004165 }
4166
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004167 // Output to a temporary file?
Reid Kleckner68eb60b2015-02-02 22:41:48 +00004168 if ((!AtTopLevel && !isSaveTempsEnabled() &&
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004169 !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
Chad Rosierbe10f982011-08-02 17:58:04 +00004170 CCGenDiagnostics) {
Chad Rosier97c37372011-08-26 22:27:02 +00004171 StringRef Name = llvm::sys::path::filename(BaseInput);
4172 std::pair<StringRef, StringRef> Split = Name.split('.');
Bob Haarman7e4d3ff2018-07-09 21:07:20 +00004173 SmallString<128> TmpName;
4174 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
4175 Arg *A = C.getArgs().getLastArg(options::OPT_fcrash_diagnostics_dir);
4176 if (CCGenDiagnostics && A) {
4177 SmallString<128> CrashDirectory(A->getValue());
4178 llvm::sys::path::append(CrashDirectory, Split.first);
4179 const char *Middle = Suffix ? "-%%%%%%." : "-%%%%%%";
4180 std::error_code EC =
4181 llvm::sys::fs::createUniqueFile(CrashDirectory + Middle + Suffix, TmpName);
4182 if (EC) {
4183 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
4184 return "";
4185 }
4186 } else {
4187 TmpName = GetTemporaryPath(Split.first, Suffix);
4188 }
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00004189 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004190 }
4191
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004192 SmallString<128> BasePath(BaseInput);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004193 StringRef BaseName;
Daniel Dunbar67fea712011-03-25 18:16:51 +00004194
4195 // Dsymutil actions should use the full path.
Eric Christopher551ef452011-08-23 17:56:55 +00004196 if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
Daniel Dunbar67fea712011-03-25 18:16:51 +00004197 BaseName = BasePath;
4198 else
4199 BaseName = llvm::sys::path::filename(BasePath);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004200
4201 // Determine what the derived output name should be.
4202 const char *NamedOutput;
Hans Wennborg2b89a262013-08-06 22:11:28 +00004203
Hans Wennborg625fba82016-10-04 21:01:04 +00004204 if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) &&
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00004205 C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
4206 // The /Fo or /o flag decides the object filename.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004207 StringRef Val =
4208 C.getArgs()
4209 .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
4210 ->getValue();
4211 NamedOutput =
4212 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
Hans Wennborg207fcf02013-08-12 21:56:42 +00004213 } else if (JA.getType() == types::TY_Image &&
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004214 C.getArgs().hasArg(options::OPT__SLASH_Fe,
4215 options::OPT__SLASH_o)) {
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00004216 // The /Fe or /o flag names the linked file.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004217 StringRef Val =
4218 C.getArgs()
4219 .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
4220 ->getValue();
4221 NamedOutput =
4222 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
Hans Wennborgf1a74252013-09-10 20:18:04 +00004223 } else if (JA.getType() == types::TY_Image) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00004224 if (IsCLMode()) {
4225 // clang-cl uses BaseName for the executable name.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004226 NamedOutput =
4227 MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
Samuel Antao59efaed2016-10-27 17:31:22 +00004228 } else {
Hans Wennborga7707222015-01-09 17:38:53 +00004229 SmallString<128> Output(getDefaultImageName());
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004230 Output += OffloadingPrefix;
Samuel Antao59efaed2016-10-27 17:31:22 +00004231 if (MultipleArchs && !BoundArch.empty()) {
4232 Output += "-";
4233 Output.append(BoundArch);
4234 }
Chad Rosier35767232013-04-30 22:01:21 +00004235 NamedOutput = C.getArgs().MakeArgString(Output.c_str());
Nico Weber2ca4be92016-03-01 23:16:44 +00004236 }
4237 } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00004238 NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName));
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004239 } else {
Hans Wennborg0a096a02013-09-05 17:05:56 +00004240 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004241 assert(Suffix && "All types used for output should have a suffix.");
4242
4243 std::string::size_type End = std::string::npos;
4244 if (!types::appendSuffixForType(JA.getType()))
4245 End = BaseName.rfind('.');
Chad Rosier35767232013-04-30 22:01:21 +00004246 SmallString<128> Suffixed(BaseName.substr(0, End));
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004247 Suffixed += OffloadingPrefix;
Mehdi Aminic50b1a22016-10-07 21:27:26 +00004248 if (MultipleArchs && !BoundArch.empty()) {
Chad Rosier35767232013-04-30 22:01:21 +00004249 Suffixed += "-";
4250 Suffixed.append(BoundArch);
4251 }
Bob Wilson23a55f12014-12-21 07:00:00 +00004252 // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
4253 // the unoptimized bitcode so that it does not get overwritten by the ".bc"
4254 // optimized bitcode output.
4255 if (!AtTopLevel && C.getArgs().hasArg(options::OPT_emit_llvm) &&
4256 JA.getType() == types::TY_LLVM_BC)
4257 Suffixed += ".tmp";
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004258 Suffixed += '.';
4259 Suffixed += Suffix;
4260 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
4261 }
4262
Reid Kleckner68eb60b2015-02-02 22:41:48 +00004263 // Prepend object file path if -save-temps=obj
4264 if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
4265 JA.getType() != types::TY_PCH) {
4266 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
4267 SmallString<128> TempPath(FinalOutput->getValue());
4268 llvm::sys::path::remove_filename(TempPath);
4269 StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
4270 llvm::sys::path::append(TempPath, OutputFileName);
4271 NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
4272 }
4273
Chad Rosier62135492012-07-09 17:31:28 +00004274 // If we're saving temps and the temp file conflicts with the input file,
Chad Rosier5b58af02012-04-20 20:05:08 +00004275 // then avoid overwriting input file.
Reid Kleckner68eb60b2015-02-02 22:41:48 +00004276 if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
Chad Rosier5b58af02012-04-20 20:05:08 +00004277 bool SameFile = false;
4278 SmallString<256> Result;
4279 llvm::sys::fs::current_path(Result);
4280 llvm::sys::path::append(Result, BaseName);
4281 llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
4282 // Must share the same path to conflict.
4283 if (SameFile) {
4284 StringRef Name = llvm::sys::path::filename(BaseInput);
4285 std::pair<StringRef, StringRef> Split = Name.split('.');
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004286 std::string TmpName = GetTemporaryPath(
4287 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00004288 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
Chad Rosier5b58af02012-04-20 20:05:08 +00004289 }
Chad Rosierf8412cd2011-07-15 21:54:29 +00004290 }
4291
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00004292 // As an annoying special case, PCH generation doesn't strip the pathname.
Nico Weber8ab92192016-03-02 23:29:29 +00004293 if (JA.getType() == types::TY_PCH && !IsCLMode()) {
Michael J. Spencere1696752010-12-18 00:19:12 +00004294 llvm::sys::path::remove_filename(BasePath);
4295 if (BasePath.empty())
Daniel Dunbare6c83192009-03-18 09:58:30 +00004296 BasePath = NamedOutput;
4297 else
Michael J. Spencere1696752010-12-18 00:19:12 +00004298 llvm::sys::path::append(BasePath, NamedOutput);
Chad Rosier633dcdc2013-01-24 19:14:47 +00004299 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004300 } else {
Chad Rosier633dcdc2013-01-24 19:14:47 +00004301 return C.addResultFile(NamedOutput, &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004302 }
4303}
4304
Mehdi Amini12011172016-10-06 05:11:48 +00004305std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const {
Petr Hosek8f2499f2018-09-12 03:26:10 +00004306 // Seach for Name in a list of paths.
4307 auto SearchPaths = [&](const llvm::SmallVectorImpl<std::string> &P)
4308 -> llvm::Optional<std::string> {
4309 // Respect a limited subset of the '-Bprefix' functionality in GCC by
4310 // attempting to use this prefix when looking for file paths.
4311 for (const auto &Dir : P) {
4312 if (Dir.empty())
4313 continue;
4314 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
4315 llvm::sys::path::append(P, Name);
4316 if (llvm::sys::fs::exists(Twine(P)))
Simon Pilgrim4588fc82018-09-13 10:10:18 +00004317 return P.str().str();
Petr Hosek8f2499f2018-09-12 03:26:10 +00004318 }
4319 return None;
4320 };
4321
4322 if (auto P = SearchPaths(PrefixDirs))
4323 return *P;
Chandler Carruth84559242010-03-22 01:52:07 +00004324
Petr Hosek916a4672017-08-10 04:16:38 +00004325 SmallString<128> R(ResourceDir);
4326 llvm::sys::path::append(R, Name);
4327 if (llvm::sys::fs::exists(Twine(R)))
4328 return R.str();
4329
4330 SmallString<128> P(TC.getCompilerRTPath());
Rafael Espindola609a6642013-06-24 18:33:43 +00004331 llvm::sys::path::append(P, Name);
4332 if (llvm::sys::fs::exists(Twine(P)))
Peter Collingbournefa9771f2011-09-06 02:08:31 +00004333 return P.str();
4334
Petr Hosek8f2499f2018-09-12 03:26:10 +00004335 if (auto P = SearchPaths(TC.getLibraryPaths()))
4336 return *P;
4337
4338 if (auto P = SearchPaths(TC.getFilePaths()))
4339 return *P;
Daniel Dunbar68b01a02009-03-18 20:26:19 +00004340
Daniel Dunbar1ce81532009-09-09 22:33:00 +00004341 return Name;
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00004342}
4343
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004344void Driver::generatePrefixedToolNames(
Mehdi Amini12011172016-10-06 05:11:48 +00004345 StringRef Tool, const ToolChain &TC,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004346 SmallVectorImpl<std::string> &Names) const {
Petr Hosekdd38d932018-05-29 22:35:39 +00004347 // FIXME: Needs a better variable than TargetTriple
4348 Names.emplace_back((TargetTriple + "-" + Tool).str());
Benjamin Kramer3204b152015-05-29 19:42:19 +00004349 Names.emplace_back(Tool);
Vasileios Kalintirisc744e122015-11-12 15:26:54 +00004350
4351 // Allow the discovery of tools prefixed with LLVM's default target triple.
Petr Hosekdd38d932018-05-29 22:35:39 +00004352 std::string DefaultTargetTriple = llvm::sys::getDefaultTargetTriple();
4353 if (DefaultTargetTriple != TargetTriple)
4354 Names.emplace_back((DefaultTargetTriple + "-" + Tool).str());
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004355}
4356
Benjamin Kramer7111b912014-11-04 20:26:01 +00004357static bool ScanDirForExecutable(SmallString<128> &Dir,
4358 ArrayRef<std::string> Names) {
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004359 for (const auto &Name : Names) {
4360 llvm::sys::path::append(Dir, Name);
4361 if (llvm::sys::fs::can_execute(Twine(Dir)))
4362 return true;
4363 llvm::sys::path::remove_filename(Dir);
4364 }
4365 return false;
4366}
4367
Mehdi Amini12011172016-10-06 05:11:48 +00004368std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const {
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004369 SmallVector<std::string, 2> TargetSpecificExecutables;
4370 generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
4371
Chandler Carruth84559242010-03-22 01:52:07 +00004372 // Respect a limited subset of the '-Bprefix' functionality in GCC by
Logan Chiencd679fd2012-10-04 08:08:56 +00004373 // attempting to use this prefix when looking for program paths.
Saleem Abdulrasool23d99b12014-09-16 03:48:32 +00004374 for (const auto &PrefixDir : PrefixDirs) {
4375 if (llvm::sys::fs::is_directory(PrefixDir)) {
4376 SmallString<128> P(PrefixDir);
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004377 if (ScanDirForExecutable(P, TargetSpecificExecutables))
Rafael Espindola8be5c052013-06-19 13:24:29 +00004378 return P.str();
Simon Atanasyana47ba292012-10-31 14:39:28 +00004379 } else {
Mehdi Amini12011172016-10-06 05:11:48 +00004380 SmallString<128> P((PrefixDir + Name).str());
Rafael Espindola609a6642013-06-24 18:33:43 +00004381 if (llvm::sys::fs::can_execute(Twine(P)))
Rafael Espindola8be5c052013-06-19 13:24:29 +00004382 return P.str();
Simon Atanasyan86bdab72012-10-31 12:01:53 +00004383 }
Chandler Carruth84559242010-03-22 01:52:07 +00004384 }
4385
Daniel Dunbar68b01a02009-03-18 20:26:19 +00004386 const ToolChain::path_list &List = TC.getProgramPaths();
Saleem Abdulrasool23d99b12014-09-16 03:48:32 +00004387 for (const auto &Path : List) {
4388 SmallString<128> P(Path);
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004389 if (ScanDirForExecutable(P, TargetSpecificExecutables))
Rafael Espindola8be5c052013-06-19 13:24:29 +00004390 return P.str();
Daniel Dunbar68b01a02009-03-18 20:26:19 +00004391 }
4392
Daniel Dunbar76ce7412009-03-23 16:15:50 +00004393 // If all else failed, search the path.
Michael J. Spencerb011d482014-11-07 21:30:32 +00004394 for (const auto &TargetSpecificExecutable : TargetSpecificExecutables)
4395 if (llvm::ErrorOr<std::string> P =
4396 llvm::sys::findProgramByName(TargetSpecificExecutable))
Michael J. Spencer04162ea2014-11-04 01:30:55 +00004397 return *P;
Daniel Dunbar6f668772009-03-18 21:34:08 +00004398
Daniel Dunbar1ce81532009-09-09 22:33:00 +00004399 return Name;
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00004400}
4401
Mehdi Amini12011172016-10-06 05:11:48 +00004402std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const {
Rafael Espindola37d229d2013-06-25 04:26:55 +00004403 SmallString<128> Path;
Rafael Espindolac0809172014-06-12 14:02:15 +00004404 std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
Rafael Espindola37d229d2013-06-25 04:26:55 +00004405 if (EC) {
4406 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
Daniel Dunbare627c1c2009-03-18 19:34:39 +00004407 return "";
4408 }
4409
Rafael Espindola37d229d2013-06-25 04:26:55 +00004410 return Path.str();
Daniel Dunbare627c1c2009-03-18 19:34:39 +00004411}
4412
Nico Weber2ca4be92016-03-01 23:16:44 +00004413std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
4414 SmallString<128> Output;
4415 if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
4416 // FIXME: If anybody needs it, implement this obscure rule:
4417 // "If you specify a directory without a file name, the default file name
4418 // is VCx0.pch., where x is the major version of Visual C++ in use."
4419 Output = FpArg->getValue();
4420
4421 // "If you do not specify an extension as part of the path name, an
4422 // extension of .pch is assumed. "
4423 if (!llvm::sys::path::has_extension(Output))
4424 Output += ".pch";
4425 } else {
Mike Rice58df1af2018-09-11 17:10:44 +00004426 if (Arg *YcArg = C.getArgs().getLastArg(options::OPT__SLASH_Yc))
4427 Output = YcArg->getValue();
4428 if (Output.empty())
4429 Output = BaseName;
Nico Weber2ca4be92016-03-01 23:16:44 +00004430 llvm::sys::path::replace_extension(Output, ".pch");
4431 }
4432 return Output.str();
4433}
4434
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004435const ToolChain &Driver::getToolChain(const ArgList &Args,
Artem Belevich959e0542015-07-10 19:47:55 +00004436 const llvm::Triple &Target) const {
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004437
David Blaikie6ad71012017-01-13 18:53:43 +00004438 auto &TC = ToolChains[Target.str()];
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004439 if (!TC) {
4440 switch (Target.getOS()) {
Reid Kleckner330fb172016-05-11 16:19:05 +00004441 case llvm::Triple::Haiku:
David Blaikie6ad71012017-01-13 18:53:43 +00004442 TC = llvm::make_unique<toolchains::Haiku>(*this, Target, Args);
Reid Kleckner330fb172016-05-11 16:19:05 +00004443 break;
Ed Schouten4dabea22017-06-25 08:29:09 +00004444 case llvm::Triple::Ananas:
4445 TC = llvm::make_unique<toolchains::Ananas>(*this, Target, Args);
4446 break;
Ed Schouten3c3e58c2015-03-26 11:13:44 +00004447 case llvm::Triple::CloudABI:
David Blaikie6ad71012017-01-13 18:53:43 +00004448 TC = llvm::make_unique<toolchains::CloudABI>(*this, Target, Args);
Ed Schouten3c3e58c2015-03-26 11:13:44 +00004449 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004450 case llvm::Triple::Darwin:
4451 case llvm::Triple::MacOSX:
4452 case llvm::Triple::IOS:
Tim Northover6f3ff222015-10-30 16:30:27 +00004453 case llvm::Triple::TvOS:
4454 case llvm::Triple::WatchOS:
David Blaikie6ad71012017-01-13 18:53:43 +00004455 TC = llvm::make_unique<toolchains::DarwinClang>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004456 break;
4457 case llvm::Triple::DragonFly:
David Blaikie6ad71012017-01-13 18:53:43 +00004458 TC = llvm::make_unique<toolchains::DragonFly>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004459 break;
4460 case llvm::Triple::OpenBSD:
David Blaikie6ad71012017-01-13 18:53:43 +00004461 TC = llvm::make_unique<toolchains::OpenBSD>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004462 break;
4463 case llvm::Triple::NetBSD:
David Blaikie6ad71012017-01-13 18:53:43 +00004464 TC = llvm::make_unique<toolchains::NetBSD>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004465 break;
4466 case llvm::Triple::FreeBSD:
David Blaikie6ad71012017-01-13 18:53:43 +00004467 TC = llvm::make_unique<toolchains::FreeBSD>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004468 break;
4469 case llvm::Triple::Minix:
David Blaikie6ad71012017-01-13 18:53:43 +00004470 TC = llvm::make_unique<toolchains::Minix>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004471 break;
4472 case llvm::Triple::Linux:
Andrey Turetskiy4798eb62016-06-16 10:36:09 +00004473 case llvm::Triple::ELFIAMCU:
Chandler Carruthcf705b22012-01-25 21:03:58 +00004474 if (Target.getArch() == llvm::Triple::hexagon)
David Blaikie6ad71012017-01-13 18:53:43 +00004475 TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
4476 Args);
Vasileios Kalintirisc744e122015-11-12 15:26:54 +00004477 else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
4478 !Target.hasEnvironment())
David Blaikie6ad71012017-01-13 18:53:43 +00004479 TC = llvm::make_unique<toolchains::MipsLLVMToolChain>(*this, Target,
4480 Args);
Chandler Carruthcf705b22012-01-25 21:03:58 +00004481 else
David Blaikie6ad71012017-01-13 18:53:43 +00004482 TC = llvm::make_unique<toolchains::Linux>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004483 break;
Derek Schuff6ab52fa2015-03-30 20:31:33 +00004484 case llvm::Triple::NaCl:
David Blaikie6ad71012017-01-13 18:53:43 +00004485 TC = llvm::make_unique<toolchains::NaClToolChain>(*this, Target, Args);
Derek Schuff6ab52fa2015-03-30 20:31:33 +00004486 break;
Petr Hosek62e1d232016-10-06 06:08:09 +00004487 case llvm::Triple::Fuchsia:
David Blaikie6ad71012017-01-13 18:53:43 +00004488 TC = llvm::make_unique<toolchains::Fuchsia>(*this, Target, Args);
Petr Hosek62e1d232016-10-06 06:08:09 +00004489 break;
David Chisnallf571cde2012-02-15 13:39:01 +00004490 case llvm::Triple::Solaris:
David Blaikie6ad71012017-01-13 18:53:43 +00004491 TC = llvm::make_unique<toolchains::Solaris>(*this, Target, Args);
David Chisnallf571cde2012-02-15 13:39:01 +00004492 break;
Tom Stellard8fa33092015-07-18 01:49:05 +00004493 case llvm::Triple::AMDHSA:
David Blaikie6ad71012017-01-13 18:53:43 +00004494 TC = llvm::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args);
Tom Stellard8fa33092015-07-18 01:49:05 +00004495 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004496 case llvm::Triple::Win32:
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004497 switch (Target.getEnvironment()) {
4498 default:
4499 if (Target.isOSBinFormatELF())
David Blaikie6ad71012017-01-13 18:53:43 +00004500 TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004501 else if (Target.isOSBinFormatMachO())
David Blaikie6ad71012017-01-13 18:53:43 +00004502 TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004503 else
David Blaikie6ad71012017-01-13 18:53:43 +00004504 TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004505 break;
4506 case llvm::Triple::GNU:
David Blaikie6ad71012017-01-13 18:53:43 +00004507 TC = llvm::make_unique<toolchains::MinGW>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004508 break;
Saleem Abdulrasool543a78b2014-10-24 03:13:37 +00004509 case llvm::Triple::Itanium:
David Blaikie6ad71012017-01-13 18:53:43 +00004510 TC = llvm::make_unique<toolchains::CrossWindowsToolChain>(*this, Target,
4511 Args);
Saleem Abdulrasool543a78b2014-10-24 03:13:37 +00004512 break;
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004513 case llvm::Triple::MSVC:
4514 case llvm::Triple::UnknownEnvironment:
Dave Leef96bedf2017-11-06 21:18:05 +00004515 if (Args.getLastArgValue(options::OPT_fuse_ld_EQ)
4516 .startswith_lower("bfd"))
4517 TC = llvm::make_unique<toolchains::CrossWindowsToolChain>(
4518 *this, Target, Args);
4519 else
4520 TC =
4521 llvm::make_unique<toolchains::MSVCToolChain>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004522 break;
4523 }
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004524 break;
Filipe Cabecinhasc888e192015-10-14 12:25:43 +00004525 case llvm::Triple::PS4:
David Blaikie6ad71012017-01-13 18:53:43 +00004526 TC = llvm::make_unique<toolchains::PS4CPU>(*this, Target, Args);
Filipe Cabecinhasc888e192015-10-14 12:25:43 +00004527 break;
David L Kreitzerd397ea42016-10-14 20:44:33 +00004528 case llvm::Triple::Contiki:
David Blaikie6ad71012017-01-13 18:53:43 +00004529 TC = llvm::make_unique<toolchains::Contiki>(*this, Target, Args);
David L Kreitzerd397ea42016-10-14 20:44:33 +00004530 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004531 default:
Douglas Katzman9f5e70e2015-05-26 18:01:33 +00004532 // Of these targets, Hexagon is the only one that might have
4533 // an OS of Linux, in which case it got handled above already.
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004534 switch (Target.getArch()) {
4535 case llvm::Triple::tce:
David Blaikie6ad71012017-01-13 18:53:43 +00004536 TC = llvm::make_unique<toolchains::TCEToolChain>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004537 break;
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00004538 case llvm::Triple::tcele:
David Blaikie6ad71012017-01-13 18:53:43 +00004539 TC = llvm::make_unique<toolchains::TCELEToolChain>(*this, Target, Args);
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00004540 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004541 case llvm::Triple::hexagon:
David Blaikie6ad71012017-01-13 18:53:43 +00004542 TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
4543 Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004544 break;
Jacques Pienaard964cc22016-03-28 21:02:54 +00004545 case llvm::Triple::lanai:
David Blaikie6ad71012017-01-13 18:53:43 +00004546 TC = llvm::make_unique<toolchains::LanaiToolChain>(*this, Target, Args);
Jacques Pienaard964cc22016-03-28 21:02:54 +00004547 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004548 case llvm::Triple::xcore:
David Blaikie6ad71012017-01-13 18:53:43 +00004549 TC = llvm::make_unique<toolchains::XCoreToolChain>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004550 break;
Dan Gohmanc2853072015-09-03 22:51:53 +00004551 case llvm::Triple::wasm32:
4552 case llvm::Triple::wasm64:
David Blaikie6ad71012017-01-13 18:53:43 +00004553 TC = llvm::make_unique<toolchains::WebAssembly>(*this, Target, Args);
Dan Gohmanc2853072015-09-03 22:51:53 +00004554 break;
Dylan McKay924fa3a2017-01-05 05:20:27 +00004555 case llvm::Triple::avr:
David Blaikie6ad71012017-01-13 18:53:43 +00004556 TC = llvm::make_unique<toolchains::AVRToolChain>(*this, Target, Args);
Dylan McKay924fa3a2017-01-05 05:20:27 +00004557 break;
David Bolvanskyf4be2532018-07-31 14:21:46 +00004558 case llvm::Triple::riscv32:
4559 case llvm::Triple::riscv64:
4560 TC = llvm::make_unique<toolchains::RISCVToolChain>(*this, Target, Args);
4561 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004562 default:
Douglas Katzmand6e597c2015-09-17 19:56:40 +00004563 if (Target.getVendor() == llvm::Triple::Myriad)
David Blaikie6ad71012017-01-13 18:53:43 +00004564 TC = llvm::make_unique<toolchains::MyriadToolChain>(*this, Target,
4565 Args);
Jonathan Roelofs901c7762017-05-25 15:42:13 +00004566 else if (toolchains::BareMetal::handlesTarget(Target))
4567 TC = llvm::make_unique<toolchains::BareMetal>(*this, Target, Args);
Douglas Katzmand6e597c2015-09-17 19:56:40 +00004568 else if (Target.isOSBinFormatELF())
David Blaikie6ad71012017-01-13 18:53:43 +00004569 TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004570 else if (Target.isOSBinFormatMachO())
David Blaikie6ad71012017-01-13 18:53:43 +00004571 TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004572 else
David Blaikie6ad71012017-01-13 18:53:43 +00004573 TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004574 }
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004575 }
4576 }
Justin Lebar66c4fd72016-11-18 00:41:22 +00004577
4578 // Intentionally omitted from the switch above: llvm::Triple::CUDA. CUDA
4579 // compiles always need two toolchains, the CUDA toolchain and the host
4580 // toolchain. So the only valid way to create a CUDA toolchain is via
4581 // CreateOffloadingDeviceToolChains.
4582
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004583 return *TC;
Daniel Dunbar4dff6a42009-03-10 23:41:59 +00004584}
Daniel Dunbar8fa879d2009-03-24 18:57:02 +00004585
Rafael Espindola2f69d402013-03-18 15:33:26 +00004586bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
Douglas Katzman00249092015-06-12 15:45:21 +00004587 // Say "no" if there is not exactly one input of a type clang understands.
Nico Weber5a459f82016-02-23 19:30:43 +00004588 if (JA.size() != 1 ||
4589 !types::isAcceptedByClang((*JA.input_begin())->getType()))
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00004590 return false;
4591
Douglas Katzman00249092015-06-12 15:45:21 +00004592 // And say "no" if this is not a kind of action clang understands.
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00004593 if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
Bob Wilson23a55f12014-12-21 07:00:00 +00004594 !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00004595 return false;
4596
4597 return true;
4598}
4599
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00004600/// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
4601/// grouped values as integers. Numbers which are not provided are set to 0.
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004602///
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00004603/// \return True if the entire string was parsed (9.2), or all groups were
4604/// parsed (10.3.5extrastuff).
Mehdi Amini12011172016-10-06 05:11:48 +00004605bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
4606 unsigned &Micro, bool &HadExtra) {
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004607 HadExtra = false;
4608
4609 Major = Minor = Micro = 0;
Mehdi Amini12011172016-10-06 05:11:48 +00004610 if (Str.empty())
Bob Wilson433cb312015-04-07 01:03:35 +00004611 return false;
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004612
Mehdi Amini12011172016-10-06 05:11:48 +00004613 if (Str.consumeInteger(10, Major))
4614 return false;
4615 if (Str.empty())
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004616 return true;
Mehdi Amini12011172016-10-06 05:11:48 +00004617 if (Str[0] != '.')
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004618 return false;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00004619
Mehdi Amini12011172016-10-06 05:11:48 +00004620 Str = Str.drop_front(1);
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004621
Mehdi Amini12011172016-10-06 05:11:48 +00004622 if (Str.consumeInteger(10, Minor))
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004623 return false;
Mehdi Amini12011172016-10-06 05:11:48 +00004624 if (Str.empty())
4625 return true;
4626 if (Str[0] != '.')
4627 return false;
4628 Str = Str.drop_front(1);
4629
4630 if (Str.consumeInteger(10, Micro))
4631 return false;
4632 if (!Str.empty())
4633 HadExtra = true;
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004634 return true;
4635}
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004636
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004637/// Parse digits from a string \p Str and fulfill \p Digits with
4638/// the parsed numbers. This method assumes that the max number of
4639/// digits to look for is equal to Digits.size().
4640///
4641/// \return True if the entire string was parsed and there are
4642/// no extra characters remaining at the end.
Mehdi Amini12011172016-10-06 05:11:48 +00004643bool Driver::GetReleaseVersion(StringRef Str,
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004644 MutableArrayRef<unsigned> Digits) {
Mehdi Amini12011172016-10-06 05:11:48 +00004645 if (Str.empty())
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004646 return false;
4647
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004648 unsigned CurDigit = 0;
4649 while (CurDigit < Digits.size()) {
Mehdi Amini12011172016-10-06 05:11:48 +00004650 unsigned Digit;
4651 if (Str.consumeInteger(10, Digit))
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004652 return false;
Mehdi Amini12011172016-10-06 05:11:48 +00004653 Digits[CurDigit] = Digit;
4654 if (Str.empty())
4655 return true;
4656 if (Str[0] != '.')
4657 return false;
4658 Str = Str.drop_front(1);
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004659 CurDigit++;
4660 }
4661
4662 // More digits than requested, bail out...
4663 return false;
4664}
4665
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004666std::pair<unsigned, unsigned> Driver::getIncludeExcludeOptionFlagMasks() const {
4667 unsigned IncludedFlagsBitmask = 0;
Rafael Espindolacc707bc2013-09-25 15:54:41 +00004668 unsigned ExcludedFlagsBitmask = options::NoDriverOption;
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004669
4670 if (Mode == CLMode) {
Hans Wennborg19076102013-07-31 20:51:53 +00004671 // Include CL and Core options.
4672 IncludedFlagsBitmask |= options::CLOption;
4673 IncludedFlagsBitmask |= options::CoreOption;
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004674 } else {
4675 ExcludedFlagsBitmask |= options::CLOption;
4676 }
4677
4678 return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
4679}
Benjamin Kramerab88f622014-03-25 18:02:07 +00004680
Douglas Katzmanf08fadf2015-06-04 14:40:44 +00004681bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
Benjamin Kramerab88f622014-03-25 18:02:07 +00004682 return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);
4683}