blob: 5eaa483229bb9716f271c806dfa06dff793710e3 [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"
David Blaikie79000202011-09-23 05:57:42 +000065#include "llvm/Support/ErrorHandling.h"
Michael J. Spencerf28df4c2010-12-17 21:22:22 +000066#include "llvm/Support/FileSystem.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000067#include "llvm/Support/Path.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000068#include "llvm/Support/PrettyStackTrace.h"
Hans Wennborg23d26a32014-06-18 17:21:50 +000069#include "llvm/Support/Process.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000070#include "llvm/Support/Program.h"
Dimitry Andric81c40422017-06-06 21:54:21 +000071#include "llvm/Support/TargetRegistry.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000072#include "llvm/Support/raw_ostream.h"
Dylan Noblesmith4f4e7452012-02-02 00:40:14 +000073#include <map>
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000074#include <memory>
Benjamin Kramercfeacf52016-05-27 14:27:13 +000075#include <utility>
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +000076#if LLVM_ON_UNIX
77#include <unistd.h> // getpid
78#endif
Dylan Noblesmith86780e92012-02-01 14:25:28 +000079
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000080using namespace clang::driver;
Chris Lattnerada1c912009-03-26 05:56:24 +000081using namespace clang;
Reid Kleckner898229a2013-06-14 17:17:23 +000082using namespace llvm::opt;
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000083
Reid Kleckner68eb60b2015-02-02 22:41:48 +000084Driver::Driver(StringRef ClangExecutable, StringRef DefaultTargetTriple,
Benjamin Kramerd45b2052015-10-07 15:48:01 +000085 DiagnosticsEngine &Diags,
86 IntrusiveRefCntPtr<vfs::FileSystem> VFS)
Benjamin Kramercfeacf52016-05-27 14:27:13 +000087 : Opts(createDriverOptTable()), Diags(Diags), VFS(std::move(VFS)),
88 Mode(GCCMode), SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
89 LTOMode(LTOK_None), ClangExecutable(ClangExecutable),
Nico Webere0c3f902017-07-23 16:31:47 +000090 SysRoot(DEFAULT_SYSROOT),
Reid Kleckner68eb60b2015-02-02 22:41:48 +000091 DriverTitle("clang LLVM compiler"), CCPrintOptionsFilename(nullptr),
92 CCPrintHeadersFilename(nullptr), CCLogDiagnosticsFilename(nullptr),
93 CCCPrintBindings(false), CCPrintHeaders(false), CCLogDiagnostics(false),
Vedant Kumarf2030b92016-07-18 19:56:33 +000094 CCGenDiagnostics(false), DefaultTargetTriple(DefaultTargetTriple),
95 CCCGenericGCCName(""), CheckInputsExist(true), CCCUsePCH(true),
Bruno Cardoso Lopes52dfe712017-04-12 21:46:20 +000096 GenReproducer(false), SuppressMissingInputWarning(false) {
Daniel Dunbar3f3e2cd2010-01-20 02:35:16 +000097
Benjamin Kramerd45b2052015-10-07 15:48:01 +000098 // Provide a sane fallback if no VFS is specified.
99 if (!this->VFS)
100 this->VFS = vfs::getRealFileSystem();
101
Sumanth Gundapaneni3a1592942015-03-03 20:43:12 +0000102 Name = llvm::sys::path::filename(ClangExecutable);
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000103 Dir = llvm::sys::path::parent_path(ClangExecutable);
Benjamin Kramerf420dda2015-10-13 15:19:32 +0000104 InstalledDir = Dir; // Provide a sensible default installed dir.
Bob Wilsona20a1da2013-03-23 05:17:59 +0000105
106 // Compute the path to the resource directory.
107 StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
108 SmallString<128> P(Dir);
Chandler Carruthfd3cc702014-12-29 12:09:08 +0000109 if (ClangResourceDir != "") {
Bob Wilsona20a1da2013-03-23 05:17:59 +0000110 llvm::sys::path::append(P, ClangResourceDir);
Chandler Carruthfd3cc702014-12-29 12:09:08 +0000111 } else {
112 StringRef ClangLibdirSuffix(CLANG_LIBDIR_SUFFIX);
Argyrios Kyrtzidisbcae0472017-02-25 18:14:35 +0000113 P = llvm::sys::path::parent_path(Dir);
114 llvm::sys::path::append(P, Twine("lib") + ClangLibdirSuffix, "clang",
Chandler Carruthfd3cc702014-12-29 12:09:08 +0000115 CLANG_VERSION_STRING);
116 }
Bob Wilsona20a1da2013-03-23 05:17:59 +0000117 ResourceDir = P.str();
Daniel Dunbar544ecd12009-03-02 19:59:07 +0000118}
119
Zachary Turneraff19c32016-08-12 17:47:52 +0000120void Driver::ParseDriverMode(StringRef ProgramName,
121 ArrayRef<const char *> Args) {
122 auto Default = ToolChain::getTargetAndModeFromProgramName(ProgramName);
123 StringRef DefaultMode(Default.second);
124 setDriverModeFromOption(DefaultMode);
Hans Wennborg70850d82013-07-18 20:29:38 +0000125
Douglas Katzman6bbffc42015-06-25 18:51:37 +0000126 for (const char *ArgPtr : Args) {
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000127 // Ingore nullptrs, they are response file's EOL markers
Douglas Katzman6bbffc42015-06-25 18:51:37 +0000128 if (ArgPtr == nullptr)
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000129 continue;
Douglas Katzman6bbffc42015-06-25 18:51:37 +0000130 const StringRef Arg = ArgPtr;
Zachary Turneraff19c32016-08-12 17:47:52 +0000131 setDriverModeFromOption(Arg);
Hans Wennborg70850d82013-07-18 20:29:38 +0000132 }
133}
134
Zachary Turneraff19c32016-08-12 17:47:52 +0000135void Driver::setDriverModeFromOption(StringRef Opt) {
136 const std::string OptName =
137 getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
138 if (!Opt.startswith(OptName))
139 return;
140 StringRef Value = Opt.drop_front(OptName.size());
141
142 const unsigned M = llvm::StringSwitch<unsigned>(Value)
143 .Case("gcc", GCCMode)
144 .Case("g++", GXXMode)
145 .Case("cpp", CPPMode)
146 .Case("cl", CLMode)
147 .Default(~0U);
148
149 if (M != ~0U)
150 Mode = static_cast<DriverMode>(M);
151 else
152 Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
153}
154
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000155InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings,
156 bool &ContainsError) {
Daniel Dunbar2608c542009-03-18 01:38:48 +0000157 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000158 ContainsError = false;
Hans Wennborg6ddc6902013-07-27 00:23:45 +0000159
160 unsigned IncludedFlagsBitmask;
161 unsigned ExcludedFlagsBitmask;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000162 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000163 getIncludeExcludeOptionFlagMasks();
Hans Wennborg6ddc6902013-07-27 00:23:45 +0000164
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000165 unsigned MissingArgIndex, MissingArgCount;
David Blaikie69a1d8c2015-06-22 22:07:27 +0000166 InputArgList Args =
David Blaikie6d492ad2015-06-21 06:32:36 +0000167 getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
168 IncludedFlagsBitmask, ExcludedFlagsBitmask);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +0000169
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000170 // Check for missing argument error.
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000171 if (MissingArgCount) {
172 Diag(diag::err_drv_missing_argument)
David Blaikie69a1d8c2015-06-22 22:07:27 +0000173 << Args.getArgString(MissingArgIndex) << MissingArgCount;
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000174 ContainsError |=
175 Diags.getDiagnosticLevel(diag::err_drv_missing_argument,
176 SourceLocation()) > DiagnosticsEngine::Warning;
177 }
Daniel Dunbar65229332009-03-13 11:38:42 +0000178
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000179 // Check for unsupported options.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000180 for (const Arg *A : Args) {
Michael J. Spencer66e2b202012-10-19 22:37:06 +0000181 if (A->getOption().hasFlag(options::Unsupported)) {
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000182 Diag(diag::err_drv_unsupported_opt) << A->getAsString(Args);
183 ContainsError |= Diags.getDiagnosticLevel(diag::err_drv_unsupported_opt,
184 SourceLocation()) >
185 DiagnosticsEngine::Warning;
Daniel Dunbard8500f32009-03-22 23:26:43 +0000186 continue;
187 }
Chad Rosierce975d92012-02-22 17:55:22 +0000188
189 // Warn about -mcpu= without an argument.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000190 if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000191 Diag(diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
192 ContainsError |= Diags.getDiagnosticLevel(
193 diag::warn_drv_empty_joined_argument,
194 SourceLocation()) > DiagnosticsEngine::Warning;
Chad Rosierce975d92012-02-22 17:55:22 +0000195 }
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000196 }
197
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000198 for (const Arg *A : Args.filtered(options::OPT_UNKNOWN)) {
199 auto ID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl
200 : diag::err_drv_unknown_argument;
201
202 Diags.Report(ID) << A->getAsString(Args);
203 ContainsError |= Diags.getDiagnosticLevel(ID, SourceLocation()) >
204 DiagnosticsEngine::Warning;
205 }
Rafael Espindola8a2d4962013-09-23 23:55:25 +0000206
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000207 return Args;
208}
209
Chad Rosier7742b5d2011-07-27 23:36:45 +0000210// Determine which compilation mode we are in. We look for options which
211// affect the phase, starting with the earliest phases, and record which
212// option we used to determine the final phase.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000213phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
214 Arg **FinalPhaseArg) const {
Craig Topper92fc2df2014-05-17 16:56:41 +0000215 Arg *PhaseArg = nullptr;
Chad Rosier7742b5d2011-07-27 23:36:45 +0000216 phases::ID FinalPhase;
Eric Christopherf901e852011-08-17 22:59:59 +0000217
Hans Wennborge50cec32014-06-13 20:59:54 +0000218 // -{E,EP,P,M,MM} only run the preprocessor.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000219 if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
Hans Wennborge50cec32014-06-13 20:59:54 +0000220 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
Hans Wennborge0053472013-12-20 18:40:46 +0000221 (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
222 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000223 FinalPhase = phases::Preprocess;
Eric Christopherf901e852011-08-17 22:59:59 +0000224
Richard Smithdd4ad3d2016-08-30 19:06:26 +0000225 // --precompile only runs up to precompilation.
226 } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile))) {
227 FinalPhase = phases::Precompile;
228
Bob Wilson23a55f12014-12-21 07:00:00 +0000229 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
Chad Rosier7742b5d2011-07-27 23:36:45 +0000230 } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000231 (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
Ben Langmuir2cb4a782014-02-05 22:21:15 +0000232 (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
Chad Rosier7742b5d2011-07-27 23:36:45 +0000233 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
Fariborz Jahanian73223bb2012-04-02 15:59:19 +0000234 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
Ted Kremenekf7639e12012-03-06 20:06:33 +0000235 (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
Chad Rosier7742b5d2011-07-27 23:36:45 +0000236 (PhaseArg = DAL.getLastArg(options::OPT__analyze,
Chad Rosier1aeb15a2012-03-06 23:14:35 +0000237 options::OPT__analyze_auto)) ||
Bob Wilson23a55f12014-12-21 07:00:00 +0000238 (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000239 FinalPhase = phases::Compile;
240
Bob Wilson23a55f12014-12-21 07:00:00 +0000241 // -S only runs up to the backend.
242 } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
243 FinalPhase = phases::Backend;
244
Artem Belevich4242f412015-07-28 21:01:21 +0000245 // -c compilation only runs up to the assembler.
246 } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000247 FinalPhase = phases::Assemble;
248
249 // Otherwise do everything.
250 } else
251 FinalPhase = phases::Link;
252
253 if (FinalPhaseArg)
254 *FinalPhaseArg = PhaseArg;
255
256 return FinalPhase;
257}
258
David Blaikie0aaa7622017-01-13 17:34:15 +0000259static Arg *MakeInputArg(DerivedArgList &Args, OptTable &Opts,
Hans Wennborged1d0722013-08-13 21:32:29 +0000260 StringRef Value) {
David Blaikie0aaa7622017-01-13 17:34:15 +0000261 Arg *A = new Arg(Opts.getOption(options::OPT_INPUT), Value,
Hans Wennborged1d0722013-08-13 21:32:29 +0000262 Args.getBaseArgs().MakeIndex(Value), Value.data());
Hans Wennborg55362852014-05-02 22:55:30 +0000263 Args.AddSynthesizedArg(A);
Hans Wennborged1d0722013-08-13 21:32:29 +0000264 A->claim();
265 return A;
266}
267
Daniel Dunbar775d4062010-06-11 22:00:26 +0000268DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
269 DerivedArgList *DAL = new DerivedArgList(Args);
270
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000271 bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
Nirav Daveb0bb6142015-11-24 16:07:21 +0000272 bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +0000273 for (Arg *A : Args) {
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000274 // Unfortunately, we have to parse some forwarding options (-Xassembler,
275 // -Xlinker, -Xpreprocessor) because we either integrate their functionality
276 // (assembler and preprocessor), or bypass a previous driver ('collect2').
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000277
278 // Rewrite linker options, to replace --no-demangle with a custom internal
279 // option.
280 if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
281 A->getOption().matches(options::OPT_Xlinker)) &&
282 A->containsValue("--no-demangle")) {
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000283 // Add the rewritten no-demangle argument.
284 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
285
286 // Add the remaining values as Xlinker arguments.
Benjamin Kramer72e64312015-09-24 14:48:49 +0000287 for (StringRef Val : A->getValues())
Douglas Katzmana34b7bf2015-06-30 19:32:57 +0000288 if (Val != "--no-demangle")
289 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), Val);
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000290
291 continue;
292 }
293
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000294 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
295 // some build systems. We don't try to be complete here because we don't
296 // care to encourage this usage model.
297 if (A->getOption().matches(options::OPT_Wp_COMMA) &&
Richard Smithbd55daf2012-11-01 04:30:05 +0000298 (A->getValue(0) == StringRef("-MD") ||
299 A->getValue(0) == StringRef("-MMD"))) {
Daniel Dunbar3648ba72010-06-15 20:30:18 +0000300 // Rewrite to -MD/-MMD along with -MF.
Richard Smithbd55daf2012-11-01 04:30:05 +0000301 if (A->getValue(0) == StringRef("-MD"))
Daniel Dunbar3648ba72010-06-15 20:30:18 +0000302 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
303 else
304 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
Michael J. Spencer70d85be2012-11-07 23:37:14 +0000305 if (A->getNumValues() == 2)
306 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
307 A->getValue(1));
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000308 continue;
309 }
310
Shantonu Senafeb03b2010-09-17 18:39:08 +0000311 // Rewrite reserved library names.
312 if (A->getOption().matches(options::OPT_l)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000313 StringRef Value = A->getValue();
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000314
Shantonu Senafeb03b2010-09-17 18:39:08 +0000315 // Rewrite unless -nostdlib is present.
Nirav Daveb0bb6142015-11-24 16:07:21 +0000316 if (!HasNostdlib && !HasNodefaultlib && Value == "stdc++") {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000317 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_stdcxx));
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000318 continue;
319 }
Shantonu Senafeb03b2010-09-17 18:39:08 +0000320
321 // Rewrite unconditionally.
322 if (Value == "cc_kext") {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000323 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_cckext));
Shantonu Senafeb03b2010-09-17 18:39:08 +0000324 continue;
325 }
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000326 }
327
Hans Wennborged1d0722013-08-13 21:32:29 +0000328 // Pick up inputs via the -- option.
329 if (A->getOption().matches(options::OPT__DASH_DASH)) {
330 A->claim();
Benjamin Kramer72e64312015-09-24 14:48:49 +0000331 for (StringRef Val : A->getValues())
David Blaikie0aaa7622017-01-13 17:34:15 +0000332 DAL->append(MakeInputArg(*DAL, *Opts, Val));
Hans Wennborged1d0722013-08-13 21:32:29 +0000333 continue;
334 }
335
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +0000336 DAL->append(A);
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000337 }
Daniel Dunbar775d4062010-06-11 22:00:26 +0000338
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000339 // Enforce -static if -miamcu is present.
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000340 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false))
341 DAL->AddFlagArg(0, Opts->getOption(options::OPT_static));
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000342
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000343// Add a default value of -mlinker-version=, if one was given and the user
344// didn't specify one.
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000345#if defined(HOST_LINK_VERSION)
Tim Northover018578c2015-06-12 19:21:35 +0000346 if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
347 strlen(HOST_LINK_VERSION) > 0) {
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000348 DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
349 HOST_LINK_VERSION);
Daniel Dunbarb613ffc2010-08-17 22:32:45 +0000350 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000351 }
352#endif
353
Daniel Dunbar775d4062010-06-11 22:00:26 +0000354 return DAL;
355}
356
Artem Belevich959e0542015-07-10 19:47:55 +0000357/// \brief Compute target triple from args.
358///
359/// This routine provides the logic to compute a target triple from various
360/// args passed to the driver and the default triple string.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000361static llvm::Triple computeTargetTriple(const Driver &D,
362 StringRef DefaultTargetTriple,
Artem Belevich959e0542015-07-10 19:47:55 +0000363 const ArgList &Args,
364 StringRef DarwinArchName = "") {
365 // FIXME: Already done in Compilation *Driver::BuildCompilation
366 if (const Arg *A = Args.getLastArg(options::OPT_target))
367 DefaultTargetTriple = A->getValue();
368
369 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
370
371 // Handle Apple-specific options available here.
372 if (Target.isOSBinFormatMachO()) {
373 // If an explict Darwin arch name is given, that trumps all.
374 if (!DarwinArchName.empty()) {
375 tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
376 return Target;
377 }
378
379 // Handle the Darwin '-arch' flag.
380 if (Arg *A = Args.getLastArg(options::OPT_arch)) {
381 StringRef ArchName = A->getValue();
382 tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
383 }
384 }
385
386 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
387 // '-mbig-endian'/'-EB'.
388 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
389 options::OPT_mbig_endian)) {
390 if (A->getOption().matches(options::OPT_mlittle_endian)) {
391 llvm::Triple LE = Target.getLittleEndianArchVariant();
392 if (LE.getArch() != llvm::Triple::UnknownArch)
393 Target = std::move(LE);
394 } else {
395 llvm::Triple BE = Target.getBigEndianArchVariant();
396 if (BE.getArch() != llvm::Triple::UnknownArch)
397 Target = std::move(BE);
398 }
399 }
400
401 // Skip further flag support on OSes which don't support '-m32' or '-m64'.
Douglas Katzman15a63ed2015-08-12 18:36:12 +0000402 if (Target.getArch() == llvm::Triple::tce ||
403 Target.getOS() == llvm::Triple::Minix)
Artem Belevich959e0542015-07-10 19:47:55 +0000404 return Target;
405
406 // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000407 Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
408 options::OPT_m32, options::OPT_m16);
409 if (A) {
Artem Belevich959e0542015-07-10 19:47:55 +0000410 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
411
412 if (A->getOption().matches(options::OPT_m64)) {
413 AT = Target.get64BitArchVariant().getArch();
414 if (Target.getEnvironment() == llvm::Triple::GNUX32)
415 Target.setEnvironment(llvm::Triple::GNU);
416 } else if (A->getOption().matches(options::OPT_mx32) &&
417 Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
418 AT = llvm::Triple::x86_64;
419 Target.setEnvironment(llvm::Triple::GNUX32);
420 } else if (A->getOption().matches(options::OPT_m32)) {
421 AT = Target.get32BitArchVariant().getArch();
422 if (Target.getEnvironment() == llvm::Triple::GNUX32)
423 Target.setEnvironment(llvm::Triple::GNU);
424 } else if (A->getOption().matches(options::OPT_m16) &&
425 Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
426 AT = llvm::Triple::x86;
427 Target.setEnvironment(llvm::Triple::CODE16);
428 }
429
430 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
431 Target.setArch(AT);
432 }
433
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000434 // Handle -miamcu flag.
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000435 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
436 if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
437 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
438 << Target.str();
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000439
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000440 if (A && !A->getOption().matches(options::OPT_m32))
441 D.Diag(diag::err_drv_argument_not_allowed_with)
442 << "-miamcu" << A->getBaseArg().getAsString(Args);
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000443
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000444 Target.setArch(llvm::Triple::x86);
445 Target.setArchName("i586");
446 Target.setEnvironment(llvm::Triple::UnknownEnvironment);
447 Target.setEnvironmentName("");
448 Target.setOS(llvm::Triple::ELFIAMCU);
449 Target.setVendor(llvm::Triple::UnknownVendor);
450 Target.setVendorName("intel");
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000451 }
452
Artem Belevich959e0542015-07-10 19:47:55 +0000453 return Target;
454}
455
Teresa Johnson945bc502015-10-15 20:35:53 +0000456// \brief Parse the LTO options and record the type of LTO compilation
457// based on which -f(no-)?lto(=.*)? option occurs last.
458void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
459 LTOMode = LTOK_None;
460 if (!Args.hasFlag(options::OPT_flto, options::OPT_flto_EQ,
461 options::OPT_fno_lto, false))
462 return;
463
464 StringRef LTOName("full");
465
466 const Arg *A = Args.getLastArg(options::OPT_flto_EQ);
Teresa Johnson6ef80dc2015-11-02 18:03:12 +0000467 if (A)
468 LTOName = A->getValue();
Teresa Johnson945bc502015-10-15 20:35:53 +0000469
470 LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
471 .Case("full", LTOK_Full)
472 .Case("thin", LTOK_Thin)
473 .Default(LTOK_Unknown);
474
475 if (LTOMode == LTOK_Unknown) {
476 assert(A);
477 Diag(diag::err_drv_unsupported_option_argument) << A->getOption().getName()
478 << A->getValue();
479 }
480}
481
Samuel Antao39f9da22016-10-27 16:38:05 +0000482/// Compute the desired OpenMP runtime from the flags provided.
483Driver::OpenMPRuntimeKind Driver::getOpenMPRuntime(const ArgList &Args) const {
484 StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
485
486 const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
487 if (A)
488 RuntimeName = A->getValue();
489
490 auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
491 .Case("libomp", OMPRT_OMP)
492 .Case("libgomp", OMPRT_GOMP)
493 .Case("libiomp5", OMPRT_IOMP5)
494 .Default(OMPRT_Unknown);
495
496 if (RT == OMPRT_Unknown) {
497 if (A)
498 Diag(diag::err_drv_unsupported_option_argument)
499 << A->getOption().getName() << A->getValue();
500 else
501 // FIXME: We could use a nicer diagnostic here.
502 Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
503 }
504
505 return RT;
506}
507
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000508void Driver::CreateOffloadingDeviceToolChains(Compilation &C,
509 InputList &Inputs) {
510
511 //
512 // CUDA
513 //
514 // We need to generate a CUDA toolchain if any of the inputs has a CUDA type.
515 if (llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
516 return types::isCuda(I.first);
517 })) {
Justin Lebar66c4fd72016-11-18 00:41:22 +0000518 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
519 const llvm::Triple &HostTriple = HostTC->getTriple();
520 llvm::Triple CudaTriple(HostTriple.isArch64Bit() ? "nvptx64-nvidia-cuda"
521 : "nvptx-nvidia-cuda");
522 // Use the CUDA and host triples as the key into the ToolChains map, because
523 // the device toolchain we create depends on both.
David Blaikie6ad71012017-01-13 18:53:43 +0000524 auto &CudaTC = ToolChains[CudaTriple.str() + "/" + HostTriple.str()];
Justin Lebar66c4fd72016-11-18 00:41:22 +0000525 if (!CudaTC) {
David Blaikie6ad71012017-01-13 18:53:43 +0000526 CudaTC = llvm::make_unique<toolchains::CudaToolChain>(
527 *this, CudaTriple, *HostTC, C.getInputArgs());
Justin Lebar66c4fd72016-11-18 00:41:22 +0000528 }
David Blaikie6ad71012017-01-13 18:53:43 +0000529 C.addOffloadDeviceToolChain(CudaTC.get(), Action::OFK_Cuda);
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000530 }
531
532 //
Samuel Antao39f9da22016-10-27 16:38:05 +0000533 // OpenMP
534 //
535 // We need to generate an OpenMP toolchain if the user specified targets with
536 // the -fopenmp-targets option.
537 if (Arg *OpenMPTargets =
538 C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
539 if (OpenMPTargets->getNumValues()) {
540 // We expect that -fopenmp-targets is always used in conjunction with the
541 // option -fopenmp specifying a valid runtime with offloading support,
542 // i.e. libomp or libiomp.
543 bool HasValidOpenMPRuntime = C.getInputArgs().hasFlag(
544 options::OPT_fopenmp, options::OPT_fopenmp_EQ,
545 options::OPT_fno_openmp, false);
546 if (HasValidOpenMPRuntime) {
547 OpenMPRuntimeKind OpenMPKind = getOpenMPRuntime(C.getInputArgs());
548 HasValidOpenMPRuntime =
549 OpenMPKind == OMPRT_OMP || OpenMPKind == OMPRT_IOMP5;
550 }
551
552 if (HasValidOpenMPRuntime) {
553 llvm::StringMap<const char *> FoundNormalizedTriples;
554 for (const char *Val : OpenMPTargets->getValues()) {
555 llvm::Triple TT(Val);
556 std::string NormalizedName = TT.normalize();
557
558 // Make sure we don't have a duplicate triple.
559 auto Duplicate = FoundNormalizedTriples.find(NormalizedName);
560 if (Duplicate != FoundNormalizedTriples.end()) {
561 Diag(clang::diag::warn_drv_omp_offload_target_duplicate)
562 << Val << Duplicate->second;
563 continue;
564 }
565
566 // Store the current triple so that we can check for duplicates in the
567 // following iterations.
568 FoundNormalizedTriples[NormalizedName] = Val;
569
570 // If the specified target is invalid, emit a diagnostic.
571 if (TT.getArch() == llvm::Triple::UnknownArch)
572 Diag(clang::diag::err_drv_invalid_omp_target) << Val;
573 else {
Gheorghe-Teodor Bercea6a5df722017-07-06 16:08:15 +0000574 const ToolChain *TC;
575 // CUDA toolchains have to be selected differently. They pair host
576 // and device in their implementation.
577 if (TT.isNVPTX()) {
578 const ToolChain *HostTC =
579 C.getSingleOffloadToolChain<Action::OFK_Host>();
580 assert(HostTC && "Host toolchain should be always defined.");
581 auto &CudaTC =
582 ToolChains[TT.str() + "/" + HostTC->getTriple().str()];
583 if (!CudaTC)
584 CudaTC = llvm::make_unique<toolchains::CudaToolChain>(
585 *this, TT, *HostTC, C.getInputArgs());
586 TC = CudaTC.get();
587 } else
588 TC = &getToolChain(C.getInputArgs(), TT);
589 C.addOffloadDeviceToolChain(TC, Action::OFK_OpenMP);
Samuel Antao39f9da22016-10-27 16:38:05 +0000590 }
591 }
592 } else
593 Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
594 } else
595 Diag(clang::diag::warn_drv_empty_joined_argument)
596 << OpenMPTargets->getAsString(C.getInputArgs());
597 }
598
599 //
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000600 // TODO: Add support for other offloading programming models here.
601 //
602
603 return;
604}
605
Chris Lattner54b16772011-07-23 17:14:25 +0000606Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
Daniel Dunbar2608c542009-03-18 01:38:48 +0000607 llvm::PrettyStackTraceString CrashInfo("Compilation construction");
608
Eric Christopherf901e852011-08-17 22:59:59 +0000609 // FIXME: Handle environment options which affect driver behavior, somewhere
Bill Wendlingadbeb9f2012-03-12 21:24:57 +0000610 // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
Chad Rosier82301162011-09-14 00:47:55 +0000611
David Majnemer85c25b42016-07-24 17:44:03 +0000612 if (Optional<std::string> CompilerPathValue =
613 llvm::sys::Process::GetEnv("COMPILER_PATH")) {
614 StringRef CompilerPath = *CompilerPathValue;
Chad Rosier82301162011-09-14 00:47:55 +0000615 while (!CompilerPath.empty()) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000616 std::pair<StringRef, StringRef> Split =
617 CompilerPath.split(llvm::sys::EnvPathSeparator);
Chad Rosier82301162011-09-14 00:47:55 +0000618 PrefixDirs.push_back(Split.first);
619 CompilerPath = Split.second;
620 }
621 }
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +0000622
Hans Wennborg70850d82013-07-18 20:29:38 +0000623 // We look for the driver mode option early, because the mode can affect
624 // how other options are parsed.
Zachary Turneraff19c32016-08-12 17:47:52 +0000625 ParseDriverMode(ClangExecutable, ArgList.slice(1));
Hans Wennborg70850d82013-07-18 20:29:38 +0000626
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +0000627 // FIXME: What are we going to do with -V and -b?
628
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +0000629 // FIXME: This stuff needs to go into the Compilation, not the driver.
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +0000630 bool CCCPrintPhases;
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000631
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000632 bool ContainsError;
633 InputArgList Args = ParseArgStrings(ArgList.slice(1), ContainsError);
Daniel Dunbaracd69572009-12-04 21:55:23 +0000634
Filipe Cabecinhas136f35e2015-07-18 06:35:24 +0000635 // Silence driver warnings if requested
636 Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w));
637
Rafael Espindola59ae7992009-12-07 18:28:29 +0000638 // -no-canonical-prefixes is used very early in main.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000639 Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
Rafael Espindola59ae7992009-12-07 18:28:29 +0000640
Daniel Dunbar926f81f2010-08-02 02:38:03 +0000641 // Ignore -pipe.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000642 Args.ClaimAllArgs(options::OPT_pipe);
Daniel Dunbar926f81f2010-08-02 02:38:03 +0000643
Daniel Dunbaracd69572009-12-04 21:55:23 +0000644 // Extract -ccc args.
Daniel Dunbaree66cf22009-03-10 20:52:46 +0000645 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +0000646 // FIXME: We need to figure out where this behavior should live. Most of it
647 // should be outside in the client; the parts that aren't should have proper
648 // options, either by introducing new ones or by overloading gcc ones like -V
649 // or -b.
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +0000650 CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
David Blaikie69a1d8c2015-06-22 22:07:27 +0000651 CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
652 if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
Richard Smithbd55daf2012-11-01 04:30:05 +0000653 CCCGenericGCCName = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000654 CCCUsePCH =
655 Args.hasFlag(options::OPT_ccc_pch_is_pch, options::OPT_ccc_pch_is_pth);
Bruno Cardoso Lopes52dfe712017-04-12 21:46:20 +0000656 GenReproducer = Args.hasFlag(options::OPT_gen_reproducer,
657 options::OPT_fno_crash_diagnostics,
658 !!::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH"));
Joerg Sonnenberger17d75512012-02-22 19:15:16 +0000659 // FIXME: DefaultTargetTriple is used by the target-prefixed calls to as/ld
660 // and getToolChain is const.
Hans Wennborg2e274592013-08-13 23:38:57 +0000661 if (IsCLMode()) {
Hans Wennborg73609a02014-03-28 01:19:04 +0000662 // clang-cl targets MSVC-style Win32.
Hans Wennborg2e274592013-08-13 23:38:57 +0000663 llvm::Triple T(DefaultTargetTriple);
Hans Wennborg9d9ce7a2014-03-28 20:49:28 +0000664 T.setOS(llvm::Triple::Win32);
Hans Wennborg0f0e8d62015-09-18 17:11:50 +0000665 T.setVendor(llvm::Triple::PC);
Hans Wennborg9d9ce7a2014-03-28 20:49:28 +0000666 T.setEnvironment(llvm::Triple::MSVC);
Hans Wennborg2e274592013-08-13 23:38:57 +0000667 DefaultTargetTriple = T.str();
668 }
David Blaikie69a1d8c2015-06-22 22:07:27 +0000669 if (const Arg *A = Args.getLastArg(options::OPT_target))
Richard Smithbd55daf2012-11-01 04:30:05 +0000670 DefaultTargetTriple = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000671 if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
Richard Smithbd55daf2012-11-01 04:30:05 +0000672 Dir = InstalledDir = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000673 for (const Arg *A : Args.filtered(options::OPT_B)) {
Benjamin Kramer1a648d12011-02-08 20:31:42 +0000674 A->claim();
Richard Smithbd55daf2012-11-01 04:30:05 +0000675 PrefixDirs.push_back(A->getValue(0));
Benjamin Kramer1a648d12011-02-08 20:31:42 +0000676 }
David Blaikie69a1d8c2015-06-22 22:07:27 +0000677 if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
Richard Smithbd55daf2012-11-01 04:30:05 +0000678 SysRoot = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000679 if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
Peter Collingbourne9d9e1fc2013-05-27 21:40:20 +0000680 DyldPrefix = A->getValue();
Daniel Dunbaree66cf22009-03-10 20:52:46 +0000681
David Blaikie69a1d8c2015-06-22 22:07:27 +0000682 if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
Bob Wilsona20a1da2013-03-23 05:17:59 +0000683 ResourceDir = A->getValue();
Jim Grosbach061dabf2013-03-12 20:17:58 +0000684
David Blaikie69a1d8c2015-06-22 22:07:27 +0000685 if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
Reid Kleckner68eb60b2015-02-02 22:41:48 +0000686 SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
687 .Case("cwd", SaveTempsCwd)
688 .Case("obj", SaveTempsObj)
689 .Default(SaveTempsCwd);
690 }
691
Steven Wu1257cd82016-05-18 17:04:52 +0000692 setLTOMode(Args);
693
Steven Wu844ab6a2016-11-16 06:06:44 +0000694 // Process -fembed-bitcode= flags.
695 if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
696 StringRef Name = A->getValue();
697 unsigned Model = llvm::StringSwitch<unsigned>(Name)
698 .Case("off", EmbedNone)
699 .Case("all", EmbedBitcode)
700 .Case("bitcode", EmbedBitcode)
701 .Case("marker", EmbedMarker)
702 .Default(~0U);
703 if (Model == ~0U) {
704 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
705 << Name;
706 } else
707 BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
Steven Wu574b0f22016-03-01 01:07:58 +0000708 }
709
David Blaikie69a1d8c2015-06-22 22:07:27 +0000710 std::unique_ptr<llvm::opt::InputArgList> UArgs =
711 llvm::make_unique<InputArgList>(std::move(Args));
712
Daniel Dunbar775d4062010-06-11 22:00:26 +0000713 // Perform the default argument translations.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000714 DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
Daniel Dunbar775d4062010-06-11 22:00:26 +0000715
Chandler Carruthcb916192012-01-25 08:49:21 +0000716 // Owned by the host.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000717 const ToolChain &TC = getToolChain(
718 *UArgs, computeTargetTriple(*this, DefaultTargetTriple, *UArgs));
Chandler Carruthcb916192012-01-25 08:49:21 +0000719
Daniel Dunbar3ce436d2009-03-16 06:42:30 +0000720 // The compilation takes ownership of Args.
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000721 Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs,
722 ContainsError);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +0000723
Daniel Dunbarf0eddb82009-03-18 02:55:38 +0000724 if (!HandleImmediateArgs(*C))
725 return C;
726
Chad Rosierecdede82011-08-12 22:08:57 +0000727 // Construct the list of inputs.
728 InputList Inputs;
Hans Wennborged1d0722013-08-13 21:32:29 +0000729 BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
Chad Rosierecdede82011-08-12 22:08:57 +0000730
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000731 // Populate the tool chains for the offloading devices, if any.
732 CreateOffloadingDeviceToolChains(*C, Inputs);
Justin Lebar0e450a52016-03-30 23:30:25 +0000733
Chandler Carruth7f1417f2012-01-24 10:43:44 +0000734 // Construct the list of abstract actions to perform for this compilation. On
Tim Northover157d9112014-01-16 08:48:16 +0000735 // MachO targets this uses the driver-driver and universal actions.
736 if (TC.getTriple().isOSBinFormatMachO())
Artem Belevich5e2a3ec2015-11-17 22:28:40 +0000737 BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +0000738 else
Justin Lebar0f3474c2016-02-11 02:00:50 +0000739 BuildActions(*C, C->getArgs(), Inputs, C->getActions());
Daniel Dunbarf0eddb82009-03-18 02:55:38 +0000740
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +0000741 if (CCCPrintPhases) {
Daniel Dunbareb843be2009-03-18 03:13:20 +0000742 PrintActions(*C);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +0000743 return C;
744 }
745
746 BuildJobs(*C);
Daniel Dunbaradc91e62009-03-15 01:38:15 +0000747
748 return C;
Daniel Dunbaree66cf22009-03-10 20:52:46 +0000749}
750
Justin Bognered9cbe02015-07-09 06:58:31 +0000751static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
752 llvm::opt::ArgStringList ASL;
753 for (const auto *A : Args)
754 A->render(Args, ASL);
755
756 for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
757 if (I != ASL.begin())
758 OS << ' ';
759 Command::printArg(OS, *I, true);
760 }
761 OS << '\n';
762}
763
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +0000764bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename,
765 SmallString<128> &CrashDiagDir) {
766 using namespace llvm::sys;
767 assert(llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin() &&
768 "Only knows about .crash files on Darwin");
769
770 // The .crash file can be found on at ~/Library/Logs/DiagnosticReports/
771 // (or /Library/Logs/DiagnosticReports for root) and has the filename pattern
772 // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash.
773 path::home_directory(CrashDiagDir);
774 if (CrashDiagDir.startswith("/var/root"))
775 CrashDiagDir = "/";
776 path::append(CrashDiagDir, "Library/Logs/DiagnosticReports");
777 int PID =
778#if LLVM_ON_UNIX
779 getpid();
780#else
781 0;
782#endif
783 std::error_code EC;
784 fs::file_status FileStatus;
785 TimePoint<> LastAccessTime;
786 SmallString<128> CrashFilePath;
787 // Lookup the .crash files and get the one generated by a subprocess spawned
788 // by this driver invocation.
789 for (fs::directory_iterator File(CrashDiagDir, EC), FileEnd;
790 File != FileEnd && !EC; File.increment(EC)) {
791 StringRef FileName = path::filename(File->path());
792 if (!FileName.startswith(Name))
793 continue;
794 if (fs::status(File->path(), FileStatus))
795 continue;
796 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CrashFile =
797 llvm::MemoryBuffer::getFile(File->path());
798 if (!CrashFile)
799 continue;
800 // The first line should start with "Process:", otherwise this isn't a real
801 // .crash file.
802 StringRef Data = CrashFile.get()->getBuffer();
803 if (!Data.startswith("Process:"))
804 continue;
805 // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]"
806 size_t ParentProcPos = Data.find("Parent Process:");
807 if (ParentProcPos == StringRef::npos)
808 continue;
809 size_t LineEnd = Data.find_first_of("\n", ParentProcPos);
810 if (LineEnd == StringRef::npos)
811 continue;
812 StringRef ParentProcess = Data.slice(ParentProcPos+15, LineEnd).trim();
813 int OpenBracket = -1, CloseBracket = -1;
814 for (size_t i = 0, e = ParentProcess.size(); i < e; ++i) {
815 if (ParentProcess[i] == '[')
816 OpenBracket = i;
817 if (ParentProcess[i] == ']')
818 CloseBracket = i;
819 }
820 // Extract the parent process PID from the .crash file and check whether
821 // it matches this driver invocation pid.
822 int CrashPID;
823 if (OpenBracket < 0 || CloseBracket < 0 ||
824 ParentProcess.slice(OpenBracket + 1, CloseBracket)
825 .getAsInteger(10, CrashPID) || CrashPID != PID) {
826 continue;
827 }
828
829 // Found a .crash file matching the driver pid. To avoid getting an older
830 // and misleading crash file, continue looking for the most recent.
831 // FIXME: the driver can dispatch multiple cc1 invocations, leading to
832 // multiple crashes poiting to the same parent process. Since the driver
833 // does not collect pid information for the dispatched invocation there's
834 // currently no way to distinguish among them.
835 const auto FileAccessTime = FileStatus.getLastModificationTime();
836 if (FileAccessTime > LastAccessTime) {
837 CrashFilePath.assign(File->path());
838 LastAccessTime = FileAccessTime;
839 }
840 }
841
842 // If found, copy it over to the location of other reproducer files.
843 if (!CrashFilePath.empty()) {
844 EC = fs::copy_file(CrashFilePath, ReproCrashFilename);
845 if (EC)
846 return false;
847 return true;
848 }
849
850 return false;
851}
852
Eric Christopherf901e852011-08-17 22:59:59 +0000853// When clang crashes, produce diagnostic information including the fully
854// preprocessed source file(s). Request that the developer attach the
Chad Rosierbe10f982011-08-02 17:58:04 +0000855// diagnostic information to a bug report.
856void Driver::generateCompilationDiagnostics(Compilation &C,
Justin Bognere1a33d12014-10-20 21:02:05 +0000857 const Command &FailingCommand) {
Chad Rosier877c0a22012-02-22 00:30:39 +0000858 if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
Chad Rosier62135492012-07-09 17:31:28 +0000859 return;
Chad Rosierbee5a1d2012-03-07 00:30:40 +0000860
Chad Rosierdbf46a12013-02-01 18:30:26 +0000861 // Don't try to generate diagnostics for link or dsymutil jobs.
Justin Bognere1a33d12014-10-20 21:02:05 +0000862 if (FailingCommand.getCreator().isLinkJob() ||
863 FailingCommand.getCreator().isDsymutilJob())
Chad Rosier877c0a22012-02-22 00:30:39 +0000864 return;
865
Chad Rosier8179f112012-06-19 17:51:34 +0000866 // Print the version of the compiler.
867 PrintVersion(C, llvm::errs());
868
Chad Rosierbe10f982011-08-02 17:58:04 +0000869 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000870 << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the "
871 "crash backtrace, preprocessed source, and associated run script.";
Chad Rosierbe10f982011-08-02 17:58:04 +0000872
873 // Suppress driver output and emit preprocessor output to temp file.
Hans Wennborg70850d82013-07-18 20:29:38 +0000874 Mode = CPPMode;
Chad Rosierbe10f982011-08-02 17:58:04 +0000875 CCGenDiagnostics = true;
876
Chad Rosiercdb008d2011-11-02 21:29:05 +0000877 // Save the original job command(s).
Justin Bogner25645152014-10-21 17:24:44 +0000878 Command Cmd = FailingCommand;
Chad Rosiercdb008d2011-11-02 21:29:05 +0000879
Richard Smith5bb4cdf2012-12-20 02:22:15 +0000880 // Keep track of whether we produce any errors while trying to produce
881 // preprocessed sources.
882 DiagnosticErrorTrap Trap(Diags);
883
884 // Suppress tool output.
Chad Rosierbe10f982011-08-02 17:58:04 +0000885 C.initCompilationForDiagnostics();
Chad Rosierecdede82011-08-12 22:08:57 +0000886
887 // Construct the list of inputs.
888 InputList Inputs;
889 BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
Chad Rosierbe10f982011-08-02 17:58:04 +0000890
Chad Rosier4f81fc22011-08-12 23:30:05 +0000891 for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
Chad Rosierd57133d2011-08-18 00:22:25 +0000892 bool IgnoreInput = false;
893
894 // Ignore input from stdin or any inputs that cannot be preprocessed.
Paul Robinsonf44157d2014-04-28 22:24:44 +0000895 // Check type first as not all linker inputs have a value.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000896 if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
Paul Robinsonf44157d2014-04-28 22:24:44 +0000897 IgnoreInput = true;
898 } else if (!strcmp(it->second->getValue(), "-")) {
Chad Rosierd57133d2011-08-18 00:22:25 +0000899 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000900 << "Error generating preprocessed source(s) - "
901 "ignoring input from stdin.";
Chad Rosierd57133d2011-08-18 00:22:25 +0000902 IgnoreInput = true;
Chad Rosierd57133d2011-08-18 00:22:25 +0000903 }
904
905 if (IgnoreInput) {
Chad Rosier4f81fc22011-08-12 23:30:05 +0000906 it = Inputs.erase(it);
907 ie = Inputs.end();
Chad Rosier6fdf38b2011-08-17 23:08:45 +0000908 } else {
Chad Rosier4f81fc22011-08-12 23:30:05 +0000909 ++it;
Chad Rosier6fdf38b2011-08-17 23:08:45 +0000910 }
Chad Rosier4f81fc22011-08-12 23:30:05 +0000911 }
Chad Rosierd57133d2011-08-18 00:22:25 +0000912
Chad Rosierc5103c32013-01-29 23:57:10 +0000913 if (Inputs.empty()) {
914 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000915 << "Error generating preprocessed source(s) - "
916 "no preprocessable inputs.";
Chad Rosierc5103c32013-01-29 23:57:10 +0000917 return;
918 }
919
Chad Rosiere75ef402011-09-06 23:52:36 +0000920 // Don't attempt to generate preprocessed files if multiple -arch options are
Chad Rosier636d2832012-02-13 18:16:28 +0000921 // used, unless they're all duplicates.
922 llvm::StringSet<> ArchNames;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +0000923 for (const Arg *A : C.getArgs()) {
Chad Rosiere75ef402011-09-06 23:52:36 +0000924 if (A->getOption().matches(options::OPT_arch)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000925 StringRef ArchName = A->getValue();
Chad Rosier636d2832012-02-13 18:16:28 +0000926 ArchNames.insert(ArchName);
Chad Rosiere75ef402011-09-06 23:52:36 +0000927 }
928 }
Chad Rosier636d2832012-02-13 18:16:28 +0000929 if (ArchNames.size() > 1) {
930 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000931 << "Error generating preprocessed source(s) - cannot generate "
932 "preprocessed source with multiple -arch options.";
Chad Rosier636d2832012-02-13 18:16:28 +0000933 return;
934 }
Chad Rosiere75ef402011-09-06 23:52:36 +0000935
Chandler Carruth7f1417f2012-01-24 10:43:44 +0000936 // Construct the list of abstract actions to perform for this compilation. On
937 // Darwin OSes this uses the driver-driver and builds universal actions.
Chandler Carruthcb916192012-01-25 08:49:21 +0000938 const ToolChain &TC = C.getDefaultToolChain();
Tim Northover157d9112014-01-16 08:48:16 +0000939 if (TC.getTriple().isOSBinFormatMachO())
Artem Belevich5e2a3ec2015-11-17 22:28:40 +0000940 BuildUniversalActions(C, TC, Inputs);
Chad Rosierbe10f982011-08-02 17:58:04 +0000941 else
Justin Lebar0f3474c2016-02-11 02:00:50 +0000942 BuildActions(C, C.getArgs(), Inputs, C.getActions());
Chad Rosierbe10f982011-08-02 17:58:04 +0000943
944 BuildJobs(C);
945
946 // If there were errors building the compilation, quit now.
Richard Smith5bb4cdf2012-12-20 02:22:15 +0000947 if (Trap.hasErrorOccurred()) {
Chad Rosierbe10f982011-08-02 17:58:04 +0000948 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000949 << "Error generating preprocessed source(s).";
Chad Rosierbe10f982011-08-02 17:58:04 +0000950 return;
951 }
952
953 // Generate preprocessed output.
Chad Rosierdd60e092013-01-29 20:15:05 +0000954 SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
Justin Bogner0cd92482015-07-02 22:52:08 +0000955 C.ExecuteJobs(C.getJobs(), FailingCommands);
Chad Rosierbe10f982011-08-02 17:58:04 +0000956
Justin Bognerbc89b182014-10-20 21:20:27 +0000957 // If any of the preprocessing commands failed, clean up and exit.
958 if (!FailingCommands.empty()) {
Reid Kleckner68eb60b2015-02-02 22:41:48 +0000959 if (!isSaveTempsEnabled())
Chad Rosierbe10f982011-08-02 17:58:04 +0000960 C.CleanupFileList(C.getTempFiles(), true);
961
962 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000963 << "Error generating preprocessed source(s).";
Justin Bognerbc89b182014-10-20 21:20:27 +0000964 return;
Chad Rosierbe10f982011-08-02 17:58:04 +0000965 }
Justin Bognerbc89b182014-10-20 21:20:27 +0000966
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000967 const ArgStringList &TempFiles = C.getTempFiles();
968 if (TempFiles.empty()) {
969 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000970 << "Error generating preprocessed source(s).";
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000971 return;
972 }
973
Justin Bognerbc89b182014-10-20 21:20:27 +0000974 Diag(clang::diag::note_drv_command_failed_diag_msg)
975 << "\n********************\n\n"
976 "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
977 "Preprocessed source(s) and associated run script(s) are located at:";
Justin Bognerbc89b182014-10-20 21:20:27 +0000978
Justin Bogner659ecc32014-10-20 22:47:23 +0000979 SmallString<128> VFS;
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +0000980 SmallString<128> ReproCrashFilename;
Justin Bogner659ecc32014-10-20 22:47:23 +0000981 for (const char *TempFile : TempFiles) {
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000982 Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +0000983 if (ReproCrashFilename.empty()) {
984 ReproCrashFilename = TempFile;
985 llvm::sys::path::replace_extension(ReproCrashFilename, ".crash");
986 }
Justin Bogner659ecc32014-10-20 22:47:23 +0000987 if (StringRef(TempFile).endswith(".cache")) {
988 // In some cases (modules) we'll dump extra data to help with reproducing
989 // the crash into a directory next to the output.
990 VFS = llvm::sys::path::filename(TempFile);
991 llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
992 }
993 }
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000994
995 // Assume associated files are based off of the first temporary file.
Justin Bogner25645152014-10-21 17:24:44 +0000996 CrashReportInfo CrashInfo(TempFiles[0], VFS);
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000997
Justin Bogner25645152014-10-21 17:24:44 +0000998 std::string Script = CrashInfo.Filename.rsplit('.').first.str() + ".sh";
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000999 std::error_code EC;
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001000 llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::F_Excl);
1001 if (EC) {
1002 Diag(clang::diag::note_drv_command_failed_diag_msg)
1003 << "Error generating run script: " + Script + " " + EC.message();
1004 } else {
Justin Bogner42220ed2015-03-12 00:14:35 +00001005 ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
Justin Bognered9cbe02015-07-09 06:58:31 +00001006 << "# Driver args: ";
1007 printArgList(ScriptOS, C.getInputArgs());
1008 ScriptOS << "# Original command: ";
Justin Bogner42220ed2015-03-12 00:14:35 +00001009 Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
Justin Bogner33bdbc62014-10-21 18:03:08 +00001010 Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001011 Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
Justin Bognerbc89b182014-10-20 21:20:27 +00001012 }
Saleem Abdulrasool3661a822015-01-12 02:33:09 +00001013
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +00001014 // On darwin, provide information about the .crash diagnostic report.
1015 if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) {
1016 SmallString<128> CrashDiagDir;
1017 if (getCrashDiagnosticFile(ReproCrashFilename, CrashDiagDir)) {
1018 Diag(clang::diag::note_drv_command_failed_diag_msg)
1019 << ReproCrashFilename.str();
1020 } else { // Suggest a directory for the user to look for .crash files.
1021 llvm::sys::path::append(CrashDiagDir, Name);
1022 CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash";
1023 Diag(clang::diag::note_drv_command_failed_diag_msg)
1024 << "Crash backtrace is located in";
1025 Diag(clang::diag::note_drv_command_failed_diag_msg)
1026 << CrashDiagDir.str();
1027 Diag(clang::diag::note_drv_command_failed_diag_msg)
1028 << "(choose the .crash file that corresponds to your crash)";
1029 }
1030 }
1031
Saleem Abdulrasool3661a822015-01-12 02:33:09 +00001032 for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file,
1033 options::OPT_frewrite_map_file_EQ))
1034 Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
1035
Justin Bognerbc89b182014-10-20 21:20:27 +00001036 Diag(clang::diag::note_drv_command_failed_diag_msg)
1037 << "\n\n********************";
Chad Rosierbe10f982011-08-02 17:58:04 +00001038}
1039
Justin Bogner0cd92482015-07-02 22:52:08 +00001040void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
Oleg Ranevskyycd516372016-01-05 19:54:39 +00001041 // Since commandLineFitsWithinSystemLimits() may underestimate system's capacity
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001042 // if the tool does not support response files, there is a chance/ that things
1043 // will just work without a response file, so we silently just skip it.
Justin Bogner0cd92482015-07-02 22:52:08 +00001044 if (Cmd.getCreator().getResponseFilesSupport() == Tool::RF_None ||
Oleg Ranevskyycd516372016-01-05 19:54:39 +00001045 llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(), Cmd.getArguments()))
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001046 return;
1047
1048 std::string TmpName = GetTemporaryPath("response", "txt");
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00001049 Cmd.setResponseFile(C.addTempFile(C.getArgs().MakeArgString(TmpName)));
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001050}
1051
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001052int Driver::ExecuteCompilation(
1053 Compilation &C,
1054 SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001055 // Just print if -### was present.
1056 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
Hans Wennborgb212b342013-09-12 18:23:34 +00001057 C.getJobs().Print(llvm::errs(), "\n", true);
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001058 return 0;
1059 }
1060
1061 // If there were errors building the compilation, quit now.
Chad Rosierbe10f982011-08-02 17:58:04 +00001062 if (Diags.hasErrorOccurred())
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001063 return 1;
1064
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001065 // Set up response file names for each command, if necessary
Justin Bogner0cd92482015-07-02 22:52:08 +00001066 for (auto &Job : C.getJobs())
1067 setUpResponseFiles(C, Job);
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001068
Justin Bogner0cd92482015-07-02 22:52:08 +00001069 C.ExecuteJobs(C.getJobs(), FailingCommands);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001070
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001071 // Remove temp files.
1072 C.CleanupFileList(C.getTempFiles());
1073
Daniel Dunbar07494792010-05-22 00:37:20 +00001074 // If the command succeeded, we are done.
Chad Rosierdd60e092013-01-29 20:15:05 +00001075 if (FailingCommands.empty())
1076 return 0;
Daniel Dunbar07494792010-05-22 00:37:20 +00001077
Chad Rosierdd60e092013-01-29 20:15:05 +00001078 // Otherwise, remove result files and print extra information about abnormal
1079 // failures.
Douglas Katzman6bbffc42015-06-25 18:51:37 +00001080 for (const auto &CmdPair : FailingCommands) {
1081 int Res = CmdPair.first;
1082 const Command *FailingCommand = CmdPair.second;
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001083
Chad Rosierdd60e092013-01-29 20:15:05 +00001084 // Remove result files if we're not saving temps.
Reid Kleckner68eb60b2015-02-02 22:41:48 +00001085 if (!isSaveTempsEnabled()) {
Chad Rosierdd60e092013-01-29 20:15:05 +00001086 const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
1087 C.CleanupFileMap(C.getResultFiles(), JA, true);
1088
1089 // Failure result files are valid unless we crashed.
1090 if (Res < 0)
1091 C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
1092 }
1093
1094 // Print extra information about abnormal failures, if possible.
1095 //
1096 // This is ad-hoc, but we don't want to be excessively noisy. If the result
Justin Bogner5aaf2e72014-06-26 20:59:36 +00001097 // status was 1, assume the command failed normally. In particular, if it
Chad Rosierdd60e092013-01-29 20:15:05 +00001098 // was the compiler then assume it gave a reasonable error code. Failures
1099 // in other tools are less common, and they generally have worse
1100 // diagnostics, so always print the diagnostic there.
1101 const Tool &FailingTool = FailingCommand->getCreator();
1102
1103 if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
1104 // FIXME: See FIXME above regarding result code interpretation.
1105 if (Res < 0)
1106 Diag(clang::diag::err_drv_command_signalled)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001107 << FailingTool.getShortName();
Chad Rosierdd60e092013-01-29 20:15:05 +00001108 else
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001109 Diag(clang::diag::err_drv_command_failed) << FailingTool.getShortName()
1110 << Res;
Chad Rosierdd60e092013-01-29 20:15:05 +00001111 }
Peter Collingbourne119cfaa2011-11-21 00:01:05 +00001112 }
Chad Rosierdd60e092013-01-29 20:15:05 +00001113 return 0;
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001114}
1115
Daniel Dunbara7b5e212009-04-15 16:34:29 +00001116void Driver::PrintHelp(bool ShowHidden) const {
Hans Wennborg6ddc6902013-07-27 00:23:45 +00001117 unsigned IncludedFlagsBitmask;
1118 unsigned ExcludedFlagsBitmask;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001119 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001120 getIncludeExcludeOptionFlagMasks();
Hans Wennborg6ddc6902013-07-27 00:23:45 +00001121
1122 ExcludedFlagsBitmask |= options::NoDriverOption;
1123 if (!ShowHidden)
1124 ExcludedFlagsBitmask |= HelpHidden;
1125
1126 getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
George Rimar5dbfa4e2017-07-26 09:10:17 +00001127 IncludedFlagsBitmask, ExcludedFlagsBitmask,
1128 /*ShowAllAliases=*/false);
Daniel Dunbar7c925282009-03-31 21:38:17 +00001129}
1130
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001131void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001132 // FIXME: The following handlers should use a callback mechanism, we don't
1133 // know what the client would like to do.
Ted Kremenek4c0df3d2010-01-23 02:11:34 +00001134 OS << getClangFullVersion() << '\n';
Daniel Dunbarb10248802009-03-26 16:09:13 +00001135 const ToolChain &TC = C.getDefaultToolChain();
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001136 OS << "Target: " << TC.getTripleString() << '\n';
Daniel Dunbar10978e42009-06-16 23:32:58 +00001137
1138 // Print the threading model.
Jonathan Roelofsb140a102014-10-03 21:57:44 +00001139 if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
1140 // Don't print if the ToolChain would have barfed on it already
1141 if (TC.isThreadModelSupported(A->getValue()))
1142 OS << "Thread model: " << A->getValue();
1143 } else
1144 OS << "Thread model: " << TC.getThreadModel();
1145 OS << '\n';
Chandler Carruth9ade6a92015-08-05 17:07:33 +00001146
1147 // Print out the install directory.
1148 OS << "InstalledDir: " << InstalledDir << '\n';
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001149}
1150
Chris Lattner86ed5b02010-05-05 05:53:24 +00001151/// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
1152/// option.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001153static void PrintDiagnosticCategories(raw_ostream &OS) {
Argyrios Kyrtzidis0e37afa2011-05-25 05:05:01 +00001154 // Skip the empty category.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001155 for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
1156 ++i)
Argyrios Kyrtzidis0e37afa2011-05-25 05:05:01 +00001157 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
Chris Lattner86ed5b02010-05-05 05:53:24 +00001158}
1159
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001160bool Driver::HandleImmediateArgs(const Compilation &C) {
Daniel Dunbar18974bd2010-06-11 22:00:19 +00001161 // The order these options are handled in gcc is all over the place, but we
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001162 // don't expect inconsistencies w.r.t. that to matter in practice.
Daniel Dunbar7c925282009-03-31 21:38:17 +00001163
Daniel Dunbar1b09e042010-09-17 02:47:28 +00001164 if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
1165 llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
1166 return false;
1167 }
1168
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001169 if (C.getArgs().hasArg(options::OPT_dumpversion)) {
Daniel Dunbare26e5002011-01-12 00:43:47 +00001170 // Since -dumpversion is only implemented for pedantic GCC compatibility, we
1171 // return an answer which matches our definition of __VERSION__.
1172 //
1173 // If we want to return a more correct answer some day, then we should
1174 // introduce a non-pedantically GCC compatible mode to Clang in which we
1175 // provide sensible definitions for -dumpversion, __VERSION__, etc.
1176 llvm::outs() << "4.2.1\n";
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001177 return false;
1178 }
Daniel Dunbarfb3d7472010-06-14 21:23:12 +00001179
Chris Lattner86ed5b02010-05-05 05:53:24 +00001180 if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
1181 PrintDiagnosticCategories(llvm::outs());
1182 return false;
1183 }
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001184
James Molloya3c85b82012-05-01 14:57:16 +00001185 if (C.getArgs().hasArg(options::OPT_help) ||
Daniel Dunbara7b5e212009-04-15 16:34:29 +00001186 C.getArgs().hasArg(options::OPT__help_hidden)) {
1187 PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
Daniel Dunbar7c925282009-03-31 21:38:17 +00001188 return false;
1189 }
1190
Daniel Dunbarb0006ae2009-04-02 15:05:41 +00001191 if (C.getArgs().hasArg(options::OPT__version)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001192 // Follow gcc behavior and use stdout for --version and stderr for -v.
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001193 PrintVersion(C, llvm::outs());
Dimitry Andric0527c322017-06-07 12:05:41 +00001194
1195 // Print registered targets.
1196 llvm::outs() << '\n';
1197 llvm::TargetRegistry::printRegisteredTargetsForVersion(llvm::outs());
Daniel Dunbarb0006ae2009-04-02 15:05:41 +00001198 return false;
1199 }
1200
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001201 if (C.getArgs().hasArg(options::OPT_v) ||
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001202 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001203 PrintVersion(C, llvm::errs());
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001204 SuppressMissingInputWarning = true;
1205 }
1206
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001207 const ToolChain &TC = C.getDefaultToolChain();
Chandler Carruth0ae39aa2013-07-30 17:57:09 +00001208
1209 if (C.getArgs().hasArg(options::OPT_v))
1210 TC.printVerboseInfo(llvm::errs());
1211
Meador Inge51208a32017-04-04 21:46:50 +00001212 if (C.getArgs().hasArg(options::OPT_print_resource_dir)) {
Meador Ingea9113952017-04-05 22:27:20 +00001213 llvm::outs() << ResourceDir << '\n';
Meador Inge51208a32017-04-04 21:46:50 +00001214 return false;
1215 }
1216
Daniel Dunbard972e222009-03-20 04:37:21 +00001217 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
1218 llvm::outs() << "programs: =";
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001219 bool separator = false;
1220 for (const std::string &Path : TC.getProgramPaths()) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001221 if (separator)
1222 llvm::outs() << ':';
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001223 llvm::outs() << Path;
1224 separator = true;
Daniel Dunbard972e222009-03-20 04:37:21 +00001225 }
1226 llvm::outs() << "\n";
Peter Collingbournefa9771f2011-09-06 02:08:31 +00001227 llvm::outs() << "libraries: =" << ResourceDir;
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001228
Sebastian Pop980920a2012-04-16 04:16:43 +00001229 StringRef sysroot = C.getSysRoot();
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001230
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001231 for (const std::string &Path : TC.getFilePaths()) {
1232 // Always print a separator. ResourceDir was the first item shown.
Peter Collingbournefa9771f2011-09-06 02:08:31 +00001233 llvm::outs() << ':';
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001234 // Interpretation of leading '=' is needed only for NetBSD.
1235 if (Path[0] == '=')
Douglas Katzman26eabf62015-06-24 15:10:30 +00001236 llvm::outs() << sysroot << Path.substr(1);
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001237 else
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001238 llvm::outs() << Path;
Daniel Dunbard972e222009-03-20 04:37:21 +00001239 }
1240 llvm::outs() << "\n";
Daniel Dunbar7c925282009-03-31 21:38:17 +00001241 return false;
Daniel Dunbard972e222009-03-20 04:37:21 +00001242 }
1243
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001244 // FIXME: The following handlers should use a callback mechanism, we don't
1245 // know what the client would like to do.
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001246 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001247 llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001248 return false;
1249 }
1250
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001251 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001252 llvm::outs() << GetProgramPath(A->getValue(), TC) << "\n";
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001253 return false;
1254 }
1255
Yuka Takahashic8068db2017-05-23 18:39:08 +00001256 if (Arg *A = C.getArgs().getLastArg(options::OPT_autocomplete)) {
1257 // Print out all options that start with a given argument. This is used for
1258 // shell autocompletion.
Yuka Takahashiba5d4af2017-06-20 16:31:31 +00001259 StringRef PassedFlags = A->getValue();
1260 std::vector<std::string> SuggestedCompletions;
1261
Yuka Takahashi33cf63b2017-07-08 17:48:59 +00001262 unsigned short DisableFlags = options::NoDriverOption | options::Unsupported | options::Ignored;
1263 // We want to show cc1-only options only when clang is invoked as "clang -cc1".
1264 // When clang is invoked as "clang -cc1", we add "#" to the beginning of an --autocomplete
1265 // option so that the clang driver can distinguish whether it is requested to show cc1-only options or not.
1266 if (PassedFlags[0] == '#') {
1267 DisableFlags &= ~options::NoDriverOption;
1268 PassedFlags = PassedFlags.substr(1);
1269 }
1270
Yuka Takahashiba5d4af2017-06-20 16:31:31 +00001271 if (PassedFlags.find(',') == StringRef::npos) {
1272 // If the flag is in the form of "--autocomplete=-foo",
1273 // we were requested to print out all option names that start with "-foo".
1274 // For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only".
Yuka Takahashi33cf63b2017-07-08 17:48:59 +00001275 SuggestedCompletions = Opts->findByPrefix(PassedFlags, DisableFlags);
Yuka Takahashi64918d02017-07-16 15:07:20 +00001276
1277 // We have to query the -W flags manually as they're not in the OptTable.
1278 // TODO: Find a good way to add them to OptTable instead and them remove
1279 // this code.
1280 for (StringRef S : DiagnosticIDs::getDiagnosticFlags())
1281 if (S.startswith(PassedFlags))
1282 SuggestedCompletions.push_back(S);
Yuka Takahashiba5d4af2017-06-20 16:31:31 +00001283 } else {
1284 // If the flag is in the form of "--autocomplete=foo,bar", we were
1285 // requested to print out all option values for "-foo" that start with
1286 // "bar". For example,
1287 // "--autocomplete=-stdlib=,l" is expanded to "libc++" and "libstdc++".
1288 StringRef Option, Arg;
1289 std::tie(Option, Arg) = PassedFlags.split(',');
1290 SuggestedCompletions = Opts->suggestValueCompletions(Option, Arg);
1291 }
1292
Rui Ueyama5cb4b352017-06-23 15:37:52 +00001293 // Sort the autocomplete candidates so that shells print them out in a
1294 // deterministic order. We could sort in any way, but we chose
1295 // case-insensitive sorting for consistency with the -help option
1296 // which prints out options in the case-insensitive alphabetical order.
1297 std::sort(SuggestedCompletions.begin(), SuggestedCompletions.end(),
1298 [](StringRef A, StringRef B) { return A.compare_lower(B) < 0; });
1299
Yuka Takahashi66256902017-07-26 13:36:58 +00001300 llvm::outs() << llvm::join(SuggestedCompletions, "\n") << '\n';
Yuka Takahashic8068db2017-05-23 18:39:08 +00001301 return false;
1302 }
1303
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001304 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
Michal Gorny7cfe4802016-10-10 12:23:40 +00001305 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(C.getArgs());
1306 switch (RLT) {
1307 case ToolChain::RLT_CompilerRT:
1308 llvm::outs() << TC.getCompilerRT(C.getArgs(), "builtins") << "\n";
1309 break;
1310 case ToolChain::RLT_Libgcc:
1311 llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
1312 break;
1313 }
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001314 return false;
1315 }
1316
Daniel Dunbar1b3ec3a2009-06-16 23:25:22 +00001317 if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
Douglas Katzmana34b7bf2015-06-30 19:32:57 +00001318 for (const Multilib &Multilib : TC.getMultilibs())
1319 llvm::outs() << Multilib << "\n";
Daniel Dunbar1b3ec3a2009-06-16 23:25:22 +00001320 return false;
1321 }
1322
Jonathan Roelofs2cea1be2014-02-12 03:21:20 +00001323 if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
Douglas Katzmana34b7bf2015-06-30 19:32:57 +00001324 for (const Multilib &Multilib : TC.getMultilibs()) {
Douglas Katzman6bbffc42015-06-25 18:51:37 +00001325 if (Multilib.gccSuffix().empty())
Jonathan Roelofs2cea1be2014-02-12 03:21:20 +00001326 llvm::outs() << ".\n";
1327 else {
Douglas Katzman6bbffc42015-06-25 18:51:37 +00001328 StringRef Suffix(Multilib.gccSuffix());
Jonathan Roelofs2cea1be2014-02-12 03:21:20 +00001329 assert(Suffix.front() == '/');
1330 llvm::outs() << Suffix.substr(1) << "\n";
1331 }
Jonathan Roelofs3fa96d82014-02-12 01:36:51 +00001332 }
Jonathan Roelofs0e7ec602014-02-12 01:29:25 +00001333 return false;
1334 }
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001335 return true;
1336}
1337
Douglas Katzmanfd528672015-06-11 15:05:22 +00001338// Display an action graph human-readably. Action A is the "sink" node
1339// and latest-occuring action. Traversal is in pre-order, visiting the
1340// inputs to each action before printing the action itself.
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001341static unsigned PrintActions1(const Compilation &C, Action *A,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001342 std::map<Action *, unsigned> &Ids) {
Douglas Katzmanfd528672015-06-11 15:05:22 +00001343 if (Ids.count(A)) // A was already visited.
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001344 return Ids[A];
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001345
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001346 std::string str;
1347 llvm::raw_string_ostream os(str);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001348
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001349 os << Action::getClassName(A->getKind()) << ", ";
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001350 if (InputAction *IA = dyn_cast<InputAction>(A)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001351 os << "\"" << IA->getInputArg().getValue() << "\"";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001352 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001353 os << '"' << BIA->getArchName() << '"' << ", {"
Nico Weber5a459f82016-02-23 19:30:43 +00001354 << PrintActions1(C, *BIA->input_begin(), Ids) << "}";
Samuel Antaod06239d2016-07-15 23:13:27 +00001355 } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
1356 bool IsFirst = true;
1357 OA->doOnEachDependence(
1358 [&](Action *A, const ToolChain *TC, const char *BoundArch) {
1359 // E.g. for two CUDA device dependences whose bound arch is sm_20 and
1360 // sm_35 this will generate:
1361 // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
1362 // (nvptx64-nvidia-cuda:sm_35) {#ID}
1363 if (!IsFirst)
1364 os << ", ";
1365 os << '"';
1366 if (TC)
1367 os << A->getOffloadingKindPrefix();
1368 else
1369 os << "host";
1370 os << " (";
1371 os << TC->getTriple().normalize();
1372
1373 if (BoundArch)
1374 os << ":" << BoundArch;
1375 os << ")";
1376 os << '"';
1377 os << " {" << PrintActions1(C, A, Ids) << "}";
1378 IsFirst = false;
1379 });
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001380 } else {
Samuel Antaod06239d2016-07-15 23:13:27 +00001381 const ActionList *AL = &A->getInputs();
Artem Belevich0ff05cd2015-07-13 23:27:56 +00001382
Artem Belevich23256752015-09-22 17:23:09 +00001383 if (AL->size()) {
1384 const char *Prefix = "{";
1385 for (Action *PreRequisite : *AL) {
1386 os << Prefix << PrintActions1(C, PreRequisite, Ids);
1387 Prefix = ", ";
1388 }
1389 os << "}";
1390 } else
1391 os << "{}";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001392 }
1393
Samuel Antaod06239d2016-07-15 23:13:27 +00001394 // Append offload info for all options other than the offloading action
1395 // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
1396 std::string offload_str;
1397 llvm::raw_string_ostream offload_os(offload_str);
1398 if (!isa<OffloadAction>(A)) {
1399 auto S = A->getOffloadingKindPrefix();
1400 if (!S.empty()) {
1401 offload_os << ", (" << S;
1402 if (A->getOffloadingArch())
1403 offload_os << ", " << A->getOffloadingArch();
1404 offload_os << ")";
1405 }
1406 }
1407
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001408 unsigned Id = Ids.size();
1409 Ids[A] = Id;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001410 llvm::errs() << Id << ": " << os.str() << ", "
Samuel Antaod06239d2016-07-15 23:13:27 +00001411 << types::getTypeName(A->getType()) << offload_os.str() << "\n";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001412
1413 return Id;
1414}
1415
Douglas Katzmanfd528672015-06-11 15:05:22 +00001416// Print the action graphs in a compilation C.
1417// For example "clang -c file1.c file2.c" is composed of two subgraphs.
Daniel Dunbareb843be2009-03-18 03:13:20 +00001418void Driver::PrintActions(const Compilation &C) const {
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001419 std::map<Action *, unsigned> Ids;
1420 for (Action *A : C.getActions())
1421 PrintActions1(C, A, Ids);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001422}
1423
Joerg Sonnenberger5fe4a7d2011-05-06 14:05:11 +00001424/// \brief Check whether the given input tree contains any compilation or
1425/// assembly actions.
1426static bool ContainsCompileOrAssembleAction(const Action *A) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001427 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
Bob Wilson23a55f12014-12-21 07:00:00 +00001428 isa<AssembleJobAction>(A))
Daniel Dunbar00d3d8e2010-06-29 16:38:33 +00001429 return true;
1430
Nico Weber5a459f82016-02-23 19:30:43 +00001431 for (const Action *Input : A->inputs())
Nico Weberfb80f962015-09-19 21:36:51 +00001432 if (ContainsCompileOrAssembleAction(Input))
Daniel Dunbar00d3d8e2010-06-29 16:38:33 +00001433 return true;
1434
1435 return false;
1436}
1437
Artem Belevich5e2a3ec2015-11-17 22:28:40 +00001438void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
1439 const InputList &BAInputs) const {
1440 DerivedArgList &Args = C.getArgs();
1441 ActionList &Actions = C.getActions();
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001442 llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
1443 // Collect the list of architectures. Duplicates are allowed, but should only
1444 // be handled once (in the order seen).
Daniel Dunbare5dc4822009-03-13 20:33:35 +00001445 llvm::StringSet<> ArchNames;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001446 SmallVector<const char *, 4> Archs;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00001447 for (Arg *A : Args) {
Daniel Dunbar0bfb21e2009-11-19 03:26:40 +00001448 if (A->getOption().matches(options::OPT_arch)) {
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001449 // Validate the option here; we don't save the type here because its
1450 // particular spelling may participate in other driver choices.
1451 llvm::Triple::ArchType Arch =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001452 tools::darwin::getArchTypeForMachOArchName(A->getValue());
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001453 if (Arch == llvm::Triple::UnknownArch) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001454 Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001455 continue;
1456 }
1457
Daniel Dunbar2da02722009-03-19 07:55:12 +00001458 A->claim();
David Blaikie61b86d42014-11-19 02:56:13 +00001459 if (ArchNames.insert(A->getValue()).second)
Richard Smithbd55daf2012-11-01 04:30:05 +00001460 Archs.push_back(A->getValue());
Daniel Dunbarf479c122009-03-12 18:40:18 +00001461 }
1462 }
1463
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001464 // When there is no explicit arch for this platform, make sure we still bind
1465 // the architecture (to the default) so that -Xarch_ is handled correctly.
Daniel Dunbareb843be2009-03-18 03:13:20 +00001466 if (!Archs.size())
Daniel Dunbarc3bd9f52012-11-08 03:38:26 +00001467 Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
Daniel Dunbarf479c122009-03-12 18:40:18 +00001468
Daniel Dunbarf479c122009-03-12 18:40:18 +00001469 ActionList SingleActions;
Justin Lebar0f3474c2016-02-11 02:00:50 +00001470 BuildActions(C, Args, BAInputs, SingleActions);
Daniel Dunbarf479c122009-03-12 18:40:18 +00001471
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001472 // Add in arch bindings for every top level action, as well as lipo and
1473 // dsymutil steps if needed.
Nico Weberfb80f962015-09-19 21:36:51 +00001474 for (Action* Act : SingleActions) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001475 // Make sure we can lipo this kind of output. If not (and it is an actual
1476 // output) then we disallow, since we can't create an output file with the
1477 // right name without overwriting it. We could remove this oddity by just
1478 // changing the output names to include the arch, which would also fix
Daniel Dunbarf479c122009-03-12 18:40:18 +00001479 // -save-temps. Compatibility wins for now.
1480
Daniel Dunbare2ca3bd2009-03-13 17:46:02 +00001481 if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
Daniel Dunbarf479c122009-03-12 18:40:18 +00001482 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001483 << types::getTypeName(Act->getType());
Daniel Dunbarf479c122009-03-12 18:40:18 +00001484
1485 ActionList Inputs;
Justin Lebar41094612016-01-11 23:07:27 +00001486 for (unsigned i = 0, e = Archs.size(); i != e; ++i)
1487 Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
Daniel Dunbarf479c122009-03-12 18:40:18 +00001488
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001489 // Lipo if necessary, we do it this way because we need to set the arch flag
1490 // so that -Xarch_ gets overwritten.
Daniel Dunbarf479c122009-03-12 18:40:18 +00001491 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
1492 Actions.append(Inputs.begin(), Inputs.end());
1493 else
Justin Lebar41094612016-01-11 23:07:27 +00001494 Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001495
Eric Christopher65c05fa2012-02-06 19:43:51 +00001496 // Handle debug info queries.
1497 Arg *A = Args.getLastArg(options::OPT_g_Group);
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001498 if (A && !A->getOption().matches(options::OPT_g0) &&
1499 !A->getOption().matches(options::OPT_gstabs) &&
1500 ContainsCompileOrAssembleAction(Actions.back())) {
Chad Rosier62135492012-07-09 17:31:28 +00001501
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001502 // Add a 'dsymutil' step if necessary, when debug info is enabled and we
1503 // have a compile input. We need to run 'dsymutil' ourselves in such cases
Eric Christopher776c26f2013-01-28 17:39:03 +00001504 // because the debug info will refer to a temporary object file which
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001505 // will be removed at the end of the compilation process.
1506 if (Act->getType() == types::TY_Image) {
1507 ActionList Inputs;
1508 Inputs.push_back(Actions.back());
1509 Actions.pop_back();
Justin Lebar41094612016-01-11 23:07:27 +00001510 Actions.push_back(
1511 C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001512 }
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001513
Ben Langmuir9b9a8d32014-02-06 18:53:25 +00001514 // Verify the debug info output.
Alp Tokere9d2bfc2014-01-17 02:06:23 +00001515 if (Args.hasArg(options::OPT_verify_debug_info)) {
Justin Lebar41094612016-01-11 23:07:27 +00001516 Action* LastAction = Actions.back();
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001517 Actions.pop_back();
Justin Lebar41094612016-01-11 23:07:27 +00001518 Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
1519 LastAction, types::TY_Nothing));
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001520 }
1521 }
Daniel Dunbarf479c122009-03-12 18:40:18 +00001522 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001523}
1524
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001525/// \brief Check that the file referenced by Value exists. If it doesn't,
1526/// issue a diagnostic and return false.
Alp Toker8c8a8752013-12-03 06:53:35 +00001527static bool DiagnoseInputExistence(const Driver &D, const DerivedArgList &Args,
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001528 StringRef Value, types::ID Ty) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001529 if (!D.getCheckInputsExist())
1530 return true;
1531
1532 // stdin always exists.
1533 if (Value == "-")
1534 return true;
1535
1536 SmallString<64> Path(Value);
1537 if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
Yaron Keren92e1b622015-03-18 10:17:07 +00001538 if (!llvm::sys::path::is_absolute(Path)) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001539 SmallString<64> Directory(WorkDir->getValue());
1540 llvm::sys::path::append(Directory, Value);
1541 Path.assign(Directory);
1542 }
1543 }
1544
1545 if (llvm::sys::fs::exists(Twine(Path)))
1546 return true;
1547
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001548 if (D.IsCLMode()) {
1549 if (!llvm::sys::path::is_absolute(Twine(Path)) &&
1550 llvm::sys::Process::FindInEnvPath("LIB", Value))
1551 return true;
1552
1553 if (Args.hasArg(options::OPT__SLASH_link) && Ty == types::TY_Object) {
1554 // Arguments to the /link flag might cause the linker to search for object
1555 // and library files in paths we don't know about. Don't error in such
1556 // cases.
1557 return true;
1558 }
1559 }
Hans Wennborg23d26a32014-06-18 17:21:50 +00001560
Yaron Keren92e1b622015-03-18 10:17:07 +00001561 D.Diag(clang::diag::err_drv_no_such_file) << Path;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001562 return false;
1563}
1564
Chad Rosierecdede82011-08-12 22:08:57 +00001565// Construct a the list of inputs and their types.
Hans Wennborg55362852014-05-02 22:55:30 +00001566void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
Chad Rosierecdede82011-08-12 22:08:57 +00001567 InputList &Inputs) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001568 // Track the current user specified (-x) input. We also explicitly track the
1569 // argument used to set the type; we only want to claim the type when we
1570 // actually use it, so we warn about unused -x arguments.
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00001571 types::ID InputType = types::TY_Nothing;
Craig Topper92fc2df2014-05-17 16:56:41 +00001572 Arg *InputTypeArg = nullptr;
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00001573
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001574 // The last /TC or /TP option sets the input type to C or C++ globally.
Ehsan Akhgaric249abb2014-09-12 21:44:24 +00001575 if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
1576 options::OPT__SLASH_TP)) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001577 InputTypeArg = TCTP;
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001578 InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001579 ? types::TY_C
1580 : types::TY_CXX;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001581
Richard Smith0aef3052017-02-18 01:14:43 +00001582 Arg *Previous = nullptr;
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001583 bool ShowNote = false;
Richard Smith0aef3052017-02-18 01:14:43 +00001584 for (Arg *A : Args.filtered(options::OPT__SLASH_TC, options::OPT__SLASH_TP)) {
1585 if (Previous) {
1586 Diag(clang::diag::warn_drv_overriding_flag_option)
1587 << Previous->getSpelling() << A->getSpelling();
1588 ShowNote = true;
1589 }
1590 Previous = A;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001591 }
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001592 if (ShowNote)
1593 Diag(clang::diag::note_drv_t_option_is_global);
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001594
1595 // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
1596 assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
1597 }
1598
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00001599 for (Arg *A : Args) {
Michael J. Spencerad3ccc32012-08-20 21:41:17 +00001600 if (A->getOption().getKind() == Option::InputClass) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001601 const char *Value = A->getValue();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001602 types::ID Ty = types::TY_INVALID;
1603
1604 // Infer the input type if necessary.
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00001605 if (InputType == types::TY_Nothing) {
1606 // If there was an explicit arg for this, claim it.
1607 if (InputTypeArg)
1608 InputTypeArg->claim();
1609
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001610 // stdin must be handled specially.
1611 if (memcmp(Value, "-", 2) == 0) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001612 // If running with -E, treat as a C input (this changes the builtin
1613 // macros, for example). This may be overridden by -ObjC below.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001614 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001615 // Otherwise emit an error but still use a valid type to avoid
1616 // spurious errors (e.g., no inputs).
Hans Wennborg70850d82013-07-18 20:29:38 +00001617 if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
Hans Wennborgcfdd8b52014-01-29 01:04:40 +00001618 Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
1619 : clang::diag::err_drv_unknown_stdin_type);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001620 Ty = types::TY_C;
1621 } else {
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00001622 // Otherwise lookup by extension.
1623 // Fallback is C if invoked as C preprocessor or Object otherwise.
1624 // We use a host hook here because Darwin at least has its own
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001625 // idea of what .s is.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001626 if (const char *Ext = strrchr(Value, '.'))
Daniel Dunbarcc7df6c2010-08-02 05:43:56 +00001627 Ty = TC.LookupTypeForExtension(Ext + 1);
Daniel Dunbarea9f0322009-03-20 23:39:23 +00001628
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00001629 if (Ty == types::TY_INVALID) {
Hans Wennborg70850d82013-07-18 20:29:38 +00001630 if (CCCIsCPP())
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00001631 Ty = types::TY_C;
1632 else
1633 Ty = types::TY_Object;
1634 }
Daniel Dunbar0ac94452010-02-17 20:32:58 +00001635
1636 // If the driver is invoked as C++ compiler (like clang++ or c++) it
1637 // should autodetect some input files as C++ for g++ compatibility.
Hans Wennborg70850d82013-07-18 20:29:38 +00001638 if (CCCIsCXX()) {
Daniel Dunbar0ac94452010-02-17 20:32:58 +00001639 types::ID OldTy = Ty;
1640 Ty = types::lookupCXXTypeForCType(Ty);
1641
1642 if (Ty != OldTy)
1643 Diag(clang::diag::warn_drv_treating_input_as_cxx)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001644 << getTypeName(OldTy) << getTypeName(Ty);
Daniel Dunbar0ac94452010-02-17 20:32:58 +00001645 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001646 }
1647
Daniel Dunbar82b22102009-05-18 21:47:54 +00001648 // -ObjC and -ObjC++ override the default language, but only for "source
1649 // files". We just treat everything that isn't a linker input as a
1650 // source file.
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001651 //
Daniel Dunbar82b22102009-05-18 21:47:54 +00001652 // FIXME: Clean this up if we move the phase sequence into the type.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001653 if (Ty != types::TY_Object) {
1654 if (Args.hasArg(options::OPT_ObjC))
1655 Ty = types::TY_ObjC;
1656 else if (Args.hasArg(options::OPT_ObjCXX))
1657 Ty = types::TY_ObjCXX;
1658 }
1659 } else {
1660 assert(InputTypeArg && "InputType set w/o InputTypeArg");
Ehsan Akhgari7e954ea2014-09-12 18:15:10 +00001661 if (!InputTypeArg->getOption().matches(options::OPT_x)) {
1662 // If emulating cl.exe, make sure that /TC and /TP don't affect input
1663 // object files.
1664 const char *Ext = strrchr(Value, '.');
1665 if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
1666 Ty = types::TY_Object;
1667 }
1668 if (Ty == types::TY_INVALID) {
1669 Ty = InputType;
1670 InputTypeArg->claim();
1671 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001672 }
1673
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001674 if (DiagnoseInputExistence(*this, Args, Value, Ty))
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001675 Inputs.push_back(std::make_pair(Ty, A));
1676
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001677 } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
1678 StringRef Value = A->getValue();
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001679 if (DiagnoseInputExistence(*this, Args, Value, types::TY_C)) {
David Blaikie0aaa7622017-01-13 17:34:15 +00001680 Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001681 Inputs.push_back(std::make_pair(types::TY_C, InputArg));
1682 }
1683 A->claim();
1684 } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
1685 StringRef Value = A->getValue();
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001686 if (DiagnoseInputExistence(*this, Args, Value, types::TY_CXX)) {
David Blaikie0aaa7622017-01-13 17:34:15 +00001687 Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001688 Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
1689 }
1690 A->claim();
Michael J. Spencer66e2b202012-10-19 22:37:06 +00001691 } else if (A->getOption().hasFlag(options::LinkerInput)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001692 // Just treat as object type, we could make a special type for this if
1693 // necessary.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001694 Inputs.push_back(std::make_pair(types::TY_Object, A));
1695
Daniel Dunbar0bfb21e2009-11-19 03:26:40 +00001696 } else if (A->getOption().matches(options::OPT_x)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001697 InputTypeArg = A;
Richard Smithbd55daf2012-11-01 04:30:05 +00001698 InputType = types::lookupTypeForTypeSpecifier(A->getValue());
Chad Rosier706c2352012-04-07 00:01:31 +00001699 A->claim();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001700
1701 // Follow gcc behavior and treat as linker input for invalid -x
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001702 // options. Its not clear why we shouldn't just revert to unknown; but
Michael J. Spencer1a4fe8c2010-12-17 21:22:33 +00001703 // this isn't very important, we might as well be bug compatible.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001704 if (!InputType) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001705 Diag(clang::diag::err_drv_unknown_language) << A->getValue();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001706 InputType = types::TY_Object;
1707 }
Hans Wennborg091f1b62017-01-27 17:09:41 +00001708 } else if (A->getOption().getID() == options::OPT__SLASH_U) {
1709 assert(A->getNumValues() == 1 && "The /U option has one value.");
1710 StringRef Val = A->getValue(0);
1711 if (Val.find_first_of("/\\") != StringRef::npos) {
1712 // Warn about e.g. "/Users/me/myfile.c".
1713 Diag(diag::warn_slash_u_filename) << Val;
1714 Diag(diag::note_use_dashdash);
1715 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001716 }
1717 }
Hans Wennborg70850d82013-07-18 20:29:38 +00001718 if (CCCIsCPP() && Inputs.empty()) {
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00001719 // If called as standalone preprocessor, stdin is processed
1720 // if no other input is present.
David Blaikie0aaa7622017-01-13 17:34:15 +00001721 Arg *A = MakeInputArg(Args, *Opts, "-");
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00001722 Inputs.push_back(std::make_pair(types::TY_C, A));
1723 }
Chad Rosierecdede82011-08-12 22:08:57 +00001724}
1725
Samuel Antao64e965e2016-09-30 15:34:19 +00001726namespace {
1727/// Provides a convenient interface for different programming models to generate
1728/// the required device actions.
1729class OffloadingActionBuilder final {
1730 /// Flag used to trace errors in the builder.
1731 bool IsValid = false;
1732
1733 /// The compilation that is using this builder.
1734 Compilation &C;
1735
Samuel Antao64e965e2016-09-30 15:34:19 +00001736 /// Map between an input argument and the offload kinds used to process it.
1737 std::map<const Arg *, unsigned> InputArgToOffloadKindMap;
1738
1739 /// Builder interface. It doesn't build anything or keep any state.
1740 class DeviceActionBuilder {
1741 public:
1742 typedef llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PhasesTy;
1743
1744 enum ActionBuilderReturnCode {
1745 // The builder acted successfully on the current action.
1746 ABRT_Success,
1747 // The builder didn't have to act on the current action.
1748 ABRT_Inactive,
1749 // The builder was successful and requested the host action to not be
1750 // generated.
1751 ABRT_Ignore_Host,
1752 };
1753
1754 protected:
1755 /// Compilation associated with this builder.
1756 Compilation &C;
1757
1758 /// Tool chains associated with this builder. The same programming
1759 /// model may have associated one or more tool chains.
1760 SmallVector<const ToolChain *, 2> ToolChains;
1761
1762 /// The derived arguments associated with this builder.
1763 DerivedArgList &Args;
1764
1765 /// The inputs associated with this builder.
1766 const Driver::InputList &Inputs;
1767
1768 /// The associated offload kind.
1769 Action::OffloadKind AssociatedOffloadKind = Action::OFK_None;
1770
1771 public:
1772 DeviceActionBuilder(Compilation &C, DerivedArgList &Args,
1773 const Driver::InputList &Inputs,
1774 Action::OffloadKind AssociatedOffloadKind)
1775 : C(C), Args(Args), Inputs(Inputs),
1776 AssociatedOffloadKind(AssociatedOffloadKind) {}
1777 virtual ~DeviceActionBuilder() {}
1778
1779 /// Fill up the array \a DA with all the device dependences that should be
1780 /// added to the provided host action \a HostAction. By default it is
1781 /// inactive.
1782 virtual ActionBuilderReturnCode
Samuel Antao28c4f182016-10-27 17:08:03 +00001783 getDeviceDependences(OffloadAction::DeviceDependences &DA,
1784 phases::ID CurPhase, phases::ID FinalPhase,
1785 PhasesTy &Phases) {
Samuel Antao64e965e2016-09-30 15:34:19 +00001786 return ABRT_Inactive;
1787 }
1788
1789 /// Update the state to include the provided host action \a HostAction as a
1790 /// dependency of the current device action. By default it is inactive.
1791 virtual ActionBuilderReturnCode addDeviceDepences(Action *HostAction) {
1792 return ABRT_Inactive;
1793 }
1794
1795 /// Append top level actions generated by the builder. Return true if errors
1796 /// were found.
1797 virtual void appendTopLevelActions(ActionList &AL) {}
1798
1799 /// Append linker actions generated by the builder. Return true if errors
1800 /// were found.
1801 virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {}
1802
1803 /// Initialize the builder. Return true if any initialization errors are
1804 /// found.
1805 virtual bool initialize() { return false; }
1806
Samuel Antao69d6f312016-10-27 17:50:43 +00001807 /// Return true if the builder can use bundling/unbundling.
1808 virtual bool canUseBundlerUnbundler() const { return false; }
1809
Samuel Antao64e965e2016-09-30 15:34:19 +00001810 /// Return true if this builder is valid. We have a valid builder if we have
1811 /// associated device tool chains.
1812 bool isValid() { return !ToolChains.empty(); }
1813
1814 /// Return the associated offload kind.
1815 Action::OffloadKind getAssociatedOffloadKind() {
1816 return AssociatedOffloadKind;
1817 }
1818 };
1819
1820 /// \brief CUDA action builder. It injects device code in the host backend
1821 /// action.
1822 class CudaActionBuilder final : public DeviceActionBuilder {
1823 /// Flags to signal if the user requested host-only or device-only
1824 /// compilation.
1825 bool CompileHostOnly = false;
1826 bool CompileDeviceOnly = false;
1827
1828 /// List of GPU architectures to use in this compilation.
1829 SmallVector<CudaArch, 4> GpuArchList;
1830
1831 /// The CUDA actions for the current input.
1832 ActionList CudaDeviceActions;
1833
1834 /// The CUDA fat binary if it was generated for the current input.
1835 Action *CudaFatBinary = nullptr;
1836
1837 /// Flag that is set to true if this builder acted on the current input.
1838 bool IsActive = false;
1839
1840 public:
1841 CudaActionBuilder(Compilation &C, DerivedArgList &Args,
1842 const Driver::InputList &Inputs)
1843 : DeviceActionBuilder(C, Args, Inputs, Action::OFK_Cuda) {}
1844
1845 ActionBuilderReturnCode
Samuel Antao28c4f182016-10-27 17:08:03 +00001846 getDeviceDependences(OffloadAction::DeviceDependences &DA,
1847 phases::ID CurPhase, phases::ID FinalPhase,
1848 PhasesTy &Phases) override {
Samuel Antao64e965e2016-09-30 15:34:19 +00001849 if (!IsActive)
1850 return ABRT_Inactive;
1851
1852 // If we don't have more CUDA actions, we don't have any dependences to
1853 // create for the host.
1854 if (CudaDeviceActions.empty())
1855 return ABRT_Success;
1856
1857 assert(CudaDeviceActions.size() == GpuArchList.size() &&
1858 "Expecting one action per GPU architecture.");
1859 assert(!CompileHostOnly &&
1860 "Not expecting CUDA actions in host-only compilation.");
1861
1862 // If we are generating code for the device or we are in a backend phase,
1863 // we attempt to generate the fat binary. We compile each arch to ptx and
1864 // assemble to cubin, then feed the cubin *and* the ptx into a device
1865 // "link" action, which uses fatbinary to combine these cubins into one
1866 // fatbin. The fatbin is then an input to the host action if not in
1867 // device-only mode.
1868 if (CompileDeviceOnly || CurPhase == phases::Backend) {
1869 ActionList DeviceActions;
1870 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
1871 // Produce the device action from the current phase up to the assemble
1872 // phase.
1873 for (auto Ph : Phases) {
1874 // Skip the phases that were already dealt with.
1875 if (Ph < CurPhase)
1876 continue;
1877 // We have to be consistent with the host final phase.
1878 if (Ph > FinalPhase)
1879 break;
1880
1881 CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction(
1882 C, Args, Ph, CudaDeviceActions[I]);
1883
1884 if (Ph == phases::Assemble)
1885 break;
1886 }
1887
1888 // If we didn't reach the assemble phase, we can't generate the fat
1889 // binary. We don't need to generate the fat binary if we are not in
1890 // device-only mode.
1891 if (!isa<AssembleJobAction>(CudaDeviceActions[I]) ||
1892 CompileDeviceOnly)
1893 continue;
1894
1895 Action *AssembleAction = CudaDeviceActions[I];
1896 assert(AssembleAction->getType() == types::TY_Object);
1897 assert(AssembleAction->getInputs().size() == 1);
1898
1899 Action *BackendAction = AssembleAction->getInputs()[0];
1900 assert(BackendAction->getType() == types::TY_PP_Asm);
1901
1902 for (auto &A : {AssembleAction, BackendAction}) {
1903 OffloadAction::DeviceDependences DDep;
1904 DDep.add(*A, *ToolChains.front(), CudaArchToString(GpuArchList[I]),
1905 Action::OFK_Cuda);
1906 DeviceActions.push_back(
1907 C.MakeAction<OffloadAction>(DDep, A->getType()));
1908 }
1909 }
1910
1911 // We generate the fat binary if we have device input actions.
1912 if (!DeviceActions.empty()) {
1913 CudaFatBinary =
1914 C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN);
1915
1916 if (!CompileDeviceOnly) {
1917 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
1918 Action::OFK_Cuda);
1919 // Clear the fat binary, it is already a dependence to an host
1920 // action.
1921 CudaFatBinary = nullptr;
1922 }
1923
1924 // Remove the CUDA actions as they are already connected to an host
1925 // action or fat binary.
1926 CudaDeviceActions.clear();
1927 }
1928
1929 // We avoid creating host action in device-only mode.
1930 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
Samuel Antao5b1a89a2016-10-27 00:53:34 +00001931 } else if (CurPhase > phases::Backend) {
1932 // If we are past the backend phase and still have a device action, we
1933 // don't have to do anything as this action is already a device
1934 // top-level action.
1935 return ABRT_Success;
Samuel Antao64e965e2016-09-30 15:34:19 +00001936 }
1937
1938 assert(CurPhase < phases::Backend && "Generating single CUDA "
1939 "instructions should only occur "
1940 "before the backend phase!");
1941
1942 // By default, we produce an action for each device arch.
1943 for (Action *&A : CudaDeviceActions)
1944 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
1945
1946 return ABRT_Success;
1947 }
1948
1949 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
1950 // While generating code for CUDA, we only depend on the host input action
1951 // to trigger the creation of all the CUDA device actions.
1952
1953 // If we are dealing with an input action, replicate it for each GPU
1954 // architecture. If we are in host-only mode we return 'success' so that
1955 // the host uses the CUDA offload kind.
1956 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
1957 assert(!GpuArchList.empty() &&
1958 "We should have at least one GPU architecture.");
1959
1960 // If the host input is not CUDA, we don't need to bother about this
1961 // input.
1962 if (IA->getType() != types::TY_CUDA) {
1963 // The builder will ignore this input.
1964 IsActive = false;
1965 return ABRT_Inactive;
1966 }
1967
1968 // Set the flag to true, so that the builder acts on the current input.
1969 IsActive = true;
1970
1971 if (CompileHostOnly)
1972 return ABRT_Success;
1973
1974 // Replicate inputs for each GPU architecture.
1975 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
1976 CudaDeviceActions.push_back(C.MakeAction<InputAction>(
1977 IA->getInputArg(), types::TY_CUDA_DEVICE));
1978
1979 return ABRT_Success;
1980 }
1981
1982 return IsActive ? ABRT_Success : ABRT_Inactive;
1983 }
1984
1985 void appendTopLevelActions(ActionList &AL) override {
1986 // Utility to append actions to the top level list.
1987 auto AddTopLevel = [&](Action *A, CudaArch BoundArch) {
1988 OffloadAction::DeviceDependences Dep;
1989 Dep.add(*A, *ToolChains.front(), CudaArchToString(BoundArch),
1990 Action::OFK_Cuda);
1991 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
1992 };
1993
1994 // If we have a fat binary, add it to the list.
1995 if (CudaFatBinary) {
1996 AddTopLevel(CudaFatBinary, CudaArch::UNKNOWN);
1997 CudaDeviceActions.clear();
1998 CudaFatBinary = nullptr;
1999 return;
2000 }
2001
2002 if (CudaDeviceActions.empty())
2003 return;
2004
2005 // If we have CUDA actions at this point, that's because we have a have
2006 // partial compilation, so we should have an action for each GPU
2007 // architecture.
2008 assert(CudaDeviceActions.size() == GpuArchList.size() &&
2009 "Expecting one action per GPU architecture.");
2010 assert(ToolChains.size() == 1 &&
2011 "Expecting to have a sing CUDA toolchain.");
2012 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
2013 AddTopLevel(CudaDeviceActions[I], GpuArchList[I]);
2014
2015 CudaDeviceActions.clear();
2016 }
2017
2018 bool initialize() override {
2019 // We don't need to support CUDA.
2020 if (!C.hasOffloadToolChain<Action::OFK_Cuda>())
2021 return false;
2022
2023 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
2024 assert(HostTC && "No toolchain for host compilation.");
2025 if (HostTC->getTriple().isNVPTX()) {
2026 // We do not support targeting NVPTX for host compilation. Throw
2027 // an error and abort pipeline construction early so we don't trip
2028 // asserts that assume device-side compilation.
2029 C.getDriver().Diag(diag::err_drv_cuda_nvptx_host);
2030 return true;
2031 }
2032
2033 ToolChains.push_back(C.getSingleOffloadToolChain<Action::OFK_Cuda>());
2034
2035 Arg *PartialCompilationArg = Args.getLastArg(
2036 options::OPT_cuda_host_only, options::OPT_cuda_device_only,
2037 options::OPT_cuda_compile_host_device);
2038 CompileHostOnly = PartialCompilationArg &&
2039 PartialCompilationArg->getOption().matches(
2040 options::OPT_cuda_host_only);
2041 CompileDeviceOnly = PartialCompilationArg &&
2042 PartialCompilationArg->getOption().matches(
2043 options::OPT_cuda_device_only);
2044
2045 // Collect all cuda_gpu_arch parameters, removing duplicates.
Artem Belevicha424e882016-12-09 22:59:17 +00002046 std::set<CudaArch> GpuArchs;
Samuel Antao64e965e2016-09-30 15:34:19 +00002047 bool Error = false;
2048 for (Arg *A : Args) {
Artem Belevicha424e882016-12-09 22:59:17 +00002049 if (!(A->getOption().matches(options::OPT_cuda_gpu_arch_EQ) ||
2050 A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ)))
Samuel Antao64e965e2016-09-30 15:34:19 +00002051 continue;
2052 A->claim();
2053
Artem Belevicha424e882016-12-09 22:59:17 +00002054 const StringRef ArchStr = A->getValue();
2055 if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ) &&
2056 ArchStr == "all") {
2057 GpuArchs.clear();
2058 continue;
2059 }
Samuel Antao64e965e2016-09-30 15:34:19 +00002060 CudaArch Arch = StringToCudaArch(ArchStr);
2061 if (Arch == CudaArch::UNKNOWN) {
2062 C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
2063 Error = true;
Artem Belevicha424e882016-12-09 22:59:17 +00002064 } else if (A->getOption().matches(options::OPT_cuda_gpu_arch_EQ))
2065 GpuArchs.insert(Arch);
2066 else if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ))
2067 GpuArchs.erase(Arch);
2068 else
2069 llvm_unreachable("Unexpected option.");
Samuel Antao64e965e2016-09-30 15:34:19 +00002070 }
2071
Artem Belevicha424e882016-12-09 22:59:17 +00002072 // Collect list of GPUs remaining in the set.
2073 for (CudaArch Arch : GpuArchs)
2074 GpuArchList.push_back(Arch);
2075
2076 // Default to sm_20 which is the lowest common denominator for
2077 // supported GPUs. sm_20 code should work correctly, if
2078 // suboptimally, on all newer GPUs.
Samuel Antao64e965e2016-09-30 15:34:19 +00002079 if (GpuArchList.empty())
2080 GpuArchList.push_back(CudaArch::SM_20);
2081
2082 return Error;
2083 }
2084 };
2085
Samuel Antao28c4f182016-10-27 17:08:03 +00002086 /// OpenMP action builder. The host bitcode is passed to the device frontend
2087 /// and all the device linked images are passed to the host link phase.
2088 class OpenMPActionBuilder final : public DeviceActionBuilder {
2089 /// The OpenMP actions for the current input.
2090 ActionList OpenMPDeviceActions;
2091
2092 /// The linker inputs obtained for each toolchain.
2093 SmallVector<ActionList, 8> DeviceLinkerInputs;
2094
2095 public:
2096 OpenMPActionBuilder(Compilation &C, DerivedArgList &Args,
2097 const Driver::InputList &Inputs)
2098 : DeviceActionBuilder(C, Args, Inputs, Action::OFK_OpenMP) {}
2099
2100 ActionBuilderReturnCode
2101 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2102 phases::ID CurPhase, phases::ID FinalPhase,
2103 PhasesTy &Phases) override {
2104
2105 // We should always have an action for each input.
2106 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2107 "Number of OpenMP actions and toolchains do not match.");
2108
2109 // The host only depends on device action in the linking phase, when all
2110 // the device images have to be embedded in the host image.
2111 if (CurPhase == phases::Link) {
2112 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2113 "Toolchains and linker inputs sizes do not match.");
2114 auto LI = DeviceLinkerInputs.begin();
2115 for (auto *A : OpenMPDeviceActions) {
2116 LI->push_back(A);
2117 ++LI;
2118 }
2119
2120 // We passed the device action as a host dependence, so we don't need to
2121 // do anything else with them.
2122 OpenMPDeviceActions.clear();
2123 return ABRT_Success;
2124 }
2125
2126 // By default, we produce an action for each device arch.
2127 for (Action *&A : OpenMPDeviceActions)
2128 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2129
2130 return ABRT_Success;
2131 }
2132
2133 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2134
2135 // If this is an input action replicate it for each OpenMP toolchain.
2136 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2137 OpenMPDeviceActions.clear();
2138 for (unsigned I = 0; I < ToolChains.size(); ++I)
2139 OpenMPDeviceActions.push_back(
2140 C.MakeAction<InputAction>(IA->getInputArg(), IA->getType()));
2141 return ABRT_Success;
2142 }
2143
Samuel Antaofab4f372016-10-27 18:00:51 +00002144 // If this is an unbundling action use it as is for each OpenMP toolchain.
2145 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2146 OpenMPDeviceActions.clear();
2147 for (unsigned I = 0; I < ToolChains.size(); ++I) {
2148 OpenMPDeviceActions.push_back(UA);
2149 UA->registerDependentActionInfo(
2150 ToolChains[I], /*BoundArch=*/StringRef(), Action::OFK_OpenMP);
2151 }
2152 return ABRT_Success;
2153 }
2154
Samuel Antao28c4f182016-10-27 17:08:03 +00002155 // When generating code for OpenMP we use the host compile phase result as
2156 // a dependence to the device compile phase so that it can learn what
2157 // declarations should be emitted. However, this is not the only use for
2158 // the host action, so we prevent it from being collapsed.
2159 if (isa<CompileJobAction>(HostAction)) {
2160 HostAction->setCannotBeCollapsedWithNextDependentAction();
2161 assert(ToolChains.size() == OpenMPDeviceActions.size() &&
2162 "Toolchains and device action sizes do not match.");
2163 OffloadAction::HostDependence HDep(
2164 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2165 /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2166 auto TC = ToolChains.begin();
2167 for (Action *&A : OpenMPDeviceActions) {
2168 assert(isa<CompileJobAction>(A));
2169 OffloadAction::DeviceDependences DDep;
2170 DDep.add(*A, **TC, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2171 A = C.MakeAction<OffloadAction>(HDep, DDep);
2172 ++TC;
2173 }
2174 }
2175 return ABRT_Success;
2176 }
2177
Samuel Antao69d6f312016-10-27 17:50:43 +00002178 void appendTopLevelActions(ActionList &AL) override {
2179 if (OpenMPDeviceActions.empty())
2180 return;
2181
2182 // We should always have an action for each input.
2183 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2184 "Number of OpenMP actions and toolchains do not match.");
2185
2186 // Append all device actions followed by the proper offload action.
2187 auto TI = ToolChains.begin();
2188 for (auto *A : OpenMPDeviceActions) {
2189 OffloadAction::DeviceDependences Dep;
2190 Dep.add(*A, **TI, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2191 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2192 ++TI;
2193 }
2194 // We no longer need the action stored in this builder.
2195 OpenMPDeviceActions.clear();
2196 }
2197
Samuel Antao28c4f182016-10-27 17:08:03 +00002198 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {
2199 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2200 "Toolchains and linker inputs sizes do not match.");
2201
2202 // Append a new link action for each device.
2203 auto TC = ToolChains.begin();
2204 for (auto &LI : DeviceLinkerInputs) {
2205 auto *DeviceLinkAction =
2206 C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2207 DA.add(*DeviceLinkAction, **TC, /*BoundArch=*/nullptr,
2208 Action::OFK_OpenMP);
2209 ++TC;
2210 }
2211 }
2212
2213 bool initialize() override {
2214 // Get the OpenMP toolchains. If we don't get any, the action builder will
2215 // know there is nothing to do related to OpenMP offloading.
2216 auto OpenMPTCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
2217 for (auto TI = OpenMPTCRange.first, TE = OpenMPTCRange.second; TI != TE;
2218 ++TI)
2219 ToolChains.push_back(TI->second);
2220
2221 DeviceLinkerInputs.resize(ToolChains.size());
2222 return false;
2223 }
Samuel Antao69d6f312016-10-27 17:50:43 +00002224
2225 bool canUseBundlerUnbundler() const override {
2226 // OpenMP should use bundled files whenever possible.
2227 return true;
2228 }
Samuel Antao28c4f182016-10-27 17:08:03 +00002229 };
2230
2231 ///
2232 /// TODO: Add the implementation for other specialized builders here.
2233 ///
Samuel Antao64e965e2016-09-30 15:34:19 +00002234
2235 /// Specialized builders being used by this offloading action builder.
2236 SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders;
2237
Samuel Antao69d6f312016-10-27 17:50:43 +00002238 /// Flag set to true if all valid builders allow file bundling/unbundling.
2239 bool CanUseBundler;
2240
Samuel Antao64e965e2016-09-30 15:34:19 +00002241public:
2242 OffloadingActionBuilder(Compilation &C, DerivedArgList &Args,
2243 const Driver::InputList &Inputs)
Samuel Antao10e905c2016-10-27 01:08:58 +00002244 : C(C) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002245 // Create a specialized builder for each device toolchain.
2246
2247 IsValid = true;
2248
2249 // Create a specialized builder for CUDA.
2250 SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs));
2251
Samuel Antao28c4f182016-10-27 17:08:03 +00002252 // Create a specialized builder for OpenMP.
2253 SpecializedBuilders.push_back(new OpenMPActionBuilder(C, Args, Inputs));
2254
Samuel Antao64e965e2016-09-30 15:34:19 +00002255 //
2256 // TODO: Build other specialized builders here.
2257 //
2258
Samuel Antao69d6f312016-10-27 17:50:43 +00002259 // Initialize all the builders, keeping track of errors. If all valid
2260 // builders agree that we can use bundling, set the flag to true.
2261 unsigned ValidBuilders = 0u;
2262 unsigned ValidBuildersSupportingBundling = 0u;
2263 for (auto *SB : SpecializedBuilders) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002264 IsValid = IsValid && !SB->initialize();
Samuel Antao69d6f312016-10-27 17:50:43 +00002265
2266 // Update the counters if the builder is valid.
2267 if (SB->isValid()) {
2268 ++ValidBuilders;
2269 if (SB->canUseBundlerUnbundler())
2270 ++ValidBuildersSupportingBundling;
2271 }
2272 }
2273 CanUseBundler =
2274 ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling;
Artem Belevichf981e30b2016-08-02 22:37:47 +00002275 }
Justin Lebardc3c5042016-04-19 02:27:07 +00002276
Samuel Antao64e965e2016-09-30 15:34:19 +00002277 ~OffloadingActionBuilder() {
2278 for (auto *SB : SpecializedBuilders)
2279 delete SB;
Samuel Antaod06239d2016-07-15 23:13:27 +00002280 }
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002281
Samuel Antao64e965e2016-09-30 15:34:19 +00002282 /// Generate an action that adds device dependences (if any) to a host action.
2283 /// If no device dependence actions exist, just return the host action \a
2284 /// HostAction. If an error is found or if no builder requires the host action
2285 /// to be generated, return nullptr.
2286 Action *
2287 addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg,
2288 phases::ID CurPhase, phases::ID FinalPhase,
2289 DeviceActionBuilder::PhasesTy &Phases) {
2290 if (!IsValid)
2291 return nullptr;
Justin Lebar7bf77982016-01-11 23:27:13 +00002292
Samuel Antao64e965e2016-09-30 15:34:19 +00002293 if (SpecializedBuilders.empty())
2294 return HostAction;
2295
2296 assert(HostAction && "Invalid host action!");
2297
2298 OffloadAction::DeviceDependences DDeps;
2299 // Check if all the programming models agree we should not emit the host
2300 // action. Also, keep track of the offloading kinds employed.
2301 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2302 unsigned InactiveBuilders = 0u;
2303 unsigned IgnoringBuilders = 0u;
2304 for (auto *SB : SpecializedBuilders) {
2305 if (!SB->isValid()) {
2306 ++InactiveBuilders;
2307 continue;
2308 }
2309
Samuel Antao28c4f182016-10-27 17:08:03 +00002310 auto RetCode =
2311 SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases);
Samuel Antao64e965e2016-09-30 15:34:19 +00002312
2313 // If the builder explicitly says the host action should be ignored,
2314 // we need to increment the variable that tracks the builders that request
2315 // the host object to be ignored.
2316 if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host)
2317 ++IgnoringBuilders;
2318
2319 // Unless the builder was inactive for this action, we have to record the
2320 // offload kind because the host will have to use it.
2321 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2322 OffloadKind |= SB->getAssociatedOffloadKind();
2323 }
2324
2325 // If all builders agree that the host object should be ignored, just return
2326 // nullptr.
2327 if (IgnoringBuilders &&
2328 SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders))
2329 return nullptr;
2330
2331 if (DDeps.getActions().empty())
2332 return HostAction;
2333
2334 // We have dependences we need to bundle together. We use an offload action
2335 // for that.
2336 OffloadAction::HostDependence HDep(
2337 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2338 /*BoundArch=*/nullptr, DDeps);
2339 return C.MakeAction<OffloadAction>(HDep, DDeps);
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002340 }
2341
Samuel Antao64e965e2016-09-30 15:34:19 +00002342 /// Generate an action that adds a host dependence to a device action. The
2343 /// results will be kept in this action builder. Return true if an error was
2344 /// found.
Samuel Antaofab4f372016-10-27 18:00:51 +00002345 bool addHostDependenceToDeviceActions(Action *&HostAction,
Samuel Antao64e965e2016-09-30 15:34:19 +00002346 const Arg *InputArg) {
2347 if (!IsValid)
2348 return true;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002349
Samuel Antaofab4f372016-10-27 18:00:51 +00002350 // If we are supporting bundling/unbundling and the current action is an
2351 // input action of non-source file, we replace the host action by the
2352 // unbundling action. The bundler tool has the logic to detect if an input
2353 // is a bundle or not and if the input is not a bundle it assumes it is a
2354 // host file. Therefore it is safe to create an unbundling action even if
2355 // the input is not a bundle.
2356 if (CanUseBundler && isa<InputAction>(HostAction) &&
2357 InputArg->getOption().getKind() == llvm::opt::Option::InputClass &&
2358 !types::isSrcFile(HostAction->getType())) {
2359 auto UnbundlingHostAction =
2360 C.MakeAction<OffloadUnbundlingJobAction>(HostAction);
2361 UnbundlingHostAction->registerDependentActionInfo(
2362 C.getSingleOffloadToolChain<Action::OFK_Host>(),
2363 /*BoundArch=*/StringRef(), Action::OFK_Host);
2364 HostAction = UnbundlingHostAction;
2365 }
2366
Samuel Antao64e965e2016-09-30 15:34:19 +00002367 assert(HostAction && "Invalid host action!");
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002368
Samuel Antao64e965e2016-09-30 15:34:19 +00002369 // Register the offload kinds that are used.
2370 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2371 for (auto *SB : SpecializedBuilders) {
2372 if (!SB->isValid())
2373 continue;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002374
Samuel Antao64e965e2016-09-30 15:34:19 +00002375 auto RetCode = SB->addDeviceDepences(HostAction);
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002376
Samuel Antao64e965e2016-09-30 15:34:19 +00002377 // Host dependences for device actions are not compatible with that same
2378 // action being ignored.
2379 assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host &&
2380 "Host dependence not expected to be ignored.!");
Samuel Antaod06239d2016-07-15 23:13:27 +00002381
Samuel Antao64e965e2016-09-30 15:34:19 +00002382 // Unless the builder was inactive for this action, we have to record the
2383 // offload kind because the host will have to use it.
2384 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2385 OffloadKind |= SB->getAssociatedOffloadKind();
2386 }
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002387
Samuel Antao64e965e2016-09-30 15:34:19 +00002388 return false;
2389 }
2390
Samuel Antao69d6f312016-10-27 17:50:43 +00002391 /// Add the offloading top level actions to the provided action list. This
2392 /// function can replace the host action by a bundling action if the
2393 /// programming models allow it.
Samuel Antao64e965e2016-09-30 15:34:19 +00002394 bool appendTopLevelActions(ActionList &AL, Action *HostAction,
2395 const Arg *InputArg) {
Samuel Antao69d6f312016-10-27 17:50:43 +00002396 // Get the device actions to be appended.
2397 ActionList OffloadAL;
Samuel Antao64e965e2016-09-30 15:34:19 +00002398 for (auto *SB : SpecializedBuilders) {
2399 if (!SB->isValid())
2400 continue;
Samuel Antao69d6f312016-10-27 17:50:43 +00002401 SB->appendTopLevelActions(OffloadAL);
Samuel Antao64e965e2016-09-30 15:34:19 +00002402 }
2403
Samuel Antao69d6f312016-10-27 17:50:43 +00002404 // If we can use the bundler, replace the host action by the bundling one in
2405 // the resulting list. Otherwise, just append the device actions.
2406 if (CanUseBundler && !OffloadAL.empty()) {
2407 // Add the host action to the list in order to create the bundling action.
2408 OffloadAL.push_back(HostAction);
2409
2410 // We expect that the host action was just appended to the action list
2411 // before this method was called.
2412 assert(HostAction == AL.back() && "Host action not in the list??");
2413 HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL);
2414 AL.back() = HostAction;
2415 } else
2416 AL.append(OffloadAL.begin(), OffloadAL.end());
2417
Samuel Antao64e965e2016-09-30 15:34:19 +00002418 // Propagate to the current host action (if any) the offload information
2419 // associated with the current input.
2420 if (HostAction)
2421 HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg],
2422 /*BoundArch=*/nullptr);
Samuel Antao64e965e2016-09-30 15:34:19 +00002423 return false;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002424 }
Artem Belevich5bde4e02015-07-20 20:02:54 +00002425
Samuel Antao64e965e2016-09-30 15:34:19 +00002426 /// Processes the host linker action. This currently consists of replacing it
2427 /// with an offload action if there are device link objects and propagate to
2428 /// the host action all the offload kinds used in the current compilation. The
2429 /// resulting action is returned.
2430 Action *processHostLinkAction(Action *HostAction) {
2431 // Add all the dependences from the device linking actions.
2432 OffloadAction::DeviceDependences DDeps;
2433 for (auto *SB : SpecializedBuilders) {
2434 if (!SB->isValid())
2435 continue;
Justin Lebar21e5d4f2016-01-14 21:41:27 +00002436
Samuel Antao64e965e2016-09-30 15:34:19 +00002437 SB->appendLinkDependences(DDeps);
Justin Lebar21e5d4f2016-01-14 21:41:27 +00002438 }
Samuel Antaod06239d2016-07-15 23:13:27 +00002439
Samuel Antao64e965e2016-09-30 15:34:19 +00002440 // Calculate all the offload kinds used in the current compilation.
2441 unsigned ActiveOffloadKinds = 0u;
2442 for (auto &I : InputArgToOffloadKindMap)
2443 ActiveOffloadKinds |= I.second;
2444
2445 // If we don't have device dependencies, we don't have to create an offload
2446 // action.
2447 if (DDeps.getActions().empty()) {
2448 // Propagate all the active kinds to host action. Given that it is a link
2449 // action it is assumed to depend on all actions generated so far.
2450 HostAction->propagateHostOffloadInfo(ActiveOffloadKinds,
2451 /*BoundArch=*/nullptr);
2452 return HostAction;
2453 }
2454
2455 // Create the offload action with all dependences. When an offload action
2456 // is created the kinds are propagated to the host action, so we don't have
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002457 // to do that explicitly here.
Samuel Antao64e965e2016-09-30 15:34:19 +00002458 OffloadAction::HostDependence HDep(
2459 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2460 /*BoundArch*/ nullptr, ActiveOffloadKinds);
2461 return C.MakeAction<OffloadAction>(HDep, DDeps);
2462 }
2463};
2464} // anonymous namespace.
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002465
Justin Lebar0f3474c2016-02-11 02:00:50 +00002466void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
2467 const InputList &Inputs, ActionList &Actions) const {
Chad Rosierecdede82011-08-12 22:08:57 +00002468 llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00002469
Daniel Dunbar34c41872009-03-13 00:17:48 +00002470 if (!SuppressMissingInputWarning && Inputs.empty()) {
Daniel Dunbarbfeec742009-03-12 23:55:14 +00002471 Diag(clang::diag::err_drv_no_input_files);
2472 return;
2473 }
2474
Chad Rosier7742b5d2011-07-27 23:36:45 +00002475 Arg *FinalPhaseArg;
2476 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
Daniel Dunbarbfeec742009-03-12 23:55:14 +00002477
Bob Haarmanaaf51912017-02-27 19:40:19 +00002478 if (FinalPhase == phases::Link) {
2479 if (Args.hasArg(options::OPT_emit_llvm))
2480 Diag(clang::diag::err_drv_emit_llvm_link);
2481 if (IsCLMode() && LTOMode != LTOK_None &&
2482 !Args.getLastArgValue(options::OPT_fuse_ld_EQ).equals_lower("lld"))
2483 Diag(clang::diag::err_drv_lto_without_lld);
Rafael Espindolae8025642013-08-25 14:27:09 +00002484 }
2485
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002486 // Reject -Z* at the top level, these options should never have been exposed
2487 // by gcc.
Daniel Dunbardd765242009-03-26 16:12:09 +00002488 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
Daniel Dunbar0e759942009-03-20 06:14:23 +00002489 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
Daniel Dunbarbfeec742009-03-12 23:55:14 +00002490
Hans Wennborg13b7fe72013-08-12 23:26:25 +00002491 // Diagnose misuse of /Fo.
2492 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
Hans Wennborg13b7fe72013-08-12 23:26:25 +00002493 StringRef V = A->getValue();
Hans Wennborg61647532014-11-17 19:16:36 +00002494 if (Inputs.size() > 1 && !V.empty() &&
2495 !llvm::sys::path::is_separator(V.back())) {
Hans Wennborg13b7fe72013-08-12 23:26:25 +00002496 // Check whether /Fo tries to name an output file for multiple inputs.
Hans Wennborg9c1659b2013-10-18 22:49:04 +00002497 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002498 << A->getSpelling() << V;
Hans Wennborg13b7fe72013-08-12 23:26:25 +00002499 Args.eraseArg(options::OPT__SLASH_Fo);
2500 }
2501 }
2502
Hans Wennborg9c1659b2013-10-18 22:49:04 +00002503 // Diagnose misuse of /Fa.
2504 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
2505 StringRef V = A->getValue();
Hans Wennborg61647532014-11-17 19:16:36 +00002506 if (Inputs.size() > 1 && !V.empty() &&
2507 !llvm::sys::path::is_separator(V.back())) {
Hans Wennborg9c1659b2013-10-18 22:49:04 +00002508 // Check whether /Fa tries to name an asm file for multiple inputs.
2509 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002510 << A->getSpelling() << V;
Hans Wennborg9c1659b2013-10-18 22:49:04 +00002511 Args.eraseArg(options::OPT__SLASH_Fa);
2512 }
2513 }
2514
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00002515 // Diagnose misuse of /o.
2516 if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
2517 if (A->getValue()[0] == '\0') {
2518 // It has to have a value.
2519 Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
2520 Args.eraseArg(options::OPT__SLASH_o);
2521 }
2522 }
2523
Nico Weber2ca4be92016-03-01 23:16:44 +00002524 // Diagnose unsupported forms of /Yc /Yu. Ignore /Yc/Yu for now if:
2525 // * no filename after it
2526 // * both /Yc and /Yu passed but with different filenames
2527 // * corresponding file not also passed as /FI
2528 Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
2529 Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
2530 if (YcArg && YcArg->getValue()[0] == '\0') {
2531 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YcArg->getSpelling();
2532 Args.eraseArg(options::OPT__SLASH_Yc);
2533 YcArg = nullptr;
2534 }
2535 if (YuArg && YuArg->getValue()[0] == '\0') {
2536 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YuArg->getSpelling();
2537 Args.eraseArg(options::OPT__SLASH_Yu);
2538 YuArg = nullptr;
2539 }
2540 if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
2541 Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
2542 Args.eraseArg(options::OPT__SLASH_Yc);
2543 Args.eraseArg(options::OPT__SLASH_Yu);
2544 YcArg = YuArg = nullptr;
2545 }
2546 if (YcArg || YuArg) {
2547 StringRef Val = YcArg ? YcArg->getValue() : YuArg->getValue();
2548 bool FoundMatchingInclude = false;
2549 for (const Arg *Inc : Args.filtered(options::OPT_include)) {
2550 // FIXME: Do case-insensitive matching and consider / and \ as equal.
2551 if (Inc->getValue() == Val)
2552 FoundMatchingInclude = true;
2553 }
2554 if (!FoundMatchingInclude) {
2555 Diag(clang::diag::warn_drv_ycyu_no_fi_arg_clang_cl)
2556 << (YcArg ? YcArg : YuArg)->getSpelling();
2557 Args.eraseArg(options::OPT__SLASH_Yc);
2558 Args.eraseArg(options::OPT__SLASH_Yu);
2559 YcArg = YuArg = nullptr;
2560 }
2561 }
2562 if (YcArg && Inputs.size() > 1) {
2563 Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
2564 Args.eraseArg(options::OPT__SLASH_Yc);
2565 YcArg = nullptr;
2566 }
2567 if (Args.hasArg(options::OPT__SLASH_Y_)) {
2568 // /Y- disables all pch handling. Rather than check for it everywhere,
2569 // just remove clang-cl pch-related flags here.
2570 Args.eraseArg(options::OPT__SLASH_Fp);
2571 Args.eraseArg(options::OPT__SLASH_Yc);
2572 Args.eraseArg(options::OPT__SLASH_Yu);
2573 YcArg = YuArg = nullptr;
2574 }
Nico Weber2ca4be92016-03-01 23:16:44 +00002575
Samuel Antao64e965e2016-09-30 15:34:19 +00002576 // Builder to be used to build offloading actions.
2577 OffloadingActionBuilder OffloadBuilder(C, Args, Inputs);
Samuel Antaod06239d2016-07-15 23:13:27 +00002578
Daniel Dunbar65229332009-03-13 11:38:42 +00002579 // Construct the actions to perform.
2580 ActionList LinkerInputs;
Alp Toker965f8822013-11-27 05:22:15 +00002581
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002582 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL;
Artem Belevich5bde4e02015-07-20 20:02:54 +00002583 for (auto &I : Inputs) {
2584 types::ID InputType = I.first;
2585 const Arg *InputArg = I.second;
Daniel Dunbar65229332009-03-13 11:38:42 +00002586
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002587 PL.clear();
2588 types::getCompilationPhases(InputType, PL);
Daniel Dunbar65229332009-03-13 11:38:42 +00002589
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002590 // If the first step comes after the final phase we are doing as part of
2591 // this compilation, warn the user about it.
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002592 phases::ID InitialPhase = PL[0];
Daniel Dunbar65229332009-03-13 11:38:42 +00002593 if (InitialPhase > FinalPhase) {
Daniel Dunbaradc5c7c2009-03-19 07:57:08 +00002594 // Claim here to avoid the more general unused warning.
2595 InputArg->claim();
Daniel Dunbar07806ca2009-09-17 04:13:26 +00002596
Daniel Dunbar2db3e732011-04-20 15:44:48 +00002597 // Suppress all unused style warnings with -Qunused-arguments
2598 if (Args.hasArg(options::OPT_Qunused_arguments))
2599 continue;
2600
Richard Smith403f76e2012-08-06 04:09:06 +00002601 // Special case when final phase determined by binary name, rather than
2602 // by a command-line argument with a corresponding Arg.
Hans Wennborg70850d82013-07-18 20:29:38 +00002603 if (CCCIsCPP())
Richard Smith403f76e2012-08-06 04:09:06 +00002604 Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002605 << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
Daniel Dunbar07806ca2009-09-17 04:13:26 +00002606 // Special case '-E' warning on a previously preprocessed file to make
2607 // more sense.
Richard Smith403f76e2012-08-06 04:09:06 +00002608 else if (InitialPhase == phases::Compile &&
2609 FinalPhase == phases::Preprocess &&
2610 getPreprocessedType(InputType) == types::TY_INVALID)
Daniel Dunbar07806ca2009-09-17 04:13:26 +00002611 Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002612 << InputArg->getAsString(Args) << !!FinalPhaseArg
2613 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
Daniel Dunbar07806ca2009-09-17 04:13:26 +00002614 else
2615 Diag(clang::diag::warn_drv_input_file_unused)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002616 << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
2617 << !!FinalPhaseArg
2618 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
Daniel Dunbar65229332009-03-13 11:38:42 +00002619 continue;
2620 }
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002621
Nico Weberad2d8f32016-04-21 19:59:10 +00002622 if (YcArg) {
2623 // Add a separate precompile phase for the compile phase.
2624 if (FinalPhase >= phases::Compile) {
Richard Smith8cd452d2016-08-30 18:55:16 +00002625 const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType);
Nico Weberad2d8f32016-04-21 19:59:10 +00002626 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PCHPL;
Richard Smith8cd452d2016-08-30 18:55:16 +00002627 types::getCompilationPhases(HeaderType, PCHPL);
David Blaikie0aaa7622017-01-13 17:34:15 +00002628 Arg *PchInputArg = MakeInputArg(Args, *Opts, YcArg->getValue());
Nico Weberad2d8f32016-04-21 19:59:10 +00002629
2630 // Build the pipeline for the pch file.
Richard Smith8cd452d2016-08-30 18:55:16 +00002631 Action *ClangClPch =
2632 C.MakeAction<InputAction>(*PchInputArg, HeaderType);
Nico Weberad2d8f32016-04-21 19:59:10 +00002633 for (phases::ID Phase : PCHPL)
2634 ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
2635 assert(ClangClPch);
2636 Actions.push_back(ClangClPch);
2637 // The driver currently exits after the first failed command. This
2638 // relies on that behavior, to make sure if the pch generation fails,
2639 // the main compilation won't run.
2640 }
2641 }
2642
Daniel Dunbar65229332009-03-13 11:38:42 +00002643 // Build the pipeline for this file.
Justin Lebar41094612016-01-11 23:07:27 +00002644 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
Samuel Antao64e965e2016-09-30 15:34:19 +00002645
2646 // Use the current host action in any of the offloading actions, if
2647 // required.
2648 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
2649 break;
2650
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002651 for (SmallVectorImpl<phases::ID>::iterator i = PL.begin(), e = PL.end();
2652 i != e; ++i) {
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002653 phases::ID Phase = *i;
Daniel Dunbar65229332009-03-13 11:38:42 +00002654
2655 // We are done if this step is past what the user requested.
2656 if (Phase > FinalPhase)
2657 break;
2658
Samuel Antao64e965e2016-09-30 15:34:19 +00002659 // Add any offload action the host action depends on.
2660 Current = OffloadBuilder.addDeviceDependencesToHostAction(
2661 Current, InputArg, Phase, FinalPhase, PL);
2662 if (!Current)
2663 break;
2664
Daniel Dunbar65229332009-03-13 11:38:42 +00002665 // Queue linker inputs.
2666 if (Phase == phases::Link) {
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002667 assert((i + 1) == e && "linking must be final compilation step.");
Justin Lebar41094612016-01-11 23:07:27 +00002668 LinkerInputs.push_back(Current);
2669 Current = nullptr;
Daniel Dunbar65229332009-03-13 11:38:42 +00002670 break;
2671 }
2672
Samuel Antao64e965e2016-09-30 15:34:19 +00002673 // Otherwise construct the appropriate action.
2674 auto *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current);
2675
2676 // We didn't create a new action, so we will just move to the next phase.
2677 if (NewCurrent == Current)
Daniel Dunbar13864952009-03-24 20:17:30 +00002678 continue;
2679
Samuel Antao64e965e2016-09-30 15:34:19 +00002680 Current = NewCurrent;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002681
Samuel Antao64e965e2016-09-30 15:34:19 +00002682 // Use the current host action in any of the offloading actions, if
2683 // required.
2684 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
2685 break;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002686
Daniel Dunbar65229332009-03-13 11:38:42 +00002687 if (Current->getType() == types::TY_Nothing)
2688 break;
2689 }
2690
Samuel Antao64e965e2016-09-30 15:34:19 +00002691 // If we ended with something, add to the output list.
2692 if (Current)
Justin Lebar41094612016-01-11 23:07:27 +00002693 Actions.push_back(Current);
Samuel Antao64e965e2016-09-30 15:34:19 +00002694
2695 // Add any top level actions generated for offloading.
2696 OffloadBuilder.appendTopLevelActions(Actions, Current, InputArg);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002697 }
Daniel Dunbar65229332009-03-13 11:38:42 +00002698
Samuel Antao64e965e2016-09-30 15:34:19 +00002699 // Add a link action if necessary.
Samuel Antaod06239d2016-07-15 23:13:27 +00002700 if (!LinkerInputs.empty()) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002701 Action *LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image);
2702 LA = OffloadBuilder.processHostLinkAction(LA);
2703 Actions.push_back(LA);
Samuel Antaod06239d2016-07-15 23:13:27 +00002704 }
Daniel Dunbarc7a67b72009-12-22 23:19:32 +00002705
2706 // If we are linking, claim any options which are obviously only used for
2707 // compilation.
Hans Wennborga8ef14f2013-09-17 00:03:41 +00002708 if (FinalPhase == phases::Link && PL.size() == 1) {
Daniel Dunbarc7a67b72009-12-22 23:19:32 +00002709 Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
Hans Wennborga8ef14f2013-09-17 00:03:41 +00002710 Args.ClaimAllArgs(options::OPT_cl_compile_Group);
2711 }
2712
2713 // Claim ignored clang-cl options.
2714 Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
Artem Belevichbaae0932015-07-28 21:01:30 +00002715
Justin Lebardc3c5042016-04-19 02:27:07 +00002716 // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed
2717 // to non-CUDA compilations and should not trigger warnings there.
Artem Belevichbaae0932015-07-28 21:01:30 +00002718 Args.ClaimAllArgs(options::OPT_cuda_host_only);
Justin Lebardc3c5042016-04-19 02:27:07 +00002719 Args.ClaimAllArgs(options::OPT_cuda_compile_host_device);
Daniel Dunbar65229332009-03-13 11:38:42 +00002720}
2721
Justin Lebar0f3474c2016-02-11 02:00:50 +00002722Action *Driver::ConstructPhaseAction(Compilation &C, const ArgList &Args,
2723 phases::ID Phase, Action *Input) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00002724 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
Samuel Antao64e965e2016-09-30 15:34:19 +00002725
2726 // Some types skip the assembler phase (e.g., llvm-bc), but we can't
2727 // encode this in the steps because the intermediate type depends on
2728 // arguments. Just special case here.
2729 if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm)
2730 return Input;
2731
Daniel Dunbar65229332009-03-13 11:38:42 +00002732 // Build the appropriate action.
2733 switch (Phase) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002734 case phases::Link:
2735 llvm_unreachable("link action invalid here.");
Daniel Dunbar65229332009-03-13 11:38:42 +00002736 case phases::Preprocess: {
Daniel Dunbard67a3222009-03-30 06:36:42 +00002737 types::ID OutputTy;
2738 // -{M, MM} alter the output type.
Daniel Dunbar86aed7d2010-12-08 21:33:40 +00002739 if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
Daniel Dunbard67a3222009-03-30 06:36:42 +00002740 OutputTy = types::TY_Dependencies;
2741 } else {
David Blaikie5d577a22012-06-29 22:03:56 +00002742 OutputTy = Input->getType();
2743 if (!Args.hasFlag(options::OPT_frewrite_includes,
Justin Bognerce8245b2014-06-24 08:01:01 +00002744 options::OPT_fno_rewrite_includes, false) &&
Richard Smith86a3ef52017-06-09 21:24:02 +00002745 !Args.hasFlag(options::OPT_frewrite_imports,
2746 options::OPT_fno_rewrite_imports, false) &&
Justin Bognerce8245b2014-06-24 08:01:01 +00002747 !CCGenDiagnostics)
David Blaikie5d577a22012-06-29 22:03:56 +00002748 OutputTy = types::getPreprocessedType(OutputTy);
Daniel Dunbard67a3222009-03-30 06:36:42 +00002749 assert(OutputTy != types::TY_INVALID &&
2750 "Cannot preprocess this input type!");
2751 }
Justin Lebar41094612016-01-11 23:07:27 +00002752 return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
Daniel Dunbar65229332009-03-13 11:38:42 +00002753 }
Aaron Ballman1f10cc52012-07-31 01:21:00 +00002754 case phases::Precompile: {
Richard Smithdd4ad3d2016-08-30 19:06:26 +00002755 types::ID OutputTy = getPrecompiledType(Input->getType());
2756 assert(OutputTy != types::TY_INVALID &&
2757 "Cannot precompile this input type!");
Aaron Ballman1f10cc52012-07-31 01:21:00 +00002758 if (Args.hasArg(options::OPT_fsyntax_only)) {
2759 // Syntax checks should not emit a PCH file
2760 OutputTy = types::TY_Nothing;
2761 }
Justin Lebar41094612016-01-11 23:07:27 +00002762 return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
Aaron Ballman1f10cc52012-07-31 01:21:00 +00002763 }
Daniel Dunbar65229332009-03-13 11:38:42 +00002764 case phases::Compile: {
David Blaikie486f4402014-08-29 07:25:23 +00002765 if (Args.hasArg(options::OPT_fsyntax_only))
Justin Lebar41094612016-01-11 23:07:27 +00002766 return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
David Blaikie486f4402014-08-29 07:25:23 +00002767 if (Args.hasArg(options::OPT_rewrite_objc))
Justin Lebar41094612016-01-11 23:07:27 +00002768 return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
David Blaikie486f4402014-08-29 07:25:23 +00002769 if (Args.hasArg(options::OPT_rewrite_legacy_objc))
Justin Lebar41094612016-01-11 23:07:27 +00002770 return C.MakeAction<CompileJobAction>(Input,
2771 types::TY_RewrittenLegacyObjC);
David Blaikie486f4402014-08-29 07:25:23 +00002772 if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto))
Justin Lebar41094612016-01-11 23:07:27 +00002773 return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
David Blaikie486f4402014-08-29 07:25:23 +00002774 if (Args.hasArg(options::OPT__migrate))
Justin Lebar41094612016-01-11 23:07:27 +00002775 return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
David Blaikie486f4402014-08-29 07:25:23 +00002776 if (Args.hasArg(options::OPT_emit_ast))
Justin Lebar41094612016-01-11 23:07:27 +00002777 return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
David Blaikie486f4402014-08-29 07:25:23 +00002778 if (Args.hasArg(options::OPT_module_file_info))
Justin Lebar41094612016-01-11 23:07:27 +00002779 return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
David Blaikie486f4402014-08-29 07:25:23 +00002780 if (Args.hasArg(options::OPT_verify_pch))
Justin Lebar41094612016-01-11 23:07:27 +00002781 return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
2782 return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
Bob Wilson23a55f12014-12-21 07:00:00 +00002783 }
2784 case phases::Backend: {
Teresa Johnson945bc502015-10-15 20:35:53 +00002785 if (isUsingLTO()) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002786 types::ID Output =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002787 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
Justin Lebar41094612016-01-11 23:07:27 +00002788 return C.MakeAction<BackendJobAction>(Input, Output);
David Blaikie486f4402014-08-29 07:25:23 +00002789 }
2790 if (Args.hasArg(options::OPT_emit_llvm)) {
Shuxin Yang4b3c7ff2013-08-23 21:34:57 +00002791 types::ID Output =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002792 Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
Justin Lebar41094612016-01-11 23:07:27 +00002793 return C.MakeAction<BackendJobAction>(Input, Output);
Daniel Dunbar65229332009-03-13 11:38:42 +00002794 }
Justin Lebar41094612016-01-11 23:07:27 +00002795 return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
Daniel Dunbar65229332009-03-13 11:38:42 +00002796 }
2797 case phases::Assemble:
Justin Lebar21e5d4f2016-01-14 21:41:27 +00002798 return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
Daniel Dunbar65229332009-03-13 11:38:42 +00002799 }
2800
David Blaikie83d382b2011-09-23 05:06:16 +00002801 llvm_unreachable("invalid phase in ConstructPhaseAction");
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002802}
2803
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00002804void Driver::BuildJobs(Compilation &C) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00002805 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
Daniel Dunbare75d8342009-03-16 06:56:51 +00002806
2807 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
2808
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002809 // It is an error to provide a -o option if we are making multiple output
2810 // files.
Daniel Dunbare75d8342009-03-16 06:56:51 +00002811 if (FinalOutput) {
2812 unsigned NumOutputs = 0;
Saleem Abdulrasoolda3f4e52014-12-29 21:02:47 +00002813 for (const Action *A : C.getActions())
2814 if (A->getType() != types::TY_Nothing)
Daniel Dunbare75d8342009-03-16 06:56:51 +00002815 ++NumOutputs;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002816
Daniel Dunbare75d8342009-03-16 06:56:51 +00002817 if (NumOutputs > 1) {
2818 Diag(clang::diag::err_drv_output_argument_with_multiple_files);
Craig Topper92fc2df2014-05-17 16:56:41 +00002819 FinalOutput = nullptr;
Daniel Dunbare75d8342009-03-16 06:56:51 +00002820 }
2821 }
2822
Chad Rosier35767232013-04-30 22:01:21 +00002823 // Collect the list of architectures.
2824 llvm::StringSet<> ArchNames;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00002825 if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO())
2826 for (const Arg *A : C.getArgs())
Chad Rosier35767232013-04-30 22:01:21 +00002827 if (A->getOption().matches(options::OPT_arch))
2828 ArchNames.insert(A->getValue());
Chad Rosier35767232013-04-30 22:01:21 +00002829
Justin Lebarb44f6fe2016-01-14 21:41:21 +00002830 // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
2831 std::map<std::pair<const Action *, std::string>, InputInfo> CachedResults;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00002832 for (Action *A : C.getActions()) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002833 // If we are linking an image for multiple archs then the linker wants
2834 // -arch_multiple and -final_output <final image name>. Unfortunately, this
2835 // doesn't fit in cleanly because we have to pass this information down.
Daniel Dunbare75d8342009-03-16 06:56:51 +00002836 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002837 // FIXME: This is a hack; find a cleaner way to integrate this into the
2838 // process.
Craig Topper92fc2df2014-05-17 16:56:41 +00002839 const char *LinkingOutput = nullptr;
Daniel Dunbardd765242009-03-26 16:12:09 +00002840 if (isa<LipoJobAction>(A)) {
Daniel Dunbare75d8342009-03-16 06:56:51 +00002841 if (FinalOutput)
Richard Smithbd55daf2012-11-01 04:30:05 +00002842 LinkingOutput = FinalOutput->getValue();
Daniel Dunbare75d8342009-03-16 06:56:51 +00002843 else
Hans Wennborga7707222015-01-09 17:38:53 +00002844 LinkingOutput = getDefaultImageName();
Daniel Dunbare75d8342009-03-16 06:56:51 +00002845 }
2846
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002847 BuildJobsForAction(C, A, &C.getDefaultToolChain(),
Mehdi Aminic50b1a22016-10-07 21:27:26 +00002848 /*BoundArch*/ StringRef(),
Daniel Dunbare75d8342009-03-16 06:56:51 +00002849 /*AtTopLevel*/ true,
Chad Rosier35767232013-04-30 22:01:21 +00002850 /*MultipleArchs*/ ArchNames.size() > 1,
Samuel Antaod06239d2016-07-15 23:13:27 +00002851 /*LinkingOutput*/ LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00002852 /*TargetDeviceOffloadKind*/ Action::OFK_None);
Daniel Dunbare75d8342009-03-16 06:56:51 +00002853 }
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00002854
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002855 // If the user passed -Qunused-arguments or there were errors, don't warn
2856 // about any unused arguments.
Argyrios Kyrtzidis31448a42010-11-18 21:47:07 +00002857 if (Diags.hasErrorOccurred() ||
Daniel Dunbara3cfbe32009-04-07 19:04:18 +00002858 C.getArgs().hasArg(options::OPT_Qunused_arguments))
Daniel Dunbard175d972009-03-18 18:03:46 +00002859 return;
2860
Daniel Dunbar58399ae2009-03-29 22:24:54 +00002861 // Claim -### here.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002862 (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002863
Nico Weber47bf5052016-04-25 21:15:49 +00002864 // Claim --driver-mode, --rsp-quoting, it was handled earlier.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002865 (void)C.getArgs().hasArg(options::OPT_driver_mode);
Nico Weber47bf5052016-04-25 21:15:49 +00002866 (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
Hans Wennborg70850d82013-07-18 20:29:38 +00002867
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00002868 for (Arg *A : C.getArgs()) {
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00002869 // FIXME: It would be nice to be able to send the argument to the
David Blaikie9c902b52011-09-25 23:23:43 +00002870 // DiagnosticsEngine, so that extra values, position, and so on could be
2871 // printed.
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00002872 if (!A->isClaimed()) {
Michael J. Spencer66e2b202012-10-19 22:37:06 +00002873 if (A->getOption().hasFlag(options::NoArgumentUnused))
Daniel Dunbara3cfbe32009-04-07 19:04:18 +00002874 continue;
2875
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002876 // Suppress the warning automatically if this is just a flag, and it is an
2877 // instance of an argument we already claimed.
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00002878 const Option &Opt = A->getOption();
Michael J. Spencerad3ccc32012-08-20 21:41:17 +00002879 if (Opt.getKind() == Option::FlagClass) {
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00002880 bool DuplicateClaimed = false;
2881
Sean Silva14facf32015-06-09 01:57:17 +00002882 for (const Arg *AA : C.getArgs().filtered(&Opt)) {
2883 if (AA->isClaimed()) {
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00002884 DuplicateClaimed = true;
2885 break;
2886 }
2887 }
2888
2889 if (DuplicateClaimed)
2890 continue;
2891 }
2892
Ehsan Akhgarid8518332016-01-25 21:14:52 +00002893 // In clang-cl, don't mention unknown arguments here since they have
2894 // already been warned about.
2895 if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN))
2896 Diag(clang::diag::warn_drv_unused_argument)
2897 << A->getAsString(C.getArgs());
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00002898 }
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00002899 }
Daniel Dunbar95e6b192009-03-13 22:12:33 +00002900}
Daniel Dunbarc4343942010-02-03 03:07:56 +00002901
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002902namespace {
2903/// Utility class to control the collapse of dependent actions and select the
2904/// tools accordingly.
2905class ToolSelector final {
2906 /// The tool chain this selector refers to.
2907 const ToolChain &TC;
Daniel Dunbarf9ff3502010-05-14 02:03:00 +00002908
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002909 /// The compilation this selector refers to.
2910 const Compilation &C;
Samuel Antaod06239d2016-07-15 23:13:27 +00002911
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002912 /// The base action this selector refers to.
2913 const JobAction *BaseAction;
Samuel Antaod06239d2016-07-15 23:13:27 +00002914
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002915 /// Set to true if the current toolchain refers to host actions.
2916 bool IsHostSelector;
Samuel Antaod06239d2016-07-15 23:13:27 +00002917
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002918 /// Set to true if save-temps and embed-bitcode functionalities are active.
2919 bool SaveTemps;
2920 bool EmbedBitcode;
2921
2922 /// Get previous dependent action or null if that does not exist. If
2923 /// \a CanBeCollapsed is false, that action must be legal to collapse or
2924 /// null will be returned.
2925 const JobAction *getPrevDependentAction(const ActionList &Inputs,
2926 ActionList &SavedOffloadAction,
2927 bool CanBeCollapsed = true) {
2928 // An option can be collapsed only if it has a single input.
2929 if (Inputs.size() != 1)
Craig Topper92fc2df2014-05-17 16:56:41 +00002930 return nullptr;
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002931
2932 Action *CurAction = *Inputs.begin();
2933 if (CanBeCollapsed &&
2934 !CurAction->isCollapsingWithNextDependentActionLegal())
2935 return nullptr;
2936
2937 // If the input action is an offload action. Look through it and save any
2938 // offload action that can be dropped in the event of a collapse.
2939 if (auto *OA = dyn_cast<OffloadAction>(CurAction)) {
2940 // If the dependent action is a device action, we will attempt to collapse
2941 // only with other device actions. Otherwise, we would do the same but
2942 // with host actions only.
2943 if (!IsHostSelector) {
2944 if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) {
2945 CurAction =
2946 OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
2947 if (CanBeCollapsed &&
2948 !CurAction->isCollapsingWithNextDependentActionLegal())
2949 return nullptr;
2950 SavedOffloadAction.push_back(OA);
2951 return dyn_cast<JobAction>(CurAction);
2952 }
2953 } else if (OA->hasHostDependence()) {
2954 CurAction = OA->getHostDependence();
2955 if (CanBeCollapsed &&
2956 !CurAction->isCollapsingWithNextDependentActionLegal())
2957 return nullptr;
2958 SavedOffloadAction.push_back(OA);
2959 return dyn_cast<JobAction>(CurAction);
2960 }
2961 return nullptr;
2962 }
2963
2964 return dyn_cast<JobAction>(CurAction);
2965 }
2966
2967 /// Return true if an assemble action can be collapsed.
2968 bool canCollapseAssembleAction() const {
2969 return TC.useIntegratedAs() && !SaveTemps &&
2970 !C.getArgs().hasArg(options::OPT_via_file_asm) &&
2971 !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
2972 !C.getArgs().hasArg(options::OPT__SLASH_Fa);
2973 }
2974
2975 /// Return true if a preprocessor action can be collapsed.
2976 bool canCollapsePreprocessorAction() const {
2977 return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
2978 !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
2979 !C.getArgs().hasArg(options::OPT_rewrite_objc);
2980 }
2981
2982 /// Struct that relates an action with the offload actions that would be
2983 /// collapsed with it.
2984 struct JobActionInfo final {
2985 /// The action this info refers to.
2986 const JobAction *JA = nullptr;
2987 /// The offload actions we need to take care off if this action is
2988 /// collapsed.
2989 ActionList SavedOffloadAction;
2990 };
2991
2992 /// Append collapsed offload actions from the give nnumber of elements in the
2993 /// action info array.
2994 static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction,
2995 ArrayRef<JobActionInfo> &ActionInfo,
2996 unsigned ElementNum) {
2997 assert(ElementNum <= ActionInfo.size() && "Invalid number of elements.");
2998 for (unsigned I = 0; I < ElementNum; ++I)
2999 CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(),
3000 ActionInfo[I].SavedOffloadAction.end());
3001 }
3002
3003 /// Functions that attempt to perform the combining. They detect if that is
3004 /// legal, and if so they update the inputs \a Inputs and the offload action
3005 /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with
3006 /// the combined action is returned. If the combining is not legal or if the
3007 /// tool does not exist, null is returned.
3008 /// Currently three kinds of collapsing are supported:
3009 /// - Assemble + Backend + Compile;
3010 /// - Assemble + Backend ;
3011 /// - Backend + Compile.
3012 const Tool *
3013 combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
3014 const ActionList *&Inputs,
3015 ActionList &CollapsedOffloadAction) {
3016 if (ActionInfo.size() < 3 || !canCollapseAssembleAction())
3017 return nullptr;
3018 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
3019 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
3020 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA);
3021 if (!AJ || !BJ || !CJ)
3022 return nullptr;
3023
3024 // Get compiler tool.
3025 const Tool *T = TC.SelectTool(*CJ);
3026 if (!T)
3027 return nullptr;
3028
Steven Wu574b0f22016-03-01 01:07:58 +00003029 // When using -fembed-bitcode, it is required to have the same tool (clang)
3030 // for both CompilerJA and BackendJA. Otherwise, combine two stages.
3031 if (EmbedBitcode) {
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003032 const Tool *BT = TC.SelectTool(*BJ);
3033 if (BT == T)
3034 return nullptr;
Steven Wu574b0f22016-03-01 01:07:58 +00003035 }
Bob Wilson23a55f12014-12-21 07:00:00 +00003036
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003037 if (!T->hasIntegratedAssembler())
Bob Wilson23a55f12014-12-21 07:00:00 +00003038 return nullptr;
Samuel Antaod06239d2016-07-15 23:13:27 +00003039
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003040 Inputs = &CJ->getInputs();
3041 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3042 /*NumElements=*/3);
3043 return T;
3044 }
3045 const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo,
3046 const ActionList *&Inputs,
3047 ActionList &CollapsedOffloadAction) {
3048 if (ActionInfo.size() < 2 || !canCollapseAssembleAction())
3049 return nullptr;
3050 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
3051 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
3052 if (!AJ || !BJ)
3053 return nullptr;
3054
3055 // Retrieve the compile job, backend action must always be preceded by one.
3056 ActionList CompileJobOffloadActions;
3057 auto *CJ = getPrevDependentAction(BJ->getInputs(), CompileJobOffloadActions,
3058 /*CanBeCollapsed=*/false);
3059 if (!AJ || !BJ || !CJ)
3060 return nullptr;
3061
3062 assert(isa<CompileJobAction>(CJ) &&
3063 "Expecting compile job preceding backend job.");
3064
3065 // Get compiler tool.
3066 const Tool *T = TC.SelectTool(*CJ);
3067 if (!T)
3068 return nullptr;
3069
3070 if (!T->hasIntegratedAssembler())
3071 return nullptr;
3072
3073 Inputs = &BJ->getInputs();
3074 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3075 /*NumElements=*/2);
3076 return T;
3077 }
3078 const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
3079 const ActionList *&Inputs,
3080 ActionList &CollapsedOffloadAction) {
3081 if (ActionInfo.size() < 2 || !canCollapsePreprocessorAction())
3082 return nullptr;
3083 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA);
3084 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA);
3085 if (!BJ || !CJ)
3086 return nullptr;
3087
3088 // Get compiler tool.
3089 const Tool *T = TC.SelectTool(*CJ);
3090 if (!T)
3091 return nullptr;
3092
3093 if (T->canEmitIR() && (SaveTemps || EmbedBitcode))
3094 return nullptr;
3095
3096 Inputs = &CJ->getInputs();
3097 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3098 /*NumElements=*/2);
3099 return T;
3100 }
3101
3102 /// Updates the inputs if the obtained tool supports combining with
3103 /// preprocessor action, and the current input is indeed a preprocessor
3104 /// action. If combining results in the collapse of offloading actions, those
3105 /// are appended to \a CollapsedOffloadAction.
3106 void combineWithPreprocessor(const Tool *T, const ActionList *&Inputs,
3107 ActionList &CollapsedOffloadAction) {
3108 if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP())
3109 return;
3110
3111 // Attempt to get a preprocessor action dependence.
3112 ActionList PreprocessJobOffloadActions;
3113 auto *PJ = getPrevDependentAction(*Inputs, PreprocessJobOffloadActions);
3114 if (!PJ || !isa<PreprocessJobAction>(PJ))
3115 return;
3116
3117 // This is legal to combine. Append any offload action we found and set the
3118 // current inputs to preprocessor inputs.
3119 CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(),
3120 PreprocessJobOffloadActions.end());
3121 Inputs = &PJ->getInputs();
3122 }
3123
3124public:
3125 ToolSelector(const JobAction *BaseAction, const ToolChain &TC,
3126 const Compilation &C, bool SaveTemps, bool EmbedBitcode)
3127 : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps),
3128 EmbedBitcode(EmbedBitcode) {
3129 assert(BaseAction && "Invalid base action.");
3130 IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None;
3131 }
3132
3133 /// Check if a chain of actions can be combined and return the tool that can
3134 /// handle the combination of actions. The pointer to the current inputs \a
3135 /// Inputs and the list of offload actions \a CollapsedOffloadActions
3136 /// connected to collapsed actions are updated accordingly. The latter enables
3137 /// the caller of the selector to process them afterwards instead of just
3138 /// dropping them. If no suitable tool is found, null will be returned.
3139 const Tool *getTool(const ActionList *&Inputs,
3140 ActionList &CollapsedOffloadAction) {
3141 //
3142 // Get the largest chain of actions that we could combine.
3143 //
3144
3145 SmallVector<JobActionInfo, 5> ActionChain(1);
3146 ActionChain.back().JA = BaseAction;
3147 while (ActionChain.back().JA) {
3148 const Action *CurAction = ActionChain.back().JA;
3149
3150 // Grow the chain by one element.
3151 ActionChain.resize(ActionChain.size() + 1);
3152 JobActionInfo &AI = ActionChain.back();
3153
3154 // Attempt to fill it with the
3155 AI.JA =
3156 getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction);
Daniel Dunbarc4343942010-02-03 03:07:56 +00003157 }
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003158
3159 // Pop the last action info as it could not be filled.
3160 ActionChain.pop_back();
3161
3162 //
3163 // Attempt to combine actions. If all combining attempts failed, just return
3164 // the tool of the provided action. At the end we attempt to combine the
3165 // action with any preprocessor action it may depend on.
3166 //
3167
3168 const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs,
3169 CollapsedOffloadAction);
3170 if (!T)
3171 T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction);
3172 if (!T)
3173 T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction);
3174 if (!T) {
3175 Inputs = &BaseAction->getInputs();
3176 T = TC.SelectTool(*BaseAction);
3177 }
3178
3179 combineWithPreprocessor(T, Inputs, CollapsedOffloadAction);
3180 return T;
Daniel Dunbarc4343942010-02-03 03:07:56 +00003181 }
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003182};
Daniel Dunbarc4343942010-02-03 03:07:56 +00003183}
3184
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003185/// Return a string that uniquely identifies the result of a job. The bound arch
3186/// is not necessarily represented in the toolchain's triple -- for example,
3187/// armv7 and armv7s both map to the same triple -- so we need both in our map.
3188/// Also, we need to add the offloading device kind, as the same tool chain can
3189/// be used for host and device for some programming models, e.g. OpenMP.
3190static std::string GetTriplePlusArchString(const ToolChain *TC,
3191 StringRef BoundArch,
3192 Action::OffloadKind OffloadKind) {
Justin Lebar55c83322016-01-16 03:30:08 +00003193 std::string TriplePlusArch = TC->getTriple().normalize();
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003194 if (!BoundArch.empty()) {
Justin Lebar55c83322016-01-16 03:30:08 +00003195 TriplePlusArch += "-";
3196 TriplePlusArch += BoundArch;
3197 }
Samuel Antao59efaed2016-10-27 17:31:22 +00003198 TriplePlusArch += "-";
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003199 TriplePlusArch += Action::GetOffloadKindName(OffloadKind);
3200 return TriplePlusArch;
3201}
3202
3203InputInfo Driver::BuildJobsForAction(
3204 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
3205 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
3206 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
3207 Action::OffloadKind TargetDeviceOffloadKind) const {
3208 std::pair<const Action *, std::string> ActionTC = {
3209 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003210 auto CachedResult = CachedResults.find(ActionTC);
3211 if (CachedResult != CachedResults.end()) {
3212 return CachedResult->second;
3213 }
Samuel Antaod06239d2016-07-15 23:13:27 +00003214 InputInfo Result = BuildJobsForActionNoCache(
3215 C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003216 CachedResults, TargetDeviceOffloadKind);
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003217 CachedResults[ActionTC] = Result;
3218 return Result;
3219}
3220
3221InputInfo Driver::BuildJobsForActionNoCache(
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003222 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003223 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
Samuel Antaod06239d2016-07-15 23:13:27 +00003224 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003225 Action::OffloadKind TargetDeviceOffloadKind) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003226 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
Daniel Dunbarc4acf9d2009-03-18 23:18:19 +00003227
Samuel Antaod06239d2016-07-15 23:13:27 +00003228 InputInfoList OffloadDependencesInputInfo;
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003229 bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None;
Samuel Antaod06239d2016-07-15 23:13:27 +00003230 if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
3231 // The offload action is expected to be used in four different situations.
3232 //
3233 // a) Set a toolchain/architecture/kind for a host action:
3234 // Host Action 1 -> OffloadAction -> Host Action 2
3235 //
3236 // b) Set a toolchain/architecture/kind for a device action;
3237 // Device Action 1 -> OffloadAction -> Device Action 2
3238 //
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003239 // c) Specify a device dependence to a host action;
Samuel Antaod06239d2016-07-15 23:13:27 +00003240 // Device Action 1 _
3241 // \
3242 // Host Action 1 ---> OffloadAction -> Host Action 2
3243 //
3244 // d) Specify a host dependence to a device action.
3245 // Host Action 1 _
3246 // \
3247 // Device Action 1 ---> OffloadAction -> Device Action 2
3248 //
3249 // For a) and b), we just return the job generated for the dependence. For
3250 // c) and d) we override the current action with the host/device dependence
3251 // if the current toolchain is host/device and set the offload dependences
3252 // info with the jobs obtained from the device/host dependence(s).
3253
3254 // If there is a single device option, just generate the job for it.
3255 if (OA->hasSingleDeviceDependence()) {
3256 InputInfo DevA;
3257 OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
3258 const char *DepBoundArch) {
3259 DevA =
3260 BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
3261 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003262 CachedResults, DepA->getOffloadingDeviceKind());
Samuel Antaod06239d2016-07-15 23:13:27 +00003263 });
3264 return DevA;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003265 }
Samuel Antaod06239d2016-07-15 23:13:27 +00003266
3267 // If 'Action 2' is host, we generate jobs for the device dependences and
3268 // override the current action with the host dependence. Otherwise, we
3269 // generate the host dependences and override the action with the device
3270 // dependence. The dependences can't therefore be a top-level action.
3271 OA->doOnEachDependence(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003272 /*IsHostDependence=*/BuildingForOffloadDevice,
Samuel Antaod06239d2016-07-15 23:13:27 +00003273 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3274 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
3275 C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false,
3276 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003277 DepA->getOffloadingDeviceKind()));
Samuel Antaod06239d2016-07-15 23:13:27 +00003278 });
3279
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003280 A = BuildingForOffloadDevice
Samuel Antaod06239d2016-07-15 23:13:27 +00003281 ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
3282 : OA->getHostDependence();
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003283 }
3284
Daniel Dunbare75d8342009-03-16 06:56:51 +00003285 if (const InputAction *IA = dyn_cast<InputAction>(A)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003286 // FIXME: It would be nice to not claim this here; maybe the old scheme of
3287 // just using Args was better?
Daniel Dunbar5cdf3e02009-03-19 07:29:38 +00003288 const Arg &Input = IA->getInputArg();
3289 Input.claim();
Daniel Dunbar35cbfeb2010-06-09 22:31:08 +00003290 if (Input.getOption().matches(options::OPT_INPUT)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00003291 const char *Name = Input.getValue();
Justin Lebard98cea82016-01-11 23:15:21 +00003292 return InputInfo(A, Name, /* BaseInput = */ Name);
Douglas Katzman678d0cb2015-06-16 18:01:24 +00003293 }
Justin Lebard98cea82016-01-11 23:15:21 +00003294 return InputInfo(A, &Input, /* BaseInput = */ "");
Daniel Dunbare75d8342009-03-16 06:56:51 +00003295 }
3296
3297 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
Chad Rosiera78a6eb2012-04-27 16:50:38 +00003298 const ToolChain *TC;
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003299 StringRef ArchName = BAA->getArchName();
Daniel Dunbar1ef3f2a2009-09-08 23:37:19 +00003300
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003301 if (!ArchName.empty())
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +00003302 TC = &getToolChain(C.getArgs(),
3303 computeTargetTriple(*this, DefaultTargetTriple,
3304 C.getArgs(), ArchName));
Chad Rosiera78a6eb2012-04-27 16:50:38 +00003305 else
3306 TC = &C.getDefaultToolChain();
Daniel Dunbar1ef3f2a2009-09-08 23:37:19 +00003307
Nico Weber5a459f82016-02-23 19:30:43 +00003308 return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
Samuel Antaod06239d2016-07-15 23:13:27 +00003309 MultipleArchs, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003310 TargetDeviceOffloadKind);
Daniel Dunbare75d8342009-03-16 06:56:51 +00003311 }
3312
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003313
Daniel Dunbare75d8342009-03-16 06:56:51 +00003314 const ActionList *Inputs = &A->getInputs();
Daniel Dunbarc4343942010-02-03 03:07:56 +00003315
3316 const JobAction *JA = cast<JobAction>(A);
Samuel Antaod06239d2016-07-15 23:13:27 +00003317 ActionList CollapsedOffloadActions;
3318
Mehdi Amini6683e222017-01-24 18:12:25 +00003319 ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(),
3320 embedBitcodeInObject() && !isUsingLTO());
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003321 const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions);
3322
Rafael Espindola79764462013-03-24 15:06:53 +00003323 if (!T)
Justin Lebar9eaa4892016-01-11 23:09:32 +00003324 return InputInfo();
Daniel Dunbare75d8342009-03-16 06:56:51 +00003325
Samuel Antaod06239d2016-07-15 23:13:27 +00003326 // If we've collapsed action list that contained OffloadAction we
3327 // need to build jobs for host/device-side inputs it may have held.
3328 for (const auto *OA : CollapsedOffloadActions)
3329 cast<OffloadAction>(OA)->doOnEachDependence(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003330 /*IsHostDependence=*/BuildingForOffloadDevice,
Samuel Antaod06239d2016-07-15 23:13:27 +00003331 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3332 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
Artem Belevichbee2f412016-08-22 18:50:34 +00003333 C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false,
Samuel Antaod06239d2016-07-15 23:13:27 +00003334 /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003335 DepA->getOffloadingDeviceKind()));
Samuel Antaod06239d2016-07-15 23:13:27 +00003336 });
Artem Belevichf8144ab2015-08-27 18:10:41 +00003337
Daniel Dunbare75d8342009-03-16 06:56:51 +00003338 // Only use pipes when there is exactly one input.
Daniel Dunbar1a093d22009-03-18 06:00:36 +00003339 InputInfoList InputInfos;
Saleem Abdulrasoolda3f4e52014-12-29 21:02:47 +00003340 for (const Action *Input : *Inputs) {
Eric Christopher14668dd2013-02-18 00:38:25 +00003341 // Treat dsymutil and verify sub-jobs as being at the top-level too, they
3342 // shouldn't get temporary output names.
Daniel Dunbar6beaf512010-06-04 18:28:41 +00003343 // FIXME: Clean this up.
Justin Lebar9eaa4892016-01-11 23:09:32 +00003344 bool SubJobAtTopLevel =
3345 AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
Samuel Antaod06239d2016-07-15 23:13:27 +00003346 InputInfos.push_back(BuildJobsForAction(
3347 C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003348 CachedResults, A->getOffloadingDeviceKind()));
Daniel Dunbare75d8342009-03-16 06:56:51 +00003349 }
3350
Daniel Dunbare75d8342009-03-16 06:56:51 +00003351 // Always use the first input as the base input.
3352 const char *BaseInput = InputInfos[0].getBaseInput();
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003353
Daniel Dunbar6beaf512010-06-04 18:28:41 +00003354 // ... except dsymutil actions, which use their actual input as the base
3355 // input.
3356 if (JA->getType() == types::TY_dSYM)
3357 BaseInput = InputInfos[0].getFilename();
3358
Samuel Antaod06239d2016-07-15 23:13:27 +00003359 // Append outputs of offload device jobs to the input list
3360 if (!OffloadDependencesInputInfo.empty())
3361 InputInfos.append(OffloadDependencesInputInfo.begin(),
3362 OffloadDependencesInputInfo.end());
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003363
Vedant Kumar18286cf2016-07-27 23:02:20 +00003364 // Set the effective triple of the toolchain for the duration of this job.
3365 llvm::Triple EffectiveTriple;
3366 const ToolChain &ToolTC = T->getToolChain();
Samuel Antao31fef982016-10-27 17:39:44 +00003367 const ArgList &Args =
3368 C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind());
Vedant Kumar18286cf2016-07-27 23:02:20 +00003369 if (InputInfos.size() != 1) {
3370 EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args));
3371 } else {
3372 // Pass along the input type if it can be unambiguously determined.
3373 EffectiveTriple = llvm::Triple(
3374 ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType()));
3375 }
3376 RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple);
3377
Daniel Dunbard00272f2010-08-02 02:38:15 +00003378 // Determine the place to write output to, if any.
Justin Lebar9eaa4892016-01-11 23:09:32 +00003379 InputInfo Result;
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003380 InputInfoList UnbundlingResults;
3381 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) {
3382 // If we have an unbundling job, we need to create results for all the
3383 // outputs. We also update the results cache so that other actions using
3384 // this unbundling action can get the right results.
3385 for (auto &UI : UA->getDependentActionsInfo()) {
3386 assert(UI.DependentOffloadKind != Action::OFK_None &&
3387 "Unbundling with no offloading??");
3388
3389 // Unbundling actions are never at the top level. When we generate the
3390 // offloading prefix, we also do that for the host file because the
3391 // unbundling action does not change the type of the output which can
3392 // cause a overwrite.
3393 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
3394 UI.DependentOffloadKind,
3395 UI.DependentToolChain->getTriple().normalize(),
3396 /*CreatePrefixForHost=*/true);
3397 auto CurI = InputInfo(
3398 UA, GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch,
3399 /*AtTopLevel=*/false, MultipleArchs,
3400 OffloadingPrefix),
3401 BaseInput);
3402 // Save the unbundling result.
3403 UnbundlingResults.push_back(CurI);
3404
3405 // Get the unique string identifier for this dependence and cache the
3406 // result.
3407 CachedResults[{A, GetTriplePlusArchString(
3408 UI.DependentToolChain, UI.DependentBoundArch,
3409 UI.DependentOffloadKind)}] = CurI;
3410 }
3411
3412 // Now that we have all the results generated, select the one that should be
3413 // returned for the current depending action.
3414 std::pair<const Action *, std::string> ActionTC = {
3415 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
3416 assert(CachedResults.find(ActionTC) != CachedResults.end() &&
3417 "Result does not exist??");
3418 Result = CachedResults[ActionTC];
3419 } else if (JA->getType() == types::TY_Nothing)
Justin Lebard98cea82016-01-11 23:15:21 +00003420 Result = InputInfo(A, BaseInput);
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003421 else {
3422 // We only have to generate a prefix for the host if this is not a top-level
3423 // action.
3424 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
3425 A->getOffloadingDeviceKind(), TC->getTriple().normalize(),
3426 /*CreatePrefixForHost=*/!!A->getOffloadingHostActiveKinds() &&
3427 !AtTopLevel);
Justin Lebard98cea82016-01-11 23:15:21 +00003428 Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
Samuel Antaod06239d2016-07-15 23:13:27 +00003429 AtTopLevel, MultipleArchs,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003430 OffloadingPrefix),
Justin Lebard98cea82016-01-11 23:15:21 +00003431 BaseInput);
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003432 }
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003433
Chad Rosierbe10f982011-08-02 17:58:04 +00003434 if (CCCPrintBindings && !CCGenDiagnostics) {
Rafael Espindola79764462013-03-24 15:06:53 +00003435 llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
3436 << " - \"" << T->getName() << "\", inputs: [";
Daniel Dunbarb39cc522009-03-17 22:47:06 +00003437 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
3438 llvm::errs() << InputInfos[i].getAsString();
3439 if (i + 1 != e)
3440 llvm::errs() << ", ";
3441 }
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003442 if (UnbundlingResults.empty())
3443 llvm::errs() << "], output: " << Result.getAsString() << "\n";
3444 else {
3445 llvm::errs() << "], outputs: [";
3446 for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) {
3447 llvm::errs() << UnbundlingResults[i].getAsString();
3448 if (i + 1 != e)
3449 llvm::errs() << ", ";
3450 }
3451 llvm::errs() << "] \n";
3452 }
Daniel Dunbarb39cc522009-03-17 22:47:06 +00003453 } else {
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003454 if (UnbundlingResults.empty())
3455 T->ConstructJob(
3456 C, *JA, Result, InputInfos,
3457 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
3458 LinkingOutput);
3459 else
Samuel Antao7108bf32016-11-03 15:41:50 +00003460 T->ConstructJobMultipleOutputs(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003461 C, *JA, UnbundlingResults, InputInfos,
3462 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
3463 LinkingOutput);
Daniel Dunbarb39cc522009-03-17 22:47:06 +00003464 }
Justin Lebar9eaa4892016-01-11 23:09:32 +00003465 return Result;
Daniel Dunbare75d8342009-03-16 06:56:51 +00003466}
3467
Hans Wennborga7707222015-01-09 17:38:53 +00003468const char *Driver::getDefaultImageName() const {
3469 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
3470 return Target.isOSWindows() ? "a.exe" : "a.out";
3471}
3472
Hans Wennborg2c21f742013-10-17 16:16:23 +00003473/// \brief Create output filename based on ArgValue, which could either be a
3474/// full filename, filename without extension, or a directory. If ArgValue
3475/// does not provide a filename, then use BaseName, and use the extension
3476/// suitable for FileType.
Hans Wennborg207fcf02013-08-12 21:56:42 +00003477static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003478 StringRef BaseName,
3479 types::ID FileType) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00003480 SmallString<128> Filename = ArgValue;
Justin Bogner5aaf2e72014-06-26 20:59:36 +00003481
Hans Wennborgf1a74252013-09-10 20:18:04 +00003482 if (ArgValue.empty()) {
3483 // If the argument is empty, output to BaseName in the current dir.
3484 Filename = BaseName;
3485 } else if (llvm::sys::path::is_separator(Filename.back())) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00003486 // If the argument is a directory, output to BaseName in that dir.
3487 llvm::sys::path::append(Filename, BaseName);
3488 }
3489
3490 if (!llvm::sys::path::has_extension(ArgValue)) {
3491 // If the argument didn't provide an extension, then set it.
3492 const char *Extension = types::getTypeTempSuffix(FileType, true);
Hans Wennborgf1a74252013-09-10 20:18:04 +00003493
3494 if (FileType == types::TY_Image &&
3495 Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
3496 // The output file is a dll.
3497 Extension = "dll";
3498 }
3499
Hans Wennborg207fcf02013-08-12 21:56:42 +00003500 llvm::sys::path::replace_extension(Filename, Extension);
3501 }
3502
3503 return Args.MakeArgString(Filename.c_str());
3504}
3505
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003506const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003507 const char *BaseInput,
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003508 StringRef BoundArch, bool AtTopLevel,
Samuel Antaod06239d2016-07-15 23:13:27 +00003509 bool MultipleArchs,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003510 StringRef OffloadingPrefix) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00003511 llvm::PrettyStackTraceString CrashInfo("Computing output path");
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003512 // Output to a user requested destination?
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003513 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003514 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
Chad Rosier633dcdc2013-01-24 19:14:47 +00003515 return C.addResultFile(FinalOutput->getValue(), &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003516 }
3517
Hans Wennborge0053472013-12-20 18:40:46 +00003518 // For /P, preprocess to file named after BaseInput.
3519 if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
3520 assert(AtTopLevel && isa<PreprocessJobAction>(JA));
3521 StringRef BaseName = llvm::sys::path::filename(BaseInput);
Hans Wennborg04c764f2014-06-17 00:19:12 +00003522 StringRef NameArg;
Greg Bedwell065f70a2015-06-09 10:24:06 +00003523 if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
Hans Wennborg04c764f2014-06-17 00:19:12 +00003524 NameArg = A->getValue();
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003525 return C.addResultFile(
3526 MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
3527 &JA);
Hans Wennborge0053472013-12-20 18:40:46 +00003528 }
3529
Nick Lewycky6e1ce292010-09-24 00:46:53 +00003530 // Default to writing to stdout?
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00003531 if (AtTopLevel && !CCGenDiagnostics &&
3532 (isa<PreprocessJobAction>(JA) || JA.getType() == types::TY_ModuleFile))
Nick Lewycky6e1ce292010-09-24 00:46:53 +00003533 return "-";
3534
Hans Wennborg2c21f742013-10-17 16:16:23 +00003535 // Is this the assembly listing for /FA?
3536 if (JA.getType() == types::TY_PP_Asm &&
3537 (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
3538 C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
3539 // Use /Fa and the input filename to determine the asm file name.
3540 StringRef BaseName = llvm::sys::path::filename(BaseInput);
3541 StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003542 return C.addResultFile(
3543 MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
3544 &JA);
Hans Wennborg2c21f742013-10-17 16:16:23 +00003545 }
3546
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003547 // Output to a temporary file?
Reid Kleckner68eb60b2015-02-02 22:41:48 +00003548 if ((!AtTopLevel && !isSaveTempsEnabled() &&
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003549 !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
Chad Rosierbe10f982011-08-02 17:58:04 +00003550 CCGenDiagnostics) {
Chad Rosier97c37372011-08-26 22:27:02 +00003551 StringRef Name = llvm::sys::path::filename(BaseInput);
3552 std::pair<StringRef, StringRef> Split = Name.split('.');
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003553 std::string TmpName = GetTemporaryPath(
3554 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00003555 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003556 }
3557
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003558 SmallString<128> BasePath(BaseInput);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003559 StringRef BaseName;
Daniel Dunbar67fea712011-03-25 18:16:51 +00003560
3561 // Dsymutil actions should use the full path.
Eric Christopher551ef452011-08-23 17:56:55 +00003562 if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
Daniel Dunbar67fea712011-03-25 18:16:51 +00003563 BaseName = BasePath;
3564 else
3565 BaseName = llvm::sys::path::filename(BasePath);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003566
3567 // Determine what the derived output name should be.
3568 const char *NamedOutput;
Hans Wennborg2b89a262013-08-06 22:11:28 +00003569
Hans Wennborg625fba82016-10-04 21:01:04 +00003570 if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) &&
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00003571 C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
3572 // The /Fo or /o flag decides the object filename.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003573 StringRef Val =
3574 C.getArgs()
3575 .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
3576 ->getValue();
3577 NamedOutput =
3578 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
Hans Wennborg207fcf02013-08-12 21:56:42 +00003579 } else if (JA.getType() == types::TY_Image &&
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003580 C.getArgs().hasArg(options::OPT__SLASH_Fe,
3581 options::OPT__SLASH_o)) {
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00003582 // The /Fe or /o flag names the linked file.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003583 StringRef Val =
3584 C.getArgs()
3585 .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
3586 ->getValue();
3587 NamedOutput =
3588 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
Hans Wennborgf1a74252013-09-10 20:18:04 +00003589 } else if (JA.getType() == types::TY_Image) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00003590 if (IsCLMode()) {
3591 // clang-cl uses BaseName for the executable name.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003592 NamedOutput =
3593 MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
Samuel Antao59efaed2016-10-27 17:31:22 +00003594 } else {
Hans Wennborga7707222015-01-09 17:38:53 +00003595 SmallString<128> Output(getDefaultImageName());
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003596 Output += OffloadingPrefix;
Samuel Antao59efaed2016-10-27 17:31:22 +00003597 if (MultipleArchs && !BoundArch.empty()) {
3598 Output += "-";
3599 Output.append(BoundArch);
3600 }
Chad Rosier35767232013-04-30 22:01:21 +00003601 NamedOutput = C.getArgs().MakeArgString(Output.c_str());
Nico Weber2ca4be92016-03-01 23:16:44 +00003602 }
3603 } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00003604 NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName));
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003605 } else {
Hans Wennborg0a096a02013-09-05 17:05:56 +00003606 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003607 assert(Suffix && "All types used for output should have a suffix.");
3608
3609 std::string::size_type End = std::string::npos;
3610 if (!types::appendSuffixForType(JA.getType()))
3611 End = BaseName.rfind('.');
Chad Rosier35767232013-04-30 22:01:21 +00003612 SmallString<128> Suffixed(BaseName.substr(0, End));
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003613 Suffixed += OffloadingPrefix;
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003614 if (MultipleArchs && !BoundArch.empty()) {
Chad Rosier35767232013-04-30 22:01:21 +00003615 Suffixed += "-";
3616 Suffixed.append(BoundArch);
3617 }
Bob Wilson23a55f12014-12-21 07:00:00 +00003618 // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
3619 // the unoptimized bitcode so that it does not get overwritten by the ".bc"
3620 // optimized bitcode output.
3621 if (!AtTopLevel && C.getArgs().hasArg(options::OPT_emit_llvm) &&
3622 JA.getType() == types::TY_LLVM_BC)
3623 Suffixed += ".tmp";
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003624 Suffixed += '.';
3625 Suffixed += Suffix;
3626 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
3627 }
3628
Reid Kleckner68eb60b2015-02-02 22:41:48 +00003629 // Prepend object file path if -save-temps=obj
3630 if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
3631 JA.getType() != types::TY_PCH) {
3632 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
3633 SmallString<128> TempPath(FinalOutput->getValue());
3634 llvm::sys::path::remove_filename(TempPath);
3635 StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
3636 llvm::sys::path::append(TempPath, OutputFileName);
3637 NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
3638 }
3639
Chad Rosier62135492012-07-09 17:31:28 +00003640 // If we're saving temps and the temp file conflicts with the input file,
Chad Rosier5b58af02012-04-20 20:05:08 +00003641 // then avoid overwriting input file.
Reid Kleckner68eb60b2015-02-02 22:41:48 +00003642 if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
Chad Rosier5b58af02012-04-20 20:05:08 +00003643 bool SameFile = false;
3644 SmallString<256> Result;
3645 llvm::sys::fs::current_path(Result);
3646 llvm::sys::path::append(Result, BaseName);
3647 llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
3648 // Must share the same path to conflict.
3649 if (SameFile) {
3650 StringRef Name = llvm::sys::path::filename(BaseInput);
3651 std::pair<StringRef, StringRef> Split = Name.split('.');
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003652 std::string TmpName = GetTemporaryPath(
3653 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00003654 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
Chad Rosier5b58af02012-04-20 20:05:08 +00003655 }
Chad Rosierf8412cd2011-07-15 21:54:29 +00003656 }
3657
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003658 // As an annoying special case, PCH generation doesn't strip the pathname.
Nico Weber8ab92192016-03-02 23:29:29 +00003659 if (JA.getType() == types::TY_PCH && !IsCLMode()) {
Michael J. Spencere1696752010-12-18 00:19:12 +00003660 llvm::sys::path::remove_filename(BasePath);
3661 if (BasePath.empty())
Daniel Dunbare6c83192009-03-18 09:58:30 +00003662 BasePath = NamedOutput;
3663 else
Michael J. Spencere1696752010-12-18 00:19:12 +00003664 llvm::sys::path::append(BasePath, NamedOutput);
Chad Rosier633dcdc2013-01-24 19:14:47 +00003665 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003666 } else {
Chad Rosier633dcdc2013-01-24 19:14:47 +00003667 return C.addResultFile(NamedOutput, &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003668 }
3669}
3670
Mehdi Amini12011172016-10-06 05:11:48 +00003671std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const {
Chandler Carruth84559242010-03-22 01:52:07 +00003672 // Respect a limited subset of the '-Bprefix' functionality in GCC by
Logan Chiencd679fd2012-10-04 08:08:56 +00003673 // attempting to use this prefix when looking for file paths.
Douglas Katzman26eabf62015-06-24 15:10:30 +00003674 for (const std::string &Dir : PrefixDirs) {
Joerg Sonnenberger6165ab12011-03-21 13:51:29 +00003675 if (Dir.empty())
3676 continue;
Douglas Katzman26eabf62015-06-24 15:10:30 +00003677 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
Rafael Espindola609a6642013-06-24 18:33:43 +00003678 llvm::sys::path::append(P, Name);
3679 if (llvm::sys::fs::exists(Twine(P)))
Chandler Carruth84559242010-03-22 01:52:07 +00003680 return P.str();
3681 }
3682
Rafael Espindola609a6642013-06-24 18:33:43 +00003683 SmallString<128> P(ResourceDir);
3684 llvm::sys::path::append(P, Name);
3685 if (llvm::sys::fs::exists(Twine(P)))
Peter Collingbournefa9771f2011-09-06 02:08:31 +00003686 return P.str();
3687
Douglas Katzman26eabf62015-06-24 15:10:30 +00003688 for (const std::string &Dir : TC.getFilePaths()) {
Joerg Sonnenberger6165ab12011-03-21 13:51:29 +00003689 if (Dir.empty())
3690 continue;
Douglas Katzman26eabf62015-06-24 15:10:30 +00003691 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
Rafael Espindola609a6642013-06-24 18:33:43 +00003692 llvm::sys::path::append(P, Name);
3693 if (llvm::sys::fs::exists(Twine(P)))
Daniel Dunbar1ce81532009-09-09 22:33:00 +00003694 return P.str();
Daniel Dunbar68b01a02009-03-18 20:26:19 +00003695 }
3696
Daniel Dunbar1ce81532009-09-09 22:33:00 +00003697 return Name;
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00003698}
3699
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003700void Driver::generatePrefixedToolNames(
Mehdi Amini12011172016-10-06 05:11:48 +00003701 StringRef Tool, const ToolChain &TC,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003702 SmallVectorImpl<std::string> &Names) const {
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00003703 // FIXME: Needs a better variable than DefaultTargetTriple
Mehdi Amini12011172016-10-06 05:11:48 +00003704 Names.emplace_back((DefaultTargetTriple + "-" + Tool).str());
Benjamin Kramer3204b152015-05-29 19:42:19 +00003705 Names.emplace_back(Tool);
Vasileios Kalintirisc744e122015-11-12 15:26:54 +00003706
3707 // Allow the discovery of tools prefixed with LLVM's default target triple.
3708 std::string LLVMDefaultTargetTriple = llvm::sys::getDefaultTargetTriple();
3709 if (LLVMDefaultTargetTriple != DefaultTargetTriple)
Mehdi Amini12011172016-10-06 05:11:48 +00003710 Names.emplace_back((LLVMDefaultTargetTriple + "-" + Tool).str());
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00003711}
3712
Benjamin Kramer7111b912014-11-04 20:26:01 +00003713static bool ScanDirForExecutable(SmallString<128> &Dir,
3714 ArrayRef<std::string> Names) {
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00003715 for (const auto &Name : Names) {
3716 llvm::sys::path::append(Dir, Name);
3717 if (llvm::sys::fs::can_execute(Twine(Dir)))
3718 return true;
3719 llvm::sys::path::remove_filename(Dir);
3720 }
3721 return false;
3722}
3723
Mehdi Amini12011172016-10-06 05:11:48 +00003724std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const {
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00003725 SmallVector<std::string, 2> TargetSpecificExecutables;
3726 generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
3727
Chandler Carruth84559242010-03-22 01:52:07 +00003728 // Respect a limited subset of the '-Bprefix' functionality in GCC by
Logan Chiencd679fd2012-10-04 08:08:56 +00003729 // attempting to use this prefix when looking for program paths.
Saleem Abdulrasool23d99b12014-09-16 03:48:32 +00003730 for (const auto &PrefixDir : PrefixDirs) {
3731 if (llvm::sys::fs::is_directory(PrefixDir)) {
3732 SmallString<128> P(PrefixDir);
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00003733 if (ScanDirForExecutable(P, TargetSpecificExecutables))
Rafael Espindola8be5c052013-06-19 13:24:29 +00003734 return P.str();
Simon Atanasyana47ba292012-10-31 14:39:28 +00003735 } else {
Mehdi Amini12011172016-10-06 05:11:48 +00003736 SmallString<128> P((PrefixDir + Name).str());
Rafael Espindola609a6642013-06-24 18:33:43 +00003737 if (llvm::sys::fs::can_execute(Twine(P)))
Rafael Espindola8be5c052013-06-19 13:24:29 +00003738 return P.str();
Simon Atanasyan86bdab72012-10-31 12:01:53 +00003739 }
Chandler Carruth84559242010-03-22 01:52:07 +00003740 }
3741
Daniel Dunbar68b01a02009-03-18 20:26:19 +00003742 const ToolChain::path_list &List = TC.getProgramPaths();
Saleem Abdulrasool23d99b12014-09-16 03:48:32 +00003743 for (const auto &Path : List) {
3744 SmallString<128> P(Path);
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00003745 if (ScanDirForExecutable(P, TargetSpecificExecutables))
Rafael Espindola8be5c052013-06-19 13:24:29 +00003746 return P.str();
Daniel Dunbar68b01a02009-03-18 20:26:19 +00003747 }
3748
Daniel Dunbar76ce7412009-03-23 16:15:50 +00003749 // If all else failed, search the path.
Michael J. Spencerb011d482014-11-07 21:30:32 +00003750 for (const auto &TargetSpecificExecutable : TargetSpecificExecutables)
3751 if (llvm::ErrorOr<std::string> P =
3752 llvm::sys::findProgramByName(TargetSpecificExecutable))
Michael J. Spencer04162ea2014-11-04 01:30:55 +00003753 return *P;
Daniel Dunbar6f668772009-03-18 21:34:08 +00003754
Daniel Dunbar1ce81532009-09-09 22:33:00 +00003755 return Name;
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00003756}
3757
Mehdi Amini12011172016-10-06 05:11:48 +00003758std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const {
Rafael Espindola37d229d2013-06-25 04:26:55 +00003759 SmallString<128> Path;
Rafael Espindolac0809172014-06-12 14:02:15 +00003760 std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
Rafael Espindola37d229d2013-06-25 04:26:55 +00003761 if (EC) {
3762 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
Daniel Dunbare627c1c2009-03-18 19:34:39 +00003763 return "";
3764 }
3765
Rafael Espindola37d229d2013-06-25 04:26:55 +00003766 return Path.str();
Daniel Dunbare627c1c2009-03-18 19:34:39 +00003767}
3768
Nico Weber2ca4be92016-03-01 23:16:44 +00003769std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
3770 SmallString<128> Output;
3771 if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
3772 // FIXME: If anybody needs it, implement this obscure rule:
3773 // "If you specify a directory without a file name, the default file name
3774 // is VCx0.pch., where x is the major version of Visual C++ in use."
3775 Output = FpArg->getValue();
3776
3777 // "If you do not specify an extension as part of the path name, an
3778 // extension of .pch is assumed. "
3779 if (!llvm::sys::path::has_extension(Output))
3780 Output += ".pch";
3781 } else {
3782 Output = BaseName;
3783 llvm::sys::path::replace_extension(Output, ".pch");
3784 }
3785 return Output.str();
3786}
3787
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003788const ToolChain &Driver::getToolChain(const ArgList &Args,
Artem Belevich959e0542015-07-10 19:47:55 +00003789 const llvm::Triple &Target) const {
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003790
David Blaikie6ad71012017-01-13 18:53:43 +00003791 auto &TC = ToolChains[Target.str()];
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003792 if (!TC) {
3793 switch (Target.getOS()) {
Reid Kleckner330fb172016-05-11 16:19:05 +00003794 case llvm::Triple::Haiku:
David Blaikie6ad71012017-01-13 18:53:43 +00003795 TC = llvm::make_unique<toolchains::Haiku>(*this, Target, Args);
Reid Kleckner330fb172016-05-11 16:19:05 +00003796 break;
Ed Schouten4dabea22017-06-25 08:29:09 +00003797 case llvm::Triple::Ananas:
3798 TC = llvm::make_unique<toolchains::Ananas>(*this, Target, Args);
3799 break;
Ed Schouten3c3e58c2015-03-26 11:13:44 +00003800 case llvm::Triple::CloudABI:
David Blaikie6ad71012017-01-13 18:53:43 +00003801 TC = llvm::make_unique<toolchains::CloudABI>(*this, Target, Args);
Ed Schouten3c3e58c2015-03-26 11:13:44 +00003802 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003803 case llvm::Triple::Darwin:
3804 case llvm::Triple::MacOSX:
3805 case llvm::Triple::IOS:
Tim Northover6f3ff222015-10-30 16:30:27 +00003806 case llvm::Triple::TvOS:
3807 case llvm::Triple::WatchOS:
David Blaikie6ad71012017-01-13 18:53:43 +00003808 TC = llvm::make_unique<toolchains::DarwinClang>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003809 break;
3810 case llvm::Triple::DragonFly:
David Blaikie6ad71012017-01-13 18:53:43 +00003811 TC = llvm::make_unique<toolchains::DragonFly>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003812 break;
3813 case llvm::Triple::OpenBSD:
David Blaikie6ad71012017-01-13 18:53:43 +00003814 TC = llvm::make_unique<toolchains::OpenBSD>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003815 break;
3816 case llvm::Triple::NetBSD:
David Blaikie6ad71012017-01-13 18:53:43 +00003817 TC = llvm::make_unique<toolchains::NetBSD>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003818 break;
3819 case llvm::Triple::FreeBSD:
David Blaikie6ad71012017-01-13 18:53:43 +00003820 TC = llvm::make_unique<toolchains::FreeBSD>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003821 break;
3822 case llvm::Triple::Minix:
David Blaikie6ad71012017-01-13 18:53:43 +00003823 TC = llvm::make_unique<toolchains::Minix>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003824 break;
3825 case llvm::Triple::Linux:
Andrey Turetskiy4798eb62016-06-16 10:36:09 +00003826 case llvm::Triple::ELFIAMCU:
Chandler Carruthcf705b22012-01-25 21:03:58 +00003827 if (Target.getArch() == llvm::Triple::hexagon)
David Blaikie6ad71012017-01-13 18:53:43 +00003828 TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
3829 Args);
Vasileios Kalintirisc744e122015-11-12 15:26:54 +00003830 else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
3831 !Target.hasEnvironment())
David Blaikie6ad71012017-01-13 18:53:43 +00003832 TC = llvm::make_unique<toolchains::MipsLLVMToolChain>(*this, Target,
3833 Args);
Chandler Carruthcf705b22012-01-25 21:03:58 +00003834 else
David Blaikie6ad71012017-01-13 18:53:43 +00003835 TC = llvm::make_unique<toolchains::Linux>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003836 break;
Derek Schuff6ab52fa2015-03-30 20:31:33 +00003837 case llvm::Triple::NaCl:
David Blaikie6ad71012017-01-13 18:53:43 +00003838 TC = llvm::make_unique<toolchains::NaClToolChain>(*this, Target, Args);
Derek Schuff6ab52fa2015-03-30 20:31:33 +00003839 break;
Petr Hosek62e1d232016-10-06 06:08:09 +00003840 case llvm::Triple::Fuchsia:
David Blaikie6ad71012017-01-13 18:53:43 +00003841 TC = llvm::make_unique<toolchains::Fuchsia>(*this, Target, Args);
Petr Hosek62e1d232016-10-06 06:08:09 +00003842 break;
David Chisnallf571cde2012-02-15 13:39:01 +00003843 case llvm::Triple::Solaris:
David Blaikie6ad71012017-01-13 18:53:43 +00003844 TC = llvm::make_unique<toolchains::Solaris>(*this, Target, Args);
David Chisnallf571cde2012-02-15 13:39:01 +00003845 break;
Tom Stellard8fa33092015-07-18 01:49:05 +00003846 case llvm::Triple::AMDHSA:
David Blaikie6ad71012017-01-13 18:53:43 +00003847 TC = llvm::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args);
Tom Stellard8fa33092015-07-18 01:49:05 +00003848 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003849 case llvm::Triple::Win32:
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00003850 switch (Target.getEnvironment()) {
3851 default:
3852 if (Target.isOSBinFormatELF())
David Blaikie6ad71012017-01-13 18:53:43 +00003853 TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00003854 else if (Target.isOSBinFormatMachO())
David Blaikie6ad71012017-01-13 18:53:43 +00003855 TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00003856 else
David Blaikie6ad71012017-01-13 18:53:43 +00003857 TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00003858 break;
3859 case llvm::Triple::GNU:
David Blaikie6ad71012017-01-13 18:53:43 +00003860 TC = llvm::make_unique<toolchains::MinGW>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00003861 break;
Saleem Abdulrasool543a78b2014-10-24 03:13:37 +00003862 case llvm::Triple::Itanium:
David Blaikie6ad71012017-01-13 18:53:43 +00003863 TC = llvm::make_unique<toolchains::CrossWindowsToolChain>(*this, Target,
3864 Args);
Saleem Abdulrasool543a78b2014-10-24 03:13:37 +00003865 break;
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00003866 case llvm::Triple::MSVC:
3867 case llvm::Triple::UnknownEnvironment:
David Blaikie6ad71012017-01-13 18:53:43 +00003868 TC = llvm::make_unique<toolchains::MSVCToolChain>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00003869 break;
3870 }
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003871 break;
Filipe Cabecinhasc888e192015-10-14 12:25:43 +00003872 case llvm::Triple::PS4:
David Blaikie6ad71012017-01-13 18:53:43 +00003873 TC = llvm::make_unique<toolchains::PS4CPU>(*this, Target, Args);
Filipe Cabecinhasc888e192015-10-14 12:25:43 +00003874 break;
David L Kreitzerd397ea42016-10-14 20:44:33 +00003875 case llvm::Triple::Contiki:
David Blaikie6ad71012017-01-13 18:53:43 +00003876 TC = llvm::make_unique<toolchains::Contiki>(*this, Target, Args);
David L Kreitzerd397ea42016-10-14 20:44:33 +00003877 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003878 default:
Douglas Katzman9f5e70e2015-05-26 18:01:33 +00003879 // Of these targets, Hexagon is the only one that might have
3880 // an OS of Linux, in which case it got handled above already.
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003881 switch (Target.getArch()) {
3882 case llvm::Triple::tce:
David Blaikie6ad71012017-01-13 18:53:43 +00003883 TC = llvm::make_unique<toolchains::TCEToolChain>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003884 break;
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00003885 case llvm::Triple::tcele:
David Blaikie6ad71012017-01-13 18:53:43 +00003886 TC = llvm::make_unique<toolchains::TCELEToolChain>(*this, Target, Args);
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00003887 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003888 case llvm::Triple::hexagon:
David Blaikie6ad71012017-01-13 18:53:43 +00003889 TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
3890 Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003891 break;
Jacques Pienaard964cc22016-03-28 21:02:54 +00003892 case llvm::Triple::lanai:
David Blaikie6ad71012017-01-13 18:53:43 +00003893 TC = llvm::make_unique<toolchains::LanaiToolChain>(*this, Target, Args);
Jacques Pienaard964cc22016-03-28 21:02:54 +00003894 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003895 case llvm::Triple::xcore:
David Blaikie6ad71012017-01-13 18:53:43 +00003896 TC = llvm::make_unique<toolchains::XCoreToolChain>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003897 break;
Dan Gohmanc2853072015-09-03 22:51:53 +00003898 case llvm::Triple::wasm32:
3899 case llvm::Triple::wasm64:
David Blaikie6ad71012017-01-13 18:53:43 +00003900 TC = llvm::make_unique<toolchains::WebAssembly>(*this, Target, Args);
Dan Gohmanc2853072015-09-03 22:51:53 +00003901 break;
Dylan McKay924fa3a2017-01-05 05:20:27 +00003902 case llvm::Triple::avr:
David Blaikie6ad71012017-01-13 18:53:43 +00003903 TC = llvm::make_unique<toolchains::AVRToolChain>(*this, Target, Args);
Dylan McKay924fa3a2017-01-05 05:20:27 +00003904 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003905 default:
Douglas Katzmand6e597c2015-09-17 19:56:40 +00003906 if (Target.getVendor() == llvm::Triple::Myriad)
David Blaikie6ad71012017-01-13 18:53:43 +00003907 TC = llvm::make_unique<toolchains::MyriadToolChain>(*this, Target,
3908 Args);
Jonathan Roelofs901c7762017-05-25 15:42:13 +00003909 else if (toolchains::BareMetal::handlesTarget(Target))
3910 TC = llvm::make_unique<toolchains::BareMetal>(*this, Target, Args);
Douglas Katzmand6e597c2015-09-17 19:56:40 +00003911 else if (Target.isOSBinFormatELF())
David Blaikie6ad71012017-01-13 18:53:43 +00003912 TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003913 else if (Target.isOSBinFormatMachO())
David Blaikie6ad71012017-01-13 18:53:43 +00003914 TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003915 else
David Blaikie6ad71012017-01-13 18:53:43 +00003916 TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003917 }
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003918 }
3919 }
Justin Lebar66c4fd72016-11-18 00:41:22 +00003920
3921 // Intentionally omitted from the switch above: llvm::Triple::CUDA. CUDA
3922 // compiles always need two toolchains, the CUDA toolchain and the host
3923 // toolchain. So the only valid way to create a CUDA toolchain is via
3924 // CreateOffloadingDeviceToolChains.
3925
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003926 return *TC;
Daniel Dunbar4dff6a42009-03-10 23:41:59 +00003927}
Daniel Dunbar8fa879d2009-03-24 18:57:02 +00003928
Rafael Espindola2f69d402013-03-18 15:33:26 +00003929bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
Douglas Katzman00249092015-06-12 15:45:21 +00003930 // Say "no" if there is not exactly one input of a type clang understands.
Nico Weber5a459f82016-02-23 19:30:43 +00003931 if (JA.size() != 1 ||
3932 !types::isAcceptedByClang((*JA.input_begin())->getType()))
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00003933 return false;
3934
Douglas Katzman00249092015-06-12 15:45:21 +00003935 // And say "no" if this is not a kind of action clang understands.
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00003936 if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
Bob Wilson23a55f12014-12-21 07:00:00 +00003937 !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00003938 return false;
3939
3940 return true;
3941}
3942
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003943/// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
3944/// grouped values as integers. Numbers which are not provided are set to 0.
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003945///
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003946/// \return True if the entire string was parsed (9.2), or all groups were
3947/// parsed (10.3.5extrastuff).
Mehdi Amini12011172016-10-06 05:11:48 +00003948bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
3949 unsigned &Micro, bool &HadExtra) {
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003950 HadExtra = false;
3951
3952 Major = Minor = Micro = 0;
Mehdi Amini12011172016-10-06 05:11:48 +00003953 if (Str.empty())
Bob Wilson433cb312015-04-07 01:03:35 +00003954 return false;
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003955
Mehdi Amini12011172016-10-06 05:11:48 +00003956 if (Str.consumeInteger(10, Major))
3957 return false;
3958 if (Str.empty())
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003959 return true;
Mehdi Amini12011172016-10-06 05:11:48 +00003960 if (Str[0] != '.')
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003961 return false;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003962
Mehdi Amini12011172016-10-06 05:11:48 +00003963 Str = Str.drop_front(1);
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003964
Mehdi Amini12011172016-10-06 05:11:48 +00003965 if (Str.consumeInteger(10, Minor))
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003966 return false;
Mehdi Amini12011172016-10-06 05:11:48 +00003967 if (Str.empty())
3968 return true;
3969 if (Str[0] != '.')
3970 return false;
3971 Str = Str.drop_front(1);
3972
3973 if (Str.consumeInteger(10, Micro))
3974 return false;
3975 if (!Str.empty())
3976 HadExtra = true;
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003977 return true;
3978}
Hans Wennborg6ddc6902013-07-27 00:23:45 +00003979
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00003980/// Parse digits from a string \p Str and fulfill \p Digits with
3981/// the parsed numbers. This method assumes that the max number of
3982/// digits to look for is equal to Digits.size().
3983///
3984/// \return True if the entire string was parsed and there are
3985/// no extra characters remaining at the end.
Mehdi Amini12011172016-10-06 05:11:48 +00003986bool Driver::GetReleaseVersion(StringRef Str,
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00003987 MutableArrayRef<unsigned> Digits) {
Mehdi Amini12011172016-10-06 05:11:48 +00003988 if (Str.empty())
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00003989 return false;
3990
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00003991 unsigned CurDigit = 0;
3992 while (CurDigit < Digits.size()) {
Mehdi Amini12011172016-10-06 05:11:48 +00003993 unsigned Digit;
3994 if (Str.consumeInteger(10, Digit))
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00003995 return false;
Mehdi Amini12011172016-10-06 05:11:48 +00003996 Digits[CurDigit] = Digit;
3997 if (Str.empty())
3998 return true;
3999 if (Str[0] != '.')
4000 return false;
4001 Str = Str.drop_front(1);
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004002 CurDigit++;
4003 }
4004
4005 // More digits than requested, bail out...
4006 return false;
4007}
4008
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004009std::pair<unsigned, unsigned> Driver::getIncludeExcludeOptionFlagMasks() const {
4010 unsigned IncludedFlagsBitmask = 0;
Rafael Espindolacc707bc2013-09-25 15:54:41 +00004011 unsigned ExcludedFlagsBitmask = options::NoDriverOption;
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004012
4013 if (Mode == CLMode) {
Hans Wennborg19076102013-07-31 20:51:53 +00004014 // Include CL and Core options.
4015 IncludedFlagsBitmask |= options::CLOption;
4016 IncludedFlagsBitmask |= options::CoreOption;
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004017 } else {
4018 ExcludedFlagsBitmask |= options::CLOption;
4019 }
4020
4021 return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
4022}
Benjamin Kramerab88f622014-03-25 18:02:07 +00004023
Douglas Katzmanf08fadf2015-06-04 14:40:44 +00004024bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
Benjamin Kramerab88f622014-03-25 18:02:07 +00004025 return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);
4026}