blob: eb03e6e87cc02ccca3c5a287aa8a3c1403c03fa0 [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Daniel Dunbar544ecd12009-03-02 19:59:07 +00006//
7//===----------------------------------------------------------------------===//
8
Daniel Dunbar544ecd12009-03-02 19:59:07 +00009#include "clang/Driver/Driver.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000010#include "InputInfo.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000011#include "ToolChains/AMDGPU.h"
12#include "ToolChains/AVR.h"
Ed Schouten4dabea22017-06-25 08:29:09 +000013#include "ToolChains/Ananas.h"
Yaxun Liuf6144222018-05-30 00:53:50 +000014#include "ToolChains/BareMetal.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000015#include "ToolChains/Clang.h"
16#include "ToolChains/CloudABI.h"
17#include "ToolChains/Contiki.h"
18#include "ToolChains/CrossWindows.h"
19#include "ToolChains/Cuda.h"
20#include "ToolChains/Darwin.h"
21#include "ToolChains/DragonFly.h"
22#include "ToolChains/FreeBSD.h"
23#include "ToolChains/Fuchsia.h"
24#include "ToolChains/Gnu.h"
Yaxun Liuf6144222018-05-30 00:53:50 +000025#include "ToolChains/HIP.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000026#include "ToolChains/Haiku.h"
27#include "ToolChains/Hexagon.h"
Kristina Brooks77a4adc2018-11-29 03:49:14 +000028#include "ToolChains/Hurd.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000029#include "ToolChains/Lanai.h"
30#include "ToolChains/Linux.h"
Anton Korobeynikov93165d62019-01-15 19:44:05 +000031#include "ToolChains/MSP430.h"
Yaxun Liuf6144222018-05-30 00:53:50 +000032#include "ToolChains/MSVC.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000033#include "ToolChains/MinGW.h"
34#include "ToolChains/Minix.h"
Konstantin Zhuravlyove37b32c2017-03-08 22:36:04 +000035#include "ToolChains/MipsLinux.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000036#include "ToolChains/Myriad.h"
37#include "ToolChains/NaCl.h"
38#include "ToolChains/NetBSD.h"
39#include "ToolChains/OpenBSD.h"
40#include "ToolChains/PS4CPU.h"
Erik Pilkington46420b62018-09-27 20:36:28 +000041#include "ToolChains/RISCVToolchain.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000042#include "ToolChains/Solaris.h"
43#include "ToolChains/TCE.h"
44#include "ToolChains/WebAssembly.h"
45#include "ToolChains/XCore.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000046#include "clang/Basic/Version.h"
Alp Toker1d257e12014-06-04 03:28:55 +000047#include "clang/Config/config.h"
Daniel Dunbar1688f1a2009-03-12 07:58:46 +000048#include "clang/Driver/Action.h"
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000049#include "clang/Driver/Compilation.h"
Daniel Dunbarc0b3e952009-03-12 08:55:43 +000050#include "clang/Driver/DriverDiagnostic.h"
Daniel Dunbare75d8342009-03-16 06:56:51 +000051#include "clang/Driver/Job.h"
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000052#include "clang/Driver/Options.h"
Peter Collingbournea4ccff32015-02-20 20:30:56 +000053#include "clang/Driver/SanitizerArgs.h"
Daniel Dunbare75d8342009-03-16 06:56:51 +000054#include "clang/Driver/Tool.h"
55#include "clang/Driver/ToolChain.h"
Chris Lattnerce6c42f2011-03-23 04:04:01 +000056#include "llvm/ADT/ArrayRef.h"
Hans Wennborg6ddc6902013-07-27 00:23:45 +000057#include "llvm/ADT/STLExtras.h"
Justin Lebar62907612016-07-06 21:21:39 +000058#include "llvm/ADT/SmallSet.h"
Hans Wennborg23d26a32014-06-18 17:21:50 +000059#include "llvm/ADT/StringExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000060#include "llvm/ADT/StringSet.h"
Hans Wennborg70850d82013-07-18 20:29:38 +000061#include "llvm/ADT/StringSwitch.h"
Nico Weberd637c052018-04-30 13:52:15 +000062#include "llvm/Config/llvm-config.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000063#include "llvm/Option/Arg.h"
64#include "llvm/Option/ArgList.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000065#include "llvm/Option/OptSpecifier.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000066#include "llvm/Option/OptTable.h"
67#include "llvm/Option/Option.h"
Serge Pavlov208ac652018-01-01 13:27:01 +000068#include "llvm/Support/CommandLine.h"
David Blaikie79000202011-09-23 05:57:42 +000069#include "llvm/Support/ErrorHandling.h"
Michael J. Spencerf28df4c2010-12-17 21:22:22 +000070#include "llvm/Support/FileSystem.h"
Fangrui Songd0028232018-10-10 00:15:33 +000071#include "llvm/Support/FormatVariadic.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000072#include "llvm/Support/Path.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000073#include "llvm/Support/PrettyStackTrace.h"
Hans Wennborg23d26a32014-06-18 17:21:50 +000074#include "llvm/Support/Process.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000075#include "llvm/Support/Program.h"
Yaxun Liuf6144222018-05-30 00:53:50 +000076#include "llvm/Support/StringSaver.h"
Dimitry Andric81c40422017-06-06 21:54:21 +000077#include "llvm/Support/TargetRegistry.h"
Jonas Devliegherefc514902018-10-10 13:27:25 +000078#include "llvm/Support/VirtualFileSystem.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000079#include "llvm/Support/raw_ostream.h"
Dylan Noblesmith4f4e7452012-02-02 00:40:14 +000080#include <map>
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000081#include <memory>
Benjamin Kramercfeacf52016-05-27 14:27:13 +000082#include <utility>
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +000083#if LLVM_ON_UNIX
84#include <unistd.h> // getpid
Nick Desaulniers9d0df312018-10-15 17:39:00 +000085#include <sysexits.h> // EX_IOERR
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +000086#endif
Dylan Noblesmith86780e92012-02-01 14:25:28 +000087
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000088using namespace clang::driver;
Chris Lattnerada1c912009-03-26 05:56:24 +000089using namespace clang;
Reid Kleckner898229a2013-06-14 17:17:23 +000090using namespace llvm::opt;
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000091
Nico Weber0abcafd2019-01-31 22:15:32 +000092// static
93std::string Driver::GetResourcesPath(StringRef BinaryPath,
94 StringRef CustomResourceDir) {
95 // Since the resource directory is embedded in the module hash, it's important
96 // that all places that need it call this function, so that they get the
97 // exact same string ("a/../b/" and "b/" get different hashes, for example).
98
99 // Dir is bin/ or lib/, depending on where BinaryPath is.
100 std::string Dir = llvm::sys::path::parent_path(BinaryPath);
101
102 SmallString<128> P(Dir);
103 if (CustomResourceDir != "") {
104 llvm::sys::path::append(P, CustomResourceDir);
105 } else {
106 // On Windows, libclang.dll is in bin/.
107 // On non-Windows, libclang.so/.dylib is in lib/.
108 // With a static-library build of libclang, LibClangPath will contain the
109 // path of the embedding binary, which for LLVM binaries will be in bin/.
110 // ../lib gets us to lib/ in both cases.
111 P = llvm::sys::path::parent_path(Dir);
112 llvm::sys::path::append(P, Twine("lib") + CLANG_LIBDIR_SUFFIX, "clang",
113 CLANG_VERSION_STRING);
114 }
115
116 return P.str();
117}
118
Petr Hosekdd38d932018-05-29 22:35:39 +0000119Driver::Driver(StringRef ClangExecutable, StringRef TargetTriple,
Benjamin Kramerd45b2052015-10-07 15:48:01 +0000120 DiagnosticsEngine &Diags,
Jonas Devliegherefc514902018-10-10 13:27:25 +0000121 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)
Benjamin Kramercfeacf52016-05-27 14:27:13 +0000122 : Opts(createDriverOptTable()), Diags(Diags), VFS(std::move(VFS)),
123 Mode(GCCMode), SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
124 LTOMode(LTOK_None), ClangExecutable(ClangExecutable),
Alex Lorenz045c5142018-04-07 00:03:27 +0000125 SysRoot(DEFAULT_SYSROOT), DriverTitle("clang LLVM compiler"),
126 CCPrintOptionsFilename(nullptr), CCPrintHeadersFilename(nullptr),
127 CCLogDiagnosticsFilename(nullptr), CCCPrintBindings(false),
128 CCPrintOptions(false), CCPrintHeaders(false), CCLogDiagnostics(false),
Petr Hosekdd38d932018-05-29 22:35:39 +0000129 CCGenDiagnostics(false), TargetTriple(TargetTriple),
Alex Lorenz045c5142018-04-07 00:03:27 +0000130 CCCGenericGCCName(""), Saver(Alloc), CheckInputsExist(true),
Erich Keane0a6b5b62018-12-04 14:34:09 +0000131 GenReproducer(false), SuppressMissingInputWarning(false) {
Daniel Dunbar3f3e2cd2010-01-20 02:35:16 +0000132
Benjamin Kramerd45b2052015-10-07 15:48:01 +0000133 // Provide a sane fallback if no VFS is specified.
134 if (!this->VFS)
Jonas Devliegherefc514902018-10-10 13:27:25 +0000135 this->VFS = llvm::vfs::getRealFileSystem();
Benjamin Kramerd45b2052015-10-07 15:48:01 +0000136
Sumanth Gundapaneni3a1592942015-03-03 20:43:12 +0000137 Name = llvm::sys::path::filename(ClangExecutable);
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000138 Dir = llvm::sys::path::parent_path(ClangExecutable);
Benjamin Kramerf420dda2015-10-13 15:19:32 +0000139 InstalledDir = Dir; // Provide a sensible default installed dir.
Bob Wilsona20a1da2013-03-23 05:17:59 +0000140
Serge Pavlov208ac652018-01-01 13:27:01 +0000141#if defined(CLANG_CONFIG_FILE_SYSTEM_DIR)
142 SystemConfigDir = CLANG_CONFIG_FILE_SYSTEM_DIR;
143#endif
144#if defined(CLANG_CONFIG_FILE_USER_DIR)
145 UserConfigDir = CLANG_CONFIG_FILE_USER_DIR;
146#endif
147
Bob Wilsona20a1da2013-03-23 05:17:59 +0000148 // Compute the path to the resource directory.
Nico Weber0abcafd2019-01-31 22:15:32 +0000149 ResourceDir = GetResourcesPath(ClangExecutable, CLANG_RESOURCE_DIR);
Daniel Dunbar544ecd12009-03-02 19:59:07 +0000150}
151
Zachary Turneraff19c32016-08-12 17:47:52 +0000152void Driver::ParseDriverMode(StringRef ProgramName,
153 ArrayRef<const char *> Args) {
Martin Storsjo1fab23d2018-04-25 21:23:59 +0000154 if (ClangNameParts.isEmpty())
155 ClangNameParts = ToolChain::getTargetAndModeFromProgramName(ProgramName);
Serge Pavlov4e769842017-08-29 05:22:26 +0000156 setDriverModeFromOption(ClangNameParts.DriverMode);
Hans Wennborg70850d82013-07-18 20:29:38 +0000157
Douglas Katzman6bbffc42015-06-25 18:51:37 +0000158 for (const char *ArgPtr : Args) {
Erich Keane258f0592018-02-07 00:19:58 +0000159 // Ignore nullptrs, they are the response file's EOL markers.
Douglas Katzman6bbffc42015-06-25 18:51:37 +0000160 if (ArgPtr == nullptr)
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000161 continue;
Douglas Katzman6bbffc42015-06-25 18:51:37 +0000162 const StringRef Arg = ArgPtr;
Zachary Turneraff19c32016-08-12 17:47:52 +0000163 setDriverModeFromOption(Arg);
Hans Wennborg70850d82013-07-18 20:29:38 +0000164 }
165}
166
Zachary Turneraff19c32016-08-12 17:47:52 +0000167void Driver::setDriverModeFromOption(StringRef Opt) {
168 const std::string OptName =
169 getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
170 if (!Opt.startswith(OptName))
171 return;
172 StringRef Value = Opt.drop_front(OptName.size());
173
Erich Keane2908a042018-02-12 17:47:01 +0000174 if (auto M = llvm::StringSwitch<llvm::Optional<DriverMode>>(Value)
175 .Case("gcc", GCCMode)
176 .Case("g++", GXXMode)
177 .Case("cpp", CPPMode)
178 .Case("cl", CLMode)
179 .Default(None))
180 Mode = *M;
Zachary Turneraff19c32016-08-12 17:47:52 +0000181 else
182 Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
183}
184
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000185InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings,
Hans Wennborg797004d2018-11-08 11:27:04 +0000186 bool IsClCompatMode,
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000187 bool &ContainsError) {
Daniel Dunbar2608c542009-03-18 01:38:48 +0000188 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000189 ContainsError = false;
Hans Wennborg6ddc6902013-07-27 00:23:45 +0000190
191 unsigned IncludedFlagsBitmask;
192 unsigned ExcludedFlagsBitmask;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000193 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
Hans Wennborg797004d2018-11-08 11:27:04 +0000194 getIncludeExcludeOptionFlagMasks(IsClCompatMode);
Hans Wennborg6ddc6902013-07-27 00:23:45 +0000195
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000196 unsigned MissingArgIndex, MissingArgCount;
David Blaikie69a1d8c2015-06-22 22:07:27 +0000197 InputArgList Args =
David Blaikie6d492ad2015-06-21 06:32:36 +0000198 getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
199 IncludedFlagsBitmask, ExcludedFlagsBitmask);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +0000200
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000201 // Check for missing argument error.
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000202 if (MissingArgCount) {
203 Diag(diag::err_drv_missing_argument)
David Blaikie69a1d8c2015-06-22 22:07:27 +0000204 << Args.getArgString(MissingArgIndex) << MissingArgCount;
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000205 ContainsError |=
206 Diags.getDiagnosticLevel(diag::err_drv_missing_argument,
207 SourceLocation()) > DiagnosticsEngine::Warning;
208 }
Daniel Dunbar65229332009-03-13 11:38:42 +0000209
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000210 // Check for unsupported options.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000211 for (const Arg *A : Args) {
Michael J. Spencer66e2b202012-10-19 22:37:06 +0000212 if (A->getOption().hasFlag(options::Unsupported)) {
Brian Gesiak24910762018-01-06 00:25:40 +0000213 unsigned DiagID;
214 auto ArgString = A->getAsString(Args);
215 std::string Nearest;
216 if (getOpts().findNearest(
217 ArgString, Nearest, IncludedFlagsBitmask,
218 ExcludedFlagsBitmask | options::Unsupported) > 1) {
219 DiagID = diag::err_drv_unsupported_opt;
220 Diag(DiagID) << ArgString;
221 } else {
222 DiagID = diag::err_drv_unsupported_opt_with_suggestion;
223 Diag(DiagID) << ArgString << Nearest;
224 }
225 ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000226 DiagnosticsEngine::Warning;
Daniel Dunbard8500f32009-03-22 23:26:43 +0000227 continue;
228 }
Chad Rosierce975d92012-02-22 17:55:22 +0000229
230 // Warn about -mcpu= without an argument.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000231 if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000232 Diag(diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
233 ContainsError |= Diags.getDiagnosticLevel(
234 diag::warn_drv_empty_joined_argument,
235 SourceLocation()) > DiagnosticsEngine::Warning;
Chad Rosierce975d92012-02-22 17:55:22 +0000236 }
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000237 }
238
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000239 for (const Arg *A : Args.filtered(options::OPT_UNKNOWN)) {
Brian Gesiak24910762018-01-06 00:25:40 +0000240 unsigned DiagID;
241 auto ArgString = A->getAsString(Args);
242 std::string Nearest;
243 if (getOpts().findNearest(
244 ArgString, Nearest, IncludedFlagsBitmask, ExcludedFlagsBitmask) > 1) {
245 DiagID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl
246 : diag::err_drv_unknown_argument;
247 Diags.Report(DiagID) << ArgString;
248 } else {
249 DiagID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl_with_suggestion
250 : diag::err_drv_unknown_argument_with_suggestion;
251 Diags.Report(DiagID) << ArgString << Nearest;
252 }
253 ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000254 DiagnosticsEngine::Warning;
255 }
Rafael Espindola8a2d4962013-09-23 23:55:25 +0000256
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000257 return Args;
258}
259
Chad Rosier7742b5d2011-07-27 23:36:45 +0000260// Determine which compilation mode we are in. We look for options which
261// affect the phase, starting with the earliest phases, and record which
262// option we used to determine the final phase.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000263phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
264 Arg **FinalPhaseArg) const {
Craig Topper92fc2df2014-05-17 16:56:41 +0000265 Arg *PhaseArg = nullptr;
Chad Rosier7742b5d2011-07-27 23:36:45 +0000266 phases::ID FinalPhase;
Eric Christopherf901e852011-08-17 22:59:59 +0000267
Hans Wennborge50cec32014-06-13 20:59:54 +0000268 // -{E,EP,P,M,MM} only run the preprocessor.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000269 if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
Hans Wennborge50cec32014-06-13 20:59:54 +0000270 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
Hans Wennborge0053472013-12-20 18:40:46 +0000271 (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
272 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000273 FinalPhase = phases::Preprocess;
Eric Christopherf901e852011-08-17 22:59:59 +0000274
Richard Smithdd4ad3d2016-08-30 19:06:26 +0000275 // --precompile only runs up to precompilation.
276 } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile))) {
277 FinalPhase = phases::Precompile;
278
Bob Wilson23a55f12014-12-21 07:00:00 +0000279 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
Chad Rosier7742b5d2011-07-27 23:36:45 +0000280 } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000281 (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
Ben Langmuir2cb4a782014-02-05 22:21:15 +0000282 (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
Chad Rosier7742b5d2011-07-27 23:36:45 +0000283 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
Fariborz Jahanian73223bb2012-04-02 15:59:19 +0000284 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
Ted Kremenekf7639e12012-03-06 20:06:33 +0000285 (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
Chad Rosier7742b5d2011-07-27 23:36:45 +0000286 (PhaseArg = DAL.getLastArg(options::OPT__analyze,
Chad Rosier1aeb15a2012-03-06 23:14:35 +0000287 options::OPT__analyze_auto)) ||
Bob Wilson23a55f12014-12-21 07:00:00 +0000288 (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000289 FinalPhase = phases::Compile;
290
Bob Wilson23a55f12014-12-21 07:00:00 +0000291 // -S only runs up to the backend.
292 } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
293 FinalPhase = phases::Backend;
294
Artem Belevich4242f412015-07-28 21:01:21 +0000295 // -c compilation only runs up to the assembler.
296 } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000297 FinalPhase = phases::Assemble;
298
299 // Otherwise do everything.
300 } else
301 FinalPhase = phases::Link;
302
303 if (FinalPhaseArg)
304 *FinalPhaseArg = PhaseArg;
305
306 return FinalPhase;
307}
308
David Blaikie0aaa7622017-01-13 17:34:15 +0000309static Arg *MakeInputArg(DerivedArgList &Args, OptTable &Opts,
Martin Storsjo665c7a42018-05-04 06:05:58 +0000310 StringRef Value, bool Claim = true) {
David Blaikie0aaa7622017-01-13 17:34:15 +0000311 Arg *A = new Arg(Opts.getOption(options::OPT_INPUT), Value,
Hans Wennborged1d0722013-08-13 21:32:29 +0000312 Args.getBaseArgs().MakeIndex(Value), Value.data());
Hans Wennborg55362852014-05-02 22:55:30 +0000313 Args.AddSynthesizedArg(A);
Martin Storsjo665c7a42018-05-04 06:05:58 +0000314 if (Claim)
315 A->claim();
Hans Wennborged1d0722013-08-13 21:32:29 +0000316 return A;
317}
318
Daniel Dunbar775d4062010-06-11 22:00:26 +0000319DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
320 DerivedArgList *DAL = new DerivedArgList(Args);
321
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000322 bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
Dan Albertf5ffa1a2018-12-18 23:29:35 +0000323 bool HasNostdlibxx = Args.hasArg(options::OPT_nostdlibxx);
Nirav Daveb0bb6142015-11-24 16:07:21 +0000324 bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +0000325 for (Arg *A : Args) {
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000326 // Unfortunately, we have to parse some forwarding options (-Xassembler,
327 // -Xlinker, -Xpreprocessor) because we either integrate their functionality
328 // (assembler and preprocessor), or bypass a previous driver ('collect2').
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000329
330 // Rewrite linker options, to replace --no-demangle with a custom internal
331 // option.
332 if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
333 A->getOption().matches(options::OPT_Xlinker)) &&
334 A->containsValue("--no-demangle")) {
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000335 // Add the rewritten no-demangle argument.
336 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
337
338 // Add the remaining values as Xlinker arguments.
Benjamin Kramer72e64312015-09-24 14:48:49 +0000339 for (StringRef Val : A->getValues())
Douglas Katzmana34b7bf2015-06-30 19:32:57 +0000340 if (Val != "--no-demangle")
341 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), Val);
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000342
343 continue;
344 }
345
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000346 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
347 // some build systems. We don't try to be complete here because we don't
348 // care to encourage this usage model.
349 if (A->getOption().matches(options::OPT_Wp_COMMA) &&
Richard Smithbd55daf2012-11-01 04:30:05 +0000350 (A->getValue(0) == StringRef("-MD") ||
351 A->getValue(0) == StringRef("-MMD"))) {
Daniel Dunbar3648ba72010-06-15 20:30:18 +0000352 // Rewrite to -MD/-MMD along with -MF.
Richard Smithbd55daf2012-11-01 04:30:05 +0000353 if (A->getValue(0) == StringRef("-MD"))
Daniel Dunbar3648ba72010-06-15 20:30:18 +0000354 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
355 else
356 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
Michael J. Spencer70d85be2012-11-07 23:37:14 +0000357 if (A->getNumValues() == 2)
358 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
359 A->getValue(1));
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000360 continue;
361 }
362
Shantonu Senafeb03b2010-09-17 18:39:08 +0000363 // Rewrite reserved library names.
364 if (A->getOption().matches(options::OPT_l)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000365 StringRef Value = A->getValue();
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000366
Shantonu Senafeb03b2010-09-17 18:39:08 +0000367 // Rewrite unless -nostdlib is present.
Dan Albertf5ffa1a2018-12-18 23:29:35 +0000368 if (!HasNostdlib && !HasNodefaultlib && !HasNostdlibxx &&
369 Value == "stdc++") {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000370 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_stdcxx));
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000371 continue;
372 }
Shantonu Senafeb03b2010-09-17 18:39:08 +0000373
374 // Rewrite unconditionally.
375 if (Value == "cc_kext") {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000376 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_cckext));
Shantonu Senafeb03b2010-09-17 18:39:08 +0000377 continue;
378 }
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000379 }
380
Hans Wennborged1d0722013-08-13 21:32:29 +0000381 // Pick up inputs via the -- option.
382 if (A->getOption().matches(options::OPT__DASH_DASH)) {
383 A->claim();
Benjamin Kramer72e64312015-09-24 14:48:49 +0000384 for (StringRef Val : A->getValues())
Martin Storsjo665c7a42018-05-04 06:05:58 +0000385 DAL->append(MakeInputArg(*DAL, *Opts, Val, false));
Hans Wennborged1d0722013-08-13 21:32:29 +0000386 continue;
387 }
388
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +0000389 DAL->append(A);
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000390 }
Daniel Dunbar775d4062010-06-11 22:00:26 +0000391
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000392 // Enforce -static if -miamcu is present.
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000393 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false))
394 DAL->AddFlagArg(0, Opts->getOption(options::OPT_static));
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000395
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000396// Add a default value of -mlinker-version=, if one was given and the user
397// didn't specify one.
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000398#if defined(HOST_LINK_VERSION)
Tim Northover018578c2015-06-12 19:21:35 +0000399 if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
400 strlen(HOST_LINK_VERSION) > 0) {
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000401 DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
402 HOST_LINK_VERSION);
Daniel Dunbarb613ffc2010-08-17 22:32:45 +0000403 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000404 }
405#endif
406
Daniel Dunbar775d4062010-06-11 22:00:26 +0000407 return DAL;
408}
409
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000410/// Compute target triple from args.
Artem Belevich959e0542015-07-10 19:47:55 +0000411///
412/// This routine provides the logic to compute a target triple from various
413/// args passed to the driver and the default triple string.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000414static llvm::Triple computeTargetTriple(const Driver &D,
Petr Hosekdd38d932018-05-29 22:35:39 +0000415 StringRef TargetTriple,
Artem Belevich959e0542015-07-10 19:47:55 +0000416 const ArgList &Args,
417 StringRef DarwinArchName = "") {
418 // FIXME: Already done in Compilation *Driver::BuildCompilation
419 if (const Arg *A = Args.getLastArg(options::OPT_target))
Petr Hosekdd38d932018-05-29 22:35:39 +0000420 TargetTriple = A->getValue();
Artem Belevich959e0542015-07-10 19:47:55 +0000421
Petr Hosekdd38d932018-05-29 22:35:39 +0000422 llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
Artem Belevich959e0542015-07-10 19:47:55 +0000423
Kristina Brooks77a4adc2018-11-29 03:49:14 +0000424 // GNU/Hurd's triples should have been -hurd-gnu*, but were historically made
425 // -gnu* only, and we can not change this, so we have to detect that case as
426 // being the Hurd OS.
427 if (TargetTriple.find("-unknown-gnu") != StringRef::npos ||
428 TargetTriple.find("-pc-gnu") != StringRef::npos)
429 Target.setOSName("hurd");
430
Artem Belevich959e0542015-07-10 19:47:55 +0000431 // Handle Apple-specific options available here.
432 if (Target.isOSBinFormatMachO()) {
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000433 // If an explicit Darwin arch name is given, that trumps all.
Artem Belevich959e0542015-07-10 19:47:55 +0000434 if (!DarwinArchName.empty()) {
435 tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
436 return Target;
437 }
438
439 // Handle the Darwin '-arch' flag.
440 if (Arg *A = Args.getLastArg(options::OPT_arch)) {
441 StringRef ArchName = A->getValue();
442 tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
443 }
444 }
445
446 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
447 // '-mbig-endian'/'-EB'.
448 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
449 options::OPT_mbig_endian)) {
450 if (A->getOption().matches(options::OPT_mlittle_endian)) {
451 llvm::Triple LE = Target.getLittleEndianArchVariant();
452 if (LE.getArch() != llvm::Triple::UnknownArch)
453 Target = std::move(LE);
454 } else {
455 llvm::Triple BE = Target.getBigEndianArchVariant();
456 if (BE.getArch() != llvm::Triple::UnknownArch)
457 Target = std::move(BE);
458 }
459 }
460
461 // Skip further flag support on OSes which don't support '-m32' or '-m64'.
Douglas Katzman15a63ed2015-08-12 18:36:12 +0000462 if (Target.getArch() == llvm::Triple::tce ||
463 Target.getOS() == llvm::Triple::Minix)
Artem Belevich959e0542015-07-10 19:47:55 +0000464 return Target;
465
466 // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000467 Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
468 options::OPT_m32, options::OPT_m16);
469 if (A) {
Artem Belevich959e0542015-07-10 19:47:55 +0000470 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
471
472 if (A->getOption().matches(options::OPT_m64)) {
473 AT = Target.get64BitArchVariant().getArch();
474 if (Target.getEnvironment() == llvm::Triple::GNUX32)
475 Target.setEnvironment(llvm::Triple::GNU);
476 } else if (A->getOption().matches(options::OPT_mx32) &&
477 Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
478 AT = llvm::Triple::x86_64;
479 Target.setEnvironment(llvm::Triple::GNUX32);
480 } else if (A->getOption().matches(options::OPT_m32)) {
481 AT = Target.get32BitArchVariant().getArch();
482 if (Target.getEnvironment() == llvm::Triple::GNUX32)
483 Target.setEnvironment(llvm::Triple::GNU);
484 } else if (A->getOption().matches(options::OPT_m16) &&
485 Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
486 AT = llvm::Triple::x86;
487 Target.setEnvironment(llvm::Triple::CODE16);
488 }
489
490 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
491 Target.setArch(AT);
492 }
493
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000494 // Handle -miamcu flag.
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000495 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
496 if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
497 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
498 << Target.str();
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000499
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000500 if (A && !A->getOption().matches(options::OPT_m32))
501 D.Diag(diag::err_drv_argument_not_allowed_with)
502 << "-miamcu" << A->getBaseArg().getAsString(Args);
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000503
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000504 Target.setArch(llvm::Triple::x86);
505 Target.setArchName("i586");
506 Target.setEnvironment(llvm::Triple::UnknownEnvironment);
507 Target.setEnvironmentName("");
508 Target.setOS(llvm::Triple::ELFIAMCU);
509 Target.setVendor(llvm::Triple::UnknownVendor);
510 Target.setVendorName("intel");
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000511 }
512
Simon Atanasyan0c0fb4b2018-09-27 05:04:50 +0000513 // If target is MIPS adjust the target triple
514 // accordingly to provided ABI name.
515 A = Args.getLastArg(options::OPT_mabi_EQ);
Simon Atanasyane60eae42018-10-16 10:19:06 +0000516 if (A && Target.isMIPS()) {
517 StringRef ABIName = A->getValue();
518 if (ABIName == "32") {
519 Target = Target.get32BitArchVariant();
520 if (Target.getEnvironment() == llvm::Triple::GNUABI64 ||
521 Target.getEnvironment() == llvm::Triple::GNUABIN32)
522 Target.setEnvironment(llvm::Triple::GNU);
523 } else if (ABIName == "n32") {
524 Target = Target.get64BitArchVariant();
525 if (Target.getEnvironment() == llvm::Triple::GNU ||
526 Target.getEnvironment() == llvm::Triple::GNUABI64)
527 Target.setEnvironment(llvm::Triple::GNUABIN32);
528 } else if (ABIName == "64") {
529 Target = Target.get64BitArchVariant();
530 if (Target.getEnvironment() == llvm::Triple::GNU ||
531 Target.getEnvironment() == llvm::Triple::GNUABIN32)
532 Target.setEnvironment(llvm::Triple::GNUABI64);
533 }
534 }
Simon Atanasyan0c0fb4b2018-09-27 05:04:50 +0000535
Artem Belevich959e0542015-07-10 19:47:55 +0000536 return Target;
537}
538
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000539// Parse the LTO options and record the type of LTO compilation
Teresa Johnson945bc502015-10-15 20:35:53 +0000540// based on which -f(no-)?lto(=.*)? option occurs last.
541void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
542 LTOMode = LTOK_None;
543 if (!Args.hasFlag(options::OPT_flto, options::OPT_flto_EQ,
544 options::OPT_fno_lto, false))
545 return;
546
547 StringRef LTOName("full");
548
549 const Arg *A = Args.getLastArg(options::OPT_flto_EQ);
Teresa Johnson6ef80dc2015-11-02 18:03:12 +0000550 if (A)
551 LTOName = A->getValue();
Teresa Johnson945bc502015-10-15 20:35:53 +0000552
553 LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
554 .Case("full", LTOK_Full)
555 .Case("thin", LTOK_Thin)
556 .Default(LTOK_Unknown);
557
558 if (LTOMode == LTOK_Unknown) {
559 assert(A);
560 Diag(diag::err_drv_unsupported_option_argument) << A->getOption().getName()
561 << A->getValue();
562 }
563}
564
Samuel Antao39f9da22016-10-27 16:38:05 +0000565/// Compute the desired OpenMP runtime from the flags provided.
566Driver::OpenMPRuntimeKind Driver::getOpenMPRuntime(const ArgList &Args) const {
567 StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
568
569 const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
570 if (A)
571 RuntimeName = A->getValue();
572
573 auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
574 .Case("libomp", OMPRT_OMP)
575 .Case("libgomp", OMPRT_GOMP)
576 .Case("libiomp5", OMPRT_IOMP5)
577 .Default(OMPRT_Unknown);
578
579 if (RT == OMPRT_Unknown) {
580 if (A)
581 Diag(diag::err_drv_unsupported_option_argument)
582 << A->getOption().getName() << A->getValue();
583 else
584 // FIXME: We could use a nicer diagnostic here.
585 Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
586 }
587
588 return RT;
589}
590
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000591void Driver::CreateOffloadingDeviceToolChains(Compilation &C,
592 InputList &Inputs) {
593
594 //
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000595 // CUDA/HIP
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000596 //
Yaxun Liuf6144222018-05-30 00:53:50 +0000597 // We need to generate a CUDA/HIP toolchain if any of the inputs has a CUDA
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000598 // or HIP type. However, mixed CUDA/HIP compilation is not supported.
599 bool IsCuda =
600 llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000601 return types::isCuda(I.first);
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000602 });
603 bool IsHIP =
604 llvm::any_of(Inputs,
605 [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
606 return types::isHIP(I.first);
607 }) ||
608 C.getInputArgs().hasArg(options::OPT_hip_link);
609 if (IsCuda && IsHIP) {
610 Diag(clang::diag::err_drv_mix_cuda_hip);
611 return;
612 }
Yaxun Liuf6144222018-05-30 00:53:50 +0000613 if (IsCuda) {
Justin Lebar66c4fd72016-11-18 00:41:22 +0000614 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
615 const llvm::Triple &HostTriple = HostTC->getTriple();
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000616 StringRef DeviceTripleStr;
Yaxun Liuf6144222018-05-30 00:53:50 +0000617 auto OFK = Action::OFK_Cuda;
618 DeviceTripleStr =
619 HostTriple.isArch64Bit() ? "nvptx64-nvidia-cuda" : "nvptx-nvidia-cuda";
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000620 llvm::Triple CudaTriple(DeviceTripleStr);
Yaxun Liuf6144222018-05-30 00:53:50 +0000621 // Use the CUDA and host triples as the key into the ToolChains map,
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000622 // because the device toolchain we create depends on both.
David Blaikie6ad71012017-01-13 18:53:43 +0000623 auto &CudaTC = ToolChains[CudaTriple.str() + "/" + HostTriple.str()];
Justin Lebar66c4fd72016-11-18 00:41:22 +0000624 if (!CudaTC) {
David Blaikie6ad71012017-01-13 18:53:43 +0000625 CudaTC = llvm::make_unique<toolchains::CudaToolChain>(
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000626 *this, CudaTriple, *HostTC, C.getInputArgs(), OFK);
Justin Lebar66c4fd72016-11-18 00:41:22 +0000627 }
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000628 C.addOffloadDeviceToolChain(CudaTC.get(), OFK);
Yaxun Liuf6144222018-05-30 00:53:50 +0000629 } else if (IsHIP) {
630 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
631 const llvm::Triple &HostTriple = HostTC->getTriple();
632 StringRef DeviceTripleStr;
633 auto OFK = Action::OFK_HIP;
634 DeviceTripleStr = "amdgcn-amd-amdhsa";
635 llvm::Triple HIPTriple(DeviceTripleStr);
636 // Use the HIP and host triples as the key into the ToolChains map,
637 // because the device toolchain we create depends on both.
638 auto &HIPTC = ToolChains[HIPTriple.str() + "/" + HostTriple.str()];
639 if (!HIPTC) {
640 HIPTC = llvm::make_unique<toolchains::HIPToolChain>(
641 *this, HIPTriple, *HostTC, C.getInputArgs());
642 }
643 C.addOffloadDeviceToolChain(HIPTC.get(), OFK);
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000644 }
645
646 //
Samuel Antao39f9da22016-10-27 16:38:05 +0000647 // OpenMP
648 //
649 // We need to generate an OpenMP toolchain if the user specified targets with
650 // the -fopenmp-targets option.
651 if (Arg *OpenMPTargets =
652 C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
653 if (OpenMPTargets->getNumValues()) {
654 // We expect that -fopenmp-targets is always used in conjunction with the
655 // option -fopenmp specifying a valid runtime with offloading support,
656 // i.e. libomp or libiomp.
657 bool HasValidOpenMPRuntime = C.getInputArgs().hasFlag(
658 options::OPT_fopenmp, options::OPT_fopenmp_EQ,
659 options::OPT_fno_openmp, false);
660 if (HasValidOpenMPRuntime) {
661 OpenMPRuntimeKind OpenMPKind = getOpenMPRuntime(C.getInputArgs());
662 HasValidOpenMPRuntime =
663 OpenMPKind == OMPRT_OMP || OpenMPKind == OMPRT_IOMP5;
664 }
665
666 if (HasValidOpenMPRuntime) {
667 llvm::StringMap<const char *> FoundNormalizedTriples;
668 for (const char *Val : OpenMPTargets->getValues()) {
669 llvm::Triple TT(Val);
670 std::string NormalizedName = TT.normalize();
671
672 // Make sure we don't have a duplicate triple.
673 auto Duplicate = FoundNormalizedTriples.find(NormalizedName);
674 if (Duplicate != FoundNormalizedTriples.end()) {
675 Diag(clang::diag::warn_drv_omp_offload_target_duplicate)
676 << Val << Duplicate->second;
677 continue;
678 }
679
680 // Store the current triple so that we can check for duplicates in the
681 // following iterations.
682 FoundNormalizedTriples[NormalizedName] = Val;
683
684 // If the specified target is invalid, emit a diagnostic.
685 if (TT.getArch() == llvm::Triple::UnknownArch)
686 Diag(clang::diag::err_drv_invalid_omp_target) << Val;
687 else {
Gheorghe-Teodor Bercea6a5df722017-07-06 16:08:15 +0000688 const ToolChain *TC;
689 // CUDA toolchains have to be selected differently. They pair host
690 // and device in their implementation.
691 if (TT.isNVPTX()) {
692 const ToolChain *HostTC =
693 C.getSingleOffloadToolChain<Action::OFK_Host>();
694 assert(HostTC && "Host toolchain should be always defined.");
695 auto &CudaTC =
Gheorghe-Teodor Bercea52898432017-08-09 01:02:19 +0000696 ToolChains[TT.str() + "/" + HostTC->getTriple().normalize()];
Gheorghe-Teodor Bercea6a5df722017-07-06 16:08:15 +0000697 if (!CudaTC)
698 CudaTC = llvm::make_unique<toolchains::CudaToolChain>(
Gheorghe-Teodor Bercea2c926932017-08-08 14:33:05 +0000699 *this, TT, *HostTC, C.getInputArgs(), Action::OFK_OpenMP);
Gheorghe-Teodor Bercea6a5df722017-07-06 16:08:15 +0000700 TC = CudaTC.get();
701 } else
702 TC = &getToolChain(C.getInputArgs(), TT);
703 C.addOffloadDeviceToolChain(TC, Action::OFK_OpenMP);
Samuel Antao39f9da22016-10-27 16:38:05 +0000704 }
705 }
706 } else
707 Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
708 } else
709 Diag(clang::diag::warn_drv_empty_joined_argument)
710 << OpenMPTargets->getAsString(C.getInputArgs());
711 }
712
713 //
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000714 // TODO: Add support for other offloading programming models here.
715 //
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000716}
717
Serge Pavlov208ac652018-01-01 13:27:01 +0000718/// Looks the given directories for the specified file.
719///
720/// \param[out] FilePath File path, if the file was found.
721/// \param[in] Dirs Directories used for the search.
722/// \param[in] FileName Name of the file to search for.
723/// \return True if file was found.
724///
725/// Looks for file specified by FileName sequentially in directories specified
726/// by Dirs.
727///
728static bool searchForFile(SmallVectorImpl<char> &FilePath,
729 ArrayRef<std::string> Dirs,
730 StringRef FileName) {
731 SmallString<128> WPath;
732 for (const StringRef &Dir : Dirs) {
733 if (Dir.empty())
734 continue;
735 WPath.clear();
736 llvm::sys::path::append(WPath, Dir, FileName);
737 llvm::sys::path::native(WPath);
738 if (llvm::sys::fs::is_regular_file(WPath)) {
739 FilePath = std::move(WPath);
740 return true;
741 }
742 }
743 return false;
744}
745
746bool Driver::readConfigFile(StringRef FileName) {
747 // Try reading the given file.
748 SmallVector<const char *, 32> NewCfgArgs;
749 if (!llvm::cl::readConfigFile(FileName, Saver, NewCfgArgs)) {
750 Diag(diag::err_drv_cannot_read_config_file) << FileName;
751 return true;
752 }
753
754 // Read options from config file.
755 llvm::SmallString<128> CfgFileName(FileName);
756 llvm::sys::path::native(CfgFileName);
757 ConfigFile = CfgFileName.str();
758 bool ContainErrors;
759 CfgOptions = llvm::make_unique<InputArgList>(
Hans Wennborg797004d2018-11-08 11:27:04 +0000760 ParseArgStrings(NewCfgArgs, IsCLMode(), ContainErrors));
Serge Pavlov208ac652018-01-01 13:27:01 +0000761 if (ContainErrors) {
762 CfgOptions.reset();
763 return true;
764 }
765
766 if (CfgOptions->hasArg(options::OPT_config)) {
767 CfgOptions.reset();
768 Diag(diag::err_drv_nested_config_file);
769 return true;
770 }
771
772 // Claim all arguments that come from a configuration file so that the driver
773 // does not warn on any that is unused.
774 for (Arg *A : *CfgOptions)
775 A->claim();
776 return false;
777}
778
779bool Driver::loadConfigFile() {
780 std::string CfgFileName;
781 bool FileSpecifiedExplicitly = false;
782
783 // Process options that change search path for config files.
784 if (CLOptions) {
785 if (CLOptions->hasArg(options::OPT_config_system_dir_EQ)) {
786 SmallString<128> CfgDir;
787 CfgDir.append(
788 CLOptions->getLastArgValue(options::OPT_config_system_dir_EQ));
789 if (!CfgDir.empty()) {
Sam McCall296d8322018-01-02 09:35:10 +0000790 if (llvm::sys::fs::make_absolute(CfgDir).value() != 0)
Serge Pavlov208ac652018-01-01 13:27:01 +0000791 SystemConfigDir.clear();
792 else
793 SystemConfigDir = std::string(CfgDir.begin(), CfgDir.end());
794 }
795 }
796 if (CLOptions->hasArg(options::OPT_config_user_dir_EQ)) {
797 SmallString<128> CfgDir;
798 CfgDir.append(
799 CLOptions->getLastArgValue(options::OPT_config_user_dir_EQ));
800 if (!CfgDir.empty()) {
Sam McCall296d8322018-01-02 09:35:10 +0000801 if (llvm::sys::fs::make_absolute(CfgDir).value() != 0)
Serge Pavlov208ac652018-01-01 13:27:01 +0000802 UserConfigDir.clear();
803 else
804 UserConfigDir = std::string(CfgDir.begin(), CfgDir.end());
805 }
806 }
807 }
808
809 // First try to find config file specified in command line.
810 if (CLOptions) {
811 std::vector<std::string> ConfigFiles =
812 CLOptions->getAllArgValues(options::OPT_config);
813 if (ConfigFiles.size() > 1) {
814 Diag(diag::err_drv_duplicate_config);
815 return true;
816 }
817
818 if (!ConfigFiles.empty()) {
819 CfgFileName = ConfigFiles.front();
820 assert(!CfgFileName.empty());
821
822 // If argument contains directory separator, treat it as a path to
823 // configuration file.
824 if (llvm::sys::path::has_parent_path(CfgFileName)) {
825 SmallString<128> CfgFilePath;
826 if (llvm::sys::path::is_relative(CfgFileName))
827 llvm::sys::fs::current_path(CfgFilePath);
828 llvm::sys::path::append(CfgFilePath, CfgFileName);
829 if (!llvm::sys::fs::is_regular_file(CfgFilePath)) {
830 Diag(diag::err_drv_config_file_not_exist) << CfgFilePath;
831 return true;
832 }
833 return readConfigFile(CfgFilePath);
834 }
835
836 FileSpecifiedExplicitly = true;
837 }
838 }
839
840 // If config file is not specified explicitly, try to deduce configuration
841 // from executable name. For instance, an executable 'armv7l-clang' will
842 // search for config file 'armv7l-clang.cfg'.
843 if (CfgFileName.empty() && !ClangNameParts.TargetPrefix.empty())
844 CfgFileName = ClangNameParts.TargetPrefix + '-' + ClangNameParts.ModeSuffix;
845
846 if (CfgFileName.empty())
847 return false;
848
849 // Determine architecture part of the file name, if it is present.
850 StringRef CfgFileArch = CfgFileName;
851 size_t ArchPrefixLen = CfgFileArch.find('-');
852 if (ArchPrefixLen == StringRef::npos)
853 ArchPrefixLen = CfgFileArch.size();
854 llvm::Triple CfgTriple;
855 CfgFileArch = CfgFileArch.take_front(ArchPrefixLen);
856 CfgTriple = llvm::Triple(llvm::Triple::normalize(CfgFileArch));
857 if (CfgTriple.getArch() == llvm::Triple::ArchType::UnknownArch)
858 ArchPrefixLen = 0;
859
860 if (!StringRef(CfgFileName).endswith(".cfg"))
861 CfgFileName += ".cfg";
862
863 // If config file starts with architecture name and command line options
864 // redefine architecture (with options like -m32 -LE etc), try finding new
865 // config file with that architecture.
866 SmallString<128> FixedConfigFile;
867 size_t FixedArchPrefixLen = 0;
868 if (ArchPrefixLen) {
869 // Get architecture name from config file name like 'i386.cfg' or
870 // 'armv7l-clang.cfg'.
871 // Check if command line options changes effective triple.
872 llvm::Triple EffectiveTriple = computeTargetTriple(*this,
873 CfgTriple.getTriple(), *CLOptions);
874 if (CfgTriple.getArch() != EffectiveTriple.getArch()) {
875 FixedConfigFile = EffectiveTriple.getArchName();
876 FixedArchPrefixLen = FixedConfigFile.size();
877 // Append the rest of original file name so that file name transforms
878 // like: i386-clang.cfg -> x86_64-clang.cfg.
879 if (ArchPrefixLen < CfgFileName.size())
880 FixedConfigFile += CfgFileName.substr(ArchPrefixLen);
881 }
882 }
883
884 // Prepare list of directories where config file is searched for.
885 SmallVector<std::string, 3> CfgFileSearchDirs;
886 CfgFileSearchDirs.push_back(UserConfigDir);
887 CfgFileSearchDirs.push_back(SystemConfigDir);
888 CfgFileSearchDirs.push_back(Dir);
889
890 // Try to find config file. First try file with corrected architecture.
891 llvm::SmallString<128> CfgFilePath;
892 if (!FixedConfigFile.empty()) {
893 if (searchForFile(CfgFilePath, CfgFileSearchDirs, FixedConfigFile))
894 return readConfigFile(CfgFilePath);
895 // If 'x86_64-clang.cfg' was not found, try 'x86_64.cfg'.
896 FixedConfigFile.resize(FixedArchPrefixLen);
897 FixedConfigFile.append(".cfg");
898 if (searchForFile(CfgFilePath, CfgFileSearchDirs, FixedConfigFile))
899 return readConfigFile(CfgFilePath);
900 }
901
902 // Then try original file name.
903 if (searchForFile(CfgFilePath, CfgFileSearchDirs, CfgFileName))
904 return readConfigFile(CfgFilePath);
905
906 // Finally try removing driver mode part: 'x86_64-clang.cfg' -> 'x86_64.cfg'.
907 if (!ClangNameParts.ModeSuffix.empty() &&
908 !ClangNameParts.TargetPrefix.empty()) {
909 CfgFileName.assign(ClangNameParts.TargetPrefix);
910 CfgFileName.append(".cfg");
911 if (searchForFile(CfgFilePath, CfgFileSearchDirs, CfgFileName))
912 return readConfigFile(CfgFilePath);
913 }
914
915 // Report error but only if config file was specified explicitly, by option
916 // --config. If it was deduced from executable name, it is not an error.
917 if (FileSpecifiedExplicitly) {
918 Diag(diag::err_drv_config_file_not_found) << CfgFileName;
919 for (const std::string &SearchDir : CfgFileSearchDirs)
920 if (!SearchDir.empty())
921 Diag(diag::note_drv_config_file_searched_in) << SearchDir;
922 return true;
923 }
924
925 return false;
926}
927
Chris Lattner54b16772011-07-23 17:14:25 +0000928Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
Daniel Dunbar2608c542009-03-18 01:38:48 +0000929 llvm::PrettyStackTraceString CrashInfo("Compilation construction");
930
Eric Christopherf901e852011-08-17 22:59:59 +0000931 // FIXME: Handle environment options which affect driver behavior, somewhere
Bill Wendlingadbeb9f2012-03-12 21:24:57 +0000932 // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
Chad Rosier82301162011-09-14 00:47:55 +0000933
David Majnemer85c25b42016-07-24 17:44:03 +0000934 if (Optional<std::string> CompilerPathValue =
935 llvm::sys::Process::GetEnv("COMPILER_PATH")) {
936 StringRef CompilerPath = *CompilerPathValue;
Chad Rosier82301162011-09-14 00:47:55 +0000937 while (!CompilerPath.empty()) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000938 std::pair<StringRef, StringRef> Split =
939 CompilerPath.split(llvm::sys::EnvPathSeparator);
Chad Rosier82301162011-09-14 00:47:55 +0000940 PrefixDirs.push_back(Split.first);
941 CompilerPath = Split.second;
942 }
943 }
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +0000944
Hans Wennborg70850d82013-07-18 20:29:38 +0000945 // We look for the driver mode option early, because the mode can affect
946 // how other options are parsed.
Zachary Turneraff19c32016-08-12 17:47:52 +0000947 ParseDriverMode(ClangExecutable, ArgList.slice(1));
Hans Wennborg70850d82013-07-18 20:29:38 +0000948
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +0000949 // FIXME: What are we going to do with -V and -b?
950
Serge Pavlov208ac652018-01-01 13:27:01 +0000951 // Arguments specified in command line.
952 bool ContainsError;
953 CLOptions = llvm::make_unique<InputArgList>(
Hans Wennborg797004d2018-11-08 11:27:04 +0000954 ParseArgStrings(ArgList.slice(1), IsCLMode(), ContainsError));
Serge Pavlov208ac652018-01-01 13:27:01 +0000955
956 // Try parsing configuration file.
957 if (!ContainsError)
958 ContainsError = loadConfigFile();
959 bool HasConfigFile = !ContainsError && (CfgOptions.get() != nullptr);
960
961 // All arguments, from both config file and command line.
962 InputArgList Args = std::move(HasConfigFile ? std::move(*CfgOptions)
963 : std::move(*CLOptions));
Hans Wennborg797004d2018-11-08 11:27:04 +0000964
965 auto appendOneArg = [&Args](const Arg *Opt, const Arg *BaseArg) {
Serge Pavlovf015a562018-04-26 06:28:47 +0000966 unsigned Index = Args.MakeIndex(Opt->getSpelling());
Serge Pavlov208ac652018-01-01 13:27:01 +0000967 Arg *Copy = new llvm::opt::Arg(Opt->getOption(), Opt->getSpelling(),
Serge Pavlovf015a562018-04-26 06:28:47 +0000968 Index, BaseArg);
Serge Pavlov208ac652018-01-01 13:27:01 +0000969 Copy->getValues() = Opt->getValues();
970 if (Opt->isClaimed())
971 Copy->claim();
972 Args.append(Copy);
Hans Wennborg797004d2018-11-08 11:27:04 +0000973 };
974
975 if (HasConfigFile)
976 for (auto *Opt : *CLOptions) {
977 if (Opt->getOption().matches(options::OPT_config))
978 continue;
979 const Arg *BaseArg = &Opt->getBaseArg();
980 if (BaseArg == Opt)
981 BaseArg = nullptr;
982 appendOneArg(Opt, BaseArg);
Serge Pavlov208ac652018-01-01 13:27:01 +0000983 }
984
Hans Wennborg797004d2018-11-08 11:27:04 +0000985 // In CL mode, look for any pass-through arguments
986 if (IsCLMode() && !ContainsError) {
987 SmallVector<const char *, 16> CLModePassThroughArgList;
988 for (const auto *A : Args.filtered(options::OPT__SLASH_clang)) {
989 A->claim();
990 CLModePassThroughArgList.push_back(A->getValue());
991 }
992
993 if (!CLModePassThroughArgList.empty()) {
994 // Parse any pass through args using default clang processing rather
995 // than clang-cl processing.
996 auto CLModePassThroughOptions = llvm::make_unique<InputArgList>(
997 ParseArgStrings(CLModePassThroughArgList, false, ContainsError));
998
999 if (!ContainsError)
1000 for (auto *Opt : *CLModePassThroughOptions) {
1001 appendOneArg(Opt, nullptr);
1002 }
1003 }
1004 }
1005
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001006 // FIXME: This stuff needs to go into the Compilation, not the driver.
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001007 bool CCCPrintPhases;
Daniel Dunbard02cb1d2009-03-05 06:38:47 +00001008
Filipe Cabecinhas136f35e2015-07-18 06:35:24 +00001009 // Silence driver warnings if requested
1010 Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w));
1011
Rafael Espindola59ae7992009-12-07 18:28:29 +00001012 // -no-canonical-prefixes is used very early in main.
David Blaikie69a1d8c2015-06-22 22:07:27 +00001013 Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
Rafael Espindola59ae7992009-12-07 18:28:29 +00001014
Daniel Dunbar926f81f2010-08-02 02:38:03 +00001015 // Ignore -pipe.
David Blaikie69a1d8c2015-06-22 22:07:27 +00001016 Args.ClaimAllArgs(options::OPT_pipe);
Daniel Dunbar926f81f2010-08-02 02:38:03 +00001017
Daniel Dunbaracd69572009-12-04 21:55:23 +00001018 // Extract -ccc args.
Daniel Dunbaree66cf22009-03-10 20:52:46 +00001019 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001020 // FIXME: We need to figure out where this behavior should live. Most of it
1021 // should be outside in the client; the parts that aren't should have proper
1022 // options, either by introducing new ones or by overloading gcc ones like -V
1023 // or -b.
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001024 CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
David Blaikie69a1d8c2015-06-22 22:07:27 +00001025 CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
1026 if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
Richard Smithbd55daf2012-11-01 04:30:05 +00001027 CCCGenericGCCName = A->getValue();
Bruno Cardoso Lopes52dfe712017-04-12 21:46:20 +00001028 GenReproducer = Args.hasFlag(options::OPT_gen_reproducer,
1029 options::OPT_fno_crash_diagnostics,
1030 !!::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH"));
Petr Hosekdd38d932018-05-29 22:35:39 +00001031 // FIXME: TargetTriple is used by the target-prefixed calls to as/ld
Joerg Sonnenberger17d75512012-02-22 19:15:16 +00001032 // and getToolChain is const.
Hans Wennborg2e274592013-08-13 23:38:57 +00001033 if (IsCLMode()) {
Hans Wennborg73609a02014-03-28 01:19:04 +00001034 // clang-cl targets MSVC-style Win32.
Petr Hosekdd38d932018-05-29 22:35:39 +00001035 llvm::Triple T(TargetTriple);
Hans Wennborg9d9ce7a2014-03-28 20:49:28 +00001036 T.setOS(llvm::Triple::Win32);
Hans Wennborg0f0e8d62015-09-18 17:11:50 +00001037 T.setVendor(llvm::Triple::PC);
Hans Wennborg9d9ce7a2014-03-28 20:49:28 +00001038 T.setEnvironment(llvm::Triple::MSVC);
Oleg Ranevskyy80523182017-08-31 20:31:30 +00001039 T.setObjectFormat(llvm::Triple::COFF);
Petr Hosekdd38d932018-05-29 22:35:39 +00001040 TargetTriple = T.str();
Hans Wennborg2e274592013-08-13 23:38:57 +00001041 }
David Blaikie69a1d8c2015-06-22 22:07:27 +00001042 if (const Arg *A = Args.getLastArg(options::OPT_target))
Petr Hosekdd38d932018-05-29 22:35:39 +00001043 TargetTriple = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +00001044 if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
Richard Smithbd55daf2012-11-01 04:30:05 +00001045 Dir = InstalledDir = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +00001046 for (const Arg *A : Args.filtered(options::OPT_B)) {
Benjamin Kramer1a648d12011-02-08 20:31:42 +00001047 A->claim();
Richard Smithbd55daf2012-11-01 04:30:05 +00001048 PrefixDirs.push_back(A->getValue(0));
Benjamin Kramer1a648d12011-02-08 20:31:42 +00001049 }
David Blaikie69a1d8c2015-06-22 22:07:27 +00001050 if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
Richard Smithbd55daf2012-11-01 04:30:05 +00001051 SysRoot = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +00001052 if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
Peter Collingbourne9d9e1fc2013-05-27 21:40:20 +00001053 DyldPrefix = A->getValue();
Daniel Dunbaree66cf22009-03-10 20:52:46 +00001054
David Blaikie69a1d8c2015-06-22 22:07:27 +00001055 if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
Bob Wilsona20a1da2013-03-23 05:17:59 +00001056 ResourceDir = A->getValue();
Jim Grosbach061dabf2013-03-12 20:17:58 +00001057
David Blaikie69a1d8c2015-06-22 22:07:27 +00001058 if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
Reid Kleckner68eb60b2015-02-02 22:41:48 +00001059 SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
1060 .Case("cwd", SaveTempsCwd)
1061 .Case("obj", SaveTempsObj)
1062 .Default(SaveTempsCwd);
1063 }
1064
Steven Wu1257cd82016-05-18 17:04:52 +00001065 setLTOMode(Args);
1066
Steven Wu844ab6a2016-11-16 06:06:44 +00001067 // Process -fembed-bitcode= flags.
1068 if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
1069 StringRef Name = A->getValue();
1070 unsigned Model = llvm::StringSwitch<unsigned>(Name)
1071 .Case("off", EmbedNone)
1072 .Case("all", EmbedBitcode)
1073 .Case("bitcode", EmbedBitcode)
1074 .Case("marker", EmbedMarker)
1075 .Default(~0U);
1076 if (Model == ~0U) {
1077 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
1078 << Name;
1079 } else
1080 BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
Steven Wu574b0f22016-03-01 01:07:58 +00001081 }
1082
David Blaikie69a1d8c2015-06-22 22:07:27 +00001083 std::unique_ptr<llvm::opt::InputArgList> UArgs =
1084 llvm::make_unique<InputArgList>(std::move(Args));
1085
Daniel Dunbar775d4062010-06-11 22:00:26 +00001086 // Perform the default argument translations.
David Blaikie69a1d8c2015-06-22 22:07:27 +00001087 DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
Daniel Dunbar775d4062010-06-11 22:00:26 +00001088
Chandler Carruthcb916192012-01-25 08:49:21 +00001089 // Owned by the host.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +00001090 const ToolChain &TC = getToolChain(
Petr Hosekdd38d932018-05-29 22:35:39 +00001091 *UArgs, computeTargetTriple(*this, TargetTriple, *UArgs));
Chandler Carruthcb916192012-01-25 08:49:21 +00001092
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00001093 // The compilation takes ownership of Args.
Benjamin Kramer43c0f482017-06-30 13:21:27 +00001094 Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs,
1095 ContainsError);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001096
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001097 if (!HandleImmediateArgs(*C))
1098 return C;
1099
Chad Rosierecdede82011-08-12 22:08:57 +00001100 // Construct the list of inputs.
1101 InputList Inputs;
Hans Wennborged1d0722013-08-13 21:32:29 +00001102 BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
Chad Rosierecdede82011-08-12 22:08:57 +00001103
Samuel Antaoc1ffba52016-06-13 18:10:57 +00001104 // Populate the tool chains for the offloading devices, if any.
1105 CreateOffloadingDeviceToolChains(*C, Inputs);
Justin Lebar0e450a52016-03-30 23:30:25 +00001106
Chandler Carruth7f1417f2012-01-24 10:43:44 +00001107 // Construct the list of abstract actions to perform for this compilation. On
Tim Northover157d9112014-01-16 08:48:16 +00001108 // MachO targets this uses the driver-driver and universal actions.
1109 if (TC.getTriple().isOSBinFormatMachO())
Artem Belevich5e2a3ec2015-11-17 22:28:40 +00001110 BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001111 else
Justin Lebar0f3474c2016-02-11 02:00:50 +00001112 BuildActions(*C, C->getArgs(), Inputs, C->getActions());
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001113
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001114 if (CCCPrintPhases) {
Daniel Dunbareb843be2009-03-18 03:13:20 +00001115 PrintActions(*C);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001116 return C;
1117 }
1118
1119 BuildJobs(*C);
Daniel Dunbaradc91e62009-03-15 01:38:15 +00001120
1121 return C;
Daniel Dunbaree66cf22009-03-10 20:52:46 +00001122}
1123
Justin Bognered9cbe02015-07-09 06:58:31 +00001124static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
1125 llvm::opt::ArgStringList ASL;
1126 for (const auto *A : Args)
1127 A->render(Args, ASL);
1128
1129 for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
1130 if (I != ASL.begin())
1131 OS << ' ';
1132 Command::printArg(OS, *I, true);
1133 }
1134 OS << '\n';
1135}
1136
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +00001137bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename,
1138 SmallString<128> &CrashDiagDir) {
1139 using namespace llvm::sys;
1140 assert(llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin() &&
1141 "Only knows about .crash files on Darwin");
1142
1143 // The .crash file can be found on at ~/Library/Logs/DiagnosticReports/
1144 // (or /Library/Logs/DiagnosticReports for root) and has the filename pattern
1145 // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash.
1146 path::home_directory(CrashDiagDir);
1147 if (CrashDiagDir.startswith("/var/root"))
1148 CrashDiagDir = "/";
1149 path::append(CrashDiagDir, "Library/Logs/DiagnosticReports");
1150 int PID =
1151#if LLVM_ON_UNIX
1152 getpid();
1153#else
1154 0;
1155#endif
1156 std::error_code EC;
1157 fs::file_status FileStatus;
1158 TimePoint<> LastAccessTime;
1159 SmallString<128> CrashFilePath;
1160 // Lookup the .crash files and get the one generated by a subprocess spawned
1161 // by this driver invocation.
1162 for (fs::directory_iterator File(CrashDiagDir, EC), FileEnd;
1163 File != FileEnd && !EC; File.increment(EC)) {
1164 StringRef FileName = path::filename(File->path());
1165 if (!FileName.startswith(Name))
1166 continue;
1167 if (fs::status(File->path(), FileStatus))
1168 continue;
1169 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CrashFile =
1170 llvm::MemoryBuffer::getFile(File->path());
1171 if (!CrashFile)
1172 continue;
1173 // The first line should start with "Process:", otherwise this isn't a real
1174 // .crash file.
1175 StringRef Data = CrashFile.get()->getBuffer();
1176 if (!Data.startswith("Process:"))
1177 continue;
1178 // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]"
1179 size_t ParentProcPos = Data.find("Parent Process:");
1180 if (ParentProcPos == StringRef::npos)
1181 continue;
1182 size_t LineEnd = Data.find_first_of("\n", ParentProcPos);
1183 if (LineEnd == StringRef::npos)
1184 continue;
1185 StringRef ParentProcess = Data.slice(ParentProcPos+15, LineEnd).trim();
1186 int OpenBracket = -1, CloseBracket = -1;
1187 for (size_t i = 0, e = ParentProcess.size(); i < e; ++i) {
1188 if (ParentProcess[i] == '[')
1189 OpenBracket = i;
1190 if (ParentProcess[i] == ']')
1191 CloseBracket = i;
1192 }
1193 // Extract the parent process PID from the .crash file and check whether
1194 // it matches this driver invocation pid.
1195 int CrashPID;
1196 if (OpenBracket < 0 || CloseBracket < 0 ||
1197 ParentProcess.slice(OpenBracket + 1, CloseBracket)
1198 .getAsInteger(10, CrashPID) || CrashPID != PID) {
1199 continue;
1200 }
1201
1202 // Found a .crash file matching the driver pid. To avoid getting an older
1203 // and misleading crash file, continue looking for the most recent.
1204 // FIXME: the driver can dispatch multiple cc1 invocations, leading to
1205 // multiple crashes poiting to the same parent process. Since the driver
1206 // does not collect pid information for the dispatched invocation there's
1207 // currently no way to distinguish among them.
1208 const auto FileAccessTime = FileStatus.getLastModificationTime();
1209 if (FileAccessTime > LastAccessTime) {
1210 CrashFilePath.assign(File->path());
1211 LastAccessTime = FileAccessTime;
1212 }
1213 }
1214
1215 // If found, copy it over to the location of other reproducer files.
1216 if (!CrashFilePath.empty()) {
1217 EC = fs::copy_file(CrashFilePath, ReproCrashFilename);
1218 if (EC)
1219 return false;
1220 return true;
1221 }
1222
1223 return false;
1224}
1225
Eric Christopherf901e852011-08-17 22:59:59 +00001226// When clang crashes, produce diagnostic information including the fully
1227// preprocessed source file(s). Request that the developer attach the
Chad Rosierbe10f982011-08-02 17:58:04 +00001228// diagnostic information to a bug report.
Alex Lorenz045c5142018-04-07 00:03:27 +00001229void Driver::generateCompilationDiagnostics(
1230 Compilation &C, const Command &FailingCommand,
1231 StringRef AdditionalInformation, CompilationDiagnosticReport *Report) {
Chad Rosier877c0a22012-02-22 00:30:39 +00001232 if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
Chad Rosier62135492012-07-09 17:31:28 +00001233 return;
Chad Rosierbee5a1d2012-03-07 00:30:40 +00001234
Chad Rosierdbf46a12013-02-01 18:30:26 +00001235 // Don't try to generate diagnostics for link or dsymutil jobs.
Justin Bognere1a33d12014-10-20 21:02:05 +00001236 if (FailingCommand.getCreator().isLinkJob() ||
1237 FailingCommand.getCreator().isDsymutilJob())
Chad Rosier877c0a22012-02-22 00:30:39 +00001238 return;
1239
Chad Rosier8179f112012-06-19 17:51:34 +00001240 // Print the version of the compiler.
1241 PrintVersion(C, llvm::errs());
1242
Chad Rosierbe10f982011-08-02 17:58:04 +00001243 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001244 << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the "
1245 "crash backtrace, preprocessed source, and associated run script.";
Chad Rosierbe10f982011-08-02 17:58:04 +00001246
1247 // Suppress driver output and emit preprocessor output to temp file.
Hans Wennborg70850d82013-07-18 20:29:38 +00001248 Mode = CPPMode;
Chad Rosierbe10f982011-08-02 17:58:04 +00001249 CCGenDiagnostics = true;
1250
Chad Rosiercdb008d2011-11-02 21:29:05 +00001251 // Save the original job command(s).
Justin Bogner25645152014-10-21 17:24:44 +00001252 Command Cmd = FailingCommand;
Chad Rosiercdb008d2011-11-02 21:29:05 +00001253
Richard Smith5bb4cdf2012-12-20 02:22:15 +00001254 // Keep track of whether we produce any errors while trying to produce
1255 // preprocessed sources.
1256 DiagnosticErrorTrap Trap(Diags);
1257
1258 // Suppress tool output.
Chad Rosierbe10f982011-08-02 17:58:04 +00001259 C.initCompilationForDiagnostics();
Chad Rosierecdede82011-08-12 22:08:57 +00001260
1261 // Construct the list of inputs.
1262 InputList Inputs;
1263 BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
Chad Rosierbe10f982011-08-02 17:58:04 +00001264
Chad Rosier4f81fc22011-08-12 23:30:05 +00001265 for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
Chad Rosierd57133d2011-08-18 00:22:25 +00001266 bool IgnoreInput = false;
1267
1268 // Ignore input from stdin or any inputs that cannot be preprocessed.
Paul Robinsonf44157d2014-04-28 22:24:44 +00001269 // Check type first as not all linker inputs have a value.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001270 if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
Paul Robinsonf44157d2014-04-28 22:24:44 +00001271 IgnoreInput = true;
1272 } else if (!strcmp(it->second->getValue(), "-")) {
Chad Rosierd57133d2011-08-18 00:22:25 +00001273 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001274 << "Error generating preprocessed source(s) - "
1275 "ignoring input from stdin.";
Chad Rosierd57133d2011-08-18 00:22:25 +00001276 IgnoreInput = true;
Chad Rosierd57133d2011-08-18 00:22:25 +00001277 }
1278
1279 if (IgnoreInput) {
Chad Rosier4f81fc22011-08-12 23:30:05 +00001280 it = Inputs.erase(it);
1281 ie = Inputs.end();
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001282 } else {
Chad Rosier4f81fc22011-08-12 23:30:05 +00001283 ++it;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001284 }
Chad Rosier4f81fc22011-08-12 23:30:05 +00001285 }
Chad Rosierd57133d2011-08-18 00:22:25 +00001286
Chad Rosierc5103c32013-01-29 23:57:10 +00001287 if (Inputs.empty()) {
1288 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001289 << "Error generating preprocessed source(s) - "
1290 "no preprocessable inputs.";
Chad Rosierc5103c32013-01-29 23:57:10 +00001291 return;
1292 }
1293
Chad Rosiere75ef402011-09-06 23:52:36 +00001294 // Don't attempt to generate preprocessed files if multiple -arch options are
Chad Rosier636d2832012-02-13 18:16:28 +00001295 // used, unless they're all duplicates.
1296 llvm::StringSet<> ArchNames;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00001297 for (const Arg *A : C.getArgs()) {
Chad Rosiere75ef402011-09-06 23:52:36 +00001298 if (A->getOption().matches(options::OPT_arch)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001299 StringRef ArchName = A->getValue();
Chad Rosier636d2832012-02-13 18:16:28 +00001300 ArchNames.insert(ArchName);
Chad Rosiere75ef402011-09-06 23:52:36 +00001301 }
1302 }
Chad Rosier636d2832012-02-13 18:16:28 +00001303 if (ArchNames.size() > 1) {
1304 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001305 << "Error generating preprocessed source(s) - cannot generate "
1306 "preprocessed source with multiple -arch options.";
Chad Rosier636d2832012-02-13 18:16:28 +00001307 return;
1308 }
Chad Rosiere75ef402011-09-06 23:52:36 +00001309
Chandler Carruth7f1417f2012-01-24 10:43:44 +00001310 // Construct the list of abstract actions to perform for this compilation. On
1311 // Darwin OSes this uses the driver-driver and builds universal actions.
Chandler Carruthcb916192012-01-25 08:49:21 +00001312 const ToolChain &TC = C.getDefaultToolChain();
Tim Northover157d9112014-01-16 08:48:16 +00001313 if (TC.getTriple().isOSBinFormatMachO())
Artem Belevich5e2a3ec2015-11-17 22:28:40 +00001314 BuildUniversalActions(C, TC, Inputs);
Chad Rosierbe10f982011-08-02 17:58:04 +00001315 else
Justin Lebar0f3474c2016-02-11 02:00:50 +00001316 BuildActions(C, C.getArgs(), Inputs, C.getActions());
Chad Rosierbe10f982011-08-02 17:58:04 +00001317
1318 BuildJobs(C);
1319
1320 // If there were errors building the compilation, quit now.
Richard Smith5bb4cdf2012-12-20 02:22:15 +00001321 if (Trap.hasErrorOccurred()) {
Chad Rosierbe10f982011-08-02 17:58:04 +00001322 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001323 << "Error generating preprocessed source(s).";
Chad Rosierbe10f982011-08-02 17:58:04 +00001324 return;
1325 }
1326
1327 // Generate preprocessed output.
Chad Rosierdd60e092013-01-29 20:15:05 +00001328 SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
Justin Bogner0cd92482015-07-02 22:52:08 +00001329 C.ExecuteJobs(C.getJobs(), FailingCommands);
Chad Rosierbe10f982011-08-02 17:58:04 +00001330
Justin Bognerbc89b182014-10-20 21:20:27 +00001331 // If any of the preprocessing commands failed, clean up and exit.
1332 if (!FailingCommands.empty()) {
Chad Rosierbe10f982011-08-02 17:58:04 +00001333 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001334 << "Error generating preprocessed source(s).";
Justin Bognerbc89b182014-10-20 21:20:27 +00001335 return;
Chad Rosierbe10f982011-08-02 17:58:04 +00001336 }
Justin Bognerbc89b182014-10-20 21:20:27 +00001337
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001338 const ArgStringList &TempFiles = C.getTempFiles();
1339 if (TempFiles.empty()) {
1340 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001341 << "Error generating preprocessed source(s).";
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001342 return;
1343 }
1344
Justin Bognerbc89b182014-10-20 21:20:27 +00001345 Diag(clang::diag::note_drv_command_failed_diag_msg)
1346 << "\n********************\n\n"
1347 "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
1348 "Preprocessed source(s) and associated run script(s) are located at:";
Justin Bognerbc89b182014-10-20 21:20:27 +00001349
Justin Bogner659ecc32014-10-20 22:47:23 +00001350 SmallString<128> VFS;
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +00001351 SmallString<128> ReproCrashFilename;
Justin Bogner659ecc32014-10-20 22:47:23 +00001352 for (const char *TempFile : TempFiles) {
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001353 Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
Alex Lorenz045c5142018-04-07 00:03:27 +00001354 if (Report)
1355 Report->TemporaryFiles.push_back(TempFile);
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +00001356 if (ReproCrashFilename.empty()) {
1357 ReproCrashFilename = TempFile;
1358 llvm::sys::path::replace_extension(ReproCrashFilename, ".crash");
1359 }
Justin Bogner659ecc32014-10-20 22:47:23 +00001360 if (StringRef(TempFile).endswith(".cache")) {
1361 // In some cases (modules) we'll dump extra data to help with reproducing
1362 // the crash into a directory next to the output.
1363 VFS = llvm::sys::path::filename(TempFile);
1364 llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
1365 }
1366 }
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001367
1368 // Assume associated files are based off of the first temporary file.
Justin Bogner25645152014-10-21 17:24:44 +00001369 CrashReportInfo CrashInfo(TempFiles[0], VFS);
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001370
Bob Haarman7e4d3ff2018-07-09 21:07:20 +00001371 llvm::SmallString<128> Script(CrashInfo.Filename);
1372 llvm::sys::path::replace_extension(Script, "sh");
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001373 std::error_code EC;
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001374 llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::CD_CreateNew);
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001375 if (EC) {
1376 Diag(clang::diag::note_drv_command_failed_diag_msg)
Bob Haarman7e4d3ff2018-07-09 21:07:20 +00001377 << "Error generating run script: " << Script << " " << EC.message();
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001378 } else {
Justin Bogner42220ed2015-03-12 00:14:35 +00001379 ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
Justin Bognered9cbe02015-07-09 06:58:31 +00001380 << "# Driver args: ";
1381 printArgList(ScriptOS, C.getInputArgs());
1382 ScriptOS << "# Original command: ";
Justin Bogner42220ed2015-03-12 00:14:35 +00001383 Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
Justin Bogner33bdbc62014-10-21 18:03:08 +00001384 Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
Alex Lorenz045c5142018-04-07 00:03:27 +00001385 if (!AdditionalInformation.empty())
1386 ScriptOS << "\n# Additional information: " << AdditionalInformation
1387 << "\n";
1388 if (Report)
Bob Haarman7e4d3ff2018-07-09 21:07:20 +00001389 Report->TemporaryFiles.push_back(Script.str());
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001390 Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
Justin Bognerbc89b182014-10-20 21:20:27 +00001391 }
Saleem Abdulrasool3661a822015-01-12 02:33:09 +00001392
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +00001393 // On darwin, provide information about the .crash diagnostic report.
1394 if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) {
1395 SmallString<128> CrashDiagDir;
1396 if (getCrashDiagnosticFile(ReproCrashFilename, CrashDiagDir)) {
1397 Diag(clang::diag::note_drv_command_failed_diag_msg)
1398 << ReproCrashFilename.str();
1399 } else { // Suggest a directory for the user to look for .crash files.
1400 llvm::sys::path::append(CrashDiagDir, Name);
1401 CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash";
1402 Diag(clang::diag::note_drv_command_failed_diag_msg)
1403 << "Crash backtrace is located in";
1404 Diag(clang::diag::note_drv_command_failed_diag_msg)
1405 << CrashDiagDir.str();
1406 Diag(clang::diag::note_drv_command_failed_diag_msg)
1407 << "(choose the .crash file that corresponds to your crash)";
1408 }
1409 }
1410
Saleem Abdulrasool3661a822015-01-12 02:33:09 +00001411 for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file,
1412 options::OPT_frewrite_map_file_EQ))
1413 Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
1414
Justin Bognerbc89b182014-10-20 21:20:27 +00001415 Diag(clang::diag::note_drv_command_failed_diag_msg)
1416 << "\n\n********************";
Chad Rosierbe10f982011-08-02 17:58:04 +00001417}
1418
Justin Bogner0cd92482015-07-02 22:52:08 +00001419void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
Oleg Ranevskyycd516372016-01-05 19:54:39 +00001420 // Since commandLineFitsWithinSystemLimits() may underestimate system's capacity
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001421 // if the tool does not support response files, there is a chance/ that things
1422 // will just work without a response file, so we silently just skip it.
Justin Bogner0cd92482015-07-02 22:52:08 +00001423 if (Cmd.getCreator().getResponseFilesSupport() == Tool::RF_None ||
Oleg Ranevskyycd516372016-01-05 19:54:39 +00001424 llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(), Cmd.getArguments()))
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001425 return;
1426
1427 std::string TmpName = GetTemporaryPath("response", "txt");
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00001428 Cmd.setResponseFile(C.addTempFile(C.getArgs().MakeArgString(TmpName)));
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001429}
1430
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001431int Driver::ExecuteCompilation(
1432 Compilation &C,
1433 SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001434 // Just print if -### was present.
1435 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
Hans Wennborgb212b342013-09-12 18:23:34 +00001436 C.getJobs().Print(llvm::errs(), "\n", true);
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001437 return 0;
1438 }
1439
1440 // If there were errors building the compilation, quit now.
Chad Rosierbe10f982011-08-02 17:58:04 +00001441 if (Diags.hasErrorOccurred())
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001442 return 1;
1443
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001444 // Set up response file names for each command, if necessary
Justin Bogner0cd92482015-07-02 22:52:08 +00001445 for (auto &Job : C.getJobs())
1446 setUpResponseFiles(C, Job);
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001447
Justin Bogner0cd92482015-07-02 22:52:08 +00001448 C.ExecuteJobs(C.getJobs(), FailingCommands);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001449
Daniel Dunbar07494792010-05-22 00:37:20 +00001450 // If the command succeeded, we are done.
Chad Rosierdd60e092013-01-29 20:15:05 +00001451 if (FailingCommands.empty())
1452 return 0;
Daniel Dunbar07494792010-05-22 00:37:20 +00001453
Chad Rosierdd60e092013-01-29 20:15:05 +00001454 // Otherwise, remove result files and print extra information about abnormal
1455 // failures.
Nick Desaulniers9d0df312018-10-15 17:39:00 +00001456 int Res = 0;
Douglas Katzman6bbffc42015-06-25 18:51:37 +00001457 for (const auto &CmdPair : FailingCommands) {
Nick Desaulniers9d0df312018-10-15 17:39:00 +00001458 int CommandRes = CmdPair.first;
Douglas Katzman6bbffc42015-06-25 18:51:37 +00001459 const Command *FailingCommand = CmdPair.second;
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001460
Chad Rosierdd60e092013-01-29 20:15:05 +00001461 // Remove result files if we're not saving temps.
Reid Kleckner68eb60b2015-02-02 22:41:48 +00001462 if (!isSaveTempsEnabled()) {
Chad Rosierdd60e092013-01-29 20:15:05 +00001463 const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
1464 C.CleanupFileMap(C.getResultFiles(), JA, true);
1465
1466 // Failure result files are valid unless we crashed.
Nick Desaulniers9d0df312018-10-15 17:39:00 +00001467 if (CommandRes < 0)
Chad Rosierdd60e092013-01-29 20:15:05 +00001468 C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
1469 }
1470
Nick Desaulniers9d0df312018-10-15 17:39:00 +00001471#if LLVM_ON_UNIX
1472 // llvm/lib/Support/Unix/Signals.inc will exit with a special return code
1473 // for SIGPIPE. Do not print diagnostics for this case.
1474 if (CommandRes == EX_IOERR) {
1475 Res = CommandRes;
1476 continue;
1477 }
1478#endif
1479
Chad Rosierdd60e092013-01-29 20:15:05 +00001480 // Print extra information about abnormal failures, if possible.
1481 //
1482 // This is ad-hoc, but we don't want to be excessively noisy. If the result
Justin Bogner5aaf2e72014-06-26 20:59:36 +00001483 // status was 1, assume the command failed normally. In particular, if it
Chad Rosierdd60e092013-01-29 20:15:05 +00001484 // was the compiler then assume it gave a reasonable error code. Failures
1485 // in other tools are less common, and they generally have worse
1486 // diagnostics, so always print the diagnostic there.
1487 const Tool &FailingTool = FailingCommand->getCreator();
1488
Nick Desaulniers9d0df312018-10-15 17:39:00 +00001489 if (!FailingCommand->getCreator().hasGoodDiagnostics() || CommandRes != 1) {
Chad Rosierdd60e092013-01-29 20:15:05 +00001490 // FIXME: See FIXME above regarding result code interpretation.
Nick Desaulniers9d0df312018-10-15 17:39:00 +00001491 if (CommandRes < 0)
Chad Rosierdd60e092013-01-29 20:15:05 +00001492 Diag(clang::diag::err_drv_command_signalled)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001493 << FailingTool.getShortName();
Chad Rosierdd60e092013-01-29 20:15:05 +00001494 else
Nick Desaulniers9d0df312018-10-15 17:39:00 +00001495 Diag(clang::diag::err_drv_command_failed)
1496 << FailingTool.getShortName() << CommandRes;
Chad Rosierdd60e092013-01-29 20:15:05 +00001497 }
Peter Collingbourne119cfaa2011-11-21 00:01:05 +00001498 }
Nick Desaulniers9d0df312018-10-15 17:39:00 +00001499 return Res;
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001500}
1501
Daniel Dunbara7b5e212009-04-15 16:34:29 +00001502void Driver::PrintHelp(bool ShowHidden) const {
Hans Wennborg6ddc6902013-07-27 00:23:45 +00001503 unsigned IncludedFlagsBitmask;
1504 unsigned ExcludedFlagsBitmask;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001505 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
Hans Wennborg797004d2018-11-08 11:27:04 +00001506 getIncludeExcludeOptionFlagMasks(IsCLMode());
Hans Wennborg6ddc6902013-07-27 00:23:45 +00001507
1508 ExcludedFlagsBitmask |= options::NoDriverOption;
1509 if (!ShowHidden)
1510 ExcludedFlagsBitmask |= HelpHidden;
1511
Fangrui Songd0028232018-10-10 00:15:33 +00001512 std::string Usage = llvm::formatv("{0} [options] file...", Name).str();
1513 getOpts().PrintHelp(llvm::outs(), Usage.c_str(), DriverTitle.c_str(),
George Rimar5dbfa4e2017-07-26 09:10:17 +00001514 IncludedFlagsBitmask, ExcludedFlagsBitmask,
1515 /*ShowAllAliases=*/false);
Daniel Dunbar7c925282009-03-31 21:38:17 +00001516}
1517
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001518void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001519 // FIXME: The following handlers should use a callback mechanism, we don't
1520 // know what the client would like to do.
Ted Kremenek4c0df3d2010-01-23 02:11:34 +00001521 OS << getClangFullVersion() << '\n';
Daniel Dunbarb10248802009-03-26 16:09:13 +00001522 const ToolChain &TC = C.getDefaultToolChain();
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001523 OS << "Target: " << TC.getTripleString() << '\n';
Daniel Dunbar10978e42009-06-16 23:32:58 +00001524
1525 // Print the threading model.
Jonathan Roelofsb140a102014-10-03 21:57:44 +00001526 if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
1527 // Don't print if the ToolChain would have barfed on it already
1528 if (TC.isThreadModelSupported(A->getValue()))
1529 OS << "Thread model: " << A->getValue();
1530 } else
1531 OS << "Thread model: " << TC.getThreadModel();
1532 OS << '\n';
Chandler Carruth9ade6a92015-08-05 17:07:33 +00001533
1534 // Print out the install directory.
1535 OS << "InstalledDir: " << InstalledDir << '\n';
Serge Pavlov208ac652018-01-01 13:27:01 +00001536
1537 // If configuration file was used, print its path.
1538 if (!ConfigFile.empty())
1539 OS << "Configuration file: " << ConfigFile << '\n';
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001540}
1541
Chris Lattner86ed5b02010-05-05 05:53:24 +00001542/// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
1543/// option.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001544static void PrintDiagnosticCategories(raw_ostream &OS) {
Argyrios Kyrtzidis0e37afa2011-05-25 05:05:01 +00001545 // Skip the empty category.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001546 for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
1547 ++i)
Argyrios Kyrtzidis0e37afa2011-05-25 05:05:01 +00001548 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
Chris Lattner86ed5b02010-05-05 05:53:24 +00001549}
1550
Yuka Takahashi41789e42018-03-05 08:54:20 +00001551void Driver::HandleAutocompletions(StringRef PassedFlags) const {
Yuka Takahashi503da8f2018-03-05 09:01:31 +00001552 if (PassedFlags == "")
1553 return;
Yuka Takahashi1a895202017-08-29 17:46:46 +00001554 // Print out all options that start with a given argument. This is used for
1555 // shell autocompletion.
1556 std::vector<std::string> SuggestedCompletions;
Yuka Takahashi41789e42018-03-05 08:54:20 +00001557 std::vector<std::string> Flags;
Yuka Takahashi1a895202017-08-29 17:46:46 +00001558
1559 unsigned short DisableFlags =
1560 options::NoDriverOption | options::Unsupported | options::Ignored;
Yuka Takahashi41789e42018-03-05 08:54:20 +00001561
Yuka Takahashi46106f52018-10-24 12:43:25 +00001562 // Distinguish "--autocomplete=-someflag" and "--autocomplete=-someflag,"
1563 // because the latter indicates that the user put space before pushing tab
1564 // which should end up in a file completion.
1565 const bool HasSpace = PassedFlags.endswith(",");
1566
Yuka Takahashi41789e42018-03-05 08:54:20 +00001567 // Parse PassedFlags by "," as all the command-line flags are passed to this
1568 // function separated by ","
1569 StringRef TargetFlags = PassedFlags;
1570 while (TargetFlags != "") {
1571 StringRef CurFlag;
1572 std::tie(CurFlag, TargetFlags) = TargetFlags.split(",");
1573 Flags.push_back(std::string(CurFlag));
Yuka Takahashi1a895202017-08-29 17:46:46 +00001574 }
1575
Yuka Takahashi41789e42018-03-05 08:54:20 +00001576 // We want to show cc1-only options only when clang is invoked with -cc1 or
1577 // -Xclang.
Fangrui Song9ac13a12019-02-10 05:54:57 +00001578 if (llvm::is_contained(Flags, "-Xclang") || llvm::is_contained(Flags, "-cc1"))
Yuka Takahashi41789e42018-03-05 08:54:20 +00001579 DisableFlags &= ~options::NoDriverOption;
1580
1581 StringRef Cur;
1582 Cur = Flags.at(Flags.size() - 1);
1583 StringRef Prev;
1584 if (Flags.size() >= 2) {
1585 Prev = Flags.at(Flags.size() - 2);
1586 SuggestedCompletions = Opts->suggestValueCompletions(Prev, Cur);
1587 }
1588
1589 if (SuggestedCompletions.empty())
1590 SuggestedCompletions = Opts->suggestValueCompletions(Cur, "");
1591
Yuka Takahashi46106f52018-10-24 12:43:25 +00001592 // If Flags were empty, it means the user typed `clang [tab]` where we should
1593 // list all possible flags. If there was no value completion and the user
1594 // pressed tab after a space, we should fall back to a file completion.
1595 // We're printing a newline to be consistent with what we print at the end of
1596 // this function.
1597 if (SuggestedCompletions.empty() && HasSpace && !Flags.empty()) {
1598 llvm::outs() << '\n';
1599 return;
1600 }
1601
Yuka Takahashidf9c7e32018-10-24 08:24:16 +00001602 // When flag ends with '=' and there was no value completion, return empty
1603 // string and fall back to the file autocompletion.
1604 if (SuggestedCompletions.empty() && !Cur.endswith("=")) {
Yuka Takahashi1a895202017-08-29 17:46:46 +00001605 // If the flag is in the form of "--autocomplete=-foo",
1606 // we were requested to print out all option names that start with "-foo".
1607 // For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only".
Yuka Takahashi41789e42018-03-05 08:54:20 +00001608 SuggestedCompletions = Opts->findByPrefix(Cur, DisableFlags);
Yuka Takahashi1a895202017-08-29 17:46:46 +00001609
1610 // We have to query the -W flags manually as they're not in the OptTable.
1611 // TODO: Find a good way to add them to OptTable instead and them remove
1612 // this code.
1613 for (StringRef S : DiagnosticIDs::getDiagnosticFlags())
Yuka Takahashi41789e42018-03-05 08:54:20 +00001614 if (S.startswith(Cur))
Yuka Takahashi1a895202017-08-29 17:46:46 +00001615 SuggestedCompletions.push_back(S);
Yuka Takahashi1a895202017-08-29 17:46:46 +00001616 }
1617
1618 // Sort the autocomplete candidates so that shells print them out in a
1619 // deterministic order. We could sort in any way, but we chose
1620 // case-insensitive sorting for consistency with the -help option
1621 // which prints out options in the case-insensitive alphabetical order.
Fangrui Song55fab262018-09-26 22:16:28 +00001622 llvm::sort(SuggestedCompletions, [](StringRef A, StringRef B) {
1623 if (int X = A.compare_lower(B))
1624 return X < 0;
1625 return A.compare(B) > 0;
1626 });
Yuka Takahashi1a895202017-08-29 17:46:46 +00001627
1628 llvm::outs() << llvm::join(SuggestedCompletions, "\n") << '\n';
1629}
1630
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001631bool Driver::HandleImmediateArgs(const Compilation &C) {
Daniel Dunbar18974bd2010-06-11 22:00:19 +00001632 // The order these options are handled in gcc is all over the place, but we
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001633 // don't expect inconsistencies w.r.t. that to matter in practice.
Daniel Dunbar7c925282009-03-31 21:38:17 +00001634
Daniel Dunbar1b09e042010-09-17 02:47:28 +00001635 if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
1636 llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
1637 return false;
1638 }
1639
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001640 if (C.getArgs().hasArg(options::OPT_dumpversion)) {
Daniel Dunbare26e5002011-01-12 00:43:47 +00001641 // Since -dumpversion is only implemented for pedantic GCC compatibility, we
1642 // return an answer which matches our definition of __VERSION__.
1643 //
1644 // If we want to return a more correct answer some day, then we should
1645 // introduce a non-pedantically GCC compatible mode to Clang in which we
1646 // provide sensible definitions for -dumpversion, __VERSION__, etc.
1647 llvm::outs() << "4.2.1\n";
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001648 return false;
1649 }
Daniel Dunbarfb3d7472010-06-14 21:23:12 +00001650
Chris Lattner86ed5b02010-05-05 05:53:24 +00001651 if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
1652 PrintDiagnosticCategories(llvm::outs());
1653 return false;
1654 }
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001655
James Molloya3c85b82012-05-01 14:57:16 +00001656 if (C.getArgs().hasArg(options::OPT_help) ||
Daniel Dunbara7b5e212009-04-15 16:34:29 +00001657 C.getArgs().hasArg(options::OPT__help_hidden)) {
1658 PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
Daniel Dunbar7c925282009-03-31 21:38:17 +00001659 return false;
1660 }
1661
Daniel Dunbarb0006ae2009-04-02 15:05:41 +00001662 if (C.getArgs().hasArg(options::OPT__version)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001663 // Follow gcc behavior and use stdout for --version and stderr for -v.
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001664 PrintVersion(C, llvm::outs());
Daniel Dunbarb0006ae2009-04-02 15:05:41 +00001665 return false;
1666 }
1667
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001668 if (C.getArgs().hasArg(options::OPT_v) ||
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001669 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001670 PrintVersion(C, llvm::errs());
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001671 SuppressMissingInputWarning = true;
1672 }
1673
Serge Pavlov208ac652018-01-01 13:27:01 +00001674 if (C.getArgs().hasArg(options::OPT_v)) {
1675 if (!SystemConfigDir.empty())
1676 llvm::errs() << "System configuration file directory: "
1677 << SystemConfigDir << "\n";
1678 if (!UserConfigDir.empty())
1679 llvm::errs() << "User configuration file directory: "
1680 << UserConfigDir << "\n";
1681 }
1682
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001683 const ToolChain &TC = C.getDefaultToolChain();
Chandler Carruth0ae39aa2013-07-30 17:57:09 +00001684
1685 if (C.getArgs().hasArg(options::OPT_v))
1686 TC.printVerboseInfo(llvm::errs());
1687
Meador Inge51208a32017-04-04 21:46:50 +00001688 if (C.getArgs().hasArg(options::OPT_print_resource_dir)) {
Meador Ingea9113952017-04-05 22:27:20 +00001689 llvm::outs() << ResourceDir << '\n';
Meador Inge51208a32017-04-04 21:46:50 +00001690 return false;
1691 }
1692
Daniel Dunbard972e222009-03-20 04:37:21 +00001693 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
1694 llvm::outs() << "programs: =";
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001695 bool separator = false;
1696 for (const std::string &Path : TC.getProgramPaths()) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001697 if (separator)
1698 llvm::outs() << ':';
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001699 llvm::outs() << Path;
1700 separator = true;
Daniel Dunbard972e222009-03-20 04:37:21 +00001701 }
1702 llvm::outs() << "\n";
Peter Collingbournefa9771f2011-09-06 02:08:31 +00001703 llvm::outs() << "libraries: =" << ResourceDir;
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001704
Sebastian Pop980920a2012-04-16 04:16:43 +00001705 StringRef sysroot = C.getSysRoot();
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001706
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001707 for (const std::string &Path : TC.getFilePaths()) {
1708 // Always print a separator. ResourceDir was the first item shown.
Peter Collingbournefa9771f2011-09-06 02:08:31 +00001709 llvm::outs() << ':';
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001710 // Interpretation of leading '=' is needed only for NetBSD.
1711 if (Path[0] == '=')
Douglas Katzman26eabf62015-06-24 15:10:30 +00001712 llvm::outs() << sysroot << Path.substr(1);
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001713 else
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001714 llvm::outs() << Path;
Daniel Dunbard972e222009-03-20 04:37:21 +00001715 }
1716 llvm::outs() << "\n";
Daniel Dunbar7c925282009-03-31 21:38:17 +00001717 return false;
Daniel Dunbard972e222009-03-20 04:37:21 +00001718 }
1719
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001720 // FIXME: The following handlers should use a callback mechanism, we don't
1721 // know what the client would like to do.
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001722 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001723 llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001724 return false;
1725 }
1726
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001727 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
Saleem Abdulrasoole5f3cf82018-05-01 18:40:42 +00001728 StringRef ProgName = A->getValue();
1729
1730 // Null program name cannot have a path.
1731 if (! ProgName.empty())
1732 llvm::outs() << GetProgramPath(ProgName, TC);
1733
1734 llvm::outs() << "\n";
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001735 return false;
1736 }
1737
Yuka Takahashic8068db2017-05-23 18:39:08 +00001738 if (Arg *A = C.getArgs().getLastArg(options::OPT_autocomplete)) {
Yuka Takahashiba5d4af2017-06-20 16:31:31 +00001739 StringRef PassedFlags = A->getValue();
Yuka Takahashi41789e42018-03-05 08:54:20 +00001740 HandleAutocompletions(PassedFlags);
Yuka Takahashic8068db2017-05-23 18:39:08 +00001741 return false;
1742 }
1743
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001744 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
Michal Gorny7cfe4802016-10-10 12:23:40 +00001745 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(C.getArgs());
Leo Li23bb21c2017-08-24 01:51:51 +00001746 const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
1747 RegisterEffectiveTriple TripleRAII(TC, Triple);
Michal Gorny7cfe4802016-10-10 12:23:40 +00001748 switch (RLT) {
1749 case ToolChain::RLT_CompilerRT:
1750 llvm::outs() << TC.getCompilerRT(C.getArgs(), "builtins") << "\n";
1751 break;
1752 case ToolChain::RLT_Libgcc:
1753 llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
1754 break;
1755 }
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001756 return false;
1757 }
1758
Daniel Dunbar1b3ec3a2009-06-16 23:25:22 +00001759 if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
Douglas Katzmana34b7bf2015-06-30 19:32:57 +00001760 for (const Multilib &Multilib : TC.getMultilibs())
1761 llvm::outs() << Multilib << "\n";
Daniel Dunbar1b3ec3a2009-06-16 23:25:22 +00001762 return false;
1763 }
1764
Jonathan Roelofs2cea1be2014-02-12 03:21:20 +00001765 if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
Christian Bruel6ccc4a72018-09-06 14:03:44 +00001766 const Multilib &Multilib = TC.getMultilib();
1767 if (Multilib.gccSuffix().empty())
1768 llvm::outs() << ".\n";
1769 else {
1770 StringRef Suffix(Multilib.gccSuffix());
1771 assert(Suffix.front() == '/');
1772 llvm::outs() << Suffix.substr(1) << "\n";
Jonathan Roelofs3fa96d82014-02-12 01:36:51 +00001773 }
Jonathan Roelofs0e7ec602014-02-12 01:29:25 +00001774 return false;
1775 }
Petr Hosekbc86a992018-08-16 00:22:03 +00001776
1777 if (C.getArgs().hasArg(options::OPT_print_target_triple)) {
1778 llvm::outs() << TC.getTripleString() << "\n";
1779 return false;
1780 }
1781
1782 if (C.getArgs().hasArg(options::OPT_print_effective_triple)) {
1783 const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
1784 llvm::outs() << Triple.getTriple() << "\n";
1785 return false;
1786 }
1787
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001788 return true;
1789}
1790
Douglas Katzmanfd528672015-06-11 15:05:22 +00001791// Display an action graph human-readably. Action A is the "sink" node
1792// and latest-occuring action. Traversal is in pre-order, visiting the
1793// inputs to each action before printing the action itself.
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001794static unsigned PrintActions1(const Compilation &C, Action *A,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001795 std::map<Action *, unsigned> &Ids) {
Douglas Katzmanfd528672015-06-11 15:05:22 +00001796 if (Ids.count(A)) // A was already visited.
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001797 return Ids[A];
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001798
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001799 std::string str;
1800 llvm::raw_string_ostream os(str);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001801
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001802 os << Action::getClassName(A->getKind()) << ", ";
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001803 if (InputAction *IA = dyn_cast<InputAction>(A)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001804 os << "\"" << IA->getInputArg().getValue() << "\"";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001805 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001806 os << '"' << BIA->getArchName() << '"' << ", {"
Nico Weber5a459f82016-02-23 19:30:43 +00001807 << PrintActions1(C, *BIA->input_begin(), Ids) << "}";
Samuel Antaod06239d2016-07-15 23:13:27 +00001808 } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
1809 bool IsFirst = true;
1810 OA->doOnEachDependence(
1811 [&](Action *A, const ToolChain *TC, const char *BoundArch) {
1812 // E.g. for two CUDA device dependences whose bound arch is sm_20 and
1813 // sm_35 this will generate:
1814 // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
1815 // (nvptx64-nvidia-cuda:sm_35) {#ID}
1816 if (!IsFirst)
1817 os << ", ";
1818 os << '"';
1819 if (TC)
1820 os << A->getOffloadingKindPrefix();
1821 else
1822 os << "host";
1823 os << " (";
1824 os << TC->getTriple().normalize();
1825
1826 if (BoundArch)
1827 os << ":" << BoundArch;
1828 os << ")";
1829 os << '"';
1830 os << " {" << PrintActions1(C, A, Ids) << "}";
1831 IsFirst = false;
1832 });
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001833 } else {
Samuel Antaod06239d2016-07-15 23:13:27 +00001834 const ActionList *AL = &A->getInputs();
Artem Belevich0ff05cd2015-07-13 23:27:56 +00001835
Artem Belevich23256752015-09-22 17:23:09 +00001836 if (AL->size()) {
1837 const char *Prefix = "{";
1838 for (Action *PreRequisite : *AL) {
1839 os << Prefix << PrintActions1(C, PreRequisite, Ids);
1840 Prefix = ", ";
1841 }
1842 os << "}";
1843 } else
1844 os << "{}";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001845 }
1846
Samuel Antaod06239d2016-07-15 23:13:27 +00001847 // Append offload info for all options other than the offloading action
1848 // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
1849 std::string offload_str;
1850 llvm::raw_string_ostream offload_os(offload_str);
1851 if (!isa<OffloadAction>(A)) {
1852 auto S = A->getOffloadingKindPrefix();
1853 if (!S.empty()) {
1854 offload_os << ", (" << S;
1855 if (A->getOffloadingArch())
1856 offload_os << ", " << A->getOffloadingArch();
1857 offload_os << ")";
1858 }
1859 }
1860
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001861 unsigned Id = Ids.size();
1862 Ids[A] = Id;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001863 llvm::errs() << Id << ": " << os.str() << ", "
Samuel Antaod06239d2016-07-15 23:13:27 +00001864 << types::getTypeName(A->getType()) << offload_os.str() << "\n";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001865
1866 return Id;
1867}
1868
Douglas Katzmanfd528672015-06-11 15:05:22 +00001869// Print the action graphs in a compilation C.
1870// For example "clang -c file1.c file2.c" is composed of two subgraphs.
Daniel Dunbareb843be2009-03-18 03:13:20 +00001871void Driver::PrintActions(const Compilation &C) const {
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001872 std::map<Action *, unsigned> Ids;
1873 for (Action *A : C.getActions())
1874 PrintActions1(C, A, Ids);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001875}
1876
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001877/// Check whether the given input tree contains any compilation or
Joerg Sonnenberger5fe4a7d2011-05-06 14:05:11 +00001878/// assembly actions.
1879static bool ContainsCompileOrAssembleAction(const Action *A) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001880 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
Bob Wilson23a55f12014-12-21 07:00:00 +00001881 isa<AssembleJobAction>(A))
Daniel Dunbar00d3d8e2010-06-29 16:38:33 +00001882 return true;
1883
Nico Weber5a459f82016-02-23 19:30:43 +00001884 for (const Action *Input : A->inputs())
Nico Weberfb80f962015-09-19 21:36:51 +00001885 if (ContainsCompileOrAssembleAction(Input))
Daniel Dunbar00d3d8e2010-06-29 16:38:33 +00001886 return true;
1887
1888 return false;
1889}
1890
Artem Belevich5e2a3ec2015-11-17 22:28:40 +00001891void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
1892 const InputList &BAInputs) const {
1893 DerivedArgList &Args = C.getArgs();
1894 ActionList &Actions = C.getActions();
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001895 llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
1896 // Collect the list of architectures. Duplicates are allowed, but should only
1897 // be handled once (in the order seen).
Daniel Dunbare5dc4822009-03-13 20:33:35 +00001898 llvm::StringSet<> ArchNames;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001899 SmallVector<const char *, 4> Archs;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00001900 for (Arg *A : Args) {
Daniel Dunbar0bfb21e2009-11-19 03:26:40 +00001901 if (A->getOption().matches(options::OPT_arch)) {
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001902 // Validate the option here; we don't save the type here because its
1903 // particular spelling may participate in other driver choices.
1904 llvm::Triple::ArchType Arch =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001905 tools::darwin::getArchTypeForMachOArchName(A->getValue());
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001906 if (Arch == llvm::Triple::UnknownArch) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001907 Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001908 continue;
1909 }
1910
Daniel Dunbar2da02722009-03-19 07:55:12 +00001911 A->claim();
David Blaikie61b86d42014-11-19 02:56:13 +00001912 if (ArchNames.insert(A->getValue()).second)
Richard Smithbd55daf2012-11-01 04:30:05 +00001913 Archs.push_back(A->getValue());
Daniel Dunbarf479c122009-03-12 18:40:18 +00001914 }
1915 }
1916
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001917 // When there is no explicit arch for this platform, make sure we still bind
1918 // the architecture (to the default) so that -Xarch_ is handled correctly.
Daniel Dunbareb843be2009-03-18 03:13:20 +00001919 if (!Archs.size())
Daniel Dunbarc3bd9f52012-11-08 03:38:26 +00001920 Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
Daniel Dunbarf479c122009-03-12 18:40:18 +00001921
Daniel Dunbarf479c122009-03-12 18:40:18 +00001922 ActionList SingleActions;
Justin Lebar0f3474c2016-02-11 02:00:50 +00001923 BuildActions(C, Args, BAInputs, SingleActions);
Daniel Dunbarf479c122009-03-12 18:40:18 +00001924
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001925 // Add in arch bindings for every top level action, as well as lipo and
1926 // dsymutil steps if needed.
Nico Weberfb80f962015-09-19 21:36:51 +00001927 for (Action* Act : SingleActions) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001928 // Make sure we can lipo this kind of output. If not (and it is an actual
1929 // output) then we disallow, since we can't create an output file with the
1930 // right name without overwriting it. We could remove this oddity by just
1931 // changing the output names to include the arch, which would also fix
Daniel Dunbarf479c122009-03-12 18:40:18 +00001932 // -save-temps. Compatibility wins for now.
1933
Daniel Dunbare2ca3bd2009-03-13 17:46:02 +00001934 if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
Daniel Dunbarf479c122009-03-12 18:40:18 +00001935 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001936 << types::getTypeName(Act->getType());
Daniel Dunbarf479c122009-03-12 18:40:18 +00001937
1938 ActionList Inputs;
Justin Lebar41094612016-01-11 23:07:27 +00001939 for (unsigned i = 0, e = Archs.size(); i != e; ++i)
1940 Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
Daniel Dunbarf479c122009-03-12 18:40:18 +00001941
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001942 // Lipo if necessary, we do it this way because we need to set the arch flag
1943 // so that -Xarch_ gets overwritten.
Daniel Dunbarf479c122009-03-12 18:40:18 +00001944 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
1945 Actions.append(Inputs.begin(), Inputs.end());
1946 else
Justin Lebar41094612016-01-11 23:07:27 +00001947 Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001948
Eric Christopher65c05fa2012-02-06 19:43:51 +00001949 // Handle debug info queries.
1950 Arg *A = Args.getLastArg(options::OPT_g_Group);
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001951 if (A && !A->getOption().matches(options::OPT_g0) &&
1952 !A->getOption().matches(options::OPT_gstabs) &&
1953 ContainsCompileOrAssembleAction(Actions.back())) {
Chad Rosier62135492012-07-09 17:31:28 +00001954
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001955 // Add a 'dsymutil' step if necessary, when debug info is enabled and we
1956 // have a compile input. We need to run 'dsymutil' ourselves in such cases
Eric Christopher776c26f2013-01-28 17:39:03 +00001957 // because the debug info will refer to a temporary object file which
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001958 // will be removed at the end of the compilation process.
1959 if (Act->getType() == types::TY_Image) {
1960 ActionList Inputs;
1961 Inputs.push_back(Actions.back());
1962 Actions.pop_back();
Justin Lebar41094612016-01-11 23:07:27 +00001963 Actions.push_back(
1964 C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001965 }
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001966
Ben Langmuir9b9a8d32014-02-06 18:53:25 +00001967 // Verify the debug info output.
Alp Tokere9d2bfc2014-01-17 02:06:23 +00001968 if (Args.hasArg(options::OPT_verify_debug_info)) {
Justin Lebar41094612016-01-11 23:07:27 +00001969 Action* LastAction = Actions.back();
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001970 Actions.pop_back();
Justin Lebar41094612016-01-11 23:07:27 +00001971 Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
1972 LastAction, types::TY_Nothing));
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001973 }
1974 }
Daniel Dunbarf479c122009-03-12 18:40:18 +00001975 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001976}
1977
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001978/// Check that the file referenced by Value exists. If it doesn't,
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001979/// issue a diagnostic and return false.
Alp Toker8c8a8752013-12-03 06:53:35 +00001980static bool DiagnoseInputExistence(const Driver &D, const DerivedArgList &Args,
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001981 StringRef Value, types::ID Ty) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001982 if (!D.getCheckInputsExist())
1983 return true;
1984
1985 // stdin always exists.
1986 if (Value == "-")
1987 return true;
1988
1989 SmallString<64> Path(Value);
1990 if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
Yaron Keren92e1b622015-03-18 10:17:07 +00001991 if (!llvm::sys::path::is_absolute(Path)) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001992 SmallString<64> Directory(WorkDir->getValue());
1993 llvm::sys::path::append(Directory, Value);
1994 Path.assign(Directory);
1995 }
1996 }
1997
Sam McCall2c782472018-11-08 16:57:01 +00001998 if (D.getVFS().exists(Path))
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001999 return true;
2000
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00002001 if (D.IsCLMode()) {
2002 if (!llvm::sys::path::is_absolute(Twine(Path)) &&
2003 llvm::sys::Process::FindInEnvPath("LIB", Value))
2004 return true;
2005
2006 if (Args.hasArg(options::OPT__SLASH_link) && Ty == types::TY_Object) {
2007 // Arguments to the /link flag might cause the linker to search for object
2008 // and library files in paths we don't know about. Don't error in such
2009 // cases.
2010 return true;
2011 }
2012 }
Hans Wennborg23d26a32014-06-18 17:21:50 +00002013
Yaron Keren92e1b622015-03-18 10:17:07 +00002014 D.Diag(clang::diag::err_drv_no_such_file) << Path;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00002015 return false;
2016}
2017
Chad Rosierecdede82011-08-12 22:08:57 +00002018// Construct a the list of inputs and their types.
Hans Wennborg55362852014-05-02 22:55:30 +00002019void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
Chad Rosierecdede82011-08-12 22:08:57 +00002020 InputList &Inputs) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002021 // Track the current user specified (-x) input. We also explicitly track the
2022 // argument used to set the type; we only want to claim the type when we
2023 // actually use it, so we warn about unused -x arguments.
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00002024 types::ID InputType = types::TY_Nothing;
Craig Topper92fc2df2014-05-17 16:56:41 +00002025 Arg *InputTypeArg = nullptr;
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00002026
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00002027 // The last /TC or /TP option sets the input type to C or C++ globally.
Ehsan Akhgaric249abb2014-09-12 21:44:24 +00002028 if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
2029 options::OPT__SLASH_TP)) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00002030 InputTypeArg = TCTP;
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00002031 InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002032 ? types::TY_C
2033 : types::TY_CXX;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00002034
Richard Smith0aef3052017-02-18 01:14:43 +00002035 Arg *Previous = nullptr;
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00002036 bool ShowNote = false;
Richard Smith0aef3052017-02-18 01:14:43 +00002037 for (Arg *A : Args.filtered(options::OPT__SLASH_TC, options::OPT__SLASH_TP)) {
2038 if (Previous) {
2039 Diag(clang::diag::warn_drv_overriding_flag_option)
2040 << Previous->getSpelling() << A->getSpelling();
2041 ShowNote = true;
2042 }
2043 Previous = A;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00002044 }
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00002045 if (ShowNote)
2046 Diag(clang::diag::note_drv_t_option_is_global);
Hans Wennborg6ee64d52013-08-06 00:20:31 +00002047
2048 // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
2049 assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
2050 }
2051
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00002052 for (Arg *A : Args) {
Michael J. Spencerad3ccc32012-08-20 21:41:17 +00002053 if (A->getOption().getKind() == Option::InputClass) {
Richard Smithbd55daf2012-11-01 04:30:05 +00002054 const char *Value = A->getValue();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002055 types::ID Ty = types::TY_INVALID;
2056
2057 // Infer the input type if necessary.
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00002058 if (InputType == types::TY_Nothing) {
2059 // If there was an explicit arg for this, claim it.
2060 if (InputTypeArg)
2061 InputTypeArg->claim();
2062
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002063 // stdin must be handled specially.
2064 if (memcmp(Value, "-", 2) == 0) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002065 // If running with -E, treat as a C input (this changes the builtin
2066 // macros, for example). This may be overridden by -ObjC below.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002067 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002068 // Otherwise emit an error but still use a valid type to avoid
2069 // spurious errors (e.g., no inputs).
Hans Wennborg70850d82013-07-18 20:29:38 +00002070 if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
Hans Wennborgcfdd8b52014-01-29 01:04:40 +00002071 Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
2072 : clang::diag::err_drv_unknown_stdin_type);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002073 Ty = types::TY_C;
2074 } else {
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00002075 // Otherwise lookup by extension.
Reid Klecknera643e642018-12-26 21:04:08 +00002076 // Fallback is C if invoked as C preprocessor, C++ if invoked with
2077 // clang-cl /E, or Object otherwise.
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00002078 // We use a host hook here because Darwin at least has its own
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002079 // idea of what .s is.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002080 if (const char *Ext = strrchr(Value, '.'))
Daniel Dunbarcc7df6c2010-08-02 05:43:56 +00002081 Ty = TC.LookupTypeForExtension(Ext + 1);
Daniel Dunbarea9f0322009-03-20 23:39:23 +00002082
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00002083 if (Ty == types::TY_INVALID) {
Hans Wennborg70850d82013-07-18 20:29:38 +00002084 if (CCCIsCPP())
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00002085 Ty = types::TY_C;
Reid Klecknera643e642018-12-26 21:04:08 +00002086 else if (IsCLMode() && Args.hasArgNoClaim(options::OPT_E))
2087 Ty = types::TY_CXX;
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00002088 else
2089 Ty = types::TY_Object;
2090 }
Daniel Dunbar0ac94452010-02-17 20:32:58 +00002091
2092 // If the driver is invoked as C++ compiler (like clang++ or c++) it
2093 // should autodetect some input files as C++ for g++ compatibility.
Hans Wennborg70850d82013-07-18 20:29:38 +00002094 if (CCCIsCXX()) {
Daniel Dunbar0ac94452010-02-17 20:32:58 +00002095 types::ID OldTy = Ty;
2096 Ty = types::lookupCXXTypeForCType(Ty);
2097
2098 if (Ty != OldTy)
2099 Diag(clang::diag::warn_drv_treating_input_as_cxx)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002100 << getTypeName(OldTy) << getTypeName(Ty);
Daniel Dunbar0ac94452010-02-17 20:32:58 +00002101 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002102 }
2103
Daniel Dunbar82b22102009-05-18 21:47:54 +00002104 // -ObjC and -ObjC++ override the default language, but only for "source
2105 // files". We just treat everything that isn't a linker input as a
2106 // source file.
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002107 //
Daniel Dunbar82b22102009-05-18 21:47:54 +00002108 // FIXME: Clean this up if we move the phase sequence into the type.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002109 if (Ty != types::TY_Object) {
2110 if (Args.hasArg(options::OPT_ObjC))
2111 Ty = types::TY_ObjC;
2112 else if (Args.hasArg(options::OPT_ObjCXX))
2113 Ty = types::TY_ObjCXX;
2114 }
2115 } else {
2116 assert(InputTypeArg && "InputType set w/o InputTypeArg");
Ehsan Akhgari7e954ea2014-09-12 18:15:10 +00002117 if (!InputTypeArg->getOption().matches(options::OPT_x)) {
2118 // If emulating cl.exe, make sure that /TC and /TP don't affect input
2119 // object files.
2120 const char *Ext = strrchr(Value, '.');
2121 if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
2122 Ty = types::TY_Object;
2123 }
2124 if (Ty == types::TY_INVALID) {
2125 Ty = InputType;
2126 InputTypeArg->claim();
2127 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002128 }
2129
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00002130 if (DiagnoseInputExistence(*this, Args, Value, Ty))
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002131 Inputs.push_back(std::make_pair(Ty, A));
2132
Hans Wennborg6ee64d52013-08-06 00:20:31 +00002133 } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
2134 StringRef Value = A->getValue();
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00002135 if (DiagnoseInputExistence(*this, Args, Value, types::TY_C)) {
David Blaikie0aaa7622017-01-13 17:34:15 +00002136 Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
Hans Wennborg6ee64d52013-08-06 00:20:31 +00002137 Inputs.push_back(std::make_pair(types::TY_C, InputArg));
2138 }
2139 A->claim();
2140 } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
2141 StringRef Value = A->getValue();
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00002142 if (DiagnoseInputExistence(*this, Args, Value, types::TY_CXX)) {
David Blaikie0aaa7622017-01-13 17:34:15 +00002143 Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
Hans Wennborg6ee64d52013-08-06 00:20:31 +00002144 Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
2145 }
2146 A->claim();
Michael J. Spencer66e2b202012-10-19 22:37:06 +00002147 } else if (A->getOption().hasFlag(options::LinkerInput)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002148 // Just treat as object type, we could make a special type for this if
2149 // necessary.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002150 Inputs.push_back(std::make_pair(types::TY_Object, A));
2151
Daniel Dunbar0bfb21e2009-11-19 03:26:40 +00002152 } else if (A->getOption().matches(options::OPT_x)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002153 InputTypeArg = A;
Richard Smithbd55daf2012-11-01 04:30:05 +00002154 InputType = types::lookupTypeForTypeSpecifier(A->getValue());
Chad Rosier706c2352012-04-07 00:01:31 +00002155 A->claim();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002156
2157 // Follow gcc behavior and treat as linker input for invalid -x
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002158 // options. Its not clear why we shouldn't just revert to unknown; but
Michael J. Spencer1a4fe8c2010-12-17 21:22:33 +00002159 // this isn't very important, we might as well be bug compatible.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002160 if (!InputType) {
Richard Smithbd55daf2012-11-01 04:30:05 +00002161 Diag(clang::diag::err_drv_unknown_language) << A->getValue();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002162 InputType = types::TY_Object;
2163 }
Hans Wennborg091f1b62017-01-27 17:09:41 +00002164 } else if (A->getOption().getID() == options::OPT__SLASH_U) {
2165 assert(A->getNumValues() == 1 && "The /U option has one value.");
2166 StringRef Val = A->getValue(0);
2167 if (Val.find_first_of("/\\") != StringRef::npos) {
2168 // Warn about e.g. "/Users/me/myfile.c".
2169 Diag(diag::warn_slash_u_filename) << Val;
2170 Diag(diag::note_use_dashdash);
2171 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002172 }
2173 }
Hans Wennborg70850d82013-07-18 20:29:38 +00002174 if (CCCIsCPP() && Inputs.empty()) {
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00002175 // If called as standalone preprocessor, stdin is processed
2176 // if no other input is present.
David Blaikie0aaa7622017-01-13 17:34:15 +00002177 Arg *A = MakeInputArg(Args, *Opts, "-");
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00002178 Inputs.push_back(std::make_pair(types::TY_C, A));
2179 }
Chad Rosierecdede82011-08-12 22:08:57 +00002180}
2181
Samuel Antao64e965e2016-09-30 15:34:19 +00002182namespace {
2183/// Provides a convenient interface for different programming models to generate
2184/// the required device actions.
2185class OffloadingActionBuilder final {
2186 /// Flag used to trace errors in the builder.
2187 bool IsValid = false;
2188
2189 /// The compilation that is using this builder.
2190 Compilation &C;
2191
Samuel Antao64e965e2016-09-30 15:34:19 +00002192 /// Map between an input argument and the offload kinds used to process it.
2193 std::map<const Arg *, unsigned> InputArgToOffloadKindMap;
2194
2195 /// Builder interface. It doesn't build anything or keep any state.
2196 class DeviceActionBuilder {
2197 public:
2198 typedef llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PhasesTy;
2199
2200 enum ActionBuilderReturnCode {
2201 // The builder acted successfully on the current action.
2202 ABRT_Success,
2203 // The builder didn't have to act on the current action.
2204 ABRT_Inactive,
2205 // The builder was successful and requested the host action to not be
2206 // generated.
2207 ABRT_Ignore_Host,
2208 };
2209
2210 protected:
2211 /// Compilation associated with this builder.
2212 Compilation &C;
2213
2214 /// Tool chains associated with this builder. The same programming
2215 /// model may have associated one or more tool chains.
2216 SmallVector<const ToolChain *, 2> ToolChains;
2217
2218 /// The derived arguments associated with this builder.
2219 DerivedArgList &Args;
2220
2221 /// The inputs associated with this builder.
2222 const Driver::InputList &Inputs;
2223
2224 /// The associated offload kind.
2225 Action::OffloadKind AssociatedOffloadKind = Action::OFK_None;
2226
2227 public:
2228 DeviceActionBuilder(Compilation &C, DerivedArgList &Args,
2229 const Driver::InputList &Inputs,
2230 Action::OffloadKind AssociatedOffloadKind)
2231 : C(C), Args(Args), Inputs(Inputs),
2232 AssociatedOffloadKind(AssociatedOffloadKind) {}
2233 virtual ~DeviceActionBuilder() {}
2234
2235 /// Fill up the array \a DA with all the device dependences that should be
2236 /// added to the provided host action \a HostAction. By default it is
2237 /// inactive.
2238 virtual ActionBuilderReturnCode
Samuel Antao28c4f182016-10-27 17:08:03 +00002239 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2240 phases::ID CurPhase, phases::ID FinalPhase,
2241 PhasesTy &Phases) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002242 return ABRT_Inactive;
2243 }
2244
2245 /// Update the state to include the provided host action \a HostAction as a
2246 /// dependency of the current device action. By default it is inactive.
2247 virtual ActionBuilderReturnCode addDeviceDepences(Action *HostAction) {
2248 return ABRT_Inactive;
2249 }
2250
2251 /// Append top level actions generated by the builder. Return true if errors
2252 /// were found.
2253 virtual void appendTopLevelActions(ActionList &AL) {}
2254
2255 /// Append linker actions generated by the builder. Return true if errors
2256 /// were found.
2257 virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {}
2258
2259 /// Initialize the builder. Return true if any initialization errors are
2260 /// found.
2261 virtual bool initialize() { return false; }
2262
Samuel Antao69d6f312016-10-27 17:50:43 +00002263 /// Return true if the builder can use bundling/unbundling.
2264 virtual bool canUseBundlerUnbundler() const { return false; }
2265
Samuel Antao64e965e2016-09-30 15:34:19 +00002266 /// Return true if this builder is valid. We have a valid builder if we have
2267 /// associated device tool chains.
2268 bool isValid() { return !ToolChains.empty(); }
2269
2270 /// Return the associated offload kind.
2271 Action::OffloadKind getAssociatedOffloadKind() {
2272 return AssociatedOffloadKind;
2273 }
2274 };
2275
Yaxun Liu3af038b2018-05-30 00:49:10 +00002276 /// Base class for CUDA/HIP action builder. It injects device code in
2277 /// the host backend action.
2278 class CudaActionBuilderBase : public DeviceActionBuilder {
2279 protected:
Samuel Antao64e965e2016-09-30 15:34:19 +00002280 /// Flags to signal if the user requested host-only or device-only
2281 /// compilation.
2282 bool CompileHostOnly = false;
2283 bool CompileDeviceOnly = false;
2284
2285 /// List of GPU architectures to use in this compilation.
2286 SmallVector<CudaArch, 4> GpuArchList;
2287
2288 /// The CUDA actions for the current input.
2289 ActionList CudaDeviceActions;
2290
2291 /// The CUDA fat binary if it was generated for the current input.
2292 Action *CudaFatBinary = nullptr;
2293
2294 /// Flag that is set to true if this builder acted on the current input.
2295 bool IsActive = false;
Yaxun Liu3af038b2018-05-30 00:49:10 +00002296 public:
2297 CudaActionBuilderBase(Compilation &C, DerivedArgList &Args,
2298 const Driver::InputList &Inputs,
2299 Action::OffloadKind OFKind)
2300 : DeviceActionBuilder(C, Args, Inputs, OFKind) {}
Samuel Antao64e965e2016-09-30 15:34:19 +00002301
Yaxun Liu3af038b2018-05-30 00:49:10 +00002302 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2303 // While generating code for CUDA, we only depend on the host input action
2304 // to trigger the creation of all the CUDA device actions.
2305
2306 // If we are dealing with an input action, replicate it for each GPU
2307 // architecture. If we are in host-only mode we return 'success' so that
2308 // the host uses the CUDA offload kind.
2309 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2310 assert(!GpuArchList.empty() &&
2311 "We should have at least one GPU architecture.");
2312
2313 // If the host input is not CUDA or HIP, we don't need to bother about
2314 // this input.
2315 if (IA->getType() != types::TY_CUDA &&
2316 IA->getType() != types::TY_HIP) {
2317 // The builder will ignore this input.
2318 IsActive = false;
2319 return ABRT_Inactive;
2320 }
2321
2322 // Set the flag to true, so that the builder acts on the current input.
2323 IsActive = true;
2324
2325 if (CompileHostOnly)
2326 return ABRT_Success;
2327
2328 // Replicate inputs for each GPU architecture.
2329 auto Ty = IA->getType() == types::TY_HIP ? types::TY_HIP_DEVICE
2330 : types::TY_CUDA_DEVICE;
2331 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2332 CudaDeviceActions.push_back(
2333 C.MakeAction<InputAction>(IA->getInputArg(), Ty));
2334 }
2335
2336 return ABRT_Success;
2337 }
2338
2339 // If this is an unbundling action use it as is for each CUDA toolchain.
2340 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2341 CudaDeviceActions.clear();
Aaron Enye Shibea57bb2019-01-04 19:05:41 +00002342 auto *IA = cast<InputAction>(UA->getInputs().back());
2343 std::string FileName = IA->getInputArg().getAsString(Args);
2344 // Check if the type of the file is the same as the action. Do not
2345 // unbundle it if it is not. Do not unbundle .so files, for example,
2346 // which are not object files.
2347 if (IA->getType() == types::TY_Object &&
2348 (!llvm::sys::path::has_extension(FileName) ||
2349 types::lookupTypeForExtension(
2350 llvm::sys::path::extension(FileName).drop_front()) !=
2351 types::TY_Object))
2352 return ABRT_Inactive;
2353
Yaxun Liu3af038b2018-05-30 00:49:10 +00002354 for (auto Arch : GpuArchList) {
2355 CudaDeviceActions.push_back(UA);
2356 UA->registerDependentActionInfo(ToolChains[0], CudaArchToString(Arch),
2357 AssociatedOffloadKind);
2358 }
2359 return ABRT_Success;
2360 }
2361
2362 return IsActive ? ABRT_Success : ABRT_Inactive;
2363 }
2364
2365 void appendTopLevelActions(ActionList &AL) override {
2366 // Utility to append actions to the top level list.
2367 auto AddTopLevel = [&](Action *A, CudaArch BoundArch) {
2368 OffloadAction::DeviceDependences Dep;
2369 Dep.add(*A, *ToolChains.front(), CudaArchToString(BoundArch),
2370 AssociatedOffloadKind);
2371 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2372 };
2373
2374 // If we have a fat binary, add it to the list.
2375 if (CudaFatBinary) {
2376 AddTopLevel(CudaFatBinary, CudaArch::UNKNOWN);
2377 CudaDeviceActions.clear();
2378 CudaFatBinary = nullptr;
2379 return;
2380 }
2381
2382 if (CudaDeviceActions.empty())
2383 return;
2384
2385 // If we have CUDA actions at this point, that's because we have a have
2386 // partial compilation, so we should have an action for each GPU
2387 // architecture.
2388 assert(CudaDeviceActions.size() == GpuArchList.size() &&
2389 "Expecting one action per GPU architecture.");
2390 assert(ToolChains.size() == 1 &&
2391 "Expecting to have a sing CUDA toolchain.");
2392 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
2393 AddTopLevel(CudaDeviceActions[I], GpuArchList[I]);
2394
2395 CudaDeviceActions.clear();
2396 }
2397
2398 bool initialize() override {
2399 assert(AssociatedOffloadKind == Action::OFK_Cuda ||
2400 AssociatedOffloadKind == Action::OFK_HIP);
2401
2402 // We don't need to support CUDA.
2403 if (AssociatedOffloadKind == Action::OFK_Cuda &&
2404 !C.hasOffloadToolChain<Action::OFK_Cuda>())
2405 return false;
2406
2407 // We don't need to support HIP.
2408 if (AssociatedOffloadKind == Action::OFK_HIP &&
2409 !C.hasOffloadToolChain<Action::OFK_HIP>())
2410 return false;
2411
2412 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
2413 assert(HostTC && "No toolchain for host compilation.");
2414 if (HostTC->getTriple().isNVPTX() ||
2415 HostTC->getTriple().getArch() == llvm::Triple::amdgcn) {
2416 // We do not support targeting NVPTX/AMDGCN for host compilation. Throw
2417 // an error and abort pipeline construction early so we don't trip
2418 // asserts that assume device-side compilation.
2419 C.getDriver().Diag(diag::err_drv_cuda_host_arch)
2420 << HostTC->getTriple().getArchName();
2421 return true;
2422 }
2423
2424 ToolChains.push_back(
2425 AssociatedOffloadKind == Action::OFK_Cuda
2426 ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
2427 : C.getSingleOffloadToolChain<Action::OFK_HIP>());
2428
2429 Arg *PartialCompilationArg = Args.getLastArg(
2430 options::OPT_cuda_host_only, options::OPT_cuda_device_only,
2431 options::OPT_cuda_compile_host_device);
2432 CompileHostOnly = PartialCompilationArg &&
2433 PartialCompilationArg->getOption().matches(
2434 options::OPT_cuda_host_only);
2435 CompileDeviceOnly = PartialCompilationArg &&
2436 PartialCompilationArg->getOption().matches(
2437 options::OPT_cuda_device_only);
2438
2439 // Collect all cuda_gpu_arch parameters, removing duplicates.
2440 std::set<CudaArch> GpuArchs;
2441 bool Error = false;
2442 for (Arg *A : Args) {
2443 if (!(A->getOption().matches(options::OPT_cuda_gpu_arch_EQ) ||
2444 A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ)))
2445 continue;
2446 A->claim();
2447
2448 const StringRef ArchStr = A->getValue();
2449 if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ) &&
2450 ArchStr == "all") {
2451 GpuArchs.clear();
2452 continue;
2453 }
2454 CudaArch Arch = StringToCudaArch(ArchStr);
2455 if (Arch == CudaArch::UNKNOWN) {
2456 C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
2457 Error = true;
2458 } else if (A->getOption().matches(options::OPT_cuda_gpu_arch_EQ))
2459 GpuArchs.insert(Arch);
2460 else if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ))
2461 GpuArchs.erase(Arch);
2462 else
2463 llvm_unreachable("Unexpected option.");
2464 }
2465
2466 // Collect list of GPUs remaining in the set.
2467 for (CudaArch Arch : GpuArchs)
2468 GpuArchList.push_back(Arch);
2469
2470 // Default to sm_20 which is the lowest common denominator for
2471 // supported GPUs. sm_20 code should work correctly, if
2472 // suboptimally, on all newer GPUs.
2473 if (GpuArchList.empty())
2474 GpuArchList.push_back(CudaArch::SM_20);
2475
2476 return Error;
2477 }
2478 };
2479
2480 /// \brief CUDA action builder. It injects device code in the host backend
2481 /// action.
2482 class CudaActionBuilder final : public CudaActionBuilderBase {
Samuel Antao64e965e2016-09-30 15:34:19 +00002483 public:
2484 CudaActionBuilder(Compilation &C, DerivedArgList &Args,
2485 const Driver::InputList &Inputs)
Yaxun Liu3af038b2018-05-30 00:49:10 +00002486 : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_Cuda) {}
Samuel Antao64e965e2016-09-30 15:34:19 +00002487
2488 ActionBuilderReturnCode
Samuel Antao28c4f182016-10-27 17:08:03 +00002489 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2490 phases::ID CurPhase, phases::ID FinalPhase,
2491 PhasesTy &Phases) override {
Samuel Antao64e965e2016-09-30 15:34:19 +00002492 if (!IsActive)
2493 return ABRT_Inactive;
2494
2495 // If we don't have more CUDA actions, we don't have any dependences to
2496 // create for the host.
2497 if (CudaDeviceActions.empty())
2498 return ABRT_Success;
2499
2500 assert(CudaDeviceActions.size() == GpuArchList.size() &&
2501 "Expecting one action per GPU architecture.");
2502 assert(!CompileHostOnly &&
2503 "Not expecting CUDA actions in host-only compilation.");
2504
2505 // If we are generating code for the device or we are in a backend phase,
2506 // we attempt to generate the fat binary. We compile each arch to ptx and
2507 // assemble to cubin, then feed the cubin *and* the ptx into a device
2508 // "link" action, which uses fatbinary to combine these cubins into one
2509 // fatbin. The fatbin is then an input to the host action if not in
2510 // device-only mode.
2511 if (CompileDeviceOnly || CurPhase == phases::Backend) {
2512 ActionList DeviceActions;
2513 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2514 // Produce the device action from the current phase up to the assemble
2515 // phase.
2516 for (auto Ph : Phases) {
2517 // Skip the phases that were already dealt with.
2518 if (Ph < CurPhase)
2519 continue;
2520 // We have to be consistent with the host final phase.
2521 if (Ph > FinalPhase)
2522 break;
2523
2524 CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction(
Artem Belevichecb178b2018-03-21 22:22:59 +00002525 C, Args, Ph, CudaDeviceActions[I], Action::OFK_Cuda);
Samuel Antao64e965e2016-09-30 15:34:19 +00002526
2527 if (Ph == phases::Assemble)
2528 break;
2529 }
2530
2531 // If we didn't reach the assemble phase, we can't generate the fat
2532 // binary. We don't need to generate the fat binary if we are not in
2533 // device-only mode.
2534 if (!isa<AssembleJobAction>(CudaDeviceActions[I]) ||
2535 CompileDeviceOnly)
2536 continue;
2537
2538 Action *AssembleAction = CudaDeviceActions[I];
2539 assert(AssembleAction->getType() == types::TY_Object);
2540 assert(AssembleAction->getInputs().size() == 1);
2541
2542 Action *BackendAction = AssembleAction->getInputs()[0];
2543 assert(BackendAction->getType() == types::TY_PP_Asm);
2544
2545 for (auto &A : {AssembleAction, BackendAction}) {
2546 OffloadAction::DeviceDependences DDep;
2547 DDep.add(*A, *ToolChains.front(), CudaArchToString(GpuArchList[I]),
2548 Action::OFK_Cuda);
2549 DeviceActions.push_back(
2550 C.MakeAction<OffloadAction>(DDep, A->getType()));
2551 }
2552 }
2553
2554 // We generate the fat binary if we have device input actions.
2555 if (!DeviceActions.empty()) {
2556 CudaFatBinary =
2557 C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN);
2558
2559 if (!CompileDeviceOnly) {
2560 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
2561 Action::OFK_Cuda);
2562 // Clear the fat binary, it is already a dependence to an host
2563 // action.
2564 CudaFatBinary = nullptr;
2565 }
2566
2567 // Remove the CUDA actions as they are already connected to an host
2568 // action or fat binary.
2569 CudaDeviceActions.clear();
2570 }
2571
2572 // We avoid creating host action in device-only mode.
2573 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
Samuel Antao5b1a89a2016-10-27 00:53:34 +00002574 } else if (CurPhase > phases::Backend) {
2575 // If we are past the backend phase and still have a device action, we
2576 // don't have to do anything as this action is already a device
2577 // top-level action.
2578 return ABRT_Success;
Samuel Antao64e965e2016-09-30 15:34:19 +00002579 }
2580
2581 assert(CurPhase < phases::Backend && "Generating single CUDA "
2582 "instructions should only occur "
2583 "before the backend phase!");
2584
2585 // By default, we produce an action for each device arch.
2586 for (Action *&A : CudaDeviceActions)
2587 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2588
2589 return ABRT_Success;
2590 }
Yaxun Liu3af038b2018-05-30 00:49:10 +00002591 };
2592 /// \brief HIP action builder. It injects device code in the host backend
2593 /// action.
2594 class HIPActionBuilder final : public CudaActionBuilderBase {
2595 /// The linker inputs obtained for each device arch.
2596 SmallVector<ActionList, 8> DeviceLinkerInputs;
Yaxun Liu97670892018-10-02 17:48:54 +00002597 bool Relocatable;
Samuel Antao64e965e2016-09-30 15:34:19 +00002598
Yaxun Liu3af038b2018-05-30 00:49:10 +00002599 public:
2600 HIPActionBuilder(Compilation &C, DerivedArgList &Args,
2601 const Driver::InputList &Inputs)
Yaxun Liu97670892018-10-02 17:48:54 +00002602 : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_HIP),
2603 Relocatable(false) {}
Samuel Antao64e965e2016-09-30 15:34:19 +00002604
Yaxun Liu3af038b2018-05-30 00:49:10 +00002605 bool canUseBundlerUnbundler() const override { return true; }
Samuel Antao64e965e2016-09-30 15:34:19 +00002606
Yaxun Liu3af038b2018-05-30 00:49:10 +00002607 ActionBuilderReturnCode
2608 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2609 phases::ID CurPhase, phases::ID FinalPhase,
2610 PhasesTy &Phases) override {
2611 // amdgcn does not support linking of object files, therefore we skip
Yaxun Liu97670892018-10-02 17:48:54 +00002612 // backend and assemble phases to output LLVM IR. Except for generating
2613 // non-relocatable device coee, where we generate fat binary for device
2614 // code and pass to host in Backend phase.
2615 if (CudaDeviceActions.empty() ||
2616 (CurPhase == phases::Backend && Relocatable) ||
Yaxun Liu3af038b2018-05-30 00:49:10 +00002617 CurPhase == phases::Assemble)
2618 return ABRT_Success;
2619
Yaxun Liu97670892018-10-02 17:48:54 +00002620 assert(((CurPhase == phases::Link && Relocatable) ||
Yaxun Liu3af038b2018-05-30 00:49:10 +00002621 CudaDeviceActions.size() == GpuArchList.size()) &&
2622 "Expecting one action per GPU architecture.");
2623 assert(!CompileHostOnly &&
2624 "Not expecting CUDA actions in host-only compilation.");
2625
Yaxun Liu97670892018-10-02 17:48:54 +00002626 if (!Relocatable && CurPhase == phases::Backend) {
2627 // If we are in backend phase, we attempt to generate the fat binary.
2628 // We compile each arch to IR and use a link action to generate code
2629 // object containing ISA. Then we use a special "link" action to create
2630 // a fat binary containing all the code objects for different GPU's.
2631 // The fat binary is then an input to the host action.
2632 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2633 // Create a link action to link device IR with device library
2634 // and generate ISA.
2635 ActionList AL;
2636 AL.push_back(CudaDeviceActions[I]);
2637 CudaDeviceActions[I] =
2638 C.MakeAction<LinkJobAction>(AL, types::TY_Image);
2639
2640 // OffloadingActionBuilder propagates device arch until an offload
2641 // action. Since the next action for creating fatbin does
2642 // not have device arch, whereas the above link action and its input
2643 // have device arch, an offload action is needed to stop the null
2644 // device arch of the next action being propagated to the above link
2645 // action.
2646 OffloadAction::DeviceDependences DDep;
2647 DDep.add(*CudaDeviceActions[I], *ToolChains.front(),
2648 CudaArchToString(GpuArchList[I]), AssociatedOffloadKind);
2649 CudaDeviceActions[I] = C.MakeAction<OffloadAction>(
2650 DDep, CudaDeviceActions[I]->getType());
2651 }
2652 // Create HIP fat binary with a special "link" action.
2653 CudaFatBinary =
2654 C.MakeAction<LinkJobAction>(CudaDeviceActions,
2655 types::TY_HIP_FATBIN);
2656
Yaxun Liu2bcc9512018-11-14 04:47:31 +00002657 if (!CompileDeviceOnly) {
2658 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
2659 AssociatedOffloadKind);
2660 // Clear the fat binary, it is already a dependence to an host
2661 // action.
2662 CudaFatBinary = nullptr;
2663 }
Yaxun Liu97670892018-10-02 17:48:54 +00002664
2665 // Remove the CUDA actions as they are already connected to an host
2666 // action or fat binary.
2667 CudaDeviceActions.clear();
2668
Yaxun Liu2bcc9512018-11-14 04:47:31 +00002669 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
Yaxun Liu97670892018-10-02 17:48:54 +00002670 } else if (CurPhase == phases::Link) {
2671 // Save CudaDeviceActions to DeviceLinkerInputs for each GPU subarch.
2672 // This happens to each device action originated from each input file.
2673 // Later on, device actions in DeviceLinkerInputs are used to create
2674 // device link actions in appendLinkDependences and the created device
2675 // link actions are passed to the offload action as device dependence.
Yaxun Liu3af038b2018-05-30 00:49:10 +00002676 DeviceLinkerInputs.resize(CudaDeviceActions.size());
2677 auto LI = DeviceLinkerInputs.begin();
2678 for (auto *A : CudaDeviceActions) {
2679 LI->push_back(A);
2680 ++LI;
Samuel Antao64e965e2016-09-30 15:34:19 +00002681 }
2682
Yaxun Liu3af038b2018-05-30 00:49:10 +00002683 // We will pass the device action as a host dependence, so we don't
2684 // need to do anything else with them.
2685 CudaDeviceActions.clear();
Samuel Antao64e965e2016-09-30 15:34:19 +00002686 return ABRT_Success;
2687 }
2688
Yaxun Liu3af038b2018-05-30 00:49:10 +00002689 // By default, we produce an action for each device arch.
2690 for (Action *&A : CudaDeviceActions)
2691 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A,
2692 AssociatedOffloadKind);
2693
2694 return ABRT_Success;
Samuel Antao64e965e2016-09-30 15:34:19 +00002695 }
2696
Yaxun Liu3af038b2018-05-30 00:49:10 +00002697 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {
2698 // Append a new link action for each device.
2699 unsigned I = 0;
2700 for (auto &LI : DeviceLinkerInputs) {
2701 auto *DeviceLinkAction =
2702 C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2703 DA.add(*DeviceLinkAction, *ToolChains[0],
2704 CudaArchToString(GpuArchList[I]), AssociatedOffloadKind);
2705 ++I;
Samuel Antao64e965e2016-09-30 15:34:19 +00002706 }
Samuel Antao64e965e2016-09-30 15:34:19 +00002707 }
Yaxun Liu97670892018-10-02 17:48:54 +00002708
2709 bool initialize() override {
2710 Relocatable = Args.hasFlag(options::OPT_fgpu_rdc,
2711 options::OPT_fno_gpu_rdc, /*Default=*/false);
2712
2713 return CudaActionBuilderBase::initialize();
2714 }
Samuel Antao64e965e2016-09-30 15:34:19 +00002715 };
2716
Samuel Antao28c4f182016-10-27 17:08:03 +00002717 /// OpenMP action builder. The host bitcode is passed to the device frontend
2718 /// and all the device linked images are passed to the host link phase.
2719 class OpenMPActionBuilder final : public DeviceActionBuilder {
2720 /// The OpenMP actions for the current input.
2721 ActionList OpenMPDeviceActions;
2722
2723 /// The linker inputs obtained for each toolchain.
2724 SmallVector<ActionList, 8> DeviceLinkerInputs;
2725
2726 public:
2727 OpenMPActionBuilder(Compilation &C, DerivedArgList &Args,
2728 const Driver::InputList &Inputs)
2729 : DeviceActionBuilder(C, Args, Inputs, Action::OFK_OpenMP) {}
2730
2731 ActionBuilderReturnCode
2732 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2733 phases::ID CurPhase, phases::ID FinalPhase,
2734 PhasesTy &Phases) override {
Alexey Bataeva5178f52018-09-28 16:17:59 +00002735 if (OpenMPDeviceActions.empty())
2736 return ABRT_Inactive;
Samuel Antao28c4f182016-10-27 17:08:03 +00002737
2738 // We should always have an action for each input.
2739 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2740 "Number of OpenMP actions and toolchains do not match.");
2741
2742 // The host only depends on device action in the linking phase, when all
2743 // the device images have to be embedded in the host image.
2744 if (CurPhase == phases::Link) {
2745 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2746 "Toolchains and linker inputs sizes do not match.");
2747 auto LI = DeviceLinkerInputs.begin();
2748 for (auto *A : OpenMPDeviceActions) {
2749 LI->push_back(A);
2750 ++LI;
2751 }
2752
2753 // We passed the device action as a host dependence, so we don't need to
2754 // do anything else with them.
2755 OpenMPDeviceActions.clear();
2756 return ABRT_Success;
2757 }
2758
2759 // By default, we produce an action for each device arch.
2760 for (Action *&A : OpenMPDeviceActions)
2761 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2762
2763 return ABRT_Success;
2764 }
2765
2766 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2767
2768 // If this is an input action replicate it for each OpenMP toolchain.
2769 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2770 OpenMPDeviceActions.clear();
2771 for (unsigned I = 0; I < ToolChains.size(); ++I)
2772 OpenMPDeviceActions.push_back(
2773 C.MakeAction<InputAction>(IA->getInputArg(), IA->getType()));
2774 return ABRT_Success;
2775 }
2776
Samuel Antaofab4f372016-10-27 18:00:51 +00002777 // If this is an unbundling action use it as is for each OpenMP toolchain.
2778 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2779 OpenMPDeviceActions.clear();
Alexey Bataeva5178f52018-09-28 16:17:59 +00002780 auto *IA = cast<InputAction>(UA->getInputs().back());
2781 std::string FileName = IA->getInputArg().getAsString(Args);
2782 // Check if the type of the file is the same as the action. Do not
2783 // unbundle it if it is not. Do not unbundle .so files, for example,
2784 // which are not object files.
2785 if (IA->getType() == types::TY_Object &&
2786 (!llvm::sys::path::has_extension(FileName) ||
2787 types::lookupTypeForExtension(
2788 llvm::sys::path::extension(FileName).drop_front()) !=
2789 types::TY_Object))
2790 return ABRT_Inactive;
Samuel Antaofab4f372016-10-27 18:00:51 +00002791 for (unsigned I = 0; I < ToolChains.size(); ++I) {
2792 OpenMPDeviceActions.push_back(UA);
2793 UA->registerDependentActionInfo(
2794 ToolChains[I], /*BoundArch=*/StringRef(), Action::OFK_OpenMP);
2795 }
2796 return ABRT_Success;
2797 }
2798
Samuel Antao28c4f182016-10-27 17:08:03 +00002799 // When generating code for OpenMP we use the host compile phase result as
2800 // a dependence to the device compile phase so that it can learn what
2801 // declarations should be emitted. However, this is not the only use for
2802 // the host action, so we prevent it from being collapsed.
2803 if (isa<CompileJobAction>(HostAction)) {
2804 HostAction->setCannotBeCollapsedWithNextDependentAction();
2805 assert(ToolChains.size() == OpenMPDeviceActions.size() &&
2806 "Toolchains and device action sizes do not match.");
2807 OffloadAction::HostDependence HDep(
2808 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2809 /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2810 auto TC = ToolChains.begin();
2811 for (Action *&A : OpenMPDeviceActions) {
2812 assert(isa<CompileJobAction>(A));
2813 OffloadAction::DeviceDependences DDep;
2814 DDep.add(*A, **TC, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2815 A = C.MakeAction<OffloadAction>(HDep, DDep);
2816 ++TC;
2817 }
2818 }
2819 return ABRT_Success;
2820 }
2821
Samuel Antao69d6f312016-10-27 17:50:43 +00002822 void appendTopLevelActions(ActionList &AL) override {
2823 if (OpenMPDeviceActions.empty())
2824 return;
2825
2826 // We should always have an action for each input.
2827 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2828 "Number of OpenMP actions and toolchains do not match.");
2829
2830 // Append all device actions followed by the proper offload action.
2831 auto TI = ToolChains.begin();
2832 for (auto *A : OpenMPDeviceActions) {
2833 OffloadAction::DeviceDependences Dep;
2834 Dep.add(*A, **TI, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2835 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2836 ++TI;
2837 }
2838 // We no longer need the action stored in this builder.
2839 OpenMPDeviceActions.clear();
2840 }
2841
Samuel Antao28c4f182016-10-27 17:08:03 +00002842 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {
2843 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2844 "Toolchains and linker inputs sizes do not match.");
2845
2846 // Append a new link action for each device.
2847 auto TC = ToolChains.begin();
2848 for (auto &LI : DeviceLinkerInputs) {
2849 auto *DeviceLinkAction =
2850 C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2851 DA.add(*DeviceLinkAction, **TC, /*BoundArch=*/nullptr,
2852 Action::OFK_OpenMP);
2853 ++TC;
2854 }
2855 }
2856
2857 bool initialize() override {
2858 // Get the OpenMP toolchains. If we don't get any, the action builder will
2859 // know there is nothing to do related to OpenMP offloading.
2860 auto OpenMPTCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
2861 for (auto TI = OpenMPTCRange.first, TE = OpenMPTCRange.second; TI != TE;
2862 ++TI)
2863 ToolChains.push_back(TI->second);
2864
2865 DeviceLinkerInputs.resize(ToolChains.size());
2866 return false;
2867 }
Samuel Antao69d6f312016-10-27 17:50:43 +00002868
2869 bool canUseBundlerUnbundler() const override {
2870 // OpenMP should use bundled files whenever possible.
2871 return true;
2872 }
Samuel Antao28c4f182016-10-27 17:08:03 +00002873 };
2874
2875 ///
2876 /// TODO: Add the implementation for other specialized builders here.
2877 ///
Samuel Antao64e965e2016-09-30 15:34:19 +00002878
2879 /// Specialized builders being used by this offloading action builder.
2880 SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders;
2881
Samuel Antao69d6f312016-10-27 17:50:43 +00002882 /// Flag set to true if all valid builders allow file bundling/unbundling.
2883 bool CanUseBundler;
2884
Samuel Antao64e965e2016-09-30 15:34:19 +00002885public:
2886 OffloadingActionBuilder(Compilation &C, DerivedArgList &Args,
2887 const Driver::InputList &Inputs)
Samuel Antao10e905c2016-10-27 01:08:58 +00002888 : C(C) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002889 // Create a specialized builder for each device toolchain.
2890
2891 IsValid = true;
2892
2893 // Create a specialized builder for CUDA.
2894 SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs));
2895
Yaxun Liu3af038b2018-05-30 00:49:10 +00002896 // Create a specialized builder for HIP.
2897 SpecializedBuilders.push_back(new HIPActionBuilder(C, Args, Inputs));
2898
Samuel Antao28c4f182016-10-27 17:08:03 +00002899 // Create a specialized builder for OpenMP.
2900 SpecializedBuilders.push_back(new OpenMPActionBuilder(C, Args, Inputs));
2901
Samuel Antao64e965e2016-09-30 15:34:19 +00002902 //
2903 // TODO: Build other specialized builders here.
2904 //
2905
Samuel Antao69d6f312016-10-27 17:50:43 +00002906 // Initialize all the builders, keeping track of errors. If all valid
2907 // builders agree that we can use bundling, set the flag to true.
2908 unsigned ValidBuilders = 0u;
2909 unsigned ValidBuildersSupportingBundling = 0u;
2910 for (auto *SB : SpecializedBuilders) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002911 IsValid = IsValid && !SB->initialize();
Samuel Antao69d6f312016-10-27 17:50:43 +00002912
2913 // Update the counters if the builder is valid.
2914 if (SB->isValid()) {
2915 ++ValidBuilders;
2916 if (SB->canUseBundlerUnbundler())
2917 ++ValidBuildersSupportingBundling;
2918 }
2919 }
2920 CanUseBundler =
2921 ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling;
Artem Belevichf981e30b2016-08-02 22:37:47 +00002922 }
Justin Lebardc3c5042016-04-19 02:27:07 +00002923
Samuel Antao64e965e2016-09-30 15:34:19 +00002924 ~OffloadingActionBuilder() {
2925 for (auto *SB : SpecializedBuilders)
2926 delete SB;
Samuel Antaod06239d2016-07-15 23:13:27 +00002927 }
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002928
Samuel Antao64e965e2016-09-30 15:34:19 +00002929 /// Generate an action that adds device dependences (if any) to a host action.
2930 /// If no device dependence actions exist, just return the host action \a
2931 /// HostAction. If an error is found or if no builder requires the host action
2932 /// to be generated, return nullptr.
2933 Action *
2934 addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg,
2935 phases::ID CurPhase, phases::ID FinalPhase,
2936 DeviceActionBuilder::PhasesTy &Phases) {
2937 if (!IsValid)
2938 return nullptr;
Justin Lebar7bf77982016-01-11 23:27:13 +00002939
Samuel Antao64e965e2016-09-30 15:34:19 +00002940 if (SpecializedBuilders.empty())
2941 return HostAction;
2942
2943 assert(HostAction && "Invalid host action!");
2944
2945 OffloadAction::DeviceDependences DDeps;
2946 // Check if all the programming models agree we should not emit the host
2947 // action. Also, keep track of the offloading kinds employed.
2948 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2949 unsigned InactiveBuilders = 0u;
2950 unsigned IgnoringBuilders = 0u;
2951 for (auto *SB : SpecializedBuilders) {
2952 if (!SB->isValid()) {
2953 ++InactiveBuilders;
2954 continue;
2955 }
2956
Samuel Antao28c4f182016-10-27 17:08:03 +00002957 auto RetCode =
2958 SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases);
Samuel Antao64e965e2016-09-30 15:34:19 +00002959
2960 // If the builder explicitly says the host action should be ignored,
2961 // we need to increment the variable that tracks the builders that request
2962 // the host object to be ignored.
2963 if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host)
2964 ++IgnoringBuilders;
2965
2966 // Unless the builder was inactive for this action, we have to record the
2967 // offload kind because the host will have to use it.
2968 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2969 OffloadKind |= SB->getAssociatedOffloadKind();
2970 }
2971
2972 // If all builders agree that the host object should be ignored, just return
2973 // nullptr.
2974 if (IgnoringBuilders &&
2975 SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders))
2976 return nullptr;
2977
2978 if (DDeps.getActions().empty())
2979 return HostAction;
2980
2981 // We have dependences we need to bundle together. We use an offload action
2982 // for that.
2983 OffloadAction::HostDependence HDep(
2984 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2985 /*BoundArch=*/nullptr, DDeps);
2986 return C.MakeAction<OffloadAction>(HDep, DDeps);
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002987 }
2988
Samuel Antao64e965e2016-09-30 15:34:19 +00002989 /// Generate an action that adds a host dependence to a device action. The
2990 /// results will be kept in this action builder. Return true if an error was
2991 /// found.
Samuel Antaofab4f372016-10-27 18:00:51 +00002992 bool addHostDependenceToDeviceActions(Action *&HostAction,
Samuel Antao64e965e2016-09-30 15:34:19 +00002993 const Arg *InputArg) {
2994 if (!IsValid)
2995 return true;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002996
Samuel Antaofab4f372016-10-27 18:00:51 +00002997 // If we are supporting bundling/unbundling and the current action is an
2998 // input action of non-source file, we replace the host action by the
2999 // unbundling action. The bundler tool has the logic to detect if an input
3000 // is a bundle or not and if the input is not a bundle it assumes it is a
3001 // host file. Therefore it is safe to create an unbundling action even if
3002 // the input is not a bundle.
3003 if (CanUseBundler && isa<InputAction>(HostAction) &&
3004 InputArg->getOption().getKind() == llvm::opt::Option::InputClass &&
3005 !types::isSrcFile(HostAction->getType())) {
3006 auto UnbundlingHostAction =
3007 C.MakeAction<OffloadUnbundlingJobAction>(HostAction);
3008 UnbundlingHostAction->registerDependentActionInfo(
3009 C.getSingleOffloadToolChain<Action::OFK_Host>(),
Yaxun Liuf37b50a2018-07-24 01:03:44 +00003010 /*BoundArch=*/StringRef(), Action::OFK_Host);
Samuel Antaofab4f372016-10-27 18:00:51 +00003011 HostAction = UnbundlingHostAction;
3012 }
3013
Samuel Antao64e965e2016-09-30 15:34:19 +00003014 assert(HostAction && "Invalid host action!");
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003015
Samuel Antao64e965e2016-09-30 15:34:19 +00003016 // Register the offload kinds that are used.
3017 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
3018 for (auto *SB : SpecializedBuilders) {
3019 if (!SB->isValid())
3020 continue;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003021
Samuel Antao64e965e2016-09-30 15:34:19 +00003022 auto RetCode = SB->addDeviceDepences(HostAction);
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003023
Samuel Antao64e965e2016-09-30 15:34:19 +00003024 // Host dependences for device actions are not compatible with that same
3025 // action being ignored.
3026 assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host &&
3027 "Host dependence not expected to be ignored.!");
Samuel Antaod06239d2016-07-15 23:13:27 +00003028
Samuel Antao64e965e2016-09-30 15:34:19 +00003029 // Unless the builder was inactive for this action, we have to record the
3030 // offload kind because the host will have to use it.
3031 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
3032 OffloadKind |= SB->getAssociatedOffloadKind();
3033 }
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003034
Alexey Bataeva5178f52018-09-28 16:17:59 +00003035 // Do not use unbundler if the Host does not depend on device action.
3036 if (OffloadKind == Action::OFK_None && CanUseBundler)
3037 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction))
3038 HostAction = UA->getInputs().back();
3039
Samuel Antao64e965e2016-09-30 15:34:19 +00003040 return false;
3041 }
3042
Samuel Antao69d6f312016-10-27 17:50:43 +00003043 /// Add the offloading top level actions to the provided action list. This
3044 /// function can replace the host action by a bundling action if the
3045 /// programming models allow it.
Samuel Antao64e965e2016-09-30 15:34:19 +00003046 bool appendTopLevelActions(ActionList &AL, Action *HostAction,
3047 const Arg *InputArg) {
Samuel Antao69d6f312016-10-27 17:50:43 +00003048 // Get the device actions to be appended.
3049 ActionList OffloadAL;
Samuel Antao64e965e2016-09-30 15:34:19 +00003050 for (auto *SB : SpecializedBuilders) {
3051 if (!SB->isValid())
3052 continue;
Samuel Antao69d6f312016-10-27 17:50:43 +00003053 SB->appendTopLevelActions(OffloadAL);
Samuel Antao64e965e2016-09-30 15:34:19 +00003054 }
3055
Samuel Antao69d6f312016-10-27 17:50:43 +00003056 // If we can use the bundler, replace the host action by the bundling one in
Yaxun Liu2bcc9512018-11-14 04:47:31 +00003057 // the resulting list. Otherwise, just append the device actions. For
3058 // device only compilation, HostAction is a null pointer, therefore only do
3059 // this when HostAction is not a null pointer.
3060 if (CanUseBundler && HostAction && !OffloadAL.empty()) {
Samuel Antao69d6f312016-10-27 17:50:43 +00003061 // Add the host action to the list in order to create the bundling action.
3062 OffloadAL.push_back(HostAction);
3063
3064 // We expect that the host action was just appended to the action list
3065 // before this method was called.
3066 assert(HostAction == AL.back() && "Host action not in the list??");
3067 HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL);
3068 AL.back() = HostAction;
3069 } else
3070 AL.append(OffloadAL.begin(), OffloadAL.end());
3071
Samuel Antao64e965e2016-09-30 15:34:19 +00003072 // Propagate to the current host action (if any) the offload information
3073 // associated with the current input.
3074 if (HostAction)
3075 HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg],
3076 /*BoundArch=*/nullptr);
Samuel Antao64e965e2016-09-30 15:34:19 +00003077 return false;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003078 }
Artem Belevich5bde4e02015-07-20 20:02:54 +00003079
Samuel Antao64e965e2016-09-30 15:34:19 +00003080 /// Processes the host linker action. This currently consists of replacing it
3081 /// with an offload action if there are device link objects and propagate to
3082 /// the host action all the offload kinds used in the current compilation. The
3083 /// resulting action is returned.
3084 Action *processHostLinkAction(Action *HostAction) {
3085 // Add all the dependences from the device linking actions.
3086 OffloadAction::DeviceDependences DDeps;
3087 for (auto *SB : SpecializedBuilders) {
3088 if (!SB->isValid())
3089 continue;
Justin Lebar21e5d4f2016-01-14 21:41:27 +00003090
Samuel Antao64e965e2016-09-30 15:34:19 +00003091 SB->appendLinkDependences(DDeps);
Justin Lebar21e5d4f2016-01-14 21:41:27 +00003092 }
Samuel Antaod06239d2016-07-15 23:13:27 +00003093
Samuel Antao64e965e2016-09-30 15:34:19 +00003094 // Calculate all the offload kinds used in the current compilation.
3095 unsigned ActiveOffloadKinds = 0u;
3096 for (auto &I : InputArgToOffloadKindMap)
3097 ActiveOffloadKinds |= I.second;
3098
3099 // If we don't have device dependencies, we don't have to create an offload
3100 // action.
3101 if (DDeps.getActions().empty()) {
3102 // Propagate all the active kinds to host action. Given that it is a link
3103 // action it is assumed to depend on all actions generated so far.
3104 HostAction->propagateHostOffloadInfo(ActiveOffloadKinds,
3105 /*BoundArch=*/nullptr);
3106 return HostAction;
3107 }
3108
3109 // Create the offload action with all dependences. When an offload action
3110 // is created the kinds are propagated to the host action, so we don't have
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003111 // to do that explicitly here.
Samuel Antao64e965e2016-09-30 15:34:19 +00003112 OffloadAction::HostDependence HDep(
3113 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
3114 /*BoundArch*/ nullptr, ActiveOffloadKinds);
3115 return C.MakeAction<OffloadAction>(HDep, DDeps);
3116 }
3117};
3118} // anonymous namespace.
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003119
Justin Lebar0f3474c2016-02-11 02:00:50 +00003120void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
3121 const InputList &Inputs, ActionList &Actions) const {
Chad Rosierecdede82011-08-12 22:08:57 +00003122 llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00003123
Daniel Dunbar34c41872009-03-13 00:17:48 +00003124 if (!SuppressMissingInputWarning && Inputs.empty()) {
Daniel Dunbarbfeec742009-03-12 23:55:14 +00003125 Diag(clang::diag::err_drv_no_input_files);
3126 return;
3127 }
3128
Chad Rosier7742b5d2011-07-27 23:36:45 +00003129 Arg *FinalPhaseArg;
3130 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
Daniel Dunbarbfeec742009-03-12 23:55:14 +00003131
Bob Haarmanaaf51912017-02-27 19:40:19 +00003132 if (FinalPhase == phases::Link) {
3133 if (Args.hasArg(options::OPT_emit_llvm))
3134 Diag(clang::diag::err_drv_emit_llvm_link);
3135 if (IsCLMode() && LTOMode != LTOK_None &&
3136 !Args.getLastArgValue(options::OPT_fuse_ld_EQ).equals_lower("lld"))
3137 Diag(clang::diag::err_drv_lto_without_lld);
Rafael Espindolae8025642013-08-25 14:27:09 +00003138 }
3139
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003140 // Reject -Z* at the top level, these options should never have been exposed
3141 // by gcc.
Daniel Dunbardd765242009-03-26 16:12:09 +00003142 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
Daniel Dunbar0e759942009-03-20 06:14:23 +00003143 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
Daniel Dunbarbfeec742009-03-12 23:55:14 +00003144
Hans Wennborg13b7fe72013-08-12 23:26:25 +00003145 // Diagnose misuse of /Fo.
3146 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
Hans Wennborg13b7fe72013-08-12 23:26:25 +00003147 StringRef V = A->getValue();
Hans Wennborg61647532014-11-17 19:16:36 +00003148 if (Inputs.size() > 1 && !V.empty() &&
3149 !llvm::sys::path::is_separator(V.back())) {
Hans Wennborg13b7fe72013-08-12 23:26:25 +00003150 // Check whether /Fo tries to name an output file for multiple inputs.
Hans Wennborg9c1659b2013-10-18 22:49:04 +00003151 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003152 << A->getSpelling() << V;
Hans Wennborg13b7fe72013-08-12 23:26:25 +00003153 Args.eraseArg(options::OPT__SLASH_Fo);
3154 }
3155 }
3156
Hans Wennborg9c1659b2013-10-18 22:49:04 +00003157 // Diagnose misuse of /Fa.
3158 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
3159 StringRef V = A->getValue();
Hans Wennborg61647532014-11-17 19:16:36 +00003160 if (Inputs.size() > 1 && !V.empty() &&
3161 !llvm::sys::path::is_separator(V.back())) {
Hans Wennborg9c1659b2013-10-18 22:49:04 +00003162 // Check whether /Fa tries to name an asm file for multiple inputs.
3163 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003164 << A->getSpelling() << V;
Hans Wennborg9c1659b2013-10-18 22:49:04 +00003165 Args.eraseArg(options::OPT__SLASH_Fa);
3166 }
3167 }
3168
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00003169 // Diagnose misuse of /o.
3170 if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
3171 if (A->getValue()[0] == '\0') {
3172 // It has to have a value.
3173 Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
3174 Args.eraseArg(options::OPT__SLASH_o);
3175 }
3176 }
3177
Mike Rice58df1af2018-09-11 17:10:44 +00003178 // Ignore /Yc/Yu if both /Yc and /Yu passed but with different filenames.
Nico Weber2ca4be92016-03-01 23:16:44 +00003179 Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
3180 Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
Nico Weber2ca4be92016-03-01 23:16:44 +00003181 if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
3182 Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
3183 Args.eraseArg(options::OPT__SLASH_Yc);
3184 Args.eraseArg(options::OPT__SLASH_Yu);
3185 YcArg = YuArg = nullptr;
3186 }
Nico Weber2ca4be92016-03-01 23:16:44 +00003187 if (YcArg && Inputs.size() > 1) {
3188 Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
3189 Args.eraseArg(options::OPT__SLASH_Yc);
3190 YcArg = nullptr;
3191 }
Erich Keaneeaca3882018-08-17 13:43:39 +00003192 if (FinalPhase == phases::Preprocess || Args.hasArg(options::OPT__SLASH_Y_)) {
3193 // If only preprocessing or /Y- is used, all pch handling is disabled.
3194 // Rather than check for it everywhere, just remove clang-cl pch-related
3195 // flags here.
Nico Weber2ca4be92016-03-01 23:16:44 +00003196 Args.eraseArg(options::OPT__SLASH_Fp);
3197 Args.eraseArg(options::OPT__SLASH_Yc);
3198 Args.eraseArg(options::OPT__SLASH_Yu);
3199 YcArg = YuArg = nullptr;
3200 }
Nico Weber2ca4be92016-03-01 23:16:44 +00003201
Samuel Antao64e965e2016-09-30 15:34:19 +00003202 // Builder to be used to build offloading actions.
3203 OffloadingActionBuilder OffloadBuilder(C, Args, Inputs);
Samuel Antaod06239d2016-07-15 23:13:27 +00003204
Daniel Dunbar65229332009-03-13 11:38:42 +00003205 // Construct the actions to perform.
Richard Smithcd35eff2018-09-15 01:21:16 +00003206 HeaderModulePrecompileJobAction *HeaderModuleAction = nullptr;
Daniel Dunbar65229332009-03-13 11:38:42 +00003207 ActionList LinkerInputs;
Alp Toker965f8822013-11-27 05:22:15 +00003208
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00003209 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL;
Artem Belevich5bde4e02015-07-20 20:02:54 +00003210 for (auto &I : Inputs) {
3211 types::ID InputType = I.first;
3212 const Arg *InputArg = I.second;
Daniel Dunbar65229332009-03-13 11:38:42 +00003213
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00003214 PL.clear();
3215 types::getCompilationPhases(InputType, PL);
Daniel Dunbar65229332009-03-13 11:38:42 +00003216
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003217 // If the first step comes after the final phase we are doing as part of
3218 // this compilation, warn the user about it.
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00003219 phases::ID InitialPhase = PL[0];
Daniel Dunbar65229332009-03-13 11:38:42 +00003220 if (InitialPhase > FinalPhase) {
Martin Storsjo665c7a42018-05-04 06:05:58 +00003221 if (InputArg->isClaimed())
3222 continue;
3223
Daniel Dunbaradc5c7c2009-03-19 07:57:08 +00003224 // Claim here to avoid the more general unused warning.
3225 InputArg->claim();
Daniel Dunbar07806ca2009-09-17 04:13:26 +00003226
Daniel Dunbar2db3e732011-04-20 15:44:48 +00003227 // Suppress all unused style warnings with -Qunused-arguments
3228 if (Args.hasArg(options::OPT_Qunused_arguments))
3229 continue;
3230
Richard Smith403f76e2012-08-06 04:09:06 +00003231 // Special case when final phase determined by binary name, rather than
3232 // by a command-line argument with a corresponding Arg.
Hans Wennborg70850d82013-07-18 20:29:38 +00003233 if (CCCIsCPP())
Richard Smith403f76e2012-08-06 04:09:06 +00003234 Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003235 << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
Daniel Dunbar07806ca2009-09-17 04:13:26 +00003236 // Special case '-E' warning on a previously preprocessed file to make
3237 // more sense.
Richard Smith403f76e2012-08-06 04:09:06 +00003238 else if (InitialPhase == phases::Compile &&
3239 FinalPhase == phases::Preprocess &&
3240 getPreprocessedType(InputType) == types::TY_INVALID)
Daniel Dunbar07806ca2009-09-17 04:13:26 +00003241 Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003242 << InputArg->getAsString(Args) << !!FinalPhaseArg
3243 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
Daniel Dunbar07806ca2009-09-17 04:13:26 +00003244 else
3245 Diag(clang::diag::warn_drv_input_file_unused)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003246 << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
3247 << !!FinalPhaseArg
3248 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
Daniel Dunbar65229332009-03-13 11:38:42 +00003249 continue;
3250 }
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003251
Nico Weberad2d8f32016-04-21 19:59:10 +00003252 if (YcArg) {
3253 // Add a separate precompile phase for the compile phase.
3254 if (FinalPhase >= phases::Compile) {
Richard Smith8cd452d2016-08-30 18:55:16 +00003255 const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType);
Nico Weberad2d8f32016-04-21 19:59:10 +00003256 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PCHPL;
Richard Smith8cd452d2016-08-30 18:55:16 +00003257 types::getCompilationPhases(HeaderType, PCHPL);
Nico Weberad2d8f32016-04-21 19:59:10 +00003258 // Build the pipeline for the pch file.
Richard Smith8cd452d2016-08-30 18:55:16 +00003259 Action *ClangClPch =
Erich Keane76675de2018-07-05 17:22:13 +00003260 C.MakeAction<InputAction>(*InputArg, HeaderType);
Nico Weberad2d8f32016-04-21 19:59:10 +00003261 for (phases::ID Phase : PCHPL)
3262 ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
3263 assert(ClangClPch);
3264 Actions.push_back(ClangClPch);
3265 // The driver currently exits after the first failed command. This
3266 // relies on that behavior, to make sure if the pch generation fails,
3267 // the main compilation won't run.
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00003268 // FIXME: If the main compilation fails, the PCH generation should
3269 // probably not be considered successful either.
Nico Weberad2d8f32016-04-21 19:59:10 +00003270 }
3271 }
3272
Daniel Dunbar65229332009-03-13 11:38:42 +00003273 // Build the pipeline for this file.
Justin Lebar41094612016-01-11 23:07:27 +00003274 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
Samuel Antao64e965e2016-09-30 15:34:19 +00003275
3276 // Use the current host action in any of the offloading actions, if
3277 // required.
3278 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
3279 break;
3280
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003281 for (SmallVectorImpl<phases::ID>::iterator i = PL.begin(), e = PL.end();
3282 i != e; ++i) {
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00003283 phases::ID Phase = *i;
Daniel Dunbar65229332009-03-13 11:38:42 +00003284
3285 // We are done if this step is past what the user requested.
3286 if (Phase > FinalPhase)
3287 break;
3288
Samuel Antao64e965e2016-09-30 15:34:19 +00003289 // Add any offload action the host action depends on.
3290 Current = OffloadBuilder.addDeviceDependencesToHostAction(
3291 Current, InputArg, Phase, FinalPhase, PL);
3292 if (!Current)
3293 break;
3294
Daniel Dunbar65229332009-03-13 11:38:42 +00003295 // Queue linker inputs.
3296 if (Phase == phases::Link) {
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00003297 assert((i + 1) == e && "linking must be final compilation step.");
Justin Lebar41094612016-01-11 23:07:27 +00003298 LinkerInputs.push_back(Current);
3299 Current = nullptr;
Daniel Dunbar65229332009-03-13 11:38:42 +00003300 break;
3301 }
3302
Richard Smithcd35eff2018-09-15 01:21:16 +00003303 // Each precompiled header file after a module file action is a module
3304 // header of that same module file, rather than being compiled to a
3305 // separate PCH.
3306 if (Phase == phases::Precompile && HeaderModuleAction &&
3307 getPrecompiledType(InputType) == types::TY_PCH) {
3308 HeaderModuleAction->addModuleHeaderInput(Current);
3309 Current = nullptr;
3310 break;
3311 }
3312
3313 // FIXME: Should we include any prior module file outputs as inputs of
3314 // later actions in the same command line?
3315
Samuel Antao64e965e2016-09-30 15:34:19 +00003316 // Otherwise construct the appropriate action.
Richard Smithcd35eff2018-09-15 01:21:16 +00003317 Action *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current);
Samuel Antao64e965e2016-09-30 15:34:19 +00003318
3319 // We didn't create a new action, so we will just move to the next phase.
3320 if (NewCurrent == Current)
Daniel Dunbar13864952009-03-24 20:17:30 +00003321 continue;
3322
Richard Smithcd35eff2018-09-15 01:21:16 +00003323 if (auto *HMA = dyn_cast<HeaderModulePrecompileJobAction>(NewCurrent))
3324 HeaderModuleAction = HMA;
3325
Samuel Antao64e965e2016-09-30 15:34:19 +00003326 Current = NewCurrent;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003327
Samuel Antao64e965e2016-09-30 15:34:19 +00003328 // Use the current host action in any of the offloading actions, if
3329 // required.
3330 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
3331 break;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003332
Daniel Dunbar65229332009-03-13 11:38:42 +00003333 if (Current->getType() == types::TY_Nothing)
3334 break;
3335 }
3336
Samuel Antao64e965e2016-09-30 15:34:19 +00003337 // If we ended with something, add to the output list.
3338 if (Current)
Justin Lebar41094612016-01-11 23:07:27 +00003339 Actions.push_back(Current);
Samuel Antao64e965e2016-09-30 15:34:19 +00003340
3341 // Add any top level actions generated for offloading.
3342 OffloadBuilder.appendTopLevelActions(Actions, Current, InputArg);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00003343 }
Daniel Dunbar65229332009-03-13 11:38:42 +00003344
Samuel Antao64e965e2016-09-30 15:34:19 +00003345 // Add a link action if necessary.
Samuel Antaod06239d2016-07-15 23:13:27 +00003346 if (!LinkerInputs.empty()) {
Samuel Antao64e965e2016-09-30 15:34:19 +00003347 Action *LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image);
3348 LA = OffloadBuilder.processHostLinkAction(LA);
3349 Actions.push_back(LA);
Samuel Antaod06239d2016-07-15 23:13:27 +00003350 }
Daniel Dunbarc7a67b72009-12-22 23:19:32 +00003351
3352 // If we are linking, claim any options which are obviously only used for
3353 // compilation.
Hans Wennborga8ef14f2013-09-17 00:03:41 +00003354 if (FinalPhase == phases::Link && PL.size() == 1) {
Daniel Dunbarc7a67b72009-12-22 23:19:32 +00003355 Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
Hans Wennborga8ef14f2013-09-17 00:03:41 +00003356 Args.ClaimAllArgs(options::OPT_cl_compile_Group);
3357 }
3358
3359 // Claim ignored clang-cl options.
3360 Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
Artem Belevichbaae0932015-07-28 21:01:30 +00003361
Justin Lebardc3c5042016-04-19 02:27:07 +00003362 // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed
3363 // to non-CUDA compilations and should not trigger warnings there.
Artem Belevichbaae0932015-07-28 21:01:30 +00003364 Args.ClaimAllArgs(options::OPT_cuda_host_only);
Justin Lebardc3c5042016-04-19 02:27:07 +00003365 Args.ClaimAllArgs(options::OPT_cuda_compile_host_device);
Daniel Dunbar65229332009-03-13 11:38:42 +00003366}
3367
Artem Belevichecb178b2018-03-21 22:22:59 +00003368Action *Driver::ConstructPhaseAction(
3369 Compilation &C, const ArgList &Args, phases::ID Phase, Action *Input,
3370 Action::OffloadKind TargetDeviceOffloadKind) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00003371 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
Samuel Antao64e965e2016-09-30 15:34:19 +00003372
3373 // Some types skip the assembler phase (e.g., llvm-bc), but we can't
3374 // encode this in the steps because the intermediate type depends on
3375 // arguments. Just special case here.
3376 if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm)
3377 return Input;
3378
Daniel Dunbar65229332009-03-13 11:38:42 +00003379 // Build the appropriate action.
3380 switch (Phase) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003381 case phases::Link:
3382 llvm_unreachable("link action invalid here.");
Daniel Dunbar65229332009-03-13 11:38:42 +00003383 case phases::Preprocess: {
Daniel Dunbard67a3222009-03-30 06:36:42 +00003384 types::ID OutputTy;
3385 // -{M, MM} alter the output type.
Daniel Dunbar86aed7d2010-12-08 21:33:40 +00003386 if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
Daniel Dunbard67a3222009-03-30 06:36:42 +00003387 OutputTy = types::TY_Dependencies;
3388 } else {
David Blaikie5d577a22012-06-29 22:03:56 +00003389 OutputTy = Input->getType();
3390 if (!Args.hasFlag(options::OPT_frewrite_includes,
Justin Bognerce8245b2014-06-24 08:01:01 +00003391 options::OPT_fno_rewrite_includes, false) &&
Richard Smith86a3ef52017-06-09 21:24:02 +00003392 !Args.hasFlag(options::OPT_frewrite_imports,
3393 options::OPT_fno_rewrite_imports, false) &&
Justin Bognerce8245b2014-06-24 08:01:01 +00003394 !CCGenDiagnostics)
David Blaikie5d577a22012-06-29 22:03:56 +00003395 OutputTy = types::getPreprocessedType(OutputTy);
Daniel Dunbard67a3222009-03-30 06:36:42 +00003396 assert(OutputTy != types::TY_INVALID &&
3397 "Cannot preprocess this input type!");
3398 }
Justin Lebar41094612016-01-11 23:07:27 +00003399 return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
Daniel Dunbar65229332009-03-13 11:38:42 +00003400 }
Aaron Ballman1f10cc52012-07-31 01:21:00 +00003401 case phases::Precompile: {
Richard Smithdd4ad3d2016-08-30 19:06:26 +00003402 types::ID OutputTy = getPrecompiledType(Input->getType());
3403 assert(OutputTy != types::TY_INVALID &&
3404 "Cannot precompile this input type!");
Richard Smithcd35eff2018-09-15 01:21:16 +00003405
3406 // If we're given a module name, precompile header file inputs as a
3407 // module, not as a precompiled header.
3408 const char *ModName = nullptr;
3409 if (OutputTy == types::TY_PCH) {
3410 if (Arg *A = Args.getLastArg(options::OPT_fmodule_name_EQ))
3411 ModName = A->getValue();
3412 if (ModName)
3413 OutputTy = types::TY_ModuleFile;
3414 }
3415
Aaron Ballman1f10cc52012-07-31 01:21:00 +00003416 if (Args.hasArg(options::OPT_fsyntax_only)) {
3417 // Syntax checks should not emit a PCH file
3418 OutputTy = types::TY_Nothing;
3419 }
Richard Smithcd35eff2018-09-15 01:21:16 +00003420
3421 if (ModName)
3422 return C.MakeAction<HeaderModulePrecompileJobAction>(Input, OutputTy,
3423 ModName);
Justin Lebar41094612016-01-11 23:07:27 +00003424 return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
Aaron Ballman1f10cc52012-07-31 01:21:00 +00003425 }
Daniel Dunbar65229332009-03-13 11:38:42 +00003426 case phases::Compile: {
David Blaikie486f4402014-08-29 07:25:23 +00003427 if (Args.hasArg(options::OPT_fsyntax_only))
Justin Lebar41094612016-01-11 23:07:27 +00003428 return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
David Blaikie486f4402014-08-29 07:25:23 +00003429 if (Args.hasArg(options::OPT_rewrite_objc))
Justin Lebar41094612016-01-11 23:07:27 +00003430 return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
David Blaikie486f4402014-08-29 07:25:23 +00003431 if (Args.hasArg(options::OPT_rewrite_legacy_objc))
Justin Lebar41094612016-01-11 23:07:27 +00003432 return C.MakeAction<CompileJobAction>(Input,
3433 types::TY_RewrittenLegacyObjC);
David Blaikie486f4402014-08-29 07:25:23 +00003434 if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto))
Justin Lebar41094612016-01-11 23:07:27 +00003435 return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
David Blaikie486f4402014-08-29 07:25:23 +00003436 if (Args.hasArg(options::OPT__migrate))
Justin Lebar41094612016-01-11 23:07:27 +00003437 return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
David Blaikie486f4402014-08-29 07:25:23 +00003438 if (Args.hasArg(options::OPT_emit_ast))
Justin Lebar41094612016-01-11 23:07:27 +00003439 return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
David Blaikie486f4402014-08-29 07:25:23 +00003440 if (Args.hasArg(options::OPT_module_file_info))
Justin Lebar41094612016-01-11 23:07:27 +00003441 return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
David Blaikie486f4402014-08-29 07:25:23 +00003442 if (Args.hasArg(options::OPT_verify_pch))
Justin Lebar41094612016-01-11 23:07:27 +00003443 return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
3444 return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
Bob Wilson23a55f12014-12-21 07:00:00 +00003445 }
3446 case phases::Backend: {
Artem Belevichecb178b2018-03-21 22:22:59 +00003447 if (isUsingLTO() && TargetDeviceOffloadKind == Action::OFK_None) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003448 types::ID Output =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003449 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
Justin Lebar41094612016-01-11 23:07:27 +00003450 return C.MakeAction<BackendJobAction>(Input, Output);
David Blaikie486f4402014-08-29 07:25:23 +00003451 }
3452 if (Args.hasArg(options::OPT_emit_llvm)) {
Shuxin Yang4b3c7ff2013-08-23 21:34:57 +00003453 types::ID Output =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003454 Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
Justin Lebar41094612016-01-11 23:07:27 +00003455 return C.MakeAction<BackendJobAction>(Input, Output);
Daniel Dunbar65229332009-03-13 11:38:42 +00003456 }
Justin Lebar41094612016-01-11 23:07:27 +00003457 return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
Daniel Dunbar65229332009-03-13 11:38:42 +00003458 }
3459 case phases::Assemble:
Justin Lebar21e5d4f2016-01-14 21:41:27 +00003460 return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
Daniel Dunbar65229332009-03-13 11:38:42 +00003461 }
3462
David Blaikie83d382b2011-09-23 05:06:16 +00003463 llvm_unreachable("invalid phase in ConstructPhaseAction");
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00003464}
3465
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00003466void Driver::BuildJobs(Compilation &C) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00003467 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
Daniel Dunbare75d8342009-03-16 06:56:51 +00003468
3469 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
3470
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003471 // It is an error to provide a -o option if we are making multiple output
3472 // files.
Daniel Dunbare75d8342009-03-16 06:56:51 +00003473 if (FinalOutput) {
3474 unsigned NumOutputs = 0;
Saleem Abdulrasoolda3f4e52014-12-29 21:02:47 +00003475 for (const Action *A : C.getActions())
3476 if (A->getType() != types::TY_Nothing)
Daniel Dunbare75d8342009-03-16 06:56:51 +00003477 ++NumOutputs;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003478
Daniel Dunbare75d8342009-03-16 06:56:51 +00003479 if (NumOutputs > 1) {
3480 Diag(clang::diag::err_drv_output_argument_with_multiple_files);
Craig Topper92fc2df2014-05-17 16:56:41 +00003481 FinalOutput = nullptr;
Daniel Dunbare75d8342009-03-16 06:56:51 +00003482 }
3483 }
3484
Chad Rosier35767232013-04-30 22:01:21 +00003485 // Collect the list of architectures.
3486 llvm::StringSet<> ArchNames;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00003487 if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO())
3488 for (const Arg *A : C.getArgs())
Chad Rosier35767232013-04-30 22:01:21 +00003489 if (A->getOption().matches(options::OPT_arch))
3490 ArchNames.insert(A->getValue());
Chad Rosier35767232013-04-30 22:01:21 +00003491
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003492 // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
3493 std::map<std::pair<const Action *, std::string>, InputInfo> CachedResults;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00003494 for (Action *A : C.getActions()) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003495 // If we are linking an image for multiple archs then the linker wants
3496 // -arch_multiple and -final_output <final image name>. Unfortunately, this
3497 // doesn't fit in cleanly because we have to pass this information down.
Daniel Dunbare75d8342009-03-16 06:56:51 +00003498 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003499 // FIXME: This is a hack; find a cleaner way to integrate this into the
3500 // process.
Craig Topper92fc2df2014-05-17 16:56:41 +00003501 const char *LinkingOutput = nullptr;
Daniel Dunbardd765242009-03-26 16:12:09 +00003502 if (isa<LipoJobAction>(A)) {
Daniel Dunbare75d8342009-03-16 06:56:51 +00003503 if (FinalOutput)
Richard Smithbd55daf2012-11-01 04:30:05 +00003504 LinkingOutput = FinalOutput->getValue();
Daniel Dunbare75d8342009-03-16 06:56:51 +00003505 else
Hans Wennborga7707222015-01-09 17:38:53 +00003506 LinkingOutput = getDefaultImageName();
Daniel Dunbare75d8342009-03-16 06:56:51 +00003507 }
3508
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003509 BuildJobsForAction(C, A, &C.getDefaultToolChain(),
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003510 /*BoundArch*/ StringRef(),
Daniel Dunbare75d8342009-03-16 06:56:51 +00003511 /*AtTopLevel*/ true,
Chad Rosier35767232013-04-30 22:01:21 +00003512 /*MultipleArchs*/ ArchNames.size() > 1,
Samuel Antaod06239d2016-07-15 23:13:27 +00003513 /*LinkingOutput*/ LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003514 /*TargetDeviceOffloadKind*/ Action::OFK_None);
Daniel Dunbare75d8342009-03-16 06:56:51 +00003515 }
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00003516
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003517 // If the user passed -Qunused-arguments or there were errors, don't warn
3518 // about any unused arguments.
Argyrios Kyrtzidis31448a42010-11-18 21:47:07 +00003519 if (Diags.hasErrorOccurred() ||
Daniel Dunbara3cfbe32009-04-07 19:04:18 +00003520 C.getArgs().hasArg(options::OPT_Qunused_arguments))
Daniel Dunbard175d972009-03-18 18:03:46 +00003521 return;
3522
Daniel Dunbar58399ae2009-03-29 22:24:54 +00003523 // Claim -### here.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003524 (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003525
Nico Weber47bf5052016-04-25 21:15:49 +00003526 // Claim --driver-mode, --rsp-quoting, it was handled earlier.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003527 (void)C.getArgs().hasArg(options::OPT_driver_mode);
Nico Weber47bf5052016-04-25 21:15:49 +00003528 (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
Hans Wennborg70850d82013-07-18 20:29:38 +00003529
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00003530 for (Arg *A : C.getArgs()) {
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00003531 // FIXME: It would be nice to be able to send the argument to the
David Blaikie9c902b52011-09-25 23:23:43 +00003532 // DiagnosticsEngine, so that extra values, position, and so on could be
3533 // printed.
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003534 if (!A->isClaimed()) {
Michael J. Spencer66e2b202012-10-19 22:37:06 +00003535 if (A->getOption().hasFlag(options::NoArgumentUnused))
Daniel Dunbara3cfbe32009-04-07 19:04:18 +00003536 continue;
3537
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003538 // Suppress the warning automatically if this is just a flag, and it is an
3539 // instance of an argument we already claimed.
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003540 const Option &Opt = A->getOption();
Michael J. Spencerad3ccc32012-08-20 21:41:17 +00003541 if (Opt.getKind() == Option::FlagClass) {
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003542 bool DuplicateClaimed = false;
3543
Sean Silva14facf32015-06-09 01:57:17 +00003544 for (const Arg *AA : C.getArgs().filtered(&Opt)) {
3545 if (AA->isClaimed()) {
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003546 DuplicateClaimed = true;
3547 break;
3548 }
3549 }
3550
3551 if (DuplicateClaimed)
3552 continue;
3553 }
3554
Ehsan Akhgarid8518332016-01-25 21:14:52 +00003555 // In clang-cl, don't mention unknown arguments here since they have
3556 // already been warned about.
3557 if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN))
3558 Diag(clang::diag::warn_drv_unused_argument)
3559 << A->getAsString(C.getArgs());
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003560 }
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00003561 }
Daniel Dunbar95e6b192009-03-13 22:12:33 +00003562}
Daniel Dunbarc4343942010-02-03 03:07:56 +00003563
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003564namespace {
3565/// Utility class to control the collapse of dependent actions and select the
3566/// tools accordingly.
3567class ToolSelector final {
3568 /// The tool chain this selector refers to.
3569 const ToolChain &TC;
Daniel Dunbarf9ff3502010-05-14 02:03:00 +00003570
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003571 /// The compilation this selector refers to.
3572 const Compilation &C;
Samuel Antaod06239d2016-07-15 23:13:27 +00003573
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003574 /// The base action this selector refers to.
3575 const JobAction *BaseAction;
Samuel Antaod06239d2016-07-15 23:13:27 +00003576
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003577 /// Set to true if the current toolchain refers to host actions.
3578 bool IsHostSelector;
Samuel Antaod06239d2016-07-15 23:13:27 +00003579
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003580 /// Set to true if save-temps and embed-bitcode functionalities are active.
3581 bool SaveTemps;
3582 bool EmbedBitcode;
3583
3584 /// Get previous dependent action or null if that does not exist. If
3585 /// \a CanBeCollapsed is false, that action must be legal to collapse or
3586 /// null will be returned.
3587 const JobAction *getPrevDependentAction(const ActionList &Inputs,
3588 ActionList &SavedOffloadAction,
3589 bool CanBeCollapsed = true) {
3590 // An option can be collapsed only if it has a single input.
3591 if (Inputs.size() != 1)
Craig Topper92fc2df2014-05-17 16:56:41 +00003592 return nullptr;
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003593
3594 Action *CurAction = *Inputs.begin();
3595 if (CanBeCollapsed &&
3596 !CurAction->isCollapsingWithNextDependentActionLegal())
3597 return nullptr;
3598
3599 // If the input action is an offload action. Look through it and save any
3600 // offload action that can be dropped in the event of a collapse.
3601 if (auto *OA = dyn_cast<OffloadAction>(CurAction)) {
3602 // If the dependent action is a device action, we will attempt to collapse
3603 // only with other device actions. Otherwise, we would do the same but
3604 // with host actions only.
3605 if (!IsHostSelector) {
3606 if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) {
3607 CurAction =
3608 OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
3609 if (CanBeCollapsed &&
3610 !CurAction->isCollapsingWithNextDependentActionLegal())
3611 return nullptr;
3612 SavedOffloadAction.push_back(OA);
3613 return dyn_cast<JobAction>(CurAction);
3614 }
3615 } else if (OA->hasHostDependence()) {
3616 CurAction = OA->getHostDependence();
3617 if (CanBeCollapsed &&
3618 !CurAction->isCollapsingWithNextDependentActionLegal())
3619 return nullptr;
3620 SavedOffloadAction.push_back(OA);
3621 return dyn_cast<JobAction>(CurAction);
3622 }
3623 return nullptr;
3624 }
3625
3626 return dyn_cast<JobAction>(CurAction);
3627 }
3628
3629 /// Return true if an assemble action can be collapsed.
3630 bool canCollapseAssembleAction() const {
3631 return TC.useIntegratedAs() && !SaveTemps &&
3632 !C.getArgs().hasArg(options::OPT_via_file_asm) &&
3633 !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
3634 !C.getArgs().hasArg(options::OPT__SLASH_Fa);
3635 }
3636
3637 /// Return true if a preprocessor action can be collapsed.
3638 bool canCollapsePreprocessorAction() const {
3639 return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
3640 !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
3641 !C.getArgs().hasArg(options::OPT_rewrite_objc);
3642 }
3643
3644 /// Struct that relates an action with the offload actions that would be
3645 /// collapsed with it.
3646 struct JobActionInfo final {
3647 /// The action this info refers to.
3648 const JobAction *JA = nullptr;
3649 /// The offload actions we need to take care off if this action is
3650 /// collapsed.
3651 ActionList SavedOffloadAction;
3652 };
3653
3654 /// Append collapsed offload actions from the give nnumber of elements in the
3655 /// action info array.
3656 static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction,
3657 ArrayRef<JobActionInfo> &ActionInfo,
3658 unsigned ElementNum) {
3659 assert(ElementNum <= ActionInfo.size() && "Invalid number of elements.");
3660 for (unsigned I = 0; I < ElementNum; ++I)
3661 CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(),
3662 ActionInfo[I].SavedOffloadAction.end());
3663 }
3664
3665 /// Functions that attempt to perform the combining. They detect if that is
3666 /// legal, and if so they update the inputs \a Inputs and the offload action
3667 /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with
3668 /// the combined action is returned. If the combining is not legal or if the
3669 /// tool does not exist, null is returned.
3670 /// Currently three kinds of collapsing are supported:
3671 /// - Assemble + Backend + Compile;
3672 /// - Assemble + Backend ;
3673 /// - Backend + Compile.
3674 const Tool *
3675 combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
Richard Smithcd35eff2018-09-15 01:21:16 +00003676 ActionList &Inputs,
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003677 ActionList &CollapsedOffloadAction) {
3678 if (ActionInfo.size() < 3 || !canCollapseAssembleAction())
3679 return nullptr;
3680 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
3681 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
3682 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA);
3683 if (!AJ || !BJ || !CJ)
3684 return nullptr;
3685
3686 // Get compiler tool.
3687 const Tool *T = TC.SelectTool(*CJ);
3688 if (!T)
3689 return nullptr;
3690
Steven Wu574b0f22016-03-01 01:07:58 +00003691 // When using -fembed-bitcode, it is required to have the same tool (clang)
3692 // for both CompilerJA and BackendJA. Otherwise, combine two stages.
3693 if (EmbedBitcode) {
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003694 const Tool *BT = TC.SelectTool(*BJ);
3695 if (BT == T)
3696 return nullptr;
Steven Wu574b0f22016-03-01 01:07:58 +00003697 }
Bob Wilson23a55f12014-12-21 07:00:00 +00003698
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003699 if (!T->hasIntegratedAssembler())
Bob Wilson23a55f12014-12-21 07:00:00 +00003700 return nullptr;
Samuel Antaod06239d2016-07-15 23:13:27 +00003701
Richard Smithcd35eff2018-09-15 01:21:16 +00003702 Inputs = CJ->getInputs();
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003703 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3704 /*NumElements=*/3);
3705 return T;
3706 }
3707 const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo,
Richard Smithcd35eff2018-09-15 01:21:16 +00003708 ActionList &Inputs,
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003709 ActionList &CollapsedOffloadAction) {
3710 if (ActionInfo.size() < 2 || !canCollapseAssembleAction())
3711 return nullptr;
3712 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
3713 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
3714 if (!AJ || !BJ)
3715 return nullptr;
3716
3717 // Retrieve the compile job, backend action must always be preceded by one.
3718 ActionList CompileJobOffloadActions;
3719 auto *CJ = getPrevDependentAction(BJ->getInputs(), CompileJobOffloadActions,
3720 /*CanBeCollapsed=*/false);
3721 if (!AJ || !BJ || !CJ)
3722 return nullptr;
3723
3724 assert(isa<CompileJobAction>(CJ) &&
3725 "Expecting compile job preceding backend job.");
3726
3727 // Get compiler tool.
3728 const Tool *T = TC.SelectTool(*CJ);
3729 if (!T)
3730 return nullptr;
3731
3732 if (!T->hasIntegratedAssembler())
3733 return nullptr;
3734
Richard Smithcd35eff2018-09-15 01:21:16 +00003735 Inputs = BJ->getInputs();
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003736 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3737 /*NumElements=*/2);
3738 return T;
3739 }
3740 const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
Richard Smithcd35eff2018-09-15 01:21:16 +00003741 ActionList &Inputs,
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003742 ActionList &CollapsedOffloadAction) {
Teresa Johnson9e4321c2018-04-17 16:39:25 +00003743 if (ActionInfo.size() < 2)
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003744 return nullptr;
3745 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA);
3746 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA);
3747 if (!BJ || !CJ)
3748 return nullptr;
3749
Teresa Johnson9e4321c2018-04-17 16:39:25 +00003750 // Check if the initial input (to the compile job or its predessor if one
3751 // exists) is LLVM bitcode. In that case, no preprocessor step is required
3752 // and we can still collapse the compile and backend jobs when we have
3753 // -save-temps. I.e. there is no need for a separate compile job just to
3754 // emit unoptimized bitcode.
3755 bool InputIsBitcode = true;
3756 for (size_t i = 1; i < ActionInfo.size(); i++)
3757 if (ActionInfo[i].JA->getType() != types::TY_LLVM_BC &&
3758 ActionInfo[i].JA->getType() != types::TY_LTO_BC) {
3759 InputIsBitcode = false;
3760 break;
3761 }
3762 if (!InputIsBitcode && !canCollapsePreprocessorAction())
3763 return nullptr;
3764
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003765 // Get compiler tool.
3766 const Tool *T = TC.SelectTool(*CJ);
3767 if (!T)
3768 return nullptr;
3769
Teresa Johnson9e4321c2018-04-17 16:39:25 +00003770 if (T->canEmitIR() && ((SaveTemps && !InputIsBitcode) || EmbedBitcode))
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003771 return nullptr;
3772
Richard Smithcd35eff2018-09-15 01:21:16 +00003773 Inputs = CJ->getInputs();
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003774 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3775 /*NumElements=*/2);
3776 return T;
3777 }
3778
3779 /// Updates the inputs if the obtained tool supports combining with
3780 /// preprocessor action, and the current input is indeed a preprocessor
3781 /// action. If combining results in the collapse of offloading actions, those
3782 /// are appended to \a CollapsedOffloadAction.
Richard Smithcd35eff2018-09-15 01:21:16 +00003783 void combineWithPreprocessor(const Tool *T, ActionList &Inputs,
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003784 ActionList &CollapsedOffloadAction) {
3785 if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP())
3786 return;
3787
3788 // Attempt to get a preprocessor action dependence.
3789 ActionList PreprocessJobOffloadActions;
Richard Smithcd35eff2018-09-15 01:21:16 +00003790 ActionList NewInputs;
3791 for (Action *A : Inputs) {
3792 auto *PJ = getPrevDependentAction({A}, PreprocessJobOffloadActions);
3793 if (!PJ || !isa<PreprocessJobAction>(PJ)) {
3794 NewInputs.push_back(A);
3795 continue;
3796 }
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003797
Richard Smithcd35eff2018-09-15 01:21:16 +00003798 // This is legal to combine. Append any offload action we found and add the
3799 // current input to preprocessor inputs.
3800 CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(),
3801 PreprocessJobOffloadActions.end());
3802 NewInputs.append(PJ->input_begin(), PJ->input_end());
3803 }
3804 Inputs = NewInputs;
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003805 }
3806
3807public:
3808 ToolSelector(const JobAction *BaseAction, const ToolChain &TC,
3809 const Compilation &C, bool SaveTemps, bool EmbedBitcode)
3810 : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps),
3811 EmbedBitcode(EmbedBitcode) {
3812 assert(BaseAction && "Invalid base action.");
3813 IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None;
3814 }
3815
3816 /// Check if a chain of actions can be combined and return the tool that can
3817 /// handle the combination of actions. The pointer to the current inputs \a
3818 /// Inputs and the list of offload actions \a CollapsedOffloadActions
3819 /// connected to collapsed actions are updated accordingly. The latter enables
3820 /// the caller of the selector to process them afterwards instead of just
3821 /// dropping them. If no suitable tool is found, null will be returned.
Richard Smithcd35eff2018-09-15 01:21:16 +00003822 const Tool *getTool(ActionList &Inputs,
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003823 ActionList &CollapsedOffloadAction) {
3824 //
3825 // Get the largest chain of actions that we could combine.
3826 //
3827
3828 SmallVector<JobActionInfo, 5> ActionChain(1);
3829 ActionChain.back().JA = BaseAction;
3830 while (ActionChain.back().JA) {
3831 const Action *CurAction = ActionChain.back().JA;
3832
3833 // Grow the chain by one element.
3834 ActionChain.resize(ActionChain.size() + 1);
3835 JobActionInfo &AI = ActionChain.back();
3836
3837 // Attempt to fill it with the
3838 AI.JA =
3839 getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction);
Daniel Dunbarc4343942010-02-03 03:07:56 +00003840 }
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003841
3842 // Pop the last action info as it could not be filled.
3843 ActionChain.pop_back();
3844
3845 //
3846 // Attempt to combine actions. If all combining attempts failed, just return
3847 // the tool of the provided action. At the end we attempt to combine the
3848 // action with any preprocessor action it may depend on.
3849 //
3850
3851 const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs,
3852 CollapsedOffloadAction);
3853 if (!T)
3854 T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction);
3855 if (!T)
3856 T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction);
3857 if (!T) {
Richard Smithcd35eff2018-09-15 01:21:16 +00003858 Inputs = BaseAction->getInputs();
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003859 T = TC.SelectTool(*BaseAction);
3860 }
3861
3862 combineWithPreprocessor(T, Inputs, CollapsedOffloadAction);
3863 return T;
Daniel Dunbarc4343942010-02-03 03:07:56 +00003864 }
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003865};
Daniel Dunbarc4343942010-02-03 03:07:56 +00003866}
3867
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003868/// Return a string that uniquely identifies the result of a job. The bound arch
3869/// is not necessarily represented in the toolchain's triple -- for example,
3870/// armv7 and armv7s both map to the same triple -- so we need both in our map.
3871/// Also, we need to add the offloading device kind, as the same tool chain can
3872/// be used for host and device for some programming models, e.g. OpenMP.
3873static std::string GetTriplePlusArchString(const ToolChain *TC,
3874 StringRef BoundArch,
3875 Action::OffloadKind OffloadKind) {
Justin Lebar55c83322016-01-16 03:30:08 +00003876 std::string TriplePlusArch = TC->getTriple().normalize();
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003877 if (!BoundArch.empty()) {
Justin Lebar55c83322016-01-16 03:30:08 +00003878 TriplePlusArch += "-";
3879 TriplePlusArch += BoundArch;
3880 }
Samuel Antao59efaed2016-10-27 17:31:22 +00003881 TriplePlusArch += "-";
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003882 TriplePlusArch += Action::GetOffloadKindName(OffloadKind);
3883 return TriplePlusArch;
3884}
3885
3886InputInfo Driver::BuildJobsForAction(
3887 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
3888 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
3889 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
3890 Action::OffloadKind TargetDeviceOffloadKind) const {
3891 std::pair<const Action *, std::string> ActionTC = {
3892 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003893 auto CachedResult = CachedResults.find(ActionTC);
3894 if (CachedResult != CachedResults.end()) {
3895 return CachedResult->second;
3896 }
Samuel Antaod06239d2016-07-15 23:13:27 +00003897 InputInfo Result = BuildJobsForActionNoCache(
3898 C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003899 CachedResults, TargetDeviceOffloadKind);
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003900 CachedResults[ActionTC] = Result;
3901 return Result;
3902}
3903
3904InputInfo Driver::BuildJobsForActionNoCache(
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003905 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003906 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
Samuel Antaod06239d2016-07-15 23:13:27 +00003907 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003908 Action::OffloadKind TargetDeviceOffloadKind) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003909 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
Daniel Dunbarc4acf9d2009-03-18 23:18:19 +00003910
Samuel Antaod06239d2016-07-15 23:13:27 +00003911 InputInfoList OffloadDependencesInputInfo;
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003912 bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None;
Samuel Antaod06239d2016-07-15 23:13:27 +00003913 if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
Alex Lorenz4003a982017-08-08 11:22:21 +00003914 // The 'Darwin' toolchain is initialized only when its arguments are
3915 // computed. Get the default arguments for OFK_None to ensure that
3916 // initialization is performed before processing the offload action.
3917 // FIXME: Remove when darwin's toolchain is initialized during construction.
3918 C.getArgsForToolChain(TC, BoundArch, Action::OFK_None);
3919
Samuel Antaod06239d2016-07-15 23:13:27 +00003920 // The offload action is expected to be used in four different situations.
3921 //
3922 // a) Set a toolchain/architecture/kind for a host action:
3923 // Host Action 1 -> OffloadAction -> Host Action 2
3924 //
3925 // b) Set a toolchain/architecture/kind for a device action;
3926 // Device Action 1 -> OffloadAction -> Device Action 2
3927 //
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003928 // c) Specify a device dependence to a host action;
Samuel Antaod06239d2016-07-15 23:13:27 +00003929 // Device Action 1 _
3930 // \
3931 // Host Action 1 ---> OffloadAction -> Host Action 2
3932 //
3933 // d) Specify a host dependence to a device action.
3934 // Host Action 1 _
3935 // \
3936 // Device Action 1 ---> OffloadAction -> Device Action 2
3937 //
3938 // For a) and b), we just return the job generated for the dependence. For
3939 // c) and d) we override the current action with the host/device dependence
3940 // if the current toolchain is host/device and set the offload dependences
3941 // info with the jobs obtained from the device/host dependence(s).
3942
3943 // If there is a single device option, just generate the job for it.
3944 if (OA->hasSingleDeviceDependence()) {
3945 InputInfo DevA;
3946 OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
3947 const char *DepBoundArch) {
3948 DevA =
3949 BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
3950 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003951 CachedResults, DepA->getOffloadingDeviceKind());
Samuel Antaod06239d2016-07-15 23:13:27 +00003952 });
3953 return DevA;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003954 }
Samuel Antaod06239d2016-07-15 23:13:27 +00003955
3956 // If 'Action 2' is host, we generate jobs for the device dependences and
3957 // override the current action with the host dependence. Otherwise, we
3958 // generate the host dependences and override the action with the device
3959 // dependence. The dependences can't therefore be a top-level action.
3960 OA->doOnEachDependence(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003961 /*IsHostDependence=*/BuildingForOffloadDevice,
Samuel Antaod06239d2016-07-15 23:13:27 +00003962 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3963 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
3964 C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false,
3965 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003966 DepA->getOffloadingDeviceKind()));
Samuel Antaod06239d2016-07-15 23:13:27 +00003967 });
3968
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003969 A = BuildingForOffloadDevice
Samuel Antaod06239d2016-07-15 23:13:27 +00003970 ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
3971 : OA->getHostDependence();
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003972 }
3973
Daniel Dunbare75d8342009-03-16 06:56:51 +00003974 if (const InputAction *IA = dyn_cast<InputAction>(A)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003975 // FIXME: It would be nice to not claim this here; maybe the old scheme of
3976 // just using Args was better?
Daniel Dunbar5cdf3e02009-03-19 07:29:38 +00003977 const Arg &Input = IA->getInputArg();
3978 Input.claim();
Daniel Dunbar35cbfeb2010-06-09 22:31:08 +00003979 if (Input.getOption().matches(options::OPT_INPUT)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00003980 const char *Name = Input.getValue();
Justin Lebard98cea82016-01-11 23:15:21 +00003981 return InputInfo(A, Name, /* BaseInput = */ Name);
Douglas Katzman678d0cb2015-06-16 18:01:24 +00003982 }
Justin Lebard98cea82016-01-11 23:15:21 +00003983 return InputInfo(A, &Input, /* BaseInput = */ "");
Daniel Dunbare75d8342009-03-16 06:56:51 +00003984 }
3985
3986 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
Chad Rosiera78a6eb2012-04-27 16:50:38 +00003987 const ToolChain *TC;
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003988 StringRef ArchName = BAA->getArchName();
Daniel Dunbar1ef3f2a2009-09-08 23:37:19 +00003989
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003990 if (!ArchName.empty())
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +00003991 TC = &getToolChain(C.getArgs(),
Petr Hosekdd38d932018-05-29 22:35:39 +00003992 computeTargetTriple(*this, TargetTriple,
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +00003993 C.getArgs(), ArchName));
Chad Rosiera78a6eb2012-04-27 16:50:38 +00003994 else
3995 TC = &C.getDefaultToolChain();
Daniel Dunbar1ef3f2a2009-09-08 23:37:19 +00003996
Nico Weber5a459f82016-02-23 19:30:43 +00003997 return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
Samuel Antaod06239d2016-07-15 23:13:27 +00003998 MultipleArchs, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003999 TargetDeviceOffloadKind);
Daniel Dunbare75d8342009-03-16 06:56:51 +00004000 }
4001
Artem Belevich0ff05cd2015-07-13 23:27:56 +00004002
Richard Smithcd35eff2018-09-15 01:21:16 +00004003 ActionList Inputs = A->getInputs();
Daniel Dunbarc4343942010-02-03 03:07:56 +00004004
4005 const JobAction *JA = cast<JobAction>(A);
Samuel Antaod06239d2016-07-15 23:13:27 +00004006 ActionList CollapsedOffloadActions;
4007
Mehdi Amini6683e222017-01-24 18:12:25 +00004008 ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(),
4009 embedBitcodeInObject() && !isUsingLTO());
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00004010 const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions);
4011
Rafael Espindola79764462013-03-24 15:06:53 +00004012 if (!T)
Justin Lebar9eaa4892016-01-11 23:09:32 +00004013 return InputInfo();
Daniel Dunbare75d8342009-03-16 06:56:51 +00004014
Samuel Antaod06239d2016-07-15 23:13:27 +00004015 // If we've collapsed action list that contained OffloadAction we
4016 // need to build jobs for host/device-side inputs it may have held.
4017 for (const auto *OA : CollapsedOffloadActions)
4018 cast<OffloadAction>(OA)->doOnEachDependence(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004019 /*IsHostDependence=*/BuildingForOffloadDevice,
Samuel Antaod06239d2016-07-15 23:13:27 +00004020 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
4021 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
Artem Belevichbee2f412016-08-22 18:50:34 +00004022 C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false,
Samuel Antaod06239d2016-07-15 23:13:27 +00004023 /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004024 DepA->getOffloadingDeviceKind()));
Samuel Antaod06239d2016-07-15 23:13:27 +00004025 });
Artem Belevichf8144ab2015-08-27 18:10:41 +00004026
Daniel Dunbare75d8342009-03-16 06:56:51 +00004027 // Only use pipes when there is exactly one input.
Daniel Dunbar1a093d22009-03-18 06:00:36 +00004028 InputInfoList InputInfos;
Richard Smithcd35eff2018-09-15 01:21:16 +00004029 for (const Action *Input : Inputs) {
Eric Christopher14668dd2013-02-18 00:38:25 +00004030 // Treat dsymutil and verify sub-jobs as being at the top-level too, they
4031 // shouldn't get temporary output names.
Daniel Dunbar6beaf512010-06-04 18:28:41 +00004032 // FIXME: Clean this up.
Justin Lebar9eaa4892016-01-11 23:09:32 +00004033 bool SubJobAtTopLevel =
4034 AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
Samuel Antaod06239d2016-07-15 23:13:27 +00004035 InputInfos.push_back(BuildJobsForAction(
4036 C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004037 CachedResults, A->getOffloadingDeviceKind()));
Daniel Dunbare75d8342009-03-16 06:56:51 +00004038 }
4039
Daniel Dunbare75d8342009-03-16 06:56:51 +00004040 // Always use the first input as the base input.
4041 const char *BaseInput = InputInfos[0].getBaseInput();
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004042
Daniel Dunbar6beaf512010-06-04 18:28:41 +00004043 // ... except dsymutil actions, which use their actual input as the base
4044 // input.
4045 if (JA->getType() == types::TY_dSYM)
4046 BaseInput = InputInfos[0].getFilename();
4047
Richard Smithcd35eff2018-09-15 01:21:16 +00004048 // ... and in header module compilations, which use the module name.
4049 if (auto *ModuleJA = dyn_cast<HeaderModulePrecompileJobAction>(JA))
4050 BaseInput = ModuleJA->getModuleName();
4051
Samuel Antaod06239d2016-07-15 23:13:27 +00004052 // Append outputs of offload device jobs to the input list
4053 if (!OffloadDependencesInputInfo.empty())
4054 InputInfos.append(OffloadDependencesInputInfo.begin(),
4055 OffloadDependencesInputInfo.end());
Artem Belevich0ff05cd2015-07-13 23:27:56 +00004056
Vedant Kumar18286cf2016-07-27 23:02:20 +00004057 // Set the effective triple of the toolchain for the duration of this job.
4058 llvm::Triple EffectiveTriple;
4059 const ToolChain &ToolTC = T->getToolChain();
Samuel Antao31fef982016-10-27 17:39:44 +00004060 const ArgList &Args =
4061 C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind());
Vedant Kumar18286cf2016-07-27 23:02:20 +00004062 if (InputInfos.size() != 1) {
4063 EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args));
4064 } else {
4065 // Pass along the input type if it can be unambiguously determined.
4066 EffectiveTriple = llvm::Triple(
4067 ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType()));
4068 }
4069 RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple);
4070
Daniel Dunbard00272f2010-08-02 02:38:15 +00004071 // Determine the place to write output to, if any.
Justin Lebar9eaa4892016-01-11 23:09:32 +00004072 InputInfo Result;
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004073 InputInfoList UnbundlingResults;
4074 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) {
4075 // If we have an unbundling job, we need to create results for all the
4076 // outputs. We also update the results cache so that other actions using
4077 // this unbundling action can get the right results.
4078 for (auto &UI : UA->getDependentActionsInfo()) {
4079 assert(UI.DependentOffloadKind != Action::OFK_None &&
4080 "Unbundling with no offloading??");
4081
4082 // Unbundling actions are never at the top level. When we generate the
4083 // offloading prefix, we also do that for the host file because the
4084 // unbundling action does not change the type of the output which can
4085 // cause a overwrite.
4086 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
4087 UI.DependentOffloadKind,
4088 UI.DependentToolChain->getTriple().normalize(),
4089 /*CreatePrefixForHost=*/true);
4090 auto CurI = InputInfo(
Yaxun Liu609f7522018-05-11 19:02:18 +00004091 UA,
4092 GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch,
4093 /*AtTopLevel=*/false,
4094 MultipleArchs ||
4095 UI.DependentOffloadKind == Action::OFK_HIP,
4096 OffloadingPrefix),
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004097 BaseInput);
4098 // Save the unbundling result.
4099 UnbundlingResults.push_back(CurI);
4100
4101 // Get the unique string identifier for this dependence and cache the
4102 // result.
Yaxun Liu470b8332018-06-06 19:44:10 +00004103 StringRef Arch;
4104 if (TargetDeviceOffloadKind == Action::OFK_HIP) {
4105 if (UI.DependentOffloadKind == Action::OFK_Host)
Yaxun Liuf37b50a2018-07-24 01:03:44 +00004106 Arch = StringRef();
Yaxun Liu470b8332018-06-06 19:44:10 +00004107 else
4108 Arch = UI.DependentBoundArch;
4109 } else
4110 Arch = BoundArch;
4111
4112 CachedResults[{A, GetTriplePlusArchString(UI.DependentToolChain, Arch,
4113 UI.DependentOffloadKind)}] =
4114 CurI;
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004115 }
4116
4117 // Now that we have all the results generated, select the one that should be
4118 // returned for the current depending action.
4119 std::pair<const Action *, std::string> ActionTC = {
4120 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
4121 assert(CachedResults.find(ActionTC) != CachedResults.end() &&
4122 "Result does not exist??");
4123 Result = CachedResults[ActionTC];
4124 } else if (JA->getType() == types::TY_Nothing)
Justin Lebard98cea82016-01-11 23:15:21 +00004125 Result = InputInfo(A, BaseInput);
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004126 else {
4127 // We only have to generate a prefix for the host if this is not a top-level
4128 // action.
4129 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
4130 A->getOffloadingDeviceKind(), TC->getTriple().normalize(),
4131 /*CreatePrefixForHost=*/!!A->getOffloadingHostActiveKinds() &&
4132 !AtTopLevel);
Justin Lebard98cea82016-01-11 23:15:21 +00004133 Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
Samuel Antaod06239d2016-07-15 23:13:27 +00004134 AtTopLevel, MultipleArchs,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004135 OffloadingPrefix),
Justin Lebard98cea82016-01-11 23:15:21 +00004136 BaseInput);
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004137 }
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004138
Chad Rosierbe10f982011-08-02 17:58:04 +00004139 if (CCCPrintBindings && !CCGenDiagnostics) {
Rafael Espindola79764462013-03-24 15:06:53 +00004140 llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
4141 << " - \"" << T->getName() << "\", inputs: [";
Daniel Dunbarb39cc522009-03-17 22:47:06 +00004142 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
4143 llvm::errs() << InputInfos[i].getAsString();
4144 if (i + 1 != e)
4145 llvm::errs() << ", ";
4146 }
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004147 if (UnbundlingResults.empty())
4148 llvm::errs() << "], output: " << Result.getAsString() << "\n";
4149 else {
4150 llvm::errs() << "], outputs: [";
4151 for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) {
4152 llvm::errs() << UnbundlingResults[i].getAsString();
4153 if (i + 1 != e)
4154 llvm::errs() << ", ";
4155 }
4156 llvm::errs() << "] \n";
4157 }
Daniel Dunbarb39cc522009-03-17 22:47:06 +00004158 } else {
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004159 if (UnbundlingResults.empty())
4160 T->ConstructJob(
4161 C, *JA, Result, InputInfos,
4162 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
4163 LinkingOutput);
4164 else
Samuel Antao7108bf32016-11-03 15:41:50 +00004165 T->ConstructJobMultipleOutputs(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004166 C, *JA, UnbundlingResults, InputInfos,
4167 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
4168 LinkingOutput);
Daniel Dunbarb39cc522009-03-17 22:47:06 +00004169 }
Justin Lebar9eaa4892016-01-11 23:09:32 +00004170 return Result;
Daniel Dunbare75d8342009-03-16 06:56:51 +00004171}
4172
Hans Wennborga7707222015-01-09 17:38:53 +00004173const char *Driver::getDefaultImageName() const {
Petr Hosekdd38d932018-05-29 22:35:39 +00004174 llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
Hans Wennborga7707222015-01-09 17:38:53 +00004175 return Target.isOSWindows() ? "a.exe" : "a.out";
4176}
4177
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004178/// Create output filename based on ArgValue, which could either be a
Hans Wennborg2c21f742013-10-17 16:16:23 +00004179/// full filename, filename without extension, or a directory. If ArgValue
4180/// does not provide a filename, then use BaseName, and use the extension
4181/// suitable for FileType.
Hans Wennborg207fcf02013-08-12 21:56:42 +00004182static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004183 StringRef BaseName,
4184 types::ID FileType) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00004185 SmallString<128> Filename = ArgValue;
Justin Bogner5aaf2e72014-06-26 20:59:36 +00004186
Hans Wennborgf1a74252013-09-10 20:18:04 +00004187 if (ArgValue.empty()) {
4188 // If the argument is empty, output to BaseName in the current dir.
4189 Filename = BaseName;
4190 } else if (llvm::sys::path::is_separator(Filename.back())) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00004191 // If the argument is a directory, output to BaseName in that dir.
4192 llvm::sys::path::append(Filename, BaseName);
4193 }
4194
4195 if (!llvm::sys::path::has_extension(ArgValue)) {
4196 // If the argument didn't provide an extension, then set it.
4197 const char *Extension = types::getTypeTempSuffix(FileType, true);
Hans Wennborgf1a74252013-09-10 20:18:04 +00004198
4199 if (FileType == types::TY_Image &&
4200 Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
4201 // The output file is a dll.
4202 Extension = "dll";
4203 }
4204
Hans Wennborg207fcf02013-08-12 21:56:42 +00004205 llvm::sys::path::replace_extension(Filename, Extension);
4206 }
4207
4208 return Args.MakeArgString(Filename.c_str());
4209}
4210
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004211const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004212 const char *BaseInput,
Mehdi Aminic50b1a22016-10-07 21:27:26 +00004213 StringRef BoundArch, bool AtTopLevel,
Samuel Antaod06239d2016-07-15 23:13:27 +00004214 bool MultipleArchs,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004215 StringRef OffloadingPrefix) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00004216 llvm::PrettyStackTraceString CrashInfo("Computing output path");
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004217 // Output to a user requested destination?
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004218 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004219 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
Chad Rosier633dcdc2013-01-24 19:14:47 +00004220 return C.addResultFile(FinalOutput->getValue(), &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004221 }
4222
Hans Wennborge0053472013-12-20 18:40:46 +00004223 // For /P, preprocess to file named after BaseInput.
4224 if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
4225 assert(AtTopLevel && isa<PreprocessJobAction>(JA));
4226 StringRef BaseName = llvm::sys::path::filename(BaseInput);
Hans Wennborg04c764f2014-06-17 00:19:12 +00004227 StringRef NameArg;
Greg Bedwell065f70a2015-06-09 10:24:06 +00004228 if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
Hans Wennborg04c764f2014-06-17 00:19:12 +00004229 NameArg = A->getValue();
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004230 return C.addResultFile(
4231 MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
4232 &JA);
Hans Wennborge0053472013-12-20 18:40:46 +00004233 }
4234
Nick Lewycky6e1ce292010-09-24 00:46:53 +00004235 // Default to writing to stdout?
David Blaikiebc023c92018-06-14 23:09:06 +00004236 if (AtTopLevel && !CCGenDiagnostics && isa<PreprocessJobAction>(JA))
Nick Lewycky6e1ce292010-09-24 00:46:53 +00004237 return "-";
4238
Hans Wennborg2c21f742013-10-17 16:16:23 +00004239 // Is this the assembly listing for /FA?
4240 if (JA.getType() == types::TY_PP_Asm &&
4241 (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
4242 C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
4243 // Use /Fa and the input filename to determine the asm file name.
4244 StringRef BaseName = llvm::sys::path::filename(BaseInput);
4245 StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004246 return C.addResultFile(
4247 MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
4248 &JA);
Hans Wennborg2c21f742013-10-17 16:16:23 +00004249 }
4250
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004251 // Output to a temporary file?
Reid Kleckner68eb60b2015-02-02 22:41:48 +00004252 if ((!AtTopLevel && !isSaveTempsEnabled() &&
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004253 !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
Chad Rosierbe10f982011-08-02 17:58:04 +00004254 CCGenDiagnostics) {
Chad Rosier97c37372011-08-26 22:27:02 +00004255 StringRef Name = llvm::sys::path::filename(BaseInput);
4256 std::pair<StringRef, StringRef> Split = Name.split('.');
Bob Haarman7e4d3ff2018-07-09 21:07:20 +00004257 SmallString<128> TmpName;
4258 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
4259 Arg *A = C.getArgs().getLastArg(options::OPT_fcrash_diagnostics_dir);
4260 if (CCGenDiagnostics && A) {
4261 SmallString<128> CrashDirectory(A->getValue());
4262 llvm::sys::path::append(CrashDirectory, Split.first);
4263 const char *Middle = Suffix ? "-%%%%%%." : "-%%%%%%";
4264 std::error_code EC =
4265 llvm::sys::fs::createUniqueFile(CrashDirectory + Middle + Suffix, TmpName);
4266 if (EC) {
4267 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
4268 return "";
4269 }
4270 } else {
4271 TmpName = GetTemporaryPath(Split.first, Suffix);
4272 }
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00004273 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004274 }
4275
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004276 SmallString<128> BasePath(BaseInput);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004277 StringRef BaseName;
Daniel Dunbar67fea712011-03-25 18:16:51 +00004278
4279 // Dsymutil actions should use the full path.
Eric Christopher551ef452011-08-23 17:56:55 +00004280 if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
Daniel Dunbar67fea712011-03-25 18:16:51 +00004281 BaseName = BasePath;
4282 else
4283 BaseName = llvm::sys::path::filename(BasePath);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004284
4285 // Determine what the derived output name should be.
4286 const char *NamedOutput;
Hans Wennborg2b89a262013-08-06 22:11:28 +00004287
Hans Wennborg625fba82016-10-04 21:01:04 +00004288 if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) &&
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00004289 C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
4290 // The /Fo or /o flag decides the object filename.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004291 StringRef Val =
4292 C.getArgs()
4293 .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
4294 ->getValue();
4295 NamedOutput =
4296 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
Hans Wennborg207fcf02013-08-12 21:56:42 +00004297 } else if (JA.getType() == types::TY_Image &&
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004298 C.getArgs().hasArg(options::OPT__SLASH_Fe,
4299 options::OPT__SLASH_o)) {
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00004300 // The /Fe or /o flag names the linked file.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004301 StringRef Val =
4302 C.getArgs()
4303 .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
4304 ->getValue();
4305 NamedOutput =
4306 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
Hans Wennborgf1a74252013-09-10 20:18:04 +00004307 } else if (JA.getType() == types::TY_Image) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00004308 if (IsCLMode()) {
4309 // clang-cl uses BaseName for the executable name.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004310 NamedOutput =
4311 MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
Samuel Antao59efaed2016-10-27 17:31:22 +00004312 } else {
Hans Wennborga7707222015-01-09 17:38:53 +00004313 SmallString<128> Output(getDefaultImageName());
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004314 Output += OffloadingPrefix;
Samuel Antao59efaed2016-10-27 17:31:22 +00004315 if (MultipleArchs && !BoundArch.empty()) {
4316 Output += "-";
4317 Output.append(BoundArch);
4318 }
Chad Rosier35767232013-04-30 22:01:21 +00004319 NamedOutput = C.getArgs().MakeArgString(Output.c_str());
Nico Weber2ca4be92016-03-01 23:16:44 +00004320 }
4321 } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00004322 NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName));
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004323 } else {
Hans Wennborg0a096a02013-09-05 17:05:56 +00004324 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004325 assert(Suffix && "All types used for output should have a suffix.");
4326
4327 std::string::size_type End = std::string::npos;
4328 if (!types::appendSuffixForType(JA.getType()))
4329 End = BaseName.rfind('.');
Chad Rosier35767232013-04-30 22:01:21 +00004330 SmallString<128> Suffixed(BaseName.substr(0, End));
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004331 Suffixed += OffloadingPrefix;
Mehdi Aminic50b1a22016-10-07 21:27:26 +00004332 if (MultipleArchs && !BoundArch.empty()) {
Chad Rosier35767232013-04-30 22:01:21 +00004333 Suffixed += "-";
4334 Suffixed.append(BoundArch);
4335 }
Bob Wilson23a55f12014-12-21 07:00:00 +00004336 // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
4337 // the unoptimized bitcode so that it does not get overwritten by the ".bc"
4338 // optimized bitcode output.
4339 if (!AtTopLevel && C.getArgs().hasArg(options::OPT_emit_llvm) &&
4340 JA.getType() == types::TY_LLVM_BC)
4341 Suffixed += ".tmp";
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004342 Suffixed += '.';
4343 Suffixed += Suffix;
4344 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
4345 }
4346
Reid Kleckner68eb60b2015-02-02 22:41:48 +00004347 // Prepend object file path if -save-temps=obj
4348 if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
4349 JA.getType() != types::TY_PCH) {
4350 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
4351 SmallString<128> TempPath(FinalOutput->getValue());
4352 llvm::sys::path::remove_filename(TempPath);
4353 StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
4354 llvm::sys::path::append(TempPath, OutputFileName);
4355 NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
4356 }
4357
Chad Rosier62135492012-07-09 17:31:28 +00004358 // If we're saving temps and the temp file conflicts with the input file,
Chad Rosier5b58af02012-04-20 20:05:08 +00004359 // then avoid overwriting input file.
Reid Kleckner68eb60b2015-02-02 22:41:48 +00004360 if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
Chad Rosier5b58af02012-04-20 20:05:08 +00004361 bool SameFile = false;
4362 SmallString<256> Result;
4363 llvm::sys::fs::current_path(Result);
4364 llvm::sys::path::append(Result, BaseName);
4365 llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
4366 // Must share the same path to conflict.
4367 if (SameFile) {
4368 StringRef Name = llvm::sys::path::filename(BaseInput);
4369 std::pair<StringRef, StringRef> Split = Name.split('.');
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004370 std::string TmpName = GetTemporaryPath(
4371 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00004372 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
Chad Rosier5b58af02012-04-20 20:05:08 +00004373 }
Chad Rosierf8412cd2011-07-15 21:54:29 +00004374 }
4375
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00004376 // As an annoying special case, PCH generation doesn't strip the pathname.
Nico Weber8ab92192016-03-02 23:29:29 +00004377 if (JA.getType() == types::TY_PCH && !IsCLMode()) {
Michael J. Spencere1696752010-12-18 00:19:12 +00004378 llvm::sys::path::remove_filename(BasePath);
4379 if (BasePath.empty())
Daniel Dunbare6c83192009-03-18 09:58:30 +00004380 BasePath = NamedOutput;
4381 else
Michael J. Spencere1696752010-12-18 00:19:12 +00004382 llvm::sys::path::append(BasePath, NamedOutput);
Chad Rosier633dcdc2013-01-24 19:14:47 +00004383 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004384 } else {
Chad Rosier633dcdc2013-01-24 19:14:47 +00004385 return C.addResultFile(NamedOutput, &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004386 }
4387}
4388
Mehdi Amini12011172016-10-06 05:11:48 +00004389std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const {
Raphael Isemannb23ccec2018-12-10 12:37:46 +00004390 // Search for Name in a list of paths.
Petr Hosek8f2499f2018-09-12 03:26:10 +00004391 auto SearchPaths = [&](const llvm::SmallVectorImpl<std::string> &P)
4392 -> llvm::Optional<std::string> {
4393 // Respect a limited subset of the '-Bprefix' functionality in GCC by
4394 // attempting to use this prefix when looking for file paths.
4395 for (const auto &Dir : P) {
4396 if (Dir.empty())
4397 continue;
4398 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
4399 llvm::sys::path::append(P, Name);
4400 if (llvm::sys::fs::exists(Twine(P)))
Simon Pilgrim4588fc82018-09-13 10:10:18 +00004401 return P.str().str();
Petr Hosek8f2499f2018-09-12 03:26:10 +00004402 }
4403 return None;
4404 };
4405
4406 if (auto P = SearchPaths(PrefixDirs))
4407 return *P;
Chandler Carruth84559242010-03-22 01:52:07 +00004408
Petr Hosek916a4672017-08-10 04:16:38 +00004409 SmallString<128> R(ResourceDir);
4410 llvm::sys::path::append(R, Name);
4411 if (llvm::sys::fs::exists(Twine(R)))
4412 return R.str();
4413
4414 SmallString<128> P(TC.getCompilerRTPath());
Rafael Espindola609a6642013-06-24 18:33:43 +00004415 llvm::sys::path::append(P, Name);
4416 if (llvm::sys::fs::exists(Twine(P)))
Peter Collingbournefa9771f2011-09-06 02:08:31 +00004417 return P.str();
4418
Petr Hosek8f2499f2018-09-12 03:26:10 +00004419 if (auto P = SearchPaths(TC.getLibraryPaths()))
4420 return *P;
4421
4422 if (auto P = SearchPaths(TC.getFilePaths()))
4423 return *P;
Daniel Dunbar68b01a02009-03-18 20:26:19 +00004424
Daniel Dunbar1ce81532009-09-09 22:33:00 +00004425 return Name;
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00004426}
4427
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004428void Driver::generatePrefixedToolNames(
Mehdi Amini12011172016-10-06 05:11:48 +00004429 StringRef Tool, const ToolChain &TC,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004430 SmallVectorImpl<std::string> &Names) const {
Petr Hosekdd38d932018-05-29 22:35:39 +00004431 // FIXME: Needs a better variable than TargetTriple
4432 Names.emplace_back((TargetTriple + "-" + Tool).str());
Benjamin Kramer3204b152015-05-29 19:42:19 +00004433 Names.emplace_back(Tool);
Vasileios Kalintirisc744e122015-11-12 15:26:54 +00004434
4435 // Allow the discovery of tools prefixed with LLVM's default target triple.
Petr Hosekdd38d932018-05-29 22:35:39 +00004436 std::string DefaultTargetTriple = llvm::sys::getDefaultTargetTriple();
4437 if (DefaultTargetTriple != TargetTriple)
4438 Names.emplace_back((DefaultTargetTriple + "-" + Tool).str());
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004439}
4440
Benjamin Kramer7111b912014-11-04 20:26:01 +00004441static bool ScanDirForExecutable(SmallString<128> &Dir,
4442 ArrayRef<std::string> Names) {
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004443 for (const auto &Name : Names) {
4444 llvm::sys::path::append(Dir, Name);
4445 if (llvm::sys::fs::can_execute(Twine(Dir)))
4446 return true;
4447 llvm::sys::path::remove_filename(Dir);
4448 }
4449 return false;
4450}
4451
Mehdi Amini12011172016-10-06 05:11:48 +00004452std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const {
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004453 SmallVector<std::string, 2> TargetSpecificExecutables;
4454 generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
4455
Chandler Carruth84559242010-03-22 01:52:07 +00004456 // Respect a limited subset of the '-Bprefix' functionality in GCC by
Logan Chiencd679fd2012-10-04 08:08:56 +00004457 // attempting to use this prefix when looking for program paths.
Saleem Abdulrasool23d99b12014-09-16 03:48:32 +00004458 for (const auto &PrefixDir : PrefixDirs) {
4459 if (llvm::sys::fs::is_directory(PrefixDir)) {
4460 SmallString<128> P(PrefixDir);
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004461 if (ScanDirForExecutable(P, TargetSpecificExecutables))
Rafael Espindola8be5c052013-06-19 13:24:29 +00004462 return P.str();
Simon Atanasyana47ba292012-10-31 14:39:28 +00004463 } else {
Mehdi Amini12011172016-10-06 05:11:48 +00004464 SmallString<128> P((PrefixDir + Name).str());
Rafael Espindola609a6642013-06-24 18:33:43 +00004465 if (llvm::sys::fs::can_execute(Twine(P)))
Rafael Espindola8be5c052013-06-19 13:24:29 +00004466 return P.str();
Simon Atanasyan86bdab72012-10-31 12:01:53 +00004467 }
Chandler Carruth84559242010-03-22 01:52:07 +00004468 }
4469
Daniel Dunbar68b01a02009-03-18 20:26:19 +00004470 const ToolChain::path_list &List = TC.getProgramPaths();
Saleem Abdulrasool23d99b12014-09-16 03:48:32 +00004471 for (const auto &Path : List) {
4472 SmallString<128> P(Path);
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004473 if (ScanDirForExecutable(P, TargetSpecificExecutables))
Rafael Espindola8be5c052013-06-19 13:24:29 +00004474 return P.str();
Daniel Dunbar68b01a02009-03-18 20:26:19 +00004475 }
4476
Daniel Dunbar76ce7412009-03-23 16:15:50 +00004477 // If all else failed, search the path.
Michael J. Spencerb011d482014-11-07 21:30:32 +00004478 for (const auto &TargetSpecificExecutable : TargetSpecificExecutables)
4479 if (llvm::ErrorOr<std::string> P =
4480 llvm::sys::findProgramByName(TargetSpecificExecutable))
Michael J. Spencer04162ea2014-11-04 01:30:55 +00004481 return *P;
Daniel Dunbar6f668772009-03-18 21:34:08 +00004482
Daniel Dunbar1ce81532009-09-09 22:33:00 +00004483 return Name;
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00004484}
4485
Mehdi Amini12011172016-10-06 05:11:48 +00004486std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const {
Rafael Espindola37d229d2013-06-25 04:26:55 +00004487 SmallString<128> Path;
Rafael Espindolac0809172014-06-12 14:02:15 +00004488 std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
Rafael Espindola37d229d2013-06-25 04:26:55 +00004489 if (EC) {
4490 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
Daniel Dunbare627c1c2009-03-18 19:34:39 +00004491 return "";
4492 }
4493
Rafael Espindola37d229d2013-06-25 04:26:55 +00004494 return Path.str();
Daniel Dunbare627c1c2009-03-18 19:34:39 +00004495}
4496
Steven Wuc3399db62019-01-11 21:16:04 +00004497std::string Driver::GetTemporaryDirectory(StringRef Prefix) const {
4498 SmallString<128> Path;
4499 std::error_code EC = llvm::sys::fs::createUniqueDirectory(Prefix, Path);
4500 if (EC) {
4501 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
4502 return "";
4503 }
4504
4505 return Path.str();
4506}
4507
Nico Weber2ca4be92016-03-01 23:16:44 +00004508std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
4509 SmallString<128> Output;
4510 if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
4511 // FIXME: If anybody needs it, implement this obscure rule:
4512 // "If you specify a directory without a file name, the default file name
4513 // is VCx0.pch., where x is the major version of Visual C++ in use."
4514 Output = FpArg->getValue();
4515
4516 // "If you do not specify an extension as part of the path name, an
4517 // extension of .pch is assumed. "
4518 if (!llvm::sys::path::has_extension(Output))
4519 Output += ".pch";
4520 } else {
Mike Rice58df1af2018-09-11 17:10:44 +00004521 if (Arg *YcArg = C.getArgs().getLastArg(options::OPT__SLASH_Yc))
4522 Output = YcArg->getValue();
4523 if (Output.empty())
4524 Output = BaseName;
Nico Weber2ca4be92016-03-01 23:16:44 +00004525 llvm::sys::path::replace_extension(Output, ".pch");
4526 }
4527 return Output.str();
4528}
4529
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004530const ToolChain &Driver::getToolChain(const ArgList &Args,
Artem Belevich959e0542015-07-10 19:47:55 +00004531 const llvm::Triple &Target) const {
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004532
David Blaikie6ad71012017-01-13 18:53:43 +00004533 auto &TC = ToolChains[Target.str()];
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004534 if (!TC) {
4535 switch (Target.getOS()) {
Reid Kleckner330fb172016-05-11 16:19:05 +00004536 case llvm::Triple::Haiku:
David Blaikie6ad71012017-01-13 18:53:43 +00004537 TC = llvm::make_unique<toolchains::Haiku>(*this, Target, Args);
Reid Kleckner330fb172016-05-11 16:19:05 +00004538 break;
Ed Schouten4dabea22017-06-25 08:29:09 +00004539 case llvm::Triple::Ananas:
4540 TC = llvm::make_unique<toolchains::Ananas>(*this, Target, Args);
4541 break;
Ed Schouten3c3e58c2015-03-26 11:13:44 +00004542 case llvm::Triple::CloudABI:
David Blaikie6ad71012017-01-13 18:53:43 +00004543 TC = llvm::make_unique<toolchains::CloudABI>(*this, Target, Args);
Ed Schouten3c3e58c2015-03-26 11:13:44 +00004544 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004545 case llvm::Triple::Darwin:
4546 case llvm::Triple::MacOSX:
4547 case llvm::Triple::IOS:
Tim Northover6f3ff222015-10-30 16:30:27 +00004548 case llvm::Triple::TvOS:
4549 case llvm::Triple::WatchOS:
David Blaikie6ad71012017-01-13 18:53:43 +00004550 TC = llvm::make_unique<toolchains::DarwinClang>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004551 break;
4552 case llvm::Triple::DragonFly:
David Blaikie6ad71012017-01-13 18:53:43 +00004553 TC = llvm::make_unique<toolchains::DragonFly>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004554 break;
4555 case llvm::Triple::OpenBSD:
David Blaikie6ad71012017-01-13 18:53:43 +00004556 TC = llvm::make_unique<toolchains::OpenBSD>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004557 break;
4558 case llvm::Triple::NetBSD:
David Blaikie6ad71012017-01-13 18:53:43 +00004559 TC = llvm::make_unique<toolchains::NetBSD>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004560 break;
4561 case llvm::Triple::FreeBSD:
David Blaikie6ad71012017-01-13 18:53:43 +00004562 TC = llvm::make_unique<toolchains::FreeBSD>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004563 break;
4564 case llvm::Triple::Minix:
David Blaikie6ad71012017-01-13 18:53:43 +00004565 TC = llvm::make_unique<toolchains::Minix>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004566 break;
4567 case llvm::Triple::Linux:
Andrey Turetskiy4798eb62016-06-16 10:36:09 +00004568 case llvm::Triple::ELFIAMCU:
Chandler Carruthcf705b22012-01-25 21:03:58 +00004569 if (Target.getArch() == llvm::Triple::hexagon)
David Blaikie6ad71012017-01-13 18:53:43 +00004570 TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
4571 Args);
Vasileios Kalintirisc744e122015-11-12 15:26:54 +00004572 else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
4573 !Target.hasEnvironment())
David Blaikie6ad71012017-01-13 18:53:43 +00004574 TC = llvm::make_unique<toolchains::MipsLLVMToolChain>(*this, Target,
4575 Args);
Chandler Carruthcf705b22012-01-25 21:03:58 +00004576 else
David Blaikie6ad71012017-01-13 18:53:43 +00004577 TC = llvm::make_unique<toolchains::Linux>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004578 break;
Derek Schuff6ab52fa2015-03-30 20:31:33 +00004579 case llvm::Triple::NaCl:
David Blaikie6ad71012017-01-13 18:53:43 +00004580 TC = llvm::make_unique<toolchains::NaClToolChain>(*this, Target, Args);
Derek Schuff6ab52fa2015-03-30 20:31:33 +00004581 break;
Petr Hosek62e1d232016-10-06 06:08:09 +00004582 case llvm::Triple::Fuchsia:
David Blaikie6ad71012017-01-13 18:53:43 +00004583 TC = llvm::make_unique<toolchains::Fuchsia>(*this, Target, Args);
Petr Hosek62e1d232016-10-06 06:08:09 +00004584 break;
David Chisnallf571cde2012-02-15 13:39:01 +00004585 case llvm::Triple::Solaris:
David Blaikie6ad71012017-01-13 18:53:43 +00004586 TC = llvm::make_unique<toolchains::Solaris>(*this, Target, Args);
David Chisnallf571cde2012-02-15 13:39:01 +00004587 break;
Tom Stellard8fa33092015-07-18 01:49:05 +00004588 case llvm::Triple::AMDHSA:
David Blaikie6ad71012017-01-13 18:53:43 +00004589 TC = llvm::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args);
Tom Stellard8fa33092015-07-18 01:49:05 +00004590 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004591 case llvm::Triple::Win32:
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004592 switch (Target.getEnvironment()) {
4593 default:
4594 if (Target.isOSBinFormatELF())
David Blaikie6ad71012017-01-13 18:53:43 +00004595 TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004596 else if (Target.isOSBinFormatMachO())
David Blaikie6ad71012017-01-13 18:53:43 +00004597 TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004598 else
David Blaikie6ad71012017-01-13 18:53:43 +00004599 TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004600 break;
4601 case llvm::Triple::GNU:
David Blaikie6ad71012017-01-13 18:53:43 +00004602 TC = llvm::make_unique<toolchains::MinGW>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004603 break;
Saleem Abdulrasool543a78b2014-10-24 03:13:37 +00004604 case llvm::Triple::Itanium:
David Blaikie6ad71012017-01-13 18:53:43 +00004605 TC = llvm::make_unique<toolchains::CrossWindowsToolChain>(*this, Target,
4606 Args);
Saleem Abdulrasool543a78b2014-10-24 03:13:37 +00004607 break;
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004608 case llvm::Triple::MSVC:
4609 case llvm::Triple::UnknownEnvironment:
Dave Leef96bedf2017-11-06 21:18:05 +00004610 if (Args.getLastArgValue(options::OPT_fuse_ld_EQ)
4611 .startswith_lower("bfd"))
4612 TC = llvm::make_unique<toolchains::CrossWindowsToolChain>(
4613 *this, Target, Args);
4614 else
4615 TC =
4616 llvm::make_unique<toolchains::MSVCToolChain>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004617 break;
4618 }
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004619 break;
Filipe Cabecinhasc888e192015-10-14 12:25:43 +00004620 case llvm::Triple::PS4:
David Blaikie6ad71012017-01-13 18:53:43 +00004621 TC = llvm::make_unique<toolchains::PS4CPU>(*this, Target, Args);
Filipe Cabecinhasc888e192015-10-14 12:25:43 +00004622 break;
David L Kreitzerd397ea42016-10-14 20:44:33 +00004623 case llvm::Triple::Contiki:
David Blaikie6ad71012017-01-13 18:53:43 +00004624 TC = llvm::make_unique<toolchains::Contiki>(*this, Target, Args);
David L Kreitzerd397ea42016-10-14 20:44:33 +00004625 break;
Kristina Brooks77a4adc2018-11-29 03:49:14 +00004626 case llvm::Triple::Hurd:
4627 TC = llvm::make_unique<toolchains::Hurd>(*this, Target, Args);
4628 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004629 default:
Douglas Katzman9f5e70e2015-05-26 18:01:33 +00004630 // Of these targets, Hexagon is the only one that might have
4631 // an OS of Linux, in which case it got handled above already.
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004632 switch (Target.getArch()) {
4633 case llvm::Triple::tce:
David Blaikie6ad71012017-01-13 18:53:43 +00004634 TC = llvm::make_unique<toolchains::TCEToolChain>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004635 break;
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00004636 case llvm::Triple::tcele:
David Blaikie6ad71012017-01-13 18:53:43 +00004637 TC = llvm::make_unique<toolchains::TCELEToolChain>(*this, Target, Args);
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00004638 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004639 case llvm::Triple::hexagon:
David Blaikie6ad71012017-01-13 18:53:43 +00004640 TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
4641 Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004642 break;
Jacques Pienaard964cc22016-03-28 21:02:54 +00004643 case llvm::Triple::lanai:
David Blaikie6ad71012017-01-13 18:53:43 +00004644 TC = llvm::make_unique<toolchains::LanaiToolChain>(*this, Target, Args);
Jacques Pienaard964cc22016-03-28 21:02:54 +00004645 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004646 case llvm::Triple::xcore:
David Blaikie6ad71012017-01-13 18:53:43 +00004647 TC = llvm::make_unique<toolchains::XCoreToolChain>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004648 break;
Dan Gohmanc2853072015-09-03 22:51:53 +00004649 case llvm::Triple::wasm32:
4650 case llvm::Triple::wasm64:
David Blaikie6ad71012017-01-13 18:53:43 +00004651 TC = llvm::make_unique<toolchains::WebAssembly>(*this, Target, Args);
Dan Gohmanc2853072015-09-03 22:51:53 +00004652 break;
Dylan McKay924fa3a2017-01-05 05:20:27 +00004653 case llvm::Triple::avr:
David Blaikie6ad71012017-01-13 18:53:43 +00004654 TC = llvm::make_unique<toolchains::AVRToolChain>(*this, Target, Args);
Dylan McKay924fa3a2017-01-05 05:20:27 +00004655 break;
Anton Korobeynikov93165d62019-01-15 19:44:05 +00004656 case llvm::Triple::msp430:
4657 TC =
4658 llvm::make_unique<toolchains::MSP430ToolChain>(*this, Target, Args);
4659 break;
David Bolvanskyf4be2532018-07-31 14:21:46 +00004660 case llvm::Triple::riscv32:
4661 case llvm::Triple::riscv64:
4662 TC = llvm::make_unique<toolchains::RISCVToolChain>(*this, Target, Args);
4663 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004664 default:
Douglas Katzmand6e597c2015-09-17 19:56:40 +00004665 if (Target.getVendor() == llvm::Triple::Myriad)
David Blaikie6ad71012017-01-13 18:53:43 +00004666 TC = llvm::make_unique<toolchains::MyriadToolChain>(*this, Target,
4667 Args);
Jonathan Roelofs901c7762017-05-25 15:42:13 +00004668 else if (toolchains::BareMetal::handlesTarget(Target))
4669 TC = llvm::make_unique<toolchains::BareMetal>(*this, Target, Args);
Douglas Katzmand6e597c2015-09-17 19:56:40 +00004670 else if (Target.isOSBinFormatELF())
David Blaikie6ad71012017-01-13 18:53:43 +00004671 TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004672 else if (Target.isOSBinFormatMachO())
David Blaikie6ad71012017-01-13 18:53:43 +00004673 TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004674 else
David Blaikie6ad71012017-01-13 18:53:43 +00004675 TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004676 }
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004677 }
4678 }
Justin Lebar66c4fd72016-11-18 00:41:22 +00004679
4680 // Intentionally omitted from the switch above: llvm::Triple::CUDA. CUDA
4681 // compiles always need two toolchains, the CUDA toolchain and the host
4682 // toolchain. So the only valid way to create a CUDA toolchain is via
4683 // CreateOffloadingDeviceToolChains.
4684
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004685 return *TC;
Daniel Dunbar4dff6a42009-03-10 23:41:59 +00004686}
Daniel Dunbar8fa879d2009-03-24 18:57:02 +00004687
Rafael Espindola2f69d402013-03-18 15:33:26 +00004688bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
Douglas Katzman00249092015-06-12 15:45:21 +00004689 // Say "no" if there is not exactly one input of a type clang understands.
Nico Weber5a459f82016-02-23 19:30:43 +00004690 if (JA.size() != 1 ||
4691 !types::isAcceptedByClang((*JA.input_begin())->getType()))
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00004692 return false;
4693
Douglas Katzman00249092015-06-12 15:45:21 +00004694 // And say "no" if this is not a kind of action clang understands.
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00004695 if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
Bob Wilson23a55f12014-12-21 07:00:00 +00004696 !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00004697 return false;
4698
4699 return true;
4700}
4701
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00004702/// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
4703/// grouped values as integers. Numbers which are not provided are set to 0.
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004704///
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00004705/// \return True if the entire string was parsed (9.2), or all groups were
4706/// parsed (10.3.5extrastuff).
Mehdi Amini12011172016-10-06 05:11:48 +00004707bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
4708 unsigned &Micro, bool &HadExtra) {
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004709 HadExtra = false;
4710
4711 Major = Minor = Micro = 0;
Mehdi Amini12011172016-10-06 05:11:48 +00004712 if (Str.empty())
Bob Wilson433cb312015-04-07 01:03:35 +00004713 return false;
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004714
Mehdi Amini12011172016-10-06 05:11:48 +00004715 if (Str.consumeInteger(10, Major))
4716 return false;
4717 if (Str.empty())
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004718 return true;
Mehdi Amini12011172016-10-06 05:11:48 +00004719 if (Str[0] != '.')
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004720 return false;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00004721
Mehdi Amini12011172016-10-06 05:11:48 +00004722 Str = Str.drop_front(1);
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004723
Mehdi Amini12011172016-10-06 05:11:48 +00004724 if (Str.consumeInteger(10, Minor))
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004725 return false;
Mehdi Amini12011172016-10-06 05:11:48 +00004726 if (Str.empty())
4727 return true;
4728 if (Str[0] != '.')
4729 return false;
4730 Str = Str.drop_front(1);
4731
4732 if (Str.consumeInteger(10, Micro))
4733 return false;
4734 if (!Str.empty())
4735 HadExtra = true;
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004736 return true;
4737}
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004738
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004739/// Parse digits from a string \p Str and fulfill \p Digits with
4740/// the parsed numbers. This method assumes that the max number of
4741/// digits to look for is equal to Digits.size().
4742///
4743/// \return True if the entire string was parsed and there are
4744/// no extra characters remaining at the end.
Mehdi Amini12011172016-10-06 05:11:48 +00004745bool Driver::GetReleaseVersion(StringRef Str,
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004746 MutableArrayRef<unsigned> Digits) {
Mehdi Amini12011172016-10-06 05:11:48 +00004747 if (Str.empty())
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004748 return false;
4749
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004750 unsigned CurDigit = 0;
4751 while (CurDigit < Digits.size()) {
Mehdi Amini12011172016-10-06 05:11:48 +00004752 unsigned Digit;
4753 if (Str.consumeInteger(10, Digit))
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004754 return false;
Mehdi Amini12011172016-10-06 05:11:48 +00004755 Digits[CurDigit] = Digit;
4756 if (Str.empty())
4757 return true;
4758 if (Str[0] != '.')
4759 return false;
4760 Str = Str.drop_front(1);
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004761 CurDigit++;
4762 }
4763
4764 // More digits than requested, bail out...
4765 return false;
4766}
4767
Hans Wennborg797004d2018-11-08 11:27:04 +00004768std::pair<unsigned, unsigned> Driver::getIncludeExcludeOptionFlagMasks(bool IsClCompatMode) const {
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004769 unsigned IncludedFlagsBitmask = 0;
Rafael Espindolacc707bc2013-09-25 15:54:41 +00004770 unsigned ExcludedFlagsBitmask = options::NoDriverOption;
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004771
Hans Wennborg797004d2018-11-08 11:27:04 +00004772 if (IsClCompatMode) {
Hans Wennborg19076102013-07-31 20:51:53 +00004773 // Include CL and Core options.
4774 IncludedFlagsBitmask |= options::CLOption;
4775 IncludedFlagsBitmask |= options::CoreOption;
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004776 } else {
4777 ExcludedFlagsBitmask |= options::CLOption;
4778 }
4779
4780 return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
4781}
Benjamin Kramerab88f622014-03-25 18:02:07 +00004782
Douglas Katzmanf08fadf2015-06-04 14:40:44 +00004783bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
Benjamin Kramerab88f622014-03-25 18:02:07 +00004784 return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);
4785}