blob: a5aed299e399249825e5048158427f10628565a1 [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"
David L. Jonesf561aba2017-03-08 01:02:16 +000015#include "ToolChains/Clang.h"
16#include "ToolChains/CloudABI.h"
17#include "ToolChains/Contiki.h"
18#include "ToolChains/CrossWindows.h"
19#include "ToolChains/Cuda.h"
20#include "ToolChains/Darwin.h"
21#include "ToolChains/DragonFly.h"
22#include "ToolChains/FreeBSD.h"
23#include "ToolChains/Fuchsia.h"
24#include "ToolChains/Gnu.h"
Jonathan Roelofs901c7762017-05-25 15:42:13 +000025#include "ToolChains/BareMetal.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000026#include "ToolChains/Haiku.h"
27#include "ToolChains/Hexagon.h"
28#include "ToolChains/Lanai.h"
29#include "ToolChains/Linux.h"
30#include "ToolChains/MinGW.h"
31#include "ToolChains/Minix.h"
Konstantin Zhuravlyove37b32c2017-03-08 22:36:04 +000032#include "ToolChains/MipsLinux.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000033#include "ToolChains/MSVC.h"
34#include "ToolChains/Myriad.h"
35#include "ToolChains/NaCl.h"
36#include "ToolChains/NetBSD.h"
37#include "ToolChains/OpenBSD.h"
38#include "ToolChains/PS4CPU.h"
39#include "ToolChains/Solaris.h"
40#include "ToolChains/TCE.h"
41#include "ToolChains/WebAssembly.h"
42#include "ToolChains/XCore.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000043#include "clang/Basic/Version.h"
Benjamin Kramerd45b2052015-10-07 15:48:01 +000044#include "clang/Basic/VirtualFileSystem.h"
Alp Toker1d257e12014-06-04 03:28:55 +000045#include "clang/Config/config.h"
Daniel Dunbar1688f1a2009-03-12 07:58:46 +000046#include "clang/Driver/Action.h"
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000047#include "clang/Driver/Compilation.h"
Daniel Dunbarc0b3e952009-03-12 08:55:43 +000048#include "clang/Driver/DriverDiagnostic.h"
Daniel Dunbare75d8342009-03-16 06:56:51 +000049#include "clang/Driver/Job.h"
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000050#include "clang/Driver/Options.h"
Peter Collingbournea4ccff32015-02-20 20:30:56 +000051#include "clang/Driver/SanitizerArgs.h"
Daniel Dunbare75d8342009-03-16 06:56:51 +000052#include "clang/Driver/Tool.h"
53#include "clang/Driver/ToolChain.h"
Chris Lattnerce6c42f2011-03-23 04:04:01 +000054#include "llvm/ADT/ArrayRef.h"
Hans Wennborg6ddc6902013-07-27 00:23:45 +000055#include "llvm/ADT/STLExtras.h"
Justin Lebar62907612016-07-06 21:21:39 +000056#include "llvm/ADT/SmallSet.h"
Hans Wennborg23d26a32014-06-18 17:21:50 +000057#include "llvm/ADT/StringExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000058#include "llvm/ADT/StringSet.h"
Hans Wennborg70850d82013-07-18 20:29:38 +000059#include "llvm/ADT/StringSwitch.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000060#include "llvm/Option/Arg.h"
61#include "llvm/Option/ArgList.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000062#include "llvm/Option/OptSpecifier.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000063#include "llvm/Option/OptTable.h"
64#include "llvm/Option/Option.h"
Serge Pavlov208ac652018-01-01 13:27:01 +000065#include "llvm/Support/CommandLine.h"
David Blaikie79000202011-09-23 05:57:42 +000066#include "llvm/Support/ErrorHandling.h"
Michael J. Spencerf28df4c2010-12-17 21:22:22 +000067#include "llvm/Support/FileSystem.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000068#include "llvm/Support/Path.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000069#include "llvm/Support/PrettyStackTrace.h"
Hans Wennborg23d26a32014-06-18 17:21:50 +000070#include "llvm/Support/Process.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000071#include "llvm/Support/Program.h"
Dimitry Andric81c40422017-06-06 21:54:21 +000072#include "llvm/Support/TargetRegistry.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000073#include "llvm/Support/raw_ostream.h"
Serge Pavlov208ac652018-01-01 13:27:01 +000074#include "llvm/Support/StringSaver.h"
Dylan Noblesmith4f4e7452012-02-02 00:40:14 +000075#include <map>
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000076#include <memory>
Benjamin Kramercfeacf52016-05-27 14:27:13 +000077#include <utility>
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +000078#if LLVM_ON_UNIX
79#include <unistd.h> // getpid
80#endif
Dylan Noblesmith86780e92012-02-01 14:25:28 +000081
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000082using namespace clang::driver;
Chris Lattnerada1c912009-03-26 05:56:24 +000083using namespace clang;
Reid Kleckner898229a2013-06-14 17:17:23 +000084using namespace llvm::opt;
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000085
Reid Kleckner68eb60b2015-02-02 22:41:48 +000086Driver::Driver(StringRef ClangExecutable, StringRef DefaultTargetTriple,
Benjamin Kramerd45b2052015-10-07 15:48:01 +000087 DiagnosticsEngine &Diags,
88 IntrusiveRefCntPtr<vfs::FileSystem> VFS)
Benjamin Kramercfeacf52016-05-27 14:27:13 +000089 : Opts(createDriverOptTable()), Diags(Diags), VFS(std::move(VFS)),
90 Mode(GCCMode), SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
91 LTOMode(LTOK_None), ClangExecutable(ClangExecutable),
Nico Webere0c3f902017-07-23 16:31:47 +000092 SysRoot(DEFAULT_SYSROOT),
Reid Kleckner68eb60b2015-02-02 22:41:48 +000093 DriverTitle("clang LLVM compiler"), CCPrintOptionsFilename(nullptr),
94 CCPrintHeadersFilename(nullptr), CCLogDiagnosticsFilename(nullptr),
95 CCCPrintBindings(false), CCPrintHeaders(false), CCLogDiagnostics(false),
Vedant Kumarf2030b92016-07-18 19:56:33 +000096 CCGenDiagnostics(false), DefaultTargetTriple(DefaultTargetTriple),
Serge Pavlov208ac652018-01-01 13:27:01 +000097 CCCGenericGCCName(""), Saver(Alloc),
98 CheckInputsExist(true), CCCUsePCH(true),
Bruno Cardoso Lopes52dfe712017-04-12 21:46:20 +000099 GenReproducer(false), SuppressMissingInputWarning(false) {
Daniel Dunbar3f3e2cd2010-01-20 02:35:16 +0000100
Benjamin Kramerd45b2052015-10-07 15:48:01 +0000101 // Provide a sane fallback if no VFS is specified.
102 if (!this->VFS)
103 this->VFS = vfs::getRealFileSystem();
104
Sumanth Gundapaneni3a1592942015-03-03 20:43:12 +0000105 Name = llvm::sys::path::filename(ClangExecutable);
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000106 Dir = llvm::sys::path::parent_path(ClangExecutable);
Benjamin Kramerf420dda2015-10-13 15:19:32 +0000107 InstalledDir = Dir; // Provide a sensible default installed dir.
Bob Wilsona20a1da2013-03-23 05:17:59 +0000108
Serge Pavlov208ac652018-01-01 13:27:01 +0000109#if defined(CLANG_CONFIG_FILE_SYSTEM_DIR)
110 SystemConfigDir = CLANG_CONFIG_FILE_SYSTEM_DIR;
111#endif
112#if defined(CLANG_CONFIG_FILE_USER_DIR)
113 UserConfigDir = CLANG_CONFIG_FILE_USER_DIR;
114#endif
115
Bob Wilsona20a1da2013-03-23 05:17:59 +0000116 // Compute the path to the resource directory.
117 StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
118 SmallString<128> P(Dir);
Chandler Carruthfd3cc702014-12-29 12:09:08 +0000119 if (ClangResourceDir != "") {
Bob Wilsona20a1da2013-03-23 05:17:59 +0000120 llvm::sys::path::append(P, ClangResourceDir);
Chandler Carruthfd3cc702014-12-29 12:09:08 +0000121 } else {
122 StringRef ClangLibdirSuffix(CLANG_LIBDIR_SUFFIX);
Argyrios Kyrtzidisbcae0472017-02-25 18:14:35 +0000123 P = llvm::sys::path::parent_path(Dir);
124 llvm::sys::path::append(P, Twine("lib") + ClangLibdirSuffix, "clang",
Chandler Carruthfd3cc702014-12-29 12:09:08 +0000125 CLANG_VERSION_STRING);
126 }
Bob Wilsona20a1da2013-03-23 05:17:59 +0000127 ResourceDir = P.str();
Daniel Dunbar544ecd12009-03-02 19:59:07 +0000128}
129
Zachary Turneraff19c32016-08-12 17:47:52 +0000130void Driver::ParseDriverMode(StringRef ProgramName,
131 ArrayRef<const char *> Args) {
Serge Pavlov4e769842017-08-29 05:22:26 +0000132 ClangNameParts = ToolChain::getTargetAndModeFromProgramName(ProgramName);
133 setDriverModeFromOption(ClangNameParts.DriverMode);
Hans Wennborg70850d82013-07-18 20:29:38 +0000134
Douglas Katzman6bbffc42015-06-25 18:51:37 +0000135 for (const char *ArgPtr : Args) {
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000136 // Ingore nullptrs, they are response file's EOL markers
Douglas Katzman6bbffc42015-06-25 18:51:37 +0000137 if (ArgPtr == nullptr)
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000138 continue;
Douglas Katzman6bbffc42015-06-25 18:51:37 +0000139 const StringRef Arg = ArgPtr;
Zachary Turneraff19c32016-08-12 17:47:52 +0000140 setDriverModeFromOption(Arg);
Hans Wennborg70850d82013-07-18 20:29:38 +0000141 }
142}
143
Zachary Turneraff19c32016-08-12 17:47:52 +0000144void Driver::setDriverModeFromOption(StringRef Opt) {
145 const std::string OptName =
146 getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
147 if (!Opt.startswith(OptName))
148 return;
149 StringRef Value = Opt.drop_front(OptName.size());
150
151 const unsigned M = llvm::StringSwitch<unsigned>(Value)
152 .Case("gcc", GCCMode)
153 .Case("g++", GXXMode)
154 .Case("cpp", CPPMode)
155 .Case("cl", CLMode)
156 .Default(~0U);
157
158 if (M != ~0U)
159 Mode = static_cast<DriverMode>(M);
160 else
161 Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
162}
163
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000164InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings,
165 bool &ContainsError) {
Daniel Dunbar2608c542009-03-18 01:38:48 +0000166 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000167 ContainsError = false;
Hans Wennborg6ddc6902013-07-27 00:23:45 +0000168
169 unsigned IncludedFlagsBitmask;
170 unsigned ExcludedFlagsBitmask;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000171 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000172 getIncludeExcludeOptionFlagMasks();
Hans Wennborg6ddc6902013-07-27 00:23:45 +0000173
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000174 unsigned MissingArgIndex, MissingArgCount;
David Blaikie69a1d8c2015-06-22 22:07:27 +0000175 InputArgList Args =
David Blaikie6d492ad2015-06-21 06:32:36 +0000176 getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
177 IncludedFlagsBitmask, ExcludedFlagsBitmask);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +0000178
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000179 // Check for missing argument error.
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000180 if (MissingArgCount) {
181 Diag(diag::err_drv_missing_argument)
David Blaikie69a1d8c2015-06-22 22:07:27 +0000182 << Args.getArgString(MissingArgIndex) << MissingArgCount;
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000183 ContainsError |=
184 Diags.getDiagnosticLevel(diag::err_drv_missing_argument,
185 SourceLocation()) > DiagnosticsEngine::Warning;
186 }
Daniel Dunbar65229332009-03-13 11:38:42 +0000187
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000188 // Check for unsupported options.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000189 for (const Arg *A : Args) {
Michael J. Spencer66e2b202012-10-19 22:37:06 +0000190 if (A->getOption().hasFlag(options::Unsupported)) {
Brian Gesiak24910762018-01-06 00:25:40 +0000191 unsigned DiagID;
192 auto ArgString = A->getAsString(Args);
193 std::string Nearest;
194 if (getOpts().findNearest(
195 ArgString, Nearest, IncludedFlagsBitmask,
196 ExcludedFlagsBitmask | options::Unsupported) > 1) {
197 DiagID = diag::err_drv_unsupported_opt;
198 Diag(DiagID) << ArgString;
199 } else {
200 DiagID = diag::err_drv_unsupported_opt_with_suggestion;
201 Diag(DiagID) << ArgString << Nearest;
202 }
203 ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000204 DiagnosticsEngine::Warning;
Daniel Dunbard8500f32009-03-22 23:26:43 +0000205 continue;
206 }
Chad Rosierce975d92012-02-22 17:55:22 +0000207
208 // Warn about -mcpu= without an argument.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000209 if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000210 Diag(diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
211 ContainsError |= Diags.getDiagnosticLevel(
212 diag::warn_drv_empty_joined_argument,
213 SourceLocation()) > DiagnosticsEngine::Warning;
Chad Rosierce975d92012-02-22 17:55:22 +0000214 }
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000215 }
216
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000217 for (const Arg *A : Args.filtered(options::OPT_UNKNOWN)) {
Brian Gesiak24910762018-01-06 00:25:40 +0000218 unsigned DiagID;
219 auto ArgString = A->getAsString(Args);
220 std::string Nearest;
221 if (getOpts().findNearest(
222 ArgString, Nearest, IncludedFlagsBitmask, ExcludedFlagsBitmask) > 1) {
223 DiagID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl
224 : diag::err_drv_unknown_argument;
225 Diags.Report(DiagID) << ArgString;
226 } else {
227 DiagID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl_with_suggestion
228 : diag::err_drv_unknown_argument_with_suggestion;
229 Diags.Report(DiagID) << ArgString << Nearest;
230 }
231 ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000232 DiagnosticsEngine::Warning;
233 }
Rafael Espindola8a2d4962013-09-23 23:55:25 +0000234
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000235 return Args;
236}
237
Chad Rosier7742b5d2011-07-27 23:36:45 +0000238// Determine which compilation mode we are in. We look for options which
239// affect the phase, starting with the earliest phases, and record which
240// option we used to determine the final phase.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000241phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
242 Arg **FinalPhaseArg) const {
Craig Topper92fc2df2014-05-17 16:56:41 +0000243 Arg *PhaseArg = nullptr;
Chad Rosier7742b5d2011-07-27 23:36:45 +0000244 phases::ID FinalPhase;
Eric Christopherf901e852011-08-17 22:59:59 +0000245
Hans Wennborge50cec32014-06-13 20:59:54 +0000246 // -{E,EP,P,M,MM} only run the preprocessor.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000247 if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
Hans Wennborge50cec32014-06-13 20:59:54 +0000248 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
Hans Wennborge0053472013-12-20 18:40:46 +0000249 (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
250 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000251 FinalPhase = phases::Preprocess;
Eric Christopherf901e852011-08-17 22:59:59 +0000252
Richard Smithdd4ad3d2016-08-30 19:06:26 +0000253 // --precompile only runs up to precompilation.
254 } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile))) {
255 FinalPhase = phases::Precompile;
256
Bob Wilson23a55f12014-12-21 07:00:00 +0000257 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
Chad Rosier7742b5d2011-07-27 23:36:45 +0000258 } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000259 (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
Ben Langmuir2cb4a782014-02-05 22:21:15 +0000260 (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
Chad Rosier7742b5d2011-07-27 23:36:45 +0000261 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
Fariborz Jahanian73223bb2012-04-02 15:59:19 +0000262 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
Ted Kremenekf7639e12012-03-06 20:06:33 +0000263 (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
Chad Rosier7742b5d2011-07-27 23:36:45 +0000264 (PhaseArg = DAL.getLastArg(options::OPT__analyze,
Chad Rosier1aeb15a2012-03-06 23:14:35 +0000265 options::OPT__analyze_auto)) ||
Bob Wilson23a55f12014-12-21 07:00:00 +0000266 (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000267 FinalPhase = phases::Compile;
268
Bob Wilson23a55f12014-12-21 07:00:00 +0000269 // -S only runs up to the backend.
270 } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
271 FinalPhase = phases::Backend;
272
Artem Belevich4242f412015-07-28 21:01:21 +0000273 // -c compilation only runs up to the assembler.
274 } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000275 FinalPhase = phases::Assemble;
276
277 // Otherwise do everything.
278 } else
279 FinalPhase = phases::Link;
280
281 if (FinalPhaseArg)
282 *FinalPhaseArg = PhaseArg;
283
284 return FinalPhase;
285}
286
David Blaikie0aaa7622017-01-13 17:34:15 +0000287static Arg *MakeInputArg(DerivedArgList &Args, OptTable &Opts,
Hans Wennborged1d0722013-08-13 21:32:29 +0000288 StringRef Value) {
David Blaikie0aaa7622017-01-13 17:34:15 +0000289 Arg *A = new Arg(Opts.getOption(options::OPT_INPUT), Value,
Hans Wennborged1d0722013-08-13 21:32:29 +0000290 Args.getBaseArgs().MakeIndex(Value), Value.data());
Hans Wennborg55362852014-05-02 22:55:30 +0000291 Args.AddSynthesizedArg(A);
Hans Wennborged1d0722013-08-13 21:32:29 +0000292 A->claim();
293 return A;
294}
295
Daniel Dunbar775d4062010-06-11 22:00:26 +0000296DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
297 DerivedArgList *DAL = new DerivedArgList(Args);
298
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000299 bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
Nirav Daveb0bb6142015-11-24 16:07:21 +0000300 bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +0000301 for (Arg *A : Args) {
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000302 // Unfortunately, we have to parse some forwarding options (-Xassembler,
303 // -Xlinker, -Xpreprocessor) because we either integrate their functionality
304 // (assembler and preprocessor), or bypass a previous driver ('collect2').
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000305
306 // Rewrite linker options, to replace --no-demangle with a custom internal
307 // option.
308 if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
309 A->getOption().matches(options::OPT_Xlinker)) &&
310 A->containsValue("--no-demangle")) {
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000311 // Add the rewritten no-demangle argument.
312 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
313
314 // Add the remaining values as Xlinker arguments.
Benjamin Kramer72e64312015-09-24 14:48:49 +0000315 for (StringRef Val : A->getValues())
Douglas Katzmana34b7bf2015-06-30 19:32:57 +0000316 if (Val != "--no-demangle")
317 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), Val);
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000318
319 continue;
320 }
321
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000322 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
323 // some build systems. We don't try to be complete here because we don't
324 // care to encourage this usage model.
325 if (A->getOption().matches(options::OPT_Wp_COMMA) &&
Richard Smithbd55daf2012-11-01 04:30:05 +0000326 (A->getValue(0) == StringRef("-MD") ||
327 A->getValue(0) == StringRef("-MMD"))) {
Daniel Dunbar3648ba72010-06-15 20:30:18 +0000328 // Rewrite to -MD/-MMD along with -MF.
Richard Smithbd55daf2012-11-01 04:30:05 +0000329 if (A->getValue(0) == StringRef("-MD"))
Daniel Dunbar3648ba72010-06-15 20:30:18 +0000330 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
331 else
332 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
Michael J. Spencer70d85be2012-11-07 23:37:14 +0000333 if (A->getNumValues() == 2)
334 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
335 A->getValue(1));
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000336 continue;
337 }
338
Shantonu Senafeb03b2010-09-17 18:39:08 +0000339 // Rewrite reserved library names.
340 if (A->getOption().matches(options::OPT_l)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000341 StringRef Value = A->getValue();
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000342
Shantonu Senafeb03b2010-09-17 18:39:08 +0000343 // Rewrite unless -nostdlib is present.
Nirav Daveb0bb6142015-11-24 16:07:21 +0000344 if (!HasNostdlib && !HasNodefaultlib && Value == "stdc++") {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000345 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_stdcxx));
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000346 continue;
347 }
Shantonu Senafeb03b2010-09-17 18:39:08 +0000348
349 // Rewrite unconditionally.
350 if (Value == "cc_kext") {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000351 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_cckext));
Shantonu Senafeb03b2010-09-17 18:39:08 +0000352 continue;
353 }
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000354 }
355
Hans Wennborged1d0722013-08-13 21:32:29 +0000356 // Pick up inputs via the -- option.
357 if (A->getOption().matches(options::OPT__DASH_DASH)) {
358 A->claim();
Benjamin Kramer72e64312015-09-24 14:48:49 +0000359 for (StringRef Val : A->getValues())
David Blaikie0aaa7622017-01-13 17:34:15 +0000360 DAL->append(MakeInputArg(*DAL, *Opts, Val));
Hans Wennborged1d0722013-08-13 21:32:29 +0000361 continue;
362 }
363
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +0000364 DAL->append(A);
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000365 }
Daniel Dunbar775d4062010-06-11 22:00:26 +0000366
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000367 // Enforce -static if -miamcu is present.
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000368 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false))
369 DAL->AddFlagArg(0, Opts->getOption(options::OPT_static));
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000370
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000371// Add a default value of -mlinker-version=, if one was given and the user
372// didn't specify one.
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000373#if defined(HOST_LINK_VERSION)
Tim Northover018578c2015-06-12 19:21:35 +0000374 if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
375 strlen(HOST_LINK_VERSION) > 0) {
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000376 DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
377 HOST_LINK_VERSION);
Daniel Dunbarb613ffc2010-08-17 22:32:45 +0000378 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000379 }
380#endif
381
Daniel Dunbar775d4062010-06-11 22:00:26 +0000382 return DAL;
383}
384
Artem Belevich959e0542015-07-10 19:47:55 +0000385/// \brief Compute target triple from args.
386///
387/// This routine provides the logic to compute a target triple from various
388/// args passed to the driver and the default triple string.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000389static llvm::Triple computeTargetTriple(const Driver &D,
390 StringRef DefaultTargetTriple,
Artem Belevich959e0542015-07-10 19:47:55 +0000391 const ArgList &Args,
392 StringRef DarwinArchName = "") {
393 // FIXME: Already done in Compilation *Driver::BuildCompilation
394 if (const Arg *A = Args.getLastArg(options::OPT_target))
395 DefaultTargetTriple = A->getValue();
396
397 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
398
399 // Handle Apple-specific options available here.
400 if (Target.isOSBinFormatMachO()) {
401 // If an explict Darwin arch name is given, that trumps all.
402 if (!DarwinArchName.empty()) {
403 tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
404 return Target;
405 }
406
407 // Handle the Darwin '-arch' flag.
408 if (Arg *A = Args.getLastArg(options::OPT_arch)) {
409 StringRef ArchName = A->getValue();
410 tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
411 }
412 }
413
414 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
415 // '-mbig-endian'/'-EB'.
416 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
417 options::OPT_mbig_endian)) {
418 if (A->getOption().matches(options::OPT_mlittle_endian)) {
419 llvm::Triple LE = Target.getLittleEndianArchVariant();
420 if (LE.getArch() != llvm::Triple::UnknownArch)
421 Target = std::move(LE);
422 } else {
423 llvm::Triple BE = Target.getBigEndianArchVariant();
424 if (BE.getArch() != llvm::Triple::UnknownArch)
425 Target = std::move(BE);
426 }
427 }
428
429 // Skip further flag support on OSes which don't support '-m32' or '-m64'.
Douglas Katzman15a63ed2015-08-12 18:36:12 +0000430 if (Target.getArch() == llvm::Triple::tce ||
431 Target.getOS() == llvm::Triple::Minix)
Artem Belevich959e0542015-07-10 19:47:55 +0000432 return Target;
433
434 // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000435 Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
436 options::OPT_m32, options::OPT_m16);
437 if (A) {
Artem Belevich959e0542015-07-10 19:47:55 +0000438 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
439
440 if (A->getOption().matches(options::OPT_m64)) {
441 AT = Target.get64BitArchVariant().getArch();
442 if (Target.getEnvironment() == llvm::Triple::GNUX32)
443 Target.setEnvironment(llvm::Triple::GNU);
444 } else if (A->getOption().matches(options::OPT_mx32) &&
445 Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
446 AT = llvm::Triple::x86_64;
447 Target.setEnvironment(llvm::Triple::GNUX32);
448 } else if (A->getOption().matches(options::OPT_m32)) {
449 AT = Target.get32BitArchVariant().getArch();
450 if (Target.getEnvironment() == llvm::Triple::GNUX32)
451 Target.setEnvironment(llvm::Triple::GNU);
452 } else if (A->getOption().matches(options::OPT_m16) &&
453 Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
454 AT = llvm::Triple::x86;
455 Target.setEnvironment(llvm::Triple::CODE16);
456 }
457
458 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
459 Target.setArch(AT);
460 }
461
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000462 // Handle -miamcu flag.
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000463 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
464 if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
465 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
466 << Target.str();
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000467
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000468 if (A && !A->getOption().matches(options::OPT_m32))
469 D.Diag(diag::err_drv_argument_not_allowed_with)
470 << "-miamcu" << A->getBaseArg().getAsString(Args);
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000471
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000472 Target.setArch(llvm::Triple::x86);
473 Target.setArchName("i586");
474 Target.setEnvironment(llvm::Triple::UnknownEnvironment);
475 Target.setEnvironmentName("");
476 Target.setOS(llvm::Triple::ELFIAMCU);
477 Target.setVendor(llvm::Triple::UnknownVendor);
478 Target.setVendorName("intel");
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000479 }
480
Artem Belevich959e0542015-07-10 19:47:55 +0000481 return Target;
482}
483
Teresa Johnson945bc502015-10-15 20:35:53 +0000484// \brief Parse the LTO options and record the type of LTO compilation
485// based on which -f(no-)?lto(=.*)? option occurs last.
486void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
487 LTOMode = LTOK_None;
488 if (!Args.hasFlag(options::OPT_flto, options::OPT_flto_EQ,
489 options::OPT_fno_lto, false))
490 return;
491
492 StringRef LTOName("full");
493
494 const Arg *A = Args.getLastArg(options::OPT_flto_EQ);
Teresa Johnson6ef80dc2015-11-02 18:03:12 +0000495 if (A)
496 LTOName = A->getValue();
Teresa Johnson945bc502015-10-15 20:35:53 +0000497
498 LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
499 .Case("full", LTOK_Full)
500 .Case("thin", LTOK_Thin)
501 .Default(LTOK_Unknown);
502
503 if (LTOMode == LTOK_Unknown) {
504 assert(A);
505 Diag(diag::err_drv_unsupported_option_argument) << A->getOption().getName()
506 << A->getValue();
507 }
508}
509
Samuel Antao39f9da22016-10-27 16:38:05 +0000510/// Compute the desired OpenMP runtime from the flags provided.
511Driver::OpenMPRuntimeKind Driver::getOpenMPRuntime(const ArgList &Args) const {
512 StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
513
514 const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
515 if (A)
516 RuntimeName = A->getValue();
517
518 auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
519 .Case("libomp", OMPRT_OMP)
520 .Case("libgomp", OMPRT_GOMP)
521 .Case("libiomp5", OMPRT_IOMP5)
522 .Default(OMPRT_Unknown);
523
524 if (RT == OMPRT_Unknown) {
525 if (A)
526 Diag(diag::err_drv_unsupported_option_argument)
527 << A->getOption().getName() << A->getValue();
528 else
529 // FIXME: We could use a nicer diagnostic here.
530 Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
531 }
532
533 return RT;
534}
535
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000536void Driver::CreateOffloadingDeviceToolChains(Compilation &C,
537 InputList &Inputs) {
538
539 //
540 // CUDA
541 //
542 // We need to generate a CUDA toolchain if any of the inputs has a CUDA type.
543 if (llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
544 return types::isCuda(I.first);
545 })) {
Justin Lebar66c4fd72016-11-18 00:41:22 +0000546 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
547 const llvm::Triple &HostTriple = HostTC->getTriple();
548 llvm::Triple CudaTriple(HostTriple.isArch64Bit() ? "nvptx64-nvidia-cuda"
549 : "nvptx-nvidia-cuda");
550 // Use the CUDA and host triples as the key into the ToolChains map, because
551 // the device toolchain we create depends on both.
David Blaikie6ad71012017-01-13 18:53:43 +0000552 auto &CudaTC = ToolChains[CudaTriple.str() + "/" + HostTriple.str()];
Justin Lebar66c4fd72016-11-18 00:41:22 +0000553 if (!CudaTC) {
David Blaikie6ad71012017-01-13 18:53:43 +0000554 CudaTC = llvm::make_unique<toolchains::CudaToolChain>(
Gheorghe-Teodor Bercea2c926932017-08-08 14:33:05 +0000555 *this, CudaTriple, *HostTC, C.getInputArgs(), Action::OFK_Cuda);
Justin Lebar66c4fd72016-11-18 00:41:22 +0000556 }
David Blaikie6ad71012017-01-13 18:53:43 +0000557 C.addOffloadDeviceToolChain(CudaTC.get(), Action::OFK_Cuda);
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000558 }
559
560 //
Samuel Antao39f9da22016-10-27 16:38:05 +0000561 // OpenMP
562 //
563 // We need to generate an OpenMP toolchain if the user specified targets with
564 // the -fopenmp-targets option.
565 if (Arg *OpenMPTargets =
566 C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
567 if (OpenMPTargets->getNumValues()) {
568 // We expect that -fopenmp-targets is always used in conjunction with the
569 // option -fopenmp specifying a valid runtime with offloading support,
570 // i.e. libomp or libiomp.
571 bool HasValidOpenMPRuntime = C.getInputArgs().hasFlag(
572 options::OPT_fopenmp, options::OPT_fopenmp_EQ,
573 options::OPT_fno_openmp, false);
574 if (HasValidOpenMPRuntime) {
575 OpenMPRuntimeKind OpenMPKind = getOpenMPRuntime(C.getInputArgs());
576 HasValidOpenMPRuntime =
577 OpenMPKind == OMPRT_OMP || OpenMPKind == OMPRT_IOMP5;
578 }
579
580 if (HasValidOpenMPRuntime) {
581 llvm::StringMap<const char *> FoundNormalizedTriples;
582 for (const char *Val : OpenMPTargets->getValues()) {
583 llvm::Triple TT(Val);
584 std::string NormalizedName = TT.normalize();
585
586 // Make sure we don't have a duplicate triple.
587 auto Duplicate = FoundNormalizedTriples.find(NormalizedName);
588 if (Duplicate != FoundNormalizedTriples.end()) {
589 Diag(clang::diag::warn_drv_omp_offload_target_duplicate)
590 << Val << Duplicate->second;
591 continue;
592 }
593
594 // Store the current triple so that we can check for duplicates in the
595 // following iterations.
596 FoundNormalizedTriples[NormalizedName] = Val;
597
598 // If the specified target is invalid, emit a diagnostic.
599 if (TT.getArch() == llvm::Triple::UnknownArch)
600 Diag(clang::diag::err_drv_invalid_omp_target) << Val;
601 else {
Gheorghe-Teodor Bercea6a5df722017-07-06 16:08:15 +0000602 const ToolChain *TC;
603 // CUDA toolchains have to be selected differently. They pair host
604 // and device in their implementation.
605 if (TT.isNVPTX()) {
606 const ToolChain *HostTC =
607 C.getSingleOffloadToolChain<Action::OFK_Host>();
608 assert(HostTC && "Host toolchain should be always defined.");
609 auto &CudaTC =
Gheorghe-Teodor Bercea52898432017-08-09 01:02:19 +0000610 ToolChains[TT.str() + "/" + HostTC->getTriple().normalize()];
Gheorghe-Teodor Bercea6a5df722017-07-06 16:08:15 +0000611 if (!CudaTC)
612 CudaTC = llvm::make_unique<toolchains::CudaToolChain>(
Gheorghe-Teodor Bercea2c926932017-08-08 14:33:05 +0000613 *this, TT, *HostTC, C.getInputArgs(), Action::OFK_OpenMP);
Gheorghe-Teodor Bercea6a5df722017-07-06 16:08:15 +0000614 TC = CudaTC.get();
615 } else
616 TC = &getToolChain(C.getInputArgs(), TT);
617 C.addOffloadDeviceToolChain(TC, Action::OFK_OpenMP);
Samuel Antao39f9da22016-10-27 16:38:05 +0000618 }
619 }
620 } else
621 Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
622 } else
623 Diag(clang::diag::warn_drv_empty_joined_argument)
624 << OpenMPTargets->getAsString(C.getInputArgs());
625 }
626
627 //
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000628 // TODO: Add support for other offloading programming models here.
629 //
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000630}
631
Serge Pavlov208ac652018-01-01 13:27:01 +0000632/// Looks the given directories for the specified file.
633///
634/// \param[out] FilePath File path, if the file was found.
635/// \param[in] Dirs Directories used for the search.
636/// \param[in] FileName Name of the file to search for.
637/// \return True if file was found.
638///
639/// Looks for file specified by FileName sequentially in directories specified
640/// by Dirs.
641///
642static bool searchForFile(SmallVectorImpl<char> &FilePath,
643 ArrayRef<std::string> Dirs,
644 StringRef FileName) {
645 SmallString<128> WPath;
646 for (const StringRef &Dir : Dirs) {
647 if (Dir.empty())
648 continue;
649 WPath.clear();
650 llvm::sys::path::append(WPath, Dir, FileName);
651 llvm::sys::path::native(WPath);
652 if (llvm::sys::fs::is_regular_file(WPath)) {
653 FilePath = std::move(WPath);
654 return true;
655 }
656 }
657 return false;
658}
659
660bool Driver::readConfigFile(StringRef FileName) {
661 // Try reading the given file.
662 SmallVector<const char *, 32> NewCfgArgs;
663 if (!llvm::cl::readConfigFile(FileName, Saver, NewCfgArgs)) {
664 Diag(diag::err_drv_cannot_read_config_file) << FileName;
665 return true;
666 }
667
668 // Read options from config file.
669 llvm::SmallString<128> CfgFileName(FileName);
670 llvm::sys::path::native(CfgFileName);
671 ConfigFile = CfgFileName.str();
672 bool ContainErrors;
673 CfgOptions = llvm::make_unique<InputArgList>(
674 ParseArgStrings(NewCfgArgs, ContainErrors));
675 if (ContainErrors) {
676 CfgOptions.reset();
677 return true;
678 }
679
680 if (CfgOptions->hasArg(options::OPT_config)) {
681 CfgOptions.reset();
682 Diag(diag::err_drv_nested_config_file);
683 return true;
684 }
685
686 // Claim all arguments that come from a configuration file so that the driver
687 // does not warn on any that is unused.
688 for (Arg *A : *CfgOptions)
689 A->claim();
690 return false;
691}
692
693bool Driver::loadConfigFile() {
694 std::string CfgFileName;
695 bool FileSpecifiedExplicitly = false;
696
697 // Process options that change search path for config files.
698 if (CLOptions) {
699 if (CLOptions->hasArg(options::OPT_config_system_dir_EQ)) {
700 SmallString<128> CfgDir;
701 CfgDir.append(
702 CLOptions->getLastArgValue(options::OPT_config_system_dir_EQ));
703 if (!CfgDir.empty()) {
Sam McCall296d8322018-01-02 09:35:10 +0000704 if (llvm::sys::fs::make_absolute(CfgDir).value() != 0)
Serge Pavlov208ac652018-01-01 13:27:01 +0000705 SystemConfigDir.clear();
706 else
707 SystemConfigDir = std::string(CfgDir.begin(), CfgDir.end());
708 }
709 }
710 if (CLOptions->hasArg(options::OPT_config_user_dir_EQ)) {
711 SmallString<128> CfgDir;
712 CfgDir.append(
713 CLOptions->getLastArgValue(options::OPT_config_user_dir_EQ));
714 if (!CfgDir.empty()) {
Sam McCall296d8322018-01-02 09:35:10 +0000715 if (llvm::sys::fs::make_absolute(CfgDir).value() != 0)
Serge Pavlov208ac652018-01-01 13:27:01 +0000716 UserConfigDir.clear();
717 else
718 UserConfigDir = std::string(CfgDir.begin(), CfgDir.end());
719 }
720 }
721 }
722
723 // First try to find config file specified in command line.
724 if (CLOptions) {
725 std::vector<std::string> ConfigFiles =
726 CLOptions->getAllArgValues(options::OPT_config);
727 if (ConfigFiles.size() > 1) {
728 Diag(diag::err_drv_duplicate_config);
729 return true;
730 }
731
732 if (!ConfigFiles.empty()) {
733 CfgFileName = ConfigFiles.front();
734 assert(!CfgFileName.empty());
735
736 // If argument contains directory separator, treat it as a path to
737 // configuration file.
738 if (llvm::sys::path::has_parent_path(CfgFileName)) {
739 SmallString<128> CfgFilePath;
740 if (llvm::sys::path::is_relative(CfgFileName))
741 llvm::sys::fs::current_path(CfgFilePath);
742 llvm::sys::path::append(CfgFilePath, CfgFileName);
743 if (!llvm::sys::fs::is_regular_file(CfgFilePath)) {
744 Diag(diag::err_drv_config_file_not_exist) << CfgFilePath;
745 return true;
746 }
747 return readConfigFile(CfgFilePath);
748 }
749
750 FileSpecifiedExplicitly = true;
751 }
752 }
753
754 // If config file is not specified explicitly, try to deduce configuration
755 // from executable name. For instance, an executable 'armv7l-clang' will
756 // search for config file 'armv7l-clang.cfg'.
757 if (CfgFileName.empty() && !ClangNameParts.TargetPrefix.empty())
758 CfgFileName = ClangNameParts.TargetPrefix + '-' + ClangNameParts.ModeSuffix;
759
760 if (CfgFileName.empty())
761 return false;
762
763 // Determine architecture part of the file name, if it is present.
764 StringRef CfgFileArch = CfgFileName;
765 size_t ArchPrefixLen = CfgFileArch.find('-');
766 if (ArchPrefixLen == StringRef::npos)
767 ArchPrefixLen = CfgFileArch.size();
768 llvm::Triple CfgTriple;
769 CfgFileArch = CfgFileArch.take_front(ArchPrefixLen);
770 CfgTriple = llvm::Triple(llvm::Triple::normalize(CfgFileArch));
771 if (CfgTriple.getArch() == llvm::Triple::ArchType::UnknownArch)
772 ArchPrefixLen = 0;
773
774 if (!StringRef(CfgFileName).endswith(".cfg"))
775 CfgFileName += ".cfg";
776
777 // If config file starts with architecture name and command line options
778 // redefine architecture (with options like -m32 -LE etc), try finding new
779 // config file with that architecture.
780 SmallString<128> FixedConfigFile;
781 size_t FixedArchPrefixLen = 0;
782 if (ArchPrefixLen) {
783 // Get architecture name from config file name like 'i386.cfg' or
784 // 'armv7l-clang.cfg'.
785 // Check if command line options changes effective triple.
786 llvm::Triple EffectiveTriple = computeTargetTriple(*this,
787 CfgTriple.getTriple(), *CLOptions);
788 if (CfgTriple.getArch() != EffectiveTriple.getArch()) {
789 FixedConfigFile = EffectiveTriple.getArchName();
790 FixedArchPrefixLen = FixedConfigFile.size();
791 // Append the rest of original file name so that file name transforms
792 // like: i386-clang.cfg -> x86_64-clang.cfg.
793 if (ArchPrefixLen < CfgFileName.size())
794 FixedConfigFile += CfgFileName.substr(ArchPrefixLen);
795 }
796 }
797
798 // Prepare list of directories where config file is searched for.
799 SmallVector<std::string, 3> CfgFileSearchDirs;
800 CfgFileSearchDirs.push_back(UserConfigDir);
801 CfgFileSearchDirs.push_back(SystemConfigDir);
802 CfgFileSearchDirs.push_back(Dir);
803
804 // Try to find config file. First try file with corrected architecture.
805 llvm::SmallString<128> CfgFilePath;
806 if (!FixedConfigFile.empty()) {
807 if (searchForFile(CfgFilePath, CfgFileSearchDirs, FixedConfigFile))
808 return readConfigFile(CfgFilePath);
809 // If 'x86_64-clang.cfg' was not found, try 'x86_64.cfg'.
810 FixedConfigFile.resize(FixedArchPrefixLen);
811 FixedConfigFile.append(".cfg");
812 if (searchForFile(CfgFilePath, CfgFileSearchDirs, FixedConfigFile))
813 return readConfigFile(CfgFilePath);
814 }
815
816 // Then try original file name.
817 if (searchForFile(CfgFilePath, CfgFileSearchDirs, CfgFileName))
818 return readConfigFile(CfgFilePath);
819
820 // Finally try removing driver mode part: 'x86_64-clang.cfg' -> 'x86_64.cfg'.
821 if (!ClangNameParts.ModeSuffix.empty() &&
822 !ClangNameParts.TargetPrefix.empty()) {
823 CfgFileName.assign(ClangNameParts.TargetPrefix);
824 CfgFileName.append(".cfg");
825 if (searchForFile(CfgFilePath, CfgFileSearchDirs, CfgFileName))
826 return readConfigFile(CfgFilePath);
827 }
828
829 // Report error but only if config file was specified explicitly, by option
830 // --config. If it was deduced from executable name, it is not an error.
831 if (FileSpecifiedExplicitly) {
832 Diag(diag::err_drv_config_file_not_found) << CfgFileName;
833 for (const std::string &SearchDir : CfgFileSearchDirs)
834 if (!SearchDir.empty())
835 Diag(diag::note_drv_config_file_searched_in) << SearchDir;
836 return true;
837 }
838
839 return false;
840}
841
Chris Lattner54b16772011-07-23 17:14:25 +0000842Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
Daniel Dunbar2608c542009-03-18 01:38:48 +0000843 llvm::PrettyStackTraceString CrashInfo("Compilation construction");
844
Eric Christopherf901e852011-08-17 22:59:59 +0000845 // FIXME: Handle environment options which affect driver behavior, somewhere
Bill Wendlingadbeb9f2012-03-12 21:24:57 +0000846 // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
Chad Rosier82301162011-09-14 00:47:55 +0000847
David Majnemer85c25b42016-07-24 17:44:03 +0000848 if (Optional<std::string> CompilerPathValue =
849 llvm::sys::Process::GetEnv("COMPILER_PATH")) {
850 StringRef CompilerPath = *CompilerPathValue;
Chad Rosier82301162011-09-14 00:47:55 +0000851 while (!CompilerPath.empty()) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000852 std::pair<StringRef, StringRef> Split =
853 CompilerPath.split(llvm::sys::EnvPathSeparator);
Chad Rosier82301162011-09-14 00:47:55 +0000854 PrefixDirs.push_back(Split.first);
855 CompilerPath = Split.second;
856 }
857 }
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +0000858
Hans Wennborg70850d82013-07-18 20:29:38 +0000859 // We look for the driver mode option early, because the mode can affect
860 // how other options are parsed.
Zachary Turneraff19c32016-08-12 17:47:52 +0000861 ParseDriverMode(ClangExecutable, ArgList.slice(1));
Hans Wennborg70850d82013-07-18 20:29:38 +0000862
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +0000863 // FIXME: What are we going to do with -V and -b?
864
Serge Pavlov208ac652018-01-01 13:27:01 +0000865 // Arguments specified in command line.
866 bool ContainsError;
867 CLOptions = llvm::make_unique<InputArgList>(
868 ParseArgStrings(ArgList.slice(1), ContainsError));
869
870 // Try parsing configuration file.
871 if (!ContainsError)
872 ContainsError = loadConfigFile();
873 bool HasConfigFile = !ContainsError && (CfgOptions.get() != nullptr);
874
875 // All arguments, from both config file and command line.
876 InputArgList Args = std::move(HasConfigFile ? std::move(*CfgOptions)
877 : std::move(*CLOptions));
878 if (HasConfigFile)
879 for (auto *Opt : *CLOptions) {
880 const Arg *BaseArg = &Opt->getBaseArg();
881 if (BaseArg == Opt)
882 BaseArg = nullptr;
883 Arg *Copy = new llvm::opt::Arg(Opt->getOption(), Opt->getSpelling(),
884 Args.size(), BaseArg);
885 Copy->getValues() = Opt->getValues();
886 if (Opt->isClaimed())
887 Copy->claim();
888 Args.append(Copy);
889 }
890
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +0000891 // FIXME: This stuff needs to go into the Compilation, not the driver.
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +0000892 bool CCCPrintPhases;
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000893
Filipe Cabecinhas136f35e2015-07-18 06:35:24 +0000894 // Silence driver warnings if requested
895 Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w));
896
Rafael Espindola59ae7992009-12-07 18:28:29 +0000897 // -no-canonical-prefixes is used very early in main.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000898 Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
Rafael Espindola59ae7992009-12-07 18:28:29 +0000899
Daniel Dunbar926f81f2010-08-02 02:38:03 +0000900 // Ignore -pipe.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000901 Args.ClaimAllArgs(options::OPT_pipe);
Daniel Dunbar926f81f2010-08-02 02:38:03 +0000902
Daniel Dunbaracd69572009-12-04 21:55:23 +0000903 // Extract -ccc args.
Daniel Dunbaree66cf22009-03-10 20:52:46 +0000904 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +0000905 // FIXME: We need to figure out where this behavior should live. Most of it
906 // should be outside in the client; the parts that aren't should have proper
907 // options, either by introducing new ones or by overloading gcc ones like -V
908 // or -b.
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +0000909 CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
David Blaikie69a1d8c2015-06-22 22:07:27 +0000910 CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
911 if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
Richard Smithbd55daf2012-11-01 04:30:05 +0000912 CCCGenericGCCName = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000913 CCCUsePCH =
914 Args.hasFlag(options::OPT_ccc_pch_is_pch, options::OPT_ccc_pch_is_pth);
Bruno Cardoso Lopes52dfe712017-04-12 21:46:20 +0000915 GenReproducer = Args.hasFlag(options::OPT_gen_reproducer,
916 options::OPT_fno_crash_diagnostics,
917 !!::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH"));
Joerg Sonnenberger17d75512012-02-22 19:15:16 +0000918 // FIXME: DefaultTargetTriple is used by the target-prefixed calls to as/ld
919 // and getToolChain is const.
Hans Wennborg2e274592013-08-13 23:38:57 +0000920 if (IsCLMode()) {
Hans Wennborg73609a02014-03-28 01:19:04 +0000921 // clang-cl targets MSVC-style Win32.
Hans Wennborg2e274592013-08-13 23:38:57 +0000922 llvm::Triple T(DefaultTargetTriple);
Hans Wennborg9d9ce7a2014-03-28 20:49:28 +0000923 T.setOS(llvm::Triple::Win32);
Hans Wennborg0f0e8d62015-09-18 17:11:50 +0000924 T.setVendor(llvm::Triple::PC);
Hans Wennborg9d9ce7a2014-03-28 20:49:28 +0000925 T.setEnvironment(llvm::Triple::MSVC);
Oleg Ranevskyy80523182017-08-31 20:31:30 +0000926 T.setObjectFormat(llvm::Triple::COFF);
Hans Wennborg2e274592013-08-13 23:38:57 +0000927 DefaultTargetTriple = T.str();
928 }
David Blaikie69a1d8c2015-06-22 22:07:27 +0000929 if (const Arg *A = Args.getLastArg(options::OPT_target))
Richard Smithbd55daf2012-11-01 04:30:05 +0000930 DefaultTargetTriple = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000931 if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
Richard Smithbd55daf2012-11-01 04:30:05 +0000932 Dir = InstalledDir = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000933 for (const Arg *A : Args.filtered(options::OPT_B)) {
Benjamin Kramer1a648d12011-02-08 20:31:42 +0000934 A->claim();
Richard Smithbd55daf2012-11-01 04:30:05 +0000935 PrefixDirs.push_back(A->getValue(0));
Benjamin Kramer1a648d12011-02-08 20:31:42 +0000936 }
David Blaikie69a1d8c2015-06-22 22:07:27 +0000937 if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
Richard Smithbd55daf2012-11-01 04:30:05 +0000938 SysRoot = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000939 if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
Peter Collingbourne9d9e1fc2013-05-27 21:40:20 +0000940 DyldPrefix = A->getValue();
Daniel Dunbaree66cf22009-03-10 20:52:46 +0000941
David Blaikie69a1d8c2015-06-22 22:07:27 +0000942 if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
Bob Wilsona20a1da2013-03-23 05:17:59 +0000943 ResourceDir = A->getValue();
Jim Grosbach061dabf2013-03-12 20:17:58 +0000944
David Blaikie69a1d8c2015-06-22 22:07:27 +0000945 if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
Reid Kleckner68eb60b2015-02-02 22:41:48 +0000946 SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
947 .Case("cwd", SaveTempsCwd)
948 .Case("obj", SaveTempsObj)
949 .Default(SaveTempsCwd);
950 }
951
Steven Wu1257cd82016-05-18 17:04:52 +0000952 setLTOMode(Args);
953
Steven Wu844ab6a2016-11-16 06:06:44 +0000954 // Process -fembed-bitcode= flags.
955 if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
956 StringRef Name = A->getValue();
957 unsigned Model = llvm::StringSwitch<unsigned>(Name)
958 .Case("off", EmbedNone)
959 .Case("all", EmbedBitcode)
960 .Case("bitcode", EmbedBitcode)
961 .Case("marker", EmbedMarker)
962 .Default(~0U);
963 if (Model == ~0U) {
964 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
965 << Name;
966 } else
967 BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
Steven Wu574b0f22016-03-01 01:07:58 +0000968 }
969
David Blaikie69a1d8c2015-06-22 22:07:27 +0000970 std::unique_ptr<llvm::opt::InputArgList> UArgs =
971 llvm::make_unique<InputArgList>(std::move(Args));
972
Daniel Dunbar775d4062010-06-11 22:00:26 +0000973 // Perform the default argument translations.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000974 DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
Daniel Dunbar775d4062010-06-11 22:00:26 +0000975
Chandler Carruthcb916192012-01-25 08:49:21 +0000976 // Owned by the host.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000977 const ToolChain &TC = getToolChain(
978 *UArgs, computeTargetTriple(*this, DefaultTargetTriple, *UArgs));
Chandler Carruthcb916192012-01-25 08:49:21 +0000979
Daniel Dunbar3ce436d2009-03-16 06:42:30 +0000980 // The compilation takes ownership of Args.
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000981 Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs,
982 ContainsError);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +0000983
Daniel Dunbarf0eddb82009-03-18 02:55:38 +0000984 if (!HandleImmediateArgs(*C))
985 return C;
986
Chad Rosierecdede82011-08-12 22:08:57 +0000987 // Construct the list of inputs.
988 InputList Inputs;
Hans Wennborged1d0722013-08-13 21:32:29 +0000989 BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
Chad Rosierecdede82011-08-12 22:08:57 +0000990
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000991 // Populate the tool chains for the offloading devices, if any.
992 CreateOffloadingDeviceToolChains(*C, Inputs);
Justin Lebar0e450a52016-03-30 23:30:25 +0000993
Chandler Carruth7f1417f2012-01-24 10:43:44 +0000994 // Construct the list of abstract actions to perform for this compilation. On
Tim Northover157d9112014-01-16 08:48:16 +0000995 // MachO targets this uses the driver-driver and universal actions.
996 if (TC.getTriple().isOSBinFormatMachO())
Artem Belevich5e2a3ec2015-11-17 22:28:40 +0000997 BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +0000998 else
Justin Lebar0f3474c2016-02-11 02:00:50 +0000999 BuildActions(*C, C->getArgs(), Inputs, C->getActions());
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001000
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001001 if (CCCPrintPhases) {
Daniel Dunbareb843be2009-03-18 03:13:20 +00001002 PrintActions(*C);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001003 return C;
1004 }
1005
1006 BuildJobs(*C);
Daniel Dunbaradc91e62009-03-15 01:38:15 +00001007
1008 return C;
Daniel Dunbaree66cf22009-03-10 20:52:46 +00001009}
1010
Justin Bognered9cbe02015-07-09 06:58:31 +00001011static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
1012 llvm::opt::ArgStringList ASL;
1013 for (const auto *A : Args)
1014 A->render(Args, ASL);
1015
1016 for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
1017 if (I != ASL.begin())
1018 OS << ' ';
1019 Command::printArg(OS, *I, true);
1020 }
1021 OS << '\n';
1022}
1023
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +00001024bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename,
1025 SmallString<128> &CrashDiagDir) {
1026 using namespace llvm::sys;
1027 assert(llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin() &&
1028 "Only knows about .crash files on Darwin");
1029
1030 // The .crash file can be found on at ~/Library/Logs/DiagnosticReports/
1031 // (or /Library/Logs/DiagnosticReports for root) and has the filename pattern
1032 // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash.
1033 path::home_directory(CrashDiagDir);
1034 if (CrashDiagDir.startswith("/var/root"))
1035 CrashDiagDir = "/";
1036 path::append(CrashDiagDir, "Library/Logs/DiagnosticReports");
1037 int PID =
1038#if LLVM_ON_UNIX
1039 getpid();
1040#else
1041 0;
1042#endif
1043 std::error_code EC;
1044 fs::file_status FileStatus;
1045 TimePoint<> LastAccessTime;
1046 SmallString<128> CrashFilePath;
1047 // Lookup the .crash files and get the one generated by a subprocess spawned
1048 // by this driver invocation.
1049 for (fs::directory_iterator File(CrashDiagDir, EC), FileEnd;
1050 File != FileEnd && !EC; File.increment(EC)) {
1051 StringRef FileName = path::filename(File->path());
1052 if (!FileName.startswith(Name))
1053 continue;
1054 if (fs::status(File->path(), FileStatus))
1055 continue;
1056 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CrashFile =
1057 llvm::MemoryBuffer::getFile(File->path());
1058 if (!CrashFile)
1059 continue;
1060 // The first line should start with "Process:", otherwise this isn't a real
1061 // .crash file.
1062 StringRef Data = CrashFile.get()->getBuffer();
1063 if (!Data.startswith("Process:"))
1064 continue;
1065 // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]"
1066 size_t ParentProcPos = Data.find("Parent Process:");
1067 if (ParentProcPos == StringRef::npos)
1068 continue;
1069 size_t LineEnd = Data.find_first_of("\n", ParentProcPos);
1070 if (LineEnd == StringRef::npos)
1071 continue;
1072 StringRef ParentProcess = Data.slice(ParentProcPos+15, LineEnd).trim();
1073 int OpenBracket = -1, CloseBracket = -1;
1074 for (size_t i = 0, e = ParentProcess.size(); i < e; ++i) {
1075 if (ParentProcess[i] == '[')
1076 OpenBracket = i;
1077 if (ParentProcess[i] == ']')
1078 CloseBracket = i;
1079 }
1080 // Extract the parent process PID from the .crash file and check whether
1081 // it matches this driver invocation pid.
1082 int CrashPID;
1083 if (OpenBracket < 0 || CloseBracket < 0 ||
1084 ParentProcess.slice(OpenBracket + 1, CloseBracket)
1085 .getAsInteger(10, CrashPID) || CrashPID != PID) {
1086 continue;
1087 }
1088
1089 // Found a .crash file matching the driver pid. To avoid getting an older
1090 // and misleading crash file, continue looking for the most recent.
1091 // FIXME: the driver can dispatch multiple cc1 invocations, leading to
1092 // multiple crashes poiting to the same parent process. Since the driver
1093 // does not collect pid information for the dispatched invocation there's
1094 // currently no way to distinguish among them.
1095 const auto FileAccessTime = FileStatus.getLastModificationTime();
1096 if (FileAccessTime > LastAccessTime) {
1097 CrashFilePath.assign(File->path());
1098 LastAccessTime = FileAccessTime;
1099 }
1100 }
1101
1102 // If found, copy it over to the location of other reproducer files.
1103 if (!CrashFilePath.empty()) {
1104 EC = fs::copy_file(CrashFilePath, ReproCrashFilename);
1105 if (EC)
1106 return false;
1107 return true;
1108 }
1109
1110 return false;
1111}
1112
Eric Christopherf901e852011-08-17 22:59:59 +00001113// When clang crashes, produce diagnostic information including the fully
1114// preprocessed source file(s). Request that the developer attach the
Chad Rosierbe10f982011-08-02 17:58:04 +00001115// diagnostic information to a bug report.
1116void Driver::generateCompilationDiagnostics(Compilation &C,
Justin Bognere1a33d12014-10-20 21:02:05 +00001117 const Command &FailingCommand) {
Chad Rosier877c0a22012-02-22 00:30:39 +00001118 if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
Chad Rosier62135492012-07-09 17:31:28 +00001119 return;
Chad Rosierbee5a1d2012-03-07 00:30:40 +00001120
Chad Rosierdbf46a12013-02-01 18:30:26 +00001121 // Don't try to generate diagnostics for link or dsymutil jobs.
Justin Bognere1a33d12014-10-20 21:02:05 +00001122 if (FailingCommand.getCreator().isLinkJob() ||
1123 FailingCommand.getCreator().isDsymutilJob())
Chad Rosier877c0a22012-02-22 00:30:39 +00001124 return;
1125
Chad Rosier8179f112012-06-19 17:51:34 +00001126 // Print the version of the compiler.
1127 PrintVersion(C, llvm::errs());
1128
Chad Rosierbe10f982011-08-02 17:58:04 +00001129 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001130 << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the "
1131 "crash backtrace, preprocessed source, and associated run script.";
Chad Rosierbe10f982011-08-02 17:58:04 +00001132
1133 // Suppress driver output and emit preprocessor output to temp file.
Hans Wennborg70850d82013-07-18 20:29:38 +00001134 Mode = CPPMode;
Chad Rosierbe10f982011-08-02 17:58:04 +00001135 CCGenDiagnostics = true;
1136
Chad Rosiercdb008d2011-11-02 21:29:05 +00001137 // Save the original job command(s).
Justin Bogner25645152014-10-21 17:24:44 +00001138 Command Cmd = FailingCommand;
Chad Rosiercdb008d2011-11-02 21:29:05 +00001139
Richard Smith5bb4cdf2012-12-20 02:22:15 +00001140 // Keep track of whether we produce any errors while trying to produce
1141 // preprocessed sources.
1142 DiagnosticErrorTrap Trap(Diags);
1143
1144 // Suppress tool output.
Chad Rosierbe10f982011-08-02 17:58:04 +00001145 C.initCompilationForDiagnostics();
Chad Rosierecdede82011-08-12 22:08:57 +00001146
1147 // Construct the list of inputs.
1148 InputList Inputs;
1149 BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
Chad Rosierbe10f982011-08-02 17:58:04 +00001150
Chad Rosier4f81fc22011-08-12 23:30:05 +00001151 for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
Chad Rosierd57133d2011-08-18 00:22:25 +00001152 bool IgnoreInput = false;
1153
1154 // Ignore input from stdin or any inputs that cannot be preprocessed.
Paul Robinsonf44157d2014-04-28 22:24:44 +00001155 // Check type first as not all linker inputs have a value.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001156 if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
Paul Robinsonf44157d2014-04-28 22:24:44 +00001157 IgnoreInput = true;
1158 } else if (!strcmp(it->second->getValue(), "-")) {
Chad Rosierd57133d2011-08-18 00:22:25 +00001159 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001160 << "Error generating preprocessed source(s) - "
1161 "ignoring input from stdin.";
Chad Rosierd57133d2011-08-18 00:22:25 +00001162 IgnoreInput = true;
Chad Rosierd57133d2011-08-18 00:22:25 +00001163 }
1164
1165 if (IgnoreInput) {
Chad Rosier4f81fc22011-08-12 23:30:05 +00001166 it = Inputs.erase(it);
1167 ie = Inputs.end();
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001168 } else {
Chad Rosier4f81fc22011-08-12 23:30:05 +00001169 ++it;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001170 }
Chad Rosier4f81fc22011-08-12 23:30:05 +00001171 }
Chad Rosierd57133d2011-08-18 00:22:25 +00001172
Chad Rosierc5103c32013-01-29 23:57:10 +00001173 if (Inputs.empty()) {
1174 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001175 << "Error generating preprocessed source(s) - "
1176 "no preprocessable inputs.";
Chad Rosierc5103c32013-01-29 23:57:10 +00001177 return;
1178 }
1179
Chad Rosiere75ef402011-09-06 23:52:36 +00001180 // Don't attempt to generate preprocessed files if multiple -arch options are
Chad Rosier636d2832012-02-13 18:16:28 +00001181 // used, unless they're all duplicates.
1182 llvm::StringSet<> ArchNames;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00001183 for (const Arg *A : C.getArgs()) {
Chad Rosiere75ef402011-09-06 23:52:36 +00001184 if (A->getOption().matches(options::OPT_arch)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001185 StringRef ArchName = A->getValue();
Chad Rosier636d2832012-02-13 18:16:28 +00001186 ArchNames.insert(ArchName);
Chad Rosiere75ef402011-09-06 23:52:36 +00001187 }
1188 }
Chad Rosier636d2832012-02-13 18:16:28 +00001189 if (ArchNames.size() > 1) {
1190 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001191 << "Error generating preprocessed source(s) - cannot generate "
1192 "preprocessed source with multiple -arch options.";
Chad Rosier636d2832012-02-13 18:16:28 +00001193 return;
1194 }
Chad Rosiere75ef402011-09-06 23:52:36 +00001195
Chandler Carruth7f1417f2012-01-24 10:43:44 +00001196 // Construct the list of abstract actions to perform for this compilation. On
1197 // Darwin OSes this uses the driver-driver and builds universal actions.
Chandler Carruthcb916192012-01-25 08:49:21 +00001198 const ToolChain &TC = C.getDefaultToolChain();
Tim Northover157d9112014-01-16 08:48:16 +00001199 if (TC.getTriple().isOSBinFormatMachO())
Artem Belevich5e2a3ec2015-11-17 22:28:40 +00001200 BuildUniversalActions(C, TC, Inputs);
Chad Rosierbe10f982011-08-02 17:58:04 +00001201 else
Justin Lebar0f3474c2016-02-11 02:00:50 +00001202 BuildActions(C, C.getArgs(), Inputs, C.getActions());
Chad Rosierbe10f982011-08-02 17:58:04 +00001203
1204 BuildJobs(C);
1205
1206 // If there were errors building the compilation, quit now.
Richard Smith5bb4cdf2012-12-20 02:22:15 +00001207 if (Trap.hasErrorOccurred()) {
Chad Rosierbe10f982011-08-02 17:58:04 +00001208 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001209 << "Error generating preprocessed source(s).";
Chad Rosierbe10f982011-08-02 17:58:04 +00001210 return;
1211 }
1212
1213 // Generate preprocessed output.
Chad Rosierdd60e092013-01-29 20:15:05 +00001214 SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
Justin Bogner0cd92482015-07-02 22:52:08 +00001215 C.ExecuteJobs(C.getJobs(), FailingCommands);
Chad Rosierbe10f982011-08-02 17:58:04 +00001216
Justin Bognerbc89b182014-10-20 21:20:27 +00001217 // If any of the preprocessing commands failed, clean up and exit.
1218 if (!FailingCommands.empty()) {
Reid Kleckner68eb60b2015-02-02 22:41:48 +00001219 if (!isSaveTempsEnabled())
Chad Rosierbe10f982011-08-02 17:58:04 +00001220 C.CleanupFileList(C.getTempFiles(), true);
1221
1222 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001223 << "Error generating preprocessed source(s).";
Justin Bognerbc89b182014-10-20 21:20:27 +00001224 return;
Chad Rosierbe10f982011-08-02 17:58:04 +00001225 }
Justin Bognerbc89b182014-10-20 21:20:27 +00001226
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001227 const ArgStringList &TempFiles = C.getTempFiles();
1228 if (TempFiles.empty()) {
1229 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001230 << "Error generating preprocessed source(s).";
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001231 return;
1232 }
1233
Justin Bognerbc89b182014-10-20 21:20:27 +00001234 Diag(clang::diag::note_drv_command_failed_diag_msg)
1235 << "\n********************\n\n"
1236 "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
1237 "Preprocessed source(s) and associated run script(s) are located at:";
Justin Bognerbc89b182014-10-20 21:20:27 +00001238
Justin Bogner659ecc32014-10-20 22:47:23 +00001239 SmallString<128> VFS;
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +00001240 SmallString<128> ReproCrashFilename;
Justin Bogner659ecc32014-10-20 22:47:23 +00001241 for (const char *TempFile : TempFiles) {
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001242 Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +00001243 if (ReproCrashFilename.empty()) {
1244 ReproCrashFilename = TempFile;
1245 llvm::sys::path::replace_extension(ReproCrashFilename, ".crash");
1246 }
Justin Bogner659ecc32014-10-20 22:47:23 +00001247 if (StringRef(TempFile).endswith(".cache")) {
1248 // In some cases (modules) we'll dump extra data to help with reproducing
1249 // the crash into a directory next to the output.
1250 VFS = llvm::sys::path::filename(TempFile);
1251 llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
1252 }
1253 }
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001254
1255 // Assume associated files are based off of the first temporary file.
Justin Bogner25645152014-10-21 17:24:44 +00001256 CrashReportInfo CrashInfo(TempFiles[0], VFS);
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001257
Justin Bogner25645152014-10-21 17:24:44 +00001258 std::string Script = CrashInfo.Filename.rsplit('.').first.str() + ".sh";
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001259 std::error_code EC;
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001260 llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::F_Excl);
1261 if (EC) {
1262 Diag(clang::diag::note_drv_command_failed_diag_msg)
1263 << "Error generating run script: " + Script + " " + EC.message();
1264 } else {
Justin Bogner42220ed2015-03-12 00:14:35 +00001265 ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
Justin Bognered9cbe02015-07-09 06:58:31 +00001266 << "# Driver args: ";
1267 printArgList(ScriptOS, C.getInputArgs());
1268 ScriptOS << "# Original command: ";
Justin Bogner42220ed2015-03-12 00:14:35 +00001269 Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
Justin Bogner33bdbc62014-10-21 18:03:08 +00001270 Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001271 Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
Justin Bognerbc89b182014-10-20 21:20:27 +00001272 }
Saleem Abdulrasool3661a822015-01-12 02:33:09 +00001273
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +00001274 // On darwin, provide information about the .crash diagnostic report.
1275 if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) {
1276 SmallString<128> CrashDiagDir;
1277 if (getCrashDiagnosticFile(ReproCrashFilename, CrashDiagDir)) {
1278 Diag(clang::diag::note_drv_command_failed_diag_msg)
1279 << ReproCrashFilename.str();
1280 } else { // Suggest a directory for the user to look for .crash files.
1281 llvm::sys::path::append(CrashDiagDir, Name);
1282 CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash";
1283 Diag(clang::diag::note_drv_command_failed_diag_msg)
1284 << "Crash backtrace is located in";
1285 Diag(clang::diag::note_drv_command_failed_diag_msg)
1286 << CrashDiagDir.str();
1287 Diag(clang::diag::note_drv_command_failed_diag_msg)
1288 << "(choose the .crash file that corresponds to your crash)";
1289 }
1290 }
1291
Saleem Abdulrasool3661a822015-01-12 02:33:09 +00001292 for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file,
1293 options::OPT_frewrite_map_file_EQ))
1294 Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
1295
Justin Bognerbc89b182014-10-20 21:20:27 +00001296 Diag(clang::diag::note_drv_command_failed_diag_msg)
1297 << "\n\n********************";
Chad Rosierbe10f982011-08-02 17:58:04 +00001298}
1299
Justin Bogner0cd92482015-07-02 22:52:08 +00001300void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
Oleg Ranevskyycd516372016-01-05 19:54:39 +00001301 // Since commandLineFitsWithinSystemLimits() may underestimate system's capacity
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001302 // if the tool does not support response files, there is a chance/ that things
1303 // will just work without a response file, so we silently just skip it.
Justin Bogner0cd92482015-07-02 22:52:08 +00001304 if (Cmd.getCreator().getResponseFilesSupport() == Tool::RF_None ||
Oleg Ranevskyycd516372016-01-05 19:54:39 +00001305 llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(), Cmd.getArguments()))
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001306 return;
1307
1308 std::string TmpName = GetTemporaryPath("response", "txt");
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00001309 Cmd.setResponseFile(C.addTempFile(C.getArgs().MakeArgString(TmpName)));
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001310}
1311
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001312int Driver::ExecuteCompilation(
1313 Compilation &C,
1314 SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001315 // Just print if -### was present.
1316 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
Hans Wennborgb212b342013-09-12 18:23:34 +00001317 C.getJobs().Print(llvm::errs(), "\n", true);
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001318 return 0;
1319 }
1320
1321 // If there were errors building the compilation, quit now.
Chad Rosierbe10f982011-08-02 17:58:04 +00001322 if (Diags.hasErrorOccurred())
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001323 return 1;
1324
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001325 // Set up response file names for each command, if necessary
Justin Bogner0cd92482015-07-02 22:52:08 +00001326 for (auto &Job : C.getJobs())
1327 setUpResponseFiles(C, Job);
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001328
Justin Bogner0cd92482015-07-02 22:52:08 +00001329 C.ExecuteJobs(C.getJobs(), FailingCommands);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001330
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001331 // Remove temp files.
1332 C.CleanupFileList(C.getTempFiles());
1333
Daniel Dunbar07494792010-05-22 00:37:20 +00001334 // If the command succeeded, we are done.
Chad Rosierdd60e092013-01-29 20:15:05 +00001335 if (FailingCommands.empty())
1336 return 0;
Daniel Dunbar07494792010-05-22 00:37:20 +00001337
Chad Rosierdd60e092013-01-29 20:15:05 +00001338 // Otherwise, remove result files and print extra information about abnormal
1339 // failures.
Douglas Katzman6bbffc42015-06-25 18:51:37 +00001340 for (const auto &CmdPair : FailingCommands) {
1341 int Res = CmdPair.first;
1342 const Command *FailingCommand = CmdPair.second;
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001343
Chad Rosierdd60e092013-01-29 20:15:05 +00001344 // Remove result files if we're not saving temps.
Reid Kleckner68eb60b2015-02-02 22:41:48 +00001345 if (!isSaveTempsEnabled()) {
Chad Rosierdd60e092013-01-29 20:15:05 +00001346 const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
1347 C.CleanupFileMap(C.getResultFiles(), JA, true);
1348
1349 // Failure result files are valid unless we crashed.
1350 if (Res < 0)
1351 C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
1352 }
1353
1354 // Print extra information about abnormal failures, if possible.
1355 //
1356 // This is ad-hoc, but we don't want to be excessively noisy. If the result
Justin Bogner5aaf2e72014-06-26 20:59:36 +00001357 // status was 1, assume the command failed normally. In particular, if it
Chad Rosierdd60e092013-01-29 20:15:05 +00001358 // was the compiler then assume it gave a reasonable error code. Failures
1359 // in other tools are less common, and they generally have worse
1360 // diagnostics, so always print the diagnostic there.
1361 const Tool &FailingTool = FailingCommand->getCreator();
1362
1363 if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
1364 // FIXME: See FIXME above regarding result code interpretation.
1365 if (Res < 0)
1366 Diag(clang::diag::err_drv_command_signalled)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001367 << FailingTool.getShortName();
Chad Rosierdd60e092013-01-29 20:15:05 +00001368 else
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001369 Diag(clang::diag::err_drv_command_failed) << FailingTool.getShortName()
1370 << Res;
Chad Rosierdd60e092013-01-29 20:15:05 +00001371 }
Peter Collingbourne119cfaa2011-11-21 00:01:05 +00001372 }
Chad Rosierdd60e092013-01-29 20:15:05 +00001373 return 0;
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001374}
1375
Daniel Dunbara7b5e212009-04-15 16:34:29 +00001376void Driver::PrintHelp(bool ShowHidden) const {
Hans Wennborg6ddc6902013-07-27 00:23:45 +00001377 unsigned IncludedFlagsBitmask;
1378 unsigned ExcludedFlagsBitmask;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001379 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001380 getIncludeExcludeOptionFlagMasks();
Hans Wennborg6ddc6902013-07-27 00:23:45 +00001381
1382 ExcludedFlagsBitmask |= options::NoDriverOption;
1383 if (!ShowHidden)
1384 ExcludedFlagsBitmask |= HelpHidden;
1385
1386 getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
George Rimar5dbfa4e2017-07-26 09:10:17 +00001387 IncludedFlagsBitmask, ExcludedFlagsBitmask,
1388 /*ShowAllAliases=*/false);
Daniel Dunbar7c925282009-03-31 21:38:17 +00001389}
1390
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001391void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001392 // FIXME: The following handlers should use a callback mechanism, we don't
1393 // know what the client would like to do.
Ted Kremenek4c0df3d2010-01-23 02:11:34 +00001394 OS << getClangFullVersion() << '\n';
Daniel Dunbarb10248802009-03-26 16:09:13 +00001395 const ToolChain &TC = C.getDefaultToolChain();
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001396 OS << "Target: " << TC.getTripleString() << '\n';
Daniel Dunbar10978e42009-06-16 23:32:58 +00001397
1398 // Print the threading model.
Jonathan Roelofsb140a102014-10-03 21:57:44 +00001399 if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
1400 // Don't print if the ToolChain would have barfed on it already
1401 if (TC.isThreadModelSupported(A->getValue()))
1402 OS << "Thread model: " << A->getValue();
1403 } else
1404 OS << "Thread model: " << TC.getThreadModel();
1405 OS << '\n';
Chandler Carruth9ade6a92015-08-05 17:07:33 +00001406
1407 // Print out the install directory.
1408 OS << "InstalledDir: " << InstalledDir << '\n';
Serge Pavlov208ac652018-01-01 13:27:01 +00001409
1410 // If configuration file was used, print its path.
1411 if (!ConfigFile.empty())
1412 OS << "Configuration file: " << ConfigFile << '\n';
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001413}
1414
Chris Lattner86ed5b02010-05-05 05:53:24 +00001415/// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
1416/// option.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001417static void PrintDiagnosticCategories(raw_ostream &OS) {
Argyrios Kyrtzidis0e37afa2011-05-25 05:05:01 +00001418 // Skip the empty category.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001419 for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
1420 ++i)
Argyrios Kyrtzidis0e37afa2011-05-25 05:05:01 +00001421 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
Chris Lattner86ed5b02010-05-05 05:53:24 +00001422}
1423
Yuka Takahashi1a895202017-08-29 17:46:46 +00001424void Driver::handleAutocompletions(StringRef PassedFlags) const {
1425 // Print out all options that start with a given argument. This is used for
1426 // shell autocompletion.
1427 std::vector<std::string> SuggestedCompletions;
1428
1429 unsigned short DisableFlags =
1430 options::NoDriverOption | options::Unsupported | options::Ignored;
1431 // We want to show cc1-only options only when clang is invoked as "clang
Raphael Isemannbd7c45e2017-09-05 12:41:00 +00001432 // -cc1". When clang is invoked as "clang -cc1", we add "#" to the beginning
1433 // of an --autocomplete option so that the clang driver can distinguish
1434 // whether it is requested to show cc1-only options or not.
1435 if (PassedFlags.size() > 0 && PassedFlags[0] == '#') {
Yuka Takahashi1a895202017-08-29 17:46:46 +00001436 DisableFlags &= ~options::NoDriverOption;
1437 PassedFlags = PassedFlags.substr(1);
1438 }
1439
1440 if (PassedFlags.find(',') == StringRef::npos) {
1441 // If the flag is in the form of "--autocomplete=-foo",
1442 // we were requested to print out all option names that start with "-foo".
1443 // For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only".
1444 SuggestedCompletions = Opts->findByPrefix(PassedFlags, DisableFlags);
1445
1446 // We have to query the -W flags manually as they're not in the OptTable.
1447 // TODO: Find a good way to add them to OptTable instead and them remove
1448 // this code.
1449 for (StringRef S : DiagnosticIDs::getDiagnosticFlags())
1450 if (S.startswith(PassedFlags))
1451 SuggestedCompletions.push_back(S);
1452 } else {
1453 // If the flag is in the form of "--autocomplete=foo,bar", we were
1454 // requested to print out all option values for "-foo" that start with
1455 // "bar". For example,
1456 // "--autocomplete=-stdlib=,l" is expanded to "libc++" and "libstdc++".
1457 StringRef Option, Arg;
1458 std::tie(Option, Arg) = PassedFlags.split(',');
1459 SuggestedCompletions = Opts->suggestValueCompletions(Option, Arg);
1460 }
1461
1462 // Sort the autocomplete candidates so that shells print them out in a
1463 // deterministic order. We could sort in any way, but we chose
1464 // case-insensitive sorting for consistency with the -help option
1465 // which prints out options in the case-insensitive alphabetical order.
1466 std::sort(SuggestedCompletions.begin(), SuggestedCompletions.end(),
Mandeep Singh Grang8f54ae12017-11-20 18:49:14 +00001467 [](StringRef A, StringRef B) {
1468 if (int X = A.compare_lower(B))
1469 return X < 0;
1470 return A.compare(B) > 0;
1471 });
Yuka Takahashi1a895202017-08-29 17:46:46 +00001472
1473 llvm::outs() << llvm::join(SuggestedCompletions, "\n") << '\n';
1474}
1475
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001476bool Driver::HandleImmediateArgs(const Compilation &C) {
Daniel Dunbar18974bd2010-06-11 22:00:19 +00001477 // The order these options are handled in gcc is all over the place, but we
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001478 // don't expect inconsistencies w.r.t. that to matter in practice.
Daniel Dunbar7c925282009-03-31 21:38:17 +00001479
Daniel Dunbar1b09e042010-09-17 02:47:28 +00001480 if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
1481 llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
1482 return false;
1483 }
1484
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001485 if (C.getArgs().hasArg(options::OPT_dumpversion)) {
Daniel Dunbare26e5002011-01-12 00:43:47 +00001486 // Since -dumpversion is only implemented for pedantic GCC compatibility, we
1487 // return an answer which matches our definition of __VERSION__.
1488 //
1489 // If we want to return a more correct answer some day, then we should
1490 // introduce a non-pedantically GCC compatible mode to Clang in which we
1491 // provide sensible definitions for -dumpversion, __VERSION__, etc.
1492 llvm::outs() << "4.2.1\n";
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001493 return false;
1494 }
Daniel Dunbarfb3d7472010-06-14 21:23:12 +00001495
Chris Lattner86ed5b02010-05-05 05:53:24 +00001496 if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
1497 PrintDiagnosticCategories(llvm::outs());
1498 return false;
1499 }
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001500
James Molloya3c85b82012-05-01 14:57:16 +00001501 if (C.getArgs().hasArg(options::OPT_help) ||
Daniel Dunbara7b5e212009-04-15 16:34:29 +00001502 C.getArgs().hasArg(options::OPT__help_hidden)) {
1503 PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
Daniel Dunbar7c925282009-03-31 21:38:17 +00001504 return false;
1505 }
1506
Daniel Dunbarb0006ae2009-04-02 15:05:41 +00001507 if (C.getArgs().hasArg(options::OPT__version)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001508 // Follow gcc behavior and use stdout for --version and stderr for -v.
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001509 PrintVersion(C, llvm::outs());
Daniel Dunbarb0006ae2009-04-02 15:05:41 +00001510 return false;
1511 }
1512
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001513 if (C.getArgs().hasArg(options::OPT_v) ||
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001514 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001515 PrintVersion(C, llvm::errs());
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001516 SuppressMissingInputWarning = true;
1517 }
1518
Serge Pavlov208ac652018-01-01 13:27:01 +00001519 if (C.getArgs().hasArg(options::OPT_v)) {
1520 if (!SystemConfigDir.empty())
1521 llvm::errs() << "System configuration file directory: "
1522 << SystemConfigDir << "\n";
1523 if (!UserConfigDir.empty())
1524 llvm::errs() << "User configuration file directory: "
1525 << UserConfigDir << "\n";
1526 }
1527
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001528 const ToolChain &TC = C.getDefaultToolChain();
Chandler Carruth0ae39aa2013-07-30 17:57:09 +00001529
1530 if (C.getArgs().hasArg(options::OPT_v))
1531 TC.printVerboseInfo(llvm::errs());
1532
Meador Inge51208a32017-04-04 21:46:50 +00001533 if (C.getArgs().hasArg(options::OPT_print_resource_dir)) {
Meador Ingea9113952017-04-05 22:27:20 +00001534 llvm::outs() << ResourceDir << '\n';
Meador Inge51208a32017-04-04 21:46:50 +00001535 return false;
1536 }
1537
Daniel Dunbard972e222009-03-20 04:37:21 +00001538 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
1539 llvm::outs() << "programs: =";
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001540 bool separator = false;
1541 for (const std::string &Path : TC.getProgramPaths()) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001542 if (separator)
1543 llvm::outs() << ':';
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001544 llvm::outs() << Path;
1545 separator = true;
Daniel Dunbard972e222009-03-20 04:37:21 +00001546 }
1547 llvm::outs() << "\n";
Peter Collingbournefa9771f2011-09-06 02:08:31 +00001548 llvm::outs() << "libraries: =" << ResourceDir;
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001549
Sebastian Pop980920a2012-04-16 04:16:43 +00001550 StringRef sysroot = C.getSysRoot();
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001551
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001552 for (const std::string &Path : TC.getFilePaths()) {
1553 // Always print a separator. ResourceDir was the first item shown.
Peter Collingbournefa9771f2011-09-06 02:08:31 +00001554 llvm::outs() << ':';
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001555 // Interpretation of leading '=' is needed only for NetBSD.
1556 if (Path[0] == '=')
Douglas Katzman26eabf62015-06-24 15:10:30 +00001557 llvm::outs() << sysroot << Path.substr(1);
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001558 else
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001559 llvm::outs() << Path;
Daniel Dunbard972e222009-03-20 04:37:21 +00001560 }
1561 llvm::outs() << "\n";
Daniel Dunbar7c925282009-03-31 21:38:17 +00001562 return false;
Daniel Dunbard972e222009-03-20 04:37:21 +00001563 }
1564
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001565 // FIXME: The following handlers should use a callback mechanism, we don't
1566 // know what the client would like to do.
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001567 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001568 llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001569 return false;
1570 }
1571
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001572 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001573 llvm::outs() << GetProgramPath(A->getValue(), TC) << "\n";
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001574 return false;
1575 }
1576
Yuka Takahashic8068db2017-05-23 18:39:08 +00001577 if (Arg *A = C.getArgs().getLastArg(options::OPT_autocomplete)) {
Yuka Takahashiba5d4af2017-06-20 16:31:31 +00001578 StringRef PassedFlags = A->getValue();
Yuka Takahashi1a895202017-08-29 17:46:46 +00001579 handleAutocompletions(PassedFlags);
Yuka Takahashic8068db2017-05-23 18:39:08 +00001580 return false;
1581 }
1582
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001583 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
Michal Gorny7cfe4802016-10-10 12:23:40 +00001584 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(C.getArgs());
Leo Li23bb21c2017-08-24 01:51:51 +00001585 const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
1586 RegisterEffectiveTriple TripleRAII(TC, Triple);
Michal Gorny7cfe4802016-10-10 12:23:40 +00001587 switch (RLT) {
1588 case ToolChain::RLT_CompilerRT:
1589 llvm::outs() << TC.getCompilerRT(C.getArgs(), "builtins") << "\n";
1590 break;
1591 case ToolChain::RLT_Libgcc:
1592 llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
1593 break;
1594 }
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001595 return false;
1596 }
1597
Daniel Dunbar1b3ec3a2009-06-16 23:25:22 +00001598 if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
Douglas Katzmana34b7bf2015-06-30 19:32:57 +00001599 for (const Multilib &Multilib : TC.getMultilibs())
1600 llvm::outs() << Multilib << "\n";
Daniel Dunbar1b3ec3a2009-06-16 23:25:22 +00001601 return false;
1602 }
1603
Jonathan Roelofs2cea1be2014-02-12 03:21:20 +00001604 if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
Douglas Katzmana34b7bf2015-06-30 19:32:57 +00001605 for (const Multilib &Multilib : TC.getMultilibs()) {
Douglas Katzman6bbffc42015-06-25 18:51:37 +00001606 if (Multilib.gccSuffix().empty())
Jonathan Roelofs2cea1be2014-02-12 03:21:20 +00001607 llvm::outs() << ".\n";
1608 else {
Douglas Katzman6bbffc42015-06-25 18:51:37 +00001609 StringRef Suffix(Multilib.gccSuffix());
Jonathan Roelofs2cea1be2014-02-12 03:21:20 +00001610 assert(Suffix.front() == '/');
1611 llvm::outs() << Suffix.substr(1) << "\n";
1612 }
Jonathan Roelofs3fa96d82014-02-12 01:36:51 +00001613 }
Jonathan Roelofs0e7ec602014-02-12 01:29:25 +00001614 return false;
1615 }
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001616 return true;
1617}
1618
Douglas Katzmanfd528672015-06-11 15:05:22 +00001619// Display an action graph human-readably. Action A is the "sink" node
1620// and latest-occuring action. Traversal is in pre-order, visiting the
1621// inputs to each action before printing the action itself.
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001622static unsigned PrintActions1(const Compilation &C, Action *A,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001623 std::map<Action *, unsigned> &Ids) {
Douglas Katzmanfd528672015-06-11 15:05:22 +00001624 if (Ids.count(A)) // A was already visited.
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001625 return Ids[A];
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001626
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001627 std::string str;
1628 llvm::raw_string_ostream os(str);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001629
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001630 os << Action::getClassName(A->getKind()) << ", ";
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001631 if (InputAction *IA = dyn_cast<InputAction>(A)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001632 os << "\"" << IA->getInputArg().getValue() << "\"";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001633 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001634 os << '"' << BIA->getArchName() << '"' << ", {"
Nico Weber5a459f82016-02-23 19:30:43 +00001635 << PrintActions1(C, *BIA->input_begin(), Ids) << "}";
Samuel Antaod06239d2016-07-15 23:13:27 +00001636 } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
1637 bool IsFirst = true;
1638 OA->doOnEachDependence(
1639 [&](Action *A, const ToolChain *TC, const char *BoundArch) {
1640 // E.g. for two CUDA device dependences whose bound arch is sm_20 and
1641 // sm_35 this will generate:
1642 // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
1643 // (nvptx64-nvidia-cuda:sm_35) {#ID}
1644 if (!IsFirst)
1645 os << ", ";
1646 os << '"';
1647 if (TC)
1648 os << A->getOffloadingKindPrefix();
1649 else
1650 os << "host";
1651 os << " (";
1652 os << TC->getTriple().normalize();
1653
1654 if (BoundArch)
1655 os << ":" << BoundArch;
1656 os << ")";
1657 os << '"';
1658 os << " {" << PrintActions1(C, A, Ids) << "}";
1659 IsFirst = false;
1660 });
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001661 } else {
Samuel Antaod06239d2016-07-15 23:13:27 +00001662 const ActionList *AL = &A->getInputs();
Artem Belevich0ff05cd2015-07-13 23:27:56 +00001663
Artem Belevich23256752015-09-22 17:23:09 +00001664 if (AL->size()) {
1665 const char *Prefix = "{";
1666 for (Action *PreRequisite : *AL) {
1667 os << Prefix << PrintActions1(C, PreRequisite, Ids);
1668 Prefix = ", ";
1669 }
1670 os << "}";
1671 } else
1672 os << "{}";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001673 }
1674
Samuel Antaod06239d2016-07-15 23:13:27 +00001675 // Append offload info for all options other than the offloading action
1676 // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
1677 std::string offload_str;
1678 llvm::raw_string_ostream offload_os(offload_str);
1679 if (!isa<OffloadAction>(A)) {
1680 auto S = A->getOffloadingKindPrefix();
1681 if (!S.empty()) {
1682 offload_os << ", (" << S;
1683 if (A->getOffloadingArch())
1684 offload_os << ", " << A->getOffloadingArch();
1685 offload_os << ")";
1686 }
1687 }
1688
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001689 unsigned Id = Ids.size();
1690 Ids[A] = Id;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001691 llvm::errs() << Id << ": " << os.str() << ", "
Samuel Antaod06239d2016-07-15 23:13:27 +00001692 << types::getTypeName(A->getType()) << offload_os.str() << "\n";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001693
1694 return Id;
1695}
1696
Douglas Katzmanfd528672015-06-11 15:05:22 +00001697// Print the action graphs in a compilation C.
1698// For example "clang -c file1.c file2.c" is composed of two subgraphs.
Daniel Dunbareb843be2009-03-18 03:13:20 +00001699void Driver::PrintActions(const Compilation &C) const {
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001700 std::map<Action *, unsigned> Ids;
1701 for (Action *A : C.getActions())
1702 PrintActions1(C, A, Ids);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001703}
1704
Joerg Sonnenberger5fe4a7d2011-05-06 14:05:11 +00001705/// \brief Check whether the given input tree contains any compilation or
1706/// assembly actions.
1707static bool ContainsCompileOrAssembleAction(const Action *A) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001708 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
Bob Wilson23a55f12014-12-21 07:00:00 +00001709 isa<AssembleJobAction>(A))
Daniel Dunbar00d3d8e2010-06-29 16:38:33 +00001710 return true;
1711
Nico Weber5a459f82016-02-23 19:30:43 +00001712 for (const Action *Input : A->inputs())
Nico Weberfb80f962015-09-19 21:36:51 +00001713 if (ContainsCompileOrAssembleAction(Input))
Daniel Dunbar00d3d8e2010-06-29 16:38:33 +00001714 return true;
1715
1716 return false;
1717}
1718
Artem Belevich5e2a3ec2015-11-17 22:28:40 +00001719void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
1720 const InputList &BAInputs) const {
1721 DerivedArgList &Args = C.getArgs();
1722 ActionList &Actions = C.getActions();
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001723 llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
1724 // Collect the list of architectures. Duplicates are allowed, but should only
1725 // be handled once (in the order seen).
Daniel Dunbare5dc4822009-03-13 20:33:35 +00001726 llvm::StringSet<> ArchNames;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001727 SmallVector<const char *, 4> Archs;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00001728 for (Arg *A : Args) {
Daniel Dunbar0bfb21e2009-11-19 03:26:40 +00001729 if (A->getOption().matches(options::OPT_arch)) {
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001730 // Validate the option here; we don't save the type here because its
1731 // particular spelling may participate in other driver choices.
1732 llvm::Triple::ArchType Arch =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001733 tools::darwin::getArchTypeForMachOArchName(A->getValue());
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001734 if (Arch == llvm::Triple::UnknownArch) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001735 Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001736 continue;
1737 }
1738
Daniel Dunbar2da02722009-03-19 07:55:12 +00001739 A->claim();
David Blaikie61b86d42014-11-19 02:56:13 +00001740 if (ArchNames.insert(A->getValue()).second)
Richard Smithbd55daf2012-11-01 04:30:05 +00001741 Archs.push_back(A->getValue());
Daniel Dunbarf479c122009-03-12 18:40:18 +00001742 }
1743 }
1744
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001745 // When there is no explicit arch for this platform, make sure we still bind
1746 // the architecture (to the default) so that -Xarch_ is handled correctly.
Daniel Dunbareb843be2009-03-18 03:13:20 +00001747 if (!Archs.size())
Daniel Dunbarc3bd9f52012-11-08 03:38:26 +00001748 Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
Daniel Dunbarf479c122009-03-12 18:40:18 +00001749
Daniel Dunbarf479c122009-03-12 18:40:18 +00001750 ActionList SingleActions;
Justin Lebar0f3474c2016-02-11 02:00:50 +00001751 BuildActions(C, Args, BAInputs, SingleActions);
Daniel Dunbarf479c122009-03-12 18:40:18 +00001752
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001753 // Add in arch bindings for every top level action, as well as lipo and
1754 // dsymutil steps if needed.
Nico Weberfb80f962015-09-19 21:36:51 +00001755 for (Action* Act : SingleActions) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001756 // Make sure we can lipo this kind of output. If not (and it is an actual
1757 // output) then we disallow, since we can't create an output file with the
1758 // right name without overwriting it. We could remove this oddity by just
1759 // changing the output names to include the arch, which would also fix
Daniel Dunbarf479c122009-03-12 18:40:18 +00001760 // -save-temps. Compatibility wins for now.
1761
Daniel Dunbare2ca3bd2009-03-13 17:46:02 +00001762 if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
Daniel Dunbarf479c122009-03-12 18:40:18 +00001763 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001764 << types::getTypeName(Act->getType());
Daniel Dunbarf479c122009-03-12 18:40:18 +00001765
1766 ActionList Inputs;
Justin Lebar41094612016-01-11 23:07:27 +00001767 for (unsigned i = 0, e = Archs.size(); i != e; ++i)
1768 Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
Daniel Dunbarf479c122009-03-12 18:40:18 +00001769
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001770 // Lipo if necessary, we do it this way because we need to set the arch flag
1771 // so that -Xarch_ gets overwritten.
Daniel Dunbarf479c122009-03-12 18:40:18 +00001772 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
1773 Actions.append(Inputs.begin(), Inputs.end());
1774 else
Justin Lebar41094612016-01-11 23:07:27 +00001775 Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001776
Eric Christopher65c05fa2012-02-06 19:43:51 +00001777 // Handle debug info queries.
1778 Arg *A = Args.getLastArg(options::OPT_g_Group);
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001779 if (A && !A->getOption().matches(options::OPT_g0) &&
1780 !A->getOption().matches(options::OPT_gstabs) &&
1781 ContainsCompileOrAssembleAction(Actions.back())) {
Chad Rosier62135492012-07-09 17:31:28 +00001782
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001783 // Add a 'dsymutil' step if necessary, when debug info is enabled and we
1784 // have a compile input. We need to run 'dsymutil' ourselves in such cases
Eric Christopher776c26f2013-01-28 17:39:03 +00001785 // because the debug info will refer to a temporary object file which
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001786 // will be removed at the end of the compilation process.
1787 if (Act->getType() == types::TY_Image) {
1788 ActionList Inputs;
1789 Inputs.push_back(Actions.back());
1790 Actions.pop_back();
Justin Lebar41094612016-01-11 23:07:27 +00001791 Actions.push_back(
1792 C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001793 }
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001794
Ben Langmuir9b9a8d32014-02-06 18:53:25 +00001795 // Verify the debug info output.
Alp Tokere9d2bfc2014-01-17 02:06:23 +00001796 if (Args.hasArg(options::OPT_verify_debug_info)) {
Justin Lebar41094612016-01-11 23:07:27 +00001797 Action* LastAction = Actions.back();
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001798 Actions.pop_back();
Justin Lebar41094612016-01-11 23:07:27 +00001799 Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
1800 LastAction, types::TY_Nothing));
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001801 }
1802 }
Daniel Dunbarf479c122009-03-12 18:40:18 +00001803 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001804}
1805
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001806/// \brief Check that the file referenced by Value exists. If it doesn't,
1807/// issue a diagnostic and return false.
Alp Toker8c8a8752013-12-03 06:53:35 +00001808static bool DiagnoseInputExistence(const Driver &D, const DerivedArgList &Args,
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001809 StringRef Value, types::ID Ty) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001810 if (!D.getCheckInputsExist())
1811 return true;
1812
1813 // stdin always exists.
1814 if (Value == "-")
1815 return true;
1816
1817 SmallString<64> Path(Value);
1818 if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
Yaron Keren92e1b622015-03-18 10:17:07 +00001819 if (!llvm::sys::path::is_absolute(Path)) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001820 SmallString<64> Directory(WorkDir->getValue());
1821 llvm::sys::path::append(Directory, Value);
1822 Path.assign(Directory);
1823 }
1824 }
1825
1826 if (llvm::sys::fs::exists(Twine(Path)))
1827 return true;
1828
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001829 if (D.IsCLMode()) {
1830 if (!llvm::sys::path::is_absolute(Twine(Path)) &&
1831 llvm::sys::Process::FindInEnvPath("LIB", Value))
1832 return true;
1833
1834 if (Args.hasArg(options::OPT__SLASH_link) && Ty == types::TY_Object) {
1835 // Arguments to the /link flag might cause the linker to search for object
1836 // and library files in paths we don't know about. Don't error in such
1837 // cases.
1838 return true;
1839 }
1840 }
Hans Wennborg23d26a32014-06-18 17:21:50 +00001841
Yaron Keren92e1b622015-03-18 10:17:07 +00001842 D.Diag(clang::diag::err_drv_no_such_file) << Path;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001843 return false;
1844}
1845
Chad Rosierecdede82011-08-12 22:08:57 +00001846// Construct a the list of inputs and their types.
Hans Wennborg55362852014-05-02 22:55:30 +00001847void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
Chad Rosierecdede82011-08-12 22:08:57 +00001848 InputList &Inputs) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001849 // Track the current user specified (-x) input. We also explicitly track the
1850 // argument used to set the type; we only want to claim the type when we
1851 // actually use it, so we warn about unused -x arguments.
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00001852 types::ID InputType = types::TY_Nothing;
Craig Topper92fc2df2014-05-17 16:56:41 +00001853 Arg *InputTypeArg = nullptr;
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00001854
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001855 // The last /TC or /TP option sets the input type to C or C++ globally.
Ehsan Akhgaric249abb2014-09-12 21:44:24 +00001856 if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
1857 options::OPT__SLASH_TP)) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001858 InputTypeArg = TCTP;
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001859 InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001860 ? types::TY_C
1861 : types::TY_CXX;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001862
Richard Smith0aef3052017-02-18 01:14:43 +00001863 Arg *Previous = nullptr;
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001864 bool ShowNote = false;
Richard Smith0aef3052017-02-18 01:14:43 +00001865 for (Arg *A : Args.filtered(options::OPT__SLASH_TC, options::OPT__SLASH_TP)) {
1866 if (Previous) {
1867 Diag(clang::diag::warn_drv_overriding_flag_option)
1868 << Previous->getSpelling() << A->getSpelling();
1869 ShowNote = true;
1870 }
1871 Previous = A;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001872 }
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001873 if (ShowNote)
1874 Diag(clang::diag::note_drv_t_option_is_global);
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001875
1876 // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
1877 assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
1878 }
1879
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00001880 for (Arg *A : Args) {
Michael J. Spencerad3ccc32012-08-20 21:41:17 +00001881 if (A->getOption().getKind() == Option::InputClass) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001882 const char *Value = A->getValue();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001883 types::ID Ty = types::TY_INVALID;
1884
1885 // Infer the input type if necessary.
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00001886 if (InputType == types::TY_Nothing) {
1887 // If there was an explicit arg for this, claim it.
1888 if (InputTypeArg)
1889 InputTypeArg->claim();
1890
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001891 // stdin must be handled specially.
1892 if (memcmp(Value, "-", 2) == 0) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001893 // If running with -E, treat as a C input (this changes the builtin
1894 // macros, for example). This may be overridden by -ObjC below.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001895 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001896 // Otherwise emit an error but still use a valid type to avoid
1897 // spurious errors (e.g., no inputs).
Hans Wennborg70850d82013-07-18 20:29:38 +00001898 if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
Hans Wennborgcfdd8b52014-01-29 01:04:40 +00001899 Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
1900 : clang::diag::err_drv_unknown_stdin_type);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001901 Ty = types::TY_C;
1902 } else {
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00001903 // Otherwise lookup by extension.
1904 // Fallback is C if invoked as C preprocessor or Object otherwise.
1905 // We use a host hook here because Darwin at least has its own
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001906 // idea of what .s is.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001907 if (const char *Ext = strrchr(Value, '.'))
Daniel Dunbarcc7df6c2010-08-02 05:43:56 +00001908 Ty = TC.LookupTypeForExtension(Ext + 1);
Daniel Dunbarea9f0322009-03-20 23:39:23 +00001909
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00001910 if (Ty == types::TY_INVALID) {
Hans Wennborg70850d82013-07-18 20:29:38 +00001911 if (CCCIsCPP())
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00001912 Ty = types::TY_C;
1913 else
1914 Ty = types::TY_Object;
1915 }
Daniel Dunbar0ac94452010-02-17 20:32:58 +00001916
1917 // If the driver is invoked as C++ compiler (like clang++ or c++) it
1918 // should autodetect some input files as C++ for g++ compatibility.
Hans Wennborg70850d82013-07-18 20:29:38 +00001919 if (CCCIsCXX()) {
Daniel Dunbar0ac94452010-02-17 20:32:58 +00001920 types::ID OldTy = Ty;
1921 Ty = types::lookupCXXTypeForCType(Ty);
1922
1923 if (Ty != OldTy)
1924 Diag(clang::diag::warn_drv_treating_input_as_cxx)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001925 << getTypeName(OldTy) << getTypeName(Ty);
Daniel Dunbar0ac94452010-02-17 20:32:58 +00001926 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001927 }
1928
Daniel Dunbar82b22102009-05-18 21:47:54 +00001929 // -ObjC and -ObjC++ override the default language, but only for "source
1930 // files". We just treat everything that isn't a linker input as a
1931 // source file.
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001932 //
Daniel Dunbar82b22102009-05-18 21:47:54 +00001933 // FIXME: Clean this up if we move the phase sequence into the type.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001934 if (Ty != types::TY_Object) {
1935 if (Args.hasArg(options::OPT_ObjC))
1936 Ty = types::TY_ObjC;
1937 else if (Args.hasArg(options::OPT_ObjCXX))
1938 Ty = types::TY_ObjCXX;
1939 }
1940 } else {
1941 assert(InputTypeArg && "InputType set w/o InputTypeArg");
Ehsan Akhgari7e954ea2014-09-12 18:15:10 +00001942 if (!InputTypeArg->getOption().matches(options::OPT_x)) {
1943 // If emulating cl.exe, make sure that /TC and /TP don't affect input
1944 // object files.
1945 const char *Ext = strrchr(Value, '.');
1946 if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
1947 Ty = types::TY_Object;
1948 }
1949 if (Ty == types::TY_INVALID) {
1950 Ty = InputType;
1951 InputTypeArg->claim();
1952 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001953 }
1954
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001955 if (DiagnoseInputExistence(*this, Args, Value, Ty))
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001956 Inputs.push_back(std::make_pair(Ty, A));
1957
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001958 } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
1959 StringRef Value = A->getValue();
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001960 if (DiagnoseInputExistence(*this, Args, Value, types::TY_C)) {
David Blaikie0aaa7622017-01-13 17:34:15 +00001961 Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001962 Inputs.push_back(std::make_pair(types::TY_C, InputArg));
1963 }
1964 A->claim();
1965 } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
1966 StringRef Value = A->getValue();
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001967 if (DiagnoseInputExistence(*this, Args, Value, types::TY_CXX)) {
David Blaikie0aaa7622017-01-13 17:34:15 +00001968 Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001969 Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
1970 }
1971 A->claim();
Michael J. Spencer66e2b202012-10-19 22:37:06 +00001972 } else if (A->getOption().hasFlag(options::LinkerInput)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001973 // Just treat as object type, we could make a special type for this if
1974 // necessary.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001975 Inputs.push_back(std::make_pair(types::TY_Object, A));
1976
Daniel Dunbar0bfb21e2009-11-19 03:26:40 +00001977 } else if (A->getOption().matches(options::OPT_x)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001978 InputTypeArg = A;
Richard Smithbd55daf2012-11-01 04:30:05 +00001979 InputType = types::lookupTypeForTypeSpecifier(A->getValue());
Chad Rosier706c2352012-04-07 00:01:31 +00001980 A->claim();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001981
1982 // Follow gcc behavior and treat as linker input for invalid -x
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001983 // options. Its not clear why we shouldn't just revert to unknown; but
Michael J. Spencer1a4fe8c2010-12-17 21:22:33 +00001984 // this isn't very important, we might as well be bug compatible.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001985 if (!InputType) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001986 Diag(clang::diag::err_drv_unknown_language) << A->getValue();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001987 InputType = types::TY_Object;
1988 }
Hans Wennborg091f1b62017-01-27 17:09:41 +00001989 } else if (A->getOption().getID() == options::OPT__SLASH_U) {
1990 assert(A->getNumValues() == 1 && "The /U option has one value.");
1991 StringRef Val = A->getValue(0);
1992 if (Val.find_first_of("/\\") != StringRef::npos) {
1993 // Warn about e.g. "/Users/me/myfile.c".
1994 Diag(diag::warn_slash_u_filename) << Val;
1995 Diag(diag::note_use_dashdash);
1996 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001997 }
1998 }
Hans Wennborg70850d82013-07-18 20:29:38 +00001999 if (CCCIsCPP() && Inputs.empty()) {
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00002000 // If called as standalone preprocessor, stdin is processed
2001 // if no other input is present.
David Blaikie0aaa7622017-01-13 17:34:15 +00002002 Arg *A = MakeInputArg(Args, *Opts, "-");
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00002003 Inputs.push_back(std::make_pair(types::TY_C, A));
2004 }
Chad Rosierecdede82011-08-12 22:08:57 +00002005}
2006
Samuel Antao64e965e2016-09-30 15:34:19 +00002007namespace {
2008/// Provides a convenient interface for different programming models to generate
2009/// the required device actions.
2010class OffloadingActionBuilder final {
2011 /// Flag used to trace errors in the builder.
2012 bool IsValid = false;
2013
2014 /// The compilation that is using this builder.
2015 Compilation &C;
2016
Samuel Antao64e965e2016-09-30 15:34:19 +00002017 /// Map between an input argument and the offload kinds used to process it.
2018 std::map<const Arg *, unsigned> InputArgToOffloadKindMap;
2019
2020 /// Builder interface. It doesn't build anything or keep any state.
2021 class DeviceActionBuilder {
2022 public:
2023 typedef llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PhasesTy;
2024
2025 enum ActionBuilderReturnCode {
2026 // The builder acted successfully on the current action.
2027 ABRT_Success,
2028 // The builder didn't have to act on the current action.
2029 ABRT_Inactive,
2030 // The builder was successful and requested the host action to not be
2031 // generated.
2032 ABRT_Ignore_Host,
2033 };
2034
2035 protected:
2036 /// Compilation associated with this builder.
2037 Compilation &C;
2038
2039 /// Tool chains associated with this builder. The same programming
2040 /// model may have associated one or more tool chains.
2041 SmallVector<const ToolChain *, 2> ToolChains;
2042
2043 /// The derived arguments associated with this builder.
2044 DerivedArgList &Args;
2045
2046 /// The inputs associated with this builder.
2047 const Driver::InputList &Inputs;
2048
2049 /// The associated offload kind.
2050 Action::OffloadKind AssociatedOffloadKind = Action::OFK_None;
2051
2052 public:
2053 DeviceActionBuilder(Compilation &C, DerivedArgList &Args,
2054 const Driver::InputList &Inputs,
2055 Action::OffloadKind AssociatedOffloadKind)
2056 : C(C), Args(Args), Inputs(Inputs),
2057 AssociatedOffloadKind(AssociatedOffloadKind) {}
2058 virtual ~DeviceActionBuilder() {}
2059
2060 /// Fill up the array \a DA with all the device dependences that should be
2061 /// added to the provided host action \a HostAction. By default it is
2062 /// inactive.
2063 virtual ActionBuilderReturnCode
Samuel Antao28c4f182016-10-27 17:08:03 +00002064 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2065 phases::ID CurPhase, phases::ID FinalPhase,
2066 PhasesTy &Phases) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002067 return ABRT_Inactive;
2068 }
2069
2070 /// Update the state to include the provided host action \a HostAction as a
2071 /// dependency of the current device action. By default it is inactive.
2072 virtual ActionBuilderReturnCode addDeviceDepences(Action *HostAction) {
2073 return ABRT_Inactive;
2074 }
2075
2076 /// Append top level actions generated by the builder. Return true if errors
2077 /// were found.
2078 virtual void appendTopLevelActions(ActionList &AL) {}
2079
2080 /// Append linker actions generated by the builder. Return true if errors
2081 /// were found.
2082 virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {}
2083
2084 /// Initialize the builder. Return true if any initialization errors are
2085 /// found.
2086 virtual bool initialize() { return false; }
2087
Samuel Antao69d6f312016-10-27 17:50:43 +00002088 /// Return true if the builder can use bundling/unbundling.
2089 virtual bool canUseBundlerUnbundler() const { return false; }
2090
Samuel Antao64e965e2016-09-30 15:34:19 +00002091 /// Return true if this builder is valid. We have a valid builder if we have
2092 /// associated device tool chains.
2093 bool isValid() { return !ToolChains.empty(); }
2094
2095 /// Return the associated offload kind.
2096 Action::OffloadKind getAssociatedOffloadKind() {
2097 return AssociatedOffloadKind;
2098 }
2099 };
2100
2101 /// \brief CUDA action builder. It injects device code in the host backend
2102 /// action.
2103 class CudaActionBuilder final : public DeviceActionBuilder {
2104 /// Flags to signal if the user requested host-only or device-only
2105 /// compilation.
2106 bool CompileHostOnly = false;
2107 bool CompileDeviceOnly = false;
2108
2109 /// List of GPU architectures to use in this compilation.
2110 SmallVector<CudaArch, 4> GpuArchList;
2111
2112 /// The CUDA actions for the current input.
2113 ActionList CudaDeviceActions;
2114
2115 /// The CUDA fat binary if it was generated for the current input.
2116 Action *CudaFatBinary = nullptr;
2117
2118 /// Flag that is set to true if this builder acted on the current input.
2119 bool IsActive = false;
2120
2121 public:
2122 CudaActionBuilder(Compilation &C, DerivedArgList &Args,
2123 const Driver::InputList &Inputs)
2124 : DeviceActionBuilder(C, Args, Inputs, Action::OFK_Cuda) {}
2125
2126 ActionBuilderReturnCode
Samuel Antao28c4f182016-10-27 17:08:03 +00002127 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2128 phases::ID CurPhase, phases::ID FinalPhase,
2129 PhasesTy &Phases) override {
Samuel Antao64e965e2016-09-30 15:34:19 +00002130 if (!IsActive)
2131 return ABRT_Inactive;
2132
2133 // If we don't have more CUDA actions, we don't have any dependences to
2134 // create for the host.
2135 if (CudaDeviceActions.empty())
2136 return ABRT_Success;
2137
2138 assert(CudaDeviceActions.size() == GpuArchList.size() &&
2139 "Expecting one action per GPU architecture.");
2140 assert(!CompileHostOnly &&
2141 "Not expecting CUDA actions in host-only compilation.");
2142
2143 // If we are generating code for the device or we are in a backend phase,
2144 // we attempt to generate the fat binary. We compile each arch to ptx and
2145 // assemble to cubin, then feed the cubin *and* the ptx into a device
2146 // "link" action, which uses fatbinary to combine these cubins into one
2147 // fatbin. The fatbin is then an input to the host action if not in
2148 // device-only mode.
2149 if (CompileDeviceOnly || CurPhase == phases::Backend) {
2150 ActionList DeviceActions;
2151 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2152 // Produce the device action from the current phase up to the assemble
2153 // phase.
2154 for (auto Ph : Phases) {
2155 // Skip the phases that were already dealt with.
2156 if (Ph < CurPhase)
2157 continue;
2158 // We have to be consistent with the host final phase.
2159 if (Ph > FinalPhase)
2160 break;
2161
2162 CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction(
2163 C, Args, Ph, CudaDeviceActions[I]);
2164
2165 if (Ph == phases::Assemble)
2166 break;
2167 }
2168
2169 // If we didn't reach the assemble phase, we can't generate the fat
2170 // binary. We don't need to generate the fat binary if we are not in
2171 // device-only mode.
2172 if (!isa<AssembleJobAction>(CudaDeviceActions[I]) ||
2173 CompileDeviceOnly)
2174 continue;
2175
2176 Action *AssembleAction = CudaDeviceActions[I];
2177 assert(AssembleAction->getType() == types::TY_Object);
2178 assert(AssembleAction->getInputs().size() == 1);
2179
2180 Action *BackendAction = AssembleAction->getInputs()[0];
2181 assert(BackendAction->getType() == types::TY_PP_Asm);
2182
2183 for (auto &A : {AssembleAction, BackendAction}) {
2184 OffloadAction::DeviceDependences DDep;
2185 DDep.add(*A, *ToolChains.front(), CudaArchToString(GpuArchList[I]),
2186 Action::OFK_Cuda);
2187 DeviceActions.push_back(
2188 C.MakeAction<OffloadAction>(DDep, A->getType()));
2189 }
2190 }
2191
2192 // We generate the fat binary if we have device input actions.
2193 if (!DeviceActions.empty()) {
2194 CudaFatBinary =
2195 C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN);
2196
2197 if (!CompileDeviceOnly) {
2198 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
2199 Action::OFK_Cuda);
2200 // Clear the fat binary, it is already a dependence to an host
2201 // action.
2202 CudaFatBinary = nullptr;
2203 }
2204
2205 // Remove the CUDA actions as they are already connected to an host
2206 // action or fat binary.
2207 CudaDeviceActions.clear();
2208 }
2209
2210 // We avoid creating host action in device-only mode.
2211 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
Samuel Antao5b1a89a2016-10-27 00:53:34 +00002212 } else if (CurPhase > phases::Backend) {
2213 // If we are past the backend phase and still have a device action, we
2214 // don't have to do anything as this action is already a device
2215 // top-level action.
2216 return ABRT_Success;
Samuel Antao64e965e2016-09-30 15:34:19 +00002217 }
2218
2219 assert(CurPhase < phases::Backend && "Generating single CUDA "
2220 "instructions should only occur "
2221 "before the backend phase!");
2222
2223 // By default, we produce an action for each device arch.
2224 for (Action *&A : CudaDeviceActions)
2225 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2226
2227 return ABRT_Success;
2228 }
2229
2230 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2231 // While generating code for CUDA, we only depend on the host input action
2232 // to trigger the creation of all the CUDA device actions.
2233
2234 // If we are dealing with an input action, replicate it for each GPU
2235 // architecture. If we are in host-only mode we return 'success' so that
2236 // the host uses the CUDA offload kind.
2237 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2238 assert(!GpuArchList.empty() &&
2239 "We should have at least one GPU architecture.");
2240
2241 // If the host input is not CUDA, we don't need to bother about this
2242 // input.
2243 if (IA->getType() != types::TY_CUDA) {
2244 // The builder will ignore this input.
2245 IsActive = false;
2246 return ABRT_Inactive;
2247 }
2248
2249 // Set the flag to true, so that the builder acts on the current input.
2250 IsActive = true;
2251
2252 if (CompileHostOnly)
2253 return ABRT_Success;
2254
2255 // Replicate inputs for each GPU architecture.
2256 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
2257 CudaDeviceActions.push_back(C.MakeAction<InputAction>(
2258 IA->getInputArg(), types::TY_CUDA_DEVICE));
2259
2260 return ABRT_Success;
2261 }
2262
2263 return IsActive ? ABRT_Success : ABRT_Inactive;
2264 }
2265
2266 void appendTopLevelActions(ActionList &AL) override {
2267 // Utility to append actions to the top level list.
2268 auto AddTopLevel = [&](Action *A, CudaArch BoundArch) {
2269 OffloadAction::DeviceDependences Dep;
2270 Dep.add(*A, *ToolChains.front(), CudaArchToString(BoundArch),
2271 Action::OFK_Cuda);
2272 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2273 };
2274
2275 // If we have a fat binary, add it to the list.
2276 if (CudaFatBinary) {
2277 AddTopLevel(CudaFatBinary, CudaArch::UNKNOWN);
2278 CudaDeviceActions.clear();
2279 CudaFatBinary = nullptr;
2280 return;
2281 }
2282
2283 if (CudaDeviceActions.empty())
2284 return;
2285
2286 // If we have CUDA actions at this point, that's because we have a have
2287 // partial compilation, so we should have an action for each GPU
2288 // architecture.
2289 assert(CudaDeviceActions.size() == GpuArchList.size() &&
2290 "Expecting one action per GPU architecture.");
2291 assert(ToolChains.size() == 1 &&
2292 "Expecting to have a sing CUDA toolchain.");
2293 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
2294 AddTopLevel(CudaDeviceActions[I], GpuArchList[I]);
2295
2296 CudaDeviceActions.clear();
2297 }
2298
2299 bool initialize() override {
2300 // We don't need to support CUDA.
2301 if (!C.hasOffloadToolChain<Action::OFK_Cuda>())
2302 return false;
2303
2304 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
2305 assert(HostTC && "No toolchain for host compilation.");
2306 if (HostTC->getTriple().isNVPTX()) {
2307 // We do not support targeting NVPTX for host compilation. Throw
2308 // an error and abort pipeline construction early so we don't trip
2309 // asserts that assume device-side compilation.
2310 C.getDriver().Diag(diag::err_drv_cuda_nvptx_host);
2311 return true;
2312 }
2313
2314 ToolChains.push_back(C.getSingleOffloadToolChain<Action::OFK_Cuda>());
2315
2316 Arg *PartialCompilationArg = Args.getLastArg(
2317 options::OPT_cuda_host_only, options::OPT_cuda_device_only,
2318 options::OPT_cuda_compile_host_device);
2319 CompileHostOnly = PartialCompilationArg &&
2320 PartialCompilationArg->getOption().matches(
2321 options::OPT_cuda_host_only);
2322 CompileDeviceOnly = PartialCompilationArg &&
2323 PartialCompilationArg->getOption().matches(
2324 options::OPT_cuda_device_only);
2325
2326 // Collect all cuda_gpu_arch parameters, removing duplicates.
Artem Belevicha424e882016-12-09 22:59:17 +00002327 std::set<CudaArch> GpuArchs;
Samuel Antao64e965e2016-09-30 15:34:19 +00002328 bool Error = false;
2329 for (Arg *A : Args) {
Artem Belevicha424e882016-12-09 22:59:17 +00002330 if (!(A->getOption().matches(options::OPT_cuda_gpu_arch_EQ) ||
2331 A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ)))
Samuel Antao64e965e2016-09-30 15:34:19 +00002332 continue;
2333 A->claim();
2334
Artem Belevicha424e882016-12-09 22:59:17 +00002335 const StringRef ArchStr = A->getValue();
2336 if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ) &&
2337 ArchStr == "all") {
2338 GpuArchs.clear();
2339 continue;
2340 }
Samuel Antao64e965e2016-09-30 15:34:19 +00002341 CudaArch Arch = StringToCudaArch(ArchStr);
2342 if (Arch == CudaArch::UNKNOWN) {
2343 C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
2344 Error = true;
Artem Belevicha424e882016-12-09 22:59:17 +00002345 } else if (A->getOption().matches(options::OPT_cuda_gpu_arch_EQ))
2346 GpuArchs.insert(Arch);
2347 else if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ))
2348 GpuArchs.erase(Arch);
2349 else
2350 llvm_unreachable("Unexpected option.");
Samuel Antao64e965e2016-09-30 15:34:19 +00002351 }
2352
Artem Belevicha424e882016-12-09 22:59:17 +00002353 // Collect list of GPUs remaining in the set.
2354 for (CudaArch Arch : GpuArchs)
2355 GpuArchList.push_back(Arch);
2356
2357 // Default to sm_20 which is the lowest common denominator for
2358 // supported GPUs. sm_20 code should work correctly, if
2359 // suboptimally, on all newer GPUs.
Samuel Antao64e965e2016-09-30 15:34:19 +00002360 if (GpuArchList.empty())
2361 GpuArchList.push_back(CudaArch::SM_20);
2362
2363 return Error;
2364 }
2365 };
2366
Samuel Antao28c4f182016-10-27 17:08:03 +00002367 /// OpenMP action builder. The host bitcode is passed to the device frontend
2368 /// and all the device linked images are passed to the host link phase.
2369 class OpenMPActionBuilder final : public DeviceActionBuilder {
2370 /// The OpenMP actions for the current input.
2371 ActionList OpenMPDeviceActions;
2372
2373 /// The linker inputs obtained for each toolchain.
2374 SmallVector<ActionList, 8> DeviceLinkerInputs;
2375
2376 public:
2377 OpenMPActionBuilder(Compilation &C, DerivedArgList &Args,
2378 const Driver::InputList &Inputs)
2379 : DeviceActionBuilder(C, Args, Inputs, Action::OFK_OpenMP) {}
2380
2381 ActionBuilderReturnCode
2382 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2383 phases::ID CurPhase, phases::ID FinalPhase,
2384 PhasesTy &Phases) override {
2385
2386 // We should always have an action for each input.
2387 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2388 "Number of OpenMP actions and toolchains do not match.");
2389
2390 // The host only depends on device action in the linking phase, when all
2391 // the device images have to be embedded in the host image.
2392 if (CurPhase == phases::Link) {
2393 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2394 "Toolchains and linker inputs sizes do not match.");
2395 auto LI = DeviceLinkerInputs.begin();
2396 for (auto *A : OpenMPDeviceActions) {
2397 LI->push_back(A);
2398 ++LI;
2399 }
2400
2401 // We passed the device action as a host dependence, so we don't need to
2402 // do anything else with them.
2403 OpenMPDeviceActions.clear();
2404 return ABRT_Success;
2405 }
2406
2407 // By default, we produce an action for each device arch.
2408 for (Action *&A : OpenMPDeviceActions)
2409 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2410
2411 return ABRT_Success;
2412 }
2413
2414 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2415
2416 // If this is an input action replicate it for each OpenMP toolchain.
2417 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2418 OpenMPDeviceActions.clear();
2419 for (unsigned I = 0; I < ToolChains.size(); ++I)
2420 OpenMPDeviceActions.push_back(
2421 C.MakeAction<InputAction>(IA->getInputArg(), IA->getType()));
2422 return ABRT_Success;
2423 }
2424
Samuel Antaofab4f372016-10-27 18:00:51 +00002425 // If this is an unbundling action use it as is for each OpenMP toolchain.
2426 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2427 OpenMPDeviceActions.clear();
2428 for (unsigned I = 0; I < ToolChains.size(); ++I) {
2429 OpenMPDeviceActions.push_back(UA);
2430 UA->registerDependentActionInfo(
2431 ToolChains[I], /*BoundArch=*/StringRef(), Action::OFK_OpenMP);
2432 }
2433 return ABRT_Success;
2434 }
2435
Samuel Antao28c4f182016-10-27 17:08:03 +00002436 // When generating code for OpenMP we use the host compile phase result as
2437 // a dependence to the device compile phase so that it can learn what
2438 // declarations should be emitted. However, this is not the only use for
2439 // the host action, so we prevent it from being collapsed.
2440 if (isa<CompileJobAction>(HostAction)) {
2441 HostAction->setCannotBeCollapsedWithNextDependentAction();
2442 assert(ToolChains.size() == OpenMPDeviceActions.size() &&
2443 "Toolchains and device action sizes do not match.");
2444 OffloadAction::HostDependence HDep(
2445 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2446 /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2447 auto TC = ToolChains.begin();
2448 for (Action *&A : OpenMPDeviceActions) {
2449 assert(isa<CompileJobAction>(A));
2450 OffloadAction::DeviceDependences DDep;
2451 DDep.add(*A, **TC, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2452 A = C.MakeAction<OffloadAction>(HDep, DDep);
2453 ++TC;
2454 }
2455 }
2456 return ABRT_Success;
2457 }
2458
Samuel Antao69d6f312016-10-27 17:50:43 +00002459 void appendTopLevelActions(ActionList &AL) override {
2460 if (OpenMPDeviceActions.empty())
2461 return;
2462
2463 // We should always have an action for each input.
2464 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2465 "Number of OpenMP actions and toolchains do not match.");
2466
2467 // Append all device actions followed by the proper offload action.
2468 auto TI = ToolChains.begin();
2469 for (auto *A : OpenMPDeviceActions) {
2470 OffloadAction::DeviceDependences Dep;
2471 Dep.add(*A, **TI, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2472 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2473 ++TI;
2474 }
2475 // We no longer need the action stored in this builder.
2476 OpenMPDeviceActions.clear();
2477 }
2478
Samuel Antao28c4f182016-10-27 17:08:03 +00002479 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {
2480 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2481 "Toolchains and linker inputs sizes do not match.");
2482
2483 // Append a new link action for each device.
2484 auto TC = ToolChains.begin();
2485 for (auto &LI : DeviceLinkerInputs) {
2486 auto *DeviceLinkAction =
2487 C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2488 DA.add(*DeviceLinkAction, **TC, /*BoundArch=*/nullptr,
2489 Action::OFK_OpenMP);
2490 ++TC;
2491 }
2492 }
2493
2494 bool initialize() override {
2495 // Get the OpenMP toolchains. If we don't get any, the action builder will
2496 // know there is nothing to do related to OpenMP offloading.
2497 auto OpenMPTCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
2498 for (auto TI = OpenMPTCRange.first, TE = OpenMPTCRange.second; TI != TE;
2499 ++TI)
2500 ToolChains.push_back(TI->second);
2501
2502 DeviceLinkerInputs.resize(ToolChains.size());
2503 return false;
2504 }
Samuel Antao69d6f312016-10-27 17:50:43 +00002505
2506 bool canUseBundlerUnbundler() const override {
2507 // OpenMP should use bundled files whenever possible.
2508 return true;
2509 }
Samuel Antao28c4f182016-10-27 17:08:03 +00002510 };
2511
2512 ///
2513 /// TODO: Add the implementation for other specialized builders here.
2514 ///
Samuel Antao64e965e2016-09-30 15:34:19 +00002515
2516 /// Specialized builders being used by this offloading action builder.
2517 SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders;
2518
Samuel Antao69d6f312016-10-27 17:50:43 +00002519 /// Flag set to true if all valid builders allow file bundling/unbundling.
2520 bool CanUseBundler;
2521
Samuel Antao64e965e2016-09-30 15:34:19 +00002522public:
2523 OffloadingActionBuilder(Compilation &C, DerivedArgList &Args,
2524 const Driver::InputList &Inputs)
Samuel Antao10e905c2016-10-27 01:08:58 +00002525 : C(C) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002526 // Create a specialized builder for each device toolchain.
2527
2528 IsValid = true;
2529
2530 // Create a specialized builder for CUDA.
2531 SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs));
2532
Samuel Antao28c4f182016-10-27 17:08:03 +00002533 // Create a specialized builder for OpenMP.
2534 SpecializedBuilders.push_back(new OpenMPActionBuilder(C, Args, Inputs));
2535
Samuel Antao64e965e2016-09-30 15:34:19 +00002536 //
2537 // TODO: Build other specialized builders here.
2538 //
2539
Samuel Antao69d6f312016-10-27 17:50:43 +00002540 // Initialize all the builders, keeping track of errors. If all valid
2541 // builders agree that we can use bundling, set the flag to true.
2542 unsigned ValidBuilders = 0u;
2543 unsigned ValidBuildersSupportingBundling = 0u;
2544 for (auto *SB : SpecializedBuilders) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002545 IsValid = IsValid && !SB->initialize();
Samuel Antao69d6f312016-10-27 17:50:43 +00002546
2547 // Update the counters if the builder is valid.
2548 if (SB->isValid()) {
2549 ++ValidBuilders;
2550 if (SB->canUseBundlerUnbundler())
2551 ++ValidBuildersSupportingBundling;
2552 }
2553 }
2554 CanUseBundler =
2555 ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling;
Artem Belevichf981e30b2016-08-02 22:37:47 +00002556 }
Justin Lebardc3c5042016-04-19 02:27:07 +00002557
Samuel Antao64e965e2016-09-30 15:34:19 +00002558 ~OffloadingActionBuilder() {
2559 for (auto *SB : SpecializedBuilders)
2560 delete SB;
Samuel Antaod06239d2016-07-15 23:13:27 +00002561 }
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002562
Samuel Antao64e965e2016-09-30 15:34:19 +00002563 /// Generate an action that adds device dependences (if any) to a host action.
2564 /// If no device dependence actions exist, just return the host action \a
2565 /// HostAction. If an error is found or if no builder requires the host action
2566 /// to be generated, return nullptr.
2567 Action *
2568 addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg,
2569 phases::ID CurPhase, phases::ID FinalPhase,
2570 DeviceActionBuilder::PhasesTy &Phases) {
2571 if (!IsValid)
2572 return nullptr;
Justin Lebar7bf77982016-01-11 23:27:13 +00002573
Samuel Antao64e965e2016-09-30 15:34:19 +00002574 if (SpecializedBuilders.empty())
2575 return HostAction;
2576
2577 assert(HostAction && "Invalid host action!");
2578
2579 OffloadAction::DeviceDependences DDeps;
2580 // Check if all the programming models agree we should not emit the host
2581 // action. Also, keep track of the offloading kinds employed.
2582 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2583 unsigned InactiveBuilders = 0u;
2584 unsigned IgnoringBuilders = 0u;
2585 for (auto *SB : SpecializedBuilders) {
2586 if (!SB->isValid()) {
2587 ++InactiveBuilders;
2588 continue;
2589 }
2590
Samuel Antao28c4f182016-10-27 17:08:03 +00002591 auto RetCode =
2592 SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases);
Samuel Antao64e965e2016-09-30 15:34:19 +00002593
2594 // If the builder explicitly says the host action should be ignored,
2595 // we need to increment the variable that tracks the builders that request
2596 // the host object to be ignored.
2597 if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host)
2598 ++IgnoringBuilders;
2599
2600 // Unless the builder was inactive for this action, we have to record the
2601 // offload kind because the host will have to use it.
2602 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2603 OffloadKind |= SB->getAssociatedOffloadKind();
2604 }
2605
2606 // If all builders agree that the host object should be ignored, just return
2607 // nullptr.
2608 if (IgnoringBuilders &&
2609 SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders))
2610 return nullptr;
2611
2612 if (DDeps.getActions().empty())
2613 return HostAction;
2614
2615 // We have dependences we need to bundle together. We use an offload action
2616 // for that.
2617 OffloadAction::HostDependence HDep(
2618 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2619 /*BoundArch=*/nullptr, DDeps);
2620 return C.MakeAction<OffloadAction>(HDep, DDeps);
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002621 }
2622
Samuel Antao64e965e2016-09-30 15:34:19 +00002623 /// Generate an action that adds a host dependence to a device action. The
2624 /// results will be kept in this action builder. Return true if an error was
2625 /// found.
Samuel Antaofab4f372016-10-27 18:00:51 +00002626 bool addHostDependenceToDeviceActions(Action *&HostAction,
Samuel Antao64e965e2016-09-30 15:34:19 +00002627 const Arg *InputArg) {
2628 if (!IsValid)
2629 return true;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002630
Samuel Antaofab4f372016-10-27 18:00:51 +00002631 // If we are supporting bundling/unbundling and the current action is an
2632 // input action of non-source file, we replace the host action by the
2633 // unbundling action. The bundler tool has the logic to detect if an input
2634 // is a bundle or not and if the input is not a bundle it assumes it is a
2635 // host file. Therefore it is safe to create an unbundling action even if
2636 // the input is not a bundle.
2637 if (CanUseBundler && isa<InputAction>(HostAction) &&
2638 InputArg->getOption().getKind() == llvm::opt::Option::InputClass &&
2639 !types::isSrcFile(HostAction->getType())) {
2640 auto UnbundlingHostAction =
2641 C.MakeAction<OffloadUnbundlingJobAction>(HostAction);
2642 UnbundlingHostAction->registerDependentActionInfo(
2643 C.getSingleOffloadToolChain<Action::OFK_Host>(),
2644 /*BoundArch=*/StringRef(), Action::OFK_Host);
2645 HostAction = UnbundlingHostAction;
2646 }
2647
Samuel Antao64e965e2016-09-30 15:34:19 +00002648 assert(HostAction && "Invalid host action!");
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002649
Samuel Antao64e965e2016-09-30 15:34:19 +00002650 // Register the offload kinds that are used.
2651 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2652 for (auto *SB : SpecializedBuilders) {
2653 if (!SB->isValid())
2654 continue;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002655
Samuel Antao64e965e2016-09-30 15:34:19 +00002656 auto RetCode = SB->addDeviceDepences(HostAction);
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002657
Samuel Antao64e965e2016-09-30 15:34:19 +00002658 // Host dependences for device actions are not compatible with that same
2659 // action being ignored.
2660 assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host &&
2661 "Host dependence not expected to be ignored.!");
Samuel Antaod06239d2016-07-15 23:13:27 +00002662
Samuel Antao64e965e2016-09-30 15:34:19 +00002663 // Unless the builder was inactive for this action, we have to record the
2664 // offload kind because the host will have to use it.
2665 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2666 OffloadKind |= SB->getAssociatedOffloadKind();
2667 }
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002668
Samuel Antao64e965e2016-09-30 15:34:19 +00002669 return false;
2670 }
2671
Samuel Antao69d6f312016-10-27 17:50:43 +00002672 /// Add the offloading top level actions to the provided action list. This
2673 /// function can replace the host action by a bundling action if the
2674 /// programming models allow it.
Samuel Antao64e965e2016-09-30 15:34:19 +00002675 bool appendTopLevelActions(ActionList &AL, Action *HostAction,
2676 const Arg *InputArg) {
Samuel Antao69d6f312016-10-27 17:50:43 +00002677 // Get the device actions to be appended.
2678 ActionList OffloadAL;
Samuel Antao64e965e2016-09-30 15:34:19 +00002679 for (auto *SB : SpecializedBuilders) {
2680 if (!SB->isValid())
2681 continue;
Samuel Antao69d6f312016-10-27 17:50:43 +00002682 SB->appendTopLevelActions(OffloadAL);
Samuel Antao64e965e2016-09-30 15:34:19 +00002683 }
2684
Samuel Antao69d6f312016-10-27 17:50:43 +00002685 // If we can use the bundler, replace the host action by the bundling one in
2686 // the resulting list. Otherwise, just append the device actions.
2687 if (CanUseBundler && !OffloadAL.empty()) {
2688 // Add the host action to the list in order to create the bundling action.
2689 OffloadAL.push_back(HostAction);
2690
2691 // We expect that the host action was just appended to the action list
2692 // before this method was called.
2693 assert(HostAction == AL.back() && "Host action not in the list??");
2694 HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL);
2695 AL.back() = HostAction;
2696 } else
2697 AL.append(OffloadAL.begin(), OffloadAL.end());
2698
Samuel Antao64e965e2016-09-30 15:34:19 +00002699 // Propagate to the current host action (if any) the offload information
2700 // associated with the current input.
2701 if (HostAction)
2702 HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg],
2703 /*BoundArch=*/nullptr);
Samuel Antao64e965e2016-09-30 15:34:19 +00002704 return false;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002705 }
Artem Belevich5bde4e02015-07-20 20:02:54 +00002706
Samuel Antao64e965e2016-09-30 15:34:19 +00002707 /// Processes the host linker action. This currently consists of replacing it
2708 /// with an offload action if there are device link objects and propagate to
2709 /// the host action all the offload kinds used in the current compilation. The
2710 /// resulting action is returned.
2711 Action *processHostLinkAction(Action *HostAction) {
2712 // Add all the dependences from the device linking actions.
2713 OffloadAction::DeviceDependences DDeps;
2714 for (auto *SB : SpecializedBuilders) {
2715 if (!SB->isValid())
2716 continue;
Justin Lebar21e5d4f2016-01-14 21:41:27 +00002717
Samuel Antao64e965e2016-09-30 15:34:19 +00002718 SB->appendLinkDependences(DDeps);
Justin Lebar21e5d4f2016-01-14 21:41:27 +00002719 }
Samuel Antaod06239d2016-07-15 23:13:27 +00002720
Samuel Antao64e965e2016-09-30 15:34:19 +00002721 // Calculate all the offload kinds used in the current compilation.
2722 unsigned ActiveOffloadKinds = 0u;
2723 for (auto &I : InputArgToOffloadKindMap)
2724 ActiveOffloadKinds |= I.second;
2725
2726 // If we don't have device dependencies, we don't have to create an offload
2727 // action.
2728 if (DDeps.getActions().empty()) {
2729 // Propagate all the active kinds to host action. Given that it is a link
2730 // action it is assumed to depend on all actions generated so far.
2731 HostAction->propagateHostOffloadInfo(ActiveOffloadKinds,
2732 /*BoundArch=*/nullptr);
2733 return HostAction;
2734 }
2735
2736 // Create the offload action with all dependences. When an offload action
2737 // is created the kinds are propagated to the host action, so we don't have
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002738 // to do that explicitly here.
Samuel Antao64e965e2016-09-30 15:34:19 +00002739 OffloadAction::HostDependence HDep(
2740 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2741 /*BoundArch*/ nullptr, ActiveOffloadKinds);
2742 return C.MakeAction<OffloadAction>(HDep, DDeps);
2743 }
2744};
2745} // anonymous namespace.
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002746
Justin Lebar0f3474c2016-02-11 02:00:50 +00002747void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
2748 const InputList &Inputs, ActionList &Actions) const {
Chad Rosierecdede82011-08-12 22:08:57 +00002749 llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00002750
Daniel Dunbar34c41872009-03-13 00:17:48 +00002751 if (!SuppressMissingInputWarning && Inputs.empty()) {
Daniel Dunbarbfeec742009-03-12 23:55:14 +00002752 Diag(clang::diag::err_drv_no_input_files);
2753 return;
2754 }
2755
Chad Rosier7742b5d2011-07-27 23:36:45 +00002756 Arg *FinalPhaseArg;
2757 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
Daniel Dunbarbfeec742009-03-12 23:55:14 +00002758
Bob Haarmanaaf51912017-02-27 19:40:19 +00002759 if (FinalPhase == phases::Link) {
2760 if (Args.hasArg(options::OPT_emit_llvm))
2761 Diag(clang::diag::err_drv_emit_llvm_link);
2762 if (IsCLMode() && LTOMode != LTOK_None &&
2763 !Args.getLastArgValue(options::OPT_fuse_ld_EQ).equals_lower("lld"))
2764 Diag(clang::diag::err_drv_lto_without_lld);
Rafael Espindolae8025642013-08-25 14:27:09 +00002765 }
2766
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002767 // Reject -Z* at the top level, these options should never have been exposed
2768 // by gcc.
Daniel Dunbardd765242009-03-26 16:12:09 +00002769 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
Daniel Dunbar0e759942009-03-20 06:14:23 +00002770 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
Daniel Dunbarbfeec742009-03-12 23:55:14 +00002771
Hans Wennborg13b7fe72013-08-12 23:26:25 +00002772 // Diagnose misuse of /Fo.
2773 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
Hans Wennborg13b7fe72013-08-12 23:26:25 +00002774 StringRef V = A->getValue();
Hans Wennborg61647532014-11-17 19:16:36 +00002775 if (Inputs.size() > 1 && !V.empty() &&
2776 !llvm::sys::path::is_separator(V.back())) {
Hans Wennborg13b7fe72013-08-12 23:26:25 +00002777 // Check whether /Fo tries to name an output file for multiple inputs.
Hans Wennborg9c1659b2013-10-18 22:49:04 +00002778 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002779 << A->getSpelling() << V;
Hans Wennborg13b7fe72013-08-12 23:26:25 +00002780 Args.eraseArg(options::OPT__SLASH_Fo);
2781 }
2782 }
2783
Hans Wennborg9c1659b2013-10-18 22:49:04 +00002784 // Diagnose misuse of /Fa.
2785 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
2786 StringRef V = A->getValue();
Hans Wennborg61647532014-11-17 19:16:36 +00002787 if (Inputs.size() > 1 && !V.empty() &&
2788 !llvm::sys::path::is_separator(V.back())) {
Hans Wennborg9c1659b2013-10-18 22:49:04 +00002789 // Check whether /Fa tries to name an asm file for multiple inputs.
2790 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002791 << A->getSpelling() << V;
Hans Wennborg9c1659b2013-10-18 22:49:04 +00002792 Args.eraseArg(options::OPT__SLASH_Fa);
2793 }
2794 }
2795
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00002796 // Diagnose misuse of /o.
2797 if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
2798 if (A->getValue()[0] == '\0') {
2799 // It has to have a value.
2800 Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
2801 Args.eraseArg(options::OPT__SLASH_o);
2802 }
2803 }
2804
Nico Weber2ca4be92016-03-01 23:16:44 +00002805 // Diagnose unsupported forms of /Yc /Yu. Ignore /Yc/Yu for now if:
2806 // * no filename after it
2807 // * both /Yc and /Yu passed but with different filenames
2808 // * corresponding file not also passed as /FI
2809 Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
2810 Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
2811 if (YcArg && YcArg->getValue()[0] == '\0') {
2812 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YcArg->getSpelling();
2813 Args.eraseArg(options::OPT__SLASH_Yc);
2814 YcArg = nullptr;
2815 }
2816 if (YuArg && YuArg->getValue()[0] == '\0') {
2817 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YuArg->getSpelling();
2818 Args.eraseArg(options::OPT__SLASH_Yu);
2819 YuArg = nullptr;
2820 }
2821 if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
2822 Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
2823 Args.eraseArg(options::OPT__SLASH_Yc);
2824 Args.eraseArg(options::OPT__SLASH_Yu);
2825 YcArg = YuArg = nullptr;
2826 }
2827 if (YcArg || YuArg) {
2828 StringRef Val = YcArg ? YcArg->getValue() : YuArg->getValue();
2829 bool FoundMatchingInclude = false;
2830 for (const Arg *Inc : Args.filtered(options::OPT_include)) {
2831 // FIXME: Do case-insensitive matching and consider / and \ as equal.
2832 if (Inc->getValue() == Val)
2833 FoundMatchingInclude = true;
2834 }
2835 if (!FoundMatchingInclude) {
2836 Diag(clang::diag::warn_drv_ycyu_no_fi_arg_clang_cl)
2837 << (YcArg ? YcArg : YuArg)->getSpelling();
2838 Args.eraseArg(options::OPT__SLASH_Yc);
2839 Args.eraseArg(options::OPT__SLASH_Yu);
2840 YcArg = YuArg = nullptr;
2841 }
2842 }
2843 if (YcArg && Inputs.size() > 1) {
2844 Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
2845 Args.eraseArg(options::OPT__SLASH_Yc);
2846 YcArg = nullptr;
2847 }
2848 if (Args.hasArg(options::OPT__SLASH_Y_)) {
2849 // /Y- disables all pch handling. Rather than check for it everywhere,
2850 // just remove clang-cl pch-related flags here.
2851 Args.eraseArg(options::OPT__SLASH_Fp);
2852 Args.eraseArg(options::OPT__SLASH_Yc);
2853 Args.eraseArg(options::OPT__SLASH_Yu);
2854 YcArg = YuArg = nullptr;
2855 }
Nico Weber2ca4be92016-03-01 23:16:44 +00002856
Samuel Antao64e965e2016-09-30 15:34:19 +00002857 // Builder to be used to build offloading actions.
2858 OffloadingActionBuilder OffloadBuilder(C, Args, Inputs);
Samuel Antaod06239d2016-07-15 23:13:27 +00002859
Daniel Dunbar65229332009-03-13 11:38:42 +00002860 // Construct the actions to perform.
2861 ActionList LinkerInputs;
Alp Toker965f8822013-11-27 05:22:15 +00002862
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002863 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL;
Artem Belevich5bde4e02015-07-20 20:02:54 +00002864 for (auto &I : Inputs) {
2865 types::ID InputType = I.first;
2866 const Arg *InputArg = I.second;
Daniel Dunbar65229332009-03-13 11:38:42 +00002867
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002868 PL.clear();
2869 types::getCompilationPhases(InputType, PL);
Daniel Dunbar65229332009-03-13 11:38:42 +00002870
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002871 // If the first step comes after the final phase we are doing as part of
2872 // this compilation, warn the user about it.
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002873 phases::ID InitialPhase = PL[0];
Daniel Dunbar65229332009-03-13 11:38:42 +00002874 if (InitialPhase > FinalPhase) {
Daniel Dunbaradc5c7c2009-03-19 07:57:08 +00002875 // Claim here to avoid the more general unused warning.
2876 InputArg->claim();
Daniel Dunbar07806ca2009-09-17 04:13:26 +00002877
Daniel Dunbar2db3e732011-04-20 15:44:48 +00002878 // Suppress all unused style warnings with -Qunused-arguments
2879 if (Args.hasArg(options::OPT_Qunused_arguments))
2880 continue;
2881
Richard Smith403f76e2012-08-06 04:09:06 +00002882 // Special case when final phase determined by binary name, rather than
2883 // by a command-line argument with a corresponding Arg.
Hans Wennborg70850d82013-07-18 20:29:38 +00002884 if (CCCIsCPP())
Richard Smith403f76e2012-08-06 04:09:06 +00002885 Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002886 << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
Daniel Dunbar07806ca2009-09-17 04:13:26 +00002887 // Special case '-E' warning on a previously preprocessed file to make
2888 // more sense.
Richard Smith403f76e2012-08-06 04:09:06 +00002889 else if (InitialPhase == phases::Compile &&
2890 FinalPhase == phases::Preprocess &&
2891 getPreprocessedType(InputType) == types::TY_INVALID)
Daniel Dunbar07806ca2009-09-17 04:13:26 +00002892 Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002893 << InputArg->getAsString(Args) << !!FinalPhaseArg
2894 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
Daniel Dunbar07806ca2009-09-17 04:13:26 +00002895 else
2896 Diag(clang::diag::warn_drv_input_file_unused)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002897 << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
2898 << !!FinalPhaseArg
2899 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
Daniel Dunbar65229332009-03-13 11:38:42 +00002900 continue;
2901 }
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002902
Nico Weberad2d8f32016-04-21 19:59:10 +00002903 if (YcArg) {
2904 // Add a separate precompile phase for the compile phase.
2905 if (FinalPhase >= phases::Compile) {
Richard Smith8cd452d2016-08-30 18:55:16 +00002906 const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType);
Nico Weberad2d8f32016-04-21 19:59:10 +00002907 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PCHPL;
Richard Smith8cd452d2016-08-30 18:55:16 +00002908 types::getCompilationPhases(HeaderType, PCHPL);
David Blaikie0aaa7622017-01-13 17:34:15 +00002909 Arg *PchInputArg = MakeInputArg(Args, *Opts, YcArg->getValue());
Nico Weberad2d8f32016-04-21 19:59:10 +00002910
2911 // Build the pipeline for the pch file.
Richard Smith8cd452d2016-08-30 18:55:16 +00002912 Action *ClangClPch =
2913 C.MakeAction<InputAction>(*PchInputArg, HeaderType);
Nico Weberad2d8f32016-04-21 19:59:10 +00002914 for (phases::ID Phase : PCHPL)
2915 ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
2916 assert(ClangClPch);
2917 Actions.push_back(ClangClPch);
2918 // The driver currently exits after the first failed command. This
2919 // relies on that behavior, to make sure if the pch generation fails,
2920 // the main compilation won't run.
2921 }
2922 }
2923
Daniel Dunbar65229332009-03-13 11:38:42 +00002924 // Build the pipeline for this file.
Justin Lebar41094612016-01-11 23:07:27 +00002925 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
Samuel Antao64e965e2016-09-30 15:34:19 +00002926
2927 // Use the current host action in any of the offloading actions, if
2928 // required.
2929 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
2930 break;
2931
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002932 for (SmallVectorImpl<phases::ID>::iterator i = PL.begin(), e = PL.end();
2933 i != e; ++i) {
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002934 phases::ID Phase = *i;
Daniel Dunbar65229332009-03-13 11:38:42 +00002935
2936 // We are done if this step is past what the user requested.
2937 if (Phase > FinalPhase)
2938 break;
2939
Samuel Antao64e965e2016-09-30 15:34:19 +00002940 // Add any offload action the host action depends on.
2941 Current = OffloadBuilder.addDeviceDependencesToHostAction(
2942 Current, InputArg, Phase, FinalPhase, PL);
2943 if (!Current)
2944 break;
2945
Daniel Dunbar65229332009-03-13 11:38:42 +00002946 // Queue linker inputs.
2947 if (Phase == phases::Link) {
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002948 assert((i + 1) == e && "linking must be final compilation step.");
Justin Lebar41094612016-01-11 23:07:27 +00002949 LinkerInputs.push_back(Current);
2950 Current = nullptr;
Daniel Dunbar65229332009-03-13 11:38:42 +00002951 break;
2952 }
2953
Samuel Antao64e965e2016-09-30 15:34:19 +00002954 // Otherwise construct the appropriate action.
2955 auto *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current);
2956
2957 // We didn't create a new action, so we will just move to the next phase.
2958 if (NewCurrent == Current)
Daniel Dunbar13864952009-03-24 20:17:30 +00002959 continue;
2960
Samuel Antao64e965e2016-09-30 15:34:19 +00002961 Current = NewCurrent;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002962
Samuel Antao64e965e2016-09-30 15:34:19 +00002963 // Use the current host action in any of the offloading actions, if
2964 // required.
2965 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
2966 break;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002967
Daniel Dunbar65229332009-03-13 11:38:42 +00002968 if (Current->getType() == types::TY_Nothing)
2969 break;
2970 }
2971
Samuel Antao64e965e2016-09-30 15:34:19 +00002972 // If we ended with something, add to the output list.
2973 if (Current)
Justin Lebar41094612016-01-11 23:07:27 +00002974 Actions.push_back(Current);
Samuel Antao64e965e2016-09-30 15:34:19 +00002975
2976 // Add any top level actions generated for offloading.
2977 OffloadBuilder.appendTopLevelActions(Actions, Current, InputArg);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002978 }
Daniel Dunbar65229332009-03-13 11:38:42 +00002979
Samuel Antao64e965e2016-09-30 15:34:19 +00002980 // Add a link action if necessary.
Samuel Antaod06239d2016-07-15 23:13:27 +00002981 if (!LinkerInputs.empty()) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002982 Action *LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image);
2983 LA = OffloadBuilder.processHostLinkAction(LA);
2984 Actions.push_back(LA);
Samuel Antaod06239d2016-07-15 23:13:27 +00002985 }
Daniel Dunbarc7a67b72009-12-22 23:19:32 +00002986
2987 // If we are linking, claim any options which are obviously only used for
2988 // compilation.
Hans Wennborga8ef14f2013-09-17 00:03:41 +00002989 if (FinalPhase == phases::Link && PL.size() == 1) {
Daniel Dunbarc7a67b72009-12-22 23:19:32 +00002990 Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
Hans Wennborga8ef14f2013-09-17 00:03:41 +00002991 Args.ClaimAllArgs(options::OPT_cl_compile_Group);
2992 }
2993
2994 // Claim ignored clang-cl options.
2995 Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
Artem Belevichbaae0932015-07-28 21:01:30 +00002996
Justin Lebardc3c5042016-04-19 02:27:07 +00002997 // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed
2998 // to non-CUDA compilations and should not trigger warnings there.
Artem Belevichbaae0932015-07-28 21:01:30 +00002999 Args.ClaimAllArgs(options::OPT_cuda_host_only);
Justin Lebardc3c5042016-04-19 02:27:07 +00003000 Args.ClaimAllArgs(options::OPT_cuda_compile_host_device);
Daniel Dunbar65229332009-03-13 11:38:42 +00003001}
3002
Justin Lebar0f3474c2016-02-11 02:00:50 +00003003Action *Driver::ConstructPhaseAction(Compilation &C, const ArgList &Args,
3004 phases::ID Phase, Action *Input) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00003005 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
Samuel Antao64e965e2016-09-30 15:34:19 +00003006
3007 // Some types skip the assembler phase (e.g., llvm-bc), but we can't
3008 // encode this in the steps because the intermediate type depends on
3009 // arguments. Just special case here.
3010 if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm)
3011 return Input;
3012
Daniel Dunbar65229332009-03-13 11:38:42 +00003013 // Build the appropriate action.
3014 switch (Phase) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003015 case phases::Link:
3016 llvm_unreachable("link action invalid here.");
Daniel Dunbar65229332009-03-13 11:38:42 +00003017 case phases::Preprocess: {
Daniel Dunbard67a3222009-03-30 06:36:42 +00003018 types::ID OutputTy;
3019 // -{M, MM} alter the output type.
Daniel Dunbar86aed7d2010-12-08 21:33:40 +00003020 if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
Daniel Dunbard67a3222009-03-30 06:36:42 +00003021 OutputTy = types::TY_Dependencies;
3022 } else {
David Blaikie5d577a22012-06-29 22:03:56 +00003023 OutputTy = Input->getType();
3024 if (!Args.hasFlag(options::OPT_frewrite_includes,
Justin Bognerce8245b2014-06-24 08:01:01 +00003025 options::OPT_fno_rewrite_includes, false) &&
Richard Smith86a3ef52017-06-09 21:24:02 +00003026 !Args.hasFlag(options::OPT_frewrite_imports,
3027 options::OPT_fno_rewrite_imports, false) &&
Justin Bognerce8245b2014-06-24 08:01:01 +00003028 !CCGenDiagnostics)
David Blaikie5d577a22012-06-29 22:03:56 +00003029 OutputTy = types::getPreprocessedType(OutputTy);
Daniel Dunbard67a3222009-03-30 06:36:42 +00003030 assert(OutputTy != types::TY_INVALID &&
3031 "Cannot preprocess this input type!");
3032 }
Justin Lebar41094612016-01-11 23:07:27 +00003033 return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
Daniel Dunbar65229332009-03-13 11:38:42 +00003034 }
Aaron Ballman1f10cc52012-07-31 01:21:00 +00003035 case phases::Precompile: {
Richard Smithdd4ad3d2016-08-30 19:06:26 +00003036 types::ID OutputTy = getPrecompiledType(Input->getType());
3037 assert(OutputTy != types::TY_INVALID &&
3038 "Cannot precompile this input type!");
Aaron Ballman1f10cc52012-07-31 01:21:00 +00003039 if (Args.hasArg(options::OPT_fsyntax_only)) {
3040 // Syntax checks should not emit a PCH file
3041 OutputTy = types::TY_Nothing;
3042 }
Justin Lebar41094612016-01-11 23:07:27 +00003043 return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
Aaron Ballman1f10cc52012-07-31 01:21:00 +00003044 }
Daniel Dunbar65229332009-03-13 11:38:42 +00003045 case phases::Compile: {
David Blaikie486f4402014-08-29 07:25:23 +00003046 if (Args.hasArg(options::OPT_fsyntax_only))
Justin Lebar41094612016-01-11 23:07:27 +00003047 return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
David Blaikie486f4402014-08-29 07:25:23 +00003048 if (Args.hasArg(options::OPT_rewrite_objc))
Justin Lebar41094612016-01-11 23:07:27 +00003049 return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
David Blaikie486f4402014-08-29 07:25:23 +00003050 if (Args.hasArg(options::OPT_rewrite_legacy_objc))
Justin Lebar41094612016-01-11 23:07:27 +00003051 return C.MakeAction<CompileJobAction>(Input,
3052 types::TY_RewrittenLegacyObjC);
David Blaikie486f4402014-08-29 07:25:23 +00003053 if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto))
Justin Lebar41094612016-01-11 23:07:27 +00003054 return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
David Blaikie486f4402014-08-29 07:25:23 +00003055 if (Args.hasArg(options::OPT__migrate))
Justin Lebar41094612016-01-11 23:07:27 +00003056 return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
David Blaikie486f4402014-08-29 07:25:23 +00003057 if (Args.hasArg(options::OPT_emit_ast))
Justin Lebar41094612016-01-11 23:07:27 +00003058 return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
David Blaikie486f4402014-08-29 07:25:23 +00003059 if (Args.hasArg(options::OPT_module_file_info))
Justin Lebar41094612016-01-11 23:07:27 +00003060 return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
David Blaikie486f4402014-08-29 07:25:23 +00003061 if (Args.hasArg(options::OPT_verify_pch))
Justin Lebar41094612016-01-11 23:07:27 +00003062 return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
3063 return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
Bob Wilson23a55f12014-12-21 07:00:00 +00003064 }
3065 case phases::Backend: {
Teresa Johnson945bc502015-10-15 20:35:53 +00003066 if (isUsingLTO()) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003067 types::ID Output =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003068 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
Justin Lebar41094612016-01-11 23:07:27 +00003069 return C.MakeAction<BackendJobAction>(Input, Output);
David Blaikie486f4402014-08-29 07:25:23 +00003070 }
3071 if (Args.hasArg(options::OPT_emit_llvm)) {
Shuxin Yang4b3c7ff2013-08-23 21:34:57 +00003072 types::ID Output =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003073 Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
Justin Lebar41094612016-01-11 23:07:27 +00003074 return C.MakeAction<BackendJobAction>(Input, Output);
Daniel Dunbar65229332009-03-13 11:38:42 +00003075 }
Justin Lebar41094612016-01-11 23:07:27 +00003076 return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
Daniel Dunbar65229332009-03-13 11:38:42 +00003077 }
3078 case phases::Assemble:
Justin Lebar21e5d4f2016-01-14 21:41:27 +00003079 return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
Daniel Dunbar65229332009-03-13 11:38:42 +00003080 }
3081
David Blaikie83d382b2011-09-23 05:06:16 +00003082 llvm_unreachable("invalid phase in ConstructPhaseAction");
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00003083}
3084
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00003085void Driver::BuildJobs(Compilation &C) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00003086 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
Daniel Dunbare75d8342009-03-16 06:56:51 +00003087
3088 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
3089
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003090 // It is an error to provide a -o option if we are making multiple output
3091 // files.
Daniel Dunbare75d8342009-03-16 06:56:51 +00003092 if (FinalOutput) {
3093 unsigned NumOutputs = 0;
Saleem Abdulrasoolda3f4e52014-12-29 21:02:47 +00003094 for (const Action *A : C.getActions())
3095 if (A->getType() != types::TY_Nothing)
Daniel Dunbare75d8342009-03-16 06:56:51 +00003096 ++NumOutputs;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003097
Daniel Dunbare75d8342009-03-16 06:56:51 +00003098 if (NumOutputs > 1) {
3099 Diag(clang::diag::err_drv_output_argument_with_multiple_files);
Craig Topper92fc2df2014-05-17 16:56:41 +00003100 FinalOutput = nullptr;
Daniel Dunbare75d8342009-03-16 06:56:51 +00003101 }
3102 }
3103
Chad Rosier35767232013-04-30 22:01:21 +00003104 // Collect the list of architectures.
3105 llvm::StringSet<> ArchNames;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00003106 if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO())
3107 for (const Arg *A : C.getArgs())
Chad Rosier35767232013-04-30 22:01:21 +00003108 if (A->getOption().matches(options::OPT_arch))
3109 ArchNames.insert(A->getValue());
Chad Rosier35767232013-04-30 22:01:21 +00003110
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003111 // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
3112 std::map<std::pair<const Action *, std::string>, InputInfo> CachedResults;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00003113 for (Action *A : C.getActions()) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003114 // If we are linking an image for multiple archs then the linker wants
3115 // -arch_multiple and -final_output <final image name>. Unfortunately, this
3116 // doesn't fit in cleanly because we have to pass this information down.
Daniel Dunbare75d8342009-03-16 06:56:51 +00003117 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003118 // FIXME: This is a hack; find a cleaner way to integrate this into the
3119 // process.
Craig Topper92fc2df2014-05-17 16:56:41 +00003120 const char *LinkingOutput = nullptr;
Daniel Dunbardd765242009-03-26 16:12:09 +00003121 if (isa<LipoJobAction>(A)) {
Daniel Dunbare75d8342009-03-16 06:56:51 +00003122 if (FinalOutput)
Richard Smithbd55daf2012-11-01 04:30:05 +00003123 LinkingOutput = FinalOutput->getValue();
Daniel Dunbare75d8342009-03-16 06:56:51 +00003124 else
Hans Wennborga7707222015-01-09 17:38:53 +00003125 LinkingOutput = getDefaultImageName();
Daniel Dunbare75d8342009-03-16 06:56:51 +00003126 }
3127
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003128 BuildJobsForAction(C, A, &C.getDefaultToolChain(),
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003129 /*BoundArch*/ StringRef(),
Daniel Dunbare75d8342009-03-16 06:56:51 +00003130 /*AtTopLevel*/ true,
Chad Rosier35767232013-04-30 22:01:21 +00003131 /*MultipleArchs*/ ArchNames.size() > 1,
Samuel Antaod06239d2016-07-15 23:13:27 +00003132 /*LinkingOutput*/ LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003133 /*TargetDeviceOffloadKind*/ Action::OFK_None);
Daniel Dunbare75d8342009-03-16 06:56:51 +00003134 }
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00003135
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003136 // If the user passed -Qunused-arguments or there were errors, don't warn
3137 // about any unused arguments.
Argyrios Kyrtzidis31448a42010-11-18 21:47:07 +00003138 if (Diags.hasErrorOccurred() ||
Daniel Dunbara3cfbe32009-04-07 19:04:18 +00003139 C.getArgs().hasArg(options::OPT_Qunused_arguments))
Daniel Dunbard175d972009-03-18 18:03:46 +00003140 return;
3141
Daniel Dunbar58399ae2009-03-29 22:24:54 +00003142 // Claim -### here.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003143 (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003144
Nico Weber47bf5052016-04-25 21:15:49 +00003145 // Claim --driver-mode, --rsp-quoting, it was handled earlier.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003146 (void)C.getArgs().hasArg(options::OPT_driver_mode);
Nico Weber47bf5052016-04-25 21:15:49 +00003147 (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
Hans Wennborg70850d82013-07-18 20:29:38 +00003148
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00003149 for (Arg *A : C.getArgs()) {
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00003150 // FIXME: It would be nice to be able to send the argument to the
David Blaikie9c902b52011-09-25 23:23:43 +00003151 // DiagnosticsEngine, so that extra values, position, and so on could be
3152 // printed.
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003153 if (!A->isClaimed()) {
Michael J. Spencer66e2b202012-10-19 22:37:06 +00003154 if (A->getOption().hasFlag(options::NoArgumentUnused))
Daniel Dunbara3cfbe32009-04-07 19:04:18 +00003155 continue;
3156
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003157 // Suppress the warning automatically if this is just a flag, and it is an
3158 // instance of an argument we already claimed.
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003159 const Option &Opt = A->getOption();
Michael J. Spencerad3ccc32012-08-20 21:41:17 +00003160 if (Opt.getKind() == Option::FlagClass) {
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003161 bool DuplicateClaimed = false;
3162
Sean Silva14facf32015-06-09 01:57:17 +00003163 for (const Arg *AA : C.getArgs().filtered(&Opt)) {
3164 if (AA->isClaimed()) {
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003165 DuplicateClaimed = true;
3166 break;
3167 }
3168 }
3169
3170 if (DuplicateClaimed)
3171 continue;
3172 }
3173
Ehsan Akhgarid8518332016-01-25 21:14:52 +00003174 // In clang-cl, don't mention unknown arguments here since they have
3175 // already been warned about.
3176 if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN))
3177 Diag(clang::diag::warn_drv_unused_argument)
3178 << A->getAsString(C.getArgs());
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003179 }
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00003180 }
Daniel Dunbar95e6b192009-03-13 22:12:33 +00003181}
Daniel Dunbarc4343942010-02-03 03:07:56 +00003182
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003183namespace {
3184/// Utility class to control the collapse of dependent actions and select the
3185/// tools accordingly.
3186class ToolSelector final {
3187 /// The tool chain this selector refers to.
3188 const ToolChain &TC;
Daniel Dunbarf9ff3502010-05-14 02:03:00 +00003189
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003190 /// The compilation this selector refers to.
3191 const Compilation &C;
Samuel Antaod06239d2016-07-15 23:13:27 +00003192
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003193 /// The base action this selector refers to.
3194 const JobAction *BaseAction;
Samuel Antaod06239d2016-07-15 23:13:27 +00003195
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003196 /// Set to true if the current toolchain refers to host actions.
3197 bool IsHostSelector;
Samuel Antaod06239d2016-07-15 23:13:27 +00003198
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003199 /// Set to true if save-temps and embed-bitcode functionalities are active.
3200 bool SaveTemps;
3201 bool EmbedBitcode;
3202
3203 /// Get previous dependent action or null if that does not exist. If
3204 /// \a CanBeCollapsed is false, that action must be legal to collapse or
3205 /// null will be returned.
3206 const JobAction *getPrevDependentAction(const ActionList &Inputs,
3207 ActionList &SavedOffloadAction,
3208 bool CanBeCollapsed = true) {
3209 // An option can be collapsed only if it has a single input.
3210 if (Inputs.size() != 1)
Craig Topper92fc2df2014-05-17 16:56:41 +00003211 return nullptr;
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003212
3213 Action *CurAction = *Inputs.begin();
3214 if (CanBeCollapsed &&
3215 !CurAction->isCollapsingWithNextDependentActionLegal())
3216 return nullptr;
3217
3218 // If the input action is an offload action. Look through it and save any
3219 // offload action that can be dropped in the event of a collapse.
3220 if (auto *OA = dyn_cast<OffloadAction>(CurAction)) {
3221 // If the dependent action is a device action, we will attempt to collapse
3222 // only with other device actions. Otherwise, we would do the same but
3223 // with host actions only.
3224 if (!IsHostSelector) {
3225 if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) {
3226 CurAction =
3227 OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
3228 if (CanBeCollapsed &&
3229 !CurAction->isCollapsingWithNextDependentActionLegal())
3230 return nullptr;
3231 SavedOffloadAction.push_back(OA);
3232 return dyn_cast<JobAction>(CurAction);
3233 }
3234 } else if (OA->hasHostDependence()) {
3235 CurAction = OA->getHostDependence();
3236 if (CanBeCollapsed &&
3237 !CurAction->isCollapsingWithNextDependentActionLegal())
3238 return nullptr;
3239 SavedOffloadAction.push_back(OA);
3240 return dyn_cast<JobAction>(CurAction);
3241 }
3242 return nullptr;
3243 }
3244
3245 return dyn_cast<JobAction>(CurAction);
3246 }
3247
3248 /// Return true if an assemble action can be collapsed.
3249 bool canCollapseAssembleAction() const {
3250 return TC.useIntegratedAs() && !SaveTemps &&
3251 !C.getArgs().hasArg(options::OPT_via_file_asm) &&
3252 !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
3253 !C.getArgs().hasArg(options::OPT__SLASH_Fa);
3254 }
3255
3256 /// Return true if a preprocessor action can be collapsed.
3257 bool canCollapsePreprocessorAction() const {
3258 return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
3259 !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
3260 !C.getArgs().hasArg(options::OPT_rewrite_objc);
3261 }
3262
3263 /// Struct that relates an action with the offload actions that would be
3264 /// collapsed with it.
3265 struct JobActionInfo final {
3266 /// The action this info refers to.
3267 const JobAction *JA = nullptr;
3268 /// The offload actions we need to take care off if this action is
3269 /// collapsed.
3270 ActionList SavedOffloadAction;
3271 };
3272
3273 /// Append collapsed offload actions from the give nnumber of elements in the
3274 /// action info array.
3275 static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction,
3276 ArrayRef<JobActionInfo> &ActionInfo,
3277 unsigned ElementNum) {
3278 assert(ElementNum <= ActionInfo.size() && "Invalid number of elements.");
3279 for (unsigned I = 0; I < ElementNum; ++I)
3280 CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(),
3281 ActionInfo[I].SavedOffloadAction.end());
3282 }
3283
3284 /// Functions that attempt to perform the combining. They detect if that is
3285 /// legal, and if so they update the inputs \a Inputs and the offload action
3286 /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with
3287 /// the combined action is returned. If the combining is not legal or if the
3288 /// tool does not exist, null is returned.
3289 /// Currently three kinds of collapsing are supported:
3290 /// - Assemble + Backend + Compile;
3291 /// - Assemble + Backend ;
3292 /// - Backend + Compile.
3293 const Tool *
3294 combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
3295 const ActionList *&Inputs,
3296 ActionList &CollapsedOffloadAction) {
3297 if (ActionInfo.size() < 3 || !canCollapseAssembleAction())
3298 return nullptr;
3299 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
3300 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
3301 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA);
3302 if (!AJ || !BJ || !CJ)
3303 return nullptr;
3304
3305 // Get compiler tool.
3306 const Tool *T = TC.SelectTool(*CJ);
3307 if (!T)
3308 return nullptr;
3309
Steven Wu574b0f22016-03-01 01:07:58 +00003310 // When using -fembed-bitcode, it is required to have the same tool (clang)
3311 // for both CompilerJA and BackendJA. Otherwise, combine two stages.
3312 if (EmbedBitcode) {
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003313 const Tool *BT = TC.SelectTool(*BJ);
3314 if (BT == T)
3315 return nullptr;
Steven Wu574b0f22016-03-01 01:07:58 +00003316 }
Bob Wilson23a55f12014-12-21 07:00:00 +00003317
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003318 if (!T->hasIntegratedAssembler())
Bob Wilson23a55f12014-12-21 07:00:00 +00003319 return nullptr;
Samuel Antaod06239d2016-07-15 23:13:27 +00003320
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003321 Inputs = &CJ->getInputs();
3322 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3323 /*NumElements=*/3);
3324 return T;
3325 }
3326 const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo,
3327 const ActionList *&Inputs,
3328 ActionList &CollapsedOffloadAction) {
3329 if (ActionInfo.size() < 2 || !canCollapseAssembleAction())
3330 return nullptr;
3331 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
3332 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
3333 if (!AJ || !BJ)
3334 return nullptr;
3335
3336 // Retrieve the compile job, backend action must always be preceded by one.
3337 ActionList CompileJobOffloadActions;
3338 auto *CJ = getPrevDependentAction(BJ->getInputs(), CompileJobOffloadActions,
3339 /*CanBeCollapsed=*/false);
3340 if (!AJ || !BJ || !CJ)
3341 return nullptr;
3342
3343 assert(isa<CompileJobAction>(CJ) &&
3344 "Expecting compile job preceding backend job.");
3345
3346 // Get compiler tool.
3347 const Tool *T = TC.SelectTool(*CJ);
3348 if (!T)
3349 return nullptr;
3350
3351 if (!T->hasIntegratedAssembler())
3352 return nullptr;
3353
3354 Inputs = &BJ->getInputs();
3355 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3356 /*NumElements=*/2);
3357 return T;
3358 }
3359 const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
3360 const ActionList *&Inputs,
3361 ActionList &CollapsedOffloadAction) {
3362 if (ActionInfo.size() < 2 || !canCollapsePreprocessorAction())
3363 return nullptr;
3364 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA);
3365 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA);
3366 if (!BJ || !CJ)
3367 return nullptr;
3368
3369 // Get compiler tool.
3370 const Tool *T = TC.SelectTool(*CJ);
3371 if (!T)
3372 return nullptr;
3373
3374 if (T->canEmitIR() && (SaveTemps || EmbedBitcode))
3375 return nullptr;
3376
3377 Inputs = &CJ->getInputs();
3378 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3379 /*NumElements=*/2);
3380 return T;
3381 }
3382
3383 /// Updates the inputs if the obtained tool supports combining with
3384 /// preprocessor action, and the current input is indeed a preprocessor
3385 /// action. If combining results in the collapse of offloading actions, those
3386 /// are appended to \a CollapsedOffloadAction.
3387 void combineWithPreprocessor(const Tool *T, const ActionList *&Inputs,
3388 ActionList &CollapsedOffloadAction) {
3389 if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP())
3390 return;
3391
3392 // Attempt to get a preprocessor action dependence.
3393 ActionList PreprocessJobOffloadActions;
3394 auto *PJ = getPrevDependentAction(*Inputs, PreprocessJobOffloadActions);
3395 if (!PJ || !isa<PreprocessJobAction>(PJ))
3396 return;
3397
3398 // This is legal to combine. Append any offload action we found and set the
3399 // current inputs to preprocessor inputs.
3400 CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(),
3401 PreprocessJobOffloadActions.end());
3402 Inputs = &PJ->getInputs();
3403 }
3404
3405public:
3406 ToolSelector(const JobAction *BaseAction, const ToolChain &TC,
3407 const Compilation &C, bool SaveTemps, bool EmbedBitcode)
3408 : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps),
3409 EmbedBitcode(EmbedBitcode) {
3410 assert(BaseAction && "Invalid base action.");
3411 IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None;
3412 }
3413
3414 /// Check if a chain of actions can be combined and return the tool that can
3415 /// handle the combination of actions. The pointer to the current inputs \a
3416 /// Inputs and the list of offload actions \a CollapsedOffloadActions
3417 /// connected to collapsed actions are updated accordingly. The latter enables
3418 /// the caller of the selector to process them afterwards instead of just
3419 /// dropping them. If no suitable tool is found, null will be returned.
3420 const Tool *getTool(const ActionList *&Inputs,
3421 ActionList &CollapsedOffloadAction) {
3422 //
3423 // Get the largest chain of actions that we could combine.
3424 //
3425
3426 SmallVector<JobActionInfo, 5> ActionChain(1);
3427 ActionChain.back().JA = BaseAction;
3428 while (ActionChain.back().JA) {
3429 const Action *CurAction = ActionChain.back().JA;
3430
3431 // Grow the chain by one element.
3432 ActionChain.resize(ActionChain.size() + 1);
3433 JobActionInfo &AI = ActionChain.back();
3434
3435 // Attempt to fill it with the
3436 AI.JA =
3437 getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction);
Daniel Dunbarc4343942010-02-03 03:07:56 +00003438 }
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003439
3440 // Pop the last action info as it could not be filled.
3441 ActionChain.pop_back();
3442
3443 //
3444 // Attempt to combine actions. If all combining attempts failed, just return
3445 // the tool of the provided action. At the end we attempt to combine the
3446 // action with any preprocessor action it may depend on.
3447 //
3448
3449 const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs,
3450 CollapsedOffloadAction);
3451 if (!T)
3452 T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction);
3453 if (!T)
3454 T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction);
3455 if (!T) {
3456 Inputs = &BaseAction->getInputs();
3457 T = TC.SelectTool(*BaseAction);
3458 }
3459
3460 combineWithPreprocessor(T, Inputs, CollapsedOffloadAction);
3461 return T;
Daniel Dunbarc4343942010-02-03 03:07:56 +00003462 }
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003463};
Daniel Dunbarc4343942010-02-03 03:07:56 +00003464}
3465
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003466/// Return a string that uniquely identifies the result of a job. The bound arch
3467/// is not necessarily represented in the toolchain's triple -- for example,
3468/// armv7 and armv7s both map to the same triple -- so we need both in our map.
3469/// Also, we need to add the offloading device kind, as the same tool chain can
3470/// be used for host and device for some programming models, e.g. OpenMP.
3471static std::string GetTriplePlusArchString(const ToolChain *TC,
3472 StringRef BoundArch,
3473 Action::OffloadKind OffloadKind) {
Justin Lebar55c83322016-01-16 03:30:08 +00003474 std::string TriplePlusArch = TC->getTriple().normalize();
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003475 if (!BoundArch.empty()) {
Justin Lebar55c83322016-01-16 03:30:08 +00003476 TriplePlusArch += "-";
3477 TriplePlusArch += BoundArch;
3478 }
Samuel Antao59efaed2016-10-27 17:31:22 +00003479 TriplePlusArch += "-";
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003480 TriplePlusArch += Action::GetOffloadKindName(OffloadKind);
3481 return TriplePlusArch;
3482}
3483
3484InputInfo Driver::BuildJobsForAction(
3485 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
3486 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
3487 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
3488 Action::OffloadKind TargetDeviceOffloadKind) const {
3489 std::pair<const Action *, std::string> ActionTC = {
3490 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003491 auto CachedResult = CachedResults.find(ActionTC);
3492 if (CachedResult != CachedResults.end()) {
3493 return CachedResult->second;
3494 }
Samuel Antaod06239d2016-07-15 23:13:27 +00003495 InputInfo Result = BuildJobsForActionNoCache(
3496 C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003497 CachedResults, TargetDeviceOffloadKind);
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003498 CachedResults[ActionTC] = Result;
3499 return Result;
3500}
3501
3502InputInfo Driver::BuildJobsForActionNoCache(
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003503 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003504 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
Samuel Antaod06239d2016-07-15 23:13:27 +00003505 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003506 Action::OffloadKind TargetDeviceOffloadKind) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003507 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
Daniel Dunbarc4acf9d2009-03-18 23:18:19 +00003508
Samuel Antaod06239d2016-07-15 23:13:27 +00003509 InputInfoList OffloadDependencesInputInfo;
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003510 bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None;
Samuel Antaod06239d2016-07-15 23:13:27 +00003511 if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
Alex Lorenz4003a982017-08-08 11:22:21 +00003512 // The 'Darwin' toolchain is initialized only when its arguments are
3513 // computed. Get the default arguments for OFK_None to ensure that
3514 // initialization is performed before processing the offload action.
3515 // FIXME: Remove when darwin's toolchain is initialized during construction.
3516 C.getArgsForToolChain(TC, BoundArch, Action::OFK_None);
3517
Samuel Antaod06239d2016-07-15 23:13:27 +00003518 // The offload action is expected to be used in four different situations.
3519 //
3520 // a) Set a toolchain/architecture/kind for a host action:
3521 // Host Action 1 -> OffloadAction -> Host Action 2
3522 //
3523 // b) Set a toolchain/architecture/kind for a device action;
3524 // Device Action 1 -> OffloadAction -> Device Action 2
3525 //
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003526 // c) Specify a device dependence to a host action;
Samuel Antaod06239d2016-07-15 23:13:27 +00003527 // Device Action 1 _
3528 // \
3529 // Host Action 1 ---> OffloadAction -> Host Action 2
3530 //
3531 // d) Specify a host dependence to a device action.
3532 // Host Action 1 _
3533 // \
3534 // Device Action 1 ---> OffloadAction -> Device Action 2
3535 //
3536 // For a) and b), we just return the job generated for the dependence. For
3537 // c) and d) we override the current action with the host/device dependence
3538 // if the current toolchain is host/device and set the offload dependences
3539 // info with the jobs obtained from the device/host dependence(s).
3540
3541 // If there is a single device option, just generate the job for it.
3542 if (OA->hasSingleDeviceDependence()) {
3543 InputInfo DevA;
3544 OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
3545 const char *DepBoundArch) {
3546 DevA =
3547 BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
3548 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003549 CachedResults, DepA->getOffloadingDeviceKind());
Samuel Antaod06239d2016-07-15 23:13:27 +00003550 });
3551 return DevA;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003552 }
Samuel Antaod06239d2016-07-15 23:13:27 +00003553
3554 // If 'Action 2' is host, we generate jobs for the device dependences and
3555 // override the current action with the host dependence. Otherwise, we
3556 // generate the host dependences and override the action with the device
3557 // dependence. The dependences can't therefore be a top-level action.
3558 OA->doOnEachDependence(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003559 /*IsHostDependence=*/BuildingForOffloadDevice,
Samuel Antaod06239d2016-07-15 23:13:27 +00003560 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3561 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
3562 C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false,
3563 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003564 DepA->getOffloadingDeviceKind()));
Samuel Antaod06239d2016-07-15 23:13:27 +00003565 });
3566
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003567 A = BuildingForOffloadDevice
Samuel Antaod06239d2016-07-15 23:13:27 +00003568 ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
3569 : OA->getHostDependence();
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003570 }
3571
Daniel Dunbare75d8342009-03-16 06:56:51 +00003572 if (const InputAction *IA = dyn_cast<InputAction>(A)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003573 // FIXME: It would be nice to not claim this here; maybe the old scheme of
3574 // just using Args was better?
Daniel Dunbar5cdf3e02009-03-19 07:29:38 +00003575 const Arg &Input = IA->getInputArg();
3576 Input.claim();
Daniel Dunbar35cbfeb2010-06-09 22:31:08 +00003577 if (Input.getOption().matches(options::OPT_INPUT)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00003578 const char *Name = Input.getValue();
Justin Lebard98cea82016-01-11 23:15:21 +00003579 return InputInfo(A, Name, /* BaseInput = */ Name);
Douglas Katzman678d0cb2015-06-16 18:01:24 +00003580 }
Justin Lebard98cea82016-01-11 23:15:21 +00003581 return InputInfo(A, &Input, /* BaseInput = */ "");
Daniel Dunbare75d8342009-03-16 06:56:51 +00003582 }
3583
3584 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
Chad Rosiera78a6eb2012-04-27 16:50:38 +00003585 const ToolChain *TC;
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003586 StringRef ArchName = BAA->getArchName();
Daniel Dunbar1ef3f2a2009-09-08 23:37:19 +00003587
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003588 if (!ArchName.empty())
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +00003589 TC = &getToolChain(C.getArgs(),
3590 computeTargetTriple(*this, DefaultTargetTriple,
3591 C.getArgs(), ArchName));
Chad Rosiera78a6eb2012-04-27 16:50:38 +00003592 else
3593 TC = &C.getDefaultToolChain();
Daniel Dunbar1ef3f2a2009-09-08 23:37:19 +00003594
Nico Weber5a459f82016-02-23 19:30:43 +00003595 return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
Samuel Antaod06239d2016-07-15 23:13:27 +00003596 MultipleArchs, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003597 TargetDeviceOffloadKind);
Daniel Dunbare75d8342009-03-16 06:56:51 +00003598 }
3599
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003600
Daniel Dunbare75d8342009-03-16 06:56:51 +00003601 const ActionList *Inputs = &A->getInputs();
Daniel Dunbarc4343942010-02-03 03:07:56 +00003602
3603 const JobAction *JA = cast<JobAction>(A);
Samuel Antaod06239d2016-07-15 23:13:27 +00003604 ActionList CollapsedOffloadActions;
3605
Mehdi Amini6683e222017-01-24 18:12:25 +00003606 ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(),
3607 embedBitcodeInObject() && !isUsingLTO());
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003608 const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions);
3609
Rafael Espindola79764462013-03-24 15:06:53 +00003610 if (!T)
Justin Lebar9eaa4892016-01-11 23:09:32 +00003611 return InputInfo();
Daniel Dunbare75d8342009-03-16 06:56:51 +00003612
Samuel Antaod06239d2016-07-15 23:13:27 +00003613 // If we've collapsed action list that contained OffloadAction we
3614 // need to build jobs for host/device-side inputs it may have held.
3615 for (const auto *OA : CollapsedOffloadActions)
3616 cast<OffloadAction>(OA)->doOnEachDependence(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003617 /*IsHostDependence=*/BuildingForOffloadDevice,
Samuel Antaod06239d2016-07-15 23:13:27 +00003618 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3619 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
Artem Belevichbee2f412016-08-22 18:50:34 +00003620 C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false,
Samuel Antaod06239d2016-07-15 23:13:27 +00003621 /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003622 DepA->getOffloadingDeviceKind()));
Samuel Antaod06239d2016-07-15 23:13:27 +00003623 });
Artem Belevichf8144ab2015-08-27 18:10:41 +00003624
Daniel Dunbare75d8342009-03-16 06:56:51 +00003625 // Only use pipes when there is exactly one input.
Daniel Dunbar1a093d22009-03-18 06:00:36 +00003626 InputInfoList InputInfos;
Saleem Abdulrasoolda3f4e52014-12-29 21:02:47 +00003627 for (const Action *Input : *Inputs) {
Eric Christopher14668dd2013-02-18 00:38:25 +00003628 // Treat dsymutil and verify sub-jobs as being at the top-level too, they
3629 // shouldn't get temporary output names.
Daniel Dunbar6beaf512010-06-04 18:28:41 +00003630 // FIXME: Clean this up.
Justin Lebar9eaa4892016-01-11 23:09:32 +00003631 bool SubJobAtTopLevel =
3632 AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
Samuel Antaod06239d2016-07-15 23:13:27 +00003633 InputInfos.push_back(BuildJobsForAction(
3634 C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003635 CachedResults, A->getOffloadingDeviceKind()));
Daniel Dunbare75d8342009-03-16 06:56:51 +00003636 }
3637
Daniel Dunbare75d8342009-03-16 06:56:51 +00003638 // Always use the first input as the base input.
3639 const char *BaseInput = InputInfos[0].getBaseInput();
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003640
Daniel Dunbar6beaf512010-06-04 18:28:41 +00003641 // ... except dsymutil actions, which use their actual input as the base
3642 // input.
3643 if (JA->getType() == types::TY_dSYM)
3644 BaseInput = InputInfos[0].getFilename();
3645
Samuel Antaod06239d2016-07-15 23:13:27 +00003646 // Append outputs of offload device jobs to the input list
3647 if (!OffloadDependencesInputInfo.empty())
3648 InputInfos.append(OffloadDependencesInputInfo.begin(),
3649 OffloadDependencesInputInfo.end());
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003650
Vedant Kumar18286cf2016-07-27 23:02:20 +00003651 // Set the effective triple of the toolchain for the duration of this job.
3652 llvm::Triple EffectiveTriple;
3653 const ToolChain &ToolTC = T->getToolChain();
Samuel Antao31fef982016-10-27 17:39:44 +00003654 const ArgList &Args =
3655 C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind());
Vedant Kumar18286cf2016-07-27 23:02:20 +00003656 if (InputInfos.size() != 1) {
3657 EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args));
3658 } else {
3659 // Pass along the input type if it can be unambiguously determined.
3660 EffectiveTriple = llvm::Triple(
3661 ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType()));
3662 }
3663 RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple);
3664
Daniel Dunbard00272f2010-08-02 02:38:15 +00003665 // Determine the place to write output to, if any.
Justin Lebar9eaa4892016-01-11 23:09:32 +00003666 InputInfo Result;
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003667 InputInfoList UnbundlingResults;
3668 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) {
3669 // If we have an unbundling job, we need to create results for all the
3670 // outputs. We also update the results cache so that other actions using
3671 // this unbundling action can get the right results.
3672 for (auto &UI : UA->getDependentActionsInfo()) {
3673 assert(UI.DependentOffloadKind != Action::OFK_None &&
3674 "Unbundling with no offloading??");
3675
3676 // Unbundling actions are never at the top level. When we generate the
3677 // offloading prefix, we also do that for the host file because the
3678 // unbundling action does not change the type of the output which can
3679 // cause a overwrite.
3680 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
3681 UI.DependentOffloadKind,
3682 UI.DependentToolChain->getTriple().normalize(),
3683 /*CreatePrefixForHost=*/true);
3684 auto CurI = InputInfo(
3685 UA, GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch,
3686 /*AtTopLevel=*/false, MultipleArchs,
3687 OffloadingPrefix),
3688 BaseInput);
3689 // Save the unbundling result.
3690 UnbundlingResults.push_back(CurI);
3691
3692 // Get the unique string identifier for this dependence and cache the
3693 // result.
3694 CachedResults[{A, GetTriplePlusArchString(
Gheorghe-Teodor Bercea52898432017-08-09 01:02:19 +00003695 UI.DependentToolChain, BoundArch,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003696 UI.DependentOffloadKind)}] = CurI;
3697 }
3698
3699 // Now that we have all the results generated, select the one that should be
3700 // returned for the current depending action.
3701 std::pair<const Action *, std::string> ActionTC = {
3702 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
3703 assert(CachedResults.find(ActionTC) != CachedResults.end() &&
3704 "Result does not exist??");
3705 Result = CachedResults[ActionTC];
3706 } else if (JA->getType() == types::TY_Nothing)
Justin Lebard98cea82016-01-11 23:15:21 +00003707 Result = InputInfo(A, BaseInput);
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003708 else {
3709 // We only have to generate a prefix for the host if this is not a top-level
3710 // action.
3711 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
3712 A->getOffloadingDeviceKind(), TC->getTriple().normalize(),
3713 /*CreatePrefixForHost=*/!!A->getOffloadingHostActiveKinds() &&
3714 !AtTopLevel);
Justin Lebard98cea82016-01-11 23:15:21 +00003715 Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
Samuel Antaod06239d2016-07-15 23:13:27 +00003716 AtTopLevel, MultipleArchs,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003717 OffloadingPrefix),
Justin Lebard98cea82016-01-11 23:15:21 +00003718 BaseInput);
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003719 }
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003720
Chad Rosierbe10f982011-08-02 17:58:04 +00003721 if (CCCPrintBindings && !CCGenDiagnostics) {
Rafael Espindola79764462013-03-24 15:06:53 +00003722 llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
3723 << " - \"" << T->getName() << "\", inputs: [";
Daniel Dunbarb39cc522009-03-17 22:47:06 +00003724 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
3725 llvm::errs() << InputInfos[i].getAsString();
3726 if (i + 1 != e)
3727 llvm::errs() << ", ";
3728 }
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003729 if (UnbundlingResults.empty())
3730 llvm::errs() << "], output: " << Result.getAsString() << "\n";
3731 else {
3732 llvm::errs() << "], outputs: [";
3733 for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) {
3734 llvm::errs() << UnbundlingResults[i].getAsString();
3735 if (i + 1 != e)
3736 llvm::errs() << ", ";
3737 }
3738 llvm::errs() << "] \n";
3739 }
Daniel Dunbarb39cc522009-03-17 22:47:06 +00003740 } else {
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003741 if (UnbundlingResults.empty())
3742 T->ConstructJob(
3743 C, *JA, Result, InputInfos,
3744 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
3745 LinkingOutput);
3746 else
Samuel Antao7108bf32016-11-03 15:41:50 +00003747 T->ConstructJobMultipleOutputs(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003748 C, *JA, UnbundlingResults, InputInfos,
3749 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
3750 LinkingOutput);
Daniel Dunbarb39cc522009-03-17 22:47:06 +00003751 }
Justin Lebar9eaa4892016-01-11 23:09:32 +00003752 return Result;
Daniel Dunbare75d8342009-03-16 06:56:51 +00003753}
3754
Hans Wennborga7707222015-01-09 17:38:53 +00003755const char *Driver::getDefaultImageName() const {
3756 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
3757 return Target.isOSWindows() ? "a.exe" : "a.out";
3758}
3759
Hans Wennborg2c21f742013-10-17 16:16:23 +00003760/// \brief Create output filename based on ArgValue, which could either be a
3761/// full filename, filename without extension, or a directory. If ArgValue
3762/// does not provide a filename, then use BaseName, and use the extension
3763/// suitable for FileType.
Hans Wennborg207fcf02013-08-12 21:56:42 +00003764static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003765 StringRef BaseName,
3766 types::ID FileType) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00003767 SmallString<128> Filename = ArgValue;
Justin Bogner5aaf2e72014-06-26 20:59:36 +00003768
Hans Wennborgf1a74252013-09-10 20:18:04 +00003769 if (ArgValue.empty()) {
3770 // If the argument is empty, output to BaseName in the current dir.
3771 Filename = BaseName;
3772 } else if (llvm::sys::path::is_separator(Filename.back())) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00003773 // If the argument is a directory, output to BaseName in that dir.
3774 llvm::sys::path::append(Filename, BaseName);
3775 }
3776
3777 if (!llvm::sys::path::has_extension(ArgValue)) {
3778 // If the argument didn't provide an extension, then set it.
3779 const char *Extension = types::getTypeTempSuffix(FileType, true);
Hans Wennborgf1a74252013-09-10 20:18:04 +00003780
3781 if (FileType == types::TY_Image &&
3782 Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
3783 // The output file is a dll.
3784 Extension = "dll";
3785 }
3786
Hans Wennborg207fcf02013-08-12 21:56:42 +00003787 llvm::sys::path::replace_extension(Filename, Extension);
3788 }
3789
3790 return Args.MakeArgString(Filename.c_str());
3791}
3792
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003793const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003794 const char *BaseInput,
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003795 StringRef BoundArch, bool AtTopLevel,
Samuel Antaod06239d2016-07-15 23:13:27 +00003796 bool MultipleArchs,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003797 StringRef OffloadingPrefix) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00003798 llvm::PrettyStackTraceString CrashInfo("Computing output path");
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003799 // Output to a user requested destination?
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003800 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003801 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
Chad Rosier633dcdc2013-01-24 19:14:47 +00003802 return C.addResultFile(FinalOutput->getValue(), &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003803 }
3804
Hans Wennborge0053472013-12-20 18:40:46 +00003805 // For /P, preprocess to file named after BaseInput.
3806 if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
3807 assert(AtTopLevel && isa<PreprocessJobAction>(JA));
3808 StringRef BaseName = llvm::sys::path::filename(BaseInput);
Hans Wennborg04c764f2014-06-17 00:19:12 +00003809 StringRef NameArg;
Greg Bedwell065f70a2015-06-09 10:24:06 +00003810 if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
Hans Wennborg04c764f2014-06-17 00:19:12 +00003811 NameArg = A->getValue();
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003812 return C.addResultFile(
3813 MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
3814 &JA);
Hans Wennborge0053472013-12-20 18:40:46 +00003815 }
3816
Nick Lewycky6e1ce292010-09-24 00:46:53 +00003817 // Default to writing to stdout?
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00003818 if (AtTopLevel && !CCGenDiagnostics &&
3819 (isa<PreprocessJobAction>(JA) || JA.getType() == types::TY_ModuleFile))
Nick Lewycky6e1ce292010-09-24 00:46:53 +00003820 return "-";
3821
Hans Wennborg2c21f742013-10-17 16:16:23 +00003822 // Is this the assembly listing for /FA?
3823 if (JA.getType() == types::TY_PP_Asm &&
3824 (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
3825 C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
3826 // Use /Fa and the input filename to determine the asm file name.
3827 StringRef BaseName = llvm::sys::path::filename(BaseInput);
3828 StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003829 return C.addResultFile(
3830 MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
3831 &JA);
Hans Wennborg2c21f742013-10-17 16:16:23 +00003832 }
3833
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003834 // Output to a temporary file?
Reid Kleckner68eb60b2015-02-02 22:41:48 +00003835 if ((!AtTopLevel && !isSaveTempsEnabled() &&
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003836 !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
Chad Rosierbe10f982011-08-02 17:58:04 +00003837 CCGenDiagnostics) {
Chad Rosier97c37372011-08-26 22:27:02 +00003838 StringRef Name = llvm::sys::path::filename(BaseInput);
3839 std::pair<StringRef, StringRef> Split = Name.split('.');
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003840 std::string TmpName = GetTemporaryPath(
3841 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00003842 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003843 }
3844
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003845 SmallString<128> BasePath(BaseInput);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003846 StringRef BaseName;
Daniel Dunbar67fea712011-03-25 18:16:51 +00003847
3848 // Dsymutil actions should use the full path.
Eric Christopher551ef452011-08-23 17:56:55 +00003849 if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
Daniel Dunbar67fea712011-03-25 18:16:51 +00003850 BaseName = BasePath;
3851 else
3852 BaseName = llvm::sys::path::filename(BasePath);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003853
3854 // Determine what the derived output name should be.
3855 const char *NamedOutput;
Hans Wennborg2b89a262013-08-06 22:11:28 +00003856
Hans Wennborg625fba82016-10-04 21:01:04 +00003857 if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) &&
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00003858 C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
3859 // The /Fo or /o flag decides the object filename.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003860 StringRef Val =
3861 C.getArgs()
3862 .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
3863 ->getValue();
3864 NamedOutput =
3865 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
Hans Wennborg207fcf02013-08-12 21:56:42 +00003866 } else if (JA.getType() == types::TY_Image &&
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003867 C.getArgs().hasArg(options::OPT__SLASH_Fe,
3868 options::OPT__SLASH_o)) {
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00003869 // The /Fe or /o flag names the linked file.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003870 StringRef Val =
3871 C.getArgs()
3872 .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
3873 ->getValue();
3874 NamedOutput =
3875 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
Hans Wennborgf1a74252013-09-10 20:18:04 +00003876 } else if (JA.getType() == types::TY_Image) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00003877 if (IsCLMode()) {
3878 // clang-cl uses BaseName for the executable name.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003879 NamedOutput =
3880 MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
Samuel Antao59efaed2016-10-27 17:31:22 +00003881 } else {
Hans Wennborga7707222015-01-09 17:38:53 +00003882 SmallString<128> Output(getDefaultImageName());
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003883 Output += OffloadingPrefix;
Samuel Antao59efaed2016-10-27 17:31:22 +00003884 if (MultipleArchs && !BoundArch.empty()) {
3885 Output += "-";
3886 Output.append(BoundArch);
3887 }
Chad Rosier35767232013-04-30 22:01:21 +00003888 NamedOutput = C.getArgs().MakeArgString(Output.c_str());
Nico Weber2ca4be92016-03-01 23:16:44 +00003889 }
3890 } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00003891 NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName));
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003892 } else {
Hans Wennborg0a096a02013-09-05 17:05:56 +00003893 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003894 assert(Suffix && "All types used for output should have a suffix.");
3895
3896 std::string::size_type End = std::string::npos;
3897 if (!types::appendSuffixForType(JA.getType()))
3898 End = BaseName.rfind('.');
Chad Rosier35767232013-04-30 22:01:21 +00003899 SmallString<128> Suffixed(BaseName.substr(0, End));
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003900 Suffixed += OffloadingPrefix;
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003901 if (MultipleArchs && !BoundArch.empty()) {
Chad Rosier35767232013-04-30 22:01:21 +00003902 Suffixed += "-";
3903 Suffixed.append(BoundArch);
3904 }
Bob Wilson23a55f12014-12-21 07:00:00 +00003905 // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
3906 // the unoptimized bitcode so that it does not get overwritten by the ".bc"
3907 // optimized bitcode output.
3908 if (!AtTopLevel && C.getArgs().hasArg(options::OPT_emit_llvm) &&
3909 JA.getType() == types::TY_LLVM_BC)
3910 Suffixed += ".tmp";
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003911 Suffixed += '.';
3912 Suffixed += Suffix;
3913 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
3914 }
3915
Reid Kleckner68eb60b2015-02-02 22:41:48 +00003916 // Prepend object file path if -save-temps=obj
3917 if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
3918 JA.getType() != types::TY_PCH) {
3919 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
3920 SmallString<128> TempPath(FinalOutput->getValue());
3921 llvm::sys::path::remove_filename(TempPath);
3922 StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
3923 llvm::sys::path::append(TempPath, OutputFileName);
3924 NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
3925 }
3926
Chad Rosier62135492012-07-09 17:31:28 +00003927 // If we're saving temps and the temp file conflicts with the input file,
Chad Rosier5b58af02012-04-20 20:05:08 +00003928 // then avoid overwriting input file.
Reid Kleckner68eb60b2015-02-02 22:41:48 +00003929 if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
Chad Rosier5b58af02012-04-20 20:05:08 +00003930 bool SameFile = false;
3931 SmallString<256> Result;
3932 llvm::sys::fs::current_path(Result);
3933 llvm::sys::path::append(Result, BaseName);
3934 llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
3935 // Must share the same path to conflict.
3936 if (SameFile) {
3937 StringRef Name = llvm::sys::path::filename(BaseInput);
3938 std::pair<StringRef, StringRef> Split = Name.split('.');
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003939 std::string TmpName = GetTemporaryPath(
3940 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00003941 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
Chad Rosier5b58af02012-04-20 20:05:08 +00003942 }
Chad Rosierf8412cd2011-07-15 21:54:29 +00003943 }
3944
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003945 // As an annoying special case, PCH generation doesn't strip the pathname.
Nico Weber8ab92192016-03-02 23:29:29 +00003946 if (JA.getType() == types::TY_PCH && !IsCLMode()) {
Michael J. Spencere1696752010-12-18 00:19:12 +00003947 llvm::sys::path::remove_filename(BasePath);
3948 if (BasePath.empty())
Daniel Dunbare6c83192009-03-18 09:58:30 +00003949 BasePath = NamedOutput;
3950 else
Michael J. Spencere1696752010-12-18 00:19:12 +00003951 llvm::sys::path::append(BasePath, NamedOutput);
Chad Rosier633dcdc2013-01-24 19:14:47 +00003952 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003953 } else {
Chad Rosier633dcdc2013-01-24 19:14:47 +00003954 return C.addResultFile(NamedOutput, &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003955 }
3956}
3957
Mehdi Amini12011172016-10-06 05:11:48 +00003958std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const {
Chandler Carruth84559242010-03-22 01:52:07 +00003959 // Respect a limited subset of the '-Bprefix' functionality in GCC by
Logan Chiencd679fd2012-10-04 08:08:56 +00003960 // attempting to use this prefix when looking for file paths.
Douglas Katzman26eabf62015-06-24 15:10:30 +00003961 for (const std::string &Dir : PrefixDirs) {
Joerg Sonnenberger6165ab12011-03-21 13:51:29 +00003962 if (Dir.empty())
3963 continue;
Douglas Katzman26eabf62015-06-24 15:10:30 +00003964 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
Rafael Espindola609a6642013-06-24 18:33:43 +00003965 llvm::sys::path::append(P, Name);
3966 if (llvm::sys::fs::exists(Twine(P)))
Chandler Carruth84559242010-03-22 01:52:07 +00003967 return P.str();
3968 }
3969
Petr Hosek916a4672017-08-10 04:16:38 +00003970 SmallString<128> R(ResourceDir);
3971 llvm::sys::path::append(R, Name);
3972 if (llvm::sys::fs::exists(Twine(R)))
3973 return R.str();
3974
3975 SmallString<128> P(TC.getCompilerRTPath());
Rafael Espindola609a6642013-06-24 18:33:43 +00003976 llvm::sys::path::append(P, Name);
3977 if (llvm::sys::fs::exists(Twine(P)))
Peter Collingbournefa9771f2011-09-06 02:08:31 +00003978 return P.str();
3979
Douglas Katzman26eabf62015-06-24 15:10:30 +00003980 for (const std::string &Dir : TC.getFilePaths()) {
Joerg Sonnenberger6165ab12011-03-21 13:51:29 +00003981 if (Dir.empty())
3982 continue;
Douglas Katzman26eabf62015-06-24 15:10:30 +00003983 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
Rafael Espindola609a6642013-06-24 18:33:43 +00003984 llvm::sys::path::append(P, Name);
3985 if (llvm::sys::fs::exists(Twine(P)))
Daniel Dunbar1ce81532009-09-09 22:33:00 +00003986 return P.str();
Daniel Dunbar68b01a02009-03-18 20:26:19 +00003987 }
3988
Daniel Dunbar1ce81532009-09-09 22:33:00 +00003989 return Name;
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00003990}
3991
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003992void Driver::generatePrefixedToolNames(
Mehdi Amini12011172016-10-06 05:11:48 +00003993 StringRef Tool, const ToolChain &TC,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003994 SmallVectorImpl<std::string> &Names) const {
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00003995 // FIXME: Needs a better variable than DefaultTargetTriple
Mehdi Amini12011172016-10-06 05:11:48 +00003996 Names.emplace_back((DefaultTargetTriple + "-" + Tool).str());
Benjamin Kramer3204b152015-05-29 19:42:19 +00003997 Names.emplace_back(Tool);
Vasileios Kalintirisc744e122015-11-12 15:26:54 +00003998
3999 // Allow the discovery of tools prefixed with LLVM's default target triple.
4000 std::string LLVMDefaultTargetTriple = llvm::sys::getDefaultTargetTriple();
4001 if (LLVMDefaultTargetTriple != DefaultTargetTriple)
Mehdi Amini12011172016-10-06 05:11:48 +00004002 Names.emplace_back((LLVMDefaultTargetTriple + "-" + Tool).str());
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004003}
4004
Benjamin Kramer7111b912014-11-04 20:26:01 +00004005static bool ScanDirForExecutable(SmallString<128> &Dir,
4006 ArrayRef<std::string> Names) {
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004007 for (const auto &Name : Names) {
4008 llvm::sys::path::append(Dir, Name);
4009 if (llvm::sys::fs::can_execute(Twine(Dir)))
4010 return true;
4011 llvm::sys::path::remove_filename(Dir);
4012 }
4013 return false;
4014}
4015
Mehdi Amini12011172016-10-06 05:11:48 +00004016std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const {
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004017 SmallVector<std::string, 2> TargetSpecificExecutables;
4018 generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
4019
Chandler Carruth84559242010-03-22 01:52:07 +00004020 // Respect a limited subset of the '-Bprefix' functionality in GCC by
Logan Chiencd679fd2012-10-04 08:08:56 +00004021 // attempting to use this prefix when looking for program paths.
Saleem Abdulrasool23d99b12014-09-16 03:48:32 +00004022 for (const auto &PrefixDir : PrefixDirs) {
4023 if (llvm::sys::fs::is_directory(PrefixDir)) {
4024 SmallString<128> P(PrefixDir);
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004025 if (ScanDirForExecutable(P, TargetSpecificExecutables))
Rafael Espindola8be5c052013-06-19 13:24:29 +00004026 return P.str();
Simon Atanasyana47ba292012-10-31 14:39:28 +00004027 } else {
Mehdi Amini12011172016-10-06 05:11:48 +00004028 SmallString<128> P((PrefixDir + Name).str());
Rafael Espindola609a6642013-06-24 18:33:43 +00004029 if (llvm::sys::fs::can_execute(Twine(P)))
Rafael Espindola8be5c052013-06-19 13:24:29 +00004030 return P.str();
Simon Atanasyan86bdab72012-10-31 12:01:53 +00004031 }
Chandler Carruth84559242010-03-22 01:52:07 +00004032 }
4033
Daniel Dunbar68b01a02009-03-18 20:26:19 +00004034 const ToolChain::path_list &List = TC.getProgramPaths();
Saleem Abdulrasool23d99b12014-09-16 03:48:32 +00004035 for (const auto &Path : List) {
4036 SmallString<128> P(Path);
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004037 if (ScanDirForExecutable(P, TargetSpecificExecutables))
Rafael Espindola8be5c052013-06-19 13:24:29 +00004038 return P.str();
Daniel Dunbar68b01a02009-03-18 20:26:19 +00004039 }
4040
Daniel Dunbar76ce7412009-03-23 16:15:50 +00004041 // If all else failed, search the path.
Michael J. Spencerb011d482014-11-07 21:30:32 +00004042 for (const auto &TargetSpecificExecutable : TargetSpecificExecutables)
4043 if (llvm::ErrorOr<std::string> P =
4044 llvm::sys::findProgramByName(TargetSpecificExecutable))
Michael J. Spencer04162ea2014-11-04 01:30:55 +00004045 return *P;
Daniel Dunbar6f668772009-03-18 21:34:08 +00004046
Daniel Dunbar1ce81532009-09-09 22:33:00 +00004047 return Name;
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00004048}
4049
Mehdi Amini12011172016-10-06 05:11:48 +00004050std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const {
Rafael Espindola37d229d2013-06-25 04:26:55 +00004051 SmallString<128> Path;
Rafael Espindolac0809172014-06-12 14:02:15 +00004052 std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
Rafael Espindola37d229d2013-06-25 04:26:55 +00004053 if (EC) {
4054 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
Daniel Dunbare627c1c2009-03-18 19:34:39 +00004055 return "";
4056 }
4057
Rafael Espindola37d229d2013-06-25 04:26:55 +00004058 return Path.str();
Daniel Dunbare627c1c2009-03-18 19:34:39 +00004059}
4060
Nico Weber2ca4be92016-03-01 23:16:44 +00004061std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
4062 SmallString<128> Output;
4063 if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
4064 // FIXME: If anybody needs it, implement this obscure rule:
4065 // "If you specify a directory without a file name, the default file name
4066 // is VCx0.pch., where x is the major version of Visual C++ in use."
4067 Output = FpArg->getValue();
4068
4069 // "If you do not specify an extension as part of the path name, an
4070 // extension of .pch is assumed. "
4071 if (!llvm::sys::path::has_extension(Output))
4072 Output += ".pch";
4073 } else {
4074 Output = BaseName;
4075 llvm::sys::path::replace_extension(Output, ".pch");
4076 }
4077 return Output.str();
4078}
4079
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004080const ToolChain &Driver::getToolChain(const ArgList &Args,
Artem Belevich959e0542015-07-10 19:47:55 +00004081 const llvm::Triple &Target) const {
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004082
David Blaikie6ad71012017-01-13 18:53:43 +00004083 auto &TC = ToolChains[Target.str()];
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004084 if (!TC) {
4085 switch (Target.getOS()) {
Reid Kleckner330fb172016-05-11 16:19:05 +00004086 case llvm::Triple::Haiku:
David Blaikie6ad71012017-01-13 18:53:43 +00004087 TC = llvm::make_unique<toolchains::Haiku>(*this, Target, Args);
Reid Kleckner330fb172016-05-11 16:19:05 +00004088 break;
Ed Schouten4dabea22017-06-25 08:29:09 +00004089 case llvm::Triple::Ananas:
4090 TC = llvm::make_unique<toolchains::Ananas>(*this, Target, Args);
4091 break;
Ed Schouten3c3e58c2015-03-26 11:13:44 +00004092 case llvm::Triple::CloudABI:
David Blaikie6ad71012017-01-13 18:53:43 +00004093 TC = llvm::make_unique<toolchains::CloudABI>(*this, Target, Args);
Ed Schouten3c3e58c2015-03-26 11:13:44 +00004094 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004095 case llvm::Triple::Darwin:
4096 case llvm::Triple::MacOSX:
4097 case llvm::Triple::IOS:
Tim Northover6f3ff222015-10-30 16:30:27 +00004098 case llvm::Triple::TvOS:
4099 case llvm::Triple::WatchOS:
David Blaikie6ad71012017-01-13 18:53:43 +00004100 TC = llvm::make_unique<toolchains::DarwinClang>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004101 break;
4102 case llvm::Triple::DragonFly:
David Blaikie6ad71012017-01-13 18:53:43 +00004103 TC = llvm::make_unique<toolchains::DragonFly>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004104 break;
4105 case llvm::Triple::OpenBSD:
David Blaikie6ad71012017-01-13 18:53:43 +00004106 TC = llvm::make_unique<toolchains::OpenBSD>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004107 break;
4108 case llvm::Triple::NetBSD:
David Blaikie6ad71012017-01-13 18:53:43 +00004109 TC = llvm::make_unique<toolchains::NetBSD>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004110 break;
4111 case llvm::Triple::FreeBSD:
David Blaikie6ad71012017-01-13 18:53:43 +00004112 TC = llvm::make_unique<toolchains::FreeBSD>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004113 break;
4114 case llvm::Triple::Minix:
David Blaikie6ad71012017-01-13 18:53:43 +00004115 TC = llvm::make_unique<toolchains::Minix>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004116 break;
4117 case llvm::Triple::Linux:
Andrey Turetskiy4798eb62016-06-16 10:36:09 +00004118 case llvm::Triple::ELFIAMCU:
Chandler Carruthcf705b22012-01-25 21:03:58 +00004119 if (Target.getArch() == llvm::Triple::hexagon)
David Blaikie6ad71012017-01-13 18:53:43 +00004120 TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
4121 Args);
Vasileios Kalintirisc744e122015-11-12 15:26:54 +00004122 else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
4123 !Target.hasEnvironment())
David Blaikie6ad71012017-01-13 18:53:43 +00004124 TC = llvm::make_unique<toolchains::MipsLLVMToolChain>(*this, Target,
4125 Args);
Chandler Carruthcf705b22012-01-25 21:03:58 +00004126 else
David Blaikie6ad71012017-01-13 18:53:43 +00004127 TC = llvm::make_unique<toolchains::Linux>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004128 break;
Derek Schuff6ab52fa2015-03-30 20:31:33 +00004129 case llvm::Triple::NaCl:
David Blaikie6ad71012017-01-13 18:53:43 +00004130 TC = llvm::make_unique<toolchains::NaClToolChain>(*this, Target, Args);
Derek Schuff6ab52fa2015-03-30 20:31:33 +00004131 break;
Petr Hosek62e1d232016-10-06 06:08:09 +00004132 case llvm::Triple::Fuchsia:
David Blaikie6ad71012017-01-13 18:53:43 +00004133 TC = llvm::make_unique<toolchains::Fuchsia>(*this, Target, Args);
Petr Hosek62e1d232016-10-06 06:08:09 +00004134 break;
David Chisnallf571cde2012-02-15 13:39:01 +00004135 case llvm::Triple::Solaris:
David Blaikie6ad71012017-01-13 18:53:43 +00004136 TC = llvm::make_unique<toolchains::Solaris>(*this, Target, Args);
David Chisnallf571cde2012-02-15 13:39:01 +00004137 break;
Tom Stellard8fa33092015-07-18 01:49:05 +00004138 case llvm::Triple::AMDHSA:
David Blaikie6ad71012017-01-13 18:53:43 +00004139 TC = llvm::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args);
Tom Stellard8fa33092015-07-18 01:49:05 +00004140 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004141 case llvm::Triple::Win32:
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004142 switch (Target.getEnvironment()) {
4143 default:
4144 if (Target.isOSBinFormatELF())
David Blaikie6ad71012017-01-13 18:53:43 +00004145 TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004146 else if (Target.isOSBinFormatMachO())
David Blaikie6ad71012017-01-13 18:53:43 +00004147 TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004148 else
David Blaikie6ad71012017-01-13 18:53:43 +00004149 TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004150 break;
4151 case llvm::Triple::GNU:
David Blaikie6ad71012017-01-13 18:53:43 +00004152 TC = llvm::make_unique<toolchains::MinGW>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004153 break;
Saleem Abdulrasool543a78b2014-10-24 03:13:37 +00004154 case llvm::Triple::Itanium:
David Blaikie6ad71012017-01-13 18:53:43 +00004155 TC = llvm::make_unique<toolchains::CrossWindowsToolChain>(*this, Target,
4156 Args);
Saleem Abdulrasool543a78b2014-10-24 03:13:37 +00004157 break;
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004158 case llvm::Triple::MSVC:
4159 case llvm::Triple::UnknownEnvironment:
Dave Leef96bedf2017-11-06 21:18:05 +00004160 if (Args.getLastArgValue(options::OPT_fuse_ld_EQ)
4161 .startswith_lower("bfd"))
4162 TC = llvm::make_unique<toolchains::CrossWindowsToolChain>(
4163 *this, Target, Args);
4164 else
4165 TC =
4166 llvm::make_unique<toolchains::MSVCToolChain>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004167 break;
4168 }
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004169 break;
Filipe Cabecinhasc888e192015-10-14 12:25:43 +00004170 case llvm::Triple::PS4:
David Blaikie6ad71012017-01-13 18:53:43 +00004171 TC = llvm::make_unique<toolchains::PS4CPU>(*this, Target, Args);
Filipe Cabecinhasc888e192015-10-14 12:25:43 +00004172 break;
David L Kreitzerd397ea42016-10-14 20:44:33 +00004173 case llvm::Triple::Contiki:
David Blaikie6ad71012017-01-13 18:53:43 +00004174 TC = llvm::make_unique<toolchains::Contiki>(*this, Target, Args);
David L Kreitzerd397ea42016-10-14 20:44:33 +00004175 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004176 default:
Douglas Katzman9f5e70e2015-05-26 18:01:33 +00004177 // Of these targets, Hexagon is the only one that might have
4178 // an OS of Linux, in which case it got handled above already.
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004179 switch (Target.getArch()) {
4180 case llvm::Triple::tce:
David Blaikie6ad71012017-01-13 18:53:43 +00004181 TC = llvm::make_unique<toolchains::TCEToolChain>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004182 break;
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00004183 case llvm::Triple::tcele:
David Blaikie6ad71012017-01-13 18:53:43 +00004184 TC = llvm::make_unique<toolchains::TCELEToolChain>(*this, Target, Args);
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00004185 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004186 case llvm::Triple::hexagon:
David Blaikie6ad71012017-01-13 18:53:43 +00004187 TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
4188 Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004189 break;
Jacques Pienaard964cc22016-03-28 21:02:54 +00004190 case llvm::Triple::lanai:
David Blaikie6ad71012017-01-13 18:53:43 +00004191 TC = llvm::make_unique<toolchains::LanaiToolChain>(*this, Target, Args);
Jacques Pienaard964cc22016-03-28 21:02:54 +00004192 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004193 case llvm::Triple::xcore:
David Blaikie6ad71012017-01-13 18:53:43 +00004194 TC = llvm::make_unique<toolchains::XCoreToolChain>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004195 break;
Dan Gohmanc2853072015-09-03 22:51:53 +00004196 case llvm::Triple::wasm32:
4197 case llvm::Triple::wasm64:
David Blaikie6ad71012017-01-13 18:53:43 +00004198 TC = llvm::make_unique<toolchains::WebAssembly>(*this, Target, Args);
Dan Gohmanc2853072015-09-03 22:51:53 +00004199 break;
Dylan McKay924fa3a2017-01-05 05:20:27 +00004200 case llvm::Triple::avr:
David Blaikie6ad71012017-01-13 18:53:43 +00004201 TC = llvm::make_unique<toolchains::AVRToolChain>(*this, Target, Args);
Dylan McKay924fa3a2017-01-05 05:20:27 +00004202 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004203 default:
Douglas Katzmand6e597c2015-09-17 19:56:40 +00004204 if (Target.getVendor() == llvm::Triple::Myriad)
David Blaikie6ad71012017-01-13 18:53:43 +00004205 TC = llvm::make_unique<toolchains::MyriadToolChain>(*this, Target,
4206 Args);
Jonathan Roelofs901c7762017-05-25 15:42:13 +00004207 else if (toolchains::BareMetal::handlesTarget(Target))
4208 TC = llvm::make_unique<toolchains::BareMetal>(*this, Target, Args);
Douglas Katzmand6e597c2015-09-17 19:56:40 +00004209 else if (Target.isOSBinFormatELF())
David Blaikie6ad71012017-01-13 18:53:43 +00004210 TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004211 else if (Target.isOSBinFormatMachO())
David Blaikie6ad71012017-01-13 18:53:43 +00004212 TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004213 else
David Blaikie6ad71012017-01-13 18:53:43 +00004214 TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004215 }
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004216 }
4217 }
Justin Lebar66c4fd72016-11-18 00:41:22 +00004218
4219 // Intentionally omitted from the switch above: llvm::Triple::CUDA. CUDA
4220 // compiles always need two toolchains, the CUDA toolchain and the host
4221 // toolchain. So the only valid way to create a CUDA toolchain is via
4222 // CreateOffloadingDeviceToolChains.
4223
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004224 return *TC;
Daniel Dunbar4dff6a42009-03-10 23:41:59 +00004225}
Daniel Dunbar8fa879d2009-03-24 18:57:02 +00004226
Rafael Espindola2f69d402013-03-18 15:33:26 +00004227bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
Douglas Katzman00249092015-06-12 15:45:21 +00004228 // Say "no" if there is not exactly one input of a type clang understands.
Nico Weber5a459f82016-02-23 19:30:43 +00004229 if (JA.size() != 1 ||
4230 !types::isAcceptedByClang((*JA.input_begin())->getType()))
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00004231 return false;
4232
Douglas Katzman00249092015-06-12 15:45:21 +00004233 // And say "no" if this is not a kind of action clang understands.
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00004234 if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
Bob Wilson23a55f12014-12-21 07:00:00 +00004235 !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00004236 return false;
4237
4238 return true;
4239}
4240
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00004241/// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
4242/// grouped values as integers. Numbers which are not provided are set to 0.
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004243///
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00004244/// \return True if the entire string was parsed (9.2), or all groups were
4245/// parsed (10.3.5extrastuff).
Mehdi Amini12011172016-10-06 05:11:48 +00004246bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
4247 unsigned &Micro, bool &HadExtra) {
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004248 HadExtra = false;
4249
4250 Major = Minor = Micro = 0;
Mehdi Amini12011172016-10-06 05:11:48 +00004251 if (Str.empty())
Bob Wilson433cb312015-04-07 01:03:35 +00004252 return false;
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004253
Mehdi Amini12011172016-10-06 05:11:48 +00004254 if (Str.consumeInteger(10, Major))
4255 return false;
4256 if (Str.empty())
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004257 return true;
Mehdi Amini12011172016-10-06 05:11:48 +00004258 if (Str[0] != '.')
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004259 return false;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00004260
Mehdi Amini12011172016-10-06 05:11:48 +00004261 Str = Str.drop_front(1);
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004262
Mehdi Amini12011172016-10-06 05:11:48 +00004263 if (Str.consumeInteger(10, Minor))
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004264 return false;
Mehdi Amini12011172016-10-06 05:11:48 +00004265 if (Str.empty())
4266 return true;
4267 if (Str[0] != '.')
4268 return false;
4269 Str = Str.drop_front(1);
4270
4271 if (Str.consumeInteger(10, Micro))
4272 return false;
4273 if (!Str.empty())
4274 HadExtra = true;
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004275 return true;
4276}
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004277
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004278/// Parse digits from a string \p Str and fulfill \p Digits with
4279/// the parsed numbers. This method assumes that the max number of
4280/// digits to look for is equal to Digits.size().
4281///
4282/// \return True if the entire string was parsed and there are
4283/// no extra characters remaining at the end.
Mehdi Amini12011172016-10-06 05:11:48 +00004284bool Driver::GetReleaseVersion(StringRef Str,
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004285 MutableArrayRef<unsigned> Digits) {
Mehdi Amini12011172016-10-06 05:11:48 +00004286 if (Str.empty())
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004287 return false;
4288
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004289 unsigned CurDigit = 0;
4290 while (CurDigit < Digits.size()) {
Mehdi Amini12011172016-10-06 05:11:48 +00004291 unsigned Digit;
4292 if (Str.consumeInteger(10, Digit))
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004293 return false;
Mehdi Amini12011172016-10-06 05:11:48 +00004294 Digits[CurDigit] = Digit;
4295 if (Str.empty())
4296 return true;
4297 if (Str[0] != '.')
4298 return false;
4299 Str = Str.drop_front(1);
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004300 CurDigit++;
4301 }
4302
4303 // More digits than requested, bail out...
4304 return false;
4305}
4306
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004307std::pair<unsigned, unsigned> Driver::getIncludeExcludeOptionFlagMasks() const {
4308 unsigned IncludedFlagsBitmask = 0;
Rafael Espindolacc707bc2013-09-25 15:54:41 +00004309 unsigned ExcludedFlagsBitmask = options::NoDriverOption;
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004310
4311 if (Mode == CLMode) {
Hans Wennborg19076102013-07-31 20:51:53 +00004312 // Include CL and Core options.
4313 IncludedFlagsBitmask |= options::CLOption;
4314 IncludedFlagsBitmask |= options::CoreOption;
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004315 } else {
4316 ExcludedFlagsBitmask |= options::CLOption;
4317 }
4318
4319 return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
4320}
Benjamin Kramerab88f622014-03-25 18:02:07 +00004321
Douglas Katzmanf08fadf2015-06-04 14:40:44 +00004322bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
Benjamin Kramerab88f622014-03-25 18:02:07 +00004323 return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);
4324}