blob: 8b77a59cca4fa67884b6b64d45112883387e7b8f [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 {
Simon Atanasyan27c0f202019-04-02 18:03:15 +0000249 DiagID = IsCLMode()
250 ? diag::warn_drv_unknown_argument_clang_cl_with_suggestion
251 : diag::err_drv_unknown_argument_with_suggestion;
Brian Gesiak24910762018-01-06 00:25:40 +0000252 Diags.Report(DiagID) << ArgString << Nearest;
253 }
254 ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000255 DiagnosticsEngine::Warning;
256 }
Rafael Espindola8a2d4962013-09-23 23:55:25 +0000257
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000258 return Args;
259}
260
Chad Rosier7742b5d2011-07-27 23:36:45 +0000261// Determine which compilation mode we are in. We look for options which
262// affect the phase, starting with the earliest phases, and record which
263// option we used to determine the final phase.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000264phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
265 Arg **FinalPhaseArg) const {
Craig Topper92fc2df2014-05-17 16:56:41 +0000266 Arg *PhaseArg = nullptr;
Chad Rosier7742b5d2011-07-27 23:36:45 +0000267 phases::ID FinalPhase;
Eric Christopherf901e852011-08-17 22:59:59 +0000268
Hans Wennborge50cec32014-06-13 20:59:54 +0000269 // -{E,EP,P,M,MM} only run the preprocessor.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000270 if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
Hans Wennborge50cec32014-06-13 20:59:54 +0000271 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
Hans Wennborge0053472013-12-20 18:40:46 +0000272 (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
273 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000274 FinalPhase = phases::Preprocess;
Eric Christopherf901e852011-08-17 22:59:59 +0000275
Richard Smithdd4ad3d2016-08-30 19:06:26 +0000276 // --precompile only runs up to precompilation.
277 } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile))) {
278 FinalPhase = phases::Precompile;
279
Bob Wilson23a55f12014-12-21 07:00:00 +0000280 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
Chad Rosier7742b5d2011-07-27 23:36:45 +0000281 } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000282 (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
Ben Langmuir2cb4a782014-02-05 22:21:15 +0000283 (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
Chad Rosier7742b5d2011-07-27 23:36:45 +0000284 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
Fariborz Jahanian73223bb2012-04-02 15:59:19 +0000285 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
Ted Kremenekf7639e12012-03-06 20:06:33 +0000286 (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
Chad Rosier7742b5d2011-07-27 23:36:45 +0000287 (PhaseArg = DAL.getLastArg(options::OPT__analyze,
Chad Rosier1aeb15a2012-03-06 23:14:35 +0000288 options::OPT__analyze_auto)) ||
Bob Wilson23a55f12014-12-21 07:00:00 +0000289 (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000290 FinalPhase = phases::Compile;
291
Bob Wilson23a55f12014-12-21 07:00:00 +0000292 // -S only runs up to the backend.
293 } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
294 FinalPhase = phases::Backend;
295
Artem Belevich4242f412015-07-28 21:01:21 +0000296 // -c compilation only runs up to the assembler.
297 } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000298 FinalPhase = phases::Assemble;
299
300 // Otherwise do everything.
301 } else
302 FinalPhase = phases::Link;
303
304 if (FinalPhaseArg)
305 *FinalPhaseArg = PhaseArg;
306
307 return FinalPhase;
308}
309
David Blaikie0aaa7622017-01-13 17:34:15 +0000310static Arg *MakeInputArg(DerivedArgList &Args, OptTable &Opts,
Martin Storsjo665c7a42018-05-04 06:05:58 +0000311 StringRef Value, bool Claim = true) {
David Blaikie0aaa7622017-01-13 17:34:15 +0000312 Arg *A = new Arg(Opts.getOption(options::OPT_INPUT), Value,
Hans Wennborged1d0722013-08-13 21:32:29 +0000313 Args.getBaseArgs().MakeIndex(Value), Value.data());
Hans Wennborg55362852014-05-02 22:55:30 +0000314 Args.AddSynthesizedArg(A);
Martin Storsjo665c7a42018-05-04 06:05:58 +0000315 if (Claim)
316 A->claim();
Hans Wennborged1d0722013-08-13 21:32:29 +0000317 return A;
318}
319
Daniel Dunbar775d4062010-06-11 22:00:26 +0000320DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
321 DerivedArgList *DAL = new DerivedArgList(Args);
322
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000323 bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
Dan Albertf5ffa1a2018-12-18 23:29:35 +0000324 bool HasNostdlibxx = Args.hasArg(options::OPT_nostdlibxx);
Nirav Daveb0bb6142015-11-24 16:07:21 +0000325 bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +0000326 for (Arg *A : Args) {
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000327 // Unfortunately, we have to parse some forwarding options (-Xassembler,
328 // -Xlinker, -Xpreprocessor) because we either integrate their functionality
329 // (assembler and preprocessor), or bypass a previous driver ('collect2').
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000330
331 // Rewrite linker options, to replace --no-demangle with a custom internal
332 // option.
333 if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
334 A->getOption().matches(options::OPT_Xlinker)) &&
335 A->containsValue("--no-demangle")) {
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000336 // Add the rewritten no-demangle argument.
337 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
338
339 // Add the remaining values as Xlinker arguments.
Benjamin Kramer72e64312015-09-24 14:48:49 +0000340 for (StringRef Val : A->getValues())
Douglas Katzmana34b7bf2015-06-30 19:32:57 +0000341 if (Val != "--no-demangle")
342 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), Val);
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000343
344 continue;
345 }
346
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000347 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
348 // some build systems. We don't try to be complete here because we don't
349 // care to encourage this usage model.
350 if (A->getOption().matches(options::OPT_Wp_COMMA) &&
Richard Smithbd55daf2012-11-01 04:30:05 +0000351 (A->getValue(0) == StringRef("-MD") ||
352 A->getValue(0) == StringRef("-MMD"))) {
Daniel Dunbar3648ba72010-06-15 20:30:18 +0000353 // Rewrite to -MD/-MMD along with -MF.
Richard Smithbd55daf2012-11-01 04:30:05 +0000354 if (A->getValue(0) == StringRef("-MD"))
Daniel Dunbar3648ba72010-06-15 20:30:18 +0000355 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
356 else
357 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
Michael J. Spencer70d85be2012-11-07 23:37:14 +0000358 if (A->getNumValues() == 2)
359 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
360 A->getValue(1));
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000361 continue;
362 }
363
Shantonu Senafeb03b2010-09-17 18:39:08 +0000364 // Rewrite reserved library names.
365 if (A->getOption().matches(options::OPT_l)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000366 StringRef Value = A->getValue();
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000367
Shantonu Senafeb03b2010-09-17 18:39:08 +0000368 // Rewrite unless -nostdlib is present.
Dan Albertf5ffa1a2018-12-18 23:29:35 +0000369 if (!HasNostdlib && !HasNodefaultlib && !HasNostdlibxx &&
370 Value == "stdc++") {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000371 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_stdcxx));
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000372 continue;
373 }
Shantonu Senafeb03b2010-09-17 18:39:08 +0000374
375 // Rewrite unconditionally.
376 if (Value == "cc_kext") {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000377 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_cckext));
Shantonu Senafeb03b2010-09-17 18:39:08 +0000378 continue;
379 }
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000380 }
381
Hans Wennborged1d0722013-08-13 21:32:29 +0000382 // Pick up inputs via the -- option.
383 if (A->getOption().matches(options::OPT__DASH_DASH)) {
384 A->claim();
Benjamin Kramer72e64312015-09-24 14:48:49 +0000385 for (StringRef Val : A->getValues())
Martin Storsjo665c7a42018-05-04 06:05:58 +0000386 DAL->append(MakeInputArg(*DAL, *Opts, Val, false));
Hans Wennborged1d0722013-08-13 21:32:29 +0000387 continue;
388 }
389
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +0000390 DAL->append(A);
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000391 }
Daniel Dunbar775d4062010-06-11 22:00:26 +0000392
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000393 // Enforce -static if -miamcu is present.
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000394 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false))
395 DAL->AddFlagArg(0, Opts->getOption(options::OPT_static));
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000396
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000397// Add a default value of -mlinker-version=, if one was given and the user
398// didn't specify one.
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000399#if defined(HOST_LINK_VERSION)
Tim Northover018578c2015-06-12 19:21:35 +0000400 if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
401 strlen(HOST_LINK_VERSION) > 0) {
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000402 DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
403 HOST_LINK_VERSION);
Daniel Dunbarb613ffc2010-08-17 22:32:45 +0000404 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000405 }
406#endif
407
Daniel Dunbar775d4062010-06-11 22:00:26 +0000408 return DAL;
409}
410
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000411/// Compute target triple from args.
Artem Belevich959e0542015-07-10 19:47:55 +0000412///
413/// This routine provides the logic to compute a target triple from various
414/// args passed to the driver and the default triple string.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000415static llvm::Triple computeTargetTriple(const Driver &D,
Petr Hosekdd38d932018-05-29 22:35:39 +0000416 StringRef TargetTriple,
Artem Belevich959e0542015-07-10 19:47:55 +0000417 const ArgList &Args,
418 StringRef DarwinArchName = "") {
419 // FIXME: Already done in Compilation *Driver::BuildCompilation
420 if (const Arg *A = Args.getLastArg(options::OPT_target))
Petr Hosekdd38d932018-05-29 22:35:39 +0000421 TargetTriple = A->getValue();
Artem Belevich959e0542015-07-10 19:47:55 +0000422
Petr Hosekdd38d932018-05-29 22:35:39 +0000423 llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
Artem Belevich959e0542015-07-10 19:47:55 +0000424
Kristina Brooks77a4adc2018-11-29 03:49:14 +0000425 // GNU/Hurd's triples should have been -hurd-gnu*, but were historically made
426 // -gnu* only, and we can not change this, so we have to detect that case as
427 // being the Hurd OS.
428 if (TargetTriple.find("-unknown-gnu") != StringRef::npos ||
429 TargetTriple.find("-pc-gnu") != StringRef::npos)
430 Target.setOSName("hurd");
431
Artem Belevich959e0542015-07-10 19:47:55 +0000432 // Handle Apple-specific options available here.
433 if (Target.isOSBinFormatMachO()) {
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000434 // If an explicit Darwin arch name is given, that trumps all.
Artem Belevich959e0542015-07-10 19:47:55 +0000435 if (!DarwinArchName.empty()) {
436 tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
437 return Target;
438 }
439
440 // Handle the Darwin '-arch' flag.
441 if (Arg *A = Args.getLastArg(options::OPT_arch)) {
442 StringRef ArchName = A->getValue();
443 tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
444 }
445 }
446
447 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
448 // '-mbig-endian'/'-EB'.
449 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
450 options::OPT_mbig_endian)) {
451 if (A->getOption().matches(options::OPT_mlittle_endian)) {
452 llvm::Triple LE = Target.getLittleEndianArchVariant();
453 if (LE.getArch() != llvm::Triple::UnknownArch)
454 Target = std::move(LE);
455 } else {
456 llvm::Triple BE = Target.getBigEndianArchVariant();
457 if (BE.getArch() != llvm::Triple::UnknownArch)
458 Target = std::move(BE);
459 }
460 }
461
462 // Skip further flag support on OSes which don't support '-m32' or '-m64'.
Douglas Katzman15a63ed2015-08-12 18:36:12 +0000463 if (Target.getArch() == llvm::Triple::tce ||
464 Target.getOS() == llvm::Triple::Minix)
Artem Belevich959e0542015-07-10 19:47:55 +0000465 return Target;
466
467 // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000468 Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
469 options::OPT_m32, options::OPT_m16);
470 if (A) {
Artem Belevich959e0542015-07-10 19:47:55 +0000471 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
472
473 if (A->getOption().matches(options::OPT_m64)) {
474 AT = Target.get64BitArchVariant().getArch();
475 if (Target.getEnvironment() == llvm::Triple::GNUX32)
476 Target.setEnvironment(llvm::Triple::GNU);
477 } else if (A->getOption().matches(options::OPT_mx32) &&
478 Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
479 AT = llvm::Triple::x86_64;
480 Target.setEnvironment(llvm::Triple::GNUX32);
481 } else if (A->getOption().matches(options::OPT_m32)) {
482 AT = Target.get32BitArchVariant().getArch();
483 if (Target.getEnvironment() == llvm::Triple::GNUX32)
484 Target.setEnvironment(llvm::Triple::GNU);
485 } else if (A->getOption().matches(options::OPT_m16) &&
486 Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
487 AT = llvm::Triple::x86;
488 Target.setEnvironment(llvm::Triple::CODE16);
489 }
490
491 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
492 Target.setArch(AT);
493 }
494
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000495 // Handle -miamcu flag.
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000496 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
497 if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
498 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
499 << Target.str();
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000500
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000501 if (A && !A->getOption().matches(options::OPT_m32))
502 D.Diag(diag::err_drv_argument_not_allowed_with)
503 << "-miamcu" << A->getBaseArg().getAsString(Args);
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000504
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000505 Target.setArch(llvm::Triple::x86);
506 Target.setArchName("i586");
507 Target.setEnvironment(llvm::Triple::UnknownEnvironment);
508 Target.setEnvironmentName("");
509 Target.setOS(llvm::Triple::ELFIAMCU);
510 Target.setVendor(llvm::Triple::UnknownVendor);
511 Target.setVendorName("intel");
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000512 }
513
Simon Atanasyan0c0fb4b2018-09-27 05:04:50 +0000514 // If target is MIPS adjust the target triple
515 // accordingly to provided ABI name.
516 A = Args.getLastArg(options::OPT_mabi_EQ);
Simon Atanasyane60eae42018-10-16 10:19:06 +0000517 if (A && Target.isMIPS()) {
518 StringRef ABIName = A->getValue();
519 if (ABIName == "32") {
520 Target = Target.get32BitArchVariant();
521 if (Target.getEnvironment() == llvm::Triple::GNUABI64 ||
522 Target.getEnvironment() == llvm::Triple::GNUABIN32)
523 Target.setEnvironment(llvm::Triple::GNU);
524 } else if (ABIName == "n32") {
525 Target = Target.get64BitArchVariant();
526 if (Target.getEnvironment() == llvm::Triple::GNU ||
527 Target.getEnvironment() == llvm::Triple::GNUABI64)
528 Target.setEnvironment(llvm::Triple::GNUABIN32);
529 } else if (ABIName == "64") {
530 Target = Target.get64BitArchVariant();
531 if (Target.getEnvironment() == llvm::Triple::GNU ||
532 Target.getEnvironment() == llvm::Triple::GNUABIN32)
533 Target.setEnvironment(llvm::Triple::GNUABI64);
534 }
535 }
Simon Atanasyan0c0fb4b2018-09-27 05:04:50 +0000536
Artem Belevich959e0542015-07-10 19:47:55 +0000537 return Target;
538}
539
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000540// Parse the LTO options and record the type of LTO compilation
Teresa Johnson945bc502015-10-15 20:35:53 +0000541// based on which -f(no-)?lto(=.*)? option occurs last.
542void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
543 LTOMode = LTOK_None;
544 if (!Args.hasFlag(options::OPT_flto, options::OPT_flto_EQ,
545 options::OPT_fno_lto, false))
546 return;
547
548 StringRef LTOName("full");
549
550 const Arg *A = Args.getLastArg(options::OPT_flto_EQ);
Teresa Johnson6ef80dc2015-11-02 18:03:12 +0000551 if (A)
552 LTOName = A->getValue();
Teresa Johnson945bc502015-10-15 20:35:53 +0000553
554 LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
555 .Case("full", LTOK_Full)
556 .Case("thin", LTOK_Thin)
557 .Default(LTOK_Unknown);
558
559 if (LTOMode == LTOK_Unknown) {
560 assert(A);
561 Diag(diag::err_drv_unsupported_option_argument) << A->getOption().getName()
562 << A->getValue();
563 }
564}
565
Samuel Antao39f9da22016-10-27 16:38:05 +0000566/// Compute the desired OpenMP runtime from the flags provided.
567Driver::OpenMPRuntimeKind Driver::getOpenMPRuntime(const ArgList &Args) const {
568 StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
569
570 const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
571 if (A)
572 RuntimeName = A->getValue();
573
574 auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
575 .Case("libomp", OMPRT_OMP)
576 .Case("libgomp", OMPRT_GOMP)
577 .Case("libiomp5", OMPRT_IOMP5)
578 .Default(OMPRT_Unknown);
579
580 if (RT == OMPRT_Unknown) {
581 if (A)
582 Diag(diag::err_drv_unsupported_option_argument)
583 << A->getOption().getName() << A->getValue();
584 else
585 // FIXME: We could use a nicer diagnostic here.
586 Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
587 }
588
589 return RT;
590}
591
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000592void Driver::CreateOffloadingDeviceToolChains(Compilation &C,
593 InputList &Inputs) {
594
595 //
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000596 // CUDA/HIP
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000597 //
Yaxun Liuf6144222018-05-30 00:53:50 +0000598 // We need to generate a CUDA/HIP toolchain if any of the inputs has a CUDA
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000599 // or HIP type. However, mixed CUDA/HIP compilation is not supported.
600 bool IsCuda =
601 llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000602 return types::isCuda(I.first);
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000603 });
604 bool IsHIP =
605 llvm::any_of(Inputs,
606 [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
607 return types::isHIP(I.first);
608 }) ||
609 C.getInputArgs().hasArg(options::OPT_hip_link);
610 if (IsCuda && IsHIP) {
611 Diag(clang::diag::err_drv_mix_cuda_hip);
612 return;
613 }
Yaxun Liuf6144222018-05-30 00:53:50 +0000614 if (IsCuda) {
Justin Lebar66c4fd72016-11-18 00:41:22 +0000615 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
616 const llvm::Triple &HostTriple = HostTC->getTriple();
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000617 StringRef DeviceTripleStr;
Yaxun Liuf6144222018-05-30 00:53:50 +0000618 auto OFK = Action::OFK_Cuda;
619 DeviceTripleStr =
620 HostTriple.isArch64Bit() ? "nvptx64-nvidia-cuda" : "nvptx-nvidia-cuda";
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000621 llvm::Triple CudaTriple(DeviceTripleStr);
Yaxun Liuf6144222018-05-30 00:53:50 +0000622 // Use the CUDA and host triples as the key into the ToolChains map,
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000623 // because the device toolchain we create depends on both.
David Blaikie6ad71012017-01-13 18:53:43 +0000624 auto &CudaTC = ToolChains[CudaTriple.str() + "/" + HostTriple.str()];
Justin Lebar66c4fd72016-11-18 00:41:22 +0000625 if (!CudaTC) {
David Blaikie6ad71012017-01-13 18:53:43 +0000626 CudaTC = llvm::make_unique<toolchains::CudaToolChain>(
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000627 *this, CudaTriple, *HostTC, C.getInputArgs(), OFK);
Justin Lebar66c4fd72016-11-18 00:41:22 +0000628 }
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000629 C.addOffloadDeviceToolChain(CudaTC.get(), OFK);
Yaxun Liuf6144222018-05-30 00:53:50 +0000630 } else if (IsHIP) {
631 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
632 const llvm::Triple &HostTriple = HostTC->getTriple();
633 StringRef DeviceTripleStr;
634 auto OFK = Action::OFK_HIP;
635 DeviceTripleStr = "amdgcn-amd-amdhsa";
636 llvm::Triple HIPTriple(DeviceTripleStr);
637 // Use the HIP and host triples as the key into the ToolChains map,
638 // because the device toolchain we create depends on both.
639 auto &HIPTC = ToolChains[HIPTriple.str() + "/" + HostTriple.str()];
640 if (!HIPTC) {
641 HIPTC = llvm::make_unique<toolchains::HIPToolChain>(
642 *this, HIPTriple, *HostTC, C.getInputArgs());
643 }
644 C.addOffloadDeviceToolChain(HIPTC.get(), OFK);
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000645 }
646
647 //
Samuel Antao39f9da22016-10-27 16:38:05 +0000648 // OpenMP
649 //
650 // We need to generate an OpenMP toolchain if the user specified targets with
651 // the -fopenmp-targets option.
652 if (Arg *OpenMPTargets =
653 C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
654 if (OpenMPTargets->getNumValues()) {
655 // We expect that -fopenmp-targets is always used in conjunction with the
656 // option -fopenmp specifying a valid runtime with offloading support,
657 // i.e. libomp or libiomp.
658 bool HasValidOpenMPRuntime = C.getInputArgs().hasFlag(
659 options::OPT_fopenmp, options::OPT_fopenmp_EQ,
660 options::OPT_fno_openmp, false);
661 if (HasValidOpenMPRuntime) {
662 OpenMPRuntimeKind OpenMPKind = getOpenMPRuntime(C.getInputArgs());
663 HasValidOpenMPRuntime =
664 OpenMPKind == OMPRT_OMP || OpenMPKind == OMPRT_IOMP5;
665 }
666
667 if (HasValidOpenMPRuntime) {
668 llvm::StringMap<const char *> FoundNormalizedTriples;
669 for (const char *Val : OpenMPTargets->getValues()) {
670 llvm::Triple TT(Val);
671 std::string NormalizedName = TT.normalize();
672
673 // Make sure we don't have a duplicate triple.
674 auto Duplicate = FoundNormalizedTriples.find(NormalizedName);
675 if (Duplicate != FoundNormalizedTriples.end()) {
676 Diag(clang::diag::warn_drv_omp_offload_target_duplicate)
677 << Val << Duplicate->second;
678 continue;
679 }
680
681 // Store the current triple so that we can check for duplicates in the
682 // following iterations.
683 FoundNormalizedTriples[NormalizedName] = Val;
684
685 // If the specified target is invalid, emit a diagnostic.
686 if (TT.getArch() == llvm::Triple::UnknownArch)
687 Diag(clang::diag::err_drv_invalid_omp_target) << Val;
688 else {
Gheorghe-Teodor Bercea6a5df722017-07-06 16:08:15 +0000689 const ToolChain *TC;
690 // CUDA toolchains have to be selected differently. They pair host
691 // and device in their implementation.
692 if (TT.isNVPTX()) {
693 const ToolChain *HostTC =
694 C.getSingleOffloadToolChain<Action::OFK_Host>();
695 assert(HostTC && "Host toolchain should be always defined.");
696 auto &CudaTC =
Gheorghe-Teodor Bercea52898432017-08-09 01:02:19 +0000697 ToolChains[TT.str() + "/" + HostTC->getTriple().normalize()];
Gheorghe-Teodor Bercea6a5df722017-07-06 16:08:15 +0000698 if (!CudaTC)
699 CudaTC = llvm::make_unique<toolchains::CudaToolChain>(
Gheorghe-Teodor Bercea2c926932017-08-08 14:33:05 +0000700 *this, TT, *HostTC, C.getInputArgs(), Action::OFK_OpenMP);
Gheorghe-Teodor Bercea6a5df722017-07-06 16:08:15 +0000701 TC = CudaTC.get();
702 } else
703 TC = &getToolChain(C.getInputArgs(), TT);
704 C.addOffloadDeviceToolChain(TC, Action::OFK_OpenMP);
Samuel Antao39f9da22016-10-27 16:38:05 +0000705 }
706 }
707 } else
708 Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
709 } else
710 Diag(clang::diag::warn_drv_empty_joined_argument)
711 << OpenMPTargets->getAsString(C.getInputArgs());
712 }
713
714 //
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000715 // TODO: Add support for other offloading programming models here.
716 //
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000717}
718
Serge Pavlov208ac652018-01-01 13:27:01 +0000719/// Looks the given directories for the specified file.
720///
721/// \param[out] FilePath File path, if the file was found.
722/// \param[in] Dirs Directories used for the search.
723/// \param[in] FileName Name of the file to search for.
724/// \return True if file was found.
725///
726/// Looks for file specified by FileName sequentially in directories specified
727/// by Dirs.
728///
729static bool searchForFile(SmallVectorImpl<char> &FilePath,
730 ArrayRef<std::string> Dirs,
731 StringRef FileName) {
732 SmallString<128> WPath;
733 for (const StringRef &Dir : Dirs) {
734 if (Dir.empty())
735 continue;
736 WPath.clear();
737 llvm::sys::path::append(WPath, Dir, FileName);
738 llvm::sys::path::native(WPath);
739 if (llvm::sys::fs::is_regular_file(WPath)) {
740 FilePath = std::move(WPath);
741 return true;
742 }
743 }
744 return false;
745}
746
747bool Driver::readConfigFile(StringRef FileName) {
748 // Try reading the given file.
749 SmallVector<const char *, 32> NewCfgArgs;
750 if (!llvm::cl::readConfigFile(FileName, Saver, NewCfgArgs)) {
751 Diag(diag::err_drv_cannot_read_config_file) << FileName;
752 return true;
753 }
754
755 // Read options from config file.
756 llvm::SmallString<128> CfgFileName(FileName);
757 llvm::sys::path::native(CfgFileName);
758 ConfigFile = CfgFileName.str();
759 bool ContainErrors;
760 CfgOptions = llvm::make_unique<InputArgList>(
Hans Wennborg797004d2018-11-08 11:27:04 +0000761 ParseArgStrings(NewCfgArgs, IsCLMode(), ContainErrors));
Serge Pavlov208ac652018-01-01 13:27:01 +0000762 if (ContainErrors) {
763 CfgOptions.reset();
764 return true;
765 }
766
767 if (CfgOptions->hasArg(options::OPT_config)) {
768 CfgOptions.reset();
769 Diag(diag::err_drv_nested_config_file);
770 return true;
771 }
772
773 // Claim all arguments that come from a configuration file so that the driver
774 // does not warn on any that is unused.
775 for (Arg *A : *CfgOptions)
776 A->claim();
777 return false;
778}
779
780bool Driver::loadConfigFile() {
781 std::string CfgFileName;
782 bool FileSpecifiedExplicitly = false;
783
784 // Process options that change search path for config files.
785 if (CLOptions) {
786 if (CLOptions->hasArg(options::OPT_config_system_dir_EQ)) {
787 SmallString<128> CfgDir;
788 CfgDir.append(
789 CLOptions->getLastArgValue(options::OPT_config_system_dir_EQ));
790 if (!CfgDir.empty()) {
Sam McCall296d8322018-01-02 09:35:10 +0000791 if (llvm::sys::fs::make_absolute(CfgDir).value() != 0)
Serge Pavlov208ac652018-01-01 13:27:01 +0000792 SystemConfigDir.clear();
793 else
794 SystemConfigDir = std::string(CfgDir.begin(), CfgDir.end());
795 }
796 }
797 if (CLOptions->hasArg(options::OPT_config_user_dir_EQ)) {
798 SmallString<128> CfgDir;
799 CfgDir.append(
800 CLOptions->getLastArgValue(options::OPT_config_user_dir_EQ));
801 if (!CfgDir.empty()) {
Sam McCall296d8322018-01-02 09:35:10 +0000802 if (llvm::sys::fs::make_absolute(CfgDir).value() != 0)
Serge Pavlov208ac652018-01-01 13:27:01 +0000803 UserConfigDir.clear();
804 else
805 UserConfigDir = std::string(CfgDir.begin(), CfgDir.end());
806 }
807 }
808 }
809
810 // First try to find config file specified in command line.
811 if (CLOptions) {
812 std::vector<std::string> ConfigFiles =
813 CLOptions->getAllArgValues(options::OPT_config);
814 if (ConfigFiles.size() > 1) {
815 Diag(diag::err_drv_duplicate_config);
816 return true;
817 }
818
819 if (!ConfigFiles.empty()) {
820 CfgFileName = ConfigFiles.front();
821 assert(!CfgFileName.empty());
822
823 // If argument contains directory separator, treat it as a path to
824 // configuration file.
825 if (llvm::sys::path::has_parent_path(CfgFileName)) {
826 SmallString<128> CfgFilePath;
827 if (llvm::sys::path::is_relative(CfgFileName))
828 llvm::sys::fs::current_path(CfgFilePath);
829 llvm::sys::path::append(CfgFilePath, CfgFileName);
830 if (!llvm::sys::fs::is_regular_file(CfgFilePath)) {
831 Diag(diag::err_drv_config_file_not_exist) << CfgFilePath;
832 return true;
833 }
834 return readConfigFile(CfgFilePath);
835 }
836
837 FileSpecifiedExplicitly = true;
838 }
839 }
840
841 // If config file is not specified explicitly, try to deduce configuration
842 // from executable name. For instance, an executable 'armv7l-clang' will
843 // search for config file 'armv7l-clang.cfg'.
844 if (CfgFileName.empty() && !ClangNameParts.TargetPrefix.empty())
845 CfgFileName = ClangNameParts.TargetPrefix + '-' + ClangNameParts.ModeSuffix;
846
847 if (CfgFileName.empty())
848 return false;
849
850 // Determine architecture part of the file name, if it is present.
851 StringRef CfgFileArch = CfgFileName;
852 size_t ArchPrefixLen = CfgFileArch.find('-');
853 if (ArchPrefixLen == StringRef::npos)
854 ArchPrefixLen = CfgFileArch.size();
855 llvm::Triple CfgTriple;
856 CfgFileArch = CfgFileArch.take_front(ArchPrefixLen);
857 CfgTriple = llvm::Triple(llvm::Triple::normalize(CfgFileArch));
858 if (CfgTriple.getArch() == llvm::Triple::ArchType::UnknownArch)
859 ArchPrefixLen = 0;
860
861 if (!StringRef(CfgFileName).endswith(".cfg"))
862 CfgFileName += ".cfg";
863
864 // If config file starts with architecture name and command line options
865 // redefine architecture (with options like -m32 -LE etc), try finding new
866 // config file with that architecture.
867 SmallString<128> FixedConfigFile;
868 size_t FixedArchPrefixLen = 0;
869 if (ArchPrefixLen) {
870 // Get architecture name from config file name like 'i386.cfg' or
871 // 'armv7l-clang.cfg'.
872 // Check if command line options changes effective triple.
873 llvm::Triple EffectiveTriple = computeTargetTriple(*this,
874 CfgTriple.getTriple(), *CLOptions);
875 if (CfgTriple.getArch() != EffectiveTriple.getArch()) {
876 FixedConfigFile = EffectiveTriple.getArchName();
877 FixedArchPrefixLen = FixedConfigFile.size();
878 // Append the rest of original file name so that file name transforms
879 // like: i386-clang.cfg -> x86_64-clang.cfg.
880 if (ArchPrefixLen < CfgFileName.size())
881 FixedConfigFile += CfgFileName.substr(ArchPrefixLen);
882 }
883 }
884
885 // Prepare list of directories where config file is searched for.
886 SmallVector<std::string, 3> CfgFileSearchDirs;
887 CfgFileSearchDirs.push_back(UserConfigDir);
888 CfgFileSearchDirs.push_back(SystemConfigDir);
889 CfgFileSearchDirs.push_back(Dir);
890
891 // Try to find config file. First try file with corrected architecture.
892 llvm::SmallString<128> CfgFilePath;
893 if (!FixedConfigFile.empty()) {
894 if (searchForFile(CfgFilePath, CfgFileSearchDirs, FixedConfigFile))
895 return readConfigFile(CfgFilePath);
896 // If 'x86_64-clang.cfg' was not found, try 'x86_64.cfg'.
897 FixedConfigFile.resize(FixedArchPrefixLen);
898 FixedConfigFile.append(".cfg");
899 if (searchForFile(CfgFilePath, CfgFileSearchDirs, FixedConfigFile))
900 return readConfigFile(CfgFilePath);
901 }
902
903 // Then try original file name.
904 if (searchForFile(CfgFilePath, CfgFileSearchDirs, CfgFileName))
905 return readConfigFile(CfgFilePath);
906
907 // Finally try removing driver mode part: 'x86_64-clang.cfg' -> 'x86_64.cfg'.
908 if (!ClangNameParts.ModeSuffix.empty() &&
909 !ClangNameParts.TargetPrefix.empty()) {
910 CfgFileName.assign(ClangNameParts.TargetPrefix);
911 CfgFileName.append(".cfg");
912 if (searchForFile(CfgFilePath, CfgFileSearchDirs, CfgFileName))
913 return readConfigFile(CfgFilePath);
914 }
915
916 // Report error but only if config file was specified explicitly, by option
917 // --config. If it was deduced from executable name, it is not an error.
918 if (FileSpecifiedExplicitly) {
919 Diag(diag::err_drv_config_file_not_found) << CfgFileName;
920 for (const std::string &SearchDir : CfgFileSearchDirs)
921 if (!SearchDir.empty())
922 Diag(diag::note_drv_config_file_searched_in) << SearchDir;
923 return true;
924 }
925
926 return false;
927}
928
Chris Lattner54b16772011-07-23 17:14:25 +0000929Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
Daniel Dunbar2608c542009-03-18 01:38:48 +0000930 llvm::PrettyStackTraceString CrashInfo("Compilation construction");
931
Eric Christopherf901e852011-08-17 22:59:59 +0000932 // FIXME: Handle environment options which affect driver behavior, somewhere
Bill Wendlingadbeb9f2012-03-12 21:24:57 +0000933 // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
Chad Rosier82301162011-09-14 00:47:55 +0000934
David Majnemer85c25b42016-07-24 17:44:03 +0000935 if (Optional<std::string> CompilerPathValue =
936 llvm::sys::Process::GetEnv("COMPILER_PATH")) {
937 StringRef CompilerPath = *CompilerPathValue;
Chad Rosier82301162011-09-14 00:47:55 +0000938 while (!CompilerPath.empty()) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000939 std::pair<StringRef, StringRef> Split =
940 CompilerPath.split(llvm::sys::EnvPathSeparator);
Chad Rosier82301162011-09-14 00:47:55 +0000941 PrefixDirs.push_back(Split.first);
942 CompilerPath = Split.second;
943 }
944 }
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +0000945
Hans Wennborg70850d82013-07-18 20:29:38 +0000946 // We look for the driver mode option early, because the mode can affect
947 // how other options are parsed.
Zachary Turneraff19c32016-08-12 17:47:52 +0000948 ParseDriverMode(ClangExecutable, ArgList.slice(1));
Hans Wennborg70850d82013-07-18 20:29:38 +0000949
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +0000950 // FIXME: What are we going to do with -V and -b?
951
Serge Pavlov208ac652018-01-01 13:27:01 +0000952 // Arguments specified in command line.
953 bool ContainsError;
954 CLOptions = llvm::make_unique<InputArgList>(
Hans Wennborg797004d2018-11-08 11:27:04 +0000955 ParseArgStrings(ArgList.slice(1), IsCLMode(), ContainsError));
Serge Pavlov208ac652018-01-01 13:27:01 +0000956
957 // Try parsing configuration file.
958 if (!ContainsError)
959 ContainsError = loadConfigFile();
960 bool HasConfigFile = !ContainsError && (CfgOptions.get() != nullptr);
961
962 // All arguments, from both config file and command line.
963 InputArgList Args = std::move(HasConfigFile ? std::move(*CfgOptions)
964 : std::move(*CLOptions));
Hans Wennborg797004d2018-11-08 11:27:04 +0000965
966 auto appendOneArg = [&Args](const Arg *Opt, const Arg *BaseArg) {
Serge Pavlovf015a562018-04-26 06:28:47 +0000967 unsigned Index = Args.MakeIndex(Opt->getSpelling());
Serge Pavlov208ac652018-01-01 13:27:01 +0000968 Arg *Copy = new llvm::opt::Arg(Opt->getOption(), Opt->getSpelling(),
Serge Pavlovf015a562018-04-26 06:28:47 +0000969 Index, BaseArg);
Serge Pavlov208ac652018-01-01 13:27:01 +0000970 Copy->getValues() = Opt->getValues();
971 if (Opt->isClaimed())
972 Copy->claim();
973 Args.append(Copy);
Hans Wennborg797004d2018-11-08 11:27:04 +0000974 };
975
976 if (HasConfigFile)
977 for (auto *Opt : *CLOptions) {
978 if (Opt->getOption().matches(options::OPT_config))
979 continue;
980 const Arg *BaseArg = &Opt->getBaseArg();
981 if (BaseArg == Opt)
982 BaseArg = nullptr;
983 appendOneArg(Opt, BaseArg);
Serge Pavlov208ac652018-01-01 13:27:01 +0000984 }
985
Hans Wennborg797004d2018-11-08 11:27:04 +0000986 // In CL mode, look for any pass-through arguments
987 if (IsCLMode() && !ContainsError) {
988 SmallVector<const char *, 16> CLModePassThroughArgList;
989 for (const auto *A : Args.filtered(options::OPT__SLASH_clang)) {
990 A->claim();
991 CLModePassThroughArgList.push_back(A->getValue());
992 }
993
994 if (!CLModePassThroughArgList.empty()) {
995 // Parse any pass through args using default clang processing rather
996 // than clang-cl processing.
997 auto CLModePassThroughOptions = llvm::make_unique<InputArgList>(
998 ParseArgStrings(CLModePassThroughArgList, false, ContainsError));
999
1000 if (!ContainsError)
1001 for (auto *Opt : *CLModePassThroughOptions) {
1002 appendOneArg(Opt, nullptr);
1003 }
1004 }
1005 }
1006
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001007 // FIXME: This stuff needs to go into the Compilation, not the driver.
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001008 bool CCCPrintPhases;
Daniel Dunbard02cb1d2009-03-05 06:38:47 +00001009
Filipe Cabecinhas136f35e2015-07-18 06:35:24 +00001010 // Silence driver warnings if requested
1011 Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w));
1012
Rafael Espindola59ae7992009-12-07 18:28:29 +00001013 // -no-canonical-prefixes is used very early in main.
David Blaikie69a1d8c2015-06-22 22:07:27 +00001014 Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
Rafael Espindola59ae7992009-12-07 18:28:29 +00001015
Daniel Dunbar926f81f2010-08-02 02:38:03 +00001016 // Ignore -pipe.
David Blaikie69a1d8c2015-06-22 22:07:27 +00001017 Args.ClaimAllArgs(options::OPT_pipe);
Daniel Dunbar926f81f2010-08-02 02:38:03 +00001018
Daniel Dunbaracd69572009-12-04 21:55:23 +00001019 // Extract -ccc args.
Daniel Dunbaree66cf22009-03-10 20:52:46 +00001020 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001021 // FIXME: We need to figure out where this behavior should live. Most of it
1022 // should be outside in the client; the parts that aren't should have proper
1023 // options, either by introducing new ones or by overloading gcc ones like -V
1024 // or -b.
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001025 CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
David Blaikie69a1d8c2015-06-22 22:07:27 +00001026 CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
1027 if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
Richard Smithbd55daf2012-11-01 04:30:05 +00001028 CCCGenericGCCName = A->getValue();
Bruno Cardoso Lopes52dfe712017-04-12 21:46:20 +00001029 GenReproducer = Args.hasFlag(options::OPT_gen_reproducer,
1030 options::OPT_fno_crash_diagnostics,
1031 !!::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH"));
Petr Hosekdd38d932018-05-29 22:35:39 +00001032 // FIXME: TargetTriple is used by the target-prefixed calls to as/ld
Joerg Sonnenberger17d75512012-02-22 19:15:16 +00001033 // and getToolChain is const.
Hans Wennborg2e274592013-08-13 23:38:57 +00001034 if (IsCLMode()) {
Hans Wennborg73609a02014-03-28 01:19:04 +00001035 // clang-cl targets MSVC-style Win32.
Petr Hosekdd38d932018-05-29 22:35:39 +00001036 llvm::Triple T(TargetTriple);
Hans Wennborg9d9ce7a2014-03-28 20:49:28 +00001037 T.setOS(llvm::Triple::Win32);
Hans Wennborg0f0e8d62015-09-18 17:11:50 +00001038 T.setVendor(llvm::Triple::PC);
Hans Wennborg9d9ce7a2014-03-28 20:49:28 +00001039 T.setEnvironment(llvm::Triple::MSVC);
Oleg Ranevskyy80523182017-08-31 20:31:30 +00001040 T.setObjectFormat(llvm::Triple::COFF);
Petr Hosekdd38d932018-05-29 22:35:39 +00001041 TargetTriple = T.str();
Hans Wennborg2e274592013-08-13 23:38:57 +00001042 }
David Blaikie69a1d8c2015-06-22 22:07:27 +00001043 if (const Arg *A = Args.getLastArg(options::OPT_target))
Petr Hosekdd38d932018-05-29 22:35:39 +00001044 TargetTriple = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +00001045 if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
Richard Smithbd55daf2012-11-01 04:30:05 +00001046 Dir = InstalledDir = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +00001047 for (const Arg *A : Args.filtered(options::OPT_B)) {
Benjamin Kramer1a648d12011-02-08 20:31:42 +00001048 A->claim();
Richard Smithbd55daf2012-11-01 04:30:05 +00001049 PrefixDirs.push_back(A->getValue(0));
Benjamin Kramer1a648d12011-02-08 20:31:42 +00001050 }
David Blaikie69a1d8c2015-06-22 22:07:27 +00001051 if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
Richard Smithbd55daf2012-11-01 04:30:05 +00001052 SysRoot = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +00001053 if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
Peter Collingbourne9d9e1fc2013-05-27 21:40:20 +00001054 DyldPrefix = A->getValue();
Daniel Dunbaree66cf22009-03-10 20:52:46 +00001055
David Blaikie69a1d8c2015-06-22 22:07:27 +00001056 if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
Bob Wilsona20a1da2013-03-23 05:17:59 +00001057 ResourceDir = A->getValue();
Jim Grosbach061dabf2013-03-12 20:17:58 +00001058
David Blaikie69a1d8c2015-06-22 22:07:27 +00001059 if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
Reid Kleckner68eb60b2015-02-02 22:41:48 +00001060 SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
1061 .Case("cwd", SaveTempsCwd)
1062 .Case("obj", SaveTempsObj)
1063 .Default(SaveTempsCwd);
1064 }
1065
Steven Wu1257cd82016-05-18 17:04:52 +00001066 setLTOMode(Args);
1067
Steven Wu844ab6a2016-11-16 06:06:44 +00001068 // Process -fembed-bitcode= flags.
1069 if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
1070 StringRef Name = A->getValue();
1071 unsigned Model = llvm::StringSwitch<unsigned>(Name)
1072 .Case("off", EmbedNone)
1073 .Case("all", EmbedBitcode)
1074 .Case("bitcode", EmbedBitcode)
1075 .Case("marker", EmbedMarker)
1076 .Default(~0U);
1077 if (Model == ~0U) {
1078 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
1079 << Name;
1080 } else
1081 BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
Steven Wu574b0f22016-03-01 01:07:58 +00001082 }
1083
David Blaikie69a1d8c2015-06-22 22:07:27 +00001084 std::unique_ptr<llvm::opt::InputArgList> UArgs =
1085 llvm::make_unique<InputArgList>(std::move(Args));
1086
Daniel Dunbar775d4062010-06-11 22:00:26 +00001087 // Perform the default argument translations.
David Blaikie69a1d8c2015-06-22 22:07:27 +00001088 DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
Daniel Dunbar775d4062010-06-11 22:00:26 +00001089
Chandler Carruthcb916192012-01-25 08:49:21 +00001090 // Owned by the host.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +00001091 const ToolChain &TC = getToolChain(
Petr Hosekdd38d932018-05-29 22:35:39 +00001092 *UArgs, computeTargetTriple(*this, TargetTriple, *UArgs));
Chandler Carruthcb916192012-01-25 08:49:21 +00001093
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00001094 // The compilation takes ownership of Args.
Benjamin Kramer43c0f482017-06-30 13:21:27 +00001095 Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs,
1096 ContainsError);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001097
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001098 if (!HandleImmediateArgs(*C))
1099 return C;
1100
Chad Rosierecdede82011-08-12 22:08:57 +00001101 // Construct the list of inputs.
1102 InputList Inputs;
Hans Wennborged1d0722013-08-13 21:32:29 +00001103 BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
Chad Rosierecdede82011-08-12 22:08:57 +00001104
Samuel Antaoc1ffba52016-06-13 18:10:57 +00001105 // Populate the tool chains for the offloading devices, if any.
1106 CreateOffloadingDeviceToolChains(*C, Inputs);
Justin Lebar0e450a52016-03-30 23:30:25 +00001107
Chandler Carruth7f1417f2012-01-24 10:43:44 +00001108 // Construct the list of abstract actions to perform for this compilation. On
Tim Northover157d9112014-01-16 08:48:16 +00001109 // MachO targets this uses the driver-driver and universal actions.
1110 if (TC.getTriple().isOSBinFormatMachO())
Artem Belevich5e2a3ec2015-11-17 22:28:40 +00001111 BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001112 else
Justin Lebar0f3474c2016-02-11 02:00:50 +00001113 BuildActions(*C, C->getArgs(), Inputs, C->getActions());
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001114
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001115 if (CCCPrintPhases) {
Daniel Dunbareb843be2009-03-18 03:13:20 +00001116 PrintActions(*C);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001117 return C;
1118 }
1119
1120 BuildJobs(*C);
Daniel Dunbaradc91e62009-03-15 01:38:15 +00001121
1122 return C;
Daniel Dunbaree66cf22009-03-10 20:52:46 +00001123}
1124
Justin Bognered9cbe02015-07-09 06:58:31 +00001125static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
1126 llvm::opt::ArgStringList ASL;
1127 for (const auto *A : Args)
1128 A->render(Args, ASL);
1129
1130 for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
1131 if (I != ASL.begin())
1132 OS << ' ';
1133 Command::printArg(OS, *I, true);
1134 }
1135 OS << '\n';
1136}
1137
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +00001138bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename,
1139 SmallString<128> &CrashDiagDir) {
1140 using namespace llvm::sys;
1141 assert(llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin() &&
1142 "Only knows about .crash files on Darwin");
1143
1144 // The .crash file can be found on at ~/Library/Logs/DiagnosticReports/
1145 // (or /Library/Logs/DiagnosticReports for root) and has the filename pattern
1146 // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash.
1147 path::home_directory(CrashDiagDir);
1148 if (CrashDiagDir.startswith("/var/root"))
1149 CrashDiagDir = "/";
1150 path::append(CrashDiagDir, "Library/Logs/DiagnosticReports");
1151 int PID =
1152#if LLVM_ON_UNIX
1153 getpid();
1154#else
1155 0;
1156#endif
1157 std::error_code EC;
1158 fs::file_status FileStatus;
1159 TimePoint<> LastAccessTime;
1160 SmallString<128> CrashFilePath;
1161 // Lookup the .crash files and get the one generated by a subprocess spawned
1162 // by this driver invocation.
1163 for (fs::directory_iterator File(CrashDiagDir, EC), FileEnd;
1164 File != FileEnd && !EC; File.increment(EC)) {
1165 StringRef FileName = path::filename(File->path());
1166 if (!FileName.startswith(Name))
1167 continue;
1168 if (fs::status(File->path(), FileStatus))
1169 continue;
1170 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CrashFile =
1171 llvm::MemoryBuffer::getFile(File->path());
1172 if (!CrashFile)
1173 continue;
1174 // The first line should start with "Process:", otherwise this isn't a real
1175 // .crash file.
1176 StringRef Data = CrashFile.get()->getBuffer();
1177 if (!Data.startswith("Process:"))
1178 continue;
1179 // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]"
1180 size_t ParentProcPos = Data.find("Parent Process:");
1181 if (ParentProcPos == StringRef::npos)
1182 continue;
1183 size_t LineEnd = Data.find_first_of("\n", ParentProcPos);
1184 if (LineEnd == StringRef::npos)
1185 continue;
1186 StringRef ParentProcess = Data.slice(ParentProcPos+15, LineEnd).trim();
1187 int OpenBracket = -1, CloseBracket = -1;
1188 for (size_t i = 0, e = ParentProcess.size(); i < e; ++i) {
1189 if (ParentProcess[i] == '[')
1190 OpenBracket = i;
1191 if (ParentProcess[i] == ']')
1192 CloseBracket = i;
1193 }
1194 // Extract the parent process PID from the .crash file and check whether
1195 // it matches this driver invocation pid.
1196 int CrashPID;
1197 if (OpenBracket < 0 || CloseBracket < 0 ||
1198 ParentProcess.slice(OpenBracket + 1, CloseBracket)
1199 .getAsInteger(10, CrashPID) || CrashPID != PID) {
1200 continue;
1201 }
1202
1203 // Found a .crash file matching the driver pid. To avoid getting an older
1204 // and misleading crash file, continue looking for the most recent.
1205 // FIXME: the driver can dispatch multiple cc1 invocations, leading to
1206 // multiple crashes poiting to the same parent process. Since the driver
1207 // does not collect pid information for the dispatched invocation there's
1208 // currently no way to distinguish among them.
1209 const auto FileAccessTime = FileStatus.getLastModificationTime();
1210 if (FileAccessTime > LastAccessTime) {
1211 CrashFilePath.assign(File->path());
1212 LastAccessTime = FileAccessTime;
1213 }
1214 }
1215
1216 // If found, copy it over to the location of other reproducer files.
1217 if (!CrashFilePath.empty()) {
1218 EC = fs::copy_file(CrashFilePath, ReproCrashFilename);
1219 if (EC)
1220 return false;
1221 return true;
1222 }
1223
1224 return false;
1225}
1226
Eric Christopherf901e852011-08-17 22:59:59 +00001227// When clang crashes, produce diagnostic information including the fully
1228// preprocessed source file(s). Request that the developer attach the
Chad Rosierbe10f982011-08-02 17:58:04 +00001229// diagnostic information to a bug report.
Alex Lorenz045c5142018-04-07 00:03:27 +00001230void Driver::generateCompilationDiagnostics(
1231 Compilation &C, const Command &FailingCommand,
1232 StringRef AdditionalInformation, CompilationDiagnosticReport *Report) {
Chad Rosier877c0a22012-02-22 00:30:39 +00001233 if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
Chad Rosier62135492012-07-09 17:31:28 +00001234 return;
Chad Rosierbee5a1d2012-03-07 00:30:40 +00001235
Chad Rosierdbf46a12013-02-01 18:30:26 +00001236 // Don't try to generate diagnostics for link or dsymutil jobs.
Justin Bognere1a33d12014-10-20 21:02:05 +00001237 if (FailingCommand.getCreator().isLinkJob() ||
1238 FailingCommand.getCreator().isDsymutilJob())
Chad Rosier877c0a22012-02-22 00:30:39 +00001239 return;
1240
Chad Rosier8179f112012-06-19 17:51:34 +00001241 // Print the version of the compiler.
1242 PrintVersion(C, llvm::errs());
1243
Chad Rosierbe10f982011-08-02 17:58:04 +00001244 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001245 << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the "
1246 "crash backtrace, preprocessed source, and associated run script.";
Chad Rosierbe10f982011-08-02 17:58:04 +00001247
1248 // Suppress driver output and emit preprocessor output to temp file.
Hans Wennborg70850d82013-07-18 20:29:38 +00001249 Mode = CPPMode;
Chad Rosierbe10f982011-08-02 17:58:04 +00001250 CCGenDiagnostics = true;
1251
Chad Rosiercdb008d2011-11-02 21:29:05 +00001252 // Save the original job command(s).
Justin Bogner25645152014-10-21 17:24:44 +00001253 Command Cmd = FailingCommand;
Chad Rosiercdb008d2011-11-02 21:29:05 +00001254
Richard Smith5bb4cdf2012-12-20 02:22:15 +00001255 // Keep track of whether we produce any errors while trying to produce
1256 // preprocessed sources.
1257 DiagnosticErrorTrap Trap(Diags);
1258
1259 // Suppress tool output.
Chad Rosierbe10f982011-08-02 17:58:04 +00001260 C.initCompilationForDiagnostics();
Chad Rosierecdede82011-08-12 22:08:57 +00001261
1262 // Construct the list of inputs.
1263 InputList Inputs;
1264 BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
Chad Rosierbe10f982011-08-02 17:58:04 +00001265
Chad Rosier4f81fc22011-08-12 23:30:05 +00001266 for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
Chad Rosierd57133d2011-08-18 00:22:25 +00001267 bool IgnoreInput = false;
1268
1269 // Ignore input from stdin or any inputs that cannot be preprocessed.
Paul Robinsonf44157d2014-04-28 22:24:44 +00001270 // Check type first as not all linker inputs have a value.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001271 if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
Paul Robinsonf44157d2014-04-28 22:24:44 +00001272 IgnoreInput = true;
1273 } else if (!strcmp(it->second->getValue(), "-")) {
Chad Rosierd57133d2011-08-18 00:22:25 +00001274 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001275 << "Error generating preprocessed source(s) - "
1276 "ignoring input from stdin.";
Chad Rosierd57133d2011-08-18 00:22:25 +00001277 IgnoreInput = true;
Chad Rosierd57133d2011-08-18 00:22:25 +00001278 }
1279
1280 if (IgnoreInput) {
Chad Rosier4f81fc22011-08-12 23:30:05 +00001281 it = Inputs.erase(it);
1282 ie = Inputs.end();
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001283 } else {
Chad Rosier4f81fc22011-08-12 23:30:05 +00001284 ++it;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001285 }
Chad Rosier4f81fc22011-08-12 23:30:05 +00001286 }
Chad Rosierd57133d2011-08-18 00:22:25 +00001287
Chad Rosierc5103c32013-01-29 23:57:10 +00001288 if (Inputs.empty()) {
1289 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001290 << "Error generating preprocessed source(s) - "
1291 "no preprocessable inputs.";
Chad Rosierc5103c32013-01-29 23:57:10 +00001292 return;
1293 }
1294
Chad Rosiere75ef402011-09-06 23:52:36 +00001295 // Don't attempt to generate preprocessed files if multiple -arch options are
Chad Rosier636d2832012-02-13 18:16:28 +00001296 // used, unless they're all duplicates.
1297 llvm::StringSet<> ArchNames;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00001298 for (const Arg *A : C.getArgs()) {
Chad Rosiere75ef402011-09-06 23:52:36 +00001299 if (A->getOption().matches(options::OPT_arch)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001300 StringRef ArchName = A->getValue();
Chad Rosier636d2832012-02-13 18:16:28 +00001301 ArchNames.insert(ArchName);
Chad Rosiere75ef402011-09-06 23:52:36 +00001302 }
1303 }
Chad Rosier636d2832012-02-13 18:16:28 +00001304 if (ArchNames.size() > 1) {
1305 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001306 << "Error generating preprocessed source(s) - cannot generate "
1307 "preprocessed source with multiple -arch options.";
Chad Rosier636d2832012-02-13 18:16:28 +00001308 return;
1309 }
Chad Rosiere75ef402011-09-06 23:52:36 +00001310
Chandler Carruth7f1417f2012-01-24 10:43:44 +00001311 // Construct the list of abstract actions to perform for this compilation. On
1312 // Darwin OSes this uses the driver-driver and builds universal actions.
Chandler Carruthcb916192012-01-25 08:49:21 +00001313 const ToolChain &TC = C.getDefaultToolChain();
Tim Northover157d9112014-01-16 08:48:16 +00001314 if (TC.getTriple().isOSBinFormatMachO())
Artem Belevich5e2a3ec2015-11-17 22:28:40 +00001315 BuildUniversalActions(C, TC, Inputs);
Chad Rosierbe10f982011-08-02 17:58:04 +00001316 else
Justin Lebar0f3474c2016-02-11 02:00:50 +00001317 BuildActions(C, C.getArgs(), Inputs, C.getActions());
Chad Rosierbe10f982011-08-02 17:58:04 +00001318
1319 BuildJobs(C);
1320
1321 // If there were errors building the compilation, quit now.
Richard Smith5bb4cdf2012-12-20 02:22:15 +00001322 if (Trap.hasErrorOccurred()) {
Chad Rosierbe10f982011-08-02 17:58:04 +00001323 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001324 << "Error generating preprocessed source(s).";
Chad Rosierbe10f982011-08-02 17:58:04 +00001325 return;
1326 }
1327
1328 // Generate preprocessed output.
Chad Rosierdd60e092013-01-29 20:15:05 +00001329 SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
Justin Bogner0cd92482015-07-02 22:52:08 +00001330 C.ExecuteJobs(C.getJobs(), FailingCommands);
Chad Rosierbe10f982011-08-02 17:58:04 +00001331
Justin Bognerbc89b182014-10-20 21:20:27 +00001332 // If any of the preprocessing commands failed, clean up and exit.
1333 if (!FailingCommands.empty()) {
Chad Rosierbe10f982011-08-02 17:58:04 +00001334 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001335 << "Error generating preprocessed source(s).";
Justin Bognerbc89b182014-10-20 21:20:27 +00001336 return;
Chad Rosierbe10f982011-08-02 17:58:04 +00001337 }
Justin Bognerbc89b182014-10-20 21:20:27 +00001338
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001339 const ArgStringList &TempFiles = C.getTempFiles();
1340 if (TempFiles.empty()) {
1341 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001342 << "Error generating preprocessed source(s).";
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001343 return;
1344 }
1345
Justin Bognerbc89b182014-10-20 21:20:27 +00001346 Diag(clang::diag::note_drv_command_failed_diag_msg)
1347 << "\n********************\n\n"
1348 "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
1349 "Preprocessed source(s) and associated run script(s) are located at:";
Justin Bognerbc89b182014-10-20 21:20:27 +00001350
Justin Bogner659ecc32014-10-20 22:47:23 +00001351 SmallString<128> VFS;
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +00001352 SmallString<128> ReproCrashFilename;
Justin Bogner659ecc32014-10-20 22:47:23 +00001353 for (const char *TempFile : TempFiles) {
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001354 Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
Alex Lorenz045c5142018-04-07 00:03:27 +00001355 if (Report)
1356 Report->TemporaryFiles.push_back(TempFile);
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +00001357 if (ReproCrashFilename.empty()) {
1358 ReproCrashFilename = TempFile;
1359 llvm::sys::path::replace_extension(ReproCrashFilename, ".crash");
1360 }
Justin Bogner659ecc32014-10-20 22:47:23 +00001361 if (StringRef(TempFile).endswith(".cache")) {
1362 // In some cases (modules) we'll dump extra data to help with reproducing
1363 // the crash into a directory next to the output.
1364 VFS = llvm::sys::path::filename(TempFile);
1365 llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
1366 }
1367 }
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001368
1369 // Assume associated files are based off of the first temporary file.
Justin Bogner25645152014-10-21 17:24:44 +00001370 CrashReportInfo CrashInfo(TempFiles[0], VFS);
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001371
Bob Haarman7e4d3ff2018-07-09 21:07:20 +00001372 llvm::SmallString<128> Script(CrashInfo.Filename);
1373 llvm::sys::path::replace_extension(Script, "sh");
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001374 std::error_code EC;
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001375 llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::CD_CreateNew);
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001376 if (EC) {
1377 Diag(clang::diag::note_drv_command_failed_diag_msg)
Bob Haarman7e4d3ff2018-07-09 21:07:20 +00001378 << "Error generating run script: " << Script << " " << EC.message();
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001379 } else {
Justin Bogner42220ed2015-03-12 00:14:35 +00001380 ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
Justin Bognered9cbe02015-07-09 06:58:31 +00001381 << "# Driver args: ";
1382 printArgList(ScriptOS, C.getInputArgs());
1383 ScriptOS << "# Original command: ";
Justin Bogner42220ed2015-03-12 00:14:35 +00001384 Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
Justin Bogner33bdbc62014-10-21 18:03:08 +00001385 Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
Alex Lorenz045c5142018-04-07 00:03:27 +00001386 if (!AdditionalInformation.empty())
1387 ScriptOS << "\n# Additional information: " << AdditionalInformation
1388 << "\n";
1389 if (Report)
Bob Haarman7e4d3ff2018-07-09 21:07:20 +00001390 Report->TemporaryFiles.push_back(Script.str());
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001391 Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
Justin Bognerbc89b182014-10-20 21:20:27 +00001392 }
Saleem Abdulrasool3661a822015-01-12 02:33:09 +00001393
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +00001394 // On darwin, provide information about the .crash diagnostic report.
1395 if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) {
1396 SmallString<128> CrashDiagDir;
1397 if (getCrashDiagnosticFile(ReproCrashFilename, CrashDiagDir)) {
1398 Diag(clang::diag::note_drv_command_failed_diag_msg)
1399 << ReproCrashFilename.str();
1400 } else { // Suggest a directory for the user to look for .crash files.
1401 llvm::sys::path::append(CrashDiagDir, Name);
1402 CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash";
1403 Diag(clang::diag::note_drv_command_failed_diag_msg)
1404 << "Crash backtrace is located in";
1405 Diag(clang::diag::note_drv_command_failed_diag_msg)
1406 << CrashDiagDir.str();
1407 Diag(clang::diag::note_drv_command_failed_diag_msg)
1408 << "(choose the .crash file that corresponds to your crash)";
1409 }
1410 }
1411
Saleem Abdulrasool3661a822015-01-12 02:33:09 +00001412 for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file,
1413 options::OPT_frewrite_map_file_EQ))
1414 Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
1415
Justin Bognerbc89b182014-10-20 21:20:27 +00001416 Diag(clang::diag::note_drv_command_failed_diag_msg)
1417 << "\n\n********************";
Chad Rosierbe10f982011-08-02 17:58:04 +00001418}
1419
Justin Bogner0cd92482015-07-02 22:52:08 +00001420void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
Simon Atanasyan27c0f202019-04-02 18:03:15 +00001421 // Since commandLineFitsWithinSystemLimits() may underestimate system's
1422 // capacity if the tool does not support response files, there is a chance/
1423 // that things will just work without a response file, so we silently just
1424 // skip it.
Justin Bogner0cd92482015-07-02 22:52:08 +00001425 if (Cmd.getCreator().getResponseFilesSupport() == Tool::RF_None ||
Simon Atanasyan27c0f202019-04-02 18:03:15 +00001426 llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(),
1427 Cmd.getArguments()))
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001428 return;
1429
1430 std::string TmpName = GetTemporaryPath("response", "txt");
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00001431 Cmd.setResponseFile(C.addTempFile(C.getArgs().MakeArgString(TmpName)));
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001432}
1433
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001434int Driver::ExecuteCompilation(
1435 Compilation &C,
1436 SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001437 // Just print if -### was present.
1438 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
Hans Wennborgb212b342013-09-12 18:23:34 +00001439 C.getJobs().Print(llvm::errs(), "\n", true);
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001440 return 0;
1441 }
1442
1443 // If there were errors building the compilation, quit now.
Chad Rosierbe10f982011-08-02 17:58:04 +00001444 if (Diags.hasErrorOccurred())
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001445 return 1;
1446
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001447 // Set up response file names for each command, if necessary
Justin Bogner0cd92482015-07-02 22:52:08 +00001448 for (auto &Job : C.getJobs())
1449 setUpResponseFiles(C, Job);
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001450
Justin Bogner0cd92482015-07-02 22:52:08 +00001451 C.ExecuteJobs(C.getJobs(), FailingCommands);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001452
Daniel Dunbar07494792010-05-22 00:37:20 +00001453 // If the command succeeded, we are done.
Chad Rosierdd60e092013-01-29 20:15:05 +00001454 if (FailingCommands.empty())
1455 return 0;
Daniel Dunbar07494792010-05-22 00:37:20 +00001456
Chad Rosierdd60e092013-01-29 20:15:05 +00001457 // Otherwise, remove result files and print extra information about abnormal
1458 // failures.
Nick Desaulniers9d0df312018-10-15 17:39:00 +00001459 int Res = 0;
Douglas Katzman6bbffc42015-06-25 18:51:37 +00001460 for (const auto &CmdPair : FailingCommands) {
Nick Desaulniers9d0df312018-10-15 17:39:00 +00001461 int CommandRes = CmdPair.first;
Douglas Katzman6bbffc42015-06-25 18:51:37 +00001462 const Command *FailingCommand = CmdPair.second;
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001463
Chad Rosierdd60e092013-01-29 20:15:05 +00001464 // Remove result files if we're not saving temps.
Reid Kleckner68eb60b2015-02-02 22:41:48 +00001465 if (!isSaveTempsEnabled()) {
Chad Rosierdd60e092013-01-29 20:15:05 +00001466 const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
1467 C.CleanupFileMap(C.getResultFiles(), JA, true);
1468
1469 // Failure result files are valid unless we crashed.
Nick Desaulniers9d0df312018-10-15 17:39:00 +00001470 if (CommandRes < 0)
Chad Rosierdd60e092013-01-29 20:15:05 +00001471 C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
1472 }
1473
Nick Desaulniers9d0df312018-10-15 17:39:00 +00001474#if LLVM_ON_UNIX
1475 // llvm/lib/Support/Unix/Signals.inc will exit with a special return code
1476 // for SIGPIPE. Do not print diagnostics for this case.
1477 if (CommandRes == EX_IOERR) {
1478 Res = CommandRes;
1479 continue;
1480 }
1481#endif
1482
Chad Rosierdd60e092013-01-29 20:15:05 +00001483 // Print extra information about abnormal failures, if possible.
1484 //
1485 // This is ad-hoc, but we don't want to be excessively noisy. If the result
Justin Bogner5aaf2e72014-06-26 20:59:36 +00001486 // status was 1, assume the command failed normally. In particular, if it
Chad Rosierdd60e092013-01-29 20:15:05 +00001487 // was the compiler then assume it gave a reasonable error code. Failures
1488 // in other tools are less common, and they generally have worse
1489 // diagnostics, so always print the diagnostic there.
1490 const Tool &FailingTool = FailingCommand->getCreator();
1491
Nick Desaulniers9d0df312018-10-15 17:39:00 +00001492 if (!FailingCommand->getCreator().hasGoodDiagnostics() || CommandRes != 1) {
Chad Rosierdd60e092013-01-29 20:15:05 +00001493 // FIXME: See FIXME above regarding result code interpretation.
Nick Desaulniers9d0df312018-10-15 17:39:00 +00001494 if (CommandRes < 0)
Chad Rosierdd60e092013-01-29 20:15:05 +00001495 Diag(clang::diag::err_drv_command_signalled)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001496 << FailingTool.getShortName();
Chad Rosierdd60e092013-01-29 20:15:05 +00001497 else
Nick Desaulniers9d0df312018-10-15 17:39:00 +00001498 Diag(clang::diag::err_drv_command_failed)
1499 << FailingTool.getShortName() << CommandRes;
Chad Rosierdd60e092013-01-29 20:15:05 +00001500 }
Peter Collingbourne119cfaa2011-11-21 00:01:05 +00001501 }
Nick Desaulniers9d0df312018-10-15 17:39:00 +00001502 return Res;
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001503}
1504
Daniel Dunbara7b5e212009-04-15 16:34:29 +00001505void Driver::PrintHelp(bool ShowHidden) const {
Hans Wennborg6ddc6902013-07-27 00:23:45 +00001506 unsigned IncludedFlagsBitmask;
1507 unsigned ExcludedFlagsBitmask;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001508 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
Hans Wennborg797004d2018-11-08 11:27:04 +00001509 getIncludeExcludeOptionFlagMasks(IsCLMode());
Hans Wennborg6ddc6902013-07-27 00:23:45 +00001510
1511 ExcludedFlagsBitmask |= options::NoDriverOption;
1512 if (!ShowHidden)
1513 ExcludedFlagsBitmask |= HelpHidden;
1514
Fangrui Songd0028232018-10-10 00:15:33 +00001515 std::string Usage = llvm::formatv("{0} [options] file...", Name).str();
1516 getOpts().PrintHelp(llvm::outs(), Usage.c_str(), DriverTitle.c_str(),
George Rimar5dbfa4e2017-07-26 09:10:17 +00001517 IncludedFlagsBitmask, ExcludedFlagsBitmask,
1518 /*ShowAllAliases=*/false);
Daniel Dunbar7c925282009-03-31 21:38:17 +00001519}
1520
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001521void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001522 // FIXME: The following handlers should use a callback mechanism, we don't
1523 // know what the client would like to do.
Ted Kremenek4c0df3d2010-01-23 02:11:34 +00001524 OS << getClangFullVersion() << '\n';
Daniel Dunbarb10248802009-03-26 16:09:13 +00001525 const ToolChain &TC = C.getDefaultToolChain();
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001526 OS << "Target: " << TC.getTripleString() << '\n';
Daniel Dunbar10978e42009-06-16 23:32:58 +00001527
1528 // Print the threading model.
Jonathan Roelofsb140a102014-10-03 21:57:44 +00001529 if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
1530 // Don't print if the ToolChain would have barfed on it already
1531 if (TC.isThreadModelSupported(A->getValue()))
1532 OS << "Thread model: " << A->getValue();
1533 } else
Thomas Livelyf3b4f992019-02-28 18:39:08 +00001534 OS << "Thread model: " << TC.getThreadModel();
Jonathan Roelofsb140a102014-10-03 21:57:44 +00001535 OS << '\n';
Chandler Carruth9ade6a92015-08-05 17:07:33 +00001536
1537 // Print out the install directory.
1538 OS << "InstalledDir: " << InstalledDir << '\n';
Serge Pavlov208ac652018-01-01 13:27:01 +00001539
1540 // If configuration file was used, print its path.
1541 if (!ConfigFile.empty())
1542 OS << "Configuration file: " << ConfigFile << '\n';
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001543}
1544
Chris Lattner86ed5b02010-05-05 05:53:24 +00001545/// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
1546/// option.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001547static void PrintDiagnosticCategories(raw_ostream &OS) {
Argyrios Kyrtzidis0e37afa2011-05-25 05:05:01 +00001548 // Skip the empty category.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001549 for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
1550 ++i)
Argyrios Kyrtzidis0e37afa2011-05-25 05:05:01 +00001551 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
Chris Lattner86ed5b02010-05-05 05:53:24 +00001552}
1553
Yuka Takahashi41789e42018-03-05 08:54:20 +00001554void Driver::HandleAutocompletions(StringRef PassedFlags) const {
Yuka Takahashi503da8f2018-03-05 09:01:31 +00001555 if (PassedFlags == "")
1556 return;
Yuka Takahashi1a895202017-08-29 17:46:46 +00001557 // Print out all options that start with a given argument. This is used for
1558 // shell autocompletion.
1559 std::vector<std::string> SuggestedCompletions;
Yuka Takahashi41789e42018-03-05 08:54:20 +00001560 std::vector<std::string> Flags;
Yuka Takahashi1a895202017-08-29 17:46:46 +00001561
1562 unsigned short DisableFlags =
1563 options::NoDriverOption | options::Unsupported | options::Ignored;
Yuka Takahashi41789e42018-03-05 08:54:20 +00001564
Yuka Takahashi46106f52018-10-24 12:43:25 +00001565 // Distinguish "--autocomplete=-someflag" and "--autocomplete=-someflag,"
1566 // because the latter indicates that the user put space before pushing tab
1567 // which should end up in a file completion.
1568 const bool HasSpace = PassedFlags.endswith(",");
1569
Yuka Takahashi41789e42018-03-05 08:54:20 +00001570 // Parse PassedFlags by "," as all the command-line flags are passed to this
1571 // function separated by ","
1572 StringRef TargetFlags = PassedFlags;
1573 while (TargetFlags != "") {
1574 StringRef CurFlag;
1575 std::tie(CurFlag, TargetFlags) = TargetFlags.split(",");
1576 Flags.push_back(std::string(CurFlag));
Yuka Takahashi1a895202017-08-29 17:46:46 +00001577 }
1578
Yuka Takahashi41789e42018-03-05 08:54:20 +00001579 // We want to show cc1-only options only when clang is invoked with -cc1 or
1580 // -Xclang.
Fangrui Song9ac13a12019-02-10 05:54:57 +00001581 if (llvm::is_contained(Flags, "-Xclang") || llvm::is_contained(Flags, "-cc1"))
Yuka Takahashi41789e42018-03-05 08:54:20 +00001582 DisableFlags &= ~options::NoDriverOption;
1583
1584 StringRef Cur;
1585 Cur = Flags.at(Flags.size() - 1);
1586 StringRef Prev;
1587 if (Flags.size() >= 2) {
1588 Prev = Flags.at(Flags.size() - 2);
1589 SuggestedCompletions = Opts->suggestValueCompletions(Prev, Cur);
1590 }
1591
1592 if (SuggestedCompletions.empty())
1593 SuggestedCompletions = Opts->suggestValueCompletions(Cur, "");
1594
Yuka Takahashi46106f52018-10-24 12:43:25 +00001595 // If Flags were empty, it means the user typed `clang [tab]` where we should
1596 // list all possible flags. If there was no value completion and the user
1597 // pressed tab after a space, we should fall back to a file completion.
1598 // We're printing a newline to be consistent with what we print at the end of
1599 // this function.
1600 if (SuggestedCompletions.empty() && HasSpace && !Flags.empty()) {
1601 llvm::outs() << '\n';
1602 return;
1603 }
1604
Yuka Takahashidf9c7e32018-10-24 08:24:16 +00001605 // When flag ends with '=' and there was no value completion, return empty
1606 // string and fall back to the file autocompletion.
1607 if (SuggestedCompletions.empty() && !Cur.endswith("=")) {
Yuka Takahashi1a895202017-08-29 17:46:46 +00001608 // If the flag is in the form of "--autocomplete=-foo",
1609 // we were requested to print out all option names that start with "-foo".
1610 // For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only".
Yuka Takahashi41789e42018-03-05 08:54:20 +00001611 SuggestedCompletions = Opts->findByPrefix(Cur, DisableFlags);
Yuka Takahashi1a895202017-08-29 17:46:46 +00001612
1613 // We have to query the -W flags manually as they're not in the OptTable.
1614 // TODO: Find a good way to add them to OptTable instead and them remove
1615 // this code.
1616 for (StringRef S : DiagnosticIDs::getDiagnosticFlags())
Yuka Takahashi41789e42018-03-05 08:54:20 +00001617 if (S.startswith(Cur))
Yuka Takahashi1a895202017-08-29 17:46:46 +00001618 SuggestedCompletions.push_back(S);
Yuka Takahashi1a895202017-08-29 17:46:46 +00001619 }
1620
1621 // Sort the autocomplete candidates so that shells print them out in a
1622 // deterministic order. We could sort in any way, but we chose
1623 // case-insensitive sorting for consistency with the -help option
1624 // which prints out options in the case-insensitive alphabetical order.
Fangrui Song55fab262018-09-26 22:16:28 +00001625 llvm::sort(SuggestedCompletions, [](StringRef A, StringRef B) {
1626 if (int X = A.compare_lower(B))
1627 return X < 0;
1628 return A.compare(B) > 0;
1629 });
Yuka Takahashi1a895202017-08-29 17:46:46 +00001630
1631 llvm::outs() << llvm::join(SuggestedCompletions, "\n") << '\n';
1632}
1633
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001634bool Driver::HandleImmediateArgs(const Compilation &C) {
Daniel Dunbar18974bd2010-06-11 22:00:19 +00001635 // The order these options are handled in gcc is all over the place, but we
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001636 // don't expect inconsistencies w.r.t. that to matter in practice.
Daniel Dunbar7c925282009-03-31 21:38:17 +00001637
Daniel Dunbar1b09e042010-09-17 02:47:28 +00001638 if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
1639 llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
1640 return false;
1641 }
1642
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001643 if (C.getArgs().hasArg(options::OPT_dumpversion)) {
Daniel Dunbare26e5002011-01-12 00:43:47 +00001644 // Since -dumpversion is only implemented for pedantic GCC compatibility, we
1645 // return an answer which matches our definition of __VERSION__.
Sylvestre Ledrua199a9b2019-03-25 18:06:20 +00001646 llvm::outs() << CLANG_VERSION_STRING << "\n";
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001647 return false;
1648 }
Daniel Dunbarfb3d7472010-06-14 21:23:12 +00001649
Chris Lattner86ed5b02010-05-05 05:53:24 +00001650 if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
1651 PrintDiagnosticCategories(llvm::outs());
1652 return false;
1653 }
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001654
James Molloya3c85b82012-05-01 14:57:16 +00001655 if (C.getArgs().hasArg(options::OPT_help) ||
Daniel Dunbara7b5e212009-04-15 16:34:29 +00001656 C.getArgs().hasArg(options::OPT__help_hidden)) {
1657 PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
Daniel Dunbar7c925282009-03-31 21:38:17 +00001658 return false;
1659 }
1660
Daniel Dunbarb0006ae2009-04-02 15:05:41 +00001661 if (C.getArgs().hasArg(options::OPT__version)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001662 // Follow gcc behavior and use stdout for --version and stderr for -v.
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001663 PrintVersion(C, llvm::outs());
Daniel Dunbarb0006ae2009-04-02 15:05:41 +00001664 return false;
1665 }
1666
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001667 if (C.getArgs().hasArg(options::OPT_v) ||
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001668 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001669 PrintVersion(C, llvm::errs());
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001670 SuppressMissingInputWarning = true;
1671 }
1672
Serge Pavlov208ac652018-01-01 13:27:01 +00001673 if (C.getArgs().hasArg(options::OPT_v)) {
1674 if (!SystemConfigDir.empty())
1675 llvm::errs() << "System configuration file directory: "
1676 << SystemConfigDir << "\n";
1677 if (!UserConfigDir.empty())
1678 llvm::errs() << "User configuration file directory: "
1679 << UserConfigDir << "\n";
1680 }
1681
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001682 const ToolChain &TC = C.getDefaultToolChain();
Chandler Carruth0ae39aa2013-07-30 17:57:09 +00001683
1684 if (C.getArgs().hasArg(options::OPT_v))
1685 TC.printVerboseInfo(llvm::errs());
1686
Meador Inge51208a32017-04-04 21:46:50 +00001687 if (C.getArgs().hasArg(options::OPT_print_resource_dir)) {
Meador Ingea9113952017-04-05 22:27:20 +00001688 llvm::outs() << ResourceDir << '\n';
Meador Inge51208a32017-04-04 21:46:50 +00001689 return false;
1690 }
1691
Daniel Dunbard972e222009-03-20 04:37:21 +00001692 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
1693 llvm::outs() << "programs: =";
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001694 bool separator = false;
1695 for (const std::string &Path : TC.getProgramPaths()) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001696 if (separator)
1697 llvm::outs() << ':';
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001698 llvm::outs() << Path;
1699 separator = true;
Daniel Dunbard972e222009-03-20 04:37:21 +00001700 }
1701 llvm::outs() << "\n";
Peter Collingbournefa9771f2011-09-06 02:08:31 +00001702 llvm::outs() << "libraries: =" << ResourceDir;
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001703
Sebastian Pop980920a2012-04-16 04:16:43 +00001704 StringRef sysroot = C.getSysRoot();
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001705
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001706 for (const std::string &Path : TC.getFilePaths()) {
1707 // Always print a separator. ResourceDir was the first item shown.
Peter Collingbournefa9771f2011-09-06 02:08:31 +00001708 llvm::outs() << ':';
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001709 // Interpretation of leading '=' is needed only for NetBSD.
1710 if (Path[0] == '=')
Douglas Katzman26eabf62015-06-24 15:10:30 +00001711 llvm::outs() << sysroot << Path.substr(1);
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001712 else
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001713 llvm::outs() << Path;
Daniel Dunbard972e222009-03-20 04:37:21 +00001714 }
1715 llvm::outs() << "\n";
Daniel Dunbar7c925282009-03-31 21:38:17 +00001716 return false;
Daniel Dunbard972e222009-03-20 04:37:21 +00001717 }
1718
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001719 // FIXME: The following handlers should use a callback mechanism, we don't
1720 // know what the client would like to do.
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001721 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001722 llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001723 return false;
1724 }
1725
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001726 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
Saleem Abdulrasoole5f3cf82018-05-01 18:40:42 +00001727 StringRef ProgName = A->getValue();
1728
1729 // Null program name cannot have a path.
1730 if (! ProgName.empty())
1731 llvm::outs() << GetProgramPath(ProgName, TC);
1732
1733 llvm::outs() << "\n";
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001734 return false;
1735 }
1736
Yuka Takahashic8068db2017-05-23 18:39:08 +00001737 if (Arg *A = C.getArgs().getLastArg(options::OPT_autocomplete)) {
Yuka Takahashiba5d4af2017-06-20 16:31:31 +00001738 StringRef PassedFlags = A->getValue();
Yuka Takahashi41789e42018-03-05 08:54:20 +00001739 HandleAutocompletions(PassedFlags);
Yuka Takahashic8068db2017-05-23 18:39:08 +00001740 return false;
1741 }
1742
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001743 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
Michal Gorny7cfe4802016-10-10 12:23:40 +00001744 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(C.getArgs());
Leo Li23bb21c2017-08-24 01:51:51 +00001745 const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
1746 RegisterEffectiveTriple TripleRAII(TC, Triple);
Michal Gorny7cfe4802016-10-10 12:23:40 +00001747 switch (RLT) {
1748 case ToolChain::RLT_CompilerRT:
1749 llvm::outs() << TC.getCompilerRT(C.getArgs(), "builtins") << "\n";
1750 break;
1751 case ToolChain::RLT_Libgcc:
1752 llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
1753 break;
1754 }
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001755 return false;
1756 }
1757
Daniel Dunbar1b3ec3a2009-06-16 23:25:22 +00001758 if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
Douglas Katzmana34b7bf2015-06-30 19:32:57 +00001759 for (const Multilib &Multilib : TC.getMultilibs())
1760 llvm::outs() << Multilib << "\n";
Daniel Dunbar1b3ec3a2009-06-16 23:25:22 +00001761 return false;
1762 }
1763
Jonathan Roelofs2cea1be2014-02-12 03:21:20 +00001764 if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
Christian Bruel6ccc4a72018-09-06 14:03:44 +00001765 const Multilib &Multilib = TC.getMultilib();
1766 if (Multilib.gccSuffix().empty())
1767 llvm::outs() << ".\n";
1768 else {
1769 StringRef Suffix(Multilib.gccSuffix());
1770 assert(Suffix.front() == '/');
1771 llvm::outs() << Suffix.substr(1) << "\n";
Jonathan Roelofs3fa96d82014-02-12 01:36:51 +00001772 }
Jonathan Roelofs0e7ec602014-02-12 01:29:25 +00001773 return false;
1774 }
Petr Hosekbc86a992018-08-16 00:22:03 +00001775
1776 if (C.getArgs().hasArg(options::OPT_print_target_triple)) {
1777 llvm::outs() << TC.getTripleString() << "\n";
1778 return false;
1779 }
1780
1781 if (C.getArgs().hasArg(options::OPT_print_effective_triple)) {
1782 const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
1783 llvm::outs() << Triple.getTriple() << "\n";
1784 return false;
1785 }
1786
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001787 return true;
1788}
1789
Douglas Katzmanfd528672015-06-11 15:05:22 +00001790// Display an action graph human-readably. Action A is the "sink" node
1791// and latest-occuring action. Traversal is in pre-order, visiting the
1792// inputs to each action before printing the action itself.
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001793static unsigned PrintActions1(const Compilation &C, Action *A,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001794 std::map<Action *, unsigned> &Ids) {
Douglas Katzmanfd528672015-06-11 15:05:22 +00001795 if (Ids.count(A)) // A was already visited.
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001796 return Ids[A];
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001797
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001798 std::string str;
1799 llvm::raw_string_ostream os(str);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001800
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001801 os << Action::getClassName(A->getKind()) << ", ";
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001802 if (InputAction *IA = dyn_cast<InputAction>(A)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001803 os << "\"" << IA->getInputArg().getValue() << "\"";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001804 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001805 os << '"' << BIA->getArchName() << '"' << ", {"
Nico Weber5a459f82016-02-23 19:30:43 +00001806 << PrintActions1(C, *BIA->input_begin(), Ids) << "}";
Samuel Antaod06239d2016-07-15 23:13:27 +00001807 } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
1808 bool IsFirst = true;
1809 OA->doOnEachDependence(
1810 [&](Action *A, const ToolChain *TC, const char *BoundArch) {
1811 // E.g. for two CUDA device dependences whose bound arch is sm_20 and
1812 // sm_35 this will generate:
1813 // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
1814 // (nvptx64-nvidia-cuda:sm_35) {#ID}
1815 if (!IsFirst)
1816 os << ", ";
1817 os << '"';
1818 if (TC)
1819 os << A->getOffloadingKindPrefix();
1820 else
1821 os << "host";
1822 os << " (";
1823 os << TC->getTriple().normalize();
1824
1825 if (BoundArch)
1826 os << ":" << BoundArch;
1827 os << ")";
1828 os << '"';
1829 os << " {" << PrintActions1(C, A, Ids) << "}";
1830 IsFirst = false;
1831 });
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001832 } else {
Samuel Antaod06239d2016-07-15 23:13:27 +00001833 const ActionList *AL = &A->getInputs();
Artem Belevich0ff05cd2015-07-13 23:27:56 +00001834
Artem Belevich23256752015-09-22 17:23:09 +00001835 if (AL->size()) {
1836 const char *Prefix = "{";
1837 for (Action *PreRequisite : *AL) {
1838 os << Prefix << PrintActions1(C, PreRequisite, Ids);
1839 Prefix = ", ";
1840 }
1841 os << "}";
1842 } else
1843 os << "{}";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001844 }
1845
Samuel Antaod06239d2016-07-15 23:13:27 +00001846 // Append offload info for all options other than the offloading action
1847 // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
1848 std::string offload_str;
1849 llvm::raw_string_ostream offload_os(offload_str);
1850 if (!isa<OffloadAction>(A)) {
1851 auto S = A->getOffloadingKindPrefix();
1852 if (!S.empty()) {
1853 offload_os << ", (" << S;
1854 if (A->getOffloadingArch())
1855 offload_os << ", " << A->getOffloadingArch();
1856 offload_os << ")";
1857 }
1858 }
1859
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001860 unsigned Id = Ids.size();
1861 Ids[A] = Id;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001862 llvm::errs() << Id << ": " << os.str() << ", "
Samuel Antaod06239d2016-07-15 23:13:27 +00001863 << types::getTypeName(A->getType()) << offload_os.str() << "\n";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001864
1865 return Id;
1866}
1867
Douglas Katzmanfd528672015-06-11 15:05:22 +00001868// Print the action graphs in a compilation C.
1869// For example "clang -c file1.c file2.c" is composed of two subgraphs.
Daniel Dunbareb843be2009-03-18 03:13:20 +00001870void Driver::PrintActions(const Compilation &C) const {
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001871 std::map<Action *, unsigned> Ids;
1872 for (Action *A : C.getActions())
1873 PrintActions1(C, A, Ids);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001874}
1875
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001876/// Check whether the given input tree contains any compilation or
Joerg Sonnenberger5fe4a7d2011-05-06 14:05:11 +00001877/// assembly actions.
1878static bool ContainsCompileOrAssembleAction(const Action *A) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001879 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
Bob Wilson23a55f12014-12-21 07:00:00 +00001880 isa<AssembleJobAction>(A))
Daniel Dunbar00d3d8e2010-06-29 16:38:33 +00001881 return true;
1882
Nico Weber5a459f82016-02-23 19:30:43 +00001883 for (const Action *Input : A->inputs())
Nico Weberfb80f962015-09-19 21:36:51 +00001884 if (ContainsCompileOrAssembleAction(Input))
Daniel Dunbar00d3d8e2010-06-29 16:38:33 +00001885 return true;
1886
1887 return false;
1888}
1889
Artem Belevich5e2a3ec2015-11-17 22:28:40 +00001890void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
1891 const InputList &BAInputs) const {
1892 DerivedArgList &Args = C.getArgs();
1893 ActionList &Actions = C.getActions();
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001894 llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
1895 // Collect the list of architectures. Duplicates are allowed, but should only
1896 // be handled once (in the order seen).
Daniel Dunbare5dc4822009-03-13 20:33:35 +00001897 llvm::StringSet<> ArchNames;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001898 SmallVector<const char *, 4> Archs;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00001899 for (Arg *A : Args) {
Daniel Dunbar0bfb21e2009-11-19 03:26:40 +00001900 if (A->getOption().matches(options::OPT_arch)) {
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001901 // Validate the option here; we don't save the type here because its
1902 // particular spelling may participate in other driver choices.
1903 llvm::Triple::ArchType Arch =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001904 tools::darwin::getArchTypeForMachOArchName(A->getValue());
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001905 if (Arch == llvm::Triple::UnknownArch) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001906 Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001907 continue;
1908 }
1909
Daniel Dunbar2da02722009-03-19 07:55:12 +00001910 A->claim();
David Blaikie61b86d42014-11-19 02:56:13 +00001911 if (ArchNames.insert(A->getValue()).second)
Richard Smithbd55daf2012-11-01 04:30:05 +00001912 Archs.push_back(A->getValue());
Daniel Dunbarf479c122009-03-12 18:40:18 +00001913 }
1914 }
1915
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001916 // When there is no explicit arch for this platform, make sure we still bind
1917 // the architecture (to the default) so that -Xarch_ is handled correctly.
Daniel Dunbareb843be2009-03-18 03:13:20 +00001918 if (!Archs.size())
Daniel Dunbarc3bd9f52012-11-08 03:38:26 +00001919 Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
Daniel Dunbarf479c122009-03-12 18:40:18 +00001920
Daniel Dunbarf479c122009-03-12 18:40:18 +00001921 ActionList SingleActions;
Justin Lebar0f3474c2016-02-11 02:00:50 +00001922 BuildActions(C, Args, BAInputs, SingleActions);
Daniel Dunbarf479c122009-03-12 18:40:18 +00001923
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001924 // Add in arch bindings for every top level action, as well as lipo and
1925 // dsymutil steps if needed.
Nico Weberfb80f962015-09-19 21:36:51 +00001926 for (Action* Act : SingleActions) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001927 // Make sure we can lipo this kind of output. If not (and it is an actual
1928 // output) then we disallow, since we can't create an output file with the
1929 // right name without overwriting it. We could remove this oddity by just
1930 // changing the output names to include the arch, which would also fix
Daniel Dunbarf479c122009-03-12 18:40:18 +00001931 // -save-temps. Compatibility wins for now.
1932
Daniel Dunbare2ca3bd2009-03-13 17:46:02 +00001933 if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
Daniel Dunbarf479c122009-03-12 18:40:18 +00001934 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001935 << types::getTypeName(Act->getType());
Daniel Dunbarf479c122009-03-12 18:40:18 +00001936
1937 ActionList Inputs;
Justin Lebar41094612016-01-11 23:07:27 +00001938 for (unsigned i = 0, e = Archs.size(); i != e; ++i)
1939 Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
Daniel Dunbarf479c122009-03-12 18:40:18 +00001940
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001941 // Lipo if necessary, we do it this way because we need to set the arch flag
1942 // so that -Xarch_ gets overwritten.
Daniel Dunbarf479c122009-03-12 18:40:18 +00001943 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
1944 Actions.append(Inputs.begin(), Inputs.end());
1945 else
Justin Lebar41094612016-01-11 23:07:27 +00001946 Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001947
Eric Christopher65c05fa2012-02-06 19:43:51 +00001948 // Handle debug info queries.
1949 Arg *A = Args.getLastArg(options::OPT_g_Group);
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001950 if (A && !A->getOption().matches(options::OPT_g0) &&
1951 !A->getOption().matches(options::OPT_gstabs) &&
1952 ContainsCompileOrAssembleAction(Actions.back())) {
Chad Rosier62135492012-07-09 17:31:28 +00001953
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001954 // Add a 'dsymutil' step if necessary, when debug info is enabled and we
1955 // have a compile input. We need to run 'dsymutil' ourselves in such cases
Eric Christopher776c26f2013-01-28 17:39:03 +00001956 // because the debug info will refer to a temporary object file which
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001957 // will be removed at the end of the compilation process.
1958 if (Act->getType() == types::TY_Image) {
1959 ActionList Inputs;
1960 Inputs.push_back(Actions.back());
1961 Actions.pop_back();
Justin Lebar41094612016-01-11 23:07:27 +00001962 Actions.push_back(
1963 C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001964 }
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001965
Ben Langmuir9b9a8d32014-02-06 18:53:25 +00001966 // Verify the debug info output.
Alp Tokere9d2bfc2014-01-17 02:06:23 +00001967 if (Args.hasArg(options::OPT_verify_debug_info)) {
Justin Lebar41094612016-01-11 23:07:27 +00001968 Action* LastAction = Actions.back();
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001969 Actions.pop_back();
Justin Lebar41094612016-01-11 23:07:27 +00001970 Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
1971 LastAction, types::TY_Nothing));
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001972 }
1973 }
Daniel Dunbarf479c122009-03-12 18:40:18 +00001974 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001975}
1976
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001977/// Check that the file referenced by Value exists. If it doesn't,
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001978/// issue a diagnostic and return false.
Alp Toker8c8a8752013-12-03 06:53:35 +00001979static bool DiagnoseInputExistence(const Driver &D, const DerivedArgList &Args,
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001980 StringRef Value, types::ID Ty) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001981 if (!D.getCheckInputsExist())
1982 return true;
1983
1984 // stdin always exists.
1985 if (Value == "-")
1986 return true;
1987
1988 SmallString<64> Path(Value);
1989 if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
Yaron Keren92e1b622015-03-18 10:17:07 +00001990 if (!llvm::sys::path::is_absolute(Path)) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001991 SmallString<64> Directory(WorkDir->getValue());
1992 llvm::sys::path::append(Directory, Value);
1993 Path.assign(Directory);
1994 }
1995 }
1996
Sam McCall2c782472018-11-08 16:57:01 +00001997 if (D.getVFS().exists(Path))
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001998 return true;
1999
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00002000 if (D.IsCLMode()) {
2001 if (!llvm::sys::path::is_absolute(Twine(Path)) &&
2002 llvm::sys::Process::FindInEnvPath("LIB", Value))
2003 return true;
2004
2005 if (Args.hasArg(options::OPT__SLASH_link) && Ty == types::TY_Object) {
2006 // Arguments to the /link flag might cause the linker to search for object
2007 // and library files in paths we don't know about. Don't error in such
2008 // cases.
2009 return true;
2010 }
2011 }
Hans Wennborg23d26a32014-06-18 17:21:50 +00002012
Yaron Keren92e1b622015-03-18 10:17:07 +00002013 D.Diag(clang::diag::err_drv_no_such_file) << Path;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00002014 return false;
2015}
2016
Chad Rosierecdede82011-08-12 22:08:57 +00002017// Construct a the list of inputs and their types.
Hans Wennborg55362852014-05-02 22:55:30 +00002018void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
Chad Rosierecdede82011-08-12 22:08:57 +00002019 InputList &Inputs) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002020 // Track the current user specified (-x) input. We also explicitly track the
2021 // argument used to set the type; we only want to claim the type when we
2022 // actually use it, so we warn about unused -x arguments.
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00002023 types::ID InputType = types::TY_Nothing;
Craig Topper92fc2df2014-05-17 16:56:41 +00002024 Arg *InputTypeArg = nullptr;
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00002025
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00002026 // The last /TC or /TP option sets the input type to C or C++ globally.
Ehsan Akhgaric249abb2014-09-12 21:44:24 +00002027 if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
2028 options::OPT__SLASH_TP)) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00002029 InputTypeArg = TCTP;
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00002030 InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002031 ? types::TY_C
2032 : types::TY_CXX;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00002033
Richard Smith0aef3052017-02-18 01:14:43 +00002034 Arg *Previous = nullptr;
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00002035 bool ShowNote = false;
Simon Atanasyan27c0f202019-04-02 18:03:15 +00002036 for (Arg *A :
2037 Args.filtered(options::OPT__SLASH_TC, options::OPT__SLASH_TP)) {
Richard Smith0aef3052017-02-18 01:14:43 +00002038 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 Liuab851932019-03-05 16:07:56 +00002296
2297 /// Flag for -fgpu-rdc.
2298 bool Relocatable = false;
Yaxun Liu3af038b2018-05-30 00:49:10 +00002299 public:
2300 CudaActionBuilderBase(Compilation &C, DerivedArgList &Args,
2301 const Driver::InputList &Inputs,
2302 Action::OffloadKind OFKind)
2303 : DeviceActionBuilder(C, Args, Inputs, OFKind) {}
Samuel Antao64e965e2016-09-30 15:34:19 +00002304
Yaxun Liu3af038b2018-05-30 00:49:10 +00002305 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2306 // While generating code for CUDA, we only depend on the host input action
2307 // to trigger the creation of all the CUDA device actions.
2308
2309 // If we are dealing with an input action, replicate it for each GPU
2310 // architecture. If we are in host-only mode we return 'success' so that
2311 // the host uses the CUDA offload kind.
2312 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2313 assert(!GpuArchList.empty() &&
2314 "We should have at least one GPU architecture.");
2315
2316 // If the host input is not CUDA or HIP, we don't need to bother about
2317 // this input.
2318 if (IA->getType() != types::TY_CUDA &&
2319 IA->getType() != types::TY_HIP) {
2320 // The builder will ignore this input.
2321 IsActive = false;
2322 return ABRT_Inactive;
2323 }
2324
2325 // Set the flag to true, so that the builder acts on the current input.
2326 IsActive = true;
2327
2328 if (CompileHostOnly)
2329 return ABRT_Success;
2330
2331 // Replicate inputs for each GPU architecture.
2332 auto Ty = IA->getType() == types::TY_HIP ? types::TY_HIP_DEVICE
2333 : types::TY_CUDA_DEVICE;
2334 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2335 CudaDeviceActions.push_back(
2336 C.MakeAction<InputAction>(IA->getInputArg(), Ty));
2337 }
2338
2339 return ABRT_Success;
2340 }
2341
2342 // If this is an unbundling action use it as is for each CUDA toolchain.
2343 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
Yaxun Liuab851932019-03-05 16:07:56 +00002344
2345 // If -fgpu-rdc is disabled, should not unbundle since there is no
2346 // device code to link.
2347 if (!Relocatable)
2348 return ABRT_Inactive;
2349
Yaxun Liu3af038b2018-05-30 00:49:10 +00002350 CudaDeviceActions.clear();
Aaron Enye Shibea57bb2019-01-04 19:05:41 +00002351 auto *IA = cast<InputAction>(UA->getInputs().back());
2352 std::string FileName = IA->getInputArg().getAsString(Args);
2353 // Check if the type of the file is the same as the action. Do not
2354 // unbundle it if it is not. Do not unbundle .so files, for example,
2355 // which are not object files.
2356 if (IA->getType() == types::TY_Object &&
2357 (!llvm::sys::path::has_extension(FileName) ||
2358 types::lookupTypeForExtension(
2359 llvm::sys::path::extension(FileName).drop_front()) !=
2360 types::TY_Object))
2361 return ABRT_Inactive;
2362
Yaxun Liu3af038b2018-05-30 00:49:10 +00002363 for (auto Arch : GpuArchList) {
2364 CudaDeviceActions.push_back(UA);
2365 UA->registerDependentActionInfo(ToolChains[0], CudaArchToString(Arch),
2366 AssociatedOffloadKind);
2367 }
2368 return ABRT_Success;
2369 }
2370
2371 return IsActive ? ABRT_Success : ABRT_Inactive;
2372 }
2373
2374 void appendTopLevelActions(ActionList &AL) override {
2375 // Utility to append actions to the top level list.
2376 auto AddTopLevel = [&](Action *A, CudaArch BoundArch) {
2377 OffloadAction::DeviceDependences Dep;
2378 Dep.add(*A, *ToolChains.front(), CudaArchToString(BoundArch),
2379 AssociatedOffloadKind);
2380 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2381 };
2382
2383 // If we have a fat binary, add it to the list.
2384 if (CudaFatBinary) {
2385 AddTopLevel(CudaFatBinary, CudaArch::UNKNOWN);
2386 CudaDeviceActions.clear();
2387 CudaFatBinary = nullptr;
2388 return;
2389 }
2390
2391 if (CudaDeviceActions.empty())
2392 return;
2393
2394 // If we have CUDA actions at this point, that's because we have a have
2395 // partial compilation, so we should have an action for each GPU
2396 // architecture.
2397 assert(CudaDeviceActions.size() == GpuArchList.size() &&
2398 "Expecting one action per GPU architecture.");
2399 assert(ToolChains.size() == 1 &&
2400 "Expecting to have a sing CUDA toolchain.");
2401 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
2402 AddTopLevel(CudaDeviceActions[I], GpuArchList[I]);
2403
2404 CudaDeviceActions.clear();
2405 }
2406
2407 bool initialize() override {
2408 assert(AssociatedOffloadKind == Action::OFK_Cuda ||
2409 AssociatedOffloadKind == Action::OFK_HIP);
2410
2411 // We don't need to support CUDA.
2412 if (AssociatedOffloadKind == Action::OFK_Cuda &&
2413 !C.hasOffloadToolChain<Action::OFK_Cuda>())
2414 return false;
2415
2416 // We don't need to support HIP.
2417 if (AssociatedOffloadKind == Action::OFK_HIP &&
2418 !C.hasOffloadToolChain<Action::OFK_HIP>())
2419 return false;
2420
Yaxun Liuab851932019-03-05 16:07:56 +00002421 Relocatable = Args.hasFlag(options::OPT_fgpu_rdc,
2422 options::OPT_fno_gpu_rdc, /*Default=*/false);
2423
Yaxun Liu3af038b2018-05-30 00:49:10 +00002424 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
2425 assert(HostTC && "No toolchain for host compilation.");
2426 if (HostTC->getTriple().isNVPTX() ||
2427 HostTC->getTriple().getArch() == llvm::Triple::amdgcn) {
2428 // We do not support targeting NVPTX/AMDGCN for host compilation. Throw
2429 // an error and abort pipeline construction early so we don't trip
2430 // asserts that assume device-side compilation.
2431 C.getDriver().Diag(diag::err_drv_cuda_host_arch)
2432 << HostTC->getTriple().getArchName();
2433 return true;
2434 }
2435
2436 ToolChains.push_back(
2437 AssociatedOffloadKind == Action::OFK_Cuda
2438 ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
2439 : C.getSingleOffloadToolChain<Action::OFK_HIP>());
2440
2441 Arg *PartialCompilationArg = Args.getLastArg(
2442 options::OPT_cuda_host_only, options::OPT_cuda_device_only,
2443 options::OPT_cuda_compile_host_device);
2444 CompileHostOnly = PartialCompilationArg &&
2445 PartialCompilationArg->getOption().matches(
2446 options::OPT_cuda_host_only);
2447 CompileDeviceOnly = PartialCompilationArg &&
2448 PartialCompilationArg->getOption().matches(
2449 options::OPT_cuda_device_only);
2450
2451 // Collect all cuda_gpu_arch parameters, removing duplicates.
2452 std::set<CudaArch> GpuArchs;
2453 bool Error = false;
2454 for (Arg *A : Args) {
2455 if (!(A->getOption().matches(options::OPT_cuda_gpu_arch_EQ) ||
2456 A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ)))
2457 continue;
2458 A->claim();
2459
2460 const StringRef ArchStr = A->getValue();
2461 if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ) &&
2462 ArchStr == "all") {
2463 GpuArchs.clear();
2464 continue;
2465 }
2466 CudaArch Arch = StringToCudaArch(ArchStr);
2467 if (Arch == CudaArch::UNKNOWN) {
2468 C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
2469 Error = true;
2470 } else if (A->getOption().matches(options::OPT_cuda_gpu_arch_EQ))
2471 GpuArchs.insert(Arch);
2472 else if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ))
2473 GpuArchs.erase(Arch);
2474 else
2475 llvm_unreachable("Unexpected option.");
2476 }
2477
2478 // Collect list of GPUs remaining in the set.
2479 for (CudaArch Arch : GpuArchs)
2480 GpuArchList.push_back(Arch);
2481
2482 // Default to sm_20 which is the lowest common denominator for
2483 // supported GPUs. sm_20 code should work correctly, if
2484 // suboptimally, on all newer GPUs.
2485 if (GpuArchList.empty())
2486 GpuArchList.push_back(CudaArch::SM_20);
2487
2488 return Error;
2489 }
2490 };
2491
2492 /// \brief CUDA action builder. It injects device code in the host backend
2493 /// action.
2494 class CudaActionBuilder final : public CudaActionBuilderBase {
Samuel Antao64e965e2016-09-30 15:34:19 +00002495 public:
2496 CudaActionBuilder(Compilation &C, DerivedArgList &Args,
2497 const Driver::InputList &Inputs)
Yaxun Liu3af038b2018-05-30 00:49:10 +00002498 : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_Cuda) {}
Samuel Antao64e965e2016-09-30 15:34:19 +00002499
2500 ActionBuilderReturnCode
Samuel Antao28c4f182016-10-27 17:08:03 +00002501 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2502 phases::ID CurPhase, phases::ID FinalPhase,
2503 PhasesTy &Phases) override {
Samuel Antao64e965e2016-09-30 15:34:19 +00002504 if (!IsActive)
2505 return ABRT_Inactive;
2506
2507 // If we don't have more CUDA actions, we don't have any dependences to
2508 // create for the host.
2509 if (CudaDeviceActions.empty())
2510 return ABRT_Success;
2511
2512 assert(CudaDeviceActions.size() == GpuArchList.size() &&
2513 "Expecting one action per GPU architecture.");
2514 assert(!CompileHostOnly &&
2515 "Not expecting CUDA actions in host-only compilation.");
2516
2517 // If we are generating code for the device or we are in a backend phase,
2518 // we attempt to generate the fat binary. We compile each arch to ptx and
2519 // assemble to cubin, then feed the cubin *and* the ptx into a device
2520 // "link" action, which uses fatbinary to combine these cubins into one
2521 // fatbin. The fatbin is then an input to the host action if not in
2522 // device-only mode.
2523 if (CompileDeviceOnly || CurPhase == phases::Backend) {
2524 ActionList DeviceActions;
2525 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2526 // Produce the device action from the current phase up to the assemble
2527 // phase.
2528 for (auto Ph : Phases) {
2529 // Skip the phases that were already dealt with.
2530 if (Ph < CurPhase)
2531 continue;
2532 // We have to be consistent with the host final phase.
2533 if (Ph > FinalPhase)
2534 break;
2535
2536 CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction(
Artem Belevichecb178b2018-03-21 22:22:59 +00002537 C, Args, Ph, CudaDeviceActions[I], Action::OFK_Cuda);
Samuel Antao64e965e2016-09-30 15:34:19 +00002538
2539 if (Ph == phases::Assemble)
2540 break;
2541 }
2542
2543 // If we didn't reach the assemble phase, we can't generate the fat
2544 // binary. We don't need to generate the fat binary if we are not in
2545 // device-only mode.
2546 if (!isa<AssembleJobAction>(CudaDeviceActions[I]) ||
2547 CompileDeviceOnly)
2548 continue;
2549
2550 Action *AssembleAction = CudaDeviceActions[I];
2551 assert(AssembleAction->getType() == types::TY_Object);
2552 assert(AssembleAction->getInputs().size() == 1);
2553
2554 Action *BackendAction = AssembleAction->getInputs()[0];
2555 assert(BackendAction->getType() == types::TY_PP_Asm);
2556
2557 for (auto &A : {AssembleAction, BackendAction}) {
2558 OffloadAction::DeviceDependences DDep;
2559 DDep.add(*A, *ToolChains.front(), CudaArchToString(GpuArchList[I]),
2560 Action::OFK_Cuda);
2561 DeviceActions.push_back(
2562 C.MakeAction<OffloadAction>(DDep, A->getType()));
2563 }
2564 }
2565
2566 // We generate the fat binary if we have device input actions.
2567 if (!DeviceActions.empty()) {
2568 CudaFatBinary =
2569 C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN);
2570
2571 if (!CompileDeviceOnly) {
2572 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
2573 Action::OFK_Cuda);
2574 // Clear the fat binary, it is already a dependence to an host
2575 // action.
2576 CudaFatBinary = nullptr;
2577 }
2578
2579 // Remove the CUDA actions as they are already connected to an host
2580 // action or fat binary.
2581 CudaDeviceActions.clear();
2582 }
2583
2584 // We avoid creating host action in device-only mode.
2585 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
Samuel Antao5b1a89a2016-10-27 00:53:34 +00002586 } else if (CurPhase > phases::Backend) {
2587 // If we are past the backend phase and still have a device action, we
2588 // don't have to do anything as this action is already a device
2589 // top-level action.
2590 return ABRT_Success;
Samuel Antao64e965e2016-09-30 15:34:19 +00002591 }
2592
2593 assert(CurPhase < phases::Backend && "Generating single CUDA "
2594 "instructions should only occur "
2595 "before the backend phase!");
2596
2597 // By default, we produce an action for each device arch.
2598 for (Action *&A : CudaDeviceActions)
2599 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2600
2601 return ABRT_Success;
2602 }
Yaxun Liu3af038b2018-05-30 00:49:10 +00002603 };
2604 /// \brief HIP action builder. It injects device code in the host backend
2605 /// action.
2606 class HIPActionBuilder final : public CudaActionBuilderBase {
2607 /// The linker inputs obtained for each device arch.
2608 SmallVector<ActionList, 8> DeviceLinkerInputs;
Samuel Antao64e965e2016-09-30 15:34:19 +00002609
Yaxun Liu3af038b2018-05-30 00:49:10 +00002610 public:
2611 HIPActionBuilder(Compilation &C, DerivedArgList &Args,
2612 const Driver::InputList &Inputs)
Yaxun Liuab851932019-03-05 16:07:56 +00002613 : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_HIP) {}
Samuel Antao64e965e2016-09-30 15:34:19 +00002614
Yaxun Liu3af038b2018-05-30 00:49:10 +00002615 bool canUseBundlerUnbundler() const override { return true; }
Samuel Antao64e965e2016-09-30 15:34:19 +00002616
Yaxun Liu3af038b2018-05-30 00:49:10 +00002617 ActionBuilderReturnCode
2618 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2619 phases::ID CurPhase, phases::ID FinalPhase,
2620 PhasesTy &Phases) override {
2621 // amdgcn does not support linking of object files, therefore we skip
Yaxun Liu97670892018-10-02 17:48:54 +00002622 // backend and assemble phases to output LLVM IR. Except for generating
2623 // non-relocatable device coee, where we generate fat binary for device
2624 // code and pass to host in Backend phase.
2625 if (CudaDeviceActions.empty() ||
2626 (CurPhase == phases::Backend && Relocatable) ||
Yaxun Liu3af038b2018-05-30 00:49:10 +00002627 CurPhase == phases::Assemble)
2628 return ABRT_Success;
2629
Yaxun Liu97670892018-10-02 17:48:54 +00002630 assert(((CurPhase == phases::Link && Relocatable) ||
Yaxun Liu3af038b2018-05-30 00:49:10 +00002631 CudaDeviceActions.size() == GpuArchList.size()) &&
2632 "Expecting one action per GPU architecture.");
2633 assert(!CompileHostOnly &&
2634 "Not expecting CUDA actions in host-only compilation.");
2635
Yaxun Liu97670892018-10-02 17:48:54 +00002636 if (!Relocatable && CurPhase == phases::Backend) {
2637 // If we are in backend phase, we attempt to generate the fat binary.
2638 // We compile each arch to IR and use a link action to generate code
2639 // object containing ISA. Then we use a special "link" action to create
2640 // a fat binary containing all the code objects for different GPU's.
2641 // The fat binary is then an input to the host action.
2642 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2643 // Create a link action to link device IR with device library
2644 // and generate ISA.
2645 ActionList AL;
2646 AL.push_back(CudaDeviceActions[I]);
2647 CudaDeviceActions[I] =
2648 C.MakeAction<LinkJobAction>(AL, types::TY_Image);
2649
2650 // OffloadingActionBuilder propagates device arch until an offload
2651 // action. Since the next action for creating fatbin does
2652 // not have device arch, whereas the above link action and its input
2653 // have device arch, an offload action is needed to stop the null
2654 // device arch of the next action being propagated to the above link
2655 // action.
2656 OffloadAction::DeviceDependences DDep;
2657 DDep.add(*CudaDeviceActions[I], *ToolChains.front(),
2658 CudaArchToString(GpuArchList[I]), AssociatedOffloadKind);
2659 CudaDeviceActions[I] = C.MakeAction<OffloadAction>(
2660 DDep, CudaDeviceActions[I]->getType());
2661 }
2662 // Create HIP fat binary with a special "link" action.
2663 CudaFatBinary =
2664 C.MakeAction<LinkJobAction>(CudaDeviceActions,
2665 types::TY_HIP_FATBIN);
2666
Yaxun Liu2bcc9512018-11-14 04:47:31 +00002667 if (!CompileDeviceOnly) {
2668 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
2669 AssociatedOffloadKind);
2670 // Clear the fat binary, it is already a dependence to an host
2671 // action.
2672 CudaFatBinary = nullptr;
2673 }
Yaxun Liu97670892018-10-02 17:48:54 +00002674
2675 // Remove the CUDA actions as they are already connected to an host
2676 // action or fat binary.
2677 CudaDeviceActions.clear();
2678
Yaxun Liu2bcc9512018-11-14 04:47:31 +00002679 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
Yaxun Liu97670892018-10-02 17:48:54 +00002680 } else if (CurPhase == phases::Link) {
2681 // Save CudaDeviceActions to DeviceLinkerInputs for each GPU subarch.
2682 // This happens to each device action originated from each input file.
2683 // Later on, device actions in DeviceLinkerInputs are used to create
2684 // device link actions in appendLinkDependences and the created device
2685 // link actions are passed to the offload action as device dependence.
Yaxun Liu3af038b2018-05-30 00:49:10 +00002686 DeviceLinkerInputs.resize(CudaDeviceActions.size());
2687 auto LI = DeviceLinkerInputs.begin();
2688 for (auto *A : CudaDeviceActions) {
2689 LI->push_back(A);
2690 ++LI;
Samuel Antao64e965e2016-09-30 15:34:19 +00002691 }
2692
Yaxun Liu3af038b2018-05-30 00:49:10 +00002693 // We will pass the device action as a host dependence, so we don't
2694 // need to do anything else with them.
2695 CudaDeviceActions.clear();
Samuel Antao64e965e2016-09-30 15:34:19 +00002696 return ABRT_Success;
2697 }
2698
Yaxun Liu3af038b2018-05-30 00:49:10 +00002699 // By default, we produce an action for each device arch.
2700 for (Action *&A : CudaDeviceActions)
2701 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A,
2702 AssociatedOffloadKind);
2703
2704 return ABRT_Success;
Samuel Antao64e965e2016-09-30 15:34:19 +00002705 }
2706
Yaxun Liu3af038b2018-05-30 00:49:10 +00002707 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {
2708 // Append a new link action for each device.
2709 unsigned I = 0;
2710 for (auto &LI : DeviceLinkerInputs) {
2711 auto *DeviceLinkAction =
2712 C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2713 DA.add(*DeviceLinkAction, *ToolChains[0],
2714 CudaArchToString(GpuArchList[I]), AssociatedOffloadKind);
2715 ++I;
Samuel Antao64e965e2016-09-30 15:34:19 +00002716 }
Samuel Antao64e965e2016-09-30 15:34:19 +00002717 }
2718 };
2719
Samuel Antao28c4f182016-10-27 17:08:03 +00002720 /// OpenMP action builder. The host bitcode is passed to the device frontend
2721 /// and all the device linked images are passed to the host link phase.
2722 class OpenMPActionBuilder final : public DeviceActionBuilder {
2723 /// The OpenMP actions for the current input.
2724 ActionList OpenMPDeviceActions;
2725
2726 /// The linker inputs obtained for each toolchain.
2727 SmallVector<ActionList, 8> DeviceLinkerInputs;
2728
2729 public:
2730 OpenMPActionBuilder(Compilation &C, DerivedArgList &Args,
2731 const Driver::InputList &Inputs)
2732 : DeviceActionBuilder(C, Args, Inputs, Action::OFK_OpenMP) {}
2733
2734 ActionBuilderReturnCode
2735 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2736 phases::ID CurPhase, phases::ID FinalPhase,
2737 PhasesTy &Phases) override {
Alexey Bataeva5178f52018-09-28 16:17:59 +00002738 if (OpenMPDeviceActions.empty())
2739 return ABRT_Inactive;
Samuel Antao28c4f182016-10-27 17:08:03 +00002740
2741 // We should always have an action for each input.
2742 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2743 "Number of OpenMP actions and toolchains do not match.");
2744
2745 // The host only depends on device action in the linking phase, when all
2746 // the device images have to be embedded in the host image.
2747 if (CurPhase == phases::Link) {
2748 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2749 "Toolchains and linker inputs sizes do not match.");
2750 auto LI = DeviceLinkerInputs.begin();
2751 for (auto *A : OpenMPDeviceActions) {
2752 LI->push_back(A);
2753 ++LI;
2754 }
2755
2756 // We passed the device action as a host dependence, so we don't need to
2757 // do anything else with them.
2758 OpenMPDeviceActions.clear();
2759 return ABRT_Success;
2760 }
2761
2762 // By default, we produce an action for each device arch.
2763 for (Action *&A : OpenMPDeviceActions)
2764 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2765
2766 return ABRT_Success;
2767 }
2768
2769 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2770
2771 // If this is an input action replicate it for each OpenMP toolchain.
2772 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2773 OpenMPDeviceActions.clear();
2774 for (unsigned I = 0; I < ToolChains.size(); ++I)
2775 OpenMPDeviceActions.push_back(
2776 C.MakeAction<InputAction>(IA->getInputArg(), IA->getType()));
2777 return ABRT_Success;
2778 }
2779
Samuel Antaofab4f372016-10-27 18:00:51 +00002780 // If this is an unbundling action use it as is for each OpenMP toolchain.
2781 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2782 OpenMPDeviceActions.clear();
Alexey Bataeva5178f52018-09-28 16:17:59 +00002783 auto *IA = cast<InputAction>(UA->getInputs().back());
2784 std::string FileName = IA->getInputArg().getAsString(Args);
2785 // Check if the type of the file is the same as the action. Do not
2786 // unbundle it if it is not. Do not unbundle .so files, for example,
2787 // which are not object files.
2788 if (IA->getType() == types::TY_Object &&
2789 (!llvm::sys::path::has_extension(FileName) ||
2790 types::lookupTypeForExtension(
2791 llvm::sys::path::extension(FileName).drop_front()) !=
2792 types::TY_Object))
2793 return ABRT_Inactive;
Samuel Antaofab4f372016-10-27 18:00:51 +00002794 for (unsigned I = 0; I < ToolChains.size(); ++I) {
2795 OpenMPDeviceActions.push_back(UA);
2796 UA->registerDependentActionInfo(
2797 ToolChains[I], /*BoundArch=*/StringRef(), Action::OFK_OpenMP);
2798 }
2799 return ABRT_Success;
2800 }
2801
Samuel Antao28c4f182016-10-27 17:08:03 +00002802 // When generating code for OpenMP we use the host compile phase result as
2803 // a dependence to the device compile phase so that it can learn what
2804 // declarations should be emitted. However, this is not the only use for
2805 // the host action, so we prevent it from being collapsed.
2806 if (isa<CompileJobAction>(HostAction)) {
2807 HostAction->setCannotBeCollapsedWithNextDependentAction();
2808 assert(ToolChains.size() == OpenMPDeviceActions.size() &&
2809 "Toolchains and device action sizes do not match.");
2810 OffloadAction::HostDependence HDep(
2811 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2812 /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2813 auto TC = ToolChains.begin();
2814 for (Action *&A : OpenMPDeviceActions) {
2815 assert(isa<CompileJobAction>(A));
2816 OffloadAction::DeviceDependences DDep;
2817 DDep.add(*A, **TC, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2818 A = C.MakeAction<OffloadAction>(HDep, DDep);
2819 ++TC;
2820 }
2821 }
2822 return ABRT_Success;
2823 }
2824
Samuel Antao69d6f312016-10-27 17:50:43 +00002825 void appendTopLevelActions(ActionList &AL) override {
2826 if (OpenMPDeviceActions.empty())
2827 return;
2828
2829 // We should always have an action for each input.
2830 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2831 "Number of OpenMP actions and toolchains do not match.");
2832
2833 // Append all device actions followed by the proper offload action.
2834 auto TI = ToolChains.begin();
2835 for (auto *A : OpenMPDeviceActions) {
2836 OffloadAction::DeviceDependences Dep;
2837 Dep.add(*A, **TI, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2838 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2839 ++TI;
2840 }
2841 // We no longer need the action stored in this builder.
2842 OpenMPDeviceActions.clear();
2843 }
2844
Samuel Antao28c4f182016-10-27 17:08:03 +00002845 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {
2846 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2847 "Toolchains and linker inputs sizes do not match.");
2848
2849 // Append a new link action for each device.
2850 auto TC = ToolChains.begin();
2851 for (auto &LI : DeviceLinkerInputs) {
2852 auto *DeviceLinkAction =
2853 C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2854 DA.add(*DeviceLinkAction, **TC, /*BoundArch=*/nullptr,
2855 Action::OFK_OpenMP);
2856 ++TC;
2857 }
2858 }
2859
2860 bool initialize() override {
2861 // Get the OpenMP toolchains. If we don't get any, the action builder will
2862 // know there is nothing to do related to OpenMP offloading.
2863 auto OpenMPTCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
2864 for (auto TI = OpenMPTCRange.first, TE = OpenMPTCRange.second; TI != TE;
2865 ++TI)
2866 ToolChains.push_back(TI->second);
2867
2868 DeviceLinkerInputs.resize(ToolChains.size());
2869 return false;
2870 }
Samuel Antao69d6f312016-10-27 17:50:43 +00002871
2872 bool canUseBundlerUnbundler() const override {
2873 // OpenMP should use bundled files whenever possible.
2874 return true;
2875 }
Samuel Antao28c4f182016-10-27 17:08:03 +00002876 };
2877
2878 ///
2879 /// TODO: Add the implementation for other specialized builders here.
2880 ///
Samuel Antao64e965e2016-09-30 15:34:19 +00002881
2882 /// Specialized builders being used by this offloading action builder.
2883 SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders;
2884
Samuel Antao69d6f312016-10-27 17:50:43 +00002885 /// Flag set to true if all valid builders allow file bundling/unbundling.
2886 bool CanUseBundler;
2887
Samuel Antao64e965e2016-09-30 15:34:19 +00002888public:
2889 OffloadingActionBuilder(Compilation &C, DerivedArgList &Args,
2890 const Driver::InputList &Inputs)
Samuel Antao10e905c2016-10-27 01:08:58 +00002891 : C(C) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002892 // Create a specialized builder for each device toolchain.
2893
2894 IsValid = true;
2895
2896 // Create a specialized builder for CUDA.
2897 SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs));
2898
Yaxun Liu3af038b2018-05-30 00:49:10 +00002899 // Create a specialized builder for HIP.
2900 SpecializedBuilders.push_back(new HIPActionBuilder(C, Args, Inputs));
2901
Samuel Antao28c4f182016-10-27 17:08:03 +00002902 // Create a specialized builder for OpenMP.
2903 SpecializedBuilders.push_back(new OpenMPActionBuilder(C, Args, Inputs));
2904
Samuel Antao64e965e2016-09-30 15:34:19 +00002905 //
2906 // TODO: Build other specialized builders here.
2907 //
2908
Samuel Antao69d6f312016-10-27 17:50:43 +00002909 // Initialize all the builders, keeping track of errors. If all valid
2910 // builders agree that we can use bundling, set the flag to true.
2911 unsigned ValidBuilders = 0u;
2912 unsigned ValidBuildersSupportingBundling = 0u;
2913 for (auto *SB : SpecializedBuilders) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002914 IsValid = IsValid && !SB->initialize();
Samuel Antao69d6f312016-10-27 17:50:43 +00002915
2916 // Update the counters if the builder is valid.
2917 if (SB->isValid()) {
2918 ++ValidBuilders;
2919 if (SB->canUseBundlerUnbundler())
2920 ++ValidBuildersSupportingBundling;
2921 }
2922 }
2923 CanUseBundler =
2924 ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling;
Artem Belevichf981e30b2016-08-02 22:37:47 +00002925 }
Justin Lebardc3c5042016-04-19 02:27:07 +00002926
Samuel Antao64e965e2016-09-30 15:34:19 +00002927 ~OffloadingActionBuilder() {
2928 for (auto *SB : SpecializedBuilders)
2929 delete SB;
Samuel Antaod06239d2016-07-15 23:13:27 +00002930 }
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002931
Samuel Antao64e965e2016-09-30 15:34:19 +00002932 /// Generate an action that adds device dependences (if any) to a host action.
2933 /// If no device dependence actions exist, just return the host action \a
2934 /// HostAction. If an error is found or if no builder requires the host action
2935 /// to be generated, return nullptr.
2936 Action *
2937 addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg,
2938 phases::ID CurPhase, phases::ID FinalPhase,
2939 DeviceActionBuilder::PhasesTy &Phases) {
2940 if (!IsValid)
2941 return nullptr;
Justin Lebar7bf77982016-01-11 23:27:13 +00002942
Samuel Antao64e965e2016-09-30 15:34:19 +00002943 if (SpecializedBuilders.empty())
2944 return HostAction;
2945
2946 assert(HostAction && "Invalid host action!");
2947
2948 OffloadAction::DeviceDependences DDeps;
2949 // Check if all the programming models agree we should not emit the host
2950 // action. Also, keep track of the offloading kinds employed.
2951 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2952 unsigned InactiveBuilders = 0u;
2953 unsigned IgnoringBuilders = 0u;
2954 for (auto *SB : SpecializedBuilders) {
2955 if (!SB->isValid()) {
2956 ++InactiveBuilders;
2957 continue;
2958 }
2959
Samuel Antao28c4f182016-10-27 17:08:03 +00002960 auto RetCode =
2961 SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases);
Samuel Antao64e965e2016-09-30 15:34:19 +00002962
2963 // If the builder explicitly says the host action should be ignored,
2964 // we need to increment the variable that tracks the builders that request
2965 // the host object to be ignored.
2966 if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host)
2967 ++IgnoringBuilders;
2968
2969 // Unless the builder was inactive for this action, we have to record the
2970 // offload kind because the host will have to use it.
2971 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2972 OffloadKind |= SB->getAssociatedOffloadKind();
2973 }
2974
2975 // If all builders agree that the host object should be ignored, just return
2976 // nullptr.
2977 if (IgnoringBuilders &&
2978 SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders))
2979 return nullptr;
2980
2981 if (DDeps.getActions().empty())
2982 return HostAction;
2983
2984 // We have dependences we need to bundle together. We use an offload action
2985 // for that.
2986 OffloadAction::HostDependence HDep(
2987 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2988 /*BoundArch=*/nullptr, DDeps);
2989 return C.MakeAction<OffloadAction>(HDep, DDeps);
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002990 }
2991
Samuel Antao64e965e2016-09-30 15:34:19 +00002992 /// Generate an action that adds a host dependence to a device action. The
2993 /// results will be kept in this action builder. Return true if an error was
2994 /// found.
Samuel Antaofab4f372016-10-27 18:00:51 +00002995 bool addHostDependenceToDeviceActions(Action *&HostAction,
Samuel Antao64e965e2016-09-30 15:34:19 +00002996 const Arg *InputArg) {
2997 if (!IsValid)
2998 return true;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002999
Samuel Antaofab4f372016-10-27 18:00:51 +00003000 // If we are supporting bundling/unbundling and the current action is an
3001 // input action of non-source file, we replace the host action by the
3002 // unbundling action. The bundler tool has the logic to detect if an input
3003 // is a bundle or not and if the input is not a bundle it assumes it is a
3004 // host file. Therefore it is safe to create an unbundling action even if
3005 // the input is not a bundle.
3006 if (CanUseBundler && isa<InputAction>(HostAction) &&
3007 InputArg->getOption().getKind() == llvm::opt::Option::InputClass &&
3008 !types::isSrcFile(HostAction->getType())) {
3009 auto UnbundlingHostAction =
3010 C.MakeAction<OffloadUnbundlingJobAction>(HostAction);
3011 UnbundlingHostAction->registerDependentActionInfo(
3012 C.getSingleOffloadToolChain<Action::OFK_Host>(),
Yaxun Liuf37b50a2018-07-24 01:03:44 +00003013 /*BoundArch=*/StringRef(), Action::OFK_Host);
Samuel Antaofab4f372016-10-27 18:00:51 +00003014 HostAction = UnbundlingHostAction;
3015 }
3016
Samuel Antao64e965e2016-09-30 15:34:19 +00003017 assert(HostAction && "Invalid host action!");
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003018
Samuel Antao64e965e2016-09-30 15:34:19 +00003019 // Register the offload kinds that are used.
3020 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
3021 for (auto *SB : SpecializedBuilders) {
3022 if (!SB->isValid())
3023 continue;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003024
Samuel Antao64e965e2016-09-30 15:34:19 +00003025 auto RetCode = SB->addDeviceDepences(HostAction);
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003026
Samuel Antao64e965e2016-09-30 15:34:19 +00003027 // Host dependences for device actions are not compatible with that same
3028 // action being ignored.
3029 assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host &&
3030 "Host dependence not expected to be ignored.!");
Samuel Antaod06239d2016-07-15 23:13:27 +00003031
Samuel Antao64e965e2016-09-30 15:34:19 +00003032 // Unless the builder was inactive for this action, we have to record the
3033 // offload kind because the host will have to use it.
3034 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
3035 OffloadKind |= SB->getAssociatedOffloadKind();
3036 }
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003037
Alexey Bataeva5178f52018-09-28 16:17:59 +00003038 // Do not use unbundler if the Host does not depend on device action.
3039 if (OffloadKind == Action::OFK_None && CanUseBundler)
3040 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction))
3041 HostAction = UA->getInputs().back();
3042
Samuel Antao64e965e2016-09-30 15:34:19 +00003043 return false;
3044 }
3045
Samuel Antao69d6f312016-10-27 17:50:43 +00003046 /// Add the offloading top level actions to the provided action list. This
3047 /// function can replace the host action by a bundling action if the
3048 /// programming models allow it.
Samuel Antao64e965e2016-09-30 15:34:19 +00003049 bool appendTopLevelActions(ActionList &AL, Action *HostAction,
3050 const Arg *InputArg) {
Samuel Antao69d6f312016-10-27 17:50:43 +00003051 // Get the device actions to be appended.
3052 ActionList OffloadAL;
Samuel Antao64e965e2016-09-30 15:34:19 +00003053 for (auto *SB : SpecializedBuilders) {
3054 if (!SB->isValid())
3055 continue;
Samuel Antao69d6f312016-10-27 17:50:43 +00003056 SB->appendTopLevelActions(OffloadAL);
Samuel Antao64e965e2016-09-30 15:34:19 +00003057 }
3058
Samuel Antao69d6f312016-10-27 17:50:43 +00003059 // If we can use the bundler, replace the host action by the bundling one in
Yaxun Liu2bcc9512018-11-14 04:47:31 +00003060 // the resulting list. Otherwise, just append the device actions. For
3061 // device only compilation, HostAction is a null pointer, therefore only do
3062 // this when HostAction is not a null pointer.
3063 if (CanUseBundler && HostAction && !OffloadAL.empty()) {
Samuel Antao69d6f312016-10-27 17:50:43 +00003064 // Add the host action to the list in order to create the bundling action.
3065 OffloadAL.push_back(HostAction);
3066
3067 // We expect that the host action was just appended to the action list
3068 // before this method was called.
3069 assert(HostAction == AL.back() && "Host action not in the list??");
3070 HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL);
3071 AL.back() = HostAction;
3072 } else
3073 AL.append(OffloadAL.begin(), OffloadAL.end());
3074
Samuel Antao64e965e2016-09-30 15:34:19 +00003075 // Propagate to the current host action (if any) the offload information
3076 // associated with the current input.
3077 if (HostAction)
3078 HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg],
3079 /*BoundArch=*/nullptr);
Samuel Antao64e965e2016-09-30 15:34:19 +00003080 return false;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003081 }
Artem Belevich5bde4e02015-07-20 20:02:54 +00003082
Samuel Antao64e965e2016-09-30 15:34:19 +00003083 /// Processes the host linker action. This currently consists of replacing it
3084 /// with an offload action if there are device link objects and propagate to
3085 /// the host action all the offload kinds used in the current compilation. The
3086 /// resulting action is returned.
3087 Action *processHostLinkAction(Action *HostAction) {
3088 // Add all the dependences from the device linking actions.
3089 OffloadAction::DeviceDependences DDeps;
3090 for (auto *SB : SpecializedBuilders) {
3091 if (!SB->isValid())
3092 continue;
Justin Lebar21e5d4f2016-01-14 21:41:27 +00003093
Samuel Antao64e965e2016-09-30 15:34:19 +00003094 SB->appendLinkDependences(DDeps);
Justin Lebar21e5d4f2016-01-14 21:41:27 +00003095 }
Samuel Antaod06239d2016-07-15 23:13:27 +00003096
Samuel Antao64e965e2016-09-30 15:34:19 +00003097 // Calculate all the offload kinds used in the current compilation.
3098 unsigned ActiveOffloadKinds = 0u;
3099 for (auto &I : InputArgToOffloadKindMap)
3100 ActiveOffloadKinds |= I.second;
3101
3102 // If we don't have device dependencies, we don't have to create an offload
3103 // action.
3104 if (DDeps.getActions().empty()) {
3105 // Propagate all the active kinds to host action. Given that it is a link
3106 // action it is assumed to depend on all actions generated so far.
3107 HostAction->propagateHostOffloadInfo(ActiveOffloadKinds,
3108 /*BoundArch=*/nullptr);
3109 return HostAction;
3110 }
3111
3112 // Create the offload action with all dependences. When an offload action
3113 // is created the kinds are propagated to the host action, so we don't have
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003114 // to do that explicitly here.
Samuel Antao64e965e2016-09-30 15:34:19 +00003115 OffloadAction::HostDependence HDep(
3116 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
3117 /*BoundArch*/ nullptr, ActiveOffloadKinds);
3118 return C.MakeAction<OffloadAction>(HDep, DDeps);
3119 }
3120};
3121} // anonymous namespace.
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003122
Justin Lebar0f3474c2016-02-11 02:00:50 +00003123void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
3124 const InputList &Inputs, ActionList &Actions) const {
Chad Rosierecdede82011-08-12 22:08:57 +00003125 llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00003126
Daniel Dunbar34c41872009-03-13 00:17:48 +00003127 if (!SuppressMissingInputWarning && Inputs.empty()) {
Daniel Dunbarbfeec742009-03-12 23:55:14 +00003128 Diag(clang::diag::err_drv_no_input_files);
3129 return;
3130 }
3131
Chad Rosier7742b5d2011-07-27 23:36:45 +00003132 Arg *FinalPhaseArg;
3133 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
Daniel Dunbarbfeec742009-03-12 23:55:14 +00003134
Bob Haarmanaaf51912017-02-27 19:40:19 +00003135 if (FinalPhase == phases::Link) {
3136 if (Args.hasArg(options::OPT_emit_llvm))
3137 Diag(clang::diag::err_drv_emit_llvm_link);
3138 if (IsCLMode() && LTOMode != LTOK_None &&
3139 !Args.getLastArgValue(options::OPT_fuse_ld_EQ).equals_lower("lld"))
3140 Diag(clang::diag::err_drv_lto_without_lld);
Rafael Espindolae8025642013-08-25 14:27:09 +00003141 }
3142
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003143 // Reject -Z* at the top level, these options should never have been exposed
3144 // by gcc.
Daniel Dunbardd765242009-03-26 16:12:09 +00003145 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
Daniel Dunbar0e759942009-03-20 06:14:23 +00003146 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
Daniel Dunbarbfeec742009-03-12 23:55:14 +00003147
Hans Wennborg13b7fe72013-08-12 23:26:25 +00003148 // Diagnose misuse of /Fo.
3149 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
Hans Wennborg13b7fe72013-08-12 23:26:25 +00003150 StringRef V = A->getValue();
Hans Wennborg61647532014-11-17 19:16:36 +00003151 if (Inputs.size() > 1 && !V.empty() &&
3152 !llvm::sys::path::is_separator(V.back())) {
Hans Wennborg13b7fe72013-08-12 23:26:25 +00003153 // Check whether /Fo tries to name an output file for multiple inputs.
Hans Wennborg9c1659b2013-10-18 22:49:04 +00003154 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003155 << A->getSpelling() << V;
Hans Wennborg13b7fe72013-08-12 23:26:25 +00003156 Args.eraseArg(options::OPT__SLASH_Fo);
3157 }
3158 }
3159
Hans Wennborg9c1659b2013-10-18 22:49:04 +00003160 // Diagnose misuse of /Fa.
3161 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
3162 StringRef V = A->getValue();
Hans Wennborg61647532014-11-17 19:16:36 +00003163 if (Inputs.size() > 1 && !V.empty() &&
3164 !llvm::sys::path::is_separator(V.back())) {
Hans Wennborg9c1659b2013-10-18 22:49:04 +00003165 // Check whether /Fa tries to name an asm file for multiple inputs.
3166 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003167 << A->getSpelling() << V;
Hans Wennborg9c1659b2013-10-18 22:49:04 +00003168 Args.eraseArg(options::OPT__SLASH_Fa);
3169 }
3170 }
3171
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00003172 // Diagnose misuse of /o.
3173 if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
3174 if (A->getValue()[0] == '\0') {
3175 // It has to have a value.
3176 Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
3177 Args.eraseArg(options::OPT__SLASH_o);
3178 }
3179 }
3180
Mike Rice58df1af2018-09-11 17:10:44 +00003181 // Ignore /Yc/Yu if both /Yc and /Yu passed but with different filenames.
Nico Weber2ca4be92016-03-01 23:16:44 +00003182 Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
3183 Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
Nico Weber2ca4be92016-03-01 23:16:44 +00003184 if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
3185 Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
3186 Args.eraseArg(options::OPT__SLASH_Yc);
3187 Args.eraseArg(options::OPT__SLASH_Yu);
3188 YcArg = YuArg = nullptr;
3189 }
Nico Weber2ca4be92016-03-01 23:16:44 +00003190 if (YcArg && Inputs.size() > 1) {
3191 Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
3192 Args.eraseArg(options::OPT__SLASH_Yc);
3193 YcArg = nullptr;
3194 }
Erich Keaneeaca3882018-08-17 13:43:39 +00003195 if (FinalPhase == phases::Preprocess || Args.hasArg(options::OPT__SLASH_Y_)) {
3196 // If only preprocessing or /Y- is used, all pch handling is disabled.
3197 // Rather than check for it everywhere, just remove clang-cl pch-related
3198 // flags here.
Nico Weber2ca4be92016-03-01 23:16:44 +00003199 Args.eraseArg(options::OPT__SLASH_Fp);
3200 Args.eraseArg(options::OPT__SLASH_Yc);
3201 Args.eraseArg(options::OPT__SLASH_Yu);
3202 YcArg = YuArg = nullptr;
3203 }
Nico Weber2ca4be92016-03-01 23:16:44 +00003204
Samuel Antao64e965e2016-09-30 15:34:19 +00003205 // Builder to be used to build offloading actions.
3206 OffloadingActionBuilder OffloadBuilder(C, Args, Inputs);
Samuel Antaod06239d2016-07-15 23:13:27 +00003207
Daniel Dunbar65229332009-03-13 11:38:42 +00003208 // Construct the actions to perform.
Richard Smithcd35eff2018-09-15 01:21:16 +00003209 HeaderModulePrecompileJobAction *HeaderModuleAction = nullptr;
Daniel Dunbar65229332009-03-13 11:38:42 +00003210 ActionList LinkerInputs;
Alp Toker965f8822013-11-27 05:22:15 +00003211
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00003212 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL;
Artem Belevich5bde4e02015-07-20 20:02:54 +00003213 for (auto &I : Inputs) {
3214 types::ID InputType = I.first;
3215 const Arg *InputArg = I.second;
Daniel Dunbar65229332009-03-13 11:38:42 +00003216
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00003217 PL.clear();
3218 types::getCompilationPhases(InputType, PL);
Daniel Dunbar65229332009-03-13 11:38:42 +00003219
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003220 // If the first step comes after the final phase we are doing as part of
3221 // this compilation, warn the user about it.
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00003222 phases::ID InitialPhase = PL[0];
Daniel Dunbar65229332009-03-13 11:38:42 +00003223 if (InitialPhase > FinalPhase) {
Martin Storsjo665c7a42018-05-04 06:05:58 +00003224 if (InputArg->isClaimed())
3225 continue;
3226
Daniel Dunbaradc5c7c2009-03-19 07:57:08 +00003227 // Claim here to avoid the more general unused warning.
3228 InputArg->claim();
Daniel Dunbar07806ca2009-09-17 04:13:26 +00003229
Daniel Dunbar2db3e732011-04-20 15:44:48 +00003230 // Suppress all unused style warnings with -Qunused-arguments
3231 if (Args.hasArg(options::OPT_Qunused_arguments))
3232 continue;
3233
Richard Smith403f76e2012-08-06 04:09:06 +00003234 // Special case when final phase determined by binary name, rather than
3235 // by a command-line argument with a corresponding Arg.
Hans Wennborg70850d82013-07-18 20:29:38 +00003236 if (CCCIsCPP())
Richard Smith403f76e2012-08-06 04:09:06 +00003237 Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003238 << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
Daniel Dunbar07806ca2009-09-17 04:13:26 +00003239 // Special case '-E' warning on a previously preprocessed file to make
3240 // more sense.
Richard Smith403f76e2012-08-06 04:09:06 +00003241 else if (InitialPhase == phases::Compile &&
3242 FinalPhase == phases::Preprocess &&
3243 getPreprocessedType(InputType) == types::TY_INVALID)
Daniel Dunbar07806ca2009-09-17 04:13:26 +00003244 Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003245 << InputArg->getAsString(Args) << !!FinalPhaseArg
3246 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
Daniel Dunbar07806ca2009-09-17 04:13:26 +00003247 else
3248 Diag(clang::diag::warn_drv_input_file_unused)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003249 << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
3250 << !!FinalPhaseArg
3251 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
Daniel Dunbar65229332009-03-13 11:38:42 +00003252 continue;
3253 }
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003254
Nico Weberad2d8f32016-04-21 19:59:10 +00003255 if (YcArg) {
3256 // Add a separate precompile phase for the compile phase.
3257 if (FinalPhase >= phases::Compile) {
Richard Smith8cd452d2016-08-30 18:55:16 +00003258 const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType);
Nico Weberad2d8f32016-04-21 19:59:10 +00003259 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PCHPL;
Richard Smith8cd452d2016-08-30 18:55:16 +00003260 types::getCompilationPhases(HeaderType, PCHPL);
Nico Weberad2d8f32016-04-21 19:59:10 +00003261 // Build the pipeline for the pch file.
Richard Smith8cd452d2016-08-30 18:55:16 +00003262 Action *ClangClPch =
Erich Keane76675de2018-07-05 17:22:13 +00003263 C.MakeAction<InputAction>(*InputArg, HeaderType);
Nico Weberad2d8f32016-04-21 19:59:10 +00003264 for (phases::ID Phase : PCHPL)
3265 ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
3266 assert(ClangClPch);
3267 Actions.push_back(ClangClPch);
3268 // The driver currently exits after the first failed command. This
3269 // relies on that behavior, to make sure if the pch generation fails,
3270 // the main compilation won't run.
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00003271 // FIXME: If the main compilation fails, the PCH generation should
3272 // probably not be considered successful either.
Nico Weberad2d8f32016-04-21 19:59:10 +00003273 }
3274 }
3275
Daniel Dunbar65229332009-03-13 11:38:42 +00003276 // Build the pipeline for this file.
Justin Lebar41094612016-01-11 23:07:27 +00003277 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
Samuel Antao64e965e2016-09-30 15:34:19 +00003278
3279 // Use the current host action in any of the offloading actions, if
3280 // required.
3281 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
3282 break;
3283
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003284 for (SmallVectorImpl<phases::ID>::iterator i = PL.begin(), e = PL.end();
3285 i != e; ++i) {
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00003286 phases::ID Phase = *i;
Daniel Dunbar65229332009-03-13 11:38:42 +00003287
3288 // We are done if this step is past what the user requested.
3289 if (Phase > FinalPhase)
3290 break;
3291
Samuel Antao64e965e2016-09-30 15:34:19 +00003292 // Add any offload action the host action depends on.
3293 Current = OffloadBuilder.addDeviceDependencesToHostAction(
3294 Current, InputArg, Phase, FinalPhase, PL);
3295 if (!Current)
3296 break;
3297
Daniel Dunbar65229332009-03-13 11:38:42 +00003298 // Queue linker inputs.
3299 if (Phase == phases::Link) {
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00003300 assert((i + 1) == e && "linking must be final compilation step.");
Justin Lebar41094612016-01-11 23:07:27 +00003301 LinkerInputs.push_back(Current);
3302 Current = nullptr;
Daniel Dunbar65229332009-03-13 11:38:42 +00003303 break;
3304 }
3305
Richard Smithcd35eff2018-09-15 01:21:16 +00003306 // Each precompiled header file after a module file action is a module
3307 // header of that same module file, rather than being compiled to a
3308 // separate PCH.
3309 if (Phase == phases::Precompile && HeaderModuleAction &&
3310 getPrecompiledType(InputType) == types::TY_PCH) {
3311 HeaderModuleAction->addModuleHeaderInput(Current);
3312 Current = nullptr;
3313 break;
3314 }
3315
3316 // FIXME: Should we include any prior module file outputs as inputs of
3317 // later actions in the same command line?
3318
Samuel Antao64e965e2016-09-30 15:34:19 +00003319 // Otherwise construct the appropriate action.
Richard Smithcd35eff2018-09-15 01:21:16 +00003320 Action *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current);
Samuel Antao64e965e2016-09-30 15:34:19 +00003321
3322 // We didn't create a new action, so we will just move to the next phase.
3323 if (NewCurrent == Current)
Daniel Dunbar13864952009-03-24 20:17:30 +00003324 continue;
3325
Richard Smithcd35eff2018-09-15 01:21:16 +00003326 if (auto *HMA = dyn_cast<HeaderModulePrecompileJobAction>(NewCurrent))
3327 HeaderModuleAction = HMA;
3328
Samuel Antao64e965e2016-09-30 15:34:19 +00003329 Current = NewCurrent;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003330
Samuel Antao64e965e2016-09-30 15:34:19 +00003331 // Use the current host action in any of the offloading actions, if
3332 // required.
3333 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
3334 break;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003335
Daniel Dunbar65229332009-03-13 11:38:42 +00003336 if (Current->getType() == types::TY_Nothing)
3337 break;
3338 }
3339
Samuel Antao64e965e2016-09-30 15:34:19 +00003340 // If we ended with something, add to the output list.
3341 if (Current)
Justin Lebar41094612016-01-11 23:07:27 +00003342 Actions.push_back(Current);
Samuel Antao64e965e2016-09-30 15:34:19 +00003343
3344 // Add any top level actions generated for offloading.
3345 OffloadBuilder.appendTopLevelActions(Actions, Current, InputArg);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00003346 }
Daniel Dunbar65229332009-03-13 11:38:42 +00003347
Samuel Antao64e965e2016-09-30 15:34:19 +00003348 // Add a link action if necessary.
Samuel Antaod06239d2016-07-15 23:13:27 +00003349 if (!LinkerInputs.empty()) {
Samuel Antao64e965e2016-09-30 15:34:19 +00003350 Action *LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image);
3351 LA = OffloadBuilder.processHostLinkAction(LA);
3352 Actions.push_back(LA);
Samuel Antaod06239d2016-07-15 23:13:27 +00003353 }
Daniel Dunbarc7a67b72009-12-22 23:19:32 +00003354
3355 // If we are linking, claim any options which are obviously only used for
3356 // compilation.
Hans Wennborga8ef14f2013-09-17 00:03:41 +00003357 if (FinalPhase == phases::Link && PL.size() == 1) {
Daniel Dunbarc7a67b72009-12-22 23:19:32 +00003358 Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
Hans Wennborga8ef14f2013-09-17 00:03:41 +00003359 Args.ClaimAllArgs(options::OPT_cl_compile_Group);
3360 }
3361
3362 // Claim ignored clang-cl options.
3363 Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
Artem Belevichbaae0932015-07-28 21:01:30 +00003364
Justin Lebardc3c5042016-04-19 02:27:07 +00003365 // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed
3366 // to non-CUDA compilations and should not trigger warnings there.
Artem Belevichbaae0932015-07-28 21:01:30 +00003367 Args.ClaimAllArgs(options::OPT_cuda_host_only);
Justin Lebardc3c5042016-04-19 02:27:07 +00003368 Args.ClaimAllArgs(options::OPT_cuda_compile_host_device);
Daniel Dunbar65229332009-03-13 11:38:42 +00003369}
3370
Artem Belevichecb178b2018-03-21 22:22:59 +00003371Action *Driver::ConstructPhaseAction(
3372 Compilation &C, const ArgList &Args, phases::ID Phase, Action *Input,
3373 Action::OffloadKind TargetDeviceOffloadKind) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00003374 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
Samuel Antao64e965e2016-09-30 15:34:19 +00003375
3376 // Some types skip the assembler phase (e.g., llvm-bc), but we can't
3377 // encode this in the steps because the intermediate type depends on
3378 // arguments. Just special case here.
3379 if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm)
3380 return Input;
3381
Daniel Dunbar65229332009-03-13 11:38:42 +00003382 // Build the appropriate action.
3383 switch (Phase) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003384 case phases::Link:
3385 llvm_unreachable("link action invalid here.");
Daniel Dunbar65229332009-03-13 11:38:42 +00003386 case phases::Preprocess: {
Daniel Dunbard67a3222009-03-30 06:36:42 +00003387 types::ID OutputTy;
3388 // -{M, MM} alter the output type.
Daniel Dunbar86aed7d2010-12-08 21:33:40 +00003389 if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
Daniel Dunbard67a3222009-03-30 06:36:42 +00003390 OutputTy = types::TY_Dependencies;
3391 } else {
David Blaikie5d577a22012-06-29 22:03:56 +00003392 OutputTy = Input->getType();
3393 if (!Args.hasFlag(options::OPT_frewrite_includes,
Justin Bognerce8245b2014-06-24 08:01:01 +00003394 options::OPT_fno_rewrite_includes, false) &&
Richard Smith86a3ef52017-06-09 21:24:02 +00003395 !Args.hasFlag(options::OPT_frewrite_imports,
3396 options::OPT_fno_rewrite_imports, false) &&
Justin Bognerce8245b2014-06-24 08:01:01 +00003397 !CCGenDiagnostics)
David Blaikie5d577a22012-06-29 22:03:56 +00003398 OutputTy = types::getPreprocessedType(OutputTy);
Daniel Dunbard67a3222009-03-30 06:36:42 +00003399 assert(OutputTy != types::TY_INVALID &&
3400 "Cannot preprocess this input type!");
3401 }
Justin Lebar41094612016-01-11 23:07:27 +00003402 return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
Daniel Dunbar65229332009-03-13 11:38:42 +00003403 }
Aaron Ballman1f10cc52012-07-31 01:21:00 +00003404 case phases::Precompile: {
Richard Smithdd4ad3d2016-08-30 19:06:26 +00003405 types::ID OutputTy = getPrecompiledType(Input->getType());
3406 assert(OutputTy != types::TY_INVALID &&
3407 "Cannot precompile this input type!");
Richard Smithcd35eff2018-09-15 01:21:16 +00003408
3409 // If we're given a module name, precompile header file inputs as a
3410 // module, not as a precompiled header.
3411 const char *ModName = nullptr;
3412 if (OutputTy == types::TY_PCH) {
3413 if (Arg *A = Args.getLastArg(options::OPT_fmodule_name_EQ))
3414 ModName = A->getValue();
3415 if (ModName)
3416 OutputTy = types::TY_ModuleFile;
3417 }
3418
Aaron Ballman1f10cc52012-07-31 01:21:00 +00003419 if (Args.hasArg(options::OPT_fsyntax_only)) {
3420 // Syntax checks should not emit a PCH file
3421 OutputTy = types::TY_Nothing;
3422 }
Richard Smithcd35eff2018-09-15 01:21:16 +00003423
3424 if (ModName)
3425 return C.MakeAction<HeaderModulePrecompileJobAction>(Input, OutputTy,
3426 ModName);
Justin Lebar41094612016-01-11 23:07:27 +00003427 return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
Aaron Ballman1f10cc52012-07-31 01:21:00 +00003428 }
Daniel Dunbar65229332009-03-13 11:38:42 +00003429 case phases::Compile: {
David Blaikie486f4402014-08-29 07:25:23 +00003430 if (Args.hasArg(options::OPT_fsyntax_only))
Justin Lebar41094612016-01-11 23:07:27 +00003431 return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
David Blaikie486f4402014-08-29 07:25:23 +00003432 if (Args.hasArg(options::OPT_rewrite_objc))
Justin Lebar41094612016-01-11 23:07:27 +00003433 return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
David Blaikie486f4402014-08-29 07:25:23 +00003434 if (Args.hasArg(options::OPT_rewrite_legacy_objc))
Justin Lebar41094612016-01-11 23:07:27 +00003435 return C.MakeAction<CompileJobAction>(Input,
3436 types::TY_RewrittenLegacyObjC);
David Blaikie486f4402014-08-29 07:25:23 +00003437 if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto))
Justin Lebar41094612016-01-11 23:07:27 +00003438 return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
David Blaikie486f4402014-08-29 07:25:23 +00003439 if (Args.hasArg(options::OPT__migrate))
Justin Lebar41094612016-01-11 23:07:27 +00003440 return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
David Blaikie486f4402014-08-29 07:25:23 +00003441 if (Args.hasArg(options::OPT_emit_ast))
Justin Lebar41094612016-01-11 23:07:27 +00003442 return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
David Blaikie486f4402014-08-29 07:25:23 +00003443 if (Args.hasArg(options::OPT_module_file_info))
Justin Lebar41094612016-01-11 23:07:27 +00003444 return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
David Blaikie486f4402014-08-29 07:25:23 +00003445 if (Args.hasArg(options::OPT_verify_pch))
Justin Lebar41094612016-01-11 23:07:27 +00003446 return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
3447 return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
Bob Wilson23a55f12014-12-21 07:00:00 +00003448 }
3449 case phases::Backend: {
Artem Belevichecb178b2018-03-21 22:22:59 +00003450 if (isUsingLTO() && TargetDeviceOffloadKind == Action::OFK_None) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003451 types::ID Output =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003452 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
Justin Lebar41094612016-01-11 23:07:27 +00003453 return C.MakeAction<BackendJobAction>(Input, Output);
David Blaikie486f4402014-08-29 07:25:23 +00003454 }
3455 if (Args.hasArg(options::OPT_emit_llvm)) {
Shuxin Yang4b3c7ff2013-08-23 21:34:57 +00003456 types::ID Output =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003457 Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
Justin Lebar41094612016-01-11 23:07:27 +00003458 return C.MakeAction<BackendJobAction>(Input, Output);
Daniel Dunbar65229332009-03-13 11:38:42 +00003459 }
Justin Lebar41094612016-01-11 23:07:27 +00003460 return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
Daniel Dunbar65229332009-03-13 11:38:42 +00003461 }
3462 case phases::Assemble:
Justin Lebar21e5d4f2016-01-14 21:41:27 +00003463 return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
Daniel Dunbar65229332009-03-13 11:38:42 +00003464 }
3465
David Blaikie83d382b2011-09-23 05:06:16 +00003466 llvm_unreachable("invalid phase in ConstructPhaseAction");
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00003467}
3468
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00003469void Driver::BuildJobs(Compilation &C) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00003470 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
Daniel Dunbare75d8342009-03-16 06:56:51 +00003471
3472 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
3473
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003474 // It is an error to provide a -o option if we are making multiple output
3475 // files.
Daniel Dunbare75d8342009-03-16 06:56:51 +00003476 if (FinalOutput) {
3477 unsigned NumOutputs = 0;
Saleem Abdulrasoolda3f4e52014-12-29 21:02:47 +00003478 for (const Action *A : C.getActions())
3479 if (A->getType() != types::TY_Nothing)
Daniel Dunbare75d8342009-03-16 06:56:51 +00003480 ++NumOutputs;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003481
Daniel Dunbare75d8342009-03-16 06:56:51 +00003482 if (NumOutputs > 1) {
3483 Diag(clang::diag::err_drv_output_argument_with_multiple_files);
Craig Topper92fc2df2014-05-17 16:56:41 +00003484 FinalOutput = nullptr;
Daniel Dunbare75d8342009-03-16 06:56:51 +00003485 }
3486 }
3487
Chad Rosier35767232013-04-30 22:01:21 +00003488 // Collect the list of architectures.
3489 llvm::StringSet<> ArchNames;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00003490 if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO())
3491 for (const Arg *A : C.getArgs())
Chad Rosier35767232013-04-30 22:01:21 +00003492 if (A->getOption().matches(options::OPT_arch))
3493 ArchNames.insert(A->getValue());
Chad Rosier35767232013-04-30 22:01:21 +00003494
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003495 // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
3496 std::map<std::pair<const Action *, std::string>, InputInfo> CachedResults;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00003497 for (Action *A : C.getActions()) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003498 // If we are linking an image for multiple archs then the linker wants
3499 // -arch_multiple and -final_output <final image name>. Unfortunately, this
3500 // doesn't fit in cleanly because we have to pass this information down.
Daniel Dunbare75d8342009-03-16 06:56:51 +00003501 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003502 // FIXME: This is a hack; find a cleaner way to integrate this into the
3503 // process.
Craig Topper92fc2df2014-05-17 16:56:41 +00003504 const char *LinkingOutput = nullptr;
Daniel Dunbardd765242009-03-26 16:12:09 +00003505 if (isa<LipoJobAction>(A)) {
Daniel Dunbare75d8342009-03-16 06:56:51 +00003506 if (FinalOutput)
Richard Smithbd55daf2012-11-01 04:30:05 +00003507 LinkingOutput = FinalOutput->getValue();
Daniel Dunbare75d8342009-03-16 06:56:51 +00003508 else
Hans Wennborga7707222015-01-09 17:38:53 +00003509 LinkingOutput = getDefaultImageName();
Daniel Dunbare75d8342009-03-16 06:56:51 +00003510 }
3511
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003512 BuildJobsForAction(C, A, &C.getDefaultToolChain(),
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003513 /*BoundArch*/ StringRef(),
Daniel Dunbare75d8342009-03-16 06:56:51 +00003514 /*AtTopLevel*/ true,
Chad Rosier35767232013-04-30 22:01:21 +00003515 /*MultipleArchs*/ ArchNames.size() > 1,
Samuel Antaod06239d2016-07-15 23:13:27 +00003516 /*LinkingOutput*/ LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003517 /*TargetDeviceOffloadKind*/ Action::OFK_None);
Daniel Dunbare75d8342009-03-16 06:56:51 +00003518 }
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00003519
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003520 // If the user passed -Qunused-arguments or there were errors, don't warn
3521 // about any unused arguments.
Argyrios Kyrtzidis31448a42010-11-18 21:47:07 +00003522 if (Diags.hasErrorOccurred() ||
Daniel Dunbara3cfbe32009-04-07 19:04:18 +00003523 C.getArgs().hasArg(options::OPT_Qunused_arguments))
Daniel Dunbard175d972009-03-18 18:03:46 +00003524 return;
3525
Daniel Dunbar58399ae2009-03-29 22:24:54 +00003526 // Claim -### here.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003527 (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003528
Nico Weber47bf5052016-04-25 21:15:49 +00003529 // Claim --driver-mode, --rsp-quoting, it was handled earlier.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003530 (void)C.getArgs().hasArg(options::OPT_driver_mode);
Nico Weber47bf5052016-04-25 21:15:49 +00003531 (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
Hans Wennborg70850d82013-07-18 20:29:38 +00003532
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00003533 for (Arg *A : C.getArgs()) {
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00003534 // FIXME: It would be nice to be able to send the argument to the
David Blaikie9c902b52011-09-25 23:23:43 +00003535 // DiagnosticsEngine, so that extra values, position, and so on could be
3536 // printed.
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003537 if (!A->isClaimed()) {
Michael J. Spencer66e2b202012-10-19 22:37:06 +00003538 if (A->getOption().hasFlag(options::NoArgumentUnused))
Daniel Dunbara3cfbe32009-04-07 19:04:18 +00003539 continue;
3540
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003541 // Suppress the warning automatically if this is just a flag, and it is an
3542 // instance of an argument we already claimed.
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003543 const Option &Opt = A->getOption();
Michael J. Spencerad3ccc32012-08-20 21:41:17 +00003544 if (Opt.getKind() == Option::FlagClass) {
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003545 bool DuplicateClaimed = false;
3546
Sean Silva14facf32015-06-09 01:57:17 +00003547 for (const Arg *AA : C.getArgs().filtered(&Opt)) {
3548 if (AA->isClaimed()) {
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003549 DuplicateClaimed = true;
3550 break;
3551 }
3552 }
3553
3554 if (DuplicateClaimed)
3555 continue;
3556 }
3557
Ehsan Akhgarid8518332016-01-25 21:14:52 +00003558 // In clang-cl, don't mention unknown arguments here since they have
3559 // already been warned about.
3560 if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN))
3561 Diag(clang::diag::warn_drv_unused_argument)
3562 << A->getAsString(C.getArgs());
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003563 }
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00003564 }
Daniel Dunbar95e6b192009-03-13 22:12:33 +00003565}
Daniel Dunbarc4343942010-02-03 03:07:56 +00003566
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003567namespace {
3568/// Utility class to control the collapse of dependent actions and select the
3569/// tools accordingly.
3570class ToolSelector final {
3571 /// The tool chain this selector refers to.
3572 const ToolChain &TC;
Daniel Dunbarf9ff3502010-05-14 02:03:00 +00003573
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003574 /// The compilation this selector refers to.
3575 const Compilation &C;
Samuel Antaod06239d2016-07-15 23:13:27 +00003576
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003577 /// The base action this selector refers to.
3578 const JobAction *BaseAction;
Samuel Antaod06239d2016-07-15 23:13:27 +00003579
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003580 /// Set to true if the current toolchain refers to host actions.
3581 bool IsHostSelector;
Samuel Antaod06239d2016-07-15 23:13:27 +00003582
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003583 /// Set to true if save-temps and embed-bitcode functionalities are active.
3584 bool SaveTemps;
3585 bool EmbedBitcode;
3586
3587 /// Get previous dependent action or null if that does not exist. If
3588 /// \a CanBeCollapsed is false, that action must be legal to collapse or
3589 /// null will be returned.
3590 const JobAction *getPrevDependentAction(const ActionList &Inputs,
3591 ActionList &SavedOffloadAction,
3592 bool CanBeCollapsed = true) {
3593 // An option can be collapsed only if it has a single input.
3594 if (Inputs.size() != 1)
Craig Topper92fc2df2014-05-17 16:56:41 +00003595 return nullptr;
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003596
3597 Action *CurAction = *Inputs.begin();
3598 if (CanBeCollapsed &&
3599 !CurAction->isCollapsingWithNextDependentActionLegal())
3600 return nullptr;
3601
3602 // If the input action is an offload action. Look through it and save any
3603 // offload action that can be dropped in the event of a collapse.
3604 if (auto *OA = dyn_cast<OffloadAction>(CurAction)) {
3605 // If the dependent action is a device action, we will attempt to collapse
3606 // only with other device actions. Otherwise, we would do the same but
3607 // with host actions only.
3608 if (!IsHostSelector) {
3609 if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) {
3610 CurAction =
3611 OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
3612 if (CanBeCollapsed &&
3613 !CurAction->isCollapsingWithNextDependentActionLegal())
3614 return nullptr;
3615 SavedOffloadAction.push_back(OA);
3616 return dyn_cast<JobAction>(CurAction);
3617 }
3618 } else if (OA->hasHostDependence()) {
3619 CurAction = OA->getHostDependence();
3620 if (CanBeCollapsed &&
3621 !CurAction->isCollapsingWithNextDependentActionLegal())
3622 return nullptr;
3623 SavedOffloadAction.push_back(OA);
3624 return dyn_cast<JobAction>(CurAction);
3625 }
3626 return nullptr;
3627 }
3628
3629 return dyn_cast<JobAction>(CurAction);
3630 }
3631
3632 /// Return true if an assemble action can be collapsed.
3633 bool canCollapseAssembleAction() const {
3634 return TC.useIntegratedAs() && !SaveTemps &&
3635 !C.getArgs().hasArg(options::OPT_via_file_asm) &&
3636 !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
3637 !C.getArgs().hasArg(options::OPT__SLASH_Fa);
3638 }
3639
3640 /// Return true if a preprocessor action can be collapsed.
3641 bool canCollapsePreprocessorAction() const {
3642 return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
3643 !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
3644 !C.getArgs().hasArg(options::OPT_rewrite_objc);
3645 }
3646
3647 /// Struct that relates an action with the offload actions that would be
3648 /// collapsed with it.
3649 struct JobActionInfo final {
3650 /// The action this info refers to.
3651 const JobAction *JA = nullptr;
3652 /// The offload actions we need to take care off if this action is
3653 /// collapsed.
3654 ActionList SavedOffloadAction;
3655 };
3656
3657 /// Append collapsed offload actions from the give nnumber of elements in the
3658 /// action info array.
3659 static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction,
3660 ArrayRef<JobActionInfo> &ActionInfo,
3661 unsigned ElementNum) {
3662 assert(ElementNum <= ActionInfo.size() && "Invalid number of elements.");
3663 for (unsigned I = 0; I < ElementNum; ++I)
3664 CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(),
3665 ActionInfo[I].SavedOffloadAction.end());
3666 }
3667
3668 /// Functions that attempt to perform the combining. They detect if that is
3669 /// legal, and if so they update the inputs \a Inputs and the offload action
3670 /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with
3671 /// the combined action is returned. If the combining is not legal or if the
3672 /// tool does not exist, null is returned.
3673 /// Currently three kinds of collapsing are supported:
3674 /// - Assemble + Backend + Compile;
3675 /// - Assemble + Backend ;
3676 /// - Backend + Compile.
3677 const Tool *
3678 combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
Richard Smithcd35eff2018-09-15 01:21:16 +00003679 ActionList &Inputs,
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003680 ActionList &CollapsedOffloadAction) {
3681 if (ActionInfo.size() < 3 || !canCollapseAssembleAction())
3682 return nullptr;
3683 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
3684 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
3685 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA);
3686 if (!AJ || !BJ || !CJ)
3687 return nullptr;
3688
3689 // Get compiler tool.
3690 const Tool *T = TC.SelectTool(*CJ);
3691 if (!T)
3692 return nullptr;
3693
Steven Wu574b0f22016-03-01 01:07:58 +00003694 // When using -fembed-bitcode, it is required to have the same tool (clang)
3695 // for both CompilerJA and BackendJA. Otherwise, combine two stages.
3696 if (EmbedBitcode) {
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003697 const Tool *BT = TC.SelectTool(*BJ);
3698 if (BT == T)
3699 return nullptr;
Steven Wu574b0f22016-03-01 01:07:58 +00003700 }
Bob Wilson23a55f12014-12-21 07:00:00 +00003701
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003702 if (!T->hasIntegratedAssembler())
Bob Wilson23a55f12014-12-21 07:00:00 +00003703 return nullptr;
Samuel Antaod06239d2016-07-15 23:13:27 +00003704
Richard Smithcd35eff2018-09-15 01:21:16 +00003705 Inputs = CJ->getInputs();
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003706 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3707 /*NumElements=*/3);
3708 return T;
3709 }
3710 const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo,
Richard Smithcd35eff2018-09-15 01:21:16 +00003711 ActionList &Inputs,
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003712 ActionList &CollapsedOffloadAction) {
3713 if (ActionInfo.size() < 2 || !canCollapseAssembleAction())
3714 return nullptr;
3715 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
3716 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
3717 if (!AJ || !BJ)
3718 return nullptr;
3719
3720 // Retrieve the compile job, backend action must always be preceded by one.
3721 ActionList CompileJobOffloadActions;
3722 auto *CJ = getPrevDependentAction(BJ->getInputs(), CompileJobOffloadActions,
3723 /*CanBeCollapsed=*/false);
3724 if (!AJ || !BJ || !CJ)
3725 return nullptr;
3726
3727 assert(isa<CompileJobAction>(CJ) &&
3728 "Expecting compile job preceding backend job.");
3729
3730 // Get compiler tool.
3731 const Tool *T = TC.SelectTool(*CJ);
3732 if (!T)
3733 return nullptr;
3734
3735 if (!T->hasIntegratedAssembler())
3736 return nullptr;
3737
Richard Smithcd35eff2018-09-15 01:21:16 +00003738 Inputs = BJ->getInputs();
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003739 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3740 /*NumElements=*/2);
3741 return T;
3742 }
3743 const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
Richard Smithcd35eff2018-09-15 01:21:16 +00003744 ActionList &Inputs,
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003745 ActionList &CollapsedOffloadAction) {
Teresa Johnson9e4321c2018-04-17 16:39:25 +00003746 if (ActionInfo.size() < 2)
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003747 return nullptr;
3748 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA);
3749 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA);
3750 if (!BJ || !CJ)
3751 return nullptr;
3752
Teresa Johnson9e4321c2018-04-17 16:39:25 +00003753 // Check if the initial input (to the compile job or its predessor if one
3754 // exists) is LLVM bitcode. In that case, no preprocessor step is required
3755 // and we can still collapse the compile and backend jobs when we have
3756 // -save-temps. I.e. there is no need for a separate compile job just to
3757 // emit unoptimized bitcode.
3758 bool InputIsBitcode = true;
3759 for (size_t i = 1; i < ActionInfo.size(); i++)
3760 if (ActionInfo[i].JA->getType() != types::TY_LLVM_BC &&
3761 ActionInfo[i].JA->getType() != types::TY_LTO_BC) {
3762 InputIsBitcode = false;
3763 break;
3764 }
3765 if (!InputIsBitcode && !canCollapsePreprocessorAction())
3766 return nullptr;
3767
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003768 // Get compiler tool.
3769 const Tool *T = TC.SelectTool(*CJ);
3770 if (!T)
3771 return nullptr;
3772
Teresa Johnson9e4321c2018-04-17 16:39:25 +00003773 if (T->canEmitIR() && ((SaveTemps && !InputIsBitcode) || EmbedBitcode))
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003774 return nullptr;
3775
Richard Smithcd35eff2018-09-15 01:21:16 +00003776 Inputs = CJ->getInputs();
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003777 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3778 /*NumElements=*/2);
3779 return T;
3780 }
3781
3782 /// Updates the inputs if the obtained tool supports combining with
3783 /// preprocessor action, and the current input is indeed a preprocessor
3784 /// action. If combining results in the collapse of offloading actions, those
3785 /// are appended to \a CollapsedOffloadAction.
Richard Smithcd35eff2018-09-15 01:21:16 +00003786 void combineWithPreprocessor(const Tool *T, ActionList &Inputs,
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003787 ActionList &CollapsedOffloadAction) {
3788 if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP())
3789 return;
3790
3791 // Attempt to get a preprocessor action dependence.
3792 ActionList PreprocessJobOffloadActions;
Richard Smithcd35eff2018-09-15 01:21:16 +00003793 ActionList NewInputs;
3794 for (Action *A : Inputs) {
3795 auto *PJ = getPrevDependentAction({A}, PreprocessJobOffloadActions);
3796 if (!PJ || !isa<PreprocessJobAction>(PJ)) {
3797 NewInputs.push_back(A);
3798 continue;
3799 }
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003800
Richard Smithcd35eff2018-09-15 01:21:16 +00003801 // This is legal to combine. Append any offload action we found and add the
3802 // current input to preprocessor inputs.
3803 CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(),
3804 PreprocessJobOffloadActions.end());
3805 NewInputs.append(PJ->input_begin(), PJ->input_end());
3806 }
3807 Inputs = NewInputs;
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003808 }
3809
3810public:
3811 ToolSelector(const JobAction *BaseAction, const ToolChain &TC,
3812 const Compilation &C, bool SaveTemps, bool EmbedBitcode)
3813 : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps),
3814 EmbedBitcode(EmbedBitcode) {
3815 assert(BaseAction && "Invalid base action.");
3816 IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None;
3817 }
3818
3819 /// Check if a chain of actions can be combined and return the tool that can
3820 /// handle the combination of actions. The pointer to the current inputs \a
3821 /// Inputs and the list of offload actions \a CollapsedOffloadActions
3822 /// connected to collapsed actions are updated accordingly. The latter enables
3823 /// the caller of the selector to process them afterwards instead of just
3824 /// dropping them. If no suitable tool is found, null will be returned.
Richard Smithcd35eff2018-09-15 01:21:16 +00003825 const Tool *getTool(ActionList &Inputs,
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003826 ActionList &CollapsedOffloadAction) {
3827 //
3828 // Get the largest chain of actions that we could combine.
3829 //
3830
3831 SmallVector<JobActionInfo, 5> ActionChain(1);
3832 ActionChain.back().JA = BaseAction;
3833 while (ActionChain.back().JA) {
3834 const Action *CurAction = ActionChain.back().JA;
3835
3836 // Grow the chain by one element.
3837 ActionChain.resize(ActionChain.size() + 1);
3838 JobActionInfo &AI = ActionChain.back();
3839
3840 // Attempt to fill it with the
3841 AI.JA =
3842 getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction);
Daniel Dunbarc4343942010-02-03 03:07:56 +00003843 }
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003844
3845 // Pop the last action info as it could not be filled.
3846 ActionChain.pop_back();
3847
3848 //
3849 // Attempt to combine actions. If all combining attempts failed, just return
3850 // the tool of the provided action. At the end we attempt to combine the
3851 // action with any preprocessor action it may depend on.
3852 //
3853
3854 const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs,
3855 CollapsedOffloadAction);
3856 if (!T)
3857 T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction);
3858 if (!T)
3859 T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction);
3860 if (!T) {
Richard Smithcd35eff2018-09-15 01:21:16 +00003861 Inputs = BaseAction->getInputs();
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003862 T = TC.SelectTool(*BaseAction);
3863 }
3864
3865 combineWithPreprocessor(T, Inputs, CollapsedOffloadAction);
3866 return T;
Daniel Dunbarc4343942010-02-03 03:07:56 +00003867 }
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003868};
Daniel Dunbarc4343942010-02-03 03:07:56 +00003869}
3870
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003871/// Return a string that uniquely identifies the result of a job. The bound arch
3872/// is not necessarily represented in the toolchain's triple -- for example,
3873/// armv7 and armv7s both map to the same triple -- so we need both in our map.
3874/// Also, we need to add the offloading device kind, as the same tool chain can
3875/// be used for host and device for some programming models, e.g. OpenMP.
3876static std::string GetTriplePlusArchString(const ToolChain *TC,
3877 StringRef BoundArch,
3878 Action::OffloadKind OffloadKind) {
Justin Lebar55c83322016-01-16 03:30:08 +00003879 std::string TriplePlusArch = TC->getTriple().normalize();
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003880 if (!BoundArch.empty()) {
Justin Lebar55c83322016-01-16 03:30:08 +00003881 TriplePlusArch += "-";
3882 TriplePlusArch += BoundArch;
3883 }
Samuel Antao59efaed2016-10-27 17:31:22 +00003884 TriplePlusArch += "-";
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003885 TriplePlusArch += Action::GetOffloadKindName(OffloadKind);
3886 return TriplePlusArch;
3887}
3888
3889InputInfo Driver::BuildJobsForAction(
3890 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
3891 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
3892 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
3893 Action::OffloadKind TargetDeviceOffloadKind) const {
3894 std::pair<const Action *, std::string> ActionTC = {
3895 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003896 auto CachedResult = CachedResults.find(ActionTC);
3897 if (CachedResult != CachedResults.end()) {
3898 return CachedResult->second;
3899 }
Samuel Antaod06239d2016-07-15 23:13:27 +00003900 InputInfo Result = BuildJobsForActionNoCache(
3901 C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003902 CachedResults, TargetDeviceOffloadKind);
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003903 CachedResults[ActionTC] = Result;
3904 return Result;
3905}
3906
3907InputInfo Driver::BuildJobsForActionNoCache(
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003908 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003909 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
Samuel Antaod06239d2016-07-15 23:13:27 +00003910 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003911 Action::OffloadKind TargetDeviceOffloadKind) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003912 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
Daniel Dunbarc4acf9d2009-03-18 23:18:19 +00003913
Samuel Antaod06239d2016-07-15 23:13:27 +00003914 InputInfoList OffloadDependencesInputInfo;
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003915 bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None;
Samuel Antaod06239d2016-07-15 23:13:27 +00003916 if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
Alex Lorenz4003a982017-08-08 11:22:21 +00003917 // The 'Darwin' toolchain is initialized only when its arguments are
3918 // computed. Get the default arguments for OFK_None to ensure that
3919 // initialization is performed before processing the offload action.
3920 // FIXME: Remove when darwin's toolchain is initialized during construction.
3921 C.getArgsForToolChain(TC, BoundArch, Action::OFK_None);
3922
Samuel Antaod06239d2016-07-15 23:13:27 +00003923 // The offload action is expected to be used in four different situations.
3924 //
3925 // a) Set a toolchain/architecture/kind for a host action:
3926 // Host Action 1 -> OffloadAction -> Host Action 2
3927 //
3928 // b) Set a toolchain/architecture/kind for a device action;
3929 // Device Action 1 -> OffloadAction -> Device Action 2
3930 //
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003931 // c) Specify a device dependence to a host action;
Samuel Antaod06239d2016-07-15 23:13:27 +00003932 // Device Action 1 _
3933 // \
3934 // Host Action 1 ---> OffloadAction -> Host Action 2
3935 //
3936 // d) Specify a host dependence to a device action.
3937 // Host Action 1 _
3938 // \
3939 // Device Action 1 ---> OffloadAction -> Device Action 2
3940 //
3941 // For a) and b), we just return the job generated for the dependence. For
3942 // c) and d) we override the current action with the host/device dependence
3943 // if the current toolchain is host/device and set the offload dependences
3944 // info with the jobs obtained from the device/host dependence(s).
3945
3946 // If there is a single device option, just generate the job for it.
3947 if (OA->hasSingleDeviceDependence()) {
3948 InputInfo DevA;
3949 OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
3950 const char *DepBoundArch) {
3951 DevA =
3952 BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
3953 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003954 CachedResults, DepA->getOffloadingDeviceKind());
Samuel Antaod06239d2016-07-15 23:13:27 +00003955 });
3956 return DevA;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003957 }
Samuel Antaod06239d2016-07-15 23:13:27 +00003958
3959 // If 'Action 2' is host, we generate jobs for the device dependences and
3960 // override the current action with the host dependence. Otherwise, we
3961 // generate the host dependences and override the action with the device
3962 // dependence. The dependences can't therefore be a top-level action.
3963 OA->doOnEachDependence(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003964 /*IsHostDependence=*/BuildingForOffloadDevice,
Samuel Antaod06239d2016-07-15 23:13:27 +00003965 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3966 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
3967 C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false,
3968 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003969 DepA->getOffloadingDeviceKind()));
Samuel Antaod06239d2016-07-15 23:13:27 +00003970 });
3971
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003972 A = BuildingForOffloadDevice
Samuel Antaod06239d2016-07-15 23:13:27 +00003973 ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
3974 : OA->getHostDependence();
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003975 }
3976
Daniel Dunbare75d8342009-03-16 06:56:51 +00003977 if (const InputAction *IA = dyn_cast<InputAction>(A)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003978 // FIXME: It would be nice to not claim this here; maybe the old scheme of
3979 // just using Args was better?
Daniel Dunbar5cdf3e02009-03-19 07:29:38 +00003980 const Arg &Input = IA->getInputArg();
3981 Input.claim();
Daniel Dunbar35cbfeb2010-06-09 22:31:08 +00003982 if (Input.getOption().matches(options::OPT_INPUT)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00003983 const char *Name = Input.getValue();
Justin Lebard98cea82016-01-11 23:15:21 +00003984 return InputInfo(A, Name, /* BaseInput = */ Name);
Douglas Katzman678d0cb2015-06-16 18:01:24 +00003985 }
Justin Lebard98cea82016-01-11 23:15:21 +00003986 return InputInfo(A, &Input, /* BaseInput = */ "");
Daniel Dunbare75d8342009-03-16 06:56:51 +00003987 }
3988
3989 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
Chad Rosiera78a6eb2012-04-27 16:50:38 +00003990 const ToolChain *TC;
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003991 StringRef ArchName = BAA->getArchName();
Daniel Dunbar1ef3f2a2009-09-08 23:37:19 +00003992
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003993 if (!ArchName.empty())
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +00003994 TC = &getToolChain(C.getArgs(),
Petr Hosekdd38d932018-05-29 22:35:39 +00003995 computeTargetTriple(*this, TargetTriple,
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +00003996 C.getArgs(), ArchName));
Chad Rosiera78a6eb2012-04-27 16:50:38 +00003997 else
3998 TC = &C.getDefaultToolChain();
Daniel Dunbar1ef3f2a2009-09-08 23:37:19 +00003999
Nico Weber5a459f82016-02-23 19:30:43 +00004000 return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
Samuel Antaod06239d2016-07-15 23:13:27 +00004001 MultipleArchs, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004002 TargetDeviceOffloadKind);
Daniel Dunbare75d8342009-03-16 06:56:51 +00004003 }
4004
Artem Belevich0ff05cd2015-07-13 23:27:56 +00004005
Richard Smithcd35eff2018-09-15 01:21:16 +00004006 ActionList Inputs = A->getInputs();
Daniel Dunbarc4343942010-02-03 03:07:56 +00004007
4008 const JobAction *JA = cast<JobAction>(A);
Samuel Antaod06239d2016-07-15 23:13:27 +00004009 ActionList CollapsedOffloadActions;
4010
Mehdi Amini6683e222017-01-24 18:12:25 +00004011 ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(),
4012 embedBitcodeInObject() && !isUsingLTO());
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00004013 const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions);
4014
Rafael Espindola79764462013-03-24 15:06:53 +00004015 if (!T)
Justin Lebar9eaa4892016-01-11 23:09:32 +00004016 return InputInfo();
Daniel Dunbare75d8342009-03-16 06:56:51 +00004017
Samuel Antaod06239d2016-07-15 23:13:27 +00004018 // If we've collapsed action list that contained OffloadAction we
4019 // need to build jobs for host/device-side inputs it may have held.
4020 for (const auto *OA : CollapsedOffloadActions)
4021 cast<OffloadAction>(OA)->doOnEachDependence(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004022 /*IsHostDependence=*/BuildingForOffloadDevice,
Samuel Antaod06239d2016-07-15 23:13:27 +00004023 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
4024 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
Artem Belevichbee2f412016-08-22 18:50:34 +00004025 C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false,
Samuel Antaod06239d2016-07-15 23:13:27 +00004026 /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004027 DepA->getOffloadingDeviceKind()));
Samuel Antaod06239d2016-07-15 23:13:27 +00004028 });
Artem Belevichf8144ab2015-08-27 18:10:41 +00004029
Daniel Dunbare75d8342009-03-16 06:56:51 +00004030 // Only use pipes when there is exactly one input.
Daniel Dunbar1a093d22009-03-18 06:00:36 +00004031 InputInfoList InputInfos;
Richard Smithcd35eff2018-09-15 01:21:16 +00004032 for (const Action *Input : Inputs) {
Eric Christopher14668dd2013-02-18 00:38:25 +00004033 // Treat dsymutil and verify sub-jobs as being at the top-level too, they
4034 // shouldn't get temporary output names.
Daniel Dunbar6beaf512010-06-04 18:28:41 +00004035 // FIXME: Clean this up.
Justin Lebar9eaa4892016-01-11 23:09:32 +00004036 bool SubJobAtTopLevel =
4037 AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
Samuel Antaod06239d2016-07-15 23:13:27 +00004038 InputInfos.push_back(BuildJobsForAction(
4039 C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004040 CachedResults, A->getOffloadingDeviceKind()));
Daniel Dunbare75d8342009-03-16 06:56:51 +00004041 }
4042
Daniel Dunbare75d8342009-03-16 06:56:51 +00004043 // Always use the first input as the base input.
4044 const char *BaseInput = InputInfos[0].getBaseInput();
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004045
Daniel Dunbar6beaf512010-06-04 18:28:41 +00004046 // ... except dsymutil actions, which use their actual input as the base
4047 // input.
4048 if (JA->getType() == types::TY_dSYM)
4049 BaseInput = InputInfos[0].getFilename();
4050
Richard Smithcd35eff2018-09-15 01:21:16 +00004051 // ... and in header module compilations, which use the module name.
4052 if (auto *ModuleJA = dyn_cast<HeaderModulePrecompileJobAction>(JA))
4053 BaseInput = ModuleJA->getModuleName();
4054
Samuel Antaod06239d2016-07-15 23:13:27 +00004055 // Append outputs of offload device jobs to the input list
4056 if (!OffloadDependencesInputInfo.empty())
4057 InputInfos.append(OffloadDependencesInputInfo.begin(),
4058 OffloadDependencesInputInfo.end());
Artem Belevich0ff05cd2015-07-13 23:27:56 +00004059
Vedant Kumar18286cf2016-07-27 23:02:20 +00004060 // Set the effective triple of the toolchain for the duration of this job.
4061 llvm::Triple EffectiveTriple;
4062 const ToolChain &ToolTC = T->getToolChain();
Samuel Antao31fef982016-10-27 17:39:44 +00004063 const ArgList &Args =
4064 C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind());
Vedant Kumar18286cf2016-07-27 23:02:20 +00004065 if (InputInfos.size() != 1) {
4066 EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args));
4067 } else {
4068 // Pass along the input type if it can be unambiguously determined.
4069 EffectiveTriple = llvm::Triple(
4070 ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType()));
4071 }
4072 RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple);
4073
Daniel Dunbard00272f2010-08-02 02:38:15 +00004074 // Determine the place to write output to, if any.
Justin Lebar9eaa4892016-01-11 23:09:32 +00004075 InputInfo Result;
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004076 InputInfoList UnbundlingResults;
4077 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) {
4078 // If we have an unbundling job, we need to create results for all the
4079 // outputs. We also update the results cache so that other actions using
4080 // this unbundling action can get the right results.
4081 for (auto &UI : UA->getDependentActionsInfo()) {
4082 assert(UI.DependentOffloadKind != Action::OFK_None &&
4083 "Unbundling with no offloading??");
4084
4085 // Unbundling actions are never at the top level. When we generate the
4086 // offloading prefix, we also do that for the host file because the
4087 // unbundling action does not change the type of the output which can
4088 // cause a overwrite.
4089 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
4090 UI.DependentOffloadKind,
4091 UI.DependentToolChain->getTriple().normalize(),
4092 /*CreatePrefixForHost=*/true);
4093 auto CurI = InputInfo(
Yaxun Liu609f7522018-05-11 19:02:18 +00004094 UA,
4095 GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch,
4096 /*AtTopLevel=*/false,
4097 MultipleArchs ||
4098 UI.DependentOffloadKind == Action::OFK_HIP,
4099 OffloadingPrefix),
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004100 BaseInput);
4101 // Save the unbundling result.
4102 UnbundlingResults.push_back(CurI);
4103
4104 // Get the unique string identifier for this dependence and cache the
4105 // result.
Yaxun Liu470b8332018-06-06 19:44:10 +00004106 StringRef Arch;
4107 if (TargetDeviceOffloadKind == Action::OFK_HIP) {
4108 if (UI.DependentOffloadKind == Action::OFK_Host)
Yaxun Liuf37b50a2018-07-24 01:03:44 +00004109 Arch = StringRef();
Yaxun Liu470b8332018-06-06 19:44:10 +00004110 else
4111 Arch = UI.DependentBoundArch;
4112 } else
4113 Arch = BoundArch;
4114
4115 CachedResults[{A, GetTriplePlusArchString(UI.DependentToolChain, Arch,
4116 UI.DependentOffloadKind)}] =
4117 CurI;
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004118 }
4119
4120 // Now that we have all the results generated, select the one that should be
4121 // returned for the current depending action.
4122 std::pair<const Action *, std::string> ActionTC = {
4123 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
4124 assert(CachedResults.find(ActionTC) != CachedResults.end() &&
4125 "Result does not exist??");
4126 Result = CachedResults[ActionTC];
4127 } else if (JA->getType() == types::TY_Nothing)
Justin Lebard98cea82016-01-11 23:15:21 +00004128 Result = InputInfo(A, BaseInput);
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004129 else {
4130 // We only have to generate a prefix for the host if this is not a top-level
4131 // action.
4132 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
4133 A->getOffloadingDeviceKind(), TC->getTriple().normalize(),
4134 /*CreatePrefixForHost=*/!!A->getOffloadingHostActiveKinds() &&
4135 !AtTopLevel);
Justin Lebard98cea82016-01-11 23:15:21 +00004136 Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
Samuel Antaod06239d2016-07-15 23:13:27 +00004137 AtTopLevel, MultipleArchs,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004138 OffloadingPrefix),
Justin Lebard98cea82016-01-11 23:15:21 +00004139 BaseInput);
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004140 }
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004141
Chad Rosierbe10f982011-08-02 17:58:04 +00004142 if (CCCPrintBindings && !CCGenDiagnostics) {
Rafael Espindola79764462013-03-24 15:06:53 +00004143 llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
4144 << " - \"" << T->getName() << "\", inputs: [";
Daniel Dunbarb39cc522009-03-17 22:47:06 +00004145 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
4146 llvm::errs() << InputInfos[i].getAsString();
4147 if (i + 1 != e)
4148 llvm::errs() << ", ";
4149 }
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004150 if (UnbundlingResults.empty())
4151 llvm::errs() << "], output: " << Result.getAsString() << "\n";
4152 else {
4153 llvm::errs() << "], outputs: [";
4154 for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) {
4155 llvm::errs() << UnbundlingResults[i].getAsString();
4156 if (i + 1 != e)
4157 llvm::errs() << ", ";
4158 }
4159 llvm::errs() << "] \n";
4160 }
Daniel Dunbarb39cc522009-03-17 22:47:06 +00004161 } else {
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004162 if (UnbundlingResults.empty())
4163 T->ConstructJob(
4164 C, *JA, Result, InputInfos,
4165 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
4166 LinkingOutput);
4167 else
Samuel Antao7108bf32016-11-03 15:41:50 +00004168 T->ConstructJobMultipleOutputs(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004169 C, *JA, UnbundlingResults, InputInfos,
4170 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
4171 LinkingOutput);
Daniel Dunbarb39cc522009-03-17 22:47:06 +00004172 }
Justin Lebar9eaa4892016-01-11 23:09:32 +00004173 return Result;
Daniel Dunbare75d8342009-03-16 06:56:51 +00004174}
4175
Hans Wennborga7707222015-01-09 17:38:53 +00004176const char *Driver::getDefaultImageName() const {
Petr Hosekdd38d932018-05-29 22:35:39 +00004177 llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
Hans Wennborga7707222015-01-09 17:38:53 +00004178 return Target.isOSWindows() ? "a.exe" : "a.out";
4179}
4180
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004181/// Create output filename based on ArgValue, which could either be a
Hans Wennborg2c21f742013-10-17 16:16:23 +00004182/// full filename, filename without extension, or a directory. If ArgValue
4183/// does not provide a filename, then use BaseName, and use the extension
4184/// suitable for FileType.
Hans Wennborg207fcf02013-08-12 21:56:42 +00004185static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004186 StringRef BaseName,
4187 types::ID FileType) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00004188 SmallString<128> Filename = ArgValue;
Justin Bogner5aaf2e72014-06-26 20:59:36 +00004189
Hans Wennborgf1a74252013-09-10 20:18:04 +00004190 if (ArgValue.empty()) {
4191 // If the argument is empty, output to BaseName in the current dir.
4192 Filename = BaseName;
4193 } else if (llvm::sys::path::is_separator(Filename.back())) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00004194 // If the argument is a directory, output to BaseName in that dir.
4195 llvm::sys::path::append(Filename, BaseName);
4196 }
4197
4198 if (!llvm::sys::path::has_extension(ArgValue)) {
4199 // If the argument didn't provide an extension, then set it.
4200 const char *Extension = types::getTypeTempSuffix(FileType, true);
Hans Wennborgf1a74252013-09-10 20:18:04 +00004201
4202 if (FileType == types::TY_Image &&
4203 Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
4204 // The output file is a dll.
4205 Extension = "dll";
4206 }
4207
Hans Wennborg207fcf02013-08-12 21:56:42 +00004208 llvm::sys::path::replace_extension(Filename, Extension);
4209 }
4210
4211 return Args.MakeArgString(Filename.c_str());
4212}
4213
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004214const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004215 const char *BaseInput,
Mehdi Aminic50b1a22016-10-07 21:27:26 +00004216 StringRef BoundArch, bool AtTopLevel,
Samuel Antaod06239d2016-07-15 23:13:27 +00004217 bool MultipleArchs,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004218 StringRef OffloadingPrefix) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00004219 llvm::PrettyStackTraceString CrashInfo("Computing output path");
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004220 // Output to a user requested destination?
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004221 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004222 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
Chad Rosier633dcdc2013-01-24 19:14:47 +00004223 return C.addResultFile(FinalOutput->getValue(), &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004224 }
4225
Hans Wennborge0053472013-12-20 18:40:46 +00004226 // For /P, preprocess to file named after BaseInput.
4227 if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
4228 assert(AtTopLevel && isa<PreprocessJobAction>(JA));
4229 StringRef BaseName = llvm::sys::path::filename(BaseInput);
Hans Wennborg04c764f2014-06-17 00:19:12 +00004230 StringRef NameArg;
Greg Bedwell065f70a2015-06-09 10:24:06 +00004231 if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
Hans Wennborg04c764f2014-06-17 00:19:12 +00004232 NameArg = A->getValue();
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004233 return C.addResultFile(
4234 MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
4235 &JA);
Hans Wennborge0053472013-12-20 18:40:46 +00004236 }
4237
Nick Lewycky6e1ce292010-09-24 00:46:53 +00004238 // Default to writing to stdout?
David Blaikiebc023c92018-06-14 23:09:06 +00004239 if (AtTopLevel && !CCGenDiagnostics && isa<PreprocessJobAction>(JA))
Nick Lewycky6e1ce292010-09-24 00:46:53 +00004240 return "-";
4241
Hans Wennborg2c21f742013-10-17 16:16:23 +00004242 // Is this the assembly listing for /FA?
4243 if (JA.getType() == types::TY_PP_Asm &&
4244 (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
4245 C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
4246 // Use /Fa and the input filename to determine the asm file name.
4247 StringRef BaseName = llvm::sys::path::filename(BaseInput);
4248 StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004249 return C.addResultFile(
4250 MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
4251 &JA);
Hans Wennborg2c21f742013-10-17 16:16:23 +00004252 }
4253
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004254 // Output to a temporary file?
Reid Kleckner68eb60b2015-02-02 22:41:48 +00004255 if ((!AtTopLevel && !isSaveTempsEnabled() &&
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004256 !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
Chad Rosierbe10f982011-08-02 17:58:04 +00004257 CCGenDiagnostics) {
Chad Rosier97c37372011-08-26 22:27:02 +00004258 StringRef Name = llvm::sys::path::filename(BaseInput);
4259 std::pair<StringRef, StringRef> Split = Name.split('.');
Bob Haarman7e4d3ff2018-07-09 21:07:20 +00004260 SmallString<128> TmpName;
4261 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
4262 Arg *A = C.getArgs().getLastArg(options::OPT_fcrash_diagnostics_dir);
4263 if (CCGenDiagnostics && A) {
4264 SmallString<128> CrashDirectory(A->getValue());
4265 llvm::sys::path::append(CrashDirectory, Split.first);
4266 const char *Middle = Suffix ? "-%%%%%%." : "-%%%%%%";
Simon Atanasyan27c0f202019-04-02 18:03:15 +00004267 std::error_code EC = llvm::sys::fs::createUniqueFile(
4268 CrashDirectory + Middle + Suffix, TmpName);
Bob Haarman7e4d3ff2018-07-09 21:07:20 +00004269 if (EC) {
4270 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
4271 return "";
4272 }
4273 } else {
4274 TmpName = GetTemporaryPath(Split.first, Suffix);
4275 }
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00004276 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004277 }
4278
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004279 SmallString<128> BasePath(BaseInput);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004280 StringRef BaseName;
Daniel Dunbar67fea712011-03-25 18:16:51 +00004281
4282 // Dsymutil actions should use the full path.
Eric Christopher551ef452011-08-23 17:56:55 +00004283 if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
Daniel Dunbar67fea712011-03-25 18:16:51 +00004284 BaseName = BasePath;
4285 else
4286 BaseName = llvm::sys::path::filename(BasePath);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004287
4288 // Determine what the derived output name should be.
4289 const char *NamedOutput;
Hans Wennborg2b89a262013-08-06 22:11:28 +00004290
Hans Wennborg625fba82016-10-04 21:01:04 +00004291 if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) &&
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00004292 C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
4293 // The /Fo or /o flag decides the object filename.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004294 StringRef Val =
4295 C.getArgs()
4296 .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
4297 ->getValue();
4298 NamedOutput =
4299 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
Hans Wennborg207fcf02013-08-12 21:56:42 +00004300 } else if (JA.getType() == types::TY_Image &&
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004301 C.getArgs().hasArg(options::OPT__SLASH_Fe,
4302 options::OPT__SLASH_o)) {
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00004303 // The /Fe or /o flag names the linked file.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004304 StringRef Val =
4305 C.getArgs()
4306 .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
4307 ->getValue();
4308 NamedOutput =
4309 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
Hans Wennborgf1a74252013-09-10 20:18:04 +00004310 } else if (JA.getType() == types::TY_Image) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00004311 if (IsCLMode()) {
4312 // clang-cl uses BaseName for the executable name.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004313 NamedOutput =
4314 MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
Samuel Antao59efaed2016-10-27 17:31:22 +00004315 } else {
Hans Wennborga7707222015-01-09 17:38:53 +00004316 SmallString<128> Output(getDefaultImageName());
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004317 Output += OffloadingPrefix;
Samuel Antao59efaed2016-10-27 17:31:22 +00004318 if (MultipleArchs && !BoundArch.empty()) {
4319 Output += "-";
4320 Output.append(BoundArch);
4321 }
Chad Rosier35767232013-04-30 22:01:21 +00004322 NamedOutput = C.getArgs().MakeArgString(Output.c_str());
Nico Weber2ca4be92016-03-01 23:16:44 +00004323 }
4324 } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00004325 NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName));
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004326 } else {
Hans Wennborg0a096a02013-09-05 17:05:56 +00004327 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004328 assert(Suffix && "All types used for output should have a suffix.");
4329
4330 std::string::size_type End = std::string::npos;
4331 if (!types::appendSuffixForType(JA.getType()))
4332 End = BaseName.rfind('.');
Chad Rosier35767232013-04-30 22:01:21 +00004333 SmallString<128> Suffixed(BaseName.substr(0, End));
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004334 Suffixed += OffloadingPrefix;
Mehdi Aminic50b1a22016-10-07 21:27:26 +00004335 if (MultipleArchs && !BoundArch.empty()) {
Chad Rosier35767232013-04-30 22:01:21 +00004336 Suffixed += "-";
4337 Suffixed.append(BoundArch);
4338 }
Bob Wilson23a55f12014-12-21 07:00:00 +00004339 // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
4340 // the unoptimized bitcode so that it does not get overwritten by the ".bc"
4341 // optimized bitcode output.
4342 if (!AtTopLevel && C.getArgs().hasArg(options::OPT_emit_llvm) &&
4343 JA.getType() == types::TY_LLVM_BC)
4344 Suffixed += ".tmp";
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004345 Suffixed += '.';
4346 Suffixed += Suffix;
4347 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
4348 }
4349
Reid Kleckner68eb60b2015-02-02 22:41:48 +00004350 // Prepend object file path if -save-temps=obj
4351 if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
4352 JA.getType() != types::TY_PCH) {
4353 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
4354 SmallString<128> TempPath(FinalOutput->getValue());
4355 llvm::sys::path::remove_filename(TempPath);
4356 StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
4357 llvm::sys::path::append(TempPath, OutputFileName);
4358 NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
4359 }
4360
Chad Rosier62135492012-07-09 17:31:28 +00004361 // If we're saving temps and the temp file conflicts with the input file,
Chad Rosier5b58af02012-04-20 20:05:08 +00004362 // then avoid overwriting input file.
Reid Kleckner68eb60b2015-02-02 22:41:48 +00004363 if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
Chad Rosier5b58af02012-04-20 20:05:08 +00004364 bool SameFile = false;
4365 SmallString<256> Result;
4366 llvm::sys::fs::current_path(Result);
4367 llvm::sys::path::append(Result, BaseName);
4368 llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
4369 // Must share the same path to conflict.
4370 if (SameFile) {
4371 StringRef Name = llvm::sys::path::filename(BaseInput);
4372 std::pair<StringRef, StringRef> Split = Name.split('.');
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004373 std::string TmpName = GetTemporaryPath(
4374 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00004375 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
Chad Rosier5b58af02012-04-20 20:05:08 +00004376 }
Chad Rosierf8412cd2011-07-15 21:54:29 +00004377 }
4378
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00004379 // As an annoying special case, PCH generation doesn't strip the pathname.
Nico Weber8ab92192016-03-02 23:29:29 +00004380 if (JA.getType() == types::TY_PCH && !IsCLMode()) {
Michael J. Spencere1696752010-12-18 00:19:12 +00004381 llvm::sys::path::remove_filename(BasePath);
4382 if (BasePath.empty())
Daniel Dunbare6c83192009-03-18 09:58:30 +00004383 BasePath = NamedOutput;
4384 else
Michael J. Spencere1696752010-12-18 00:19:12 +00004385 llvm::sys::path::append(BasePath, NamedOutput);
Chad Rosier633dcdc2013-01-24 19:14:47 +00004386 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004387 } else {
Chad Rosier633dcdc2013-01-24 19:14:47 +00004388 return C.addResultFile(NamedOutput, &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004389 }
4390}
4391
Mehdi Amini12011172016-10-06 05:11:48 +00004392std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const {
Raphael Isemannb23ccec2018-12-10 12:37:46 +00004393 // Search for Name in a list of paths.
Petr Hosek8f2499f2018-09-12 03:26:10 +00004394 auto SearchPaths = [&](const llvm::SmallVectorImpl<std::string> &P)
4395 -> llvm::Optional<std::string> {
4396 // Respect a limited subset of the '-Bprefix' functionality in GCC by
4397 // attempting to use this prefix when looking for file paths.
4398 for (const auto &Dir : P) {
4399 if (Dir.empty())
4400 continue;
4401 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
4402 llvm::sys::path::append(P, Name);
4403 if (llvm::sys::fs::exists(Twine(P)))
Simon Pilgrim4588fc82018-09-13 10:10:18 +00004404 return P.str().str();
Petr Hosek8f2499f2018-09-12 03:26:10 +00004405 }
4406 return None;
4407 };
4408
4409 if (auto P = SearchPaths(PrefixDirs))
4410 return *P;
Chandler Carruth84559242010-03-22 01:52:07 +00004411
Petr Hosek916a4672017-08-10 04:16:38 +00004412 SmallString<128> R(ResourceDir);
4413 llvm::sys::path::append(R, Name);
4414 if (llvm::sys::fs::exists(Twine(R)))
4415 return R.str();
4416
4417 SmallString<128> P(TC.getCompilerRTPath());
Rafael Espindola609a6642013-06-24 18:33:43 +00004418 llvm::sys::path::append(P, Name);
4419 if (llvm::sys::fs::exists(Twine(P)))
Peter Collingbournefa9771f2011-09-06 02:08:31 +00004420 return P.str();
4421
Petr Hosek8f2499f2018-09-12 03:26:10 +00004422 if (auto P = SearchPaths(TC.getLibraryPaths()))
4423 return *P;
4424
4425 if (auto P = SearchPaths(TC.getFilePaths()))
4426 return *P;
Daniel Dunbar68b01a02009-03-18 20:26:19 +00004427
Daniel Dunbar1ce81532009-09-09 22:33:00 +00004428 return Name;
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00004429}
4430
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004431void Driver::generatePrefixedToolNames(
Mehdi Amini12011172016-10-06 05:11:48 +00004432 StringRef Tool, const ToolChain &TC,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004433 SmallVectorImpl<std::string> &Names) const {
Petr Hosekdd38d932018-05-29 22:35:39 +00004434 // FIXME: Needs a better variable than TargetTriple
4435 Names.emplace_back((TargetTriple + "-" + Tool).str());
Benjamin Kramer3204b152015-05-29 19:42:19 +00004436 Names.emplace_back(Tool);
Vasileios Kalintirisc744e122015-11-12 15:26:54 +00004437
4438 // Allow the discovery of tools prefixed with LLVM's default target triple.
Petr Hosekdd38d932018-05-29 22:35:39 +00004439 std::string DefaultTargetTriple = llvm::sys::getDefaultTargetTriple();
4440 if (DefaultTargetTriple != TargetTriple)
4441 Names.emplace_back((DefaultTargetTriple + "-" + Tool).str());
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004442}
4443
Benjamin Kramer7111b912014-11-04 20:26:01 +00004444static bool ScanDirForExecutable(SmallString<128> &Dir,
4445 ArrayRef<std::string> Names) {
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004446 for (const auto &Name : Names) {
4447 llvm::sys::path::append(Dir, Name);
4448 if (llvm::sys::fs::can_execute(Twine(Dir)))
4449 return true;
4450 llvm::sys::path::remove_filename(Dir);
4451 }
4452 return false;
4453}
4454
Mehdi Amini12011172016-10-06 05:11:48 +00004455std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const {
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004456 SmallVector<std::string, 2> TargetSpecificExecutables;
4457 generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
4458
Chandler Carruth84559242010-03-22 01:52:07 +00004459 // Respect a limited subset of the '-Bprefix' functionality in GCC by
Logan Chiencd679fd2012-10-04 08:08:56 +00004460 // attempting to use this prefix when looking for program paths.
Saleem Abdulrasool23d99b12014-09-16 03:48:32 +00004461 for (const auto &PrefixDir : PrefixDirs) {
4462 if (llvm::sys::fs::is_directory(PrefixDir)) {
4463 SmallString<128> P(PrefixDir);
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004464 if (ScanDirForExecutable(P, TargetSpecificExecutables))
Rafael Espindola8be5c052013-06-19 13:24:29 +00004465 return P.str();
Simon Atanasyana47ba292012-10-31 14:39:28 +00004466 } else {
Mehdi Amini12011172016-10-06 05:11:48 +00004467 SmallString<128> P((PrefixDir + Name).str());
Rafael Espindola609a6642013-06-24 18:33:43 +00004468 if (llvm::sys::fs::can_execute(Twine(P)))
Rafael Espindola8be5c052013-06-19 13:24:29 +00004469 return P.str();
Simon Atanasyan86bdab72012-10-31 12:01:53 +00004470 }
Chandler Carruth84559242010-03-22 01:52:07 +00004471 }
4472
Daniel Dunbar68b01a02009-03-18 20:26:19 +00004473 const ToolChain::path_list &List = TC.getProgramPaths();
Saleem Abdulrasool23d99b12014-09-16 03:48:32 +00004474 for (const auto &Path : List) {
4475 SmallString<128> P(Path);
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004476 if (ScanDirForExecutable(P, TargetSpecificExecutables))
Rafael Espindola8be5c052013-06-19 13:24:29 +00004477 return P.str();
Daniel Dunbar68b01a02009-03-18 20:26:19 +00004478 }
4479
Daniel Dunbar76ce7412009-03-23 16:15:50 +00004480 // If all else failed, search the path.
Michael J. Spencerb011d482014-11-07 21:30:32 +00004481 for (const auto &TargetSpecificExecutable : TargetSpecificExecutables)
4482 if (llvm::ErrorOr<std::string> P =
4483 llvm::sys::findProgramByName(TargetSpecificExecutable))
Michael J. Spencer04162ea2014-11-04 01:30:55 +00004484 return *P;
Daniel Dunbar6f668772009-03-18 21:34:08 +00004485
Daniel Dunbar1ce81532009-09-09 22:33:00 +00004486 return Name;
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00004487}
4488
Mehdi Amini12011172016-10-06 05:11:48 +00004489std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const {
Rafael Espindola37d229d2013-06-25 04:26:55 +00004490 SmallString<128> Path;
Rafael Espindolac0809172014-06-12 14:02:15 +00004491 std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
Rafael Espindola37d229d2013-06-25 04:26:55 +00004492 if (EC) {
4493 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
Daniel Dunbare627c1c2009-03-18 19:34:39 +00004494 return "";
4495 }
4496
Rafael Espindola37d229d2013-06-25 04:26:55 +00004497 return Path.str();
Daniel Dunbare627c1c2009-03-18 19:34:39 +00004498}
4499
Steven Wuc3399db62019-01-11 21:16:04 +00004500std::string Driver::GetTemporaryDirectory(StringRef Prefix) const {
4501 SmallString<128> Path;
4502 std::error_code EC = llvm::sys::fs::createUniqueDirectory(Prefix, Path);
4503 if (EC) {
4504 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
4505 return "";
4506 }
4507
4508 return Path.str();
4509}
4510
Nico Weber2ca4be92016-03-01 23:16:44 +00004511std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
4512 SmallString<128> Output;
4513 if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
4514 // FIXME: If anybody needs it, implement this obscure rule:
4515 // "If you specify a directory without a file name, the default file name
4516 // is VCx0.pch., where x is the major version of Visual C++ in use."
4517 Output = FpArg->getValue();
4518
4519 // "If you do not specify an extension as part of the path name, an
4520 // extension of .pch is assumed. "
4521 if (!llvm::sys::path::has_extension(Output))
4522 Output += ".pch";
4523 } else {
Mike Rice58df1af2018-09-11 17:10:44 +00004524 if (Arg *YcArg = C.getArgs().getLastArg(options::OPT__SLASH_Yc))
4525 Output = YcArg->getValue();
4526 if (Output.empty())
4527 Output = BaseName;
Nico Weber2ca4be92016-03-01 23:16:44 +00004528 llvm::sys::path::replace_extension(Output, ".pch");
4529 }
4530 return Output.str();
4531}
4532
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004533const ToolChain &Driver::getToolChain(const ArgList &Args,
Artem Belevich959e0542015-07-10 19:47:55 +00004534 const llvm::Triple &Target) const {
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004535
David Blaikie6ad71012017-01-13 18:53:43 +00004536 auto &TC = ToolChains[Target.str()];
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004537 if (!TC) {
4538 switch (Target.getOS()) {
Reid Kleckner330fb172016-05-11 16:19:05 +00004539 case llvm::Triple::Haiku:
David Blaikie6ad71012017-01-13 18:53:43 +00004540 TC = llvm::make_unique<toolchains::Haiku>(*this, Target, Args);
Reid Kleckner330fb172016-05-11 16:19:05 +00004541 break;
Ed Schouten4dabea22017-06-25 08:29:09 +00004542 case llvm::Triple::Ananas:
4543 TC = llvm::make_unique<toolchains::Ananas>(*this, Target, Args);
4544 break;
Ed Schouten3c3e58c2015-03-26 11:13:44 +00004545 case llvm::Triple::CloudABI:
David Blaikie6ad71012017-01-13 18:53:43 +00004546 TC = llvm::make_unique<toolchains::CloudABI>(*this, Target, Args);
Ed Schouten3c3e58c2015-03-26 11:13:44 +00004547 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004548 case llvm::Triple::Darwin:
4549 case llvm::Triple::MacOSX:
4550 case llvm::Triple::IOS:
Tim Northover6f3ff222015-10-30 16:30:27 +00004551 case llvm::Triple::TvOS:
4552 case llvm::Triple::WatchOS:
David Blaikie6ad71012017-01-13 18:53:43 +00004553 TC = llvm::make_unique<toolchains::DarwinClang>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004554 break;
4555 case llvm::Triple::DragonFly:
David Blaikie6ad71012017-01-13 18:53:43 +00004556 TC = llvm::make_unique<toolchains::DragonFly>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004557 break;
4558 case llvm::Triple::OpenBSD:
David Blaikie6ad71012017-01-13 18:53:43 +00004559 TC = llvm::make_unique<toolchains::OpenBSD>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004560 break;
4561 case llvm::Triple::NetBSD:
David Blaikie6ad71012017-01-13 18:53:43 +00004562 TC = llvm::make_unique<toolchains::NetBSD>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004563 break;
4564 case llvm::Triple::FreeBSD:
David Blaikie6ad71012017-01-13 18:53:43 +00004565 TC = llvm::make_unique<toolchains::FreeBSD>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004566 break;
4567 case llvm::Triple::Minix:
David Blaikie6ad71012017-01-13 18:53:43 +00004568 TC = llvm::make_unique<toolchains::Minix>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004569 break;
4570 case llvm::Triple::Linux:
Andrey Turetskiy4798eb62016-06-16 10:36:09 +00004571 case llvm::Triple::ELFIAMCU:
Chandler Carruthcf705b22012-01-25 21:03:58 +00004572 if (Target.getArch() == llvm::Triple::hexagon)
David Blaikie6ad71012017-01-13 18:53:43 +00004573 TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
4574 Args);
Vasileios Kalintirisc744e122015-11-12 15:26:54 +00004575 else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
4576 !Target.hasEnvironment())
David Blaikie6ad71012017-01-13 18:53:43 +00004577 TC = llvm::make_unique<toolchains::MipsLLVMToolChain>(*this, Target,
4578 Args);
Chandler Carruthcf705b22012-01-25 21:03:58 +00004579 else
David Blaikie6ad71012017-01-13 18:53:43 +00004580 TC = llvm::make_unique<toolchains::Linux>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004581 break;
Derek Schuff6ab52fa2015-03-30 20:31:33 +00004582 case llvm::Triple::NaCl:
David Blaikie6ad71012017-01-13 18:53:43 +00004583 TC = llvm::make_unique<toolchains::NaClToolChain>(*this, Target, Args);
Derek Schuff6ab52fa2015-03-30 20:31:33 +00004584 break;
Petr Hosek62e1d232016-10-06 06:08:09 +00004585 case llvm::Triple::Fuchsia:
David Blaikie6ad71012017-01-13 18:53:43 +00004586 TC = llvm::make_unique<toolchains::Fuchsia>(*this, Target, Args);
Petr Hosek62e1d232016-10-06 06:08:09 +00004587 break;
David Chisnallf571cde2012-02-15 13:39:01 +00004588 case llvm::Triple::Solaris:
David Blaikie6ad71012017-01-13 18:53:43 +00004589 TC = llvm::make_unique<toolchains::Solaris>(*this, Target, Args);
David Chisnallf571cde2012-02-15 13:39:01 +00004590 break;
Tom Stellard8fa33092015-07-18 01:49:05 +00004591 case llvm::Triple::AMDHSA:
David Blaikie6ad71012017-01-13 18:53:43 +00004592 TC = llvm::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args);
Tom Stellard8fa33092015-07-18 01:49:05 +00004593 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004594 case llvm::Triple::Win32:
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004595 switch (Target.getEnvironment()) {
4596 default:
4597 if (Target.isOSBinFormatELF())
David Blaikie6ad71012017-01-13 18:53:43 +00004598 TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004599 else if (Target.isOSBinFormatMachO())
David Blaikie6ad71012017-01-13 18:53:43 +00004600 TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004601 else
David Blaikie6ad71012017-01-13 18:53:43 +00004602 TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004603 break;
4604 case llvm::Triple::GNU:
David Blaikie6ad71012017-01-13 18:53:43 +00004605 TC = llvm::make_unique<toolchains::MinGW>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004606 break;
Saleem Abdulrasool543a78b2014-10-24 03:13:37 +00004607 case llvm::Triple::Itanium:
David Blaikie6ad71012017-01-13 18:53:43 +00004608 TC = llvm::make_unique<toolchains::CrossWindowsToolChain>(*this, Target,
4609 Args);
Saleem Abdulrasool543a78b2014-10-24 03:13:37 +00004610 break;
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004611 case llvm::Triple::MSVC:
4612 case llvm::Triple::UnknownEnvironment:
Dave Leef96bedf2017-11-06 21:18:05 +00004613 if (Args.getLastArgValue(options::OPT_fuse_ld_EQ)
4614 .startswith_lower("bfd"))
4615 TC = llvm::make_unique<toolchains::CrossWindowsToolChain>(
4616 *this, Target, Args);
4617 else
4618 TC =
4619 llvm::make_unique<toolchains::MSVCToolChain>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004620 break;
4621 }
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004622 break;
Filipe Cabecinhasc888e192015-10-14 12:25:43 +00004623 case llvm::Triple::PS4:
David Blaikie6ad71012017-01-13 18:53:43 +00004624 TC = llvm::make_unique<toolchains::PS4CPU>(*this, Target, Args);
Filipe Cabecinhasc888e192015-10-14 12:25:43 +00004625 break;
David L Kreitzerd397ea42016-10-14 20:44:33 +00004626 case llvm::Triple::Contiki:
David Blaikie6ad71012017-01-13 18:53:43 +00004627 TC = llvm::make_unique<toolchains::Contiki>(*this, Target, Args);
David L Kreitzerd397ea42016-10-14 20:44:33 +00004628 break;
Kristina Brooks77a4adc2018-11-29 03:49:14 +00004629 case llvm::Triple::Hurd:
4630 TC = llvm::make_unique<toolchains::Hurd>(*this, Target, Args);
4631 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004632 default:
Douglas Katzman9f5e70e2015-05-26 18:01:33 +00004633 // Of these targets, Hexagon is the only one that might have
4634 // an OS of Linux, in which case it got handled above already.
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004635 switch (Target.getArch()) {
4636 case llvm::Triple::tce:
David Blaikie6ad71012017-01-13 18:53:43 +00004637 TC = llvm::make_unique<toolchains::TCEToolChain>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004638 break;
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00004639 case llvm::Triple::tcele:
David Blaikie6ad71012017-01-13 18:53:43 +00004640 TC = llvm::make_unique<toolchains::TCELEToolChain>(*this, Target, Args);
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00004641 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004642 case llvm::Triple::hexagon:
David Blaikie6ad71012017-01-13 18:53:43 +00004643 TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
4644 Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004645 break;
Jacques Pienaard964cc22016-03-28 21:02:54 +00004646 case llvm::Triple::lanai:
David Blaikie6ad71012017-01-13 18:53:43 +00004647 TC = llvm::make_unique<toolchains::LanaiToolChain>(*this, Target, Args);
Jacques Pienaard964cc22016-03-28 21:02:54 +00004648 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004649 case llvm::Triple::xcore:
David Blaikie6ad71012017-01-13 18:53:43 +00004650 TC = llvm::make_unique<toolchains::XCoreToolChain>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004651 break;
Dan Gohmanc2853072015-09-03 22:51:53 +00004652 case llvm::Triple::wasm32:
4653 case llvm::Triple::wasm64:
David Blaikie6ad71012017-01-13 18:53:43 +00004654 TC = llvm::make_unique<toolchains::WebAssembly>(*this, Target, Args);
Dan Gohmanc2853072015-09-03 22:51:53 +00004655 break;
Dylan McKay924fa3a2017-01-05 05:20:27 +00004656 case llvm::Triple::avr:
David Blaikie6ad71012017-01-13 18:53:43 +00004657 TC = llvm::make_unique<toolchains::AVRToolChain>(*this, Target, Args);
Dylan McKay924fa3a2017-01-05 05:20:27 +00004658 break;
Anton Korobeynikov93165d62019-01-15 19:44:05 +00004659 case llvm::Triple::msp430:
4660 TC =
4661 llvm::make_unique<toolchains::MSP430ToolChain>(*this, Target, Args);
4662 break;
David Bolvanskyf4be2532018-07-31 14:21:46 +00004663 case llvm::Triple::riscv32:
4664 case llvm::Triple::riscv64:
4665 TC = llvm::make_unique<toolchains::RISCVToolChain>(*this, Target, Args);
4666 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004667 default:
Douglas Katzmand6e597c2015-09-17 19:56:40 +00004668 if (Target.getVendor() == llvm::Triple::Myriad)
David Blaikie6ad71012017-01-13 18:53:43 +00004669 TC = llvm::make_unique<toolchains::MyriadToolChain>(*this, Target,
4670 Args);
Jonathan Roelofs901c7762017-05-25 15:42:13 +00004671 else if (toolchains::BareMetal::handlesTarget(Target))
4672 TC = llvm::make_unique<toolchains::BareMetal>(*this, Target, Args);
Douglas Katzmand6e597c2015-09-17 19:56:40 +00004673 else if (Target.isOSBinFormatELF())
David Blaikie6ad71012017-01-13 18:53:43 +00004674 TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004675 else if (Target.isOSBinFormatMachO())
David Blaikie6ad71012017-01-13 18:53:43 +00004676 TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004677 else
David Blaikie6ad71012017-01-13 18:53:43 +00004678 TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004679 }
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004680 }
4681 }
Justin Lebar66c4fd72016-11-18 00:41:22 +00004682
4683 // Intentionally omitted from the switch above: llvm::Triple::CUDA. CUDA
4684 // compiles always need two toolchains, the CUDA toolchain and the host
4685 // toolchain. So the only valid way to create a CUDA toolchain is via
4686 // CreateOffloadingDeviceToolChains.
4687
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004688 return *TC;
Daniel Dunbar4dff6a42009-03-10 23:41:59 +00004689}
Daniel Dunbar8fa879d2009-03-24 18:57:02 +00004690
Rafael Espindola2f69d402013-03-18 15:33:26 +00004691bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
Douglas Katzman00249092015-06-12 15:45:21 +00004692 // Say "no" if there is not exactly one input of a type clang understands.
Nico Weber5a459f82016-02-23 19:30:43 +00004693 if (JA.size() != 1 ||
4694 !types::isAcceptedByClang((*JA.input_begin())->getType()))
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00004695 return false;
4696
Douglas Katzman00249092015-06-12 15:45:21 +00004697 // And say "no" if this is not a kind of action clang understands.
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00004698 if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
Bob Wilson23a55f12014-12-21 07:00:00 +00004699 !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00004700 return false;
4701
4702 return true;
4703}
4704
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00004705/// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
4706/// grouped values as integers. Numbers which are not provided are set to 0.
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004707///
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00004708/// \return True if the entire string was parsed (9.2), or all groups were
4709/// parsed (10.3.5extrastuff).
Mehdi Amini12011172016-10-06 05:11:48 +00004710bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
4711 unsigned &Micro, bool &HadExtra) {
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004712 HadExtra = false;
4713
4714 Major = Minor = Micro = 0;
Mehdi Amini12011172016-10-06 05:11:48 +00004715 if (Str.empty())
Bob Wilson433cb312015-04-07 01:03:35 +00004716 return false;
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004717
Mehdi Amini12011172016-10-06 05:11:48 +00004718 if (Str.consumeInteger(10, Major))
4719 return false;
4720 if (Str.empty())
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004721 return true;
Mehdi Amini12011172016-10-06 05:11:48 +00004722 if (Str[0] != '.')
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004723 return false;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00004724
Mehdi Amini12011172016-10-06 05:11:48 +00004725 Str = Str.drop_front(1);
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004726
Mehdi Amini12011172016-10-06 05:11:48 +00004727 if (Str.consumeInteger(10, Minor))
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004728 return false;
Mehdi Amini12011172016-10-06 05:11:48 +00004729 if (Str.empty())
4730 return true;
4731 if (Str[0] != '.')
4732 return false;
4733 Str = Str.drop_front(1);
4734
4735 if (Str.consumeInteger(10, Micro))
4736 return false;
4737 if (!Str.empty())
4738 HadExtra = true;
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004739 return true;
4740}
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004741
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004742/// Parse digits from a string \p Str and fulfill \p Digits with
4743/// the parsed numbers. This method assumes that the max number of
4744/// digits to look for is equal to Digits.size().
4745///
4746/// \return True if the entire string was parsed and there are
4747/// no extra characters remaining at the end.
Mehdi Amini12011172016-10-06 05:11:48 +00004748bool Driver::GetReleaseVersion(StringRef Str,
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004749 MutableArrayRef<unsigned> Digits) {
Mehdi Amini12011172016-10-06 05:11:48 +00004750 if (Str.empty())
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004751 return false;
4752
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004753 unsigned CurDigit = 0;
4754 while (CurDigit < Digits.size()) {
Mehdi Amini12011172016-10-06 05:11:48 +00004755 unsigned Digit;
4756 if (Str.consumeInteger(10, Digit))
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004757 return false;
Mehdi Amini12011172016-10-06 05:11:48 +00004758 Digits[CurDigit] = Digit;
4759 if (Str.empty())
4760 return true;
4761 if (Str[0] != '.')
4762 return false;
4763 Str = Str.drop_front(1);
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004764 CurDigit++;
4765 }
4766
4767 // More digits than requested, bail out...
4768 return false;
4769}
4770
Simon Atanasyan27c0f202019-04-02 18:03:15 +00004771std::pair<unsigned, unsigned>
4772Driver::getIncludeExcludeOptionFlagMasks(bool IsClCompatMode) const {
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004773 unsigned IncludedFlagsBitmask = 0;
Rafael Espindolacc707bc2013-09-25 15:54:41 +00004774 unsigned ExcludedFlagsBitmask = options::NoDriverOption;
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004775
Hans Wennborg797004d2018-11-08 11:27:04 +00004776 if (IsClCompatMode) {
Hans Wennborg19076102013-07-31 20:51:53 +00004777 // Include CL and Core options.
4778 IncludedFlagsBitmask |= options::CLOption;
4779 IncludedFlagsBitmask |= options::CoreOption;
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004780 } else {
4781 ExcludedFlagsBitmask |= options::CLOption;
4782 }
4783
4784 return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
4785}
Benjamin Kramerab88f622014-03-25 18:02:07 +00004786
Douglas Katzmanf08fadf2015-06-04 14:40:44 +00004787bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
Benjamin Kramerab88f622014-03-25 18:02:07 +00004788 return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);
4789}