blob: 725bf273ed5f65309ac3ada83aadcb1057ed80b7 [file] [log] [blame]
Nick Lewyckye47c2452010-09-23 23:48:20 +00001//===--- Driver.cpp - Clang GCC Compatible Driver -------------------------===//
Daniel Dunbar544ecd12009-03-02 19:59:07 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Daniel Dunbar544ecd12009-03-02 19:59:07 +000010#include "clang/Driver/Driver.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000011#include "InputInfo.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000012#include "ToolChains/AMDGPU.h"
13#include "ToolChains/AVR.h"
Ed Schouten4dabea22017-06-25 08:29:09 +000014#include "ToolChains/Ananas.h"
Yaxun Liuf6144222018-05-30 00:53:50 +000015#include "ToolChains/BareMetal.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000016#include "ToolChains/Clang.h"
17#include "ToolChains/CloudABI.h"
18#include "ToolChains/Contiki.h"
19#include "ToolChains/CrossWindows.h"
20#include "ToolChains/Cuda.h"
21#include "ToolChains/Darwin.h"
22#include "ToolChains/DragonFly.h"
23#include "ToolChains/FreeBSD.h"
24#include "ToolChains/Fuchsia.h"
25#include "ToolChains/Gnu.h"
Yaxun Liuf6144222018-05-30 00:53:50 +000026#include "ToolChains/HIP.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000027#include "ToolChains/Haiku.h"
28#include "ToolChains/Hexagon.h"
Kristina Brooks77a4adc2018-11-29 03:49:14 +000029#include "ToolChains/Hurd.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000030#include "ToolChains/Lanai.h"
31#include "ToolChains/Linux.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
Petr Hosekdd38d932018-05-29 22:35:39 +000092Driver::Driver(StringRef ClangExecutable, StringRef TargetTriple,
Benjamin Kramerd45b2052015-10-07 15:48:01 +000093 DiagnosticsEngine &Diags,
Jonas Devliegherefc514902018-10-10 13:27:25 +000094 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)
Benjamin Kramercfeacf52016-05-27 14:27:13 +000095 : Opts(createDriverOptTable()), Diags(Diags), VFS(std::move(VFS)),
96 Mode(GCCMode), SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
97 LTOMode(LTOK_None), ClangExecutable(ClangExecutable),
Alex Lorenz045c5142018-04-07 00:03:27 +000098 SysRoot(DEFAULT_SYSROOT), DriverTitle("clang LLVM compiler"),
99 CCPrintOptionsFilename(nullptr), CCPrintHeadersFilename(nullptr),
100 CCLogDiagnosticsFilename(nullptr), CCCPrintBindings(false),
101 CCPrintOptions(false), CCPrintHeaders(false), CCLogDiagnostics(false),
Petr Hosekdd38d932018-05-29 22:35:39 +0000102 CCGenDiagnostics(false), TargetTriple(TargetTriple),
Alex Lorenz045c5142018-04-07 00:03:27 +0000103 CCCGenericGCCName(""), Saver(Alloc), CheckInputsExist(true),
Erich Keane0a6b5b62018-12-04 14:34:09 +0000104 GenReproducer(false), SuppressMissingInputWarning(false) {
Daniel Dunbar3f3e2cd2010-01-20 02:35:16 +0000105
Benjamin Kramerd45b2052015-10-07 15:48:01 +0000106 // Provide a sane fallback if no VFS is specified.
107 if (!this->VFS)
Jonas Devliegherefc514902018-10-10 13:27:25 +0000108 this->VFS = llvm::vfs::getRealFileSystem();
Benjamin Kramerd45b2052015-10-07 15:48:01 +0000109
Sumanth Gundapaneni3a1592942015-03-03 20:43:12 +0000110 Name = llvm::sys::path::filename(ClangExecutable);
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000111 Dir = llvm::sys::path::parent_path(ClangExecutable);
Benjamin Kramerf420dda2015-10-13 15:19:32 +0000112 InstalledDir = Dir; // Provide a sensible default installed dir.
Bob Wilsona20a1da2013-03-23 05:17:59 +0000113
Serge Pavlov208ac652018-01-01 13:27:01 +0000114#if defined(CLANG_CONFIG_FILE_SYSTEM_DIR)
115 SystemConfigDir = CLANG_CONFIG_FILE_SYSTEM_DIR;
116#endif
117#if defined(CLANG_CONFIG_FILE_USER_DIR)
118 UserConfigDir = CLANG_CONFIG_FILE_USER_DIR;
119#endif
120
Bob Wilsona20a1da2013-03-23 05:17:59 +0000121 // Compute the path to the resource directory.
122 StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
123 SmallString<128> P(Dir);
Chandler Carruthfd3cc702014-12-29 12:09:08 +0000124 if (ClangResourceDir != "") {
Bob Wilsona20a1da2013-03-23 05:17:59 +0000125 llvm::sys::path::append(P, ClangResourceDir);
Chandler Carruthfd3cc702014-12-29 12:09:08 +0000126 } else {
127 StringRef ClangLibdirSuffix(CLANG_LIBDIR_SUFFIX);
Argyrios Kyrtzidisbcae0472017-02-25 18:14:35 +0000128 P = llvm::sys::path::parent_path(Dir);
129 llvm::sys::path::append(P, Twine("lib") + ClangLibdirSuffix, "clang",
Chandler Carruthfd3cc702014-12-29 12:09:08 +0000130 CLANG_VERSION_STRING);
131 }
Bob Wilsona20a1da2013-03-23 05:17:59 +0000132 ResourceDir = P.str();
Daniel Dunbar544ecd12009-03-02 19:59:07 +0000133}
134
Zachary Turneraff19c32016-08-12 17:47:52 +0000135void Driver::ParseDriverMode(StringRef ProgramName,
136 ArrayRef<const char *> Args) {
Martin Storsjo1fab23d2018-04-25 21:23:59 +0000137 if (ClangNameParts.isEmpty())
138 ClangNameParts = ToolChain::getTargetAndModeFromProgramName(ProgramName);
Serge Pavlov4e769842017-08-29 05:22:26 +0000139 setDriverModeFromOption(ClangNameParts.DriverMode);
Hans Wennborg70850d82013-07-18 20:29:38 +0000140
Douglas Katzman6bbffc42015-06-25 18:51:37 +0000141 for (const char *ArgPtr : Args) {
Erich Keane258f0592018-02-07 00:19:58 +0000142 // Ignore nullptrs, they are the response file's EOL markers.
Douglas Katzman6bbffc42015-06-25 18:51:37 +0000143 if (ArgPtr == nullptr)
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000144 continue;
Douglas Katzman6bbffc42015-06-25 18:51:37 +0000145 const StringRef Arg = ArgPtr;
Zachary Turneraff19c32016-08-12 17:47:52 +0000146 setDriverModeFromOption(Arg);
Hans Wennborg70850d82013-07-18 20:29:38 +0000147 }
148}
149
Zachary Turneraff19c32016-08-12 17:47:52 +0000150void Driver::setDriverModeFromOption(StringRef Opt) {
151 const std::string OptName =
152 getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
153 if (!Opt.startswith(OptName))
154 return;
155 StringRef Value = Opt.drop_front(OptName.size());
156
Erich Keane2908a042018-02-12 17:47:01 +0000157 if (auto M = llvm::StringSwitch<llvm::Optional<DriverMode>>(Value)
158 .Case("gcc", GCCMode)
159 .Case("g++", GXXMode)
160 .Case("cpp", CPPMode)
161 .Case("cl", CLMode)
162 .Default(None))
163 Mode = *M;
Zachary Turneraff19c32016-08-12 17:47:52 +0000164 else
165 Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
166}
167
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000168InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings,
Hans Wennborg797004d2018-11-08 11:27:04 +0000169 bool IsClCompatMode,
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000170 bool &ContainsError) {
Daniel Dunbar2608c542009-03-18 01:38:48 +0000171 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000172 ContainsError = false;
Hans Wennborg6ddc6902013-07-27 00:23:45 +0000173
174 unsigned IncludedFlagsBitmask;
175 unsigned ExcludedFlagsBitmask;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000176 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
Hans Wennborg797004d2018-11-08 11:27:04 +0000177 getIncludeExcludeOptionFlagMasks(IsClCompatMode);
Hans Wennborg6ddc6902013-07-27 00:23:45 +0000178
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000179 unsigned MissingArgIndex, MissingArgCount;
David Blaikie69a1d8c2015-06-22 22:07:27 +0000180 InputArgList Args =
David Blaikie6d492ad2015-06-21 06:32:36 +0000181 getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
182 IncludedFlagsBitmask, ExcludedFlagsBitmask);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +0000183
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000184 // Check for missing argument error.
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000185 if (MissingArgCount) {
186 Diag(diag::err_drv_missing_argument)
David Blaikie69a1d8c2015-06-22 22:07:27 +0000187 << Args.getArgString(MissingArgIndex) << MissingArgCount;
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000188 ContainsError |=
189 Diags.getDiagnosticLevel(diag::err_drv_missing_argument,
190 SourceLocation()) > DiagnosticsEngine::Warning;
191 }
Daniel Dunbar65229332009-03-13 11:38:42 +0000192
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000193 // Check for unsupported options.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000194 for (const Arg *A : Args) {
Michael J. Spencer66e2b202012-10-19 22:37:06 +0000195 if (A->getOption().hasFlag(options::Unsupported)) {
Brian Gesiak24910762018-01-06 00:25:40 +0000196 unsigned DiagID;
197 auto ArgString = A->getAsString(Args);
198 std::string Nearest;
199 if (getOpts().findNearest(
200 ArgString, Nearest, IncludedFlagsBitmask,
201 ExcludedFlagsBitmask | options::Unsupported) > 1) {
202 DiagID = diag::err_drv_unsupported_opt;
203 Diag(DiagID) << ArgString;
204 } else {
205 DiagID = diag::err_drv_unsupported_opt_with_suggestion;
206 Diag(DiagID) << ArgString << Nearest;
207 }
208 ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000209 DiagnosticsEngine::Warning;
Daniel Dunbard8500f32009-03-22 23:26:43 +0000210 continue;
211 }
Chad Rosierce975d92012-02-22 17:55:22 +0000212
213 // Warn about -mcpu= without an argument.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000214 if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000215 Diag(diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
216 ContainsError |= Diags.getDiagnosticLevel(
217 diag::warn_drv_empty_joined_argument,
218 SourceLocation()) > DiagnosticsEngine::Warning;
Chad Rosierce975d92012-02-22 17:55:22 +0000219 }
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000220 }
221
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000222 for (const Arg *A : Args.filtered(options::OPT_UNKNOWN)) {
Brian Gesiak24910762018-01-06 00:25:40 +0000223 unsigned DiagID;
224 auto ArgString = A->getAsString(Args);
225 std::string Nearest;
226 if (getOpts().findNearest(
227 ArgString, Nearest, IncludedFlagsBitmask, ExcludedFlagsBitmask) > 1) {
228 DiagID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl
229 : diag::err_drv_unknown_argument;
230 Diags.Report(DiagID) << ArgString;
231 } else {
232 DiagID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl_with_suggestion
233 : diag::err_drv_unknown_argument_with_suggestion;
234 Diags.Report(DiagID) << ArgString << Nearest;
235 }
236 ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000237 DiagnosticsEngine::Warning;
238 }
Rafael Espindola8a2d4962013-09-23 23:55:25 +0000239
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000240 return Args;
241}
242
Chad Rosier7742b5d2011-07-27 23:36:45 +0000243// Determine which compilation mode we are in. We look for options which
244// affect the phase, starting with the earliest phases, and record which
245// option we used to determine the final phase.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000246phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
247 Arg **FinalPhaseArg) const {
Craig Topper92fc2df2014-05-17 16:56:41 +0000248 Arg *PhaseArg = nullptr;
Chad Rosier7742b5d2011-07-27 23:36:45 +0000249 phases::ID FinalPhase;
Eric Christopherf901e852011-08-17 22:59:59 +0000250
Hans Wennborge50cec32014-06-13 20:59:54 +0000251 // -{E,EP,P,M,MM} only run the preprocessor.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000252 if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
Hans Wennborge50cec32014-06-13 20:59:54 +0000253 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
Hans Wennborge0053472013-12-20 18:40:46 +0000254 (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
255 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000256 FinalPhase = phases::Preprocess;
Eric Christopherf901e852011-08-17 22:59:59 +0000257
Richard Smithdd4ad3d2016-08-30 19:06:26 +0000258 // --precompile only runs up to precompilation.
259 } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile))) {
260 FinalPhase = phases::Precompile;
261
Bob Wilson23a55f12014-12-21 07:00:00 +0000262 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
Chad Rosier7742b5d2011-07-27 23:36:45 +0000263 } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000264 (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
Ben Langmuir2cb4a782014-02-05 22:21:15 +0000265 (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
Chad Rosier7742b5d2011-07-27 23:36:45 +0000266 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
Fariborz Jahanian73223bb2012-04-02 15:59:19 +0000267 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
Ted Kremenekf7639e12012-03-06 20:06:33 +0000268 (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
Chad Rosier7742b5d2011-07-27 23:36:45 +0000269 (PhaseArg = DAL.getLastArg(options::OPT__analyze,
Chad Rosier1aeb15a2012-03-06 23:14:35 +0000270 options::OPT__analyze_auto)) ||
Bob Wilson23a55f12014-12-21 07:00:00 +0000271 (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000272 FinalPhase = phases::Compile;
273
Bob Wilson23a55f12014-12-21 07:00:00 +0000274 // -S only runs up to the backend.
275 } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
276 FinalPhase = phases::Backend;
277
Artem Belevich4242f412015-07-28 21:01:21 +0000278 // -c compilation only runs up to the assembler.
279 } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000280 FinalPhase = phases::Assemble;
281
282 // Otherwise do everything.
283 } else
284 FinalPhase = phases::Link;
285
286 if (FinalPhaseArg)
287 *FinalPhaseArg = PhaseArg;
288
289 return FinalPhase;
290}
291
David Blaikie0aaa7622017-01-13 17:34:15 +0000292static Arg *MakeInputArg(DerivedArgList &Args, OptTable &Opts,
Martin Storsjo665c7a42018-05-04 06:05:58 +0000293 StringRef Value, bool Claim = true) {
David Blaikie0aaa7622017-01-13 17:34:15 +0000294 Arg *A = new Arg(Opts.getOption(options::OPT_INPUT), Value,
Hans Wennborged1d0722013-08-13 21:32:29 +0000295 Args.getBaseArgs().MakeIndex(Value), Value.data());
Hans Wennborg55362852014-05-02 22:55:30 +0000296 Args.AddSynthesizedArg(A);
Martin Storsjo665c7a42018-05-04 06:05:58 +0000297 if (Claim)
298 A->claim();
Hans Wennborged1d0722013-08-13 21:32:29 +0000299 return A;
300}
301
Daniel Dunbar775d4062010-06-11 22:00:26 +0000302DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
303 DerivedArgList *DAL = new DerivedArgList(Args);
304
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000305 bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
Dan Albertf5ffa1a2018-12-18 23:29:35 +0000306 bool HasNostdlibxx = Args.hasArg(options::OPT_nostdlibxx);
Nirav Daveb0bb6142015-11-24 16:07:21 +0000307 bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +0000308 for (Arg *A : Args) {
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000309 // Unfortunately, we have to parse some forwarding options (-Xassembler,
310 // -Xlinker, -Xpreprocessor) because we either integrate their functionality
311 // (assembler and preprocessor), or bypass a previous driver ('collect2').
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000312
313 // Rewrite linker options, to replace --no-demangle with a custom internal
314 // option.
315 if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
316 A->getOption().matches(options::OPT_Xlinker)) &&
317 A->containsValue("--no-demangle")) {
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000318 // Add the rewritten no-demangle argument.
319 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
320
321 // Add the remaining values as Xlinker arguments.
Benjamin Kramer72e64312015-09-24 14:48:49 +0000322 for (StringRef Val : A->getValues())
Douglas Katzmana34b7bf2015-06-30 19:32:57 +0000323 if (Val != "--no-demangle")
324 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), Val);
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000325
326 continue;
327 }
328
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000329 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
330 // some build systems. We don't try to be complete here because we don't
331 // care to encourage this usage model.
332 if (A->getOption().matches(options::OPT_Wp_COMMA) &&
Richard Smithbd55daf2012-11-01 04:30:05 +0000333 (A->getValue(0) == StringRef("-MD") ||
334 A->getValue(0) == StringRef("-MMD"))) {
Daniel Dunbar3648ba72010-06-15 20:30:18 +0000335 // Rewrite to -MD/-MMD along with -MF.
Richard Smithbd55daf2012-11-01 04:30:05 +0000336 if (A->getValue(0) == StringRef("-MD"))
Daniel Dunbar3648ba72010-06-15 20:30:18 +0000337 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
338 else
339 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
Michael J. Spencer70d85be2012-11-07 23:37:14 +0000340 if (A->getNumValues() == 2)
341 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
342 A->getValue(1));
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000343 continue;
344 }
345
Shantonu Senafeb03b2010-09-17 18:39:08 +0000346 // Rewrite reserved library names.
347 if (A->getOption().matches(options::OPT_l)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000348 StringRef Value = A->getValue();
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000349
Shantonu Senafeb03b2010-09-17 18:39:08 +0000350 // Rewrite unless -nostdlib is present.
Dan Albertf5ffa1a2018-12-18 23:29:35 +0000351 if (!HasNostdlib && !HasNodefaultlib && !HasNostdlibxx &&
352 Value == "stdc++") {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000353 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_stdcxx));
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000354 continue;
355 }
Shantonu Senafeb03b2010-09-17 18:39:08 +0000356
357 // Rewrite unconditionally.
358 if (Value == "cc_kext") {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000359 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_cckext));
Shantonu Senafeb03b2010-09-17 18:39:08 +0000360 continue;
361 }
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000362 }
363
Hans Wennborged1d0722013-08-13 21:32:29 +0000364 // Pick up inputs via the -- option.
365 if (A->getOption().matches(options::OPT__DASH_DASH)) {
366 A->claim();
Benjamin Kramer72e64312015-09-24 14:48:49 +0000367 for (StringRef Val : A->getValues())
Martin Storsjo665c7a42018-05-04 06:05:58 +0000368 DAL->append(MakeInputArg(*DAL, *Opts, Val, false));
Hans Wennborged1d0722013-08-13 21:32:29 +0000369 continue;
370 }
371
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +0000372 DAL->append(A);
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000373 }
Daniel Dunbar775d4062010-06-11 22:00:26 +0000374
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000375 // Enforce -static if -miamcu is present.
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000376 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false))
377 DAL->AddFlagArg(0, Opts->getOption(options::OPT_static));
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000378
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000379// Add a default value of -mlinker-version=, if one was given and the user
380// didn't specify one.
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000381#if defined(HOST_LINK_VERSION)
Tim Northover018578c2015-06-12 19:21:35 +0000382 if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
383 strlen(HOST_LINK_VERSION) > 0) {
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000384 DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
385 HOST_LINK_VERSION);
Daniel Dunbarb613ffc2010-08-17 22:32:45 +0000386 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000387 }
388#endif
389
Daniel Dunbar775d4062010-06-11 22:00:26 +0000390 return DAL;
391}
392
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000393/// Compute target triple from args.
Artem Belevich959e0542015-07-10 19:47:55 +0000394///
395/// This routine provides the logic to compute a target triple from various
396/// args passed to the driver and the default triple string.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000397static llvm::Triple computeTargetTriple(const Driver &D,
Petr Hosekdd38d932018-05-29 22:35:39 +0000398 StringRef TargetTriple,
Artem Belevich959e0542015-07-10 19:47:55 +0000399 const ArgList &Args,
400 StringRef DarwinArchName = "") {
401 // FIXME: Already done in Compilation *Driver::BuildCompilation
402 if (const Arg *A = Args.getLastArg(options::OPT_target))
Petr Hosekdd38d932018-05-29 22:35:39 +0000403 TargetTriple = A->getValue();
Artem Belevich959e0542015-07-10 19:47:55 +0000404
Petr Hosekdd38d932018-05-29 22:35:39 +0000405 llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
Artem Belevich959e0542015-07-10 19:47:55 +0000406
Kristina Brooks77a4adc2018-11-29 03:49:14 +0000407 // GNU/Hurd's triples should have been -hurd-gnu*, but were historically made
408 // -gnu* only, and we can not change this, so we have to detect that case as
409 // being the Hurd OS.
410 if (TargetTriple.find("-unknown-gnu") != StringRef::npos ||
411 TargetTriple.find("-pc-gnu") != StringRef::npos)
412 Target.setOSName("hurd");
413
Artem Belevich959e0542015-07-10 19:47:55 +0000414 // Handle Apple-specific options available here.
415 if (Target.isOSBinFormatMachO()) {
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000416 // If an explicit Darwin arch name is given, that trumps all.
Artem Belevich959e0542015-07-10 19:47:55 +0000417 if (!DarwinArchName.empty()) {
418 tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
419 return Target;
420 }
421
422 // Handle the Darwin '-arch' flag.
423 if (Arg *A = Args.getLastArg(options::OPT_arch)) {
424 StringRef ArchName = A->getValue();
425 tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
426 }
427 }
428
429 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
430 // '-mbig-endian'/'-EB'.
431 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
432 options::OPT_mbig_endian)) {
433 if (A->getOption().matches(options::OPT_mlittle_endian)) {
434 llvm::Triple LE = Target.getLittleEndianArchVariant();
435 if (LE.getArch() != llvm::Triple::UnknownArch)
436 Target = std::move(LE);
437 } else {
438 llvm::Triple BE = Target.getBigEndianArchVariant();
439 if (BE.getArch() != llvm::Triple::UnknownArch)
440 Target = std::move(BE);
441 }
442 }
443
444 // Skip further flag support on OSes which don't support '-m32' or '-m64'.
Douglas Katzman15a63ed2015-08-12 18:36:12 +0000445 if (Target.getArch() == llvm::Triple::tce ||
446 Target.getOS() == llvm::Triple::Minix)
Artem Belevich959e0542015-07-10 19:47:55 +0000447 return Target;
448
449 // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000450 Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
451 options::OPT_m32, options::OPT_m16);
452 if (A) {
Artem Belevich959e0542015-07-10 19:47:55 +0000453 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
454
455 if (A->getOption().matches(options::OPT_m64)) {
456 AT = Target.get64BitArchVariant().getArch();
457 if (Target.getEnvironment() == llvm::Triple::GNUX32)
458 Target.setEnvironment(llvm::Triple::GNU);
459 } else if (A->getOption().matches(options::OPT_mx32) &&
460 Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
461 AT = llvm::Triple::x86_64;
462 Target.setEnvironment(llvm::Triple::GNUX32);
463 } else if (A->getOption().matches(options::OPT_m32)) {
464 AT = Target.get32BitArchVariant().getArch();
465 if (Target.getEnvironment() == llvm::Triple::GNUX32)
466 Target.setEnvironment(llvm::Triple::GNU);
467 } else if (A->getOption().matches(options::OPT_m16) &&
468 Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
469 AT = llvm::Triple::x86;
470 Target.setEnvironment(llvm::Triple::CODE16);
471 }
472
473 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
474 Target.setArch(AT);
475 }
476
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000477 // Handle -miamcu flag.
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000478 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
479 if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
480 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
481 << Target.str();
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000482
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000483 if (A && !A->getOption().matches(options::OPT_m32))
484 D.Diag(diag::err_drv_argument_not_allowed_with)
485 << "-miamcu" << A->getBaseArg().getAsString(Args);
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000486
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000487 Target.setArch(llvm::Triple::x86);
488 Target.setArchName("i586");
489 Target.setEnvironment(llvm::Triple::UnknownEnvironment);
490 Target.setEnvironmentName("");
491 Target.setOS(llvm::Triple::ELFIAMCU);
492 Target.setVendor(llvm::Triple::UnknownVendor);
493 Target.setVendorName("intel");
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000494 }
495
Simon Atanasyan0c0fb4b2018-09-27 05:04:50 +0000496 // If target is MIPS adjust the target triple
497 // accordingly to provided ABI name.
498 A = Args.getLastArg(options::OPT_mabi_EQ);
Simon Atanasyane60eae42018-10-16 10:19:06 +0000499 if (A && Target.isMIPS()) {
500 StringRef ABIName = A->getValue();
501 if (ABIName == "32") {
502 Target = Target.get32BitArchVariant();
503 if (Target.getEnvironment() == llvm::Triple::GNUABI64 ||
504 Target.getEnvironment() == llvm::Triple::GNUABIN32)
505 Target.setEnvironment(llvm::Triple::GNU);
506 } else if (ABIName == "n32") {
507 Target = Target.get64BitArchVariant();
508 if (Target.getEnvironment() == llvm::Triple::GNU ||
509 Target.getEnvironment() == llvm::Triple::GNUABI64)
510 Target.setEnvironment(llvm::Triple::GNUABIN32);
511 } else if (ABIName == "64") {
512 Target = Target.get64BitArchVariant();
513 if (Target.getEnvironment() == llvm::Triple::GNU ||
514 Target.getEnvironment() == llvm::Triple::GNUABIN32)
515 Target.setEnvironment(llvm::Triple::GNUABI64);
516 }
517 }
Simon Atanasyan0c0fb4b2018-09-27 05:04:50 +0000518
Artem Belevich959e0542015-07-10 19:47:55 +0000519 return Target;
520}
521
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000522// Parse the LTO options and record the type of LTO compilation
Teresa Johnson945bc502015-10-15 20:35:53 +0000523// based on which -f(no-)?lto(=.*)? option occurs last.
524void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
525 LTOMode = LTOK_None;
526 if (!Args.hasFlag(options::OPT_flto, options::OPT_flto_EQ,
527 options::OPT_fno_lto, false))
528 return;
529
530 StringRef LTOName("full");
531
532 const Arg *A = Args.getLastArg(options::OPT_flto_EQ);
Teresa Johnson6ef80dc2015-11-02 18:03:12 +0000533 if (A)
534 LTOName = A->getValue();
Teresa Johnson945bc502015-10-15 20:35:53 +0000535
536 LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
537 .Case("full", LTOK_Full)
538 .Case("thin", LTOK_Thin)
539 .Default(LTOK_Unknown);
540
541 if (LTOMode == LTOK_Unknown) {
542 assert(A);
543 Diag(diag::err_drv_unsupported_option_argument) << A->getOption().getName()
544 << A->getValue();
545 }
546}
547
Samuel Antao39f9da22016-10-27 16:38:05 +0000548/// Compute the desired OpenMP runtime from the flags provided.
549Driver::OpenMPRuntimeKind Driver::getOpenMPRuntime(const ArgList &Args) const {
550 StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
551
552 const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
553 if (A)
554 RuntimeName = A->getValue();
555
556 auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
557 .Case("libomp", OMPRT_OMP)
558 .Case("libgomp", OMPRT_GOMP)
559 .Case("libiomp5", OMPRT_IOMP5)
560 .Default(OMPRT_Unknown);
561
562 if (RT == OMPRT_Unknown) {
563 if (A)
564 Diag(diag::err_drv_unsupported_option_argument)
565 << A->getOption().getName() << A->getValue();
566 else
567 // FIXME: We could use a nicer diagnostic here.
568 Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
569 }
570
571 return RT;
572}
573
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000574void Driver::CreateOffloadingDeviceToolChains(Compilation &C,
575 InputList &Inputs) {
576
577 //
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000578 // CUDA/HIP
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000579 //
Yaxun Liuf6144222018-05-30 00:53:50 +0000580 // We need to generate a CUDA/HIP toolchain if any of the inputs has a CUDA
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000581 // or HIP type. However, mixed CUDA/HIP compilation is not supported.
582 bool IsCuda =
583 llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000584 return types::isCuda(I.first);
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000585 });
586 bool IsHIP =
587 llvm::any_of(Inputs,
588 [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
589 return types::isHIP(I.first);
590 }) ||
591 C.getInputArgs().hasArg(options::OPT_hip_link);
592 if (IsCuda && IsHIP) {
593 Diag(clang::diag::err_drv_mix_cuda_hip);
594 return;
595 }
Yaxun Liuf6144222018-05-30 00:53:50 +0000596 if (IsCuda) {
Justin Lebar66c4fd72016-11-18 00:41:22 +0000597 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
598 const llvm::Triple &HostTriple = HostTC->getTriple();
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000599 StringRef DeviceTripleStr;
Yaxun Liuf6144222018-05-30 00:53:50 +0000600 auto OFK = Action::OFK_Cuda;
601 DeviceTripleStr =
602 HostTriple.isArch64Bit() ? "nvptx64-nvidia-cuda" : "nvptx-nvidia-cuda";
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000603 llvm::Triple CudaTriple(DeviceTripleStr);
Yaxun Liuf6144222018-05-30 00:53:50 +0000604 // Use the CUDA and host triples as the key into the ToolChains map,
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000605 // because the device toolchain we create depends on both.
David Blaikie6ad71012017-01-13 18:53:43 +0000606 auto &CudaTC = ToolChains[CudaTriple.str() + "/" + HostTriple.str()];
Justin Lebar66c4fd72016-11-18 00:41:22 +0000607 if (!CudaTC) {
David Blaikie6ad71012017-01-13 18:53:43 +0000608 CudaTC = llvm::make_unique<toolchains::CudaToolChain>(
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000609 *this, CudaTriple, *HostTC, C.getInputArgs(), OFK);
Justin Lebar66c4fd72016-11-18 00:41:22 +0000610 }
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000611 C.addOffloadDeviceToolChain(CudaTC.get(), OFK);
Yaxun Liuf6144222018-05-30 00:53:50 +0000612 } else if (IsHIP) {
613 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
614 const llvm::Triple &HostTriple = HostTC->getTriple();
615 StringRef DeviceTripleStr;
616 auto OFK = Action::OFK_HIP;
617 DeviceTripleStr = "amdgcn-amd-amdhsa";
618 llvm::Triple HIPTriple(DeviceTripleStr);
619 // Use the HIP and host triples as the key into the ToolChains map,
620 // because the device toolchain we create depends on both.
621 auto &HIPTC = ToolChains[HIPTriple.str() + "/" + HostTriple.str()];
622 if (!HIPTC) {
623 HIPTC = llvm::make_unique<toolchains::HIPToolChain>(
624 *this, HIPTriple, *HostTC, C.getInputArgs());
625 }
626 C.addOffloadDeviceToolChain(HIPTC.get(), OFK);
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000627 }
628
629 //
Samuel Antao39f9da22016-10-27 16:38:05 +0000630 // OpenMP
631 //
632 // We need to generate an OpenMP toolchain if the user specified targets with
633 // the -fopenmp-targets option.
634 if (Arg *OpenMPTargets =
635 C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
636 if (OpenMPTargets->getNumValues()) {
637 // We expect that -fopenmp-targets is always used in conjunction with the
638 // option -fopenmp specifying a valid runtime with offloading support,
639 // i.e. libomp or libiomp.
640 bool HasValidOpenMPRuntime = C.getInputArgs().hasFlag(
641 options::OPT_fopenmp, options::OPT_fopenmp_EQ,
642 options::OPT_fno_openmp, false);
643 if (HasValidOpenMPRuntime) {
644 OpenMPRuntimeKind OpenMPKind = getOpenMPRuntime(C.getInputArgs());
645 HasValidOpenMPRuntime =
646 OpenMPKind == OMPRT_OMP || OpenMPKind == OMPRT_IOMP5;
647 }
648
649 if (HasValidOpenMPRuntime) {
650 llvm::StringMap<const char *> FoundNormalizedTriples;
651 for (const char *Val : OpenMPTargets->getValues()) {
652 llvm::Triple TT(Val);
653 std::string NormalizedName = TT.normalize();
654
655 // Make sure we don't have a duplicate triple.
656 auto Duplicate = FoundNormalizedTriples.find(NormalizedName);
657 if (Duplicate != FoundNormalizedTriples.end()) {
658 Diag(clang::diag::warn_drv_omp_offload_target_duplicate)
659 << Val << Duplicate->second;
660 continue;
661 }
662
663 // Store the current triple so that we can check for duplicates in the
664 // following iterations.
665 FoundNormalizedTriples[NormalizedName] = Val;
666
667 // If the specified target is invalid, emit a diagnostic.
668 if (TT.getArch() == llvm::Triple::UnknownArch)
669 Diag(clang::diag::err_drv_invalid_omp_target) << Val;
670 else {
Gheorghe-Teodor Bercea6a5df722017-07-06 16:08:15 +0000671 const ToolChain *TC;
672 // CUDA toolchains have to be selected differently. They pair host
673 // and device in their implementation.
674 if (TT.isNVPTX()) {
675 const ToolChain *HostTC =
676 C.getSingleOffloadToolChain<Action::OFK_Host>();
677 assert(HostTC && "Host toolchain should be always defined.");
678 auto &CudaTC =
Gheorghe-Teodor Bercea52898432017-08-09 01:02:19 +0000679 ToolChains[TT.str() + "/" + HostTC->getTriple().normalize()];
Gheorghe-Teodor Bercea6a5df722017-07-06 16:08:15 +0000680 if (!CudaTC)
681 CudaTC = llvm::make_unique<toolchains::CudaToolChain>(
Gheorghe-Teodor Bercea2c926932017-08-08 14:33:05 +0000682 *this, TT, *HostTC, C.getInputArgs(), Action::OFK_OpenMP);
Gheorghe-Teodor Bercea6a5df722017-07-06 16:08:15 +0000683 TC = CudaTC.get();
684 } else
685 TC = &getToolChain(C.getInputArgs(), TT);
686 C.addOffloadDeviceToolChain(TC, Action::OFK_OpenMP);
Samuel Antao39f9da22016-10-27 16:38:05 +0000687 }
688 }
689 } else
690 Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
691 } else
692 Diag(clang::diag::warn_drv_empty_joined_argument)
693 << OpenMPTargets->getAsString(C.getInputArgs());
694 }
695
696 //
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000697 // TODO: Add support for other offloading programming models here.
698 //
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000699}
700
Serge Pavlov208ac652018-01-01 13:27:01 +0000701/// Looks the given directories for the specified file.
702///
703/// \param[out] FilePath File path, if the file was found.
704/// \param[in] Dirs Directories used for the search.
705/// \param[in] FileName Name of the file to search for.
706/// \return True if file was found.
707///
708/// Looks for file specified by FileName sequentially in directories specified
709/// by Dirs.
710///
711static bool searchForFile(SmallVectorImpl<char> &FilePath,
712 ArrayRef<std::string> Dirs,
713 StringRef FileName) {
714 SmallString<128> WPath;
715 for (const StringRef &Dir : Dirs) {
716 if (Dir.empty())
717 continue;
718 WPath.clear();
719 llvm::sys::path::append(WPath, Dir, FileName);
720 llvm::sys::path::native(WPath);
721 if (llvm::sys::fs::is_regular_file(WPath)) {
722 FilePath = std::move(WPath);
723 return true;
724 }
725 }
726 return false;
727}
728
729bool Driver::readConfigFile(StringRef FileName) {
730 // Try reading the given file.
731 SmallVector<const char *, 32> NewCfgArgs;
732 if (!llvm::cl::readConfigFile(FileName, Saver, NewCfgArgs)) {
733 Diag(diag::err_drv_cannot_read_config_file) << FileName;
734 return true;
735 }
736
737 // Read options from config file.
738 llvm::SmallString<128> CfgFileName(FileName);
739 llvm::sys::path::native(CfgFileName);
740 ConfigFile = CfgFileName.str();
741 bool ContainErrors;
742 CfgOptions = llvm::make_unique<InputArgList>(
Hans Wennborg797004d2018-11-08 11:27:04 +0000743 ParseArgStrings(NewCfgArgs, IsCLMode(), ContainErrors));
Serge Pavlov208ac652018-01-01 13:27:01 +0000744 if (ContainErrors) {
745 CfgOptions.reset();
746 return true;
747 }
748
749 if (CfgOptions->hasArg(options::OPT_config)) {
750 CfgOptions.reset();
751 Diag(diag::err_drv_nested_config_file);
752 return true;
753 }
754
755 // Claim all arguments that come from a configuration file so that the driver
756 // does not warn on any that is unused.
757 for (Arg *A : *CfgOptions)
758 A->claim();
759 return false;
760}
761
762bool Driver::loadConfigFile() {
763 std::string CfgFileName;
764 bool FileSpecifiedExplicitly = false;
765
766 // Process options that change search path for config files.
767 if (CLOptions) {
768 if (CLOptions->hasArg(options::OPT_config_system_dir_EQ)) {
769 SmallString<128> CfgDir;
770 CfgDir.append(
771 CLOptions->getLastArgValue(options::OPT_config_system_dir_EQ));
772 if (!CfgDir.empty()) {
Sam McCall296d8322018-01-02 09:35:10 +0000773 if (llvm::sys::fs::make_absolute(CfgDir).value() != 0)
Serge Pavlov208ac652018-01-01 13:27:01 +0000774 SystemConfigDir.clear();
775 else
776 SystemConfigDir = std::string(CfgDir.begin(), CfgDir.end());
777 }
778 }
779 if (CLOptions->hasArg(options::OPT_config_user_dir_EQ)) {
780 SmallString<128> CfgDir;
781 CfgDir.append(
782 CLOptions->getLastArgValue(options::OPT_config_user_dir_EQ));
783 if (!CfgDir.empty()) {
Sam McCall296d8322018-01-02 09:35:10 +0000784 if (llvm::sys::fs::make_absolute(CfgDir).value() != 0)
Serge Pavlov208ac652018-01-01 13:27:01 +0000785 UserConfigDir.clear();
786 else
787 UserConfigDir = std::string(CfgDir.begin(), CfgDir.end());
788 }
789 }
790 }
791
792 // First try to find config file specified in command line.
793 if (CLOptions) {
794 std::vector<std::string> ConfigFiles =
795 CLOptions->getAllArgValues(options::OPT_config);
796 if (ConfigFiles.size() > 1) {
797 Diag(diag::err_drv_duplicate_config);
798 return true;
799 }
800
801 if (!ConfigFiles.empty()) {
802 CfgFileName = ConfigFiles.front();
803 assert(!CfgFileName.empty());
804
805 // If argument contains directory separator, treat it as a path to
806 // configuration file.
807 if (llvm::sys::path::has_parent_path(CfgFileName)) {
808 SmallString<128> CfgFilePath;
809 if (llvm::sys::path::is_relative(CfgFileName))
810 llvm::sys::fs::current_path(CfgFilePath);
811 llvm::sys::path::append(CfgFilePath, CfgFileName);
812 if (!llvm::sys::fs::is_regular_file(CfgFilePath)) {
813 Diag(diag::err_drv_config_file_not_exist) << CfgFilePath;
814 return true;
815 }
816 return readConfigFile(CfgFilePath);
817 }
818
819 FileSpecifiedExplicitly = true;
820 }
821 }
822
823 // If config file is not specified explicitly, try to deduce configuration
824 // from executable name. For instance, an executable 'armv7l-clang' will
825 // search for config file 'armv7l-clang.cfg'.
826 if (CfgFileName.empty() && !ClangNameParts.TargetPrefix.empty())
827 CfgFileName = ClangNameParts.TargetPrefix + '-' + ClangNameParts.ModeSuffix;
828
829 if (CfgFileName.empty())
830 return false;
831
832 // Determine architecture part of the file name, if it is present.
833 StringRef CfgFileArch = CfgFileName;
834 size_t ArchPrefixLen = CfgFileArch.find('-');
835 if (ArchPrefixLen == StringRef::npos)
836 ArchPrefixLen = CfgFileArch.size();
837 llvm::Triple CfgTriple;
838 CfgFileArch = CfgFileArch.take_front(ArchPrefixLen);
839 CfgTriple = llvm::Triple(llvm::Triple::normalize(CfgFileArch));
840 if (CfgTriple.getArch() == llvm::Triple::ArchType::UnknownArch)
841 ArchPrefixLen = 0;
842
843 if (!StringRef(CfgFileName).endswith(".cfg"))
844 CfgFileName += ".cfg";
845
846 // If config file starts with architecture name and command line options
847 // redefine architecture (with options like -m32 -LE etc), try finding new
848 // config file with that architecture.
849 SmallString<128> FixedConfigFile;
850 size_t FixedArchPrefixLen = 0;
851 if (ArchPrefixLen) {
852 // Get architecture name from config file name like 'i386.cfg' or
853 // 'armv7l-clang.cfg'.
854 // Check if command line options changes effective triple.
855 llvm::Triple EffectiveTriple = computeTargetTriple(*this,
856 CfgTriple.getTriple(), *CLOptions);
857 if (CfgTriple.getArch() != EffectiveTriple.getArch()) {
858 FixedConfigFile = EffectiveTriple.getArchName();
859 FixedArchPrefixLen = FixedConfigFile.size();
860 // Append the rest of original file name so that file name transforms
861 // like: i386-clang.cfg -> x86_64-clang.cfg.
862 if (ArchPrefixLen < CfgFileName.size())
863 FixedConfigFile += CfgFileName.substr(ArchPrefixLen);
864 }
865 }
866
867 // Prepare list of directories where config file is searched for.
868 SmallVector<std::string, 3> CfgFileSearchDirs;
869 CfgFileSearchDirs.push_back(UserConfigDir);
870 CfgFileSearchDirs.push_back(SystemConfigDir);
871 CfgFileSearchDirs.push_back(Dir);
872
873 // Try to find config file. First try file with corrected architecture.
874 llvm::SmallString<128> CfgFilePath;
875 if (!FixedConfigFile.empty()) {
876 if (searchForFile(CfgFilePath, CfgFileSearchDirs, FixedConfigFile))
877 return readConfigFile(CfgFilePath);
878 // If 'x86_64-clang.cfg' was not found, try 'x86_64.cfg'.
879 FixedConfigFile.resize(FixedArchPrefixLen);
880 FixedConfigFile.append(".cfg");
881 if (searchForFile(CfgFilePath, CfgFileSearchDirs, FixedConfigFile))
882 return readConfigFile(CfgFilePath);
883 }
884
885 // Then try original file name.
886 if (searchForFile(CfgFilePath, CfgFileSearchDirs, CfgFileName))
887 return readConfigFile(CfgFilePath);
888
889 // Finally try removing driver mode part: 'x86_64-clang.cfg' -> 'x86_64.cfg'.
890 if (!ClangNameParts.ModeSuffix.empty() &&
891 !ClangNameParts.TargetPrefix.empty()) {
892 CfgFileName.assign(ClangNameParts.TargetPrefix);
893 CfgFileName.append(".cfg");
894 if (searchForFile(CfgFilePath, CfgFileSearchDirs, CfgFileName))
895 return readConfigFile(CfgFilePath);
896 }
897
898 // Report error but only if config file was specified explicitly, by option
899 // --config. If it was deduced from executable name, it is not an error.
900 if (FileSpecifiedExplicitly) {
901 Diag(diag::err_drv_config_file_not_found) << CfgFileName;
902 for (const std::string &SearchDir : CfgFileSearchDirs)
903 if (!SearchDir.empty())
904 Diag(diag::note_drv_config_file_searched_in) << SearchDir;
905 return true;
906 }
907
908 return false;
909}
910
Chris Lattner54b16772011-07-23 17:14:25 +0000911Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
Daniel Dunbar2608c542009-03-18 01:38:48 +0000912 llvm::PrettyStackTraceString CrashInfo("Compilation construction");
913
Eric Christopherf901e852011-08-17 22:59:59 +0000914 // FIXME: Handle environment options which affect driver behavior, somewhere
Bill Wendlingadbeb9f2012-03-12 21:24:57 +0000915 // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
Chad Rosier82301162011-09-14 00:47:55 +0000916
David Majnemer85c25b42016-07-24 17:44:03 +0000917 if (Optional<std::string> CompilerPathValue =
918 llvm::sys::Process::GetEnv("COMPILER_PATH")) {
919 StringRef CompilerPath = *CompilerPathValue;
Chad Rosier82301162011-09-14 00:47:55 +0000920 while (!CompilerPath.empty()) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000921 std::pair<StringRef, StringRef> Split =
922 CompilerPath.split(llvm::sys::EnvPathSeparator);
Chad Rosier82301162011-09-14 00:47:55 +0000923 PrefixDirs.push_back(Split.first);
924 CompilerPath = Split.second;
925 }
926 }
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +0000927
Hans Wennborg70850d82013-07-18 20:29:38 +0000928 // We look for the driver mode option early, because the mode can affect
929 // how other options are parsed.
Zachary Turneraff19c32016-08-12 17:47:52 +0000930 ParseDriverMode(ClangExecutable, ArgList.slice(1));
Hans Wennborg70850d82013-07-18 20:29:38 +0000931
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +0000932 // FIXME: What are we going to do with -V and -b?
933
Serge Pavlov208ac652018-01-01 13:27:01 +0000934 // Arguments specified in command line.
935 bool ContainsError;
936 CLOptions = llvm::make_unique<InputArgList>(
Hans Wennborg797004d2018-11-08 11:27:04 +0000937 ParseArgStrings(ArgList.slice(1), IsCLMode(), ContainsError));
Serge Pavlov208ac652018-01-01 13:27:01 +0000938
939 // Try parsing configuration file.
940 if (!ContainsError)
941 ContainsError = loadConfigFile();
942 bool HasConfigFile = !ContainsError && (CfgOptions.get() != nullptr);
943
944 // All arguments, from both config file and command line.
945 InputArgList Args = std::move(HasConfigFile ? std::move(*CfgOptions)
946 : std::move(*CLOptions));
Hans Wennborg797004d2018-11-08 11:27:04 +0000947
948 auto appendOneArg = [&Args](const Arg *Opt, const Arg *BaseArg) {
Serge Pavlovf015a562018-04-26 06:28:47 +0000949 unsigned Index = Args.MakeIndex(Opt->getSpelling());
Serge Pavlov208ac652018-01-01 13:27:01 +0000950 Arg *Copy = new llvm::opt::Arg(Opt->getOption(), Opt->getSpelling(),
Serge Pavlovf015a562018-04-26 06:28:47 +0000951 Index, BaseArg);
Serge Pavlov208ac652018-01-01 13:27:01 +0000952 Copy->getValues() = Opt->getValues();
953 if (Opt->isClaimed())
954 Copy->claim();
955 Args.append(Copy);
Hans Wennborg797004d2018-11-08 11:27:04 +0000956 };
957
958 if (HasConfigFile)
959 for (auto *Opt : *CLOptions) {
960 if (Opt->getOption().matches(options::OPT_config))
961 continue;
962 const Arg *BaseArg = &Opt->getBaseArg();
963 if (BaseArg == Opt)
964 BaseArg = nullptr;
965 appendOneArg(Opt, BaseArg);
Serge Pavlov208ac652018-01-01 13:27:01 +0000966 }
967
Hans Wennborg797004d2018-11-08 11:27:04 +0000968 // In CL mode, look for any pass-through arguments
969 if (IsCLMode() && !ContainsError) {
970 SmallVector<const char *, 16> CLModePassThroughArgList;
971 for (const auto *A : Args.filtered(options::OPT__SLASH_clang)) {
972 A->claim();
973 CLModePassThroughArgList.push_back(A->getValue());
974 }
975
976 if (!CLModePassThroughArgList.empty()) {
977 // Parse any pass through args using default clang processing rather
978 // than clang-cl processing.
979 auto CLModePassThroughOptions = llvm::make_unique<InputArgList>(
980 ParseArgStrings(CLModePassThroughArgList, false, ContainsError));
981
982 if (!ContainsError)
983 for (auto *Opt : *CLModePassThroughOptions) {
984 appendOneArg(Opt, nullptr);
985 }
986 }
987 }
988
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +0000989 // FIXME: This stuff needs to go into the Compilation, not the driver.
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +0000990 bool CCCPrintPhases;
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000991
Filipe Cabecinhas136f35e2015-07-18 06:35:24 +0000992 // Silence driver warnings if requested
993 Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w));
994
Rafael Espindola59ae7992009-12-07 18:28:29 +0000995 // -no-canonical-prefixes is used very early in main.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000996 Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
Rafael Espindola59ae7992009-12-07 18:28:29 +0000997
Daniel Dunbar926f81f2010-08-02 02:38:03 +0000998 // Ignore -pipe.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000999 Args.ClaimAllArgs(options::OPT_pipe);
Daniel Dunbar926f81f2010-08-02 02:38:03 +00001000
Daniel Dunbaracd69572009-12-04 21:55:23 +00001001 // Extract -ccc args.
Daniel Dunbaree66cf22009-03-10 20:52:46 +00001002 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001003 // FIXME: We need to figure out where this behavior should live. Most of it
1004 // should be outside in the client; the parts that aren't should have proper
1005 // options, either by introducing new ones or by overloading gcc ones like -V
1006 // or -b.
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001007 CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
David Blaikie69a1d8c2015-06-22 22:07:27 +00001008 CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
1009 if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
Richard Smithbd55daf2012-11-01 04:30:05 +00001010 CCCGenericGCCName = A->getValue();
Bruno Cardoso Lopes52dfe712017-04-12 21:46:20 +00001011 GenReproducer = Args.hasFlag(options::OPT_gen_reproducer,
1012 options::OPT_fno_crash_diagnostics,
1013 !!::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH"));
Petr Hosekdd38d932018-05-29 22:35:39 +00001014 // FIXME: TargetTriple is used by the target-prefixed calls to as/ld
Joerg Sonnenberger17d75512012-02-22 19:15:16 +00001015 // and getToolChain is const.
Hans Wennborg2e274592013-08-13 23:38:57 +00001016 if (IsCLMode()) {
Hans Wennborg73609a02014-03-28 01:19:04 +00001017 // clang-cl targets MSVC-style Win32.
Petr Hosekdd38d932018-05-29 22:35:39 +00001018 llvm::Triple T(TargetTriple);
Hans Wennborg9d9ce7a2014-03-28 20:49:28 +00001019 T.setOS(llvm::Triple::Win32);
Hans Wennborg0f0e8d62015-09-18 17:11:50 +00001020 T.setVendor(llvm::Triple::PC);
Hans Wennborg9d9ce7a2014-03-28 20:49:28 +00001021 T.setEnvironment(llvm::Triple::MSVC);
Oleg Ranevskyy80523182017-08-31 20:31:30 +00001022 T.setObjectFormat(llvm::Triple::COFF);
Petr Hosekdd38d932018-05-29 22:35:39 +00001023 TargetTriple = T.str();
Hans Wennborg2e274592013-08-13 23:38:57 +00001024 }
David Blaikie69a1d8c2015-06-22 22:07:27 +00001025 if (const Arg *A = Args.getLastArg(options::OPT_target))
Petr Hosekdd38d932018-05-29 22:35:39 +00001026 TargetTriple = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +00001027 if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
Richard Smithbd55daf2012-11-01 04:30:05 +00001028 Dir = InstalledDir = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +00001029 for (const Arg *A : Args.filtered(options::OPT_B)) {
Benjamin Kramer1a648d12011-02-08 20:31:42 +00001030 A->claim();
Richard Smithbd55daf2012-11-01 04:30:05 +00001031 PrefixDirs.push_back(A->getValue(0));
Benjamin Kramer1a648d12011-02-08 20:31:42 +00001032 }
David Blaikie69a1d8c2015-06-22 22:07:27 +00001033 if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
Richard Smithbd55daf2012-11-01 04:30:05 +00001034 SysRoot = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +00001035 if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
Peter Collingbourne9d9e1fc2013-05-27 21:40:20 +00001036 DyldPrefix = A->getValue();
Daniel Dunbaree66cf22009-03-10 20:52:46 +00001037
David Blaikie69a1d8c2015-06-22 22:07:27 +00001038 if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
Bob Wilsona20a1da2013-03-23 05:17:59 +00001039 ResourceDir = A->getValue();
Jim Grosbach061dabf2013-03-12 20:17:58 +00001040
David Blaikie69a1d8c2015-06-22 22:07:27 +00001041 if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
Reid Kleckner68eb60b2015-02-02 22:41:48 +00001042 SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
1043 .Case("cwd", SaveTempsCwd)
1044 .Case("obj", SaveTempsObj)
1045 .Default(SaveTempsCwd);
1046 }
1047
Steven Wu1257cd82016-05-18 17:04:52 +00001048 setLTOMode(Args);
1049
Steven Wu844ab6a2016-11-16 06:06:44 +00001050 // Process -fembed-bitcode= flags.
1051 if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
1052 StringRef Name = A->getValue();
1053 unsigned Model = llvm::StringSwitch<unsigned>(Name)
1054 .Case("off", EmbedNone)
1055 .Case("all", EmbedBitcode)
1056 .Case("bitcode", EmbedBitcode)
1057 .Case("marker", EmbedMarker)
1058 .Default(~0U);
1059 if (Model == ~0U) {
1060 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
1061 << Name;
1062 } else
1063 BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
Steven Wu574b0f22016-03-01 01:07:58 +00001064 }
1065
David Blaikie69a1d8c2015-06-22 22:07:27 +00001066 std::unique_ptr<llvm::opt::InputArgList> UArgs =
1067 llvm::make_unique<InputArgList>(std::move(Args));
1068
Daniel Dunbar775d4062010-06-11 22:00:26 +00001069 // Perform the default argument translations.
David Blaikie69a1d8c2015-06-22 22:07:27 +00001070 DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
Daniel Dunbar775d4062010-06-11 22:00:26 +00001071
Chandler Carruthcb916192012-01-25 08:49:21 +00001072 // Owned by the host.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +00001073 const ToolChain &TC = getToolChain(
Petr Hosekdd38d932018-05-29 22:35:39 +00001074 *UArgs, computeTargetTriple(*this, TargetTriple, *UArgs));
Chandler Carruthcb916192012-01-25 08:49:21 +00001075
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00001076 // The compilation takes ownership of Args.
Benjamin Kramer43c0f482017-06-30 13:21:27 +00001077 Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs,
1078 ContainsError);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001079
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001080 if (!HandleImmediateArgs(*C))
1081 return C;
1082
Chad Rosierecdede82011-08-12 22:08:57 +00001083 // Construct the list of inputs.
1084 InputList Inputs;
Hans Wennborged1d0722013-08-13 21:32:29 +00001085 BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
Chad Rosierecdede82011-08-12 22:08:57 +00001086
Samuel Antaoc1ffba52016-06-13 18:10:57 +00001087 // Populate the tool chains for the offloading devices, if any.
1088 CreateOffloadingDeviceToolChains(*C, Inputs);
Justin Lebar0e450a52016-03-30 23:30:25 +00001089
Chandler Carruth7f1417f2012-01-24 10:43:44 +00001090 // Construct the list of abstract actions to perform for this compilation. On
Tim Northover157d9112014-01-16 08:48:16 +00001091 // MachO targets this uses the driver-driver and universal actions.
1092 if (TC.getTriple().isOSBinFormatMachO())
Artem Belevich5e2a3ec2015-11-17 22:28:40 +00001093 BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001094 else
Justin Lebar0f3474c2016-02-11 02:00:50 +00001095 BuildActions(*C, C->getArgs(), Inputs, C->getActions());
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001096
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001097 if (CCCPrintPhases) {
Daniel Dunbareb843be2009-03-18 03:13:20 +00001098 PrintActions(*C);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001099 return C;
1100 }
1101
1102 BuildJobs(*C);
Daniel Dunbaradc91e62009-03-15 01:38:15 +00001103
1104 return C;
Daniel Dunbaree66cf22009-03-10 20:52:46 +00001105}
1106
Justin Bognered9cbe02015-07-09 06:58:31 +00001107static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
1108 llvm::opt::ArgStringList ASL;
1109 for (const auto *A : Args)
1110 A->render(Args, ASL);
1111
1112 for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
1113 if (I != ASL.begin())
1114 OS << ' ';
1115 Command::printArg(OS, *I, true);
1116 }
1117 OS << '\n';
1118}
1119
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +00001120bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename,
1121 SmallString<128> &CrashDiagDir) {
1122 using namespace llvm::sys;
1123 assert(llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin() &&
1124 "Only knows about .crash files on Darwin");
1125
1126 // The .crash file can be found on at ~/Library/Logs/DiagnosticReports/
1127 // (or /Library/Logs/DiagnosticReports for root) and has the filename pattern
1128 // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash.
1129 path::home_directory(CrashDiagDir);
1130 if (CrashDiagDir.startswith("/var/root"))
1131 CrashDiagDir = "/";
1132 path::append(CrashDiagDir, "Library/Logs/DiagnosticReports");
1133 int PID =
1134#if LLVM_ON_UNIX
1135 getpid();
1136#else
1137 0;
1138#endif
1139 std::error_code EC;
1140 fs::file_status FileStatus;
1141 TimePoint<> LastAccessTime;
1142 SmallString<128> CrashFilePath;
1143 // Lookup the .crash files and get the one generated by a subprocess spawned
1144 // by this driver invocation.
1145 for (fs::directory_iterator File(CrashDiagDir, EC), FileEnd;
1146 File != FileEnd && !EC; File.increment(EC)) {
1147 StringRef FileName = path::filename(File->path());
1148 if (!FileName.startswith(Name))
1149 continue;
1150 if (fs::status(File->path(), FileStatus))
1151 continue;
1152 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CrashFile =
1153 llvm::MemoryBuffer::getFile(File->path());
1154 if (!CrashFile)
1155 continue;
1156 // The first line should start with "Process:", otherwise this isn't a real
1157 // .crash file.
1158 StringRef Data = CrashFile.get()->getBuffer();
1159 if (!Data.startswith("Process:"))
1160 continue;
1161 // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]"
1162 size_t ParentProcPos = Data.find("Parent Process:");
1163 if (ParentProcPos == StringRef::npos)
1164 continue;
1165 size_t LineEnd = Data.find_first_of("\n", ParentProcPos);
1166 if (LineEnd == StringRef::npos)
1167 continue;
1168 StringRef ParentProcess = Data.slice(ParentProcPos+15, LineEnd).trim();
1169 int OpenBracket = -1, CloseBracket = -1;
1170 for (size_t i = 0, e = ParentProcess.size(); i < e; ++i) {
1171 if (ParentProcess[i] == '[')
1172 OpenBracket = i;
1173 if (ParentProcess[i] == ']')
1174 CloseBracket = i;
1175 }
1176 // Extract the parent process PID from the .crash file and check whether
1177 // it matches this driver invocation pid.
1178 int CrashPID;
1179 if (OpenBracket < 0 || CloseBracket < 0 ||
1180 ParentProcess.slice(OpenBracket + 1, CloseBracket)
1181 .getAsInteger(10, CrashPID) || CrashPID != PID) {
1182 continue;
1183 }
1184
1185 // Found a .crash file matching the driver pid. To avoid getting an older
1186 // and misleading crash file, continue looking for the most recent.
1187 // FIXME: the driver can dispatch multiple cc1 invocations, leading to
1188 // multiple crashes poiting to the same parent process. Since the driver
1189 // does not collect pid information for the dispatched invocation there's
1190 // currently no way to distinguish among them.
1191 const auto FileAccessTime = FileStatus.getLastModificationTime();
1192 if (FileAccessTime > LastAccessTime) {
1193 CrashFilePath.assign(File->path());
1194 LastAccessTime = FileAccessTime;
1195 }
1196 }
1197
1198 // If found, copy it over to the location of other reproducer files.
1199 if (!CrashFilePath.empty()) {
1200 EC = fs::copy_file(CrashFilePath, ReproCrashFilename);
1201 if (EC)
1202 return false;
1203 return true;
1204 }
1205
1206 return false;
1207}
1208
Eric Christopherf901e852011-08-17 22:59:59 +00001209// When clang crashes, produce diagnostic information including the fully
1210// preprocessed source file(s). Request that the developer attach the
Chad Rosierbe10f982011-08-02 17:58:04 +00001211// diagnostic information to a bug report.
Alex Lorenz045c5142018-04-07 00:03:27 +00001212void Driver::generateCompilationDiagnostics(
1213 Compilation &C, const Command &FailingCommand,
1214 StringRef AdditionalInformation, CompilationDiagnosticReport *Report) {
Chad Rosier877c0a22012-02-22 00:30:39 +00001215 if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
Chad Rosier62135492012-07-09 17:31:28 +00001216 return;
Chad Rosierbee5a1d2012-03-07 00:30:40 +00001217
Chad Rosierdbf46a12013-02-01 18:30:26 +00001218 // Don't try to generate diagnostics for link or dsymutil jobs.
Justin Bognere1a33d12014-10-20 21:02:05 +00001219 if (FailingCommand.getCreator().isLinkJob() ||
1220 FailingCommand.getCreator().isDsymutilJob())
Chad Rosier877c0a22012-02-22 00:30:39 +00001221 return;
1222
Chad Rosier8179f112012-06-19 17:51:34 +00001223 // Print the version of the compiler.
1224 PrintVersion(C, llvm::errs());
1225
Chad Rosierbe10f982011-08-02 17:58:04 +00001226 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001227 << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the "
1228 "crash backtrace, preprocessed source, and associated run script.";
Chad Rosierbe10f982011-08-02 17:58:04 +00001229
1230 // Suppress driver output and emit preprocessor output to temp file.
Hans Wennborg70850d82013-07-18 20:29:38 +00001231 Mode = CPPMode;
Chad Rosierbe10f982011-08-02 17:58:04 +00001232 CCGenDiagnostics = true;
1233
Chad Rosiercdb008d2011-11-02 21:29:05 +00001234 // Save the original job command(s).
Justin Bogner25645152014-10-21 17:24:44 +00001235 Command Cmd = FailingCommand;
Chad Rosiercdb008d2011-11-02 21:29:05 +00001236
Richard Smith5bb4cdf2012-12-20 02:22:15 +00001237 // Keep track of whether we produce any errors while trying to produce
1238 // preprocessed sources.
1239 DiagnosticErrorTrap Trap(Diags);
1240
1241 // Suppress tool output.
Chad Rosierbe10f982011-08-02 17:58:04 +00001242 C.initCompilationForDiagnostics();
Chad Rosierecdede82011-08-12 22:08:57 +00001243
1244 // Construct the list of inputs.
1245 InputList Inputs;
1246 BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
Chad Rosierbe10f982011-08-02 17:58:04 +00001247
Chad Rosier4f81fc22011-08-12 23:30:05 +00001248 for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
Chad Rosierd57133d2011-08-18 00:22:25 +00001249 bool IgnoreInput = false;
1250
1251 // Ignore input from stdin or any inputs that cannot be preprocessed.
Paul Robinsonf44157d2014-04-28 22:24:44 +00001252 // Check type first as not all linker inputs have a value.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001253 if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
Paul Robinsonf44157d2014-04-28 22:24:44 +00001254 IgnoreInput = true;
1255 } else if (!strcmp(it->second->getValue(), "-")) {
Chad Rosierd57133d2011-08-18 00:22:25 +00001256 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001257 << "Error generating preprocessed source(s) - "
1258 "ignoring input from stdin.";
Chad Rosierd57133d2011-08-18 00:22:25 +00001259 IgnoreInput = true;
Chad Rosierd57133d2011-08-18 00:22:25 +00001260 }
1261
1262 if (IgnoreInput) {
Chad Rosier4f81fc22011-08-12 23:30:05 +00001263 it = Inputs.erase(it);
1264 ie = Inputs.end();
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001265 } else {
Chad Rosier4f81fc22011-08-12 23:30:05 +00001266 ++it;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001267 }
Chad Rosier4f81fc22011-08-12 23:30:05 +00001268 }
Chad Rosierd57133d2011-08-18 00:22:25 +00001269
Chad Rosierc5103c32013-01-29 23:57:10 +00001270 if (Inputs.empty()) {
1271 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001272 << "Error generating preprocessed source(s) - "
1273 "no preprocessable inputs.";
Chad Rosierc5103c32013-01-29 23:57:10 +00001274 return;
1275 }
1276
Chad Rosiere75ef402011-09-06 23:52:36 +00001277 // Don't attempt to generate preprocessed files if multiple -arch options are
Chad Rosier636d2832012-02-13 18:16:28 +00001278 // used, unless they're all duplicates.
1279 llvm::StringSet<> ArchNames;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00001280 for (const Arg *A : C.getArgs()) {
Chad Rosiere75ef402011-09-06 23:52:36 +00001281 if (A->getOption().matches(options::OPT_arch)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001282 StringRef ArchName = A->getValue();
Chad Rosier636d2832012-02-13 18:16:28 +00001283 ArchNames.insert(ArchName);
Chad Rosiere75ef402011-09-06 23:52:36 +00001284 }
1285 }
Chad Rosier636d2832012-02-13 18:16:28 +00001286 if (ArchNames.size() > 1) {
1287 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001288 << "Error generating preprocessed source(s) - cannot generate "
1289 "preprocessed source with multiple -arch options.";
Chad Rosier636d2832012-02-13 18:16:28 +00001290 return;
1291 }
Chad Rosiere75ef402011-09-06 23:52:36 +00001292
Chandler Carruth7f1417f2012-01-24 10:43:44 +00001293 // Construct the list of abstract actions to perform for this compilation. On
1294 // Darwin OSes this uses the driver-driver and builds universal actions.
Chandler Carruthcb916192012-01-25 08:49:21 +00001295 const ToolChain &TC = C.getDefaultToolChain();
Tim Northover157d9112014-01-16 08:48:16 +00001296 if (TC.getTriple().isOSBinFormatMachO())
Artem Belevich5e2a3ec2015-11-17 22:28:40 +00001297 BuildUniversalActions(C, TC, Inputs);
Chad Rosierbe10f982011-08-02 17:58:04 +00001298 else
Justin Lebar0f3474c2016-02-11 02:00:50 +00001299 BuildActions(C, C.getArgs(), Inputs, C.getActions());
Chad Rosierbe10f982011-08-02 17:58:04 +00001300
1301 BuildJobs(C);
1302
1303 // If there were errors building the compilation, quit now.
Richard Smith5bb4cdf2012-12-20 02:22:15 +00001304 if (Trap.hasErrorOccurred()) {
Chad Rosierbe10f982011-08-02 17:58:04 +00001305 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001306 << "Error generating preprocessed source(s).";
Chad Rosierbe10f982011-08-02 17:58:04 +00001307 return;
1308 }
1309
1310 // Generate preprocessed output.
Chad Rosierdd60e092013-01-29 20:15:05 +00001311 SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
Justin Bogner0cd92482015-07-02 22:52:08 +00001312 C.ExecuteJobs(C.getJobs(), FailingCommands);
Chad Rosierbe10f982011-08-02 17:58:04 +00001313
Justin Bognerbc89b182014-10-20 21:20:27 +00001314 // If any of the preprocessing commands failed, clean up and exit.
1315 if (!FailingCommands.empty()) {
Chad Rosierbe10f982011-08-02 17:58:04 +00001316 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001317 << "Error generating preprocessed source(s).";
Justin Bognerbc89b182014-10-20 21:20:27 +00001318 return;
Chad Rosierbe10f982011-08-02 17:58:04 +00001319 }
Justin Bognerbc89b182014-10-20 21:20:27 +00001320
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001321 const ArgStringList &TempFiles = C.getTempFiles();
1322 if (TempFiles.empty()) {
1323 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001324 << "Error generating preprocessed source(s).";
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001325 return;
1326 }
1327
Justin Bognerbc89b182014-10-20 21:20:27 +00001328 Diag(clang::diag::note_drv_command_failed_diag_msg)
1329 << "\n********************\n\n"
1330 "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
1331 "Preprocessed source(s) and associated run script(s) are located at:";
Justin Bognerbc89b182014-10-20 21:20:27 +00001332
Justin Bogner659ecc32014-10-20 22:47:23 +00001333 SmallString<128> VFS;
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +00001334 SmallString<128> ReproCrashFilename;
Justin Bogner659ecc32014-10-20 22:47:23 +00001335 for (const char *TempFile : TempFiles) {
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001336 Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
Alex Lorenz045c5142018-04-07 00:03:27 +00001337 if (Report)
1338 Report->TemporaryFiles.push_back(TempFile);
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +00001339 if (ReproCrashFilename.empty()) {
1340 ReproCrashFilename = TempFile;
1341 llvm::sys::path::replace_extension(ReproCrashFilename, ".crash");
1342 }
Justin Bogner659ecc32014-10-20 22:47:23 +00001343 if (StringRef(TempFile).endswith(".cache")) {
1344 // In some cases (modules) we'll dump extra data to help with reproducing
1345 // the crash into a directory next to the output.
1346 VFS = llvm::sys::path::filename(TempFile);
1347 llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
1348 }
1349 }
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001350
1351 // Assume associated files are based off of the first temporary file.
Justin Bogner25645152014-10-21 17:24:44 +00001352 CrashReportInfo CrashInfo(TempFiles[0], VFS);
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001353
Bob Haarman7e4d3ff2018-07-09 21:07:20 +00001354 llvm::SmallString<128> Script(CrashInfo.Filename);
1355 llvm::sys::path::replace_extension(Script, "sh");
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001356 std::error_code EC;
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001357 llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::CD_CreateNew);
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001358 if (EC) {
1359 Diag(clang::diag::note_drv_command_failed_diag_msg)
Bob Haarman7e4d3ff2018-07-09 21:07:20 +00001360 << "Error generating run script: " << Script << " " << EC.message();
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001361 } else {
Justin Bogner42220ed2015-03-12 00:14:35 +00001362 ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
Justin Bognered9cbe02015-07-09 06:58:31 +00001363 << "# Driver args: ";
1364 printArgList(ScriptOS, C.getInputArgs());
1365 ScriptOS << "# Original command: ";
Justin Bogner42220ed2015-03-12 00:14:35 +00001366 Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
Justin Bogner33bdbc62014-10-21 18:03:08 +00001367 Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
Alex Lorenz045c5142018-04-07 00:03:27 +00001368 if (!AdditionalInformation.empty())
1369 ScriptOS << "\n# Additional information: " << AdditionalInformation
1370 << "\n";
1371 if (Report)
Bob Haarman7e4d3ff2018-07-09 21:07:20 +00001372 Report->TemporaryFiles.push_back(Script.str());
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001373 Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
Justin Bognerbc89b182014-10-20 21:20:27 +00001374 }
Saleem Abdulrasool3661a822015-01-12 02:33:09 +00001375
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +00001376 // On darwin, provide information about the .crash diagnostic report.
1377 if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) {
1378 SmallString<128> CrashDiagDir;
1379 if (getCrashDiagnosticFile(ReproCrashFilename, CrashDiagDir)) {
1380 Diag(clang::diag::note_drv_command_failed_diag_msg)
1381 << ReproCrashFilename.str();
1382 } else { // Suggest a directory for the user to look for .crash files.
1383 llvm::sys::path::append(CrashDiagDir, Name);
1384 CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash";
1385 Diag(clang::diag::note_drv_command_failed_diag_msg)
1386 << "Crash backtrace is located in";
1387 Diag(clang::diag::note_drv_command_failed_diag_msg)
1388 << CrashDiagDir.str();
1389 Diag(clang::diag::note_drv_command_failed_diag_msg)
1390 << "(choose the .crash file that corresponds to your crash)";
1391 }
1392 }
1393
Saleem Abdulrasool3661a822015-01-12 02:33:09 +00001394 for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file,
1395 options::OPT_frewrite_map_file_EQ))
1396 Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
1397
Justin Bognerbc89b182014-10-20 21:20:27 +00001398 Diag(clang::diag::note_drv_command_failed_diag_msg)
1399 << "\n\n********************";
Chad Rosierbe10f982011-08-02 17:58:04 +00001400}
1401
Justin Bogner0cd92482015-07-02 22:52:08 +00001402void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
Oleg Ranevskyycd516372016-01-05 19:54:39 +00001403 // Since commandLineFitsWithinSystemLimits() may underestimate system's capacity
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001404 // if the tool does not support response files, there is a chance/ that things
1405 // will just work without a response file, so we silently just skip it.
Justin Bogner0cd92482015-07-02 22:52:08 +00001406 if (Cmd.getCreator().getResponseFilesSupport() == Tool::RF_None ||
Oleg Ranevskyycd516372016-01-05 19:54:39 +00001407 llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(), Cmd.getArguments()))
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001408 return;
1409
1410 std::string TmpName = GetTemporaryPath("response", "txt");
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00001411 Cmd.setResponseFile(C.addTempFile(C.getArgs().MakeArgString(TmpName)));
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001412}
1413
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001414int Driver::ExecuteCompilation(
1415 Compilation &C,
1416 SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001417 // Just print if -### was present.
1418 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
Hans Wennborgb212b342013-09-12 18:23:34 +00001419 C.getJobs().Print(llvm::errs(), "\n", true);
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001420 return 0;
1421 }
1422
1423 // If there were errors building the compilation, quit now.
Chad Rosierbe10f982011-08-02 17:58:04 +00001424 if (Diags.hasErrorOccurred())
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001425 return 1;
1426
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001427 // Set up response file names for each command, if necessary
Justin Bogner0cd92482015-07-02 22:52:08 +00001428 for (auto &Job : C.getJobs())
1429 setUpResponseFiles(C, Job);
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001430
Justin Bogner0cd92482015-07-02 22:52:08 +00001431 C.ExecuteJobs(C.getJobs(), FailingCommands);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001432
Daniel Dunbar07494792010-05-22 00:37:20 +00001433 // If the command succeeded, we are done.
Chad Rosierdd60e092013-01-29 20:15:05 +00001434 if (FailingCommands.empty())
1435 return 0;
Daniel Dunbar07494792010-05-22 00:37:20 +00001436
Chad Rosierdd60e092013-01-29 20:15:05 +00001437 // Otherwise, remove result files and print extra information about abnormal
1438 // failures.
Nick Desaulniers9d0df312018-10-15 17:39:00 +00001439 int Res = 0;
Douglas Katzman6bbffc42015-06-25 18:51:37 +00001440 for (const auto &CmdPair : FailingCommands) {
Nick Desaulniers9d0df312018-10-15 17:39:00 +00001441 int CommandRes = CmdPair.first;
Douglas Katzman6bbffc42015-06-25 18:51:37 +00001442 const Command *FailingCommand = CmdPair.second;
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001443
Chad Rosierdd60e092013-01-29 20:15:05 +00001444 // Remove result files if we're not saving temps.
Reid Kleckner68eb60b2015-02-02 22:41:48 +00001445 if (!isSaveTempsEnabled()) {
Chad Rosierdd60e092013-01-29 20:15:05 +00001446 const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
1447 C.CleanupFileMap(C.getResultFiles(), JA, true);
1448
1449 // Failure result files are valid unless we crashed.
Nick Desaulniers9d0df312018-10-15 17:39:00 +00001450 if (CommandRes < 0)
Chad Rosierdd60e092013-01-29 20:15:05 +00001451 C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
1452 }
1453
Nick Desaulniers9d0df312018-10-15 17:39:00 +00001454#if LLVM_ON_UNIX
1455 // llvm/lib/Support/Unix/Signals.inc will exit with a special return code
1456 // for SIGPIPE. Do not print diagnostics for this case.
1457 if (CommandRes == EX_IOERR) {
1458 Res = CommandRes;
1459 continue;
1460 }
1461#endif
1462
Chad Rosierdd60e092013-01-29 20:15:05 +00001463 // Print extra information about abnormal failures, if possible.
1464 //
1465 // This is ad-hoc, but we don't want to be excessively noisy. If the result
Justin Bogner5aaf2e72014-06-26 20:59:36 +00001466 // status was 1, assume the command failed normally. In particular, if it
Chad Rosierdd60e092013-01-29 20:15:05 +00001467 // was the compiler then assume it gave a reasonable error code. Failures
1468 // in other tools are less common, and they generally have worse
1469 // diagnostics, so always print the diagnostic there.
1470 const Tool &FailingTool = FailingCommand->getCreator();
1471
Nick Desaulniers9d0df312018-10-15 17:39:00 +00001472 if (!FailingCommand->getCreator().hasGoodDiagnostics() || CommandRes != 1) {
Chad Rosierdd60e092013-01-29 20:15:05 +00001473 // FIXME: See FIXME above regarding result code interpretation.
Nick Desaulniers9d0df312018-10-15 17:39:00 +00001474 if (CommandRes < 0)
Chad Rosierdd60e092013-01-29 20:15:05 +00001475 Diag(clang::diag::err_drv_command_signalled)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001476 << FailingTool.getShortName();
Chad Rosierdd60e092013-01-29 20:15:05 +00001477 else
Nick Desaulniers9d0df312018-10-15 17:39:00 +00001478 Diag(clang::diag::err_drv_command_failed)
1479 << FailingTool.getShortName() << CommandRes;
Chad Rosierdd60e092013-01-29 20:15:05 +00001480 }
Peter Collingbourne119cfaa2011-11-21 00:01:05 +00001481 }
Nick Desaulniers9d0df312018-10-15 17:39:00 +00001482 return Res;
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001483}
1484
Daniel Dunbara7b5e212009-04-15 16:34:29 +00001485void Driver::PrintHelp(bool ShowHidden) const {
Hans Wennborg6ddc6902013-07-27 00:23:45 +00001486 unsigned IncludedFlagsBitmask;
1487 unsigned ExcludedFlagsBitmask;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001488 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
Hans Wennborg797004d2018-11-08 11:27:04 +00001489 getIncludeExcludeOptionFlagMasks(IsCLMode());
Hans Wennborg6ddc6902013-07-27 00:23:45 +00001490
1491 ExcludedFlagsBitmask |= options::NoDriverOption;
1492 if (!ShowHidden)
1493 ExcludedFlagsBitmask |= HelpHidden;
1494
Fangrui Songd0028232018-10-10 00:15:33 +00001495 std::string Usage = llvm::formatv("{0} [options] file...", Name).str();
1496 getOpts().PrintHelp(llvm::outs(), Usage.c_str(), DriverTitle.c_str(),
George Rimar5dbfa4e2017-07-26 09:10:17 +00001497 IncludedFlagsBitmask, ExcludedFlagsBitmask,
1498 /*ShowAllAliases=*/false);
Daniel Dunbar7c925282009-03-31 21:38:17 +00001499}
1500
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001501void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001502 // FIXME: The following handlers should use a callback mechanism, we don't
1503 // know what the client would like to do.
Ted Kremenek4c0df3d2010-01-23 02:11:34 +00001504 OS << getClangFullVersion() << '\n';
Daniel Dunbarb10248802009-03-26 16:09:13 +00001505 const ToolChain &TC = C.getDefaultToolChain();
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001506 OS << "Target: " << TC.getTripleString() << '\n';
Daniel Dunbar10978e42009-06-16 23:32:58 +00001507
1508 // Print the threading model.
Jonathan Roelofsb140a102014-10-03 21:57:44 +00001509 if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
1510 // Don't print if the ToolChain would have barfed on it already
1511 if (TC.isThreadModelSupported(A->getValue()))
1512 OS << "Thread model: " << A->getValue();
1513 } else
1514 OS << "Thread model: " << TC.getThreadModel();
1515 OS << '\n';
Chandler Carruth9ade6a92015-08-05 17:07:33 +00001516
1517 // Print out the install directory.
1518 OS << "InstalledDir: " << InstalledDir << '\n';
Serge Pavlov208ac652018-01-01 13:27:01 +00001519
1520 // If configuration file was used, print its path.
1521 if (!ConfigFile.empty())
1522 OS << "Configuration file: " << ConfigFile << '\n';
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001523}
1524
Chris Lattner86ed5b02010-05-05 05:53:24 +00001525/// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
1526/// option.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001527static void PrintDiagnosticCategories(raw_ostream &OS) {
Argyrios Kyrtzidis0e37afa2011-05-25 05:05:01 +00001528 // Skip the empty category.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001529 for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
1530 ++i)
Argyrios Kyrtzidis0e37afa2011-05-25 05:05:01 +00001531 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
Chris Lattner86ed5b02010-05-05 05:53:24 +00001532}
1533
Yuka Takahashi41789e42018-03-05 08:54:20 +00001534void Driver::HandleAutocompletions(StringRef PassedFlags) const {
Yuka Takahashi503da8f2018-03-05 09:01:31 +00001535 if (PassedFlags == "")
1536 return;
Yuka Takahashi1a895202017-08-29 17:46:46 +00001537 // Print out all options that start with a given argument. This is used for
1538 // shell autocompletion.
1539 std::vector<std::string> SuggestedCompletions;
Yuka Takahashi41789e42018-03-05 08:54:20 +00001540 std::vector<std::string> Flags;
Yuka Takahashi1a895202017-08-29 17:46:46 +00001541
1542 unsigned short DisableFlags =
1543 options::NoDriverOption | options::Unsupported | options::Ignored;
Yuka Takahashi41789e42018-03-05 08:54:20 +00001544
Yuka Takahashi46106f52018-10-24 12:43:25 +00001545 // Distinguish "--autocomplete=-someflag" and "--autocomplete=-someflag,"
1546 // because the latter indicates that the user put space before pushing tab
1547 // which should end up in a file completion.
1548 const bool HasSpace = PassedFlags.endswith(",");
1549
Yuka Takahashi41789e42018-03-05 08:54:20 +00001550 // Parse PassedFlags by "," as all the command-line flags are passed to this
1551 // function separated by ","
1552 StringRef TargetFlags = PassedFlags;
1553 while (TargetFlags != "") {
1554 StringRef CurFlag;
1555 std::tie(CurFlag, TargetFlags) = TargetFlags.split(",");
1556 Flags.push_back(std::string(CurFlag));
Yuka Takahashi1a895202017-08-29 17:46:46 +00001557 }
1558
Yuka Takahashi41789e42018-03-05 08:54:20 +00001559 // We want to show cc1-only options only when clang is invoked with -cc1 or
1560 // -Xclang.
Yuka Takahashi503da8f2018-03-05 09:01:31 +00001561 if (std::find(Flags.begin(), Flags.end(), "-Xclang") != Flags.end() ||
1562 std::find(Flags.begin(), Flags.end(), "-cc1") != Flags.end())
Yuka Takahashi41789e42018-03-05 08:54:20 +00001563 DisableFlags &= ~options::NoDriverOption;
1564
1565 StringRef Cur;
1566 Cur = Flags.at(Flags.size() - 1);
1567 StringRef Prev;
1568 if (Flags.size() >= 2) {
1569 Prev = Flags.at(Flags.size() - 2);
1570 SuggestedCompletions = Opts->suggestValueCompletions(Prev, Cur);
1571 }
1572
1573 if (SuggestedCompletions.empty())
1574 SuggestedCompletions = Opts->suggestValueCompletions(Cur, "");
1575
Yuka Takahashi46106f52018-10-24 12:43:25 +00001576 // If Flags were empty, it means the user typed `clang [tab]` where we should
1577 // list all possible flags. If there was no value completion and the user
1578 // pressed tab after a space, we should fall back to a file completion.
1579 // We're printing a newline to be consistent with what we print at the end of
1580 // this function.
1581 if (SuggestedCompletions.empty() && HasSpace && !Flags.empty()) {
1582 llvm::outs() << '\n';
1583 return;
1584 }
1585
Yuka Takahashidf9c7e32018-10-24 08:24:16 +00001586 // When flag ends with '=' and there was no value completion, return empty
1587 // string and fall back to the file autocompletion.
1588 if (SuggestedCompletions.empty() && !Cur.endswith("=")) {
Yuka Takahashi1a895202017-08-29 17:46:46 +00001589 // If the flag is in the form of "--autocomplete=-foo",
1590 // we were requested to print out all option names that start with "-foo".
1591 // For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only".
Yuka Takahashi41789e42018-03-05 08:54:20 +00001592 SuggestedCompletions = Opts->findByPrefix(Cur, DisableFlags);
Yuka Takahashi1a895202017-08-29 17:46:46 +00001593
1594 // We have to query the -W flags manually as they're not in the OptTable.
1595 // TODO: Find a good way to add them to OptTable instead and them remove
1596 // this code.
1597 for (StringRef S : DiagnosticIDs::getDiagnosticFlags())
Yuka Takahashi41789e42018-03-05 08:54:20 +00001598 if (S.startswith(Cur))
Yuka Takahashi1a895202017-08-29 17:46:46 +00001599 SuggestedCompletions.push_back(S);
Yuka Takahashi1a895202017-08-29 17:46:46 +00001600 }
1601
1602 // Sort the autocomplete candidates so that shells print them out in a
1603 // deterministic order. We could sort in any way, but we chose
1604 // case-insensitive sorting for consistency with the -help option
1605 // which prints out options in the case-insensitive alphabetical order.
Fangrui Song55fab262018-09-26 22:16:28 +00001606 llvm::sort(SuggestedCompletions, [](StringRef A, StringRef B) {
1607 if (int X = A.compare_lower(B))
1608 return X < 0;
1609 return A.compare(B) > 0;
1610 });
Yuka Takahashi1a895202017-08-29 17:46:46 +00001611
1612 llvm::outs() << llvm::join(SuggestedCompletions, "\n") << '\n';
1613}
1614
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001615bool Driver::HandleImmediateArgs(const Compilation &C) {
Daniel Dunbar18974bd2010-06-11 22:00:19 +00001616 // The order these options are handled in gcc is all over the place, but we
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001617 // don't expect inconsistencies w.r.t. that to matter in practice.
Daniel Dunbar7c925282009-03-31 21:38:17 +00001618
Daniel Dunbar1b09e042010-09-17 02:47:28 +00001619 if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
1620 llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
1621 return false;
1622 }
1623
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001624 if (C.getArgs().hasArg(options::OPT_dumpversion)) {
Daniel Dunbare26e5002011-01-12 00:43:47 +00001625 // Since -dumpversion is only implemented for pedantic GCC compatibility, we
1626 // return an answer which matches our definition of __VERSION__.
1627 //
1628 // If we want to return a more correct answer some day, then we should
1629 // introduce a non-pedantically GCC compatible mode to Clang in which we
1630 // provide sensible definitions for -dumpversion, __VERSION__, etc.
1631 llvm::outs() << "4.2.1\n";
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001632 return false;
1633 }
Daniel Dunbarfb3d7472010-06-14 21:23:12 +00001634
Chris Lattner86ed5b02010-05-05 05:53:24 +00001635 if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
1636 PrintDiagnosticCategories(llvm::outs());
1637 return false;
1638 }
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001639
James Molloya3c85b82012-05-01 14:57:16 +00001640 if (C.getArgs().hasArg(options::OPT_help) ||
Daniel Dunbara7b5e212009-04-15 16:34:29 +00001641 C.getArgs().hasArg(options::OPT__help_hidden)) {
1642 PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
Daniel Dunbar7c925282009-03-31 21:38:17 +00001643 return false;
1644 }
1645
Daniel Dunbarb0006ae2009-04-02 15:05:41 +00001646 if (C.getArgs().hasArg(options::OPT__version)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001647 // Follow gcc behavior and use stdout for --version and stderr for -v.
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001648 PrintVersion(C, llvm::outs());
Daniel Dunbarb0006ae2009-04-02 15:05:41 +00001649 return false;
1650 }
1651
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001652 if (C.getArgs().hasArg(options::OPT_v) ||
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001653 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001654 PrintVersion(C, llvm::errs());
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001655 SuppressMissingInputWarning = true;
1656 }
1657
Serge Pavlov208ac652018-01-01 13:27:01 +00001658 if (C.getArgs().hasArg(options::OPT_v)) {
1659 if (!SystemConfigDir.empty())
1660 llvm::errs() << "System configuration file directory: "
1661 << SystemConfigDir << "\n";
1662 if (!UserConfigDir.empty())
1663 llvm::errs() << "User configuration file directory: "
1664 << UserConfigDir << "\n";
1665 }
1666
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001667 const ToolChain &TC = C.getDefaultToolChain();
Chandler Carruth0ae39aa2013-07-30 17:57:09 +00001668
1669 if (C.getArgs().hasArg(options::OPT_v))
1670 TC.printVerboseInfo(llvm::errs());
1671
Meador Inge51208a32017-04-04 21:46:50 +00001672 if (C.getArgs().hasArg(options::OPT_print_resource_dir)) {
Meador Ingea9113952017-04-05 22:27:20 +00001673 llvm::outs() << ResourceDir << '\n';
Meador Inge51208a32017-04-04 21:46:50 +00001674 return false;
1675 }
1676
Daniel Dunbard972e222009-03-20 04:37:21 +00001677 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
1678 llvm::outs() << "programs: =";
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001679 bool separator = false;
1680 for (const std::string &Path : TC.getProgramPaths()) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001681 if (separator)
1682 llvm::outs() << ':';
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001683 llvm::outs() << Path;
1684 separator = true;
Daniel Dunbard972e222009-03-20 04:37:21 +00001685 }
1686 llvm::outs() << "\n";
Peter Collingbournefa9771f2011-09-06 02:08:31 +00001687 llvm::outs() << "libraries: =" << ResourceDir;
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001688
Sebastian Pop980920a2012-04-16 04:16:43 +00001689 StringRef sysroot = C.getSysRoot();
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001690
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001691 for (const std::string &Path : TC.getFilePaths()) {
1692 // Always print a separator. ResourceDir was the first item shown.
Peter Collingbournefa9771f2011-09-06 02:08:31 +00001693 llvm::outs() << ':';
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001694 // Interpretation of leading '=' is needed only for NetBSD.
1695 if (Path[0] == '=')
Douglas Katzman26eabf62015-06-24 15:10:30 +00001696 llvm::outs() << sysroot << Path.substr(1);
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001697 else
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001698 llvm::outs() << Path;
Daniel Dunbard972e222009-03-20 04:37:21 +00001699 }
1700 llvm::outs() << "\n";
Daniel Dunbar7c925282009-03-31 21:38:17 +00001701 return false;
Daniel Dunbard972e222009-03-20 04:37:21 +00001702 }
1703
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001704 // FIXME: The following handlers should use a callback mechanism, we don't
1705 // know what the client would like to do.
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001706 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001707 llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001708 return false;
1709 }
1710
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001711 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
Saleem Abdulrasoole5f3cf82018-05-01 18:40:42 +00001712 StringRef ProgName = A->getValue();
1713
1714 // Null program name cannot have a path.
1715 if (! ProgName.empty())
1716 llvm::outs() << GetProgramPath(ProgName, TC);
1717
1718 llvm::outs() << "\n";
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001719 return false;
1720 }
1721
Yuka Takahashic8068db2017-05-23 18:39:08 +00001722 if (Arg *A = C.getArgs().getLastArg(options::OPT_autocomplete)) {
Yuka Takahashiba5d4af2017-06-20 16:31:31 +00001723 StringRef PassedFlags = A->getValue();
Yuka Takahashi41789e42018-03-05 08:54:20 +00001724 HandleAutocompletions(PassedFlags);
Yuka Takahashic8068db2017-05-23 18:39:08 +00001725 return false;
1726 }
1727
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001728 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
Michal Gorny7cfe4802016-10-10 12:23:40 +00001729 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(C.getArgs());
Leo Li23bb21c2017-08-24 01:51:51 +00001730 const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
1731 RegisterEffectiveTriple TripleRAII(TC, Triple);
Michal Gorny7cfe4802016-10-10 12:23:40 +00001732 switch (RLT) {
1733 case ToolChain::RLT_CompilerRT:
1734 llvm::outs() << TC.getCompilerRT(C.getArgs(), "builtins") << "\n";
1735 break;
1736 case ToolChain::RLT_Libgcc:
1737 llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
1738 break;
1739 }
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001740 return false;
1741 }
1742
Daniel Dunbar1b3ec3a2009-06-16 23:25:22 +00001743 if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
Douglas Katzmana34b7bf2015-06-30 19:32:57 +00001744 for (const Multilib &Multilib : TC.getMultilibs())
1745 llvm::outs() << Multilib << "\n";
Daniel Dunbar1b3ec3a2009-06-16 23:25:22 +00001746 return false;
1747 }
1748
Jonathan Roelofs2cea1be2014-02-12 03:21:20 +00001749 if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
Christian Bruel6ccc4a72018-09-06 14:03:44 +00001750 const Multilib &Multilib = TC.getMultilib();
1751 if (Multilib.gccSuffix().empty())
1752 llvm::outs() << ".\n";
1753 else {
1754 StringRef Suffix(Multilib.gccSuffix());
1755 assert(Suffix.front() == '/');
1756 llvm::outs() << Suffix.substr(1) << "\n";
Jonathan Roelofs3fa96d82014-02-12 01:36:51 +00001757 }
Jonathan Roelofs0e7ec602014-02-12 01:29:25 +00001758 return false;
1759 }
Petr Hosekbc86a992018-08-16 00:22:03 +00001760
1761 if (C.getArgs().hasArg(options::OPT_print_target_triple)) {
1762 llvm::outs() << TC.getTripleString() << "\n";
1763 return false;
1764 }
1765
1766 if (C.getArgs().hasArg(options::OPT_print_effective_triple)) {
1767 const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
1768 llvm::outs() << Triple.getTriple() << "\n";
1769 return false;
1770 }
1771
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001772 return true;
1773}
1774
Douglas Katzmanfd528672015-06-11 15:05:22 +00001775// Display an action graph human-readably. Action A is the "sink" node
1776// and latest-occuring action. Traversal is in pre-order, visiting the
1777// inputs to each action before printing the action itself.
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001778static unsigned PrintActions1(const Compilation &C, Action *A,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001779 std::map<Action *, unsigned> &Ids) {
Douglas Katzmanfd528672015-06-11 15:05:22 +00001780 if (Ids.count(A)) // A was already visited.
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001781 return Ids[A];
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001782
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001783 std::string str;
1784 llvm::raw_string_ostream os(str);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001785
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001786 os << Action::getClassName(A->getKind()) << ", ";
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001787 if (InputAction *IA = dyn_cast<InputAction>(A)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001788 os << "\"" << IA->getInputArg().getValue() << "\"";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001789 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001790 os << '"' << BIA->getArchName() << '"' << ", {"
Nico Weber5a459f82016-02-23 19:30:43 +00001791 << PrintActions1(C, *BIA->input_begin(), Ids) << "}";
Samuel Antaod06239d2016-07-15 23:13:27 +00001792 } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
1793 bool IsFirst = true;
1794 OA->doOnEachDependence(
1795 [&](Action *A, const ToolChain *TC, const char *BoundArch) {
1796 // E.g. for two CUDA device dependences whose bound arch is sm_20 and
1797 // sm_35 this will generate:
1798 // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
1799 // (nvptx64-nvidia-cuda:sm_35) {#ID}
1800 if (!IsFirst)
1801 os << ", ";
1802 os << '"';
1803 if (TC)
1804 os << A->getOffloadingKindPrefix();
1805 else
1806 os << "host";
1807 os << " (";
1808 os << TC->getTriple().normalize();
1809
1810 if (BoundArch)
1811 os << ":" << BoundArch;
1812 os << ")";
1813 os << '"';
1814 os << " {" << PrintActions1(C, A, Ids) << "}";
1815 IsFirst = false;
1816 });
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001817 } else {
Samuel Antaod06239d2016-07-15 23:13:27 +00001818 const ActionList *AL = &A->getInputs();
Artem Belevich0ff05cd2015-07-13 23:27:56 +00001819
Artem Belevich23256752015-09-22 17:23:09 +00001820 if (AL->size()) {
1821 const char *Prefix = "{";
1822 for (Action *PreRequisite : *AL) {
1823 os << Prefix << PrintActions1(C, PreRequisite, Ids);
1824 Prefix = ", ";
1825 }
1826 os << "}";
1827 } else
1828 os << "{}";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001829 }
1830
Samuel Antaod06239d2016-07-15 23:13:27 +00001831 // Append offload info for all options other than the offloading action
1832 // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
1833 std::string offload_str;
1834 llvm::raw_string_ostream offload_os(offload_str);
1835 if (!isa<OffloadAction>(A)) {
1836 auto S = A->getOffloadingKindPrefix();
1837 if (!S.empty()) {
1838 offload_os << ", (" << S;
1839 if (A->getOffloadingArch())
1840 offload_os << ", " << A->getOffloadingArch();
1841 offload_os << ")";
1842 }
1843 }
1844
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001845 unsigned Id = Ids.size();
1846 Ids[A] = Id;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001847 llvm::errs() << Id << ": " << os.str() << ", "
Samuel Antaod06239d2016-07-15 23:13:27 +00001848 << types::getTypeName(A->getType()) << offload_os.str() << "\n";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001849
1850 return Id;
1851}
1852
Douglas Katzmanfd528672015-06-11 15:05:22 +00001853// Print the action graphs in a compilation C.
1854// For example "clang -c file1.c file2.c" is composed of two subgraphs.
Daniel Dunbareb843be2009-03-18 03:13:20 +00001855void Driver::PrintActions(const Compilation &C) const {
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001856 std::map<Action *, unsigned> Ids;
1857 for (Action *A : C.getActions())
1858 PrintActions1(C, A, Ids);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001859}
1860
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001861/// Check whether the given input tree contains any compilation or
Joerg Sonnenberger5fe4a7d2011-05-06 14:05:11 +00001862/// assembly actions.
1863static bool ContainsCompileOrAssembleAction(const Action *A) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001864 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
Bob Wilson23a55f12014-12-21 07:00:00 +00001865 isa<AssembleJobAction>(A))
Daniel Dunbar00d3d8e2010-06-29 16:38:33 +00001866 return true;
1867
Nico Weber5a459f82016-02-23 19:30:43 +00001868 for (const Action *Input : A->inputs())
Nico Weberfb80f962015-09-19 21:36:51 +00001869 if (ContainsCompileOrAssembleAction(Input))
Daniel Dunbar00d3d8e2010-06-29 16:38:33 +00001870 return true;
1871
1872 return false;
1873}
1874
Artem Belevich5e2a3ec2015-11-17 22:28:40 +00001875void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
1876 const InputList &BAInputs) const {
1877 DerivedArgList &Args = C.getArgs();
1878 ActionList &Actions = C.getActions();
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001879 llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
1880 // Collect the list of architectures. Duplicates are allowed, but should only
1881 // be handled once (in the order seen).
Daniel Dunbare5dc4822009-03-13 20:33:35 +00001882 llvm::StringSet<> ArchNames;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001883 SmallVector<const char *, 4> Archs;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00001884 for (Arg *A : Args) {
Daniel Dunbar0bfb21e2009-11-19 03:26:40 +00001885 if (A->getOption().matches(options::OPT_arch)) {
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001886 // Validate the option here; we don't save the type here because its
1887 // particular spelling may participate in other driver choices.
1888 llvm::Triple::ArchType Arch =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001889 tools::darwin::getArchTypeForMachOArchName(A->getValue());
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001890 if (Arch == llvm::Triple::UnknownArch) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001891 Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001892 continue;
1893 }
1894
Daniel Dunbar2da02722009-03-19 07:55:12 +00001895 A->claim();
David Blaikie61b86d42014-11-19 02:56:13 +00001896 if (ArchNames.insert(A->getValue()).second)
Richard Smithbd55daf2012-11-01 04:30:05 +00001897 Archs.push_back(A->getValue());
Daniel Dunbarf479c122009-03-12 18:40:18 +00001898 }
1899 }
1900
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001901 // When there is no explicit arch for this platform, make sure we still bind
1902 // the architecture (to the default) so that -Xarch_ is handled correctly.
Daniel Dunbareb843be2009-03-18 03:13:20 +00001903 if (!Archs.size())
Daniel Dunbarc3bd9f52012-11-08 03:38:26 +00001904 Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
Daniel Dunbarf479c122009-03-12 18:40:18 +00001905
Daniel Dunbarf479c122009-03-12 18:40:18 +00001906 ActionList SingleActions;
Justin Lebar0f3474c2016-02-11 02:00:50 +00001907 BuildActions(C, Args, BAInputs, SingleActions);
Daniel Dunbarf479c122009-03-12 18:40:18 +00001908
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001909 // Add in arch bindings for every top level action, as well as lipo and
1910 // dsymutil steps if needed.
Nico Weberfb80f962015-09-19 21:36:51 +00001911 for (Action* Act : SingleActions) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001912 // Make sure we can lipo this kind of output. If not (and it is an actual
1913 // output) then we disallow, since we can't create an output file with the
1914 // right name without overwriting it. We could remove this oddity by just
1915 // changing the output names to include the arch, which would also fix
Daniel Dunbarf479c122009-03-12 18:40:18 +00001916 // -save-temps. Compatibility wins for now.
1917
Daniel Dunbare2ca3bd2009-03-13 17:46:02 +00001918 if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
Daniel Dunbarf479c122009-03-12 18:40:18 +00001919 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001920 << types::getTypeName(Act->getType());
Daniel Dunbarf479c122009-03-12 18:40:18 +00001921
1922 ActionList Inputs;
Justin Lebar41094612016-01-11 23:07:27 +00001923 for (unsigned i = 0, e = Archs.size(); i != e; ++i)
1924 Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
Daniel Dunbarf479c122009-03-12 18:40:18 +00001925
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001926 // Lipo if necessary, we do it this way because we need to set the arch flag
1927 // so that -Xarch_ gets overwritten.
Daniel Dunbarf479c122009-03-12 18:40:18 +00001928 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
1929 Actions.append(Inputs.begin(), Inputs.end());
1930 else
Justin Lebar41094612016-01-11 23:07:27 +00001931 Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001932
Eric Christopher65c05fa2012-02-06 19:43:51 +00001933 // Handle debug info queries.
1934 Arg *A = Args.getLastArg(options::OPT_g_Group);
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001935 if (A && !A->getOption().matches(options::OPT_g0) &&
1936 !A->getOption().matches(options::OPT_gstabs) &&
1937 ContainsCompileOrAssembleAction(Actions.back())) {
Chad Rosier62135492012-07-09 17:31:28 +00001938
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001939 // Add a 'dsymutil' step if necessary, when debug info is enabled and we
1940 // have a compile input. We need to run 'dsymutil' ourselves in such cases
Eric Christopher776c26f2013-01-28 17:39:03 +00001941 // because the debug info will refer to a temporary object file which
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001942 // will be removed at the end of the compilation process.
1943 if (Act->getType() == types::TY_Image) {
1944 ActionList Inputs;
1945 Inputs.push_back(Actions.back());
1946 Actions.pop_back();
Justin Lebar41094612016-01-11 23:07:27 +00001947 Actions.push_back(
1948 C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001949 }
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001950
Ben Langmuir9b9a8d32014-02-06 18:53:25 +00001951 // Verify the debug info output.
Alp Tokere9d2bfc2014-01-17 02:06:23 +00001952 if (Args.hasArg(options::OPT_verify_debug_info)) {
Justin Lebar41094612016-01-11 23:07:27 +00001953 Action* LastAction = Actions.back();
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001954 Actions.pop_back();
Justin Lebar41094612016-01-11 23:07:27 +00001955 Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
1956 LastAction, types::TY_Nothing));
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001957 }
1958 }
Daniel Dunbarf479c122009-03-12 18:40:18 +00001959 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001960}
1961
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001962/// Check that the file referenced by Value exists. If it doesn't,
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001963/// issue a diagnostic and return false.
Alp Toker8c8a8752013-12-03 06:53:35 +00001964static bool DiagnoseInputExistence(const Driver &D, const DerivedArgList &Args,
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001965 StringRef Value, types::ID Ty) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001966 if (!D.getCheckInputsExist())
1967 return true;
1968
1969 // stdin always exists.
1970 if (Value == "-")
1971 return true;
1972
1973 SmallString<64> Path(Value);
1974 if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
Yaron Keren92e1b622015-03-18 10:17:07 +00001975 if (!llvm::sys::path::is_absolute(Path)) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001976 SmallString<64> Directory(WorkDir->getValue());
1977 llvm::sys::path::append(Directory, Value);
1978 Path.assign(Directory);
1979 }
1980 }
1981
Sam McCall2c782472018-11-08 16:57:01 +00001982 if (D.getVFS().exists(Path))
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001983 return true;
1984
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001985 if (D.IsCLMode()) {
1986 if (!llvm::sys::path::is_absolute(Twine(Path)) &&
1987 llvm::sys::Process::FindInEnvPath("LIB", Value))
1988 return true;
1989
1990 if (Args.hasArg(options::OPT__SLASH_link) && Ty == types::TY_Object) {
1991 // Arguments to the /link flag might cause the linker to search for object
1992 // and library files in paths we don't know about. Don't error in such
1993 // cases.
1994 return true;
1995 }
1996 }
Hans Wennborg23d26a32014-06-18 17:21:50 +00001997
Yaron Keren92e1b622015-03-18 10:17:07 +00001998 D.Diag(clang::diag::err_drv_no_such_file) << Path;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001999 return false;
2000}
2001
Chad Rosierecdede82011-08-12 22:08:57 +00002002// Construct a the list of inputs and their types.
Hans Wennborg55362852014-05-02 22:55:30 +00002003void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
Chad Rosierecdede82011-08-12 22:08:57 +00002004 InputList &Inputs) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002005 // Track the current user specified (-x) input. We also explicitly track the
2006 // argument used to set the type; we only want to claim the type when we
2007 // actually use it, so we warn about unused -x arguments.
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00002008 types::ID InputType = types::TY_Nothing;
Craig Topper92fc2df2014-05-17 16:56:41 +00002009 Arg *InputTypeArg = nullptr;
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00002010
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00002011 // The last /TC or /TP option sets the input type to C or C++ globally.
Ehsan Akhgaric249abb2014-09-12 21:44:24 +00002012 if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
2013 options::OPT__SLASH_TP)) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00002014 InputTypeArg = TCTP;
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00002015 InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002016 ? types::TY_C
2017 : types::TY_CXX;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00002018
Richard Smith0aef3052017-02-18 01:14:43 +00002019 Arg *Previous = nullptr;
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00002020 bool ShowNote = false;
Richard Smith0aef3052017-02-18 01:14:43 +00002021 for (Arg *A : Args.filtered(options::OPT__SLASH_TC, options::OPT__SLASH_TP)) {
2022 if (Previous) {
2023 Diag(clang::diag::warn_drv_overriding_flag_option)
2024 << Previous->getSpelling() << A->getSpelling();
2025 ShowNote = true;
2026 }
2027 Previous = A;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00002028 }
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00002029 if (ShowNote)
2030 Diag(clang::diag::note_drv_t_option_is_global);
Hans Wennborg6ee64d52013-08-06 00:20:31 +00002031
2032 // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
2033 assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
2034 }
2035
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00002036 for (Arg *A : Args) {
Michael J. Spencerad3ccc32012-08-20 21:41:17 +00002037 if (A->getOption().getKind() == Option::InputClass) {
Richard Smithbd55daf2012-11-01 04:30:05 +00002038 const char *Value = A->getValue();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002039 types::ID Ty = types::TY_INVALID;
2040
2041 // Infer the input type if necessary.
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00002042 if (InputType == types::TY_Nothing) {
2043 // If there was an explicit arg for this, claim it.
2044 if (InputTypeArg)
2045 InputTypeArg->claim();
2046
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002047 // stdin must be handled specially.
2048 if (memcmp(Value, "-", 2) == 0) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002049 // If running with -E, treat as a C input (this changes the builtin
2050 // macros, for example). This may be overridden by -ObjC below.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002051 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002052 // Otherwise emit an error but still use a valid type to avoid
2053 // spurious errors (e.g., no inputs).
Hans Wennborg70850d82013-07-18 20:29:38 +00002054 if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
Hans Wennborgcfdd8b52014-01-29 01:04:40 +00002055 Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
2056 : clang::diag::err_drv_unknown_stdin_type);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002057 Ty = types::TY_C;
2058 } else {
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00002059 // Otherwise lookup by extension.
Reid Klecknera643e642018-12-26 21:04:08 +00002060 // Fallback is C if invoked as C preprocessor, C++ if invoked with
2061 // clang-cl /E, or Object otherwise.
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00002062 // We use a host hook here because Darwin at least has its own
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002063 // idea of what .s is.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002064 if (const char *Ext = strrchr(Value, '.'))
Daniel Dunbarcc7df6c2010-08-02 05:43:56 +00002065 Ty = TC.LookupTypeForExtension(Ext + 1);
Daniel Dunbarea9f0322009-03-20 23:39:23 +00002066
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00002067 if (Ty == types::TY_INVALID) {
Hans Wennborg70850d82013-07-18 20:29:38 +00002068 if (CCCIsCPP())
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00002069 Ty = types::TY_C;
Reid Klecknera643e642018-12-26 21:04:08 +00002070 else if (IsCLMode() && Args.hasArgNoClaim(options::OPT_E))
2071 Ty = types::TY_CXX;
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00002072 else
2073 Ty = types::TY_Object;
2074 }
Daniel Dunbar0ac94452010-02-17 20:32:58 +00002075
2076 // If the driver is invoked as C++ compiler (like clang++ or c++) it
2077 // should autodetect some input files as C++ for g++ compatibility.
Hans Wennborg70850d82013-07-18 20:29:38 +00002078 if (CCCIsCXX()) {
Daniel Dunbar0ac94452010-02-17 20:32:58 +00002079 types::ID OldTy = Ty;
2080 Ty = types::lookupCXXTypeForCType(Ty);
2081
2082 if (Ty != OldTy)
2083 Diag(clang::diag::warn_drv_treating_input_as_cxx)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002084 << getTypeName(OldTy) << getTypeName(Ty);
Daniel Dunbar0ac94452010-02-17 20:32:58 +00002085 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002086 }
2087
Daniel Dunbar82b22102009-05-18 21:47:54 +00002088 // -ObjC and -ObjC++ override the default language, but only for "source
2089 // files". We just treat everything that isn't a linker input as a
2090 // source file.
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002091 //
Daniel Dunbar82b22102009-05-18 21:47:54 +00002092 // FIXME: Clean this up if we move the phase sequence into the type.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002093 if (Ty != types::TY_Object) {
2094 if (Args.hasArg(options::OPT_ObjC))
2095 Ty = types::TY_ObjC;
2096 else if (Args.hasArg(options::OPT_ObjCXX))
2097 Ty = types::TY_ObjCXX;
2098 }
2099 } else {
2100 assert(InputTypeArg && "InputType set w/o InputTypeArg");
Ehsan Akhgari7e954ea2014-09-12 18:15:10 +00002101 if (!InputTypeArg->getOption().matches(options::OPT_x)) {
2102 // If emulating cl.exe, make sure that /TC and /TP don't affect input
2103 // object files.
2104 const char *Ext = strrchr(Value, '.');
2105 if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
2106 Ty = types::TY_Object;
2107 }
2108 if (Ty == types::TY_INVALID) {
2109 Ty = InputType;
2110 InputTypeArg->claim();
2111 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002112 }
2113
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00002114 if (DiagnoseInputExistence(*this, Args, Value, Ty))
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002115 Inputs.push_back(std::make_pair(Ty, A));
2116
Hans Wennborg6ee64d52013-08-06 00:20:31 +00002117 } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
2118 StringRef Value = A->getValue();
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00002119 if (DiagnoseInputExistence(*this, Args, Value, types::TY_C)) {
David Blaikie0aaa7622017-01-13 17:34:15 +00002120 Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
Hans Wennborg6ee64d52013-08-06 00:20:31 +00002121 Inputs.push_back(std::make_pair(types::TY_C, InputArg));
2122 }
2123 A->claim();
2124 } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
2125 StringRef Value = A->getValue();
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00002126 if (DiagnoseInputExistence(*this, Args, Value, types::TY_CXX)) {
David Blaikie0aaa7622017-01-13 17:34:15 +00002127 Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
Hans Wennborg6ee64d52013-08-06 00:20:31 +00002128 Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
2129 }
2130 A->claim();
Michael J. Spencer66e2b202012-10-19 22:37:06 +00002131 } else if (A->getOption().hasFlag(options::LinkerInput)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002132 // Just treat as object type, we could make a special type for this if
2133 // necessary.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002134 Inputs.push_back(std::make_pair(types::TY_Object, A));
2135
Daniel Dunbar0bfb21e2009-11-19 03:26:40 +00002136 } else if (A->getOption().matches(options::OPT_x)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002137 InputTypeArg = A;
Richard Smithbd55daf2012-11-01 04:30:05 +00002138 InputType = types::lookupTypeForTypeSpecifier(A->getValue());
Chad Rosier706c2352012-04-07 00:01:31 +00002139 A->claim();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002140
2141 // Follow gcc behavior and treat as linker input for invalid -x
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002142 // options. Its not clear why we shouldn't just revert to unknown; but
Michael J. Spencer1a4fe8c2010-12-17 21:22:33 +00002143 // this isn't very important, we might as well be bug compatible.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002144 if (!InputType) {
Richard Smithbd55daf2012-11-01 04:30:05 +00002145 Diag(clang::diag::err_drv_unknown_language) << A->getValue();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002146 InputType = types::TY_Object;
2147 }
Hans Wennborg091f1b62017-01-27 17:09:41 +00002148 } else if (A->getOption().getID() == options::OPT__SLASH_U) {
2149 assert(A->getNumValues() == 1 && "The /U option has one value.");
2150 StringRef Val = A->getValue(0);
2151 if (Val.find_first_of("/\\") != StringRef::npos) {
2152 // Warn about e.g. "/Users/me/myfile.c".
2153 Diag(diag::warn_slash_u_filename) << Val;
2154 Diag(diag::note_use_dashdash);
2155 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002156 }
2157 }
Hans Wennborg70850d82013-07-18 20:29:38 +00002158 if (CCCIsCPP() && Inputs.empty()) {
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00002159 // If called as standalone preprocessor, stdin is processed
2160 // if no other input is present.
David Blaikie0aaa7622017-01-13 17:34:15 +00002161 Arg *A = MakeInputArg(Args, *Opts, "-");
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00002162 Inputs.push_back(std::make_pair(types::TY_C, A));
2163 }
Chad Rosierecdede82011-08-12 22:08:57 +00002164}
2165
Samuel Antao64e965e2016-09-30 15:34:19 +00002166namespace {
2167/// Provides a convenient interface for different programming models to generate
2168/// the required device actions.
2169class OffloadingActionBuilder final {
2170 /// Flag used to trace errors in the builder.
2171 bool IsValid = false;
2172
2173 /// The compilation that is using this builder.
2174 Compilation &C;
2175
Samuel Antao64e965e2016-09-30 15:34:19 +00002176 /// Map between an input argument and the offload kinds used to process it.
2177 std::map<const Arg *, unsigned> InputArgToOffloadKindMap;
2178
2179 /// Builder interface. It doesn't build anything or keep any state.
2180 class DeviceActionBuilder {
2181 public:
2182 typedef llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PhasesTy;
2183
2184 enum ActionBuilderReturnCode {
2185 // The builder acted successfully on the current action.
2186 ABRT_Success,
2187 // The builder didn't have to act on the current action.
2188 ABRT_Inactive,
2189 // The builder was successful and requested the host action to not be
2190 // generated.
2191 ABRT_Ignore_Host,
2192 };
2193
2194 protected:
2195 /// Compilation associated with this builder.
2196 Compilation &C;
2197
2198 /// Tool chains associated with this builder. The same programming
2199 /// model may have associated one or more tool chains.
2200 SmallVector<const ToolChain *, 2> ToolChains;
2201
2202 /// The derived arguments associated with this builder.
2203 DerivedArgList &Args;
2204
2205 /// The inputs associated with this builder.
2206 const Driver::InputList &Inputs;
2207
2208 /// The associated offload kind.
2209 Action::OffloadKind AssociatedOffloadKind = Action::OFK_None;
2210
2211 public:
2212 DeviceActionBuilder(Compilation &C, DerivedArgList &Args,
2213 const Driver::InputList &Inputs,
2214 Action::OffloadKind AssociatedOffloadKind)
2215 : C(C), Args(Args), Inputs(Inputs),
2216 AssociatedOffloadKind(AssociatedOffloadKind) {}
2217 virtual ~DeviceActionBuilder() {}
2218
2219 /// Fill up the array \a DA with all the device dependences that should be
2220 /// added to the provided host action \a HostAction. By default it is
2221 /// inactive.
2222 virtual ActionBuilderReturnCode
Samuel Antao28c4f182016-10-27 17:08:03 +00002223 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2224 phases::ID CurPhase, phases::ID FinalPhase,
2225 PhasesTy &Phases) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002226 return ABRT_Inactive;
2227 }
2228
2229 /// Update the state to include the provided host action \a HostAction as a
2230 /// dependency of the current device action. By default it is inactive.
2231 virtual ActionBuilderReturnCode addDeviceDepences(Action *HostAction) {
2232 return ABRT_Inactive;
2233 }
2234
2235 /// Append top level actions generated by the builder. Return true if errors
2236 /// were found.
2237 virtual void appendTopLevelActions(ActionList &AL) {}
2238
2239 /// Append linker actions generated by the builder. Return true if errors
2240 /// were found.
2241 virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {}
2242
2243 /// Initialize the builder. Return true if any initialization errors are
2244 /// found.
2245 virtual bool initialize() { return false; }
2246
Samuel Antao69d6f312016-10-27 17:50:43 +00002247 /// Return true if the builder can use bundling/unbundling.
2248 virtual bool canUseBundlerUnbundler() const { return false; }
2249
Samuel Antao64e965e2016-09-30 15:34:19 +00002250 /// Return true if this builder is valid. We have a valid builder if we have
2251 /// associated device tool chains.
2252 bool isValid() { return !ToolChains.empty(); }
2253
2254 /// Return the associated offload kind.
2255 Action::OffloadKind getAssociatedOffloadKind() {
2256 return AssociatedOffloadKind;
2257 }
2258 };
2259
Yaxun Liu3af038b2018-05-30 00:49:10 +00002260 /// Base class for CUDA/HIP action builder. It injects device code in
2261 /// the host backend action.
2262 class CudaActionBuilderBase : public DeviceActionBuilder {
2263 protected:
Samuel Antao64e965e2016-09-30 15:34:19 +00002264 /// Flags to signal if the user requested host-only or device-only
2265 /// compilation.
2266 bool CompileHostOnly = false;
2267 bool CompileDeviceOnly = false;
2268
2269 /// List of GPU architectures to use in this compilation.
2270 SmallVector<CudaArch, 4> GpuArchList;
2271
2272 /// The CUDA actions for the current input.
2273 ActionList CudaDeviceActions;
2274
2275 /// The CUDA fat binary if it was generated for the current input.
2276 Action *CudaFatBinary = nullptr;
2277
2278 /// Flag that is set to true if this builder acted on the current input.
2279 bool IsActive = false;
Yaxun Liu3af038b2018-05-30 00:49:10 +00002280 public:
2281 CudaActionBuilderBase(Compilation &C, DerivedArgList &Args,
2282 const Driver::InputList &Inputs,
2283 Action::OffloadKind OFKind)
2284 : DeviceActionBuilder(C, Args, Inputs, OFKind) {}
Samuel Antao64e965e2016-09-30 15:34:19 +00002285
Yaxun Liu3af038b2018-05-30 00:49:10 +00002286 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2287 // While generating code for CUDA, we only depend on the host input action
2288 // to trigger the creation of all the CUDA device actions.
2289
2290 // If we are dealing with an input action, replicate it for each GPU
2291 // architecture. If we are in host-only mode we return 'success' so that
2292 // the host uses the CUDA offload kind.
2293 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2294 assert(!GpuArchList.empty() &&
2295 "We should have at least one GPU architecture.");
2296
2297 // If the host input is not CUDA or HIP, we don't need to bother about
2298 // this input.
2299 if (IA->getType() != types::TY_CUDA &&
2300 IA->getType() != types::TY_HIP) {
2301 // The builder will ignore this input.
2302 IsActive = false;
2303 return ABRT_Inactive;
2304 }
2305
2306 // Set the flag to true, so that the builder acts on the current input.
2307 IsActive = true;
2308
2309 if (CompileHostOnly)
2310 return ABRT_Success;
2311
2312 // Replicate inputs for each GPU architecture.
2313 auto Ty = IA->getType() == types::TY_HIP ? types::TY_HIP_DEVICE
2314 : types::TY_CUDA_DEVICE;
2315 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2316 CudaDeviceActions.push_back(
2317 C.MakeAction<InputAction>(IA->getInputArg(), Ty));
2318 }
2319
2320 return ABRT_Success;
2321 }
2322
2323 // If this is an unbundling action use it as is for each CUDA toolchain.
2324 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2325 CudaDeviceActions.clear();
2326 for (auto Arch : GpuArchList) {
2327 CudaDeviceActions.push_back(UA);
2328 UA->registerDependentActionInfo(ToolChains[0], CudaArchToString(Arch),
2329 AssociatedOffloadKind);
2330 }
2331 return ABRT_Success;
2332 }
2333
2334 return IsActive ? ABRT_Success : ABRT_Inactive;
2335 }
2336
2337 void appendTopLevelActions(ActionList &AL) override {
2338 // Utility to append actions to the top level list.
2339 auto AddTopLevel = [&](Action *A, CudaArch BoundArch) {
2340 OffloadAction::DeviceDependences Dep;
2341 Dep.add(*A, *ToolChains.front(), CudaArchToString(BoundArch),
2342 AssociatedOffloadKind);
2343 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2344 };
2345
2346 // If we have a fat binary, add it to the list.
2347 if (CudaFatBinary) {
2348 AddTopLevel(CudaFatBinary, CudaArch::UNKNOWN);
2349 CudaDeviceActions.clear();
2350 CudaFatBinary = nullptr;
2351 return;
2352 }
2353
2354 if (CudaDeviceActions.empty())
2355 return;
2356
2357 // If we have CUDA actions at this point, that's because we have a have
2358 // partial compilation, so we should have an action for each GPU
2359 // architecture.
2360 assert(CudaDeviceActions.size() == GpuArchList.size() &&
2361 "Expecting one action per GPU architecture.");
2362 assert(ToolChains.size() == 1 &&
2363 "Expecting to have a sing CUDA toolchain.");
2364 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
2365 AddTopLevel(CudaDeviceActions[I], GpuArchList[I]);
2366
2367 CudaDeviceActions.clear();
2368 }
2369
2370 bool initialize() override {
2371 assert(AssociatedOffloadKind == Action::OFK_Cuda ||
2372 AssociatedOffloadKind == Action::OFK_HIP);
2373
2374 // We don't need to support CUDA.
2375 if (AssociatedOffloadKind == Action::OFK_Cuda &&
2376 !C.hasOffloadToolChain<Action::OFK_Cuda>())
2377 return false;
2378
2379 // We don't need to support HIP.
2380 if (AssociatedOffloadKind == Action::OFK_HIP &&
2381 !C.hasOffloadToolChain<Action::OFK_HIP>())
2382 return false;
2383
2384 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
2385 assert(HostTC && "No toolchain for host compilation.");
2386 if (HostTC->getTriple().isNVPTX() ||
2387 HostTC->getTriple().getArch() == llvm::Triple::amdgcn) {
2388 // We do not support targeting NVPTX/AMDGCN for host compilation. Throw
2389 // an error and abort pipeline construction early so we don't trip
2390 // asserts that assume device-side compilation.
2391 C.getDriver().Diag(diag::err_drv_cuda_host_arch)
2392 << HostTC->getTriple().getArchName();
2393 return true;
2394 }
2395
2396 ToolChains.push_back(
2397 AssociatedOffloadKind == Action::OFK_Cuda
2398 ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
2399 : C.getSingleOffloadToolChain<Action::OFK_HIP>());
2400
2401 Arg *PartialCompilationArg = Args.getLastArg(
2402 options::OPT_cuda_host_only, options::OPT_cuda_device_only,
2403 options::OPT_cuda_compile_host_device);
2404 CompileHostOnly = PartialCompilationArg &&
2405 PartialCompilationArg->getOption().matches(
2406 options::OPT_cuda_host_only);
2407 CompileDeviceOnly = PartialCompilationArg &&
2408 PartialCompilationArg->getOption().matches(
2409 options::OPT_cuda_device_only);
2410
2411 // Collect all cuda_gpu_arch parameters, removing duplicates.
2412 std::set<CudaArch> GpuArchs;
2413 bool Error = false;
2414 for (Arg *A : Args) {
2415 if (!(A->getOption().matches(options::OPT_cuda_gpu_arch_EQ) ||
2416 A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ)))
2417 continue;
2418 A->claim();
2419
2420 const StringRef ArchStr = A->getValue();
2421 if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ) &&
2422 ArchStr == "all") {
2423 GpuArchs.clear();
2424 continue;
2425 }
2426 CudaArch Arch = StringToCudaArch(ArchStr);
2427 if (Arch == CudaArch::UNKNOWN) {
2428 C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
2429 Error = true;
2430 } else if (A->getOption().matches(options::OPT_cuda_gpu_arch_EQ))
2431 GpuArchs.insert(Arch);
2432 else if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ))
2433 GpuArchs.erase(Arch);
2434 else
2435 llvm_unreachable("Unexpected option.");
2436 }
2437
2438 // Collect list of GPUs remaining in the set.
2439 for (CudaArch Arch : GpuArchs)
2440 GpuArchList.push_back(Arch);
2441
2442 // Default to sm_20 which is the lowest common denominator for
2443 // supported GPUs. sm_20 code should work correctly, if
2444 // suboptimally, on all newer GPUs.
2445 if (GpuArchList.empty())
2446 GpuArchList.push_back(CudaArch::SM_20);
2447
2448 return Error;
2449 }
2450 };
2451
2452 /// \brief CUDA action builder. It injects device code in the host backend
2453 /// action.
2454 class CudaActionBuilder final : public CudaActionBuilderBase {
Samuel Antao64e965e2016-09-30 15:34:19 +00002455 public:
2456 CudaActionBuilder(Compilation &C, DerivedArgList &Args,
2457 const Driver::InputList &Inputs)
Yaxun Liu3af038b2018-05-30 00:49:10 +00002458 : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_Cuda) {}
Samuel Antao64e965e2016-09-30 15:34:19 +00002459
2460 ActionBuilderReturnCode
Samuel Antao28c4f182016-10-27 17:08:03 +00002461 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2462 phases::ID CurPhase, phases::ID FinalPhase,
2463 PhasesTy &Phases) override {
Samuel Antao64e965e2016-09-30 15:34:19 +00002464 if (!IsActive)
2465 return ABRT_Inactive;
2466
2467 // If we don't have more CUDA actions, we don't have any dependences to
2468 // create for the host.
2469 if (CudaDeviceActions.empty())
2470 return ABRT_Success;
2471
2472 assert(CudaDeviceActions.size() == GpuArchList.size() &&
2473 "Expecting one action per GPU architecture.");
2474 assert(!CompileHostOnly &&
2475 "Not expecting CUDA actions in host-only compilation.");
2476
2477 // If we are generating code for the device or we are in a backend phase,
2478 // we attempt to generate the fat binary. We compile each arch to ptx and
2479 // assemble to cubin, then feed the cubin *and* the ptx into a device
2480 // "link" action, which uses fatbinary to combine these cubins into one
2481 // fatbin. The fatbin is then an input to the host action if not in
2482 // device-only mode.
2483 if (CompileDeviceOnly || CurPhase == phases::Backend) {
2484 ActionList DeviceActions;
2485 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2486 // Produce the device action from the current phase up to the assemble
2487 // phase.
2488 for (auto Ph : Phases) {
2489 // Skip the phases that were already dealt with.
2490 if (Ph < CurPhase)
2491 continue;
2492 // We have to be consistent with the host final phase.
2493 if (Ph > FinalPhase)
2494 break;
2495
2496 CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction(
Artem Belevichecb178b2018-03-21 22:22:59 +00002497 C, Args, Ph, CudaDeviceActions[I], Action::OFK_Cuda);
Samuel Antao64e965e2016-09-30 15:34:19 +00002498
2499 if (Ph == phases::Assemble)
2500 break;
2501 }
2502
2503 // If we didn't reach the assemble phase, we can't generate the fat
2504 // binary. We don't need to generate the fat binary if we are not in
2505 // device-only mode.
2506 if (!isa<AssembleJobAction>(CudaDeviceActions[I]) ||
2507 CompileDeviceOnly)
2508 continue;
2509
2510 Action *AssembleAction = CudaDeviceActions[I];
2511 assert(AssembleAction->getType() == types::TY_Object);
2512 assert(AssembleAction->getInputs().size() == 1);
2513
2514 Action *BackendAction = AssembleAction->getInputs()[0];
2515 assert(BackendAction->getType() == types::TY_PP_Asm);
2516
2517 for (auto &A : {AssembleAction, BackendAction}) {
2518 OffloadAction::DeviceDependences DDep;
2519 DDep.add(*A, *ToolChains.front(), CudaArchToString(GpuArchList[I]),
2520 Action::OFK_Cuda);
2521 DeviceActions.push_back(
2522 C.MakeAction<OffloadAction>(DDep, A->getType()));
2523 }
2524 }
2525
2526 // We generate the fat binary if we have device input actions.
2527 if (!DeviceActions.empty()) {
2528 CudaFatBinary =
2529 C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN);
2530
2531 if (!CompileDeviceOnly) {
2532 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
2533 Action::OFK_Cuda);
2534 // Clear the fat binary, it is already a dependence to an host
2535 // action.
2536 CudaFatBinary = nullptr;
2537 }
2538
2539 // Remove the CUDA actions as they are already connected to an host
2540 // action or fat binary.
2541 CudaDeviceActions.clear();
2542 }
2543
2544 // We avoid creating host action in device-only mode.
2545 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
Samuel Antao5b1a89a2016-10-27 00:53:34 +00002546 } else if (CurPhase > phases::Backend) {
2547 // If we are past the backend phase and still have a device action, we
2548 // don't have to do anything as this action is already a device
2549 // top-level action.
2550 return ABRT_Success;
Samuel Antao64e965e2016-09-30 15:34:19 +00002551 }
2552
2553 assert(CurPhase < phases::Backend && "Generating single CUDA "
2554 "instructions should only occur "
2555 "before the backend phase!");
2556
2557 // By default, we produce an action for each device arch.
2558 for (Action *&A : CudaDeviceActions)
2559 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2560
2561 return ABRT_Success;
2562 }
Yaxun Liu3af038b2018-05-30 00:49:10 +00002563 };
2564 /// \brief HIP action builder. It injects device code in the host backend
2565 /// action.
2566 class HIPActionBuilder final : public CudaActionBuilderBase {
2567 /// The linker inputs obtained for each device arch.
2568 SmallVector<ActionList, 8> DeviceLinkerInputs;
Yaxun Liu97670892018-10-02 17:48:54 +00002569 bool Relocatable;
Samuel Antao64e965e2016-09-30 15:34:19 +00002570
Yaxun Liu3af038b2018-05-30 00:49:10 +00002571 public:
2572 HIPActionBuilder(Compilation &C, DerivedArgList &Args,
2573 const Driver::InputList &Inputs)
Yaxun Liu97670892018-10-02 17:48:54 +00002574 : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_HIP),
2575 Relocatable(false) {}
Samuel Antao64e965e2016-09-30 15:34:19 +00002576
Yaxun Liu3af038b2018-05-30 00:49:10 +00002577 bool canUseBundlerUnbundler() const override { return true; }
Samuel Antao64e965e2016-09-30 15:34:19 +00002578
Yaxun Liu3af038b2018-05-30 00:49:10 +00002579 ActionBuilderReturnCode
2580 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2581 phases::ID CurPhase, phases::ID FinalPhase,
2582 PhasesTy &Phases) override {
2583 // amdgcn does not support linking of object files, therefore we skip
Yaxun Liu97670892018-10-02 17:48:54 +00002584 // backend and assemble phases to output LLVM IR. Except for generating
2585 // non-relocatable device coee, where we generate fat binary for device
2586 // code and pass to host in Backend phase.
2587 if (CudaDeviceActions.empty() ||
2588 (CurPhase == phases::Backend && Relocatable) ||
Yaxun Liu3af038b2018-05-30 00:49:10 +00002589 CurPhase == phases::Assemble)
2590 return ABRT_Success;
2591
Yaxun Liu97670892018-10-02 17:48:54 +00002592 assert(((CurPhase == phases::Link && Relocatable) ||
Yaxun Liu3af038b2018-05-30 00:49:10 +00002593 CudaDeviceActions.size() == GpuArchList.size()) &&
2594 "Expecting one action per GPU architecture.");
2595 assert(!CompileHostOnly &&
2596 "Not expecting CUDA actions in host-only compilation.");
2597
Yaxun Liu97670892018-10-02 17:48:54 +00002598 if (!Relocatable && CurPhase == phases::Backend) {
2599 // If we are in backend phase, we attempt to generate the fat binary.
2600 // We compile each arch to IR and use a link action to generate code
2601 // object containing ISA. Then we use a special "link" action to create
2602 // a fat binary containing all the code objects for different GPU's.
2603 // The fat binary is then an input to the host action.
2604 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2605 // Create a link action to link device IR with device library
2606 // and generate ISA.
2607 ActionList AL;
2608 AL.push_back(CudaDeviceActions[I]);
2609 CudaDeviceActions[I] =
2610 C.MakeAction<LinkJobAction>(AL, types::TY_Image);
2611
2612 // OffloadingActionBuilder propagates device arch until an offload
2613 // action. Since the next action for creating fatbin does
2614 // not have device arch, whereas the above link action and its input
2615 // have device arch, an offload action is needed to stop the null
2616 // device arch of the next action being propagated to the above link
2617 // action.
2618 OffloadAction::DeviceDependences DDep;
2619 DDep.add(*CudaDeviceActions[I], *ToolChains.front(),
2620 CudaArchToString(GpuArchList[I]), AssociatedOffloadKind);
2621 CudaDeviceActions[I] = C.MakeAction<OffloadAction>(
2622 DDep, CudaDeviceActions[I]->getType());
2623 }
2624 // Create HIP fat binary with a special "link" action.
2625 CudaFatBinary =
2626 C.MakeAction<LinkJobAction>(CudaDeviceActions,
2627 types::TY_HIP_FATBIN);
2628
Yaxun Liu2bcc9512018-11-14 04:47:31 +00002629 if (!CompileDeviceOnly) {
2630 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
2631 AssociatedOffloadKind);
2632 // Clear the fat binary, it is already a dependence to an host
2633 // action.
2634 CudaFatBinary = nullptr;
2635 }
Yaxun Liu97670892018-10-02 17:48:54 +00002636
2637 // Remove the CUDA actions as they are already connected to an host
2638 // action or fat binary.
2639 CudaDeviceActions.clear();
2640
Yaxun Liu2bcc9512018-11-14 04:47:31 +00002641 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
Yaxun Liu97670892018-10-02 17:48:54 +00002642 } else if (CurPhase == phases::Link) {
2643 // Save CudaDeviceActions to DeviceLinkerInputs for each GPU subarch.
2644 // This happens to each device action originated from each input file.
2645 // Later on, device actions in DeviceLinkerInputs are used to create
2646 // device link actions in appendLinkDependences and the created device
2647 // link actions are passed to the offload action as device dependence.
Yaxun Liu3af038b2018-05-30 00:49:10 +00002648 DeviceLinkerInputs.resize(CudaDeviceActions.size());
2649 auto LI = DeviceLinkerInputs.begin();
2650 for (auto *A : CudaDeviceActions) {
2651 LI->push_back(A);
2652 ++LI;
Samuel Antao64e965e2016-09-30 15:34:19 +00002653 }
2654
Yaxun Liu3af038b2018-05-30 00:49:10 +00002655 // We will pass the device action as a host dependence, so we don't
2656 // need to do anything else with them.
2657 CudaDeviceActions.clear();
Samuel Antao64e965e2016-09-30 15:34:19 +00002658 return ABRT_Success;
2659 }
2660
Yaxun Liu3af038b2018-05-30 00:49:10 +00002661 // By default, we produce an action for each device arch.
2662 for (Action *&A : CudaDeviceActions)
2663 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A,
2664 AssociatedOffloadKind);
2665
2666 return ABRT_Success;
Samuel Antao64e965e2016-09-30 15:34:19 +00002667 }
2668
Yaxun Liu3af038b2018-05-30 00:49:10 +00002669 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {
2670 // Append a new link action for each device.
2671 unsigned I = 0;
2672 for (auto &LI : DeviceLinkerInputs) {
2673 auto *DeviceLinkAction =
2674 C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2675 DA.add(*DeviceLinkAction, *ToolChains[0],
2676 CudaArchToString(GpuArchList[I]), AssociatedOffloadKind);
2677 ++I;
Samuel Antao64e965e2016-09-30 15:34:19 +00002678 }
Samuel Antao64e965e2016-09-30 15:34:19 +00002679 }
Yaxun Liu97670892018-10-02 17:48:54 +00002680
2681 bool initialize() override {
2682 Relocatable = Args.hasFlag(options::OPT_fgpu_rdc,
2683 options::OPT_fno_gpu_rdc, /*Default=*/false);
2684
2685 return CudaActionBuilderBase::initialize();
2686 }
Samuel Antao64e965e2016-09-30 15:34:19 +00002687 };
2688
Samuel Antao28c4f182016-10-27 17:08:03 +00002689 /// OpenMP action builder. The host bitcode is passed to the device frontend
2690 /// and all the device linked images are passed to the host link phase.
2691 class OpenMPActionBuilder final : public DeviceActionBuilder {
2692 /// The OpenMP actions for the current input.
2693 ActionList OpenMPDeviceActions;
2694
2695 /// The linker inputs obtained for each toolchain.
2696 SmallVector<ActionList, 8> DeviceLinkerInputs;
2697
2698 public:
2699 OpenMPActionBuilder(Compilation &C, DerivedArgList &Args,
2700 const Driver::InputList &Inputs)
2701 : DeviceActionBuilder(C, Args, Inputs, Action::OFK_OpenMP) {}
2702
2703 ActionBuilderReturnCode
2704 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2705 phases::ID CurPhase, phases::ID FinalPhase,
2706 PhasesTy &Phases) override {
Alexey Bataeva5178f52018-09-28 16:17:59 +00002707 if (OpenMPDeviceActions.empty())
2708 return ABRT_Inactive;
Samuel Antao28c4f182016-10-27 17:08:03 +00002709
2710 // We should always have an action for each input.
2711 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2712 "Number of OpenMP actions and toolchains do not match.");
2713
2714 // The host only depends on device action in the linking phase, when all
2715 // the device images have to be embedded in the host image.
2716 if (CurPhase == phases::Link) {
2717 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2718 "Toolchains and linker inputs sizes do not match.");
2719 auto LI = DeviceLinkerInputs.begin();
2720 for (auto *A : OpenMPDeviceActions) {
2721 LI->push_back(A);
2722 ++LI;
2723 }
2724
2725 // We passed the device action as a host dependence, so we don't need to
2726 // do anything else with them.
2727 OpenMPDeviceActions.clear();
2728 return ABRT_Success;
2729 }
2730
2731 // By default, we produce an action for each device arch.
2732 for (Action *&A : OpenMPDeviceActions)
2733 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2734
2735 return ABRT_Success;
2736 }
2737
2738 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2739
2740 // If this is an input action replicate it for each OpenMP toolchain.
2741 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2742 OpenMPDeviceActions.clear();
2743 for (unsigned I = 0; I < ToolChains.size(); ++I)
2744 OpenMPDeviceActions.push_back(
2745 C.MakeAction<InputAction>(IA->getInputArg(), IA->getType()));
2746 return ABRT_Success;
2747 }
2748
Samuel Antaofab4f372016-10-27 18:00:51 +00002749 // If this is an unbundling action use it as is for each OpenMP toolchain.
2750 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2751 OpenMPDeviceActions.clear();
Alexey Bataeva5178f52018-09-28 16:17:59 +00002752 auto *IA = cast<InputAction>(UA->getInputs().back());
2753 std::string FileName = IA->getInputArg().getAsString(Args);
2754 // Check if the type of the file is the same as the action. Do not
2755 // unbundle it if it is not. Do not unbundle .so files, for example,
2756 // which are not object files.
2757 if (IA->getType() == types::TY_Object &&
2758 (!llvm::sys::path::has_extension(FileName) ||
2759 types::lookupTypeForExtension(
2760 llvm::sys::path::extension(FileName).drop_front()) !=
2761 types::TY_Object))
2762 return ABRT_Inactive;
Samuel Antaofab4f372016-10-27 18:00:51 +00002763 for (unsigned I = 0; I < ToolChains.size(); ++I) {
2764 OpenMPDeviceActions.push_back(UA);
2765 UA->registerDependentActionInfo(
2766 ToolChains[I], /*BoundArch=*/StringRef(), Action::OFK_OpenMP);
2767 }
2768 return ABRT_Success;
2769 }
2770
Samuel Antao28c4f182016-10-27 17:08:03 +00002771 // When generating code for OpenMP we use the host compile phase result as
2772 // a dependence to the device compile phase so that it can learn what
2773 // declarations should be emitted. However, this is not the only use for
2774 // the host action, so we prevent it from being collapsed.
2775 if (isa<CompileJobAction>(HostAction)) {
2776 HostAction->setCannotBeCollapsedWithNextDependentAction();
2777 assert(ToolChains.size() == OpenMPDeviceActions.size() &&
2778 "Toolchains and device action sizes do not match.");
2779 OffloadAction::HostDependence HDep(
2780 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2781 /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2782 auto TC = ToolChains.begin();
2783 for (Action *&A : OpenMPDeviceActions) {
2784 assert(isa<CompileJobAction>(A));
2785 OffloadAction::DeviceDependences DDep;
2786 DDep.add(*A, **TC, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2787 A = C.MakeAction<OffloadAction>(HDep, DDep);
2788 ++TC;
2789 }
2790 }
2791 return ABRT_Success;
2792 }
2793
Samuel Antao69d6f312016-10-27 17:50:43 +00002794 void appendTopLevelActions(ActionList &AL) override {
2795 if (OpenMPDeviceActions.empty())
2796 return;
2797
2798 // We should always have an action for each input.
2799 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2800 "Number of OpenMP actions and toolchains do not match.");
2801
2802 // Append all device actions followed by the proper offload action.
2803 auto TI = ToolChains.begin();
2804 for (auto *A : OpenMPDeviceActions) {
2805 OffloadAction::DeviceDependences Dep;
2806 Dep.add(*A, **TI, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2807 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2808 ++TI;
2809 }
2810 // We no longer need the action stored in this builder.
2811 OpenMPDeviceActions.clear();
2812 }
2813
Samuel Antao28c4f182016-10-27 17:08:03 +00002814 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {
2815 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2816 "Toolchains and linker inputs sizes do not match.");
2817
2818 // Append a new link action for each device.
2819 auto TC = ToolChains.begin();
2820 for (auto &LI : DeviceLinkerInputs) {
2821 auto *DeviceLinkAction =
2822 C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2823 DA.add(*DeviceLinkAction, **TC, /*BoundArch=*/nullptr,
2824 Action::OFK_OpenMP);
2825 ++TC;
2826 }
2827 }
2828
2829 bool initialize() override {
2830 // Get the OpenMP toolchains. If we don't get any, the action builder will
2831 // know there is nothing to do related to OpenMP offloading.
2832 auto OpenMPTCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
2833 for (auto TI = OpenMPTCRange.first, TE = OpenMPTCRange.second; TI != TE;
2834 ++TI)
2835 ToolChains.push_back(TI->second);
2836
2837 DeviceLinkerInputs.resize(ToolChains.size());
2838 return false;
2839 }
Samuel Antao69d6f312016-10-27 17:50:43 +00002840
2841 bool canUseBundlerUnbundler() const override {
2842 // OpenMP should use bundled files whenever possible.
2843 return true;
2844 }
Samuel Antao28c4f182016-10-27 17:08:03 +00002845 };
2846
2847 ///
2848 /// TODO: Add the implementation for other specialized builders here.
2849 ///
Samuel Antao64e965e2016-09-30 15:34:19 +00002850
2851 /// Specialized builders being used by this offloading action builder.
2852 SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders;
2853
Samuel Antao69d6f312016-10-27 17:50:43 +00002854 /// Flag set to true if all valid builders allow file bundling/unbundling.
2855 bool CanUseBundler;
2856
Samuel Antao64e965e2016-09-30 15:34:19 +00002857public:
2858 OffloadingActionBuilder(Compilation &C, DerivedArgList &Args,
2859 const Driver::InputList &Inputs)
Samuel Antao10e905c2016-10-27 01:08:58 +00002860 : C(C) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002861 // Create a specialized builder for each device toolchain.
2862
2863 IsValid = true;
2864
2865 // Create a specialized builder for CUDA.
2866 SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs));
2867
Yaxun Liu3af038b2018-05-30 00:49:10 +00002868 // Create a specialized builder for HIP.
2869 SpecializedBuilders.push_back(new HIPActionBuilder(C, Args, Inputs));
2870
Samuel Antao28c4f182016-10-27 17:08:03 +00002871 // Create a specialized builder for OpenMP.
2872 SpecializedBuilders.push_back(new OpenMPActionBuilder(C, Args, Inputs));
2873
Samuel Antao64e965e2016-09-30 15:34:19 +00002874 //
2875 // TODO: Build other specialized builders here.
2876 //
2877
Samuel Antao69d6f312016-10-27 17:50:43 +00002878 // Initialize all the builders, keeping track of errors. If all valid
2879 // builders agree that we can use bundling, set the flag to true.
2880 unsigned ValidBuilders = 0u;
2881 unsigned ValidBuildersSupportingBundling = 0u;
2882 for (auto *SB : SpecializedBuilders) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002883 IsValid = IsValid && !SB->initialize();
Samuel Antao69d6f312016-10-27 17:50:43 +00002884
2885 // Update the counters if the builder is valid.
2886 if (SB->isValid()) {
2887 ++ValidBuilders;
2888 if (SB->canUseBundlerUnbundler())
2889 ++ValidBuildersSupportingBundling;
2890 }
2891 }
2892 CanUseBundler =
2893 ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling;
Artem Belevichf981e30b2016-08-02 22:37:47 +00002894 }
Justin Lebardc3c5042016-04-19 02:27:07 +00002895
Samuel Antao64e965e2016-09-30 15:34:19 +00002896 ~OffloadingActionBuilder() {
2897 for (auto *SB : SpecializedBuilders)
2898 delete SB;
Samuel Antaod06239d2016-07-15 23:13:27 +00002899 }
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002900
Samuel Antao64e965e2016-09-30 15:34:19 +00002901 /// Generate an action that adds device dependences (if any) to a host action.
2902 /// If no device dependence actions exist, just return the host action \a
2903 /// HostAction. If an error is found or if no builder requires the host action
2904 /// to be generated, return nullptr.
2905 Action *
2906 addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg,
2907 phases::ID CurPhase, phases::ID FinalPhase,
2908 DeviceActionBuilder::PhasesTy &Phases) {
2909 if (!IsValid)
2910 return nullptr;
Justin Lebar7bf77982016-01-11 23:27:13 +00002911
Samuel Antao64e965e2016-09-30 15:34:19 +00002912 if (SpecializedBuilders.empty())
2913 return HostAction;
2914
2915 assert(HostAction && "Invalid host action!");
2916
2917 OffloadAction::DeviceDependences DDeps;
2918 // Check if all the programming models agree we should not emit the host
2919 // action. Also, keep track of the offloading kinds employed.
2920 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2921 unsigned InactiveBuilders = 0u;
2922 unsigned IgnoringBuilders = 0u;
2923 for (auto *SB : SpecializedBuilders) {
2924 if (!SB->isValid()) {
2925 ++InactiveBuilders;
2926 continue;
2927 }
2928
Samuel Antao28c4f182016-10-27 17:08:03 +00002929 auto RetCode =
2930 SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases);
Samuel Antao64e965e2016-09-30 15:34:19 +00002931
2932 // If the builder explicitly says the host action should be ignored,
2933 // we need to increment the variable that tracks the builders that request
2934 // the host object to be ignored.
2935 if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host)
2936 ++IgnoringBuilders;
2937
2938 // Unless the builder was inactive for this action, we have to record the
2939 // offload kind because the host will have to use it.
2940 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2941 OffloadKind |= SB->getAssociatedOffloadKind();
2942 }
2943
2944 // If all builders agree that the host object should be ignored, just return
2945 // nullptr.
2946 if (IgnoringBuilders &&
2947 SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders))
2948 return nullptr;
2949
2950 if (DDeps.getActions().empty())
2951 return HostAction;
2952
2953 // We have dependences we need to bundle together. We use an offload action
2954 // for that.
2955 OffloadAction::HostDependence HDep(
2956 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2957 /*BoundArch=*/nullptr, DDeps);
2958 return C.MakeAction<OffloadAction>(HDep, DDeps);
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002959 }
2960
Samuel Antao64e965e2016-09-30 15:34:19 +00002961 /// Generate an action that adds a host dependence to a device action. The
2962 /// results will be kept in this action builder. Return true if an error was
2963 /// found.
Samuel Antaofab4f372016-10-27 18:00:51 +00002964 bool addHostDependenceToDeviceActions(Action *&HostAction,
Samuel Antao64e965e2016-09-30 15:34:19 +00002965 const Arg *InputArg) {
2966 if (!IsValid)
2967 return true;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002968
Samuel Antaofab4f372016-10-27 18:00:51 +00002969 // If we are supporting bundling/unbundling and the current action is an
2970 // input action of non-source file, we replace the host action by the
2971 // unbundling action. The bundler tool has the logic to detect if an input
2972 // is a bundle or not and if the input is not a bundle it assumes it is a
2973 // host file. Therefore it is safe to create an unbundling action even if
2974 // the input is not a bundle.
2975 if (CanUseBundler && isa<InputAction>(HostAction) &&
2976 InputArg->getOption().getKind() == llvm::opt::Option::InputClass &&
2977 !types::isSrcFile(HostAction->getType())) {
2978 auto UnbundlingHostAction =
2979 C.MakeAction<OffloadUnbundlingJobAction>(HostAction);
2980 UnbundlingHostAction->registerDependentActionInfo(
2981 C.getSingleOffloadToolChain<Action::OFK_Host>(),
Yaxun Liuf37b50a2018-07-24 01:03:44 +00002982 /*BoundArch=*/StringRef(), Action::OFK_Host);
Samuel Antaofab4f372016-10-27 18:00:51 +00002983 HostAction = UnbundlingHostAction;
2984 }
2985
Samuel Antao64e965e2016-09-30 15:34:19 +00002986 assert(HostAction && "Invalid host action!");
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002987
Samuel Antao64e965e2016-09-30 15:34:19 +00002988 // Register the offload kinds that are used.
2989 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2990 for (auto *SB : SpecializedBuilders) {
2991 if (!SB->isValid())
2992 continue;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002993
Samuel Antao64e965e2016-09-30 15:34:19 +00002994 auto RetCode = SB->addDeviceDepences(HostAction);
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002995
Samuel Antao64e965e2016-09-30 15:34:19 +00002996 // Host dependences for device actions are not compatible with that same
2997 // action being ignored.
2998 assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host &&
2999 "Host dependence not expected to be ignored.!");
Samuel Antaod06239d2016-07-15 23:13:27 +00003000
Samuel Antao64e965e2016-09-30 15:34:19 +00003001 // Unless the builder was inactive for this action, we have to record the
3002 // offload kind because the host will have to use it.
3003 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
3004 OffloadKind |= SB->getAssociatedOffloadKind();
3005 }
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003006
Alexey Bataeva5178f52018-09-28 16:17:59 +00003007 // Do not use unbundler if the Host does not depend on device action.
3008 if (OffloadKind == Action::OFK_None && CanUseBundler)
3009 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction))
3010 HostAction = UA->getInputs().back();
3011
Samuel Antao64e965e2016-09-30 15:34:19 +00003012 return false;
3013 }
3014
Samuel Antao69d6f312016-10-27 17:50:43 +00003015 /// Add the offloading top level actions to the provided action list. This
3016 /// function can replace the host action by a bundling action if the
3017 /// programming models allow it.
Samuel Antao64e965e2016-09-30 15:34:19 +00003018 bool appendTopLevelActions(ActionList &AL, Action *HostAction,
3019 const Arg *InputArg) {
Samuel Antao69d6f312016-10-27 17:50:43 +00003020 // Get the device actions to be appended.
3021 ActionList OffloadAL;
Samuel Antao64e965e2016-09-30 15:34:19 +00003022 for (auto *SB : SpecializedBuilders) {
3023 if (!SB->isValid())
3024 continue;
Samuel Antao69d6f312016-10-27 17:50:43 +00003025 SB->appendTopLevelActions(OffloadAL);
Samuel Antao64e965e2016-09-30 15:34:19 +00003026 }
3027
Samuel Antao69d6f312016-10-27 17:50:43 +00003028 // If we can use the bundler, replace the host action by the bundling one in
Yaxun Liu2bcc9512018-11-14 04:47:31 +00003029 // the resulting list. Otherwise, just append the device actions. For
3030 // device only compilation, HostAction is a null pointer, therefore only do
3031 // this when HostAction is not a null pointer.
3032 if (CanUseBundler && HostAction && !OffloadAL.empty()) {
Samuel Antao69d6f312016-10-27 17:50:43 +00003033 // Add the host action to the list in order to create the bundling action.
3034 OffloadAL.push_back(HostAction);
3035
3036 // We expect that the host action was just appended to the action list
3037 // before this method was called.
3038 assert(HostAction == AL.back() && "Host action not in the list??");
3039 HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL);
3040 AL.back() = HostAction;
3041 } else
3042 AL.append(OffloadAL.begin(), OffloadAL.end());
3043
Samuel Antao64e965e2016-09-30 15:34:19 +00003044 // Propagate to the current host action (if any) the offload information
3045 // associated with the current input.
3046 if (HostAction)
3047 HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg],
3048 /*BoundArch=*/nullptr);
Samuel Antao64e965e2016-09-30 15:34:19 +00003049 return false;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003050 }
Artem Belevich5bde4e02015-07-20 20:02:54 +00003051
Samuel Antao64e965e2016-09-30 15:34:19 +00003052 /// Processes the host linker action. This currently consists of replacing it
3053 /// with an offload action if there are device link objects and propagate to
3054 /// the host action all the offload kinds used in the current compilation. The
3055 /// resulting action is returned.
3056 Action *processHostLinkAction(Action *HostAction) {
3057 // Add all the dependences from the device linking actions.
3058 OffloadAction::DeviceDependences DDeps;
3059 for (auto *SB : SpecializedBuilders) {
3060 if (!SB->isValid())
3061 continue;
Justin Lebar21e5d4f2016-01-14 21:41:27 +00003062
Samuel Antao64e965e2016-09-30 15:34:19 +00003063 SB->appendLinkDependences(DDeps);
Justin Lebar21e5d4f2016-01-14 21:41:27 +00003064 }
Samuel Antaod06239d2016-07-15 23:13:27 +00003065
Samuel Antao64e965e2016-09-30 15:34:19 +00003066 // Calculate all the offload kinds used in the current compilation.
3067 unsigned ActiveOffloadKinds = 0u;
3068 for (auto &I : InputArgToOffloadKindMap)
3069 ActiveOffloadKinds |= I.second;
3070
3071 // If we don't have device dependencies, we don't have to create an offload
3072 // action.
3073 if (DDeps.getActions().empty()) {
3074 // Propagate all the active kinds to host action. Given that it is a link
3075 // action it is assumed to depend on all actions generated so far.
3076 HostAction->propagateHostOffloadInfo(ActiveOffloadKinds,
3077 /*BoundArch=*/nullptr);
3078 return HostAction;
3079 }
3080
3081 // Create the offload action with all dependences. When an offload action
3082 // is created the kinds are propagated to the host action, so we don't have
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003083 // to do that explicitly here.
Samuel Antao64e965e2016-09-30 15:34:19 +00003084 OffloadAction::HostDependence HDep(
3085 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
3086 /*BoundArch*/ nullptr, ActiveOffloadKinds);
3087 return C.MakeAction<OffloadAction>(HDep, DDeps);
3088 }
3089};
3090} // anonymous namespace.
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003091
Justin Lebar0f3474c2016-02-11 02:00:50 +00003092void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
3093 const InputList &Inputs, ActionList &Actions) const {
Chad Rosierecdede82011-08-12 22:08:57 +00003094 llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00003095
Daniel Dunbar34c41872009-03-13 00:17:48 +00003096 if (!SuppressMissingInputWarning && Inputs.empty()) {
Daniel Dunbarbfeec742009-03-12 23:55:14 +00003097 Diag(clang::diag::err_drv_no_input_files);
3098 return;
3099 }
3100
Chad Rosier7742b5d2011-07-27 23:36:45 +00003101 Arg *FinalPhaseArg;
3102 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
Daniel Dunbarbfeec742009-03-12 23:55:14 +00003103
Bob Haarmanaaf51912017-02-27 19:40:19 +00003104 if (FinalPhase == phases::Link) {
3105 if (Args.hasArg(options::OPT_emit_llvm))
3106 Diag(clang::diag::err_drv_emit_llvm_link);
3107 if (IsCLMode() && LTOMode != LTOK_None &&
3108 !Args.getLastArgValue(options::OPT_fuse_ld_EQ).equals_lower("lld"))
3109 Diag(clang::diag::err_drv_lto_without_lld);
Rafael Espindolae8025642013-08-25 14:27:09 +00003110 }
3111
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003112 // Reject -Z* at the top level, these options should never have been exposed
3113 // by gcc.
Daniel Dunbardd765242009-03-26 16:12:09 +00003114 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
Daniel Dunbar0e759942009-03-20 06:14:23 +00003115 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
Daniel Dunbarbfeec742009-03-12 23:55:14 +00003116
Hans Wennborg13b7fe72013-08-12 23:26:25 +00003117 // Diagnose misuse of /Fo.
3118 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
Hans Wennborg13b7fe72013-08-12 23:26:25 +00003119 StringRef V = A->getValue();
Hans Wennborg61647532014-11-17 19:16:36 +00003120 if (Inputs.size() > 1 && !V.empty() &&
3121 !llvm::sys::path::is_separator(V.back())) {
Hans Wennborg13b7fe72013-08-12 23:26:25 +00003122 // Check whether /Fo tries to name an output file for multiple inputs.
Hans Wennborg9c1659b2013-10-18 22:49:04 +00003123 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003124 << A->getSpelling() << V;
Hans Wennborg13b7fe72013-08-12 23:26:25 +00003125 Args.eraseArg(options::OPT__SLASH_Fo);
3126 }
3127 }
3128
Hans Wennborg9c1659b2013-10-18 22:49:04 +00003129 // Diagnose misuse of /Fa.
3130 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
3131 StringRef V = A->getValue();
Hans Wennborg61647532014-11-17 19:16:36 +00003132 if (Inputs.size() > 1 && !V.empty() &&
3133 !llvm::sys::path::is_separator(V.back())) {
Hans Wennborg9c1659b2013-10-18 22:49:04 +00003134 // Check whether /Fa tries to name an asm file for multiple inputs.
3135 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003136 << A->getSpelling() << V;
Hans Wennborg9c1659b2013-10-18 22:49:04 +00003137 Args.eraseArg(options::OPT__SLASH_Fa);
3138 }
3139 }
3140
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00003141 // Diagnose misuse of /o.
3142 if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
3143 if (A->getValue()[0] == '\0') {
3144 // It has to have a value.
3145 Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
3146 Args.eraseArg(options::OPT__SLASH_o);
3147 }
3148 }
3149
Mike Rice58df1af2018-09-11 17:10:44 +00003150 // Ignore /Yc/Yu if both /Yc and /Yu passed but with different filenames.
Nico Weber2ca4be92016-03-01 23:16:44 +00003151 Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
3152 Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
Nico Weber2ca4be92016-03-01 23:16:44 +00003153 if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
3154 Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
3155 Args.eraseArg(options::OPT__SLASH_Yc);
3156 Args.eraseArg(options::OPT__SLASH_Yu);
3157 YcArg = YuArg = nullptr;
3158 }
Nico Weber2ca4be92016-03-01 23:16:44 +00003159 if (YcArg && Inputs.size() > 1) {
3160 Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
3161 Args.eraseArg(options::OPT__SLASH_Yc);
3162 YcArg = nullptr;
3163 }
Erich Keaneeaca3882018-08-17 13:43:39 +00003164 if (FinalPhase == phases::Preprocess || Args.hasArg(options::OPT__SLASH_Y_)) {
3165 // If only preprocessing or /Y- is used, all pch handling is disabled.
3166 // Rather than check for it everywhere, just remove clang-cl pch-related
3167 // flags here.
Nico Weber2ca4be92016-03-01 23:16:44 +00003168 Args.eraseArg(options::OPT__SLASH_Fp);
3169 Args.eraseArg(options::OPT__SLASH_Yc);
3170 Args.eraseArg(options::OPT__SLASH_Yu);
3171 YcArg = YuArg = nullptr;
3172 }
Nico Weber2ca4be92016-03-01 23:16:44 +00003173
Samuel Antao64e965e2016-09-30 15:34:19 +00003174 // Builder to be used to build offloading actions.
3175 OffloadingActionBuilder OffloadBuilder(C, Args, Inputs);
Samuel Antaod06239d2016-07-15 23:13:27 +00003176
Daniel Dunbar65229332009-03-13 11:38:42 +00003177 // Construct the actions to perform.
Richard Smithcd35eff2018-09-15 01:21:16 +00003178 HeaderModulePrecompileJobAction *HeaderModuleAction = nullptr;
Daniel Dunbar65229332009-03-13 11:38:42 +00003179 ActionList LinkerInputs;
Alp Toker965f8822013-11-27 05:22:15 +00003180
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00003181 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL;
Artem Belevich5bde4e02015-07-20 20:02:54 +00003182 for (auto &I : Inputs) {
3183 types::ID InputType = I.first;
3184 const Arg *InputArg = I.second;
Daniel Dunbar65229332009-03-13 11:38:42 +00003185
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00003186 PL.clear();
3187 types::getCompilationPhases(InputType, PL);
Daniel Dunbar65229332009-03-13 11:38:42 +00003188
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003189 // If the first step comes after the final phase we are doing as part of
3190 // this compilation, warn the user about it.
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00003191 phases::ID InitialPhase = PL[0];
Daniel Dunbar65229332009-03-13 11:38:42 +00003192 if (InitialPhase > FinalPhase) {
Martin Storsjo665c7a42018-05-04 06:05:58 +00003193 if (InputArg->isClaimed())
3194 continue;
3195
Daniel Dunbaradc5c7c2009-03-19 07:57:08 +00003196 // Claim here to avoid the more general unused warning.
3197 InputArg->claim();
Daniel Dunbar07806ca2009-09-17 04:13:26 +00003198
Daniel Dunbar2db3e732011-04-20 15:44:48 +00003199 // Suppress all unused style warnings with -Qunused-arguments
3200 if (Args.hasArg(options::OPT_Qunused_arguments))
3201 continue;
3202
Richard Smith403f76e2012-08-06 04:09:06 +00003203 // Special case when final phase determined by binary name, rather than
3204 // by a command-line argument with a corresponding Arg.
Hans Wennborg70850d82013-07-18 20:29:38 +00003205 if (CCCIsCPP())
Richard Smith403f76e2012-08-06 04:09:06 +00003206 Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003207 << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
Daniel Dunbar07806ca2009-09-17 04:13:26 +00003208 // Special case '-E' warning on a previously preprocessed file to make
3209 // more sense.
Richard Smith403f76e2012-08-06 04:09:06 +00003210 else if (InitialPhase == phases::Compile &&
3211 FinalPhase == phases::Preprocess &&
3212 getPreprocessedType(InputType) == types::TY_INVALID)
Daniel Dunbar07806ca2009-09-17 04:13:26 +00003213 Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003214 << InputArg->getAsString(Args) << !!FinalPhaseArg
3215 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
Daniel Dunbar07806ca2009-09-17 04:13:26 +00003216 else
3217 Diag(clang::diag::warn_drv_input_file_unused)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003218 << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
3219 << !!FinalPhaseArg
3220 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
Daniel Dunbar65229332009-03-13 11:38:42 +00003221 continue;
3222 }
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003223
Nico Weberad2d8f32016-04-21 19:59:10 +00003224 if (YcArg) {
3225 // Add a separate precompile phase for the compile phase.
3226 if (FinalPhase >= phases::Compile) {
Richard Smith8cd452d2016-08-30 18:55:16 +00003227 const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType);
Nico Weberad2d8f32016-04-21 19:59:10 +00003228 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PCHPL;
Richard Smith8cd452d2016-08-30 18:55:16 +00003229 types::getCompilationPhases(HeaderType, PCHPL);
Nico Weberad2d8f32016-04-21 19:59:10 +00003230 // Build the pipeline for the pch file.
Richard Smith8cd452d2016-08-30 18:55:16 +00003231 Action *ClangClPch =
Erich Keane76675de2018-07-05 17:22:13 +00003232 C.MakeAction<InputAction>(*InputArg, HeaderType);
Nico Weberad2d8f32016-04-21 19:59:10 +00003233 for (phases::ID Phase : PCHPL)
3234 ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
3235 assert(ClangClPch);
3236 Actions.push_back(ClangClPch);
3237 // The driver currently exits after the first failed command. This
3238 // relies on that behavior, to make sure if the pch generation fails,
3239 // the main compilation won't run.
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00003240 // FIXME: If the main compilation fails, the PCH generation should
3241 // probably not be considered successful either.
Nico Weberad2d8f32016-04-21 19:59:10 +00003242 }
3243 }
3244
Daniel Dunbar65229332009-03-13 11:38:42 +00003245 // Build the pipeline for this file.
Justin Lebar41094612016-01-11 23:07:27 +00003246 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
Samuel Antao64e965e2016-09-30 15:34:19 +00003247
3248 // Use the current host action in any of the offloading actions, if
3249 // required.
3250 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
3251 break;
3252
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003253 for (SmallVectorImpl<phases::ID>::iterator i = PL.begin(), e = PL.end();
3254 i != e; ++i) {
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00003255 phases::ID Phase = *i;
Daniel Dunbar65229332009-03-13 11:38:42 +00003256
3257 // We are done if this step is past what the user requested.
3258 if (Phase > FinalPhase)
3259 break;
3260
Samuel Antao64e965e2016-09-30 15:34:19 +00003261 // Add any offload action the host action depends on.
3262 Current = OffloadBuilder.addDeviceDependencesToHostAction(
3263 Current, InputArg, Phase, FinalPhase, PL);
3264 if (!Current)
3265 break;
3266
Daniel Dunbar65229332009-03-13 11:38:42 +00003267 // Queue linker inputs.
3268 if (Phase == phases::Link) {
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00003269 assert((i + 1) == e && "linking must be final compilation step.");
Justin Lebar41094612016-01-11 23:07:27 +00003270 LinkerInputs.push_back(Current);
3271 Current = nullptr;
Daniel Dunbar65229332009-03-13 11:38:42 +00003272 break;
3273 }
3274
Richard Smithcd35eff2018-09-15 01:21:16 +00003275 // Each precompiled header file after a module file action is a module
3276 // header of that same module file, rather than being compiled to a
3277 // separate PCH.
3278 if (Phase == phases::Precompile && HeaderModuleAction &&
3279 getPrecompiledType(InputType) == types::TY_PCH) {
3280 HeaderModuleAction->addModuleHeaderInput(Current);
3281 Current = nullptr;
3282 break;
3283 }
3284
3285 // FIXME: Should we include any prior module file outputs as inputs of
3286 // later actions in the same command line?
3287
Samuel Antao64e965e2016-09-30 15:34:19 +00003288 // Otherwise construct the appropriate action.
Richard Smithcd35eff2018-09-15 01:21:16 +00003289 Action *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current);
Samuel Antao64e965e2016-09-30 15:34:19 +00003290
3291 // We didn't create a new action, so we will just move to the next phase.
3292 if (NewCurrent == Current)
Daniel Dunbar13864952009-03-24 20:17:30 +00003293 continue;
3294
Richard Smithcd35eff2018-09-15 01:21:16 +00003295 if (auto *HMA = dyn_cast<HeaderModulePrecompileJobAction>(NewCurrent))
3296 HeaderModuleAction = HMA;
3297
Samuel Antao64e965e2016-09-30 15:34:19 +00003298 Current = NewCurrent;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003299
Samuel Antao64e965e2016-09-30 15:34:19 +00003300 // Use the current host action in any of the offloading actions, if
3301 // required.
3302 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
3303 break;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003304
Daniel Dunbar65229332009-03-13 11:38:42 +00003305 if (Current->getType() == types::TY_Nothing)
3306 break;
3307 }
3308
Samuel Antao64e965e2016-09-30 15:34:19 +00003309 // If we ended with something, add to the output list.
3310 if (Current)
Justin Lebar41094612016-01-11 23:07:27 +00003311 Actions.push_back(Current);
Samuel Antao64e965e2016-09-30 15:34:19 +00003312
3313 // Add any top level actions generated for offloading.
3314 OffloadBuilder.appendTopLevelActions(Actions, Current, InputArg);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00003315 }
Daniel Dunbar65229332009-03-13 11:38:42 +00003316
Samuel Antao64e965e2016-09-30 15:34:19 +00003317 // Add a link action if necessary.
Samuel Antaod06239d2016-07-15 23:13:27 +00003318 if (!LinkerInputs.empty()) {
Samuel Antao64e965e2016-09-30 15:34:19 +00003319 Action *LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image);
3320 LA = OffloadBuilder.processHostLinkAction(LA);
3321 Actions.push_back(LA);
Samuel Antaod06239d2016-07-15 23:13:27 +00003322 }
Daniel Dunbarc7a67b72009-12-22 23:19:32 +00003323
3324 // If we are linking, claim any options which are obviously only used for
3325 // compilation.
Hans Wennborga8ef14f2013-09-17 00:03:41 +00003326 if (FinalPhase == phases::Link && PL.size() == 1) {
Daniel Dunbarc7a67b72009-12-22 23:19:32 +00003327 Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
Hans Wennborga8ef14f2013-09-17 00:03:41 +00003328 Args.ClaimAllArgs(options::OPT_cl_compile_Group);
3329 }
3330
3331 // Claim ignored clang-cl options.
3332 Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
Artem Belevichbaae0932015-07-28 21:01:30 +00003333
Justin Lebardc3c5042016-04-19 02:27:07 +00003334 // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed
3335 // to non-CUDA compilations and should not trigger warnings there.
Artem Belevichbaae0932015-07-28 21:01:30 +00003336 Args.ClaimAllArgs(options::OPT_cuda_host_only);
Justin Lebardc3c5042016-04-19 02:27:07 +00003337 Args.ClaimAllArgs(options::OPT_cuda_compile_host_device);
Daniel Dunbar65229332009-03-13 11:38:42 +00003338}
3339
Artem Belevichecb178b2018-03-21 22:22:59 +00003340Action *Driver::ConstructPhaseAction(
3341 Compilation &C, const ArgList &Args, phases::ID Phase, Action *Input,
3342 Action::OffloadKind TargetDeviceOffloadKind) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00003343 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
Samuel Antao64e965e2016-09-30 15:34:19 +00003344
3345 // Some types skip the assembler phase (e.g., llvm-bc), but we can't
3346 // encode this in the steps because the intermediate type depends on
3347 // arguments. Just special case here.
3348 if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm)
3349 return Input;
3350
Daniel Dunbar65229332009-03-13 11:38:42 +00003351 // Build the appropriate action.
3352 switch (Phase) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003353 case phases::Link:
3354 llvm_unreachable("link action invalid here.");
Daniel Dunbar65229332009-03-13 11:38:42 +00003355 case phases::Preprocess: {
Daniel Dunbard67a3222009-03-30 06:36:42 +00003356 types::ID OutputTy;
3357 // -{M, MM} alter the output type.
Daniel Dunbar86aed7d2010-12-08 21:33:40 +00003358 if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
Daniel Dunbard67a3222009-03-30 06:36:42 +00003359 OutputTy = types::TY_Dependencies;
3360 } else {
David Blaikie5d577a22012-06-29 22:03:56 +00003361 OutputTy = Input->getType();
3362 if (!Args.hasFlag(options::OPT_frewrite_includes,
Justin Bognerce8245b2014-06-24 08:01:01 +00003363 options::OPT_fno_rewrite_includes, false) &&
Richard Smith86a3ef52017-06-09 21:24:02 +00003364 !Args.hasFlag(options::OPT_frewrite_imports,
3365 options::OPT_fno_rewrite_imports, false) &&
Justin Bognerce8245b2014-06-24 08:01:01 +00003366 !CCGenDiagnostics)
David Blaikie5d577a22012-06-29 22:03:56 +00003367 OutputTy = types::getPreprocessedType(OutputTy);
Daniel Dunbard67a3222009-03-30 06:36:42 +00003368 assert(OutputTy != types::TY_INVALID &&
3369 "Cannot preprocess this input type!");
3370 }
Justin Lebar41094612016-01-11 23:07:27 +00003371 return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
Daniel Dunbar65229332009-03-13 11:38:42 +00003372 }
Aaron Ballman1f10cc52012-07-31 01:21:00 +00003373 case phases::Precompile: {
Richard Smithdd4ad3d2016-08-30 19:06:26 +00003374 types::ID OutputTy = getPrecompiledType(Input->getType());
3375 assert(OutputTy != types::TY_INVALID &&
3376 "Cannot precompile this input type!");
Richard Smithcd35eff2018-09-15 01:21:16 +00003377
3378 // If we're given a module name, precompile header file inputs as a
3379 // module, not as a precompiled header.
3380 const char *ModName = nullptr;
3381 if (OutputTy == types::TY_PCH) {
3382 if (Arg *A = Args.getLastArg(options::OPT_fmodule_name_EQ))
3383 ModName = A->getValue();
3384 if (ModName)
3385 OutputTy = types::TY_ModuleFile;
3386 }
3387
Aaron Ballman1f10cc52012-07-31 01:21:00 +00003388 if (Args.hasArg(options::OPT_fsyntax_only)) {
3389 // Syntax checks should not emit a PCH file
3390 OutputTy = types::TY_Nothing;
3391 }
Richard Smithcd35eff2018-09-15 01:21:16 +00003392
3393 if (ModName)
3394 return C.MakeAction<HeaderModulePrecompileJobAction>(Input, OutputTy,
3395 ModName);
Justin Lebar41094612016-01-11 23:07:27 +00003396 return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
Aaron Ballman1f10cc52012-07-31 01:21:00 +00003397 }
Daniel Dunbar65229332009-03-13 11:38:42 +00003398 case phases::Compile: {
David Blaikie486f4402014-08-29 07:25:23 +00003399 if (Args.hasArg(options::OPT_fsyntax_only))
Justin Lebar41094612016-01-11 23:07:27 +00003400 return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
David Blaikie486f4402014-08-29 07:25:23 +00003401 if (Args.hasArg(options::OPT_rewrite_objc))
Justin Lebar41094612016-01-11 23:07:27 +00003402 return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
David Blaikie486f4402014-08-29 07:25:23 +00003403 if (Args.hasArg(options::OPT_rewrite_legacy_objc))
Justin Lebar41094612016-01-11 23:07:27 +00003404 return C.MakeAction<CompileJobAction>(Input,
3405 types::TY_RewrittenLegacyObjC);
David Blaikie486f4402014-08-29 07:25:23 +00003406 if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto))
Justin Lebar41094612016-01-11 23:07:27 +00003407 return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
David Blaikie486f4402014-08-29 07:25:23 +00003408 if (Args.hasArg(options::OPT__migrate))
Justin Lebar41094612016-01-11 23:07:27 +00003409 return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
David Blaikie486f4402014-08-29 07:25:23 +00003410 if (Args.hasArg(options::OPT_emit_ast))
Justin Lebar41094612016-01-11 23:07:27 +00003411 return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
David Blaikie486f4402014-08-29 07:25:23 +00003412 if (Args.hasArg(options::OPT_module_file_info))
Justin Lebar41094612016-01-11 23:07:27 +00003413 return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
David Blaikie486f4402014-08-29 07:25:23 +00003414 if (Args.hasArg(options::OPT_verify_pch))
Justin Lebar41094612016-01-11 23:07:27 +00003415 return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
3416 return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
Bob Wilson23a55f12014-12-21 07:00:00 +00003417 }
3418 case phases::Backend: {
Artem Belevichecb178b2018-03-21 22:22:59 +00003419 if (isUsingLTO() && TargetDeviceOffloadKind == Action::OFK_None) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003420 types::ID Output =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003421 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
Justin Lebar41094612016-01-11 23:07:27 +00003422 return C.MakeAction<BackendJobAction>(Input, Output);
David Blaikie486f4402014-08-29 07:25:23 +00003423 }
3424 if (Args.hasArg(options::OPT_emit_llvm)) {
Shuxin Yang4b3c7ff2013-08-23 21:34:57 +00003425 types::ID Output =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003426 Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
Justin Lebar41094612016-01-11 23:07:27 +00003427 return C.MakeAction<BackendJobAction>(Input, Output);
Daniel Dunbar65229332009-03-13 11:38:42 +00003428 }
Justin Lebar41094612016-01-11 23:07:27 +00003429 return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
Daniel Dunbar65229332009-03-13 11:38:42 +00003430 }
3431 case phases::Assemble:
Justin Lebar21e5d4f2016-01-14 21:41:27 +00003432 return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
Daniel Dunbar65229332009-03-13 11:38:42 +00003433 }
3434
David Blaikie83d382b2011-09-23 05:06:16 +00003435 llvm_unreachable("invalid phase in ConstructPhaseAction");
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00003436}
3437
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00003438void Driver::BuildJobs(Compilation &C) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00003439 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
Daniel Dunbare75d8342009-03-16 06:56:51 +00003440
3441 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
3442
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003443 // It is an error to provide a -o option if we are making multiple output
3444 // files.
Daniel Dunbare75d8342009-03-16 06:56:51 +00003445 if (FinalOutput) {
3446 unsigned NumOutputs = 0;
Saleem Abdulrasoolda3f4e52014-12-29 21:02:47 +00003447 for (const Action *A : C.getActions())
3448 if (A->getType() != types::TY_Nothing)
Daniel Dunbare75d8342009-03-16 06:56:51 +00003449 ++NumOutputs;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003450
Daniel Dunbare75d8342009-03-16 06:56:51 +00003451 if (NumOutputs > 1) {
3452 Diag(clang::diag::err_drv_output_argument_with_multiple_files);
Craig Topper92fc2df2014-05-17 16:56:41 +00003453 FinalOutput = nullptr;
Daniel Dunbare75d8342009-03-16 06:56:51 +00003454 }
3455 }
3456
Chad Rosier35767232013-04-30 22:01:21 +00003457 // Collect the list of architectures.
3458 llvm::StringSet<> ArchNames;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00003459 if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO())
3460 for (const Arg *A : C.getArgs())
Chad Rosier35767232013-04-30 22:01:21 +00003461 if (A->getOption().matches(options::OPT_arch))
3462 ArchNames.insert(A->getValue());
Chad Rosier35767232013-04-30 22:01:21 +00003463
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003464 // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
3465 std::map<std::pair<const Action *, std::string>, InputInfo> CachedResults;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00003466 for (Action *A : C.getActions()) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003467 // If we are linking an image for multiple archs then the linker wants
3468 // -arch_multiple and -final_output <final image name>. Unfortunately, this
3469 // doesn't fit in cleanly because we have to pass this information down.
Daniel Dunbare75d8342009-03-16 06:56:51 +00003470 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003471 // FIXME: This is a hack; find a cleaner way to integrate this into the
3472 // process.
Craig Topper92fc2df2014-05-17 16:56:41 +00003473 const char *LinkingOutput = nullptr;
Daniel Dunbardd765242009-03-26 16:12:09 +00003474 if (isa<LipoJobAction>(A)) {
Daniel Dunbare75d8342009-03-16 06:56:51 +00003475 if (FinalOutput)
Richard Smithbd55daf2012-11-01 04:30:05 +00003476 LinkingOutput = FinalOutput->getValue();
Daniel Dunbare75d8342009-03-16 06:56:51 +00003477 else
Hans Wennborga7707222015-01-09 17:38:53 +00003478 LinkingOutput = getDefaultImageName();
Daniel Dunbare75d8342009-03-16 06:56:51 +00003479 }
3480
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003481 BuildJobsForAction(C, A, &C.getDefaultToolChain(),
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003482 /*BoundArch*/ StringRef(),
Daniel Dunbare75d8342009-03-16 06:56:51 +00003483 /*AtTopLevel*/ true,
Chad Rosier35767232013-04-30 22:01:21 +00003484 /*MultipleArchs*/ ArchNames.size() > 1,
Samuel Antaod06239d2016-07-15 23:13:27 +00003485 /*LinkingOutput*/ LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003486 /*TargetDeviceOffloadKind*/ Action::OFK_None);
Daniel Dunbare75d8342009-03-16 06:56:51 +00003487 }
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00003488
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003489 // If the user passed -Qunused-arguments or there were errors, don't warn
3490 // about any unused arguments.
Argyrios Kyrtzidis31448a42010-11-18 21:47:07 +00003491 if (Diags.hasErrorOccurred() ||
Daniel Dunbara3cfbe32009-04-07 19:04:18 +00003492 C.getArgs().hasArg(options::OPT_Qunused_arguments))
Daniel Dunbard175d972009-03-18 18:03:46 +00003493 return;
3494
Daniel Dunbar58399ae2009-03-29 22:24:54 +00003495 // Claim -### here.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003496 (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003497
Nico Weber47bf5052016-04-25 21:15:49 +00003498 // Claim --driver-mode, --rsp-quoting, it was handled earlier.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003499 (void)C.getArgs().hasArg(options::OPT_driver_mode);
Nico Weber47bf5052016-04-25 21:15:49 +00003500 (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
Hans Wennborg70850d82013-07-18 20:29:38 +00003501
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00003502 for (Arg *A : C.getArgs()) {
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00003503 // FIXME: It would be nice to be able to send the argument to the
David Blaikie9c902b52011-09-25 23:23:43 +00003504 // DiagnosticsEngine, so that extra values, position, and so on could be
3505 // printed.
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003506 if (!A->isClaimed()) {
Michael J. Spencer66e2b202012-10-19 22:37:06 +00003507 if (A->getOption().hasFlag(options::NoArgumentUnused))
Daniel Dunbara3cfbe32009-04-07 19:04:18 +00003508 continue;
3509
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003510 // Suppress the warning automatically if this is just a flag, and it is an
3511 // instance of an argument we already claimed.
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003512 const Option &Opt = A->getOption();
Michael J. Spencerad3ccc32012-08-20 21:41:17 +00003513 if (Opt.getKind() == Option::FlagClass) {
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003514 bool DuplicateClaimed = false;
3515
Sean Silva14facf32015-06-09 01:57:17 +00003516 for (const Arg *AA : C.getArgs().filtered(&Opt)) {
3517 if (AA->isClaimed()) {
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003518 DuplicateClaimed = true;
3519 break;
3520 }
3521 }
3522
3523 if (DuplicateClaimed)
3524 continue;
3525 }
3526
Ehsan Akhgarid8518332016-01-25 21:14:52 +00003527 // In clang-cl, don't mention unknown arguments here since they have
3528 // already been warned about.
3529 if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN))
3530 Diag(clang::diag::warn_drv_unused_argument)
3531 << A->getAsString(C.getArgs());
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003532 }
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00003533 }
Daniel Dunbar95e6b192009-03-13 22:12:33 +00003534}
Daniel Dunbarc4343942010-02-03 03:07:56 +00003535
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003536namespace {
3537/// Utility class to control the collapse of dependent actions and select the
3538/// tools accordingly.
3539class ToolSelector final {
3540 /// The tool chain this selector refers to.
3541 const ToolChain &TC;
Daniel Dunbarf9ff3502010-05-14 02:03:00 +00003542
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003543 /// The compilation this selector refers to.
3544 const Compilation &C;
Samuel Antaod06239d2016-07-15 23:13:27 +00003545
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003546 /// The base action this selector refers to.
3547 const JobAction *BaseAction;
Samuel Antaod06239d2016-07-15 23:13:27 +00003548
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003549 /// Set to true if the current toolchain refers to host actions.
3550 bool IsHostSelector;
Samuel Antaod06239d2016-07-15 23:13:27 +00003551
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003552 /// Set to true if save-temps and embed-bitcode functionalities are active.
3553 bool SaveTemps;
3554 bool EmbedBitcode;
3555
3556 /// Get previous dependent action or null if that does not exist. If
3557 /// \a CanBeCollapsed is false, that action must be legal to collapse or
3558 /// null will be returned.
3559 const JobAction *getPrevDependentAction(const ActionList &Inputs,
3560 ActionList &SavedOffloadAction,
3561 bool CanBeCollapsed = true) {
3562 // An option can be collapsed only if it has a single input.
3563 if (Inputs.size() != 1)
Craig Topper92fc2df2014-05-17 16:56:41 +00003564 return nullptr;
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003565
3566 Action *CurAction = *Inputs.begin();
3567 if (CanBeCollapsed &&
3568 !CurAction->isCollapsingWithNextDependentActionLegal())
3569 return nullptr;
3570
3571 // If the input action is an offload action. Look through it and save any
3572 // offload action that can be dropped in the event of a collapse.
3573 if (auto *OA = dyn_cast<OffloadAction>(CurAction)) {
3574 // If the dependent action is a device action, we will attempt to collapse
3575 // only with other device actions. Otherwise, we would do the same but
3576 // with host actions only.
3577 if (!IsHostSelector) {
3578 if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) {
3579 CurAction =
3580 OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
3581 if (CanBeCollapsed &&
3582 !CurAction->isCollapsingWithNextDependentActionLegal())
3583 return nullptr;
3584 SavedOffloadAction.push_back(OA);
3585 return dyn_cast<JobAction>(CurAction);
3586 }
3587 } else if (OA->hasHostDependence()) {
3588 CurAction = OA->getHostDependence();
3589 if (CanBeCollapsed &&
3590 !CurAction->isCollapsingWithNextDependentActionLegal())
3591 return nullptr;
3592 SavedOffloadAction.push_back(OA);
3593 return dyn_cast<JobAction>(CurAction);
3594 }
3595 return nullptr;
3596 }
3597
3598 return dyn_cast<JobAction>(CurAction);
3599 }
3600
3601 /// Return true if an assemble action can be collapsed.
3602 bool canCollapseAssembleAction() const {
3603 return TC.useIntegratedAs() && !SaveTemps &&
3604 !C.getArgs().hasArg(options::OPT_via_file_asm) &&
3605 !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
3606 !C.getArgs().hasArg(options::OPT__SLASH_Fa);
3607 }
3608
3609 /// Return true if a preprocessor action can be collapsed.
3610 bool canCollapsePreprocessorAction() const {
3611 return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
3612 !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
3613 !C.getArgs().hasArg(options::OPT_rewrite_objc);
3614 }
3615
3616 /// Struct that relates an action with the offload actions that would be
3617 /// collapsed with it.
3618 struct JobActionInfo final {
3619 /// The action this info refers to.
3620 const JobAction *JA = nullptr;
3621 /// The offload actions we need to take care off if this action is
3622 /// collapsed.
3623 ActionList SavedOffloadAction;
3624 };
3625
3626 /// Append collapsed offload actions from the give nnumber of elements in the
3627 /// action info array.
3628 static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction,
3629 ArrayRef<JobActionInfo> &ActionInfo,
3630 unsigned ElementNum) {
3631 assert(ElementNum <= ActionInfo.size() && "Invalid number of elements.");
3632 for (unsigned I = 0; I < ElementNum; ++I)
3633 CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(),
3634 ActionInfo[I].SavedOffloadAction.end());
3635 }
3636
3637 /// Functions that attempt to perform the combining. They detect if that is
3638 /// legal, and if so they update the inputs \a Inputs and the offload action
3639 /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with
3640 /// the combined action is returned. If the combining is not legal or if the
3641 /// tool does not exist, null is returned.
3642 /// Currently three kinds of collapsing are supported:
3643 /// - Assemble + Backend + Compile;
3644 /// - Assemble + Backend ;
3645 /// - Backend + Compile.
3646 const Tool *
3647 combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
Richard Smithcd35eff2018-09-15 01:21:16 +00003648 ActionList &Inputs,
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003649 ActionList &CollapsedOffloadAction) {
3650 if (ActionInfo.size() < 3 || !canCollapseAssembleAction())
3651 return nullptr;
3652 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
3653 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
3654 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA);
3655 if (!AJ || !BJ || !CJ)
3656 return nullptr;
3657
3658 // Get compiler tool.
3659 const Tool *T = TC.SelectTool(*CJ);
3660 if (!T)
3661 return nullptr;
3662
Steven Wu574b0f22016-03-01 01:07:58 +00003663 // When using -fembed-bitcode, it is required to have the same tool (clang)
3664 // for both CompilerJA and BackendJA. Otherwise, combine two stages.
3665 if (EmbedBitcode) {
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003666 const Tool *BT = TC.SelectTool(*BJ);
3667 if (BT == T)
3668 return nullptr;
Steven Wu574b0f22016-03-01 01:07:58 +00003669 }
Bob Wilson23a55f12014-12-21 07:00:00 +00003670
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003671 if (!T->hasIntegratedAssembler())
Bob Wilson23a55f12014-12-21 07:00:00 +00003672 return nullptr;
Samuel Antaod06239d2016-07-15 23:13:27 +00003673
Richard Smithcd35eff2018-09-15 01:21:16 +00003674 Inputs = CJ->getInputs();
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003675 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3676 /*NumElements=*/3);
3677 return T;
3678 }
3679 const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo,
Richard Smithcd35eff2018-09-15 01:21:16 +00003680 ActionList &Inputs,
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003681 ActionList &CollapsedOffloadAction) {
3682 if (ActionInfo.size() < 2 || !canCollapseAssembleAction())
3683 return nullptr;
3684 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
3685 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
3686 if (!AJ || !BJ)
3687 return nullptr;
3688
3689 // Retrieve the compile job, backend action must always be preceded by one.
3690 ActionList CompileJobOffloadActions;
3691 auto *CJ = getPrevDependentAction(BJ->getInputs(), CompileJobOffloadActions,
3692 /*CanBeCollapsed=*/false);
3693 if (!AJ || !BJ || !CJ)
3694 return nullptr;
3695
3696 assert(isa<CompileJobAction>(CJ) &&
3697 "Expecting compile job preceding backend job.");
3698
3699 // Get compiler tool.
3700 const Tool *T = TC.SelectTool(*CJ);
3701 if (!T)
3702 return nullptr;
3703
3704 if (!T->hasIntegratedAssembler())
3705 return nullptr;
3706
Richard Smithcd35eff2018-09-15 01:21:16 +00003707 Inputs = BJ->getInputs();
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003708 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3709 /*NumElements=*/2);
3710 return T;
3711 }
3712 const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
Richard Smithcd35eff2018-09-15 01:21:16 +00003713 ActionList &Inputs,
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003714 ActionList &CollapsedOffloadAction) {
Teresa Johnson9e4321c2018-04-17 16:39:25 +00003715 if (ActionInfo.size() < 2)
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003716 return nullptr;
3717 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA);
3718 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA);
3719 if (!BJ || !CJ)
3720 return nullptr;
3721
Teresa Johnson9e4321c2018-04-17 16:39:25 +00003722 // Check if the initial input (to the compile job or its predessor if one
3723 // exists) is LLVM bitcode. In that case, no preprocessor step is required
3724 // and we can still collapse the compile and backend jobs when we have
3725 // -save-temps. I.e. there is no need for a separate compile job just to
3726 // emit unoptimized bitcode.
3727 bool InputIsBitcode = true;
3728 for (size_t i = 1; i < ActionInfo.size(); i++)
3729 if (ActionInfo[i].JA->getType() != types::TY_LLVM_BC &&
3730 ActionInfo[i].JA->getType() != types::TY_LTO_BC) {
3731 InputIsBitcode = false;
3732 break;
3733 }
3734 if (!InputIsBitcode && !canCollapsePreprocessorAction())
3735 return nullptr;
3736
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003737 // Get compiler tool.
3738 const Tool *T = TC.SelectTool(*CJ);
3739 if (!T)
3740 return nullptr;
3741
Teresa Johnson9e4321c2018-04-17 16:39:25 +00003742 if (T->canEmitIR() && ((SaveTemps && !InputIsBitcode) || EmbedBitcode))
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003743 return nullptr;
3744
Richard Smithcd35eff2018-09-15 01:21:16 +00003745 Inputs = CJ->getInputs();
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003746 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3747 /*NumElements=*/2);
3748 return T;
3749 }
3750
3751 /// Updates the inputs if the obtained tool supports combining with
3752 /// preprocessor action, and the current input is indeed a preprocessor
3753 /// action. If combining results in the collapse of offloading actions, those
3754 /// are appended to \a CollapsedOffloadAction.
Richard Smithcd35eff2018-09-15 01:21:16 +00003755 void combineWithPreprocessor(const Tool *T, ActionList &Inputs,
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003756 ActionList &CollapsedOffloadAction) {
3757 if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP())
3758 return;
3759
3760 // Attempt to get a preprocessor action dependence.
3761 ActionList PreprocessJobOffloadActions;
Richard Smithcd35eff2018-09-15 01:21:16 +00003762 ActionList NewInputs;
3763 for (Action *A : Inputs) {
3764 auto *PJ = getPrevDependentAction({A}, PreprocessJobOffloadActions);
3765 if (!PJ || !isa<PreprocessJobAction>(PJ)) {
3766 NewInputs.push_back(A);
3767 continue;
3768 }
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003769
Richard Smithcd35eff2018-09-15 01:21:16 +00003770 // This is legal to combine. Append any offload action we found and add the
3771 // current input to preprocessor inputs.
3772 CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(),
3773 PreprocessJobOffloadActions.end());
3774 NewInputs.append(PJ->input_begin(), PJ->input_end());
3775 }
3776 Inputs = NewInputs;
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003777 }
3778
3779public:
3780 ToolSelector(const JobAction *BaseAction, const ToolChain &TC,
3781 const Compilation &C, bool SaveTemps, bool EmbedBitcode)
3782 : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps),
3783 EmbedBitcode(EmbedBitcode) {
3784 assert(BaseAction && "Invalid base action.");
3785 IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None;
3786 }
3787
3788 /// Check if a chain of actions can be combined and return the tool that can
3789 /// handle the combination of actions. The pointer to the current inputs \a
3790 /// Inputs and the list of offload actions \a CollapsedOffloadActions
3791 /// connected to collapsed actions are updated accordingly. The latter enables
3792 /// the caller of the selector to process them afterwards instead of just
3793 /// dropping them. If no suitable tool is found, null will be returned.
Richard Smithcd35eff2018-09-15 01:21:16 +00003794 const Tool *getTool(ActionList &Inputs,
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003795 ActionList &CollapsedOffloadAction) {
3796 //
3797 // Get the largest chain of actions that we could combine.
3798 //
3799
3800 SmallVector<JobActionInfo, 5> ActionChain(1);
3801 ActionChain.back().JA = BaseAction;
3802 while (ActionChain.back().JA) {
3803 const Action *CurAction = ActionChain.back().JA;
3804
3805 // Grow the chain by one element.
3806 ActionChain.resize(ActionChain.size() + 1);
3807 JobActionInfo &AI = ActionChain.back();
3808
3809 // Attempt to fill it with the
3810 AI.JA =
3811 getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction);
Daniel Dunbarc4343942010-02-03 03:07:56 +00003812 }
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003813
3814 // Pop the last action info as it could not be filled.
3815 ActionChain.pop_back();
3816
3817 //
3818 // Attempt to combine actions. If all combining attempts failed, just return
3819 // the tool of the provided action. At the end we attempt to combine the
3820 // action with any preprocessor action it may depend on.
3821 //
3822
3823 const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs,
3824 CollapsedOffloadAction);
3825 if (!T)
3826 T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction);
3827 if (!T)
3828 T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction);
3829 if (!T) {
Richard Smithcd35eff2018-09-15 01:21:16 +00003830 Inputs = BaseAction->getInputs();
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003831 T = TC.SelectTool(*BaseAction);
3832 }
3833
3834 combineWithPreprocessor(T, Inputs, CollapsedOffloadAction);
3835 return T;
Daniel Dunbarc4343942010-02-03 03:07:56 +00003836 }
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003837};
Daniel Dunbarc4343942010-02-03 03:07:56 +00003838}
3839
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003840/// Return a string that uniquely identifies the result of a job. The bound arch
3841/// is not necessarily represented in the toolchain's triple -- for example,
3842/// armv7 and armv7s both map to the same triple -- so we need both in our map.
3843/// Also, we need to add the offloading device kind, as the same tool chain can
3844/// be used for host and device for some programming models, e.g. OpenMP.
3845static std::string GetTriplePlusArchString(const ToolChain *TC,
3846 StringRef BoundArch,
3847 Action::OffloadKind OffloadKind) {
Justin Lebar55c83322016-01-16 03:30:08 +00003848 std::string TriplePlusArch = TC->getTriple().normalize();
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003849 if (!BoundArch.empty()) {
Justin Lebar55c83322016-01-16 03:30:08 +00003850 TriplePlusArch += "-";
3851 TriplePlusArch += BoundArch;
3852 }
Samuel Antao59efaed2016-10-27 17:31:22 +00003853 TriplePlusArch += "-";
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003854 TriplePlusArch += Action::GetOffloadKindName(OffloadKind);
3855 return TriplePlusArch;
3856}
3857
3858InputInfo Driver::BuildJobsForAction(
3859 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
3860 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
3861 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
3862 Action::OffloadKind TargetDeviceOffloadKind) const {
3863 std::pair<const Action *, std::string> ActionTC = {
3864 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003865 auto CachedResult = CachedResults.find(ActionTC);
3866 if (CachedResult != CachedResults.end()) {
3867 return CachedResult->second;
3868 }
Samuel Antaod06239d2016-07-15 23:13:27 +00003869 InputInfo Result = BuildJobsForActionNoCache(
3870 C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003871 CachedResults, TargetDeviceOffloadKind);
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003872 CachedResults[ActionTC] = Result;
3873 return Result;
3874}
3875
3876InputInfo Driver::BuildJobsForActionNoCache(
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003877 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003878 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
Samuel Antaod06239d2016-07-15 23:13:27 +00003879 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003880 Action::OffloadKind TargetDeviceOffloadKind) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003881 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
Daniel Dunbarc4acf9d2009-03-18 23:18:19 +00003882
Samuel Antaod06239d2016-07-15 23:13:27 +00003883 InputInfoList OffloadDependencesInputInfo;
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003884 bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None;
Samuel Antaod06239d2016-07-15 23:13:27 +00003885 if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
Alex Lorenz4003a982017-08-08 11:22:21 +00003886 // The 'Darwin' toolchain is initialized only when its arguments are
3887 // computed. Get the default arguments for OFK_None to ensure that
3888 // initialization is performed before processing the offload action.
3889 // FIXME: Remove when darwin's toolchain is initialized during construction.
3890 C.getArgsForToolChain(TC, BoundArch, Action::OFK_None);
3891
Samuel Antaod06239d2016-07-15 23:13:27 +00003892 // The offload action is expected to be used in four different situations.
3893 //
3894 // a) Set a toolchain/architecture/kind for a host action:
3895 // Host Action 1 -> OffloadAction -> Host Action 2
3896 //
3897 // b) Set a toolchain/architecture/kind for a device action;
3898 // Device Action 1 -> OffloadAction -> Device Action 2
3899 //
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003900 // c) Specify a device dependence to a host action;
Samuel Antaod06239d2016-07-15 23:13:27 +00003901 // Device Action 1 _
3902 // \
3903 // Host Action 1 ---> OffloadAction -> Host Action 2
3904 //
3905 // d) Specify a host dependence to a device action.
3906 // Host Action 1 _
3907 // \
3908 // Device Action 1 ---> OffloadAction -> Device Action 2
3909 //
3910 // For a) and b), we just return the job generated for the dependence. For
3911 // c) and d) we override the current action with the host/device dependence
3912 // if the current toolchain is host/device and set the offload dependences
3913 // info with the jobs obtained from the device/host dependence(s).
3914
3915 // If there is a single device option, just generate the job for it.
3916 if (OA->hasSingleDeviceDependence()) {
3917 InputInfo DevA;
3918 OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
3919 const char *DepBoundArch) {
3920 DevA =
3921 BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
3922 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003923 CachedResults, DepA->getOffloadingDeviceKind());
Samuel Antaod06239d2016-07-15 23:13:27 +00003924 });
3925 return DevA;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003926 }
Samuel Antaod06239d2016-07-15 23:13:27 +00003927
3928 // If 'Action 2' is host, we generate jobs for the device dependences and
3929 // override the current action with the host dependence. Otherwise, we
3930 // generate the host dependences and override the action with the device
3931 // dependence. The dependences can't therefore be a top-level action.
3932 OA->doOnEachDependence(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003933 /*IsHostDependence=*/BuildingForOffloadDevice,
Samuel Antaod06239d2016-07-15 23:13:27 +00003934 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3935 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
3936 C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false,
3937 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003938 DepA->getOffloadingDeviceKind()));
Samuel Antaod06239d2016-07-15 23:13:27 +00003939 });
3940
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003941 A = BuildingForOffloadDevice
Samuel Antaod06239d2016-07-15 23:13:27 +00003942 ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
3943 : OA->getHostDependence();
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003944 }
3945
Daniel Dunbare75d8342009-03-16 06:56:51 +00003946 if (const InputAction *IA = dyn_cast<InputAction>(A)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003947 // FIXME: It would be nice to not claim this here; maybe the old scheme of
3948 // just using Args was better?
Daniel Dunbar5cdf3e02009-03-19 07:29:38 +00003949 const Arg &Input = IA->getInputArg();
3950 Input.claim();
Daniel Dunbar35cbfeb2010-06-09 22:31:08 +00003951 if (Input.getOption().matches(options::OPT_INPUT)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00003952 const char *Name = Input.getValue();
Justin Lebard98cea82016-01-11 23:15:21 +00003953 return InputInfo(A, Name, /* BaseInput = */ Name);
Douglas Katzman678d0cb2015-06-16 18:01:24 +00003954 }
Justin Lebard98cea82016-01-11 23:15:21 +00003955 return InputInfo(A, &Input, /* BaseInput = */ "");
Daniel Dunbare75d8342009-03-16 06:56:51 +00003956 }
3957
3958 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
Chad Rosiera78a6eb2012-04-27 16:50:38 +00003959 const ToolChain *TC;
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003960 StringRef ArchName = BAA->getArchName();
Daniel Dunbar1ef3f2a2009-09-08 23:37:19 +00003961
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003962 if (!ArchName.empty())
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +00003963 TC = &getToolChain(C.getArgs(),
Petr Hosekdd38d932018-05-29 22:35:39 +00003964 computeTargetTriple(*this, TargetTriple,
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +00003965 C.getArgs(), ArchName));
Chad Rosiera78a6eb2012-04-27 16:50:38 +00003966 else
3967 TC = &C.getDefaultToolChain();
Daniel Dunbar1ef3f2a2009-09-08 23:37:19 +00003968
Nico Weber5a459f82016-02-23 19:30:43 +00003969 return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
Samuel Antaod06239d2016-07-15 23:13:27 +00003970 MultipleArchs, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003971 TargetDeviceOffloadKind);
Daniel Dunbare75d8342009-03-16 06:56:51 +00003972 }
3973
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003974
Richard Smithcd35eff2018-09-15 01:21:16 +00003975 ActionList Inputs = A->getInputs();
Daniel Dunbarc4343942010-02-03 03:07:56 +00003976
3977 const JobAction *JA = cast<JobAction>(A);
Samuel Antaod06239d2016-07-15 23:13:27 +00003978 ActionList CollapsedOffloadActions;
3979
Mehdi Amini6683e222017-01-24 18:12:25 +00003980 ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(),
3981 embedBitcodeInObject() && !isUsingLTO());
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003982 const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions);
3983
Rafael Espindola79764462013-03-24 15:06:53 +00003984 if (!T)
Justin Lebar9eaa4892016-01-11 23:09:32 +00003985 return InputInfo();
Daniel Dunbare75d8342009-03-16 06:56:51 +00003986
Samuel Antaod06239d2016-07-15 23:13:27 +00003987 // If we've collapsed action list that contained OffloadAction we
3988 // need to build jobs for host/device-side inputs it may have held.
3989 for (const auto *OA : CollapsedOffloadActions)
3990 cast<OffloadAction>(OA)->doOnEachDependence(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003991 /*IsHostDependence=*/BuildingForOffloadDevice,
Samuel Antaod06239d2016-07-15 23:13:27 +00003992 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3993 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
Artem Belevichbee2f412016-08-22 18:50:34 +00003994 C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false,
Samuel Antaod06239d2016-07-15 23:13:27 +00003995 /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003996 DepA->getOffloadingDeviceKind()));
Samuel Antaod06239d2016-07-15 23:13:27 +00003997 });
Artem Belevichf8144ab2015-08-27 18:10:41 +00003998
Daniel Dunbare75d8342009-03-16 06:56:51 +00003999 // Only use pipes when there is exactly one input.
Daniel Dunbar1a093d22009-03-18 06:00:36 +00004000 InputInfoList InputInfos;
Richard Smithcd35eff2018-09-15 01:21:16 +00004001 for (const Action *Input : Inputs) {
Eric Christopher14668dd2013-02-18 00:38:25 +00004002 // Treat dsymutil and verify sub-jobs as being at the top-level too, they
4003 // shouldn't get temporary output names.
Daniel Dunbar6beaf512010-06-04 18:28:41 +00004004 // FIXME: Clean this up.
Justin Lebar9eaa4892016-01-11 23:09:32 +00004005 bool SubJobAtTopLevel =
4006 AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
Samuel Antaod06239d2016-07-15 23:13:27 +00004007 InputInfos.push_back(BuildJobsForAction(
4008 C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004009 CachedResults, A->getOffloadingDeviceKind()));
Daniel Dunbare75d8342009-03-16 06:56:51 +00004010 }
4011
Daniel Dunbare75d8342009-03-16 06:56:51 +00004012 // Always use the first input as the base input.
4013 const char *BaseInput = InputInfos[0].getBaseInput();
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004014
Daniel Dunbar6beaf512010-06-04 18:28:41 +00004015 // ... except dsymutil actions, which use their actual input as the base
4016 // input.
4017 if (JA->getType() == types::TY_dSYM)
4018 BaseInput = InputInfos[0].getFilename();
4019
Richard Smithcd35eff2018-09-15 01:21:16 +00004020 // ... and in header module compilations, which use the module name.
4021 if (auto *ModuleJA = dyn_cast<HeaderModulePrecompileJobAction>(JA))
4022 BaseInput = ModuleJA->getModuleName();
4023
Samuel Antaod06239d2016-07-15 23:13:27 +00004024 // Append outputs of offload device jobs to the input list
4025 if (!OffloadDependencesInputInfo.empty())
4026 InputInfos.append(OffloadDependencesInputInfo.begin(),
4027 OffloadDependencesInputInfo.end());
Artem Belevich0ff05cd2015-07-13 23:27:56 +00004028
Vedant Kumar18286cf2016-07-27 23:02:20 +00004029 // Set the effective triple of the toolchain for the duration of this job.
4030 llvm::Triple EffectiveTriple;
4031 const ToolChain &ToolTC = T->getToolChain();
Samuel Antao31fef982016-10-27 17:39:44 +00004032 const ArgList &Args =
4033 C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind());
Vedant Kumar18286cf2016-07-27 23:02:20 +00004034 if (InputInfos.size() != 1) {
4035 EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args));
4036 } else {
4037 // Pass along the input type if it can be unambiguously determined.
4038 EffectiveTriple = llvm::Triple(
4039 ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType()));
4040 }
4041 RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple);
4042
Daniel Dunbard00272f2010-08-02 02:38:15 +00004043 // Determine the place to write output to, if any.
Justin Lebar9eaa4892016-01-11 23:09:32 +00004044 InputInfo Result;
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004045 InputInfoList UnbundlingResults;
4046 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) {
4047 // If we have an unbundling job, we need to create results for all the
4048 // outputs. We also update the results cache so that other actions using
4049 // this unbundling action can get the right results.
4050 for (auto &UI : UA->getDependentActionsInfo()) {
4051 assert(UI.DependentOffloadKind != Action::OFK_None &&
4052 "Unbundling with no offloading??");
4053
4054 // Unbundling actions are never at the top level. When we generate the
4055 // offloading prefix, we also do that for the host file because the
4056 // unbundling action does not change the type of the output which can
4057 // cause a overwrite.
4058 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
4059 UI.DependentOffloadKind,
4060 UI.DependentToolChain->getTriple().normalize(),
4061 /*CreatePrefixForHost=*/true);
4062 auto CurI = InputInfo(
Yaxun Liu609f7522018-05-11 19:02:18 +00004063 UA,
4064 GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch,
4065 /*AtTopLevel=*/false,
4066 MultipleArchs ||
4067 UI.DependentOffloadKind == Action::OFK_HIP,
4068 OffloadingPrefix),
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004069 BaseInput);
4070 // Save the unbundling result.
4071 UnbundlingResults.push_back(CurI);
4072
4073 // Get the unique string identifier for this dependence and cache the
4074 // result.
Yaxun Liu470b8332018-06-06 19:44:10 +00004075 StringRef Arch;
4076 if (TargetDeviceOffloadKind == Action::OFK_HIP) {
4077 if (UI.DependentOffloadKind == Action::OFK_Host)
Yaxun Liuf37b50a2018-07-24 01:03:44 +00004078 Arch = StringRef();
Yaxun Liu470b8332018-06-06 19:44:10 +00004079 else
4080 Arch = UI.DependentBoundArch;
4081 } else
4082 Arch = BoundArch;
4083
4084 CachedResults[{A, GetTriplePlusArchString(UI.DependentToolChain, Arch,
4085 UI.DependentOffloadKind)}] =
4086 CurI;
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004087 }
4088
4089 // Now that we have all the results generated, select the one that should be
4090 // returned for the current depending action.
4091 std::pair<const Action *, std::string> ActionTC = {
4092 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
4093 assert(CachedResults.find(ActionTC) != CachedResults.end() &&
4094 "Result does not exist??");
4095 Result = CachedResults[ActionTC];
4096 } else if (JA->getType() == types::TY_Nothing)
Justin Lebard98cea82016-01-11 23:15:21 +00004097 Result = InputInfo(A, BaseInput);
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004098 else {
4099 // We only have to generate a prefix for the host if this is not a top-level
4100 // action.
4101 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
4102 A->getOffloadingDeviceKind(), TC->getTriple().normalize(),
4103 /*CreatePrefixForHost=*/!!A->getOffloadingHostActiveKinds() &&
4104 !AtTopLevel);
Justin Lebard98cea82016-01-11 23:15:21 +00004105 Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
Samuel Antaod06239d2016-07-15 23:13:27 +00004106 AtTopLevel, MultipleArchs,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004107 OffloadingPrefix),
Justin Lebard98cea82016-01-11 23:15:21 +00004108 BaseInput);
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004109 }
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004110
Chad Rosierbe10f982011-08-02 17:58:04 +00004111 if (CCCPrintBindings && !CCGenDiagnostics) {
Rafael Espindola79764462013-03-24 15:06:53 +00004112 llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
4113 << " - \"" << T->getName() << "\", inputs: [";
Daniel Dunbarb39cc522009-03-17 22:47:06 +00004114 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
4115 llvm::errs() << InputInfos[i].getAsString();
4116 if (i + 1 != e)
4117 llvm::errs() << ", ";
4118 }
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004119 if (UnbundlingResults.empty())
4120 llvm::errs() << "], output: " << Result.getAsString() << "\n";
4121 else {
4122 llvm::errs() << "], outputs: [";
4123 for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) {
4124 llvm::errs() << UnbundlingResults[i].getAsString();
4125 if (i + 1 != e)
4126 llvm::errs() << ", ";
4127 }
4128 llvm::errs() << "] \n";
4129 }
Daniel Dunbarb39cc522009-03-17 22:47:06 +00004130 } else {
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004131 if (UnbundlingResults.empty())
4132 T->ConstructJob(
4133 C, *JA, Result, InputInfos,
4134 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
4135 LinkingOutput);
4136 else
Samuel Antao7108bf32016-11-03 15:41:50 +00004137 T->ConstructJobMultipleOutputs(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004138 C, *JA, UnbundlingResults, InputInfos,
4139 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
4140 LinkingOutput);
Daniel Dunbarb39cc522009-03-17 22:47:06 +00004141 }
Justin Lebar9eaa4892016-01-11 23:09:32 +00004142 return Result;
Daniel Dunbare75d8342009-03-16 06:56:51 +00004143}
4144
Hans Wennborga7707222015-01-09 17:38:53 +00004145const char *Driver::getDefaultImageName() const {
Petr Hosekdd38d932018-05-29 22:35:39 +00004146 llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
Hans Wennborga7707222015-01-09 17:38:53 +00004147 return Target.isOSWindows() ? "a.exe" : "a.out";
4148}
4149
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004150/// Create output filename based on ArgValue, which could either be a
Hans Wennborg2c21f742013-10-17 16:16:23 +00004151/// full filename, filename without extension, or a directory. If ArgValue
4152/// does not provide a filename, then use BaseName, and use the extension
4153/// suitable for FileType.
Hans Wennborg207fcf02013-08-12 21:56:42 +00004154static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004155 StringRef BaseName,
4156 types::ID FileType) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00004157 SmallString<128> Filename = ArgValue;
Justin Bogner5aaf2e72014-06-26 20:59:36 +00004158
Hans Wennborgf1a74252013-09-10 20:18:04 +00004159 if (ArgValue.empty()) {
4160 // If the argument is empty, output to BaseName in the current dir.
4161 Filename = BaseName;
4162 } else if (llvm::sys::path::is_separator(Filename.back())) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00004163 // If the argument is a directory, output to BaseName in that dir.
4164 llvm::sys::path::append(Filename, BaseName);
4165 }
4166
4167 if (!llvm::sys::path::has_extension(ArgValue)) {
4168 // If the argument didn't provide an extension, then set it.
4169 const char *Extension = types::getTypeTempSuffix(FileType, true);
Hans Wennborgf1a74252013-09-10 20:18:04 +00004170
4171 if (FileType == types::TY_Image &&
4172 Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
4173 // The output file is a dll.
4174 Extension = "dll";
4175 }
4176
Hans Wennborg207fcf02013-08-12 21:56:42 +00004177 llvm::sys::path::replace_extension(Filename, Extension);
4178 }
4179
4180 return Args.MakeArgString(Filename.c_str());
4181}
4182
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004183const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004184 const char *BaseInput,
Mehdi Aminic50b1a22016-10-07 21:27:26 +00004185 StringRef BoundArch, bool AtTopLevel,
Samuel Antaod06239d2016-07-15 23:13:27 +00004186 bool MultipleArchs,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004187 StringRef OffloadingPrefix) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00004188 llvm::PrettyStackTraceString CrashInfo("Computing output path");
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004189 // Output to a user requested destination?
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004190 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004191 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
Chad Rosier633dcdc2013-01-24 19:14:47 +00004192 return C.addResultFile(FinalOutput->getValue(), &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004193 }
4194
Hans Wennborge0053472013-12-20 18:40:46 +00004195 // For /P, preprocess to file named after BaseInput.
4196 if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
4197 assert(AtTopLevel && isa<PreprocessJobAction>(JA));
4198 StringRef BaseName = llvm::sys::path::filename(BaseInput);
Hans Wennborg04c764f2014-06-17 00:19:12 +00004199 StringRef NameArg;
Greg Bedwell065f70a2015-06-09 10:24:06 +00004200 if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
Hans Wennborg04c764f2014-06-17 00:19:12 +00004201 NameArg = A->getValue();
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004202 return C.addResultFile(
4203 MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
4204 &JA);
Hans Wennborge0053472013-12-20 18:40:46 +00004205 }
4206
Nick Lewycky6e1ce292010-09-24 00:46:53 +00004207 // Default to writing to stdout?
David Blaikiebc023c92018-06-14 23:09:06 +00004208 if (AtTopLevel && !CCGenDiagnostics && isa<PreprocessJobAction>(JA))
Nick Lewycky6e1ce292010-09-24 00:46:53 +00004209 return "-";
4210
Hans Wennborg2c21f742013-10-17 16:16:23 +00004211 // Is this the assembly listing for /FA?
4212 if (JA.getType() == types::TY_PP_Asm &&
4213 (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
4214 C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
4215 // Use /Fa and the input filename to determine the asm file name.
4216 StringRef BaseName = llvm::sys::path::filename(BaseInput);
4217 StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004218 return C.addResultFile(
4219 MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
4220 &JA);
Hans Wennborg2c21f742013-10-17 16:16:23 +00004221 }
4222
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004223 // Output to a temporary file?
Reid Kleckner68eb60b2015-02-02 22:41:48 +00004224 if ((!AtTopLevel && !isSaveTempsEnabled() &&
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004225 !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
Chad Rosierbe10f982011-08-02 17:58:04 +00004226 CCGenDiagnostics) {
Chad Rosier97c37372011-08-26 22:27:02 +00004227 StringRef Name = llvm::sys::path::filename(BaseInput);
4228 std::pair<StringRef, StringRef> Split = Name.split('.');
Bob Haarman7e4d3ff2018-07-09 21:07:20 +00004229 SmallString<128> TmpName;
4230 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
4231 Arg *A = C.getArgs().getLastArg(options::OPT_fcrash_diagnostics_dir);
4232 if (CCGenDiagnostics && A) {
4233 SmallString<128> CrashDirectory(A->getValue());
4234 llvm::sys::path::append(CrashDirectory, Split.first);
4235 const char *Middle = Suffix ? "-%%%%%%." : "-%%%%%%";
4236 std::error_code EC =
4237 llvm::sys::fs::createUniqueFile(CrashDirectory + Middle + Suffix, TmpName);
4238 if (EC) {
4239 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
4240 return "";
4241 }
4242 } else {
4243 TmpName = GetTemporaryPath(Split.first, Suffix);
4244 }
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00004245 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004246 }
4247
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004248 SmallString<128> BasePath(BaseInput);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004249 StringRef BaseName;
Daniel Dunbar67fea712011-03-25 18:16:51 +00004250
4251 // Dsymutil actions should use the full path.
Eric Christopher551ef452011-08-23 17:56:55 +00004252 if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
Daniel Dunbar67fea712011-03-25 18:16:51 +00004253 BaseName = BasePath;
4254 else
4255 BaseName = llvm::sys::path::filename(BasePath);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004256
4257 // Determine what the derived output name should be.
4258 const char *NamedOutput;
Hans Wennborg2b89a262013-08-06 22:11:28 +00004259
Hans Wennborg625fba82016-10-04 21:01:04 +00004260 if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) &&
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00004261 C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
4262 // The /Fo or /o flag decides the object filename.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004263 StringRef Val =
4264 C.getArgs()
4265 .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
4266 ->getValue();
4267 NamedOutput =
4268 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
Hans Wennborg207fcf02013-08-12 21:56:42 +00004269 } else if (JA.getType() == types::TY_Image &&
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004270 C.getArgs().hasArg(options::OPT__SLASH_Fe,
4271 options::OPT__SLASH_o)) {
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00004272 // The /Fe or /o flag names the linked file.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004273 StringRef Val =
4274 C.getArgs()
4275 .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
4276 ->getValue();
4277 NamedOutput =
4278 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
Hans Wennborgf1a74252013-09-10 20:18:04 +00004279 } else if (JA.getType() == types::TY_Image) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00004280 if (IsCLMode()) {
4281 // clang-cl uses BaseName for the executable name.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004282 NamedOutput =
4283 MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
Samuel Antao59efaed2016-10-27 17:31:22 +00004284 } else {
Hans Wennborga7707222015-01-09 17:38:53 +00004285 SmallString<128> Output(getDefaultImageName());
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004286 Output += OffloadingPrefix;
Samuel Antao59efaed2016-10-27 17:31:22 +00004287 if (MultipleArchs && !BoundArch.empty()) {
4288 Output += "-";
4289 Output.append(BoundArch);
4290 }
Chad Rosier35767232013-04-30 22:01:21 +00004291 NamedOutput = C.getArgs().MakeArgString(Output.c_str());
Nico Weber2ca4be92016-03-01 23:16:44 +00004292 }
4293 } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00004294 NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName));
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004295 } else {
Hans Wennborg0a096a02013-09-05 17:05:56 +00004296 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004297 assert(Suffix && "All types used for output should have a suffix.");
4298
4299 std::string::size_type End = std::string::npos;
4300 if (!types::appendSuffixForType(JA.getType()))
4301 End = BaseName.rfind('.');
Chad Rosier35767232013-04-30 22:01:21 +00004302 SmallString<128> Suffixed(BaseName.substr(0, End));
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004303 Suffixed += OffloadingPrefix;
Mehdi Aminic50b1a22016-10-07 21:27:26 +00004304 if (MultipleArchs && !BoundArch.empty()) {
Chad Rosier35767232013-04-30 22:01:21 +00004305 Suffixed += "-";
4306 Suffixed.append(BoundArch);
4307 }
Bob Wilson23a55f12014-12-21 07:00:00 +00004308 // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
4309 // the unoptimized bitcode so that it does not get overwritten by the ".bc"
4310 // optimized bitcode output.
4311 if (!AtTopLevel && C.getArgs().hasArg(options::OPT_emit_llvm) &&
4312 JA.getType() == types::TY_LLVM_BC)
4313 Suffixed += ".tmp";
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004314 Suffixed += '.';
4315 Suffixed += Suffix;
4316 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
4317 }
4318
Reid Kleckner68eb60b2015-02-02 22:41:48 +00004319 // Prepend object file path if -save-temps=obj
4320 if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
4321 JA.getType() != types::TY_PCH) {
4322 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
4323 SmallString<128> TempPath(FinalOutput->getValue());
4324 llvm::sys::path::remove_filename(TempPath);
4325 StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
4326 llvm::sys::path::append(TempPath, OutputFileName);
4327 NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
4328 }
4329
Chad Rosier62135492012-07-09 17:31:28 +00004330 // If we're saving temps and the temp file conflicts with the input file,
Chad Rosier5b58af02012-04-20 20:05:08 +00004331 // then avoid overwriting input file.
Reid Kleckner68eb60b2015-02-02 22:41:48 +00004332 if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
Chad Rosier5b58af02012-04-20 20:05:08 +00004333 bool SameFile = false;
4334 SmallString<256> Result;
4335 llvm::sys::fs::current_path(Result);
4336 llvm::sys::path::append(Result, BaseName);
4337 llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
4338 // Must share the same path to conflict.
4339 if (SameFile) {
4340 StringRef Name = llvm::sys::path::filename(BaseInput);
4341 std::pair<StringRef, StringRef> Split = Name.split('.');
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004342 std::string TmpName = GetTemporaryPath(
4343 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00004344 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
Chad Rosier5b58af02012-04-20 20:05:08 +00004345 }
Chad Rosierf8412cd2011-07-15 21:54:29 +00004346 }
4347
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00004348 // As an annoying special case, PCH generation doesn't strip the pathname.
Nico Weber8ab92192016-03-02 23:29:29 +00004349 if (JA.getType() == types::TY_PCH && !IsCLMode()) {
Michael J. Spencere1696752010-12-18 00:19:12 +00004350 llvm::sys::path::remove_filename(BasePath);
4351 if (BasePath.empty())
Daniel Dunbare6c83192009-03-18 09:58:30 +00004352 BasePath = NamedOutput;
4353 else
Michael J. Spencere1696752010-12-18 00:19:12 +00004354 llvm::sys::path::append(BasePath, NamedOutput);
Chad Rosier633dcdc2013-01-24 19:14:47 +00004355 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004356 } else {
Chad Rosier633dcdc2013-01-24 19:14:47 +00004357 return C.addResultFile(NamedOutput, &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004358 }
4359}
4360
Mehdi Amini12011172016-10-06 05:11:48 +00004361std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const {
Raphael Isemannb23ccec2018-12-10 12:37:46 +00004362 // Search for Name in a list of paths.
Petr Hosek8f2499f2018-09-12 03:26:10 +00004363 auto SearchPaths = [&](const llvm::SmallVectorImpl<std::string> &P)
4364 -> llvm::Optional<std::string> {
4365 // Respect a limited subset of the '-Bprefix' functionality in GCC by
4366 // attempting to use this prefix when looking for file paths.
4367 for (const auto &Dir : P) {
4368 if (Dir.empty())
4369 continue;
4370 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
4371 llvm::sys::path::append(P, Name);
4372 if (llvm::sys::fs::exists(Twine(P)))
Simon Pilgrim4588fc82018-09-13 10:10:18 +00004373 return P.str().str();
Petr Hosek8f2499f2018-09-12 03:26:10 +00004374 }
4375 return None;
4376 };
4377
4378 if (auto P = SearchPaths(PrefixDirs))
4379 return *P;
Chandler Carruth84559242010-03-22 01:52:07 +00004380
Petr Hosek916a4672017-08-10 04:16:38 +00004381 SmallString<128> R(ResourceDir);
4382 llvm::sys::path::append(R, Name);
4383 if (llvm::sys::fs::exists(Twine(R)))
4384 return R.str();
4385
4386 SmallString<128> P(TC.getCompilerRTPath());
Rafael Espindola609a6642013-06-24 18:33:43 +00004387 llvm::sys::path::append(P, Name);
4388 if (llvm::sys::fs::exists(Twine(P)))
Peter Collingbournefa9771f2011-09-06 02:08:31 +00004389 return P.str();
4390
Petr Hosek8f2499f2018-09-12 03:26:10 +00004391 if (auto P = SearchPaths(TC.getLibraryPaths()))
4392 return *P;
4393
4394 if (auto P = SearchPaths(TC.getFilePaths()))
4395 return *P;
Daniel Dunbar68b01a02009-03-18 20:26:19 +00004396
Daniel Dunbar1ce81532009-09-09 22:33:00 +00004397 return Name;
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00004398}
4399
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004400void Driver::generatePrefixedToolNames(
Mehdi Amini12011172016-10-06 05:11:48 +00004401 StringRef Tool, const ToolChain &TC,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004402 SmallVectorImpl<std::string> &Names) const {
Petr Hosekdd38d932018-05-29 22:35:39 +00004403 // FIXME: Needs a better variable than TargetTriple
4404 Names.emplace_back((TargetTriple + "-" + Tool).str());
Benjamin Kramer3204b152015-05-29 19:42:19 +00004405 Names.emplace_back(Tool);
Vasileios Kalintirisc744e122015-11-12 15:26:54 +00004406
4407 // Allow the discovery of tools prefixed with LLVM's default target triple.
Petr Hosekdd38d932018-05-29 22:35:39 +00004408 std::string DefaultTargetTriple = llvm::sys::getDefaultTargetTriple();
4409 if (DefaultTargetTriple != TargetTriple)
4410 Names.emplace_back((DefaultTargetTriple + "-" + Tool).str());
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004411}
4412
Benjamin Kramer7111b912014-11-04 20:26:01 +00004413static bool ScanDirForExecutable(SmallString<128> &Dir,
4414 ArrayRef<std::string> Names) {
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004415 for (const auto &Name : Names) {
4416 llvm::sys::path::append(Dir, Name);
4417 if (llvm::sys::fs::can_execute(Twine(Dir)))
4418 return true;
4419 llvm::sys::path::remove_filename(Dir);
4420 }
4421 return false;
4422}
4423
Mehdi Amini12011172016-10-06 05:11:48 +00004424std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const {
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004425 SmallVector<std::string, 2> TargetSpecificExecutables;
4426 generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
4427
Chandler Carruth84559242010-03-22 01:52:07 +00004428 // Respect a limited subset of the '-Bprefix' functionality in GCC by
Logan Chiencd679fd2012-10-04 08:08:56 +00004429 // attempting to use this prefix when looking for program paths.
Saleem Abdulrasool23d99b12014-09-16 03:48:32 +00004430 for (const auto &PrefixDir : PrefixDirs) {
4431 if (llvm::sys::fs::is_directory(PrefixDir)) {
4432 SmallString<128> P(PrefixDir);
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004433 if (ScanDirForExecutable(P, TargetSpecificExecutables))
Rafael Espindola8be5c052013-06-19 13:24:29 +00004434 return P.str();
Simon Atanasyana47ba292012-10-31 14:39:28 +00004435 } else {
Mehdi Amini12011172016-10-06 05:11:48 +00004436 SmallString<128> P((PrefixDir + Name).str());
Rafael Espindola609a6642013-06-24 18:33:43 +00004437 if (llvm::sys::fs::can_execute(Twine(P)))
Rafael Espindola8be5c052013-06-19 13:24:29 +00004438 return P.str();
Simon Atanasyan86bdab72012-10-31 12:01:53 +00004439 }
Chandler Carruth84559242010-03-22 01:52:07 +00004440 }
4441
Daniel Dunbar68b01a02009-03-18 20:26:19 +00004442 const ToolChain::path_list &List = TC.getProgramPaths();
Saleem Abdulrasool23d99b12014-09-16 03:48:32 +00004443 for (const auto &Path : List) {
4444 SmallString<128> P(Path);
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004445 if (ScanDirForExecutable(P, TargetSpecificExecutables))
Rafael Espindola8be5c052013-06-19 13:24:29 +00004446 return P.str();
Daniel Dunbar68b01a02009-03-18 20:26:19 +00004447 }
4448
Daniel Dunbar76ce7412009-03-23 16:15:50 +00004449 // If all else failed, search the path.
Michael J. Spencerb011d482014-11-07 21:30:32 +00004450 for (const auto &TargetSpecificExecutable : TargetSpecificExecutables)
4451 if (llvm::ErrorOr<std::string> P =
4452 llvm::sys::findProgramByName(TargetSpecificExecutable))
Michael J. Spencer04162ea2014-11-04 01:30:55 +00004453 return *P;
Daniel Dunbar6f668772009-03-18 21:34:08 +00004454
Daniel Dunbar1ce81532009-09-09 22:33:00 +00004455 return Name;
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00004456}
4457
Mehdi Amini12011172016-10-06 05:11:48 +00004458std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const {
Rafael Espindola37d229d2013-06-25 04:26:55 +00004459 SmallString<128> Path;
Rafael Espindolac0809172014-06-12 14:02:15 +00004460 std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
Rafael Espindola37d229d2013-06-25 04:26:55 +00004461 if (EC) {
4462 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
Daniel Dunbare627c1c2009-03-18 19:34:39 +00004463 return "";
4464 }
4465
Rafael Espindola37d229d2013-06-25 04:26:55 +00004466 return Path.str();
Daniel Dunbare627c1c2009-03-18 19:34:39 +00004467}
4468
Nico Weber2ca4be92016-03-01 23:16:44 +00004469std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
4470 SmallString<128> Output;
4471 if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
4472 // FIXME: If anybody needs it, implement this obscure rule:
4473 // "If you specify a directory without a file name, the default file name
4474 // is VCx0.pch., where x is the major version of Visual C++ in use."
4475 Output = FpArg->getValue();
4476
4477 // "If you do not specify an extension as part of the path name, an
4478 // extension of .pch is assumed. "
4479 if (!llvm::sys::path::has_extension(Output))
4480 Output += ".pch";
4481 } else {
Mike Rice58df1af2018-09-11 17:10:44 +00004482 if (Arg *YcArg = C.getArgs().getLastArg(options::OPT__SLASH_Yc))
4483 Output = YcArg->getValue();
4484 if (Output.empty())
4485 Output = BaseName;
Nico Weber2ca4be92016-03-01 23:16:44 +00004486 llvm::sys::path::replace_extension(Output, ".pch");
4487 }
4488 return Output.str();
4489}
4490
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004491const ToolChain &Driver::getToolChain(const ArgList &Args,
Artem Belevich959e0542015-07-10 19:47:55 +00004492 const llvm::Triple &Target) const {
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004493
David Blaikie6ad71012017-01-13 18:53:43 +00004494 auto &TC = ToolChains[Target.str()];
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004495 if (!TC) {
4496 switch (Target.getOS()) {
Reid Kleckner330fb172016-05-11 16:19:05 +00004497 case llvm::Triple::Haiku:
David Blaikie6ad71012017-01-13 18:53:43 +00004498 TC = llvm::make_unique<toolchains::Haiku>(*this, Target, Args);
Reid Kleckner330fb172016-05-11 16:19:05 +00004499 break;
Ed Schouten4dabea22017-06-25 08:29:09 +00004500 case llvm::Triple::Ananas:
4501 TC = llvm::make_unique<toolchains::Ananas>(*this, Target, Args);
4502 break;
Ed Schouten3c3e58c2015-03-26 11:13:44 +00004503 case llvm::Triple::CloudABI:
David Blaikie6ad71012017-01-13 18:53:43 +00004504 TC = llvm::make_unique<toolchains::CloudABI>(*this, Target, Args);
Ed Schouten3c3e58c2015-03-26 11:13:44 +00004505 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004506 case llvm::Triple::Darwin:
4507 case llvm::Triple::MacOSX:
4508 case llvm::Triple::IOS:
Tim Northover6f3ff222015-10-30 16:30:27 +00004509 case llvm::Triple::TvOS:
4510 case llvm::Triple::WatchOS:
David Blaikie6ad71012017-01-13 18:53:43 +00004511 TC = llvm::make_unique<toolchains::DarwinClang>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004512 break;
4513 case llvm::Triple::DragonFly:
David Blaikie6ad71012017-01-13 18:53:43 +00004514 TC = llvm::make_unique<toolchains::DragonFly>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004515 break;
4516 case llvm::Triple::OpenBSD:
David Blaikie6ad71012017-01-13 18:53:43 +00004517 TC = llvm::make_unique<toolchains::OpenBSD>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004518 break;
4519 case llvm::Triple::NetBSD:
David Blaikie6ad71012017-01-13 18:53:43 +00004520 TC = llvm::make_unique<toolchains::NetBSD>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004521 break;
4522 case llvm::Triple::FreeBSD:
David Blaikie6ad71012017-01-13 18:53:43 +00004523 TC = llvm::make_unique<toolchains::FreeBSD>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004524 break;
4525 case llvm::Triple::Minix:
David Blaikie6ad71012017-01-13 18:53:43 +00004526 TC = llvm::make_unique<toolchains::Minix>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004527 break;
4528 case llvm::Triple::Linux:
Andrey Turetskiy4798eb62016-06-16 10:36:09 +00004529 case llvm::Triple::ELFIAMCU:
Chandler Carruthcf705b22012-01-25 21:03:58 +00004530 if (Target.getArch() == llvm::Triple::hexagon)
David Blaikie6ad71012017-01-13 18:53:43 +00004531 TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
4532 Args);
Vasileios Kalintirisc744e122015-11-12 15:26:54 +00004533 else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
4534 !Target.hasEnvironment())
David Blaikie6ad71012017-01-13 18:53:43 +00004535 TC = llvm::make_unique<toolchains::MipsLLVMToolChain>(*this, Target,
4536 Args);
Chandler Carruthcf705b22012-01-25 21:03:58 +00004537 else
David Blaikie6ad71012017-01-13 18:53:43 +00004538 TC = llvm::make_unique<toolchains::Linux>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004539 break;
Derek Schuff6ab52fa2015-03-30 20:31:33 +00004540 case llvm::Triple::NaCl:
David Blaikie6ad71012017-01-13 18:53:43 +00004541 TC = llvm::make_unique<toolchains::NaClToolChain>(*this, Target, Args);
Derek Schuff6ab52fa2015-03-30 20:31:33 +00004542 break;
Petr Hosek62e1d232016-10-06 06:08:09 +00004543 case llvm::Triple::Fuchsia:
David Blaikie6ad71012017-01-13 18:53:43 +00004544 TC = llvm::make_unique<toolchains::Fuchsia>(*this, Target, Args);
Petr Hosek62e1d232016-10-06 06:08:09 +00004545 break;
David Chisnallf571cde2012-02-15 13:39:01 +00004546 case llvm::Triple::Solaris:
David Blaikie6ad71012017-01-13 18:53:43 +00004547 TC = llvm::make_unique<toolchains::Solaris>(*this, Target, Args);
David Chisnallf571cde2012-02-15 13:39:01 +00004548 break;
Tom Stellard8fa33092015-07-18 01:49:05 +00004549 case llvm::Triple::AMDHSA:
David Blaikie6ad71012017-01-13 18:53:43 +00004550 TC = llvm::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args);
Tom Stellard8fa33092015-07-18 01:49:05 +00004551 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004552 case llvm::Triple::Win32:
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004553 switch (Target.getEnvironment()) {
4554 default:
4555 if (Target.isOSBinFormatELF())
David Blaikie6ad71012017-01-13 18:53:43 +00004556 TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004557 else if (Target.isOSBinFormatMachO())
David Blaikie6ad71012017-01-13 18:53:43 +00004558 TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004559 else
David Blaikie6ad71012017-01-13 18:53:43 +00004560 TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004561 break;
4562 case llvm::Triple::GNU:
David Blaikie6ad71012017-01-13 18:53:43 +00004563 TC = llvm::make_unique<toolchains::MinGW>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004564 break;
Saleem Abdulrasool543a78b2014-10-24 03:13:37 +00004565 case llvm::Triple::Itanium:
David Blaikie6ad71012017-01-13 18:53:43 +00004566 TC = llvm::make_unique<toolchains::CrossWindowsToolChain>(*this, Target,
4567 Args);
Saleem Abdulrasool543a78b2014-10-24 03:13:37 +00004568 break;
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004569 case llvm::Triple::MSVC:
4570 case llvm::Triple::UnknownEnvironment:
Dave Leef96bedf2017-11-06 21:18:05 +00004571 if (Args.getLastArgValue(options::OPT_fuse_ld_EQ)
4572 .startswith_lower("bfd"))
4573 TC = llvm::make_unique<toolchains::CrossWindowsToolChain>(
4574 *this, Target, Args);
4575 else
4576 TC =
4577 llvm::make_unique<toolchains::MSVCToolChain>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004578 break;
4579 }
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004580 break;
Filipe Cabecinhasc888e192015-10-14 12:25:43 +00004581 case llvm::Triple::PS4:
David Blaikie6ad71012017-01-13 18:53:43 +00004582 TC = llvm::make_unique<toolchains::PS4CPU>(*this, Target, Args);
Filipe Cabecinhasc888e192015-10-14 12:25:43 +00004583 break;
David L Kreitzerd397ea42016-10-14 20:44:33 +00004584 case llvm::Triple::Contiki:
David Blaikie6ad71012017-01-13 18:53:43 +00004585 TC = llvm::make_unique<toolchains::Contiki>(*this, Target, Args);
David L Kreitzerd397ea42016-10-14 20:44:33 +00004586 break;
Kristina Brooks77a4adc2018-11-29 03:49:14 +00004587 case llvm::Triple::Hurd:
4588 TC = llvm::make_unique<toolchains::Hurd>(*this, Target, Args);
4589 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004590 default:
Douglas Katzman9f5e70e2015-05-26 18:01:33 +00004591 // Of these targets, Hexagon is the only one that might have
4592 // an OS of Linux, in which case it got handled above already.
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004593 switch (Target.getArch()) {
4594 case llvm::Triple::tce:
David Blaikie6ad71012017-01-13 18:53:43 +00004595 TC = llvm::make_unique<toolchains::TCEToolChain>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004596 break;
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00004597 case llvm::Triple::tcele:
David Blaikie6ad71012017-01-13 18:53:43 +00004598 TC = llvm::make_unique<toolchains::TCELEToolChain>(*this, Target, Args);
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00004599 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004600 case llvm::Triple::hexagon:
David Blaikie6ad71012017-01-13 18:53:43 +00004601 TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
4602 Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004603 break;
Jacques Pienaard964cc22016-03-28 21:02:54 +00004604 case llvm::Triple::lanai:
David Blaikie6ad71012017-01-13 18:53:43 +00004605 TC = llvm::make_unique<toolchains::LanaiToolChain>(*this, Target, Args);
Jacques Pienaard964cc22016-03-28 21:02:54 +00004606 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004607 case llvm::Triple::xcore:
David Blaikie6ad71012017-01-13 18:53:43 +00004608 TC = llvm::make_unique<toolchains::XCoreToolChain>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004609 break;
Dan Gohmanc2853072015-09-03 22:51:53 +00004610 case llvm::Triple::wasm32:
4611 case llvm::Triple::wasm64:
David Blaikie6ad71012017-01-13 18:53:43 +00004612 TC = llvm::make_unique<toolchains::WebAssembly>(*this, Target, Args);
Dan Gohmanc2853072015-09-03 22:51:53 +00004613 break;
Dylan McKay924fa3a2017-01-05 05:20:27 +00004614 case llvm::Triple::avr:
David Blaikie6ad71012017-01-13 18:53:43 +00004615 TC = llvm::make_unique<toolchains::AVRToolChain>(*this, Target, Args);
Dylan McKay924fa3a2017-01-05 05:20:27 +00004616 break;
David Bolvanskyf4be2532018-07-31 14:21:46 +00004617 case llvm::Triple::riscv32:
4618 case llvm::Triple::riscv64:
4619 TC = llvm::make_unique<toolchains::RISCVToolChain>(*this, Target, Args);
4620 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004621 default:
Douglas Katzmand6e597c2015-09-17 19:56:40 +00004622 if (Target.getVendor() == llvm::Triple::Myriad)
David Blaikie6ad71012017-01-13 18:53:43 +00004623 TC = llvm::make_unique<toolchains::MyriadToolChain>(*this, Target,
4624 Args);
Jonathan Roelofs901c7762017-05-25 15:42:13 +00004625 else if (toolchains::BareMetal::handlesTarget(Target))
4626 TC = llvm::make_unique<toolchains::BareMetal>(*this, Target, Args);
Douglas Katzmand6e597c2015-09-17 19:56:40 +00004627 else if (Target.isOSBinFormatELF())
David Blaikie6ad71012017-01-13 18:53:43 +00004628 TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004629 else if (Target.isOSBinFormatMachO())
David Blaikie6ad71012017-01-13 18:53:43 +00004630 TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004631 else
David Blaikie6ad71012017-01-13 18:53:43 +00004632 TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004633 }
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004634 }
4635 }
Justin Lebar66c4fd72016-11-18 00:41:22 +00004636
4637 // Intentionally omitted from the switch above: llvm::Triple::CUDA. CUDA
4638 // compiles always need two toolchains, the CUDA toolchain and the host
4639 // toolchain. So the only valid way to create a CUDA toolchain is via
4640 // CreateOffloadingDeviceToolChains.
4641
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004642 return *TC;
Daniel Dunbar4dff6a42009-03-10 23:41:59 +00004643}
Daniel Dunbar8fa879d2009-03-24 18:57:02 +00004644
Rafael Espindola2f69d402013-03-18 15:33:26 +00004645bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
Douglas Katzman00249092015-06-12 15:45:21 +00004646 // Say "no" if there is not exactly one input of a type clang understands.
Nico Weber5a459f82016-02-23 19:30:43 +00004647 if (JA.size() != 1 ||
4648 !types::isAcceptedByClang((*JA.input_begin())->getType()))
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00004649 return false;
4650
Douglas Katzman00249092015-06-12 15:45:21 +00004651 // And say "no" if this is not a kind of action clang understands.
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00004652 if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
Bob Wilson23a55f12014-12-21 07:00:00 +00004653 !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00004654 return false;
4655
4656 return true;
4657}
4658
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00004659/// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
4660/// grouped values as integers. Numbers which are not provided are set to 0.
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004661///
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00004662/// \return True if the entire string was parsed (9.2), or all groups were
4663/// parsed (10.3.5extrastuff).
Mehdi Amini12011172016-10-06 05:11:48 +00004664bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
4665 unsigned &Micro, bool &HadExtra) {
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004666 HadExtra = false;
4667
4668 Major = Minor = Micro = 0;
Mehdi Amini12011172016-10-06 05:11:48 +00004669 if (Str.empty())
Bob Wilson433cb312015-04-07 01:03:35 +00004670 return false;
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004671
Mehdi Amini12011172016-10-06 05:11:48 +00004672 if (Str.consumeInteger(10, Major))
4673 return false;
4674 if (Str.empty())
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004675 return true;
Mehdi Amini12011172016-10-06 05:11:48 +00004676 if (Str[0] != '.')
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004677 return false;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00004678
Mehdi Amini12011172016-10-06 05:11:48 +00004679 Str = Str.drop_front(1);
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004680
Mehdi Amini12011172016-10-06 05:11:48 +00004681 if (Str.consumeInteger(10, Minor))
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004682 return false;
Mehdi Amini12011172016-10-06 05:11:48 +00004683 if (Str.empty())
4684 return true;
4685 if (Str[0] != '.')
4686 return false;
4687 Str = Str.drop_front(1);
4688
4689 if (Str.consumeInteger(10, Micro))
4690 return false;
4691 if (!Str.empty())
4692 HadExtra = true;
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004693 return true;
4694}
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004695
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004696/// Parse digits from a string \p Str and fulfill \p Digits with
4697/// the parsed numbers. This method assumes that the max number of
4698/// digits to look for is equal to Digits.size().
4699///
4700/// \return True if the entire string was parsed and there are
4701/// no extra characters remaining at the end.
Mehdi Amini12011172016-10-06 05:11:48 +00004702bool Driver::GetReleaseVersion(StringRef Str,
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004703 MutableArrayRef<unsigned> Digits) {
Mehdi Amini12011172016-10-06 05:11:48 +00004704 if (Str.empty())
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004705 return false;
4706
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004707 unsigned CurDigit = 0;
4708 while (CurDigit < Digits.size()) {
Mehdi Amini12011172016-10-06 05:11:48 +00004709 unsigned Digit;
4710 if (Str.consumeInteger(10, Digit))
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004711 return false;
Mehdi Amini12011172016-10-06 05:11:48 +00004712 Digits[CurDigit] = Digit;
4713 if (Str.empty())
4714 return true;
4715 if (Str[0] != '.')
4716 return false;
4717 Str = Str.drop_front(1);
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004718 CurDigit++;
4719 }
4720
4721 // More digits than requested, bail out...
4722 return false;
4723}
4724
Hans Wennborg797004d2018-11-08 11:27:04 +00004725std::pair<unsigned, unsigned> Driver::getIncludeExcludeOptionFlagMasks(bool IsClCompatMode) const {
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004726 unsigned IncludedFlagsBitmask = 0;
Rafael Espindolacc707bc2013-09-25 15:54:41 +00004727 unsigned ExcludedFlagsBitmask = options::NoDriverOption;
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004728
Hans Wennborg797004d2018-11-08 11:27:04 +00004729 if (IsClCompatMode) {
Hans Wennborg19076102013-07-31 20:51:53 +00004730 // Include CL and Core options.
4731 IncludedFlagsBitmask |= options::CLOption;
4732 IncludedFlagsBitmask |= options::CoreOption;
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004733 } else {
4734 ExcludedFlagsBitmask |= options::CLOption;
4735 }
4736
4737 return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
4738}
Benjamin Kramerab88f622014-03-25 18:02:07 +00004739
Douglas Katzmanf08fadf2015-06-04 14:40:44 +00004740bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
Benjamin Kramerab88f622014-03-25 18:02:07 +00004741 return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);
4742}