blob: 78c3125cdb65da8bab3085d526f57a01058c3533 [file] [log] [blame]
Nick Lewyckye3365aa2010-09-23 23:48:20 +00001//===--- Driver.cpp - Clang GCC Compatible Driver -------------------------===//
Daniel Dunbar3ede8d02009-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 Dunbar3ede8d02009-03-02 19:59:07 +000010#include "clang/Driver/Driver.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000011#include "InputInfo.h"
12#include "ToolChains.h"
13#include "clang/Basic/Version.h"
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -080014#include "clang/Basic/VirtualFileSystem.h"
Stephen Hinesc568f1e2014-07-21 00:47:37 -070015#include "clang/Config/config.h"
Daniel Dunbar53ec5522009-03-12 07:58:46 +000016#include "clang/Driver/Action.h"
Daniel Dunbar1b3bb6e2009-03-04 20:49:20 +000017#include "clang/Driver/Compilation.h"
Daniel Dunbar4ad4b3e2009-03-12 08:55:43 +000018#include "clang/Driver/DriverDiagnostic.h"
Daniel Dunbarf353c8c2009-03-16 06:56:51 +000019#include "clang/Driver/Job.h"
Daniel Dunbar1b3bb6e2009-03-04 20:49:20 +000020#include "clang/Driver/Options.h"
Stephen Hines0e2c34f2015-03-23 12:09:02 -070021#include "clang/Driver/SanitizerArgs.h"
Daniel Dunbarf353c8c2009-03-16 06:56:51 +000022#include "clang/Driver/Tool.h"
23#include "clang/Driver/ToolChain.h"
Chris Lattner7f9fc3f2011-03-23 04:04:01 +000024#include "llvm/ADT/ArrayRef.h"
Hans Wennborg69813302013-07-27 00:23:45 +000025#include "llvm/ADT/STLExtras.h"
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -070026#include "llvm/ADT/SmallSet.h"
Stephen Hinesc568f1e2014-07-21 00:47:37 -070027#include "llvm/ADT/StringExtras.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000028#include "llvm/ADT/StringSet.h"
Hans Wennborg76b86c22013-07-18 20:29:38 +000029#include "llvm/ADT/StringSwitch.h"
Reid Klecknerb1e25a12013-06-14 17:17:23 +000030#include "llvm/Option/Arg.h"
31#include "llvm/Option/ArgList.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070032#include "llvm/Option/OptSpecifier.h"
Reid Klecknerb1e25a12013-06-14 17:17:23 +000033#include "llvm/Option/OptTable.h"
34#include "llvm/Option/Option.h"
Eric Christopherc706c8e2013-02-05 07:29:57 +000035#include "llvm/Support/Debug.h"
David Blaikie548f6c82011-09-23 05:57:42 +000036#include "llvm/Support/ErrorHandling.h"
Michael J. Spencer256053b2010-12-17 21:22:22 +000037#include "llvm/Support/FileSystem.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000038#include "llvm/Support/Path.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000039#include "llvm/Support/PrettyStackTrace.h"
Stephen Hinesc568f1e2014-07-21 00:47:37 -070040#include "llvm/Support/Process.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000041#include "llvm/Support/Program.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000042#include "llvm/Support/raw_ostream.h"
Dylan Noblesmithf2462be2012-02-02 00:40:14 +000043#include <map>
Stephen Hines651f13c2014-04-23 16:59:28 -070044#include <memory>
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -070045#include <utility>
Dylan Noblesmith69d3b4f2012-02-01 14:25:28 +000046
Daniel Dunbar1b3bb6e2009-03-04 20:49:20 +000047using namespace clang::driver;
Chris Lattner92b36992009-03-26 05:56:24 +000048using namespace clang;
Reid Klecknerb1e25a12013-06-14 17:17:23 +000049using namespace llvm::opt;
Daniel Dunbar1b3bb6e2009-03-04 20:49:20 +000050
Stephen Hines0e2c34f2015-03-23 12:09:02 -070051Driver::Driver(StringRef ClangExecutable, StringRef DefaultTargetTriple,
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -080052 DiagnosticsEngine &Diags,
53 IntrusiveRefCntPtr<vfs::FileSystem> VFS)
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -070054 : Opts(createDriverOptTable()), Diags(Diags), VFS(std::move(VFS)),
55 Mode(GCCMode), SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
56 LTOMode(LTOK_None), ClangExecutable(ClangExecutable),
Stephen Hines0e2c34f2015-03-23 12:09:02 -070057 SysRoot(DEFAULT_SYSROOT), UseStdLib(true),
58 DefaultTargetTriple(DefaultTargetTriple),
59 DriverTitle("clang LLVM compiler"), CCPrintOptionsFilename(nullptr),
60 CCPrintHeadersFilename(nullptr), CCLogDiagnosticsFilename(nullptr),
61 CCCPrintBindings(false), CCPrintHeaders(false), CCLogDiagnostics(false),
62 CCGenDiagnostics(false), CCCGenericGCCName(""), CheckInputsExist(true),
63 CCCUsePCH(true), SuppressMissingInputWarning(false) {
Daniel Dunbar225c4172010-01-20 02:35:16 +000064
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -080065 // Provide a sane fallback if no VFS is specified.
66 if (!this->VFS)
67 this->VFS = vfs::getRealFileSystem();
68
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -070069 Name = llvm::sys::path::filename(ClangExecutable);
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -080070 Dir = llvm::sys::path::parent_path(ClangExecutable);
71 InstalledDir = Dir; // Provide a sensible default installed dir.
Bob Wilson4a792962013-03-23 05:17:59 +000072
73 // Compute the path to the resource directory.
74 StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
75 SmallString<128> P(Dir);
Stephen Hines0e2c34f2015-03-23 12:09:02 -070076 if (ClangResourceDir != "") {
Bob Wilson4a792962013-03-23 05:17:59 +000077 llvm::sys::path::append(P, ClangResourceDir);
Stephen Hines0e2c34f2015-03-23 12:09:02 -070078 } else {
79 StringRef ClangLibdirSuffix(CLANG_LIBDIR_SUFFIX);
80 llvm::sys::path::append(P, "..", Twine("lib") + ClangLibdirSuffix, "clang",
81 CLANG_VERSION_STRING);
82 }
Bob Wilson4a792962013-03-23 05:17:59 +000083 ResourceDir = P.str();
Daniel Dunbar3ede8d02009-03-02 19:59:07 +000084}
85
86Driver::~Driver() {
Daniel Dunbar1b3bb6e2009-03-04 20:49:20 +000087 delete Opts;
Chandler Carruth18d7f3a2012-01-25 11:01:57 +000088
Stephen Hines651f13c2014-04-23 16:59:28 -070089 llvm::DeleteContainerSeconds(ToolChains);
Daniel Dunbar3ede8d02009-03-02 19:59:07 +000090}
91
Hans Wennborg76b86c22013-07-18 20:29:38 +000092void Driver::ParseDriverMode(ArrayRef<const char *> Args) {
93 const std::string OptName =
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -080094 getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
Hans Wennborg76b86c22013-07-18 20:29:38 +000095
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -080096 for (const char *ArgPtr : Args) {
Stephen Hines176edba2014-12-01 14:53:08 -080097 // Ingore nullptrs, they are response file's EOL markers
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -080098 if (ArgPtr == nullptr)
Stephen Hines176edba2014-12-01 14:53:08 -080099 continue;
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800100 const StringRef Arg = ArgPtr;
Hans Wennborg76b86c22013-07-18 20:29:38 +0000101 if (!Arg.startswith(OptName))
102 continue;
103
104 const StringRef Value = Arg.drop_front(OptName.size());
105 const unsigned M = llvm::StringSwitch<unsigned>(Value)
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800106 .Case("gcc", GCCMode)
107 .Case("g++", GXXMode)
108 .Case("cpp", CPPMode)
109 .Case("cl", CLMode)
110 .Default(~0U);
Hans Wennborg76b86c22013-07-18 20:29:38 +0000111
112 if (M != ~0U)
113 Mode = static_cast<DriverMode>(M);
114 else
115 Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
116 }
117}
118
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800119InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings) {
Daniel Dunbar8f25c792009-03-18 01:38:48 +0000120 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
Hans Wennborg69813302013-07-27 00:23:45 +0000121
122 unsigned IncludedFlagsBitmask;
123 unsigned ExcludedFlagsBitmask;
Stephen Hines651f13c2014-04-23 16:59:28 -0700124 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800125 getIncludeExcludeOptionFlagMasks();
Hans Wennborg69813302013-07-27 00:23:45 +0000126
Daniel Dunbar847abaa2009-11-19 06:35:06 +0000127 unsigned MissingArgIndex, MissingArgCount;
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800128 InputArgList Args =
129 getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
130 IncludedFlagsBitmask, ExcludedFlagsBitmask);
Daniel Dunbara8231832009-09-08 23:36:43 +0000131
Daniel Dunbar847abaa2009-11-19 06:35:06 +0000132 // Check for missing argument error.
133 if (MissingArgCount)
134 Diag(clang::diag::err_drv_missing_argument)
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800135 << Args.getArgString(MissingArgIndex) << MissingArgCount;
Daniel Dunbarad2a9af2009-03-13 11:38:42 +0000136
Daniel Dunbar847abaa2009-11-19 06:35:06 +0000137 // Check for unsupported options.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800138 for (const Arg *A : Args) {
Michael J. Spencer91e06da2012-10-19 22:37:06 +0000139 if (A->getOption().hasFlag(options::Unsupported)) {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800140 Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(Args);
Daniel Dunbarb0c4df52009-03-22 23:26:43 +0000141 continue;
142 }
Chad Rosier2dd17a12012-02-22 17:55:22 +0000143
144 // Warn about -mcpu= without an argument.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800145 if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
146 Diag(clang::diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
Chad Rosier2dd17a12012-02-22 17:55:22 +0000147 }
Daniel Dunbar06482622009-03-05 06:38:47 +0000148 }
149
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800150 for (const Arg *A : Args.filtered(options::OPT_UNKNOWN))
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700151 Diags.Report(IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl :
152 diag::err_drv_unknown_argument)
153 << A->getAsString(Args);
Rafael Espindola06b52b42013-09-23 23:55:25 +0000154
Daniel Dunbar06482622009-03-05 06:38:47 +0000155 return Args;
156}
157
Chad Rosier1fc1de42011-07-27 23:36:45 +0000158// Determine which compilation mode we are in. We look for options which
159// affect the phase, starting with the earliest phases, and record which
160// option we used to determine the final phase.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800161phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
162 Arg **FinalPhaseArg) const {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700163 Arg *PhaseArg = nullptr;
Chad Rosier1fc1de42011-07-27 23:36:45 +0000164 phases::ID FinalPhase;
Eric Christopher59f9b262011-08-17 22:59:59 +0000165
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700166 // -{E,EP,P,M,MM} only run the preprocessor.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800167 if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700168 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
Stephen Hines651f13c2014-04-23 16:59:28 -0700169 (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
170 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
Chad Rosier1fc1de42011-07-27 23:36:45 +0000171 FinalPhase = phases::Preprocess;
Eric Christopher59f9b262011-08-17 22:59:59 +0000172
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700173 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
Chad Rosier1fc1de42011-07-27 23:36:45 +0000174 } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
Douglas Gregorc544ba02013-03-27 16:47:18 +0000175 (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
Stephen Hines651f13c2014-04-23 16:59:28 -0700176 (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
Chad Rosier1fc1de42011-07-27 23:36:45 +0000177 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
Fariborz Jahanian582b3952012-04-02 15:59:19 +0000178 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
Ted Kremenek30660a82012-03-06 20:06:33 +0000179 (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
Chad Rosier1fc1de42011-07-27 23:36:45 +0000180 (PhaseArg = DAL.getLastArg(options::OPT__analyze,
Chad Rosier53cb2b42012-03-06 23:14:35 +0000181 options::OPT__analyze_auto)) ||
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700182 (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
Chad Rosier1fc1de42011-07-27 23:36:45 +0000183 FinalPhase = phases::Compile;
184
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700185 // -S only runs up to the backend.
186 } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
187 FinalPhase = phases::Backend;
188
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800189 // -c compilation only runs up to the assembler.
Chad Rosier1fc1de42011-07-27 23:36:45 +0000190 } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
191 FinalPhase = phases::Assemble;
192
193 // Otherwise do everything.
194 } else
195 FinalPhase = phases::Link;
196
197 if (FinalPhaseArg)
198 *FinalPhaseArg = PhaseArg;
199
200 return FinalPhase;
201}
202
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800203static Arg *MakeInputArg(DerivedArgList &Args, OptTable *Opts,
Hans Wennborg73052bf2013-08-13 21:32:29 +0000204 StringRef Value) {
205 Arg *A = new Arg(Opts->getOption(options::OPT_INPUT), Value,
206 Args.getBaseArgs().MakeIndex(Value), Value.data());
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700207 Args.AddSynthesizedArg(A);
Hans Wennborg73052bf2013-08-13 21:32:29 +0000208 A->claim();
209 return A;
210}
211
Daniel Dunbar279c1db2010-06-11 22:00:26 +0000212DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
213 DerivedArgList *DAL = new DerivedArgList(Args);
214
Daniel Dunbare5a37f42010-09-17 00:45:02 +0000215 bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800216 bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700217 for (Arg *A : Args) {
Daniel Dunbarf78925f2010-06-14 21:23:12 +0000218 // Unfortunately, we have to parse some forwarding options (-Xassembler,
219 // -Xlinker, -Xpreprocessor) because we either integrate their functionality
220 // (assembler and preprocessor), or bypass a previous driver ('collect2').
Daniel Dunbareda3f702010-06-14 21:37:09 +0000221
222 // Rewrite linker options, to replace --no-demangle with a custom internal
223 // option.
224 if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
225 A->getOption().matches(options::OPT_Xlinker)) &&
226 A->containsValue("--no-demangle")) {
Daniel Dunbarf78925f2010-06-14 21:23:12 +0000227 // Add the rewritten no-demangle argument.
228 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
229
230 // Add the remaining values as Xlinker arguments.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800231 for (StringRef Val : A->getValues())
232 if (Val != "--no-demangle")
233 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), Val);
Daniel Dunbarf78925f2010-06-14 21:23:12 +0000234
235 continue;
236 }
237
Daniel Dunbareda3f702010-06-14 21:37:09 +0000238 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
239 // some build systems. We don't try to be complete here because we don't
240 // care to encourage this usage model.
241 if (A->getOption().matches(options::OPT_Wp_COMMA) &&
Richard Smith1d489cf2012-11-01 04:30:05 +0000242 (A->getValue(0) == StringRef("-MD") ||
243 A->getValue(0) == StringRef("-MMD"))) {
Daniel Dunbar212df322010-06-15 20:30:18 +0000244 // Rewrite to -MD/-MMD along with -MF.
Richard Smith1d489cf2012-11-01 04:30:05 +0000245 if (A->getValue(0) == StringRef("-MD"))
Daniel Dunbar212df322010-06-15 20:30:18 +0000246 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
247 else
248 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
Michael J. Spencerda05df72012-11-07 23:37:14 +0000249 if (A->getNumValues() == 2)
250 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
251 A->getValue(1));
Daniel Dunbareda3f702010-06-14 21:37:09 +0000252 continue;
253 }
254
Shantonu Sen7433fed2010-09-17 18:39:08 +0000255 // Rewrite reserved library names.
256 if (A->getOption().matches(options::OPT_l)) {
Richard Smith1d489cf2012-11-01 04:30:05 +0000257 StringRef Value = A->getValue();
Daniel Dunbare5a37f42010-09-17 00:45:02 +0000258
Shantonu Sen7433fed2010-09-17 18:39:08 +0000259 // Rewrite unless -nostdlib is present.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800260 if (!HasNostdlib && !HasNodefaultlib && Value == "stdc++") {
261 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_stdcxx));
Daniel Dunbare5a37f42010-09-17 00:45:02 +0000262 continue;
263 }
Shantonu Sen7433fed2010-09-17 18:39:08 +0000264
265 // Rewrite unconditionally.
266 if (Value == "cc_kext") {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800267 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_cckext));
Shantonu Sen7433fed2010-09-17 18:39:08 +0000268 continue;
269 }
Daniel Dunbare5a37f42010-09-17 00:45:02 +0000270 }
271
Hans Wennborg73052bf2013-08-13 21:32:29 +0000272 // Pick up inputs via the -- option.
273 if (A->getOption().matches(options::OPT__DASH_DASH)) {
274 A->claim();
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800275 for (StringRef Val : A->getValues())
276 DAL->append(MakeInputArg(*DAL, Opts, Val));
Hans Wennborg73052bf2013-08-13 21:32:29 +0000277 continue;
278 }
279
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700280 DAL->append(A);
Daniel Dunbarf78925f2010-06-14 21:23:12 +0000281 }
Daniel Dunbar279c1db2010-06-11 22:00:26 +0000282
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700283 // Enforce -static if -miamcu is present.
284 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false))
285 DAL->AddFlagArg(0, Opts->getOption(options::OPT_static));
286
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800287// Add a default value of -mlinker-version=, if one was given and the user
288// didn't specify one.
Daniel Dunbara77a7232010-08-12 00:05:12 +0000289#if defined(HOST_LINK_VERSION)
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -0700290 if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
291 strlen(HOST_LINK_VERSION) > 0) {
Daniel Dunbara77a7232010-08-12 00:05:12 +0000292 DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
293 HOST_LINK_VERSION);
Daniel Dunbarc326b642010-08-17 22:32:45 +0000294 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
Daniel Dunbara77a7232010-08-12 00:05:12 +0000295 }
296#endif
297
Daniel Dunbar279c1db2010-06-11 22:00:26 +0000298 return DAL;
299}
300
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800301/// \brief Compute target triple from args.
302///
303/// This routine provides the logic to compute a target triple from various
304/// args passed to the driver and the default triple string.
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700305static llvm::Triple computeTargetTriple(const Driver &D,
306 StringRef DefaultTargetTriple,
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800307 const ArgList &Args,
308 StringRef DarwinArchName = "") {
309 // FIXME: Already done in Compilation *Driver::BuildCompilation
310 if (const Arg *A = Args.getLastArg(options::OPT_target))
311 DefaultTargetTriple = A->getValue();
312
313 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
314
315 // Handle Apple-specific options available here.
316 if (Target.isOSBinFormatMachO()) {
317 // If an explict Darwin arch name is given, that trumps all.
318 if (!DarwinArchName.empty()) {
319 tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
320 return Target;
321 }
322
323 // Handle the Darwin '-arch' flag.
324 if (Arg *A = Args.getLastArg(options::OPT_arch)) {
325 StringRef ArchName = A->getValue();
326 tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
327 }
328 }
329
330 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
331 // '-mbig-endian'/'-EB'.
332 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
333 options::OPT_mbig_endian)) {
334 if (A->getOption().matches(options::OPT_mlittle_endian)) {
335 llvm::Triple LE = Target.getLittleEndianArchVariant();
336 if (LE.getArch() != llvm::Triple::UnknownArch)
337 Target = std::move(LE);
338 } else {
339 llvm::Triple BE = Target.getBigEndianArchVariant();
340 if (BE.getArch() != llvm::Triple::UnknownArch)
341 Target = std::move(BE);
342 }
343 }
344
345 // Skip further flag support on OSes which don't support '-m32' or '-m64'.
346 if (Target.getArch() == llvm::Triple::tce ||
347 Target.getOS() == llvm::Triple::Minix)
348 return Target;
349
350 // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700351 Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
352 options::OPT_m32, options::OPT_m16);
353 if (A) {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800354 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
355
356 if (A->getOption().matches(options::OPT_m64)) {
357 AT = Target.get64BitArchVariant().getArch();
358 if (Target.getEnvironment() == llvm::Triple::GNUX32)
359 Target.setEnvironment(llvm::Triple::GNU);
360 } else if (A->getOption().matches(options::OPT_mx32) &&
361 Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
362 AT = llvm::Triple::x86_64;
363 Target.setEnvironment(llvm::Triple::GNUX32);
364 } else if (A->getOption().matches(options::OPT_m32)) {
365 AT = Target.get32BitArchVariant().getArch();
366 if (Target.getEnvironment() == llvm::Triple::GNUX32)
367 Target.setEnvironment(llvm::Triple::GNU);
368 } else if (A->getOption().matches(options::OPT_m16) &&
369 Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
370 AT = llvm::Triple::x86;
371 Target.setEnvironment(llvm::Triple::CODE16);
372 }
373
374 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
375 Target.setArch(AT);
376 }
377
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700378 // Handle -miamcu flag.
379 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
380 if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
381 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
382 << Target.str();
383
384 if (A && !A->getOption().matches(options::OPT_m32))
385 D.Diag(diag::err_drv_argument_not_allowed_with)
386 << "-miamcu" << A->getBaseArg().getAsString(Args);
387
388 Target.setArch(llvm::Triple::x86);
389 Target.setArchName("i586");
390 Target.setEnvironment(llvm::Triple::UnknownEnvironment);
391 Target.setEnvironmentName("");
392 Target.setOS(llvm::Triple::ELFIAMCU);
393 Target.setVendor(llvm::Triple::UnknownVendor);
394 Target.setVendorName("intel");
395 }
396
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800397 return Target;
398}
399
400// \brief Parse the LTO options and record the type of LTO compilation
401// based on which -f(no-)?lto(=.*)? option occurs last.
402void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
403 LTOMode = LTOK_None;
404 if (!Args.hasFlag(options::OPT_flto, options::OPT_flto_EQ,
405 options::OPT_fno_lto, false))
406 return;
407
408 StringRef LTOName("full");
409
410 const Arg *A = Args.getLastArg(options::OPT_flto_EQ);
411 if (A)
412 LTOName = A->getValue();
413
414 LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
415 .Case("full", LTOK_Full)
416 .Case("thin", LTOK_Thin)
417 .Default(LTOK_Unknown);
418
419 if (LTOMode == LTOK_Unknown) {
420 assert(A);
421 Diag(diag::err_drv_unsupported_option_argument) << A->getOption().getName()
422 << A->getValue();
423 }
424}
425
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700426void Driver::CreateOffloadingDeviceToolChains(Compilation &C,
427 InputList &Inputs) {
428
429 //
430 // CUDA
431 //
432 // We need to generate a CUDA toolchain if any of the inputs has a CUDA type.
433 if (llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
434 return types::isCuda(I.first);
435 })) {
436 const ToolChain &TC = getToolChain(
437 C.getInputArgs(),
438 llvm::Triple(C.getOffloadingHostToolChain()->getTriple().isArch64Bit()
439 ? "nvptx64-nvidia-cuda"
440 : "nvptx-nvidia-cuda"));
441 C.addOffloadDeviceToolChain(&TC, Action::OFK_Cuda);
442 }
443
444 //
445 // TODO: Add support for other offloading programming models here.
446 //
447
448 return;
449}
450
Chris Lattner2d3ba4f2011-07-23 17:14:25 +0000451Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
Daniel Dunbar8f25c792009-03-18 01:38:48 +0000452 llvm::PrettyStackTraceString CrashInfo("Compilation construction");
453
Eric Christopher59f9b262011-08-17 22:59:59 +0000454 // FIXME: Handle environment options which affect driver behavior, somewhere
Bill Wendlinge8cb5542012-03-12 21:24:57 +0000455 // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
Chad Rosier815eb6b2011-09-14 00:47:55 +0000456
457 if (char *env = ::getenv("COMPILER_PATH")) {
458 StringRef CompilerPath = env;
459 while (!CompilerPath.empty()) {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800460 std::pair<StringRef, StringRef> Split =
461 CompilerPath.split(llvm::sys::EnvPathSeparator);
Chad Rosier815eb6b2011-09-14 00:47:55 +0000462 PrefixDirs.push_back(Split.first);
463 CompilerPath = Split.second;
464 }
465 }
Daniel Dunbarcb881672009-03-13 00:51:18 +0000466
Hans Wennborg76b86c22013-07-18 20:29:38 +0000467 // We look for the driver mode option early, because the mode can affect
468 // how other options are parsed.
469 ParseDriverMode(ArgList.slice(1));
470
Daniel Dunbarcb881672009-03-13 00:51:18 +0000471 // FIXME: What are we going to do with -V and -b?
472
Daniel Dunbara8231832009-09-08 23:36:43 +0000473 // FIXME: This stuff needs to go into the Compilation, not the driver.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800474 bool CCCPrintPhases;
Daniel Dunbar06482622009-03-05 06:38:47 +0000475
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800476 InputArgList Args = ParseArgStrings(ArgList.slice(1));
477
478 // Silence driver warnings if requested
479 Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w));
Daniel Dunbar8477ee92009-12-04 21:55:23 +0000480
Rafael Espindola7ca79872009-12-07 18:28:29 +0000481 // -no-canonical-prefixes is used very early in main.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800482 Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
Rafael Espindola7ca79872009-12-07 18:28:29 +0000483
Daniel Dunbarc19a12d2010-08-02 02:38:03 +0000484 // Ignore -pipe.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800485 Args.ClaimAllArgs(options::OPT_pipe);
Daniel Dunbarc19a12d2010-08-02 02:38:03 +0000486
Daniel Dunbar8477ee92009-12-04 21:55:23 +0000487 // Extract -ccc args.
Daniel Dunbar365c02f2009-03-10 20:52:46 +0000488 //
Daniel Dunbara8231832009-09-08 23:36:43 +0000489 // FIXME: We need to figure out where this behavior should live. Most of it
490 // should be outside in the client; the parts that aren't should have proper
491 // options, either by introducing new ones or by overloading gcc ones like -V
492 // or -b.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800493 CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
494 CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
495 if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
Richard Smith1d489cf2012-11-01 04:30:05 +0000496 CCCGenericGCCName = A->getValue();
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800497 CCCUsePCH =
498 Args.hasFlag(options::OPT_ccc_pch_is_pch, options::OPT_ccc_pch_is_pth);
Joerg Sonnenberger8a988c32012-02-22 19:15:16 +0000499 // FIXME: DefaultTargetTriple is used by the target-prefixed calls to as/ld
500 // and getToolChain is const.
Hans Wennborg5db95272013-08-13 23:38:57 +0000501 if (IsCLMode()) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700502 // clang-cl targets MSVC-style Win32.
Hans Wennborg5db95272013-08-13 23:38:57 +0000503 llvm::Triple T(DefaultTargetTriple);
Stephen Hines651f13c2014-04-23 16:59:28 -0700504 T.setOS(llvm::Triple::Win32);
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800505 T.setVendor(llvm::Triple::PC);
Stephen Hines651f13c2014-04-23 16:59:28 -0700506 T.setEnvironment(llvm::Triple::MSVC);
Hans Wennborg5db95272013-08-13 23:38:57 +0000507 DefaultTargetTriple = T.str();
508 }
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800509 if (const Arg *A = Args.getLastArg(options::OPT_target))
Richard Smith1d489cf2012-11-01 04:30:05 +0000510 DefaultTargetTriple = A->getValue();
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800511 if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
Richard Smith1d489cf2012-11-01 04:30:05 +0000512 Dir = InstalledDir = A->getValue();
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800513 for (const Arg *A : Args.filtered(options::OPT_B)) {
Benjamin Kramer09982ce2011-02-08 20:31:42 +0000514 A->claim();
Richard Smith1d489cf2012-11-01 04:30:05 +0000515 PrefixDirs.push_back(A->getValue(0));
Benjamin Kramer09982ce2011-02-08 20:31:42 +0000516 }
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800517 if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
Richard Smith1d489cf2012-11-01 04:30:05 +0000518 SysRoot = A->getValue();
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800519 if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
Peter Collingbournebdaa1342013-05-27 21:40:20 +0000520 DyldPrefix = A->getValue();
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800521 if (Args.hasArg(options::OPT_nostdlib))
Joerg Sonnenberger05e59302011-03-21 13:59:26 +0000522 UseStdLib = false;
Daniel Dunbar365c02f2009-03-10 20:52:46 +0000523
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800524 if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
Bob Wilson4a792962013-03-23 05:17:59 +0000525 ResourceDir = A->getValue();
Jim Grosbach61d16c12013-03-12 20:17:58 +0000526
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800527 if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700528 SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
529 .Case("cwd", SaveTempsCwd)
530 .Case("obj", SaveTempsObj)
531 .Default(SaveTempsCwd);
532 }
533
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800534 setLTOMode(Args);
535
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700536 // Ignore -fembed-bitcode options with LTO
537 // since the output will be bitcode anyway.
538 if (getLTOMode() == LTOK_None) {
539 if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
540 StringRef Name = A->getValue();
541 unsigned Model = llvm::StringSwitch<unsigned>(Name)
542 .Case("off", EmbedNone)
543 .Case("all", EmbedBitcode)
544 .Case("bitcode", EmbedBitcode)
545 .Case("marker", EmbedMarker)
546 .Default(~0U);
547 if (Model == ~0U) {
548 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
549 << Name;
550 } else
551 BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
552 }
553 } else {
554 // claim the bitcode option under LTO so no warning is issued.
555 Args.ClaimAllArgs(options::OPT_fembed_bitcode_EQ);
556 }
557
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800558 std::unique_ptr<llvm::opt::InputArgList> UArgs =
559 llvm::make_unique<InputArgList>(std::move(Args));
560
Daniel Dunbar279c1db2010-06-11 22:00:26 +0000561 // Perform the default argument translations.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800562 DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
Daniel Dunbar279c1db2010-06-11 22:00:26 +0000563
Chandler Carruth08386a92012-01-25 08:49:21 +0000564 // Owned by the host.
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700565 const ToolChain &TC = getToolChain(
566 *UArgs, computeTargetTriple(*this, DefaultTargetTriple, *UArgs));
Chandler Carruth08386a92012-01-25 08:49:21 +0000567
Daniel Dunbar586dc232009-03-16 06:42:30 +0000568 // The compilation takes ownership of Args.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800569 Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs);
Daniel Dunbar21549232009-03-18 02:55:38 +0000570
Daniel Dunbar21549232009-03-18 02:55:38 +0000571 if (!HandleImmediateArgs(*C))
572 return C;
573
Chad Rosierbe69f602011-08-12 22:08:57 +0000574 // Construct the list of inputs.
575 InputList Inputs;
Hans Wennborg73052bf2013-08-13 21:32:29 +0000576 BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
Chad Rosierbe69f602011-08-12 22:08:57 +0000577
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700578 // Populate the tool chains for the offloading devices, if any.
579 CreateOffloadingDeviceToolChains(*C, Inputs);
580
Chandler Carruth4a04d0b2012-01-24 10:43:44 +0000581 // Construct the list of abstract actions to perform for this compilation. On
Stephen Hines651f13c2014-04-23 16:59:28 -0700582 // MachO targets this uses the driver-driver and universal actions.
583 if (TC.getTriple().isOSBinFormatMachO())
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800584 BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
Daniel Dunbar21549232009-03-18 02:55:38 +0000585 else
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700586 BuildActions(*C, C->getArgs(), Inputs, C->getActions());
Daniel Dunbar21549232009-03-18 02:55:38 +0000587
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800588 if (CCCPrintPhases) {
Daniel Dunbar10ffa9a2009-03-18 03:13:20 +0000589 PrintActions(*C);
Daniel Dunbar21549232009-03-18 02:55:38 +0000590 return C;
591 }
592
593 BuildJobs(*C);
Daniel Dunbar8d2554a2009-03-15 01:38:15 +0000594
595 return C;
Daniel Dunbar365c02f2009-03-10 20:52:46 +0000596}
597
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800598static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
599 llvm::opt::ArgStringList ASL;
600 for (const auto *A : Args)
601 A->render(Args, ASL);
602
603 for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
604 if (I != ASL.begin())
605 OS << ' ';
606 Command::printArg(OS, *I, true);
607 }
608 OS << '\n';
609}
610
Eric Christopher59f9b262011-08-17 22:59:59 +0000611// When clang crashes, produce diagnostic information including the fully
612// preprocessed source file(s). Request that the developer attach the
Chad Rosier2b819102011-08-02 17:58:04 +0000613// diagnostic information to a bug report.
614void Driver::generateCompilationDiagnostics(Compilation &C,
Stephen Hines176edba2014-12-01 14:53:08 -0800615 const Command &FailingCommand) {
Chad Rosier2639ac62012-02-22 00:30:39 +0000616 if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
Chad Rosier6467c9b2012-07-09 17:31:28 +0000617 return;
Chad Rosier8ba9a622012-03-07 00:30:40 +0000618
Chad Rosier75dbc712013-02-01 18:30:26 +0000619 // Don't try to generate diagnostics for link or dsymutil jobs.
Stephen Hines176edba2014-12-01 14:53:08 -0800620 if (FailingCommand.getCreator().isLinkJob() ||
621 FailingCommand.getCreator().isDsymutilJob())
Chad Rosier2639ac62012-02-22 00:30:39 +0000622 return;
623
Chad Rosier4f6a4b42012-06-19 17:51:34 +0000624 // Print the version of the compiler.
625 PrintVersion(C, llvm::errs());
626
Chad Rosier2b819102011-08-02 17:58:04 +0000627 Diag(clang::diag::note_drv_command_failed_diag_msg)
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800628 << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the "
629 "crash backtrace, preprocessed source, and associated run script.";
Chad Rosier2b819102011-08-02 17:58:04 +0000630
631 // Suppress driver output and emit preprocessor output to temp file.
Hans Wennborg76b86c22013-07-18 20:29:38 +0000632 Mode = CPPMode;
Chad Rosier2b819102011-08-02 17:58:04 +0000633 CCGenDiagnostics = true;
634
Chad Rosierce50c552011-11-02 21:29:05 +0000635 // Save the original job command(s).
Stephen Hines176edba2014-12-01 14:53:08 -0800636 Command Cmd = FailingCommand;
Chad Rosierce50c552011-11-02 21:29:05 +0000637
Richard Smith5b9268f2012-12-20 02:22:15 +0000638 // Keep track of whether we produce any errors while trying to produce
639 // preprocessed sources.
640 DiagnosticErrorTrap Trap(Diags);
641
642 // Suppress tool output.
Chad Rosier2b819102011-08-02 17:58:04 +0000643 C.initCompilationForDiagnostics();
Chad Rosierbe69f602011-08-12 22:08:57 +0000644
645 // Construct the list of inputs.
646 InputList Inputs;
647 BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
Chad Rosier2b819102011-08-02 17:58:04 +0000648
Chad Rosier137a20b2011-08-12 23:30:05 +0000649 for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
Chad Rosier90c88022011-08-18 00:22:25 +0000650 bool IgnoreInput = false;
651
652 // Ignore input from stdin or any inputs that cannot be preprocessed.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700653 // Check type first as not all linker inputs have a value.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800654 if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700655 IgnoreInput = true;
656 } else if (!strcmp(it->second->getValue(), "-")) {
Chad Rosier90c88022011-08-18 00:22:25 +0000657 Diag(clang::diag::note_drv_command_failed_diag_msg)
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800658 << "Error generating preprocessed source(s) - "
659 "ignoring input from stdin.";
Chad Rosier90c88022011-08-18 00:22:25 +0000660 IgnoreInput = true;
Chad Rosier90c88022011-08-18 00:22:25 +0000661 }
662
663 if (IgnoreInput) {
Chad Rosier137a20b2011-08-12 23:30:05 +0000664 it = Inputs.erase(it);
665 ie = Inputs.end();
Chad Rosier30601782011-08-17 23:08:45 +0000666 } else {
Chad Rosier137a20b2011-08-12 23:30:05 +0000667 ++it;
Chad Rosier30601782011-08-17 23:08:45 +0000668 }
Chad Rosier137a20b2011-08-12 23:30:05 +0000669 }
Chad Rosier90c88022011-08-18 00:22:25 +0000670
Chad Rosier8425a542013-01-29 23:57:10 +0000671 if (Inputs.empty()) {
672 Diag(clang::diag::note_drv_command_failed_diag_msg)
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800673 << "Error generating preprocessed source(s) - "
674 "no preprocessable inputs.";
Chad Rosier8425a542013-01-29 23:57:10 +0000675 return;
676 }
677
Chad Rosier46e39082011-09-06 23:52:36 +0000678 // Don't attempt to generate preprocessed files if multiple -arch options are
Chad Rosierc5638912012-02-13 18:16:28 +0000679 // used, unless they're all duplicates.
680 llvm::StringSet<> ArchNames;
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700681 for (const Arg *A : C.getArgs()) {
Chad Rosier46e39082011-09-06 23:52:36 +0000682 if (A->getOption().matches(options::OPT_arch)) {
Richard Smith1d489cf2012-11-01 04:30:05 +0000683 StringRef ArchName = A->getValue();
Chad Rosierc5638912012-02-13 18:16:28 +0000684 ArchNames.insert(ArchName);
Chad Rosier46e39082011-09-06 23:52:36 +0000685 }
686 }
Chad Rosierc5638912012-02-13 18:16:28 +0000687 if (ArchNames.size() > 1) {
688 Diag(clang::diag::note_drv_command_failed_diag_msg)
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800689 << "Error generating preprocessed source(s) - cannot generate "
690 "preprocessed source with multiple -arch options.";
Chad Rosierc5638912012-02-13 18:16:28 +0000691 return;
692 }
Chad Rosier46e39082011-09-06 23:52:36 +0000693
Chandler Carruth4a04d0b2012-01-24 10:43:44 +0000694 // Construct the list of abstract actions to perform for this compilation. On
695 // Darwin OSes this uses the driver-driver and builds universal actions.
Chandler Carruth08386a92012-01-25 08:49:21 +0000696 const ToolChain &TC = C.getDefaultToolChain();
Stephen Hines651f13c2014-04-23 16:59:28 -0700697 if (TC.getTriple().isOSBinFormatMachO())
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800698 BuildUniversalActions(C, TC, Inputs);
Chad Rosier2b819102011-08-02 17:58:04 +0000699 else
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700700 BuildActions(C, C.getArgs(), Inputs, C.getActions());
Chad Rosier2b819102011-08-02 17:58:04 +0000701
702 BuildJobs(C);
703
704 // If there were errors building the compilation, quit now.
Richard Smith5b9268f2012-12-20 02:22:15 +0000705 if (Trap.hasErrorOccurred()) {
Chad Rosier2b819102011-08-02 17:58:04 +0000706 Diag(clang::diag::note_drv_command_failed_diag_msg)
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800707 << "Error generating preprocessed source(s).";
Chad Rosier2b819102011-08-02 17:58:04 +0000708 return;
709 }
710
711 // Generate preprocessed output.
Chad Rosiera16355c2013-01-29 20:15:05 +0000712 SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800713 C.ExecuteJobs(C.getJobs(), FailingCommands);
Chad Rosier2b819102011-08-02 17:58:04 +0000714
Stephen Hines176edba2014-12-01 14:53:08 -0800715 // If any of the preprocessing commands failed, clean up and exit.
716 if (!FailingCommands.empty()) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700717 if (!isSaveTempsEnabled())
Chad Rosier2b819102011-08-02 17:58:04 +0000718 C.CleanupFileList(C.getTempFiles(), true);
719
720 Diag(clang::diag::note_drv_command_failed_diag_msg)
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800721 << "Error generating preprocessed source(s).";
Stephen Hines176edba2014-12-01 14:53:08 -0800722 return;
Chad Rosier2b819102011-08-02 17:58:04 +0000723 }
Stephen Hines176edba2014-12-01 14:53:08 -0800724
725 const ArgStringList &TempFiles = C.getTempFiles();
726 if (TempFiles.empty()) {
727 Diag(clang::diag::note_drv_command_failed_diag_msg)
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800728 << "Error generating preprocessed source(s).";
Stephen Hines176edba2014-12-01 14:53:08 -0800729 return;
730 }
731
732 Diag(clang::diag::note_drv_command_failed_diag_msg)
733 << "\n********************\n\n"
734 "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
735 "Preprocessed source(s) and associated run script(s) are located at:";
736
737 SmallString<128> VFS;
738 for (const char *TempFile : TempFiles) {
739 Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
740 if (StringRef(TempFile).endswith(".cache")) {
741 // In some cases (modules) we'll dump extra data to help with reproducing
742 // the crash into a directory next to the output.
743 VFS = llvm::sys::path::filename(TempFile);
744 llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
745 }
746 }
747
748 // Assume associated files are based off of the first temporary file.
749 CrashReportInfo CrashInfo(TempFiles[0], VFS);
750
751 std::string Script = CrashInfo.Filename.rsplit('.').first.str() + ".sh";
752 std::error_code EC;
753 llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::F_Excl);
754 if (EC) {
755 Diag(clang::diag::note_drv_command_failed_diag_msg)
756 << "Error generating run script: " + Script + " " + EC.message();
757 } else {
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -0700758 ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800759 << "# Driver args: ";
760 printArgList(ScriptOS, C.getInputArgs());
761 ScriptOS << "# Original command: ";
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -0700762 Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
Stephen Hines176edba2014-12-01 14:53:08 -0800763 Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
764 Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
765 }
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700766
767 for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file,
768 options::OPT_frewrite_map_file_EQ))
769 Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
770
Stephen Hines176edba2014-12-01 14:53:08 -0800771 Diag(clang::diag::note_drv_command_failed_diag_msg)
772 << "\n\n********************";
Chad Rosier2b819102011-08-02 17:58:04 +0000773}
774
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800775void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700776 // Since commandLineFitsWithinSystemLimits() may underestimate system's capacity
Stephen Hines176edba2014-12-01 14:53:08 -0800777 // if the tool does not support response files, there is a chance/ that things
778 // will just work without a response file, so we silently just skip it.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800779 if (Cmd.getCreator().getResponseFilesSupport() == Tool::RF_None ||
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700780 llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(), Cmd.getArguments()))
Stephen Hines176edba2014-12-01 14:53:08 -0800781 return;
782
783 std::string TmpName = GetTemporaryPath("response", "txt");
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800784 Cmd.setResponseFile(
785 C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str())));
Stephen Hines176edba2014-12-01 14:53:08 -0800786}
787
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800788int Driver::ExecuteCompilation(
789 Compilation &C,
790 SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
Daniel Dunbarc88a88f2009-07-01 20:03:04 +0000791 // Just print if -### was present.
792 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
Hans Wennborgfc338972013-09-12 18:23:34 +0000793 C.getJobs().Print(llvm::errs(), "\n", true);
Daniel Dunbarc88a88f2009-07-01 20:03:04 +0000794 return 0;
795 }
796
797 // If there were errors building the compilation, quit now.
Chad Rosier2b819102011-08-02 17:58:04 +0000798 if (Diags.hasErrorOccurred())
Daniel Dunbarc88a88f2009-07-01 20:03:04 +0000799 return 1;
800
Stephen Hines176edba2014-12-01 14:53:08 -0800801 // Set up response file names for each command, if necessary
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800802 for (auto &Job : C.getJobs())
803 setUpResponseFiles(C, Job);
Stephen Hines176edba2014-12-01 14:53:08 -0800804
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800805 C.ExecuteJobs(C.getJobs(), FailingCommands);
Daniel Dunbara8231832009-09-08 23:36:43 +0000806
Daniel Dunbarc88a88f2009-07-01 20:03:04 +0000807 // Remove temp files.
808 C.CleanupFileList(C.getTempFiles());
809
Daniel Dunbar9fcbc052010-05-22 00:37:20 +0000810 // If the command succeeded, we are done.
Chad Rosiera16355c2013-01-29 20:15:05 +0000811 if (FailingCommands.empty())
812 return 0;
Daniel Dunbar9fcbc052010-05-22 00:37:20 +0000813
Chad Rosiera16355c2013-01-29 20:15:05 +0000814 // Otherwise, remove result files and print extra information about abnormal
815 // failures.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800816 for (const auto &CmdPair : FailingCommands) {
817 int Res = CmdPair.first;
818 const Command *FailingCommand = CmdPair.second;
Daniel Dunbarc88a88f2009-07-01 20:03:04 +0000819
Chad Rosiera16355c2013-01-29 20:15:05 +0000820 // Remove result files if we're not saving temps.
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700821 if (!isSaveTempsEnabled()) {
Chad Rosiera16355c2013-01-29 20:15:05 +0000822 const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
823 C.CleanupFileMap(C.getResultFiles(), JA, true);
824
825 // Failure result files are valid unless we crashed.
826 if (Res < 0)
827 C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
828 }
829
830 // Print extra information about abnormal failures, if possible.
831 //
832 // This is ad-hoc, but we don't want to be excessively noisy. If the result
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700833 // status was 1, assume the command failed normally. In particular, if it
Chad Rosiera16355c2013-01-29 20:15:05 +0000834 // was the compiler then assume it gave a reasonable error code. Failures
835 // in other tools are less common, and they generally have worse
836 // diagnostics, so always print the diagnostic there.
837 const Tool &FailingTool = FailingCommand->getCreator();
838
839 if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
840 // FIXME: See FIXME above regarding result code interpretation.
841 if (Res < 0)
842 Diag(clang::diag::err_drv_command_signalled)
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800843 << FailingTool.getShortName();
Chad Rosiera16355c2013-01-29 20:15:05 +0000844 else
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800845 Diag(clang::diag::err_drv_command_failed) << FailingTool.getShortName()
846 << Res;
Chad Rosiera16355c2013-01-29 20:15:05 +0000847 }
Peter Collingbourne5d4d9802011-11-21 00:01:05 +0000848 }
Chad Rosiera16355c2013-01-29 20:15:05 +0000849 return 0;
Daniel Dunbarc88a88f2009-07-01 20:03:04 +0000850}
851
Daniel Dunbarc35d71f2009-04-15 16:34:29 +0000852void Driver::PrintHelp(bool ShowHidden) const {
Hans Wennborg69813302013-07-27 00:23:45 +0000853 unsigned IncludedFlagsBitmask;
854 unsigned ExcludedFlagsBitmask;
Stephen Hines651f13c2014-04-23 16:59:28 -0700855 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800856 getIncludeExcludeOptionFlagMasks();
Hans Wennborg69813302013-07-27 00:23:45 +0000857
858 ExcludedFlagsBitmask |= options::NoDriverOption;
859 if (!ShowHidden)
860 ExcludedFlagsBitmask |= HelpHidden;
861
862 getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
863 IncludedFlagsBitmask, ExcludedFlagsBitmask);
Daniel Dunbar91e28af2009-03-31 21:38:17 +0000864}
865
Chris Lattner5f9e2722011-07-23 10:55:15 +0000866void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
Daniel Dunbara8231832009-09-08 23:36:43 +0000867 // FIXME: The following handlers should use a callback mechanism, we don't
868 // know what the client would like to do.
Ted Kremeneka18f1b82010-01-23 02:11:34 +0000869 OS << getClangFullVersion() << '\n';
Daniel Dunbar70c8db12009-03-26 16:09:13 +0000870 const ToolChain &TC = C.getDefaultToolChain();
Daniel Dunbar79300722009-07-21 20:06:58 +0000871 OS << "Target: " << TC.getTripleString() << '\n';
Daniel Dunbar3ee96ba2009-06-16 23:32:58 +0000872
873 // Print the threading model.
Stephen Hines176edba2014-12-01 14:53:08 -0800874 if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
875 // Don't print if the ToolChain would have barfed on it already
876 if (TC.isThreadModelSupported(A->getValue()))
877 OS << "Thread model: " << A->getValue();
878 } else
879 OS << "Thread model: " << TC.getThreadModel();
880 OS << '\n';
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800881
882 // Print out the install directory.
883 OS << "InstalledDir: " << InstalledDir << '\n';
Daniel Dunbarcb881672009-03-13 00:51:18 +0000884}
885
Chris Lattnerc3d26cc2010-05-05 05:53:24 +0000886/// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
887/// option.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000888static void PrintDiagnosticCategories(raw_ostream &OS) {
Argyrios Kyrtzidis477aab62011-05-25 05:05:01 +0000889 // Skip the empty category.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800890 for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
891 ++i)
Argyrios Kyrtzidis477aab62011-05-25 05:05:01 +0000892 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
Chris Lattnerc3d26cc2010-05-05 05:53:24 +0000893}
894
Daniel Dunbar21549232009-03-18 02:55:38 +0000895bool Driver::HandleImmediateArgs(const Compilation &C) {
Daniel Dunbare82ec0b2010-06-11 22:00:19 +0000896 // The order these options are handled in gcc is all over the place, but we
Daniel Dunbara8231832009-09-08 23:36:43 +0000897 // don't expect inconsistencies w.r.t. that to matter in practice.
Daniel Dunbar91e28af2009-03-31 21:38:17 +0000898
Daniel Dunbard8299502010-09-17 02:47:28 +0000899 if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
900 llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
901 return false;
902 }
903
Daniel Dunbare06dc212009-04-04 05:17:38 +0000904 if (C.getArgs().hasArg(options::OPT_dumpversion)) {
Daniel Dunbar95a907f2011-01-12 00:43:47 +0000905 // Since -dumpversion is only implemented for pedantic GCC compatibility, we
906 // return an answer which matches our definition of __VERSION__.
907 //
908 // If we want to return a more correct answer some day, then we should
909 // introduce a non-pedantically GCC compatible mode to Clang in which we
910 // provide sensible definitions for -dumpversion, __VERSION__, etc.
911 llvm::outs() << "4.2.1\n";
Daniel Dunbare06dc212009-04-04 05:17:38 +0000912 return false;
913 }
Daniel Dunbarf78925f2010-06-14 21:23:12 +0000914
Chris Lattnerc3d26cc2010-05-05 05:53:24 +0000915 if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
916 PrintDiagnosticCategories(llvm::outs());
917 return false;
918 }
Daniel Dunbare06dc212009-04-04 05:17:38 +0000919
James Molloybfd7a522012-05-01 14:57:16 +0000920 if (C.getArgs().hasArg(options::OPT_help) ||
Daniel Dunbarc35d71f2009-04-15 16:34:29 +0000921 C.getArgs().hasArg(options::OPT__help_hidden)) {
922 PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
Daniel Dunbar91e28af2009-03-31 21:38:17 +0000923 return false;
924 }
925
Daniel Dunbar6cc73de2009-04-02 15:05:41 +0000926 if (C.getArgs().hasArg(options::OPT__version)) {
Daniel Dunbara8231832009-09-08 23:36:43 +0000927 // Follow gcc behavior and use stdout for --version and stderr for -v.
Daniel Dunbar79300722009-07-21 20:06:58 +0000928 PrintVersion(C, llvm::outs());
Daniel Dunbar6cc73de2009-04-02 15:05:41 +0000929 return false;
930 }
931
Daniel Dunbara8231832009-09-08 23:36:43 +0000932 if (C.getArgs().hasArg(options::OPT_v) ||
Daniel Dunbar21549232009-03-18 02:55:38 +0000933 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
Daniel Dunbar79300722009-07-21 20:06:58 +0000934 PrintVersion(C, llvm::errs());
Daniel Dunbarcb881672009-03-13 00:51:18 +0000935 SuppressMissingInputWarning = true;
936 }
937
Daniel Dunbar21549232009-03-18 02:55:38 +0000938 const ToolChain &TC = C.getDefaultToolChain();
Chandler Carruth6365ab92013-07-30 17:57:09 +0000939
940 if (C.getArgs().hasArg(options::OPT_v))
941 TC.printVerboseInfo(llvm::errs());
942
Daniel Dunbarca3459e2009-03-20 04:37:21 +0000943 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
944 llvm::outs() << "programs: =";
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800945 bool separator = false;
946 for (const std::string &Path : TC.getProgramPaths()) {
947 if (separator)
Daniel Dunbarca3459e2009-03-20 04:37:21 +0000948 llvm::outs() << ':';
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800949 llvm::outs() << Path;
950 separator = true;
Daniel Dunbarca3459e2009-03-20 04:37:21 +0000951 }
952 llvm::outs() << "\n";
Peter Collingbourne41ee7a32011-09-06 02:08:31 +0000953 llvm::outs() << "libraries: =" << ResourceDir;
Joerg Sonnenberger59c84572011-07-16 10:50:05 +0000954
Sebastian Pop4762a2d2012-04-16 04:16:43 +0000955 StringRef sysroot = C.getSysRoot();
Joerg Sonnenberger59c84572011-07-16 10:50:05 +0000956
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800957 for (const std::string &Path : TC.getFilePaths()) {
958 // Always print a separator. ResourceDir was the first item shown.
Peter Collingbourne41ee7a32011-09-06 02:08:31 +0000959 llvm::outs() << ':';
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800960 // Interpretation of leading '=' is needed only for NetBSD.
961 if (Path[0] == '=')
962 llvm::outs() << sysroot << Path.substr(1);
Joerg Sonnenberger59c84572011-07-16 10:50:05 +0000963 else
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800964 llvm::outs() << Path;
Daniel Dunbarca3459e2009-03-20 04:37:21 +0000965 }
966 llvm::outs() << "\n";
Daniel Dunbar91e28af2009-03-31 21:38:17 +0000967 return false;
Daniel Dunbarca3459e2009-03-20 04:37:21 +0000968 }
969
Daniel Dunbara8231832009-09-08 23:36:43 +0000970 // FIXME: The following handlers should use a callback mechanism, we don't
971 // know what the client would like to do.
Daniel Dunbar21549232009-03-18 02:55:38 +0000972 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
Richard Smith1d489cf2012-11-01 04:30:05 +0000973 llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
Daniel Dunbarcb881672009-03-13 00:51:18 +0000974 return false;
975 }
976
Daniel Dunbar21549232009-03-18 02:55:38 +0000977 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
Richard Smith1d489cf2012-11-01 04:30:05 +0000978 llvm::outs() << GetProgramPath(A->getValue(), TC) << "\n";
Daniel Dunbarcb881672009-03-13 00:51:18 +0000979 return false;
980 }
981
Daniel Dunbar21549232009-03-18 02:55:38 +0000982 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
Daniel Dunbar5ed34f42009-09-09 22:33:00 +0000983 llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
Daniel Dunbarcb881672009-03-13 00:51:18 +0000984 return false;
985 }
986
Daniel Dunbar12cfe032009-06-16 23:25:22 +0000987 if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800988 for (const Multilib &Multilib : TC.getMultilibs())
989 llvm::outs() << Multilib << "\n";
Daniel Dunbar12cfe032009-06-16 23:25:22 +0000990 return false;
991 }
992
Stephen Hines651f13c2014-04-23 16:59:28 -0700993 if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800994 for (const Multilib &Multilib : TC.getMultilibs()) {
995 if (Multilib.gccSuffix().empty())
Stephen Hines651f13c2014-04-23 16:59:28 -0700996 llvm::outs() << ".\n";
997 else {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800998 StringRef Suffix(Multilib.gccSuffix());
Stephen Hines651f13c2014-04-23 16:59:28 -0700999 assert(Suffix.front() == '/');
1000 llvm::outs() << Suffix.substr(1) << "\n";
1001 }
Daniel Dunbar12cfe032009-06-16 23:25:22 +00001002 }
1003 return false;
1004 }
Daniel Dunbarcb881672009-03-13 00:51:18 +00001005 return true;
1006}
1007
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -07001008// Display an action graph human-readably. Action A is the "sink" node
1009// and latest-occuring action. Traversal is in pre-order, visiting the
1010// inputs to each action before printing the action itself.
Daniel Dunbara8231832009-09-08 23:36:43 +00001011static unsigned PrintActions1(const Compilation &C, Action *A,
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001012 std::map<Action *, unsigned> &Ids) {
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -07001013 if (Ids.count(A)) // A was already visited.
Daniel Dunbarba102132009-03-13 12:19:02 +00001014 return Ids[A];
Daniel Dunbara8231832009-09-08 23:36:43 +00001015
Daniel Dunbarba102132009-03-13 12:19:02 +00001016 std::string str;
1017 llvm::raw_string_ostream os(str);
Daniel Dunbara8231832009-09-08 23:36:43 +00001018
Daniel Dunbarba102132009-03-13 12:19:02 +00001019 os << Action::getClassName(A->getKind()) << ", ";
Daniel Dunbara8231832009-09-08 23:36:43 +00001020 if (InputAction *IA = dyn_cast<InputAction>(A)) {
Richard Smith1d489cf2012-11-01 04:30:05 +00001021 os << "\"" << IA->getInputArg().getValue() << "\"";
Daniel Dunbarba102132009-03-13 12:19:02 +00001022 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001023 os << '"' << BIA->getArchName() << '"' << ", {"
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001024 << PrintActions1(C, *BIA->input_begin(), Ids) << "}";
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001025 } else if (CudaDeviceAction *CDA = dyn_cast<CudaDeviceAction>(A)) {
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001026 CudaArch Arch = CDA->getGpuArch();
1027 if (Arch != CudaArch::UNKNOWN)
1028 os << "'" << CudaArchToString(Arch) << "', ";
1029 os << "{" << PrintActions1(C, *CDA->input_begin(), Ids) << "}";
Daniel Dunbarba102132009-03-13 12:19:02 +00001030 } else {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001031 const ActionList *AL;
1032 if (CudaHostAction *CHA = dyn_cast<CudaHostAction>(A)) {
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001033 os << "{" << PrintActions1(C, *CHA->input_begin(), Ids) << "}"
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001034 << ", gpu binaries ";
1035 AL = &CHA->getDeviceActions();
1036 } else
1037 AL = &A->getInputs();
1038
1039 if (AL->size()) {
1040 const char *Prefix = "{";
1041 for (Action *PreRequisite : *AL) {
1042 os << Prefix << PrintActions1(C, PreRequisite, Ids);
1043 Prefix = ", ";
1044 }
1045 os << "}";
1046 } else
1047 os << "{}";
Daniel Dunbarba102132009-03-13 12:19:02 +00001048 }
1049
1050 unsigned Id = Ids.size();
1051 Ids[A] = Id;
Daniel Dunbara8231832009-09-08 23:36:43 +00001052 llvm::errs() << Id << ": " << os.str() << ", "
Daniel Dunbarba102132009-03-13 12:19:02 +00001053 << types::getTypeName(A->getType()) << "\n";
1054
1055 return Id;
1056}
1057
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -07001058// Print the action graphs in a compilation C.
1059// For example "clang -c file1.c file2.c" is composed of two subgraphs.
Daniel Dunbar10ffa9a2009-03-18 03:13:20 +00001060void Driver::PrintActions(const Compilation &C) const {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001061 std::map<Action *, unsigned> Ids;
1062 for (Action *A : C.getActions())
1063 PrintActions1(C, A, Ids);
Daniel Dunbar53ec5522009-03-12 07:58:46 +00001064}
1065
Joerg Sonnenberger9d0fbea2011-05-06 14:05:11 +00001066/// \brief Check whether the given input tree contains any compilation or
1067/// assembly actions.
1068static bool ContainsCompileOrAssembleAction(const Action *A) {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001069 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001070 isa<AssembleJobAction>(A))
Daniel Dunbarb5e2f692010-06-29 16:38:33 +00001071 return true;
1072
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001073 for (const Action *Input : A->inputs())
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001074 if (ContainsCompileOrAssembleAction(Input))
Daniel Dunbarb5e2f692010-06-29 16:38:33 +00001075 return true;
1076
1077 return false;
1078}
1079
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001080void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
1081 const InputList &BAInputs) const {
1082 DerivedArgList &Args = C.getArgs();
1083 ActionList &Actions = C.getActions();
Daniel Dunbara8231832009-09-08 23:36:43 +00001084 llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
1085 // Collect the list of architectures. Duplicates are allowed, but should only
1086 // be handled once (in the order seen).
Daniel Dunbar13689542009-03-13 20:33:35 +00001087 llvm::StringSet<> ArchNames;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001088 SmallVector<const char *, 4> Archs;
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001089 for (Arg *A : Args) {
Daniel Dunbarb827a052009-11-19 03:26:40 +00001090 if (A->getOption().matches(options::OPT_arch)) {
Daniel Dunbar36df2902009-09-08 23:37:30 +00001091 // Validate the option here; we don't save the type here because its
1092 // particular spelling may participate in other driver choices.
1093 llvm::Triple::ArchType Arch =
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001094 tools::darwin::getArchTypeForMachOArchName(A->getValue());
Daniel Dunbar36df2902009-09-08 23:37:30 +00001095 if (Arch == llvm::Triple::UnknownArch) {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001096 Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
Daniel Dunbar36df2902009-09-08 23:37:30 +00001097 continue;
1098 }
1099
Daniel Dunbar75877192009-03-19 07:55:12 +00001100 A->claim();
Stephen Hines176edba2014-12-01 14:53:08 -08001101 if (ArchNames.insert(A->getValue()).second)
Richard Smith1d489cf2012-11-01 04:30:05 +00001102 Archs.push_back(A->getValue());
Daniel Dunbar2fe63e62009-03-12 18:40:18 +00001103 }
1104 }
1105
Daniel Dunbara8231832009-09-08 23:36:43 +00001106 // When there is no explicit arch for this platform, make sure we still bind
1107 // the architecture (to the default) so that -Xarch_ is handled correctly.
Daniel Dunbar10ffa9a2009-03-18 03:13:20 +00001108 if (!Archs.size())
Daniel Dunbard2a527e2012-11-08 03:38:26 +00001109 Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
Daniel Dunbar2fe63e62009-03-12 18:40:18 +00001110
Daniel Dunbar2fe63e62009-03-12 18:40:18 +00001111 ActionList SingleActions;
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001112 BuildActions(C, Args, BAInputs, SingleActions);
Daniel Dunbar2fe63e62009-03-12 18:40:18 +00001113
Daniel Dunbarbe1cc3e2010-06-04 18:28:41 +00001114 // Add in arch bindings for every top level action, as well as lipo and
1115 // dsymutil steps if needed.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001116 for (Action* Act : SingleActions) {
Daniel Dunbara8231832009-09-08 23:36:43 +00001117 // Make sure we can lipo this kind of output. If not (and it is an actual
1118 // output) then we disallow, since we can't create an output file with the
1119 // right name without overwriting it. We could remove this oddity by just
1120 // changing the output names to include the arch, which would also fix
Daniel Dunbar2fe63e62009-03-12 18:40:18 +00001121 // -save-temps. Compatibility wins for now.
1122
Daniel Dunbar3dbd6c52009-03-13 17:46:02 +00001123 if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
Daniel Dunbar2fe63e62009-03-12 18:40:18 +00001124 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001125 << types::getTypeName(Act->getType());
Daniel Dunbar2fe63e62009-03-12 18:40:18 +00001126
1127 ActionList Inputs;
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001128 for (unsigned i = 0, e = Archs.size(); i != e; ++i)
1129 Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
Daniel Dunbar2fe63e62009-03-12 18:40:18 +00001130
Daniel Dunbara8231832009-09-08 23:36:43 +00001131 // Lipo if necessary, we do it this way because we need to set the arch flag
1132 // so that -Xarch_ gets overwritten.
Daniel Dunbar2fe63e62009-03-12 18:40:18 +00001133 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
1134 Actions.append(Inputs.begin(), Inputs.end());
1135 else
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001136 Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
Daniel Dunbarbe1cc3e2010-06-04 18:28:41 +00001137
Eric Christopherb822f722012-02-06 19:43:51 +00001138 // Handle debug info queries.
1139 Arg *A = Args.getLastArg(options::OPT_g_Group);
David Blaikie6c229392012-04-15 21:22:10 +00001140 if (A && !A->getOption().matches(options::OPT_g0) &&
1141 !A->getOption().matches(options::OPT_gstabs) &&
1142 ContainsCompileOrAssembleAction(Actions.back())) {
Chad Rosier6467c9b2012-07-09 17:31:28 +00001143
David Blaikie6c229392012-04-15 21:22:10 +00001144 // Add a 'dsymutil' step if necessary, when debug info is enabled and we
1145 // have a compile input. We need to run 'dsymutil' ourselves in such cases
Eric Christophera5229872013-01-28 17:39:03 +00001146 // because the debug info will refer to a temporary object file which
David Blaikie6c229392012-04-15 21:22:10 +00001147 // will be removed at the end of the compilation process.
1148 if (Act->getType() == types::TY_Image) {
1149 ActionList Inputs;
1150 Inputs.push_back(Actions.back());
1151 Actions.pop_back();
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001152 Actions.push_back(
1153 C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
Daniel Dunbarbe1cc3e2010-06-04 18:28:41 +00001154 }
David Blaikie6c229392012-04-15 21:22:10 +00001155
Stephen Hines651f13c2014-04-23 16:59:28 -07001156 // Verify the debug info output.
1157 if (Args.hasArg(options::OPT_verify_debug_info)) {
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001158 Action* LastAction = Actions.back();
David Blaikie6c229392012-04-15 21:22:10 +00001159 Actions.pop_back();
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001160 Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
1161 LastAction, types::TY_Nothing));
David Blaikie6c229392012-04-15 21:22:10 +00001162 }
1163 }
Daniel Dunbar2fe63e62009-03-12 18:40:18 +00001164 }
Daniel Dunbar53ec5522009-03-12 07:58:46 +00001165}
1166
Hans Wennborg4c587532013-08-06 00:20:31 +00001167/// \brief Check that the file referenced by Value exists. If it doesn't,
1168/// issue a diagnostic and return false.
Stephen Hines651f13c2014-04-23 16:59:28 -07001169static bool DiagnoseInputExistence(const Driver &D, const DerivedArgList &Args,
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001170 StringRef Value, types::ID Ty) {
Hans Wennborg4c587532013-08-06 00:20:31 +00001171 if (!D.getCheckInputsExist())
1172 return true;
1173
1174 // stdin always exists.
1175 if (Value == "-")
1176 return true;
1177
1178 SmallString<64> Path(Value);
1179 if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07001180 if (!llvm::sys::path::is_absolute(Path)) {
Hans Wennborg4c587532013-08-06 00:20:31 +00001181 SmallString<64> Directory(WorkDir->getValue());
1182 llvm::sys::path::append(Directory, Value);
1183 Path.assign(Directory);
1184 }
1185 }
1186
1187 if (llvm::sys::fs::exists(Twine(Path)))
1188 return true;
1189
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001190 if (D.IsCLMode()) {
1191 if (!llvm::sys::path::is_absolute(Twine(Path)) &&
1192 llvm::sys::Process::FindInEnvPath("LIB", Value))
1193 return true;
1194
1195 if (Args.hasArg(options::OPT__SLASH_link) && Ty == types::TY_Object) {
1196 // Arguments to the /link flag might cause the linker to search for object
1197 // and library files in paths we don't know about. Don't error in such
1198 // cases.
1199 return true;
1200 }
1201 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001202
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07001203 D.Diag(clang::diag::err_drv_no_such_file) << Path;
Hans Wennborg4c587532013-08-06 00:20:31 +00001204 return false;
1205}
1206
Chad Rosierbe69f602011-08-12 22:08:57 +00001207// Construct a the list of inputs and their types.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001208void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
Chad Rosierbe69f602011-08-12 22:08:57 +00001209 InputList &Inputs) const {
Daniel Dunbara8231832009-09-08 23:36:43 +00001210 // Track the current user specified (-x) input. We also explicitly track the
1211 // argument used to set the type; we only want to claim the type when we
1212 // actually use it, so we warn about unused -x arguments.
Daniel Dunbar83dd21f2009-03-13 17:57:10 +00001213 types::ID InputType = types::TY_Nothing;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001214 Arg *InputTypeArg = nullptr;
Daniel Dunbar83dd21f2009-03-13 17:57:10 +00001215
Hans Wennborgf86c1392013-08-12 18:34:17 +00001216 // The last /TC or /TP option sets the input type to C or C++ globally.
Stephen Hines176edba2014-12-01 14:53:08 -08001217 if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
1218 options::OPT__SLASH_TP)) {
Hans Wennborg4c587532013-08-06 00:20:31 +00001219 InputTypeArg = TCTP;
Hans Wennborgf86c1392013-08-12 18:34:17 +00001220 InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001221 ? types::TY_C
1222 : types::TY_CXX;
Hans Wennborg4c587532013-08-06 00:20:31 +00001223
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001224 arg_iterator it =
1225 Args.filtered_begin(options::OPT__SLASH_TC, options::OPT__SLASH_TP);
Hans Wennborgf86c1392013-08-12 18:34:17 +00001226 const arg_iterator ie = Args.filtered_end();
1227 Arg *Previous = *it++;
1228 bool ShowNote = false;
1229 while (it != ie) {
Hans Wennborg42ade492013-09-11 16:38:41 +00001230 Diag(clang::diag::warn_drv_overriding_flag_option)
1231 << Previous->getSpelling() << (*it)->getSpelling();
Hans Wennborgf86c1392013-08-12 18:34:17 +00001232 Previous = *it++;
1233 ShowNote = true;
Hans Wennborg4c587532013-08-06 00:20:31 +00001234 }
Hans Wennborgf86c1392013-08-12 18:34:17 +00001235 if (ShowNote)
1236 Diag(clang::diag::note_drv_t_option_is_global);
Hans Wennborg4c587532013-08-06 00:20:31 +00001237
1238 // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
1239 assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
1240 }
1241
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001242 for (Arg *A : Args) {
Michael J. Spencer43275572012-08-20 21:41:17 +00001243 if (A->getOption().getKind() == Option::InputClass) {
Richard Smith1d489cf2012-11-01 04:30:05 +00001244 const char *Value = A->getValue();
Daniel Dunbar53ec5522009-03-12 07:58:46 +00001245 types::ID Ty = types::TY_INVALID;
1246
1247 // Infer the input type if necessary.
Daniel Dunbar83dd21f2009-03-13 17:57:10 +00001248 if (InputType == types::TY_Nothing) {
1249 // If there was an explicit arg for this, claim it.
1250 if (InputTypeArg)
1251 InputTypeArg->claim();
1252
Daniel Dunbar53ec5522009-03-12 07:58:46 +00001253 // stdin must be handled specially.
1254 if (memcmp(Value, "-", 2) == 0) {
Daniel Dunbara8231832009-09-08 23:36:43 +00001255 // If running with -E, treat as a C input (this changes the builtin
1256 // macros, for example). This may be overridden by -ObjC below.
Daniel Dunbar53ec5522009-03-12 07:58:46 +00001257 //
Daniel Dunbara8231832009-09-08 23:36:43 +00001258 // Otherwise emit an error but still use a valid type to avoid
1259 // spurious errors (e.g., no inputs).
Hans Wennborg76b86c22013-07-18 20:29:38 +00001260 if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
Stephen Hines651f13c2014-04-23 16:59:28 -07001261 Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
1262 : clang::diag::err_drv_unknown_stdin_type);
Daniel Dunbar53ec5522009-03-12 07:58:46 +00001263 Ty = types::TY_C;
1264 } else {
Joerg Sonnenberger9a2927c2011-03-16 22:45:02 +00001265 // Otherwise lookup by extension.
1266 // Fallback is C if invoked as C preprocessor or Object otherwise.
1267 // We use a host hook here because Darwin at least has its own
Daniel Dunbara8231832009-09-08 23:36:43 +00001268 // idea of what .s is.
Daniel Dunbar53ec5522009-03-12 07:58:46 +00001269 if (const char *Ext = strrchr(Value, '.'))
Daniel Dunbar41800112010-08-02 05:43:56 +00001270 Ty = TC.LookupTypeForExtension(Ext + 1);
Daniel Dunbare33bea42009-03-20 23:39:23 +00001271
Joerg Sonnenberger9a2927c2011-03-16 22:45:02 +00001272 if (Ty == types::TY_INVALID) {
Hans Wennborg76b86c22013-07-18 20:29:38 +00001273 if (CCCIsCPP())
Joerg Sonnenberger9a2927c2011-03-16 22:45:02 +00001274 Ty = types::TY_C;
1275 else
1276 Ty = types::TY_Object;
1277 }
Daniel Dunbar51679c52010-02-17 20:32:58 +00001278
1279 // If the driver is invoked as C++ compiler (like clang++ or c++) it
1280 // should autodetect some input files as C++ for g++ compatibility.
Hans Wennborg76b86c22013-07-18 20:29:38 +00001281 if (CCCIsCXX()) {
Daniel Dunbar51679c52010-02-17 20:32:58 +00001282 types::ID OldTy = Ty;
1283 Ty = types::lookupCXXTypeForCType(Ty);
1284
1285 if (Ty != OldTy)
1286 Diag(clang::diag::warn_drv_treating_input_as_cxx)
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001287 << getTypeName(OldTy) << getTypeName(Ty);
Daniel Dunbar51679c52010-02-17 20:32:58 +00001288 }
Daniel Dunbar53ec5522009-03-12 07:58:46 +00001289 }
1290
Daniel Dunbar683ca382009-05-18 21:47:54 +00001291 // -ObjC and -ObjC++ override the default language, but only for "source
1292 // files". We just treat everything that isn't a linker input as a
1293 // source file.
Daniel Dunbara8231832009-09-08 23:36:43 +00001294 //
Daniel Dunbar683ca382009-05-18 21:47:54 +00001295 // FIXME: Clean this up if we move the phase sequence into the type.
Daniel Dunbar53ec5522009-03-12 07:58:46 +00001296 if (Ty != types::TY_Object) {
1297 if (Args.hasArg(options::OPT_ObjC))
1298 Ty = types::TY_ObjC;
1299 else if (Args.hasArg(options::OPT_ObjCXX))
1300 Ty = types::TY_ObjCXX;
1301 }
1302 } else {
1303 assert(InputTypeArg && "InputType set w/o InputTypeArg");
Stephen Hines176edba2014-12-01 14:53:08 -08001304 if (!InputTypeArg->getOption().matches(options::OPT_x)) {
1305 // If emulating cl.exe, make sure that /TC and /TP don't affect input
1306 // object files.
1307 const char *Ext = strrchr(Value, '.');
1308 if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
1309 Ty = types::TY_Object;
1310 }
1311 if (Ty == types::TY_INVALID) {
1312 Ty = InputType;
1313 InputTypeArg->claim();
1314 }
Daniel Dunbar53ec5522009-03-12 07:58:46 +00001315 }
1316
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001317 if (DiagnoseInputExistence(*this, Args, Value, Ty))
Daniel Dunbar53ec5522009-03-12 07:58:46 +00001318 Inputs.push_back(std::make_pair(Ty, A));
1319
Hans Wennborg4c587532013-08-06 00:20:31 +00001320 } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
1321 StringRef Value = A->getValue();
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001322 if (DiagnoseInputExistence(*this, Args, Value, types::TY_C)) {
Hans Wennborg4c587532013-08-06 00:20:31 +00001323 Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
1324 Inputs.push_back(std::make_pair(types::TY_C, InputArg));
1325 }
1326 A->claim();
1327 } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
1328 StringRef Value = A->getValue();
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001329 if (DiagnoseInputExistence(*this, Args, Value, types::TY_CXX)) {
Hans Wennborg4c587532013-08-06 00:20:31 +00001330 Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
1331 Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
1332 }
1333 A->claim();
Michael J. Spencer91e06da2012-10-19 22:37:06 +00001334 } else if (A->getOption().hasFlag(options::LinkerInput)) {
Daniel Dunbara8231832009-09-08 23:36:43 +00001335 // Just treat as object type, we could make a special type for this if
1336 // necessary.
Daniel Dunbar53ec5522009-03-12 07:58:46 +00001337 Inputs.push_back(std::make_pair(types::TY_Object, A));
1338
Daniel Dunbarb827a052009-11-19 03:26:40 +00001339 } else if (A->getOption().matches(options::OPT_x)) {
Daniel Dunbara8231832009-09-08 23:36:43 +00001340 InputTypeArg = A;
Richard Smith1d489cf2012-11-01 04:30:05 +00001341 InputType = types::lookupTypeForTypeSpecifier(A->getValue());
Chad Rosiera53ab5c2012-04-07 00:01:31 +00001342 A->claim();
Daniel Dunbar53ec5522009-03-12 07:58:46 +00001343
1344 // Follow gcc behavior and treat as linker input for invalid -x
Daniel Dunbara8231832009-09-08 23:36:43 +00001345 // options. Its not clear why we shouldn't just revert to unknown; but
Michael J. Spencer74cae0c2010-12-17 21:22:33 +00001346 // this isn't very important, we might as well be bug compatible.
Daniel Dunbar53ec5522009-03-12 07:58:46 +00001347 if (!InputType) {
Richard Smith1d489cf2012-11-01 04:30:05 +00001348 Diag(clang::diag::err_drv_unknown_language) << A->getValue();
Daniel Dunbar53ec5522009-03-12 07:58:46 +00001349 InputType = types::TY_Object;
1350 }
1351 }
1352 }
Hans Wennborg76b86c22013-07-18 20:29:38 +00001353 if (CCCIsCPP() && Inputs.empty()) {
Joerg Sonnenberger9ade4ae2011-03-06 23:31:01 +00001354 // If called as standalone preprocessor, stdin is processed
1355 // if no other input is present.
Hans Wennborg4c587532013-08-06 00:20:31 +00001356 Arg *A = MakeInputArg(Args, Opts, "-");
Joerg Sonnenberger9ade4ae2011-03-06 23:31:01 +00001357 Inputs.push_back(std::make_pair(types::TY_C, A));
1358 }
Chad Rosierbe69f602011-08-12 22:08:57 +00001359}
1360
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001361// For each unique --cuda-gpu-arch= argument creates a TY_CUDA_DEVICE
1362// input action and then wraps each in CudaDeviceAction paired with
1363// appropriate GPU arch name. In case of partial (i.e preprocessing
1364// only) or device-only compilation, each device action is added to /p
1365// Actions and /p Current is released. Otherwise the function creates
1366// and returns a new CudaHostAction which wraps /p Current and device
1367// side actions.
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001368static Action *buildCudaActions(Compilation &C, DerivedArgList &Args,
1369 const Arg *InputArg, Action *HostAction,
1370 ActionList &Actions) {
1371 Arg *PartialCompilationArg = Args.getLastArg(
1372 options::OPT_cuda_host_only, options::OPT_cuda_device_only,
1373 options::OPT_cuda_compile_host_device);
1374 bool CompileHostOnly =
1375 PartialCompilationArg &&
1376 PartialCompilationArg->getOption().matches(options::OPT_cuda_host_only);
1377 bool CompileDeviceOnly =
1378 PartialCompilationArg &&
1379 PartialCompilationArg->getOption().matches(options::OPT_cuda_device_only);
1380
1381 if (CompileHostOnly)
1382 return C.MakeAction<CudaHostAction>(HostAction, ActionList());
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001383
1384 // Collect all cuda_gpu_arch parameters, removing duplicates.
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001385 SmallVector<CudaArch, 4> GpuArchList;
1386 llvm::SmallSet<CudaArch, 4> GpuArchs;
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001387 for (Arg *A : Args) {
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001388 if (!A->getOption().matches(options::OPT_cuda_gpu_arch_EQ))
1389 continue;
1390 A->claim();
1391
1392 const auto &ArchStr = A->getValue();
1393 CudaArch Arch = StringToCudaArch(ArchStr);
1394 if (Arch == CudaArch::UNKNOWN)
1395 C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
1396 else if (GpuArchs.insert(Arch).second)
1397 GpuArchList.push_back(Arch);
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001398 }
1399
1400 // Default to sm_20 which is the lowest common denominator for supported GPUs.
1401 // sm_20 code should work correctly, if suboptimally, on all newer GPUs.
1402 if (GpuArchList.empty())
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001403 GpuArchList.push_back(CudaArch::SM_20);
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001404
1405 // Replicate inputs for each GPU architecture.
1406 Driver::InputList CudaDeviceInputs;
1407 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
1408 CudaDeviceInputs.push_back(std::make_pair(types::TY_CUDA_DEVICE, InputArg));
1409
1410 // Build actions for all device inputs.
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001411 assert(C.getSingleOffloadToolChain<Action::OFK_Cuda>() &&
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001412 "Missing toolchain for device-side compilation.");
1413 ActionList CudaDeviceActions;
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001414 C.getDriver().BuildActions(C, Args, CudaDeviceInputs, CudaDeviceActions);
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001415 assert(GpuArchList.size() == CudaDeviceActions.size() &&
1416 "Failed to create actions for all devices");
1417
1418 // Check whether any of device actions stopped before they could generate PTX.
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001419 bool PartialCompilation =
1420 llvm::any_of(CudaDeviceActions, [](const Action *a) {
1421 return a->getKind() != Action::AssembleJobClass;
1422 });
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001423
1424 // Figure out what to do with device actions -- pass them as inputs to the
1425 // host action or run each of them independently.
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001426 if (PartialCompilation || CompileDeviceOnly) {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001427 // In case of partial or device-only compilation results of device actions
1428 // are not consumed by the host action device actions have to be added to
1429 // top-level actions list with AtTopLevel=true and run independently.
1430
1431 // -o is ambiguous if we have more than one top-level action.
1432 if (Args.hasArg(options::OPT_o) &&
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001433 (!CompileDeviceOnly || GpuArchList.size() > 1)) {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001434 C.getDriver().Diag(
1435 clang::diag::err_drv_output_argument_with_multiple_files);
1436 return nullptr;
1437 }
1438
1439 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001440 Actions.push_back(C.MakeAction<CudaDeviceAction>(CudaDeviceActions[I],
1441 GpuArchList[I],
1442 /* AtTopLevel */ true));
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001443 // Kill host action in case of device-only compilation.
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001444 if (CompileDeviceOnly)
1445 return nullptr;
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001446 return HostAction;
1447 }
1448
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001449 // If we're not a partial or device-only compilation, we compile each arch to
1450 // ptx and assemble to cubin, then feed the cubin *and* the ptx into a device
1451 // "link" action, which uses fatbinary to combine these cubins into one
1452 // fatbin. The fatbin is then an input to the host compilation.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001453 ActionList DeviceActions;
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001454 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
1455 Action* AssembleAction = CudaDeviceActions[I];
1456 assert(AssembleAction->getType() == types::TY_Object);
1457 assert(AssembleAction->getInputs().size() == 1);
1458
1459 Action* BackendAction = AssembleAction->getInputs()[0];
1460 assert(BackendAction->getType() == types::TY_PP_Asm);
1461
1462 for (const auto& A : {AssembleAction, BackendAction}) {
1463 DeviceActions.push_back(C.MakeAction<CudaDeviceAction>(
1464 A, GpuArchList[I], /* AtTopLevel */ false));
1465 }
1466 }
1467 auto FatbinAction = C.MakeAction<CudaDeviceAction>(
1468 C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN),
1469 CudaArch::UNKNOWN,
1470 /* AtTopLevel = */ false);
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001471 // Return a new host action that incorporates original host action and all
1472 // device actions.
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001473 return C.MakeAction<CudaHostAction>(std::move(HostAction),
1474 ActionList({FatbinAction}));
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001475}
1476
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001477void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
1478 const InputList &Inputs, ActionList &Actions) const {
Chad Rosierbe69f602011-08-12 22:08:57 +00001479 llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
Joerg Sonnenberger9ade4ae2011-03-06 23:31:01 +00001480
Daniel Dunbar8b1604e2009-03-13 00:17:48 +00001481 if (!SuppressMissingInputWarning && Inputs.empty()) {
Daniel Dunbaraf61c712009-03-12 23:55:14 +00001482 Diag(clang::diag::err_drv_no_input_files);
1483 return;
1484 }
1485
Chad Rosier1fc1de42011-07-27 23:36:45 +00001486 Arg *FinalPhaseArg;
1487 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
Daniel Dunbaraf61c712009-03-12 23:55:14 +00001488
Rafael Espindola6db90882013-08-25 14:27:09 +00001489 if (FinalPhase == phases::Link && Args.hasArg(options::OPT_emit_llvm)) {
1490 Diag(clang::diag::err_drv_emit_llvm_link);
1491 }
1492
Daniel Dunbara8231832009-09-08 23:36:43 +00001493 // Reject -Z* at the top level, these options should never have been exposed
1494 // by gcc.
Daniel Dunbard7b88c22009-03-26 16:12:09 +00001495 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
Daniel Dunbar38dd3d52009-03-20 06:14:23 +00001496 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
Daniel Dunbaraf61c712009-03-12 23:55:14 +00001497
Hans Wennborg9c0ed912013-08-12 23:26:25 +00001498 // Diagnose misuse of /Fo.
1499 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
Hans Wennborg9c0ed912013-08-12 23:26:25 +00001500 StringRef V = A->getValue();
Stephen Hines176edba2014-12-01 14:53:08 -08001501 if (Inputs.size() > 1 && !V.empty() &&
1502 !llvm::sys::path::is_separator(V.back())) {
Hans Wennborg9c0ed912013-08-12 23:26:25 +00001503 // Check whether /Fo tries to name an output file for multiple inputs.
Hans Wennborgb405c952013-10-18 22:49:04 +00001504 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001505 << A->getSpelling() << V;
Hans Wennborg9c0ed912013-08-12 23:26:25 +00001506 Args.eraseArg(options::OPT__SLASH_Fo);
1507 }
1508 }
1509
Hans Wennborgb405c952013-10-18 22:49:04 +00001510 // Diagnose misuse of /Fa.
1511 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
1512 StringRef V = A->getValue();
Stephen Hines176edba2014-12-01 14:53:08 -08001513 if (Inputs.size() > 1 && !V.empty() &&
1514 !llvm::sys::path::is_separator(V.back())) {
Hans Wennborgb405c952013-10-18 22:49:04 +00001515 // Check whether /Fa tries to name an asm file for multiple inputs.
1516 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001517 << A->getSpelling() << V;
Hans Wennborgb405c952013-10-18 22:49:04 +00001518 Args.eraseArg(options::OPT__SLASH_Fa);
1519 }
1520 }
1521
Stephen Hines176edba2014-12-01 14:53:08 -08001522 // Diagnose misuse of /o.
1523 if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
Hans Wennborg9c0ed912013-08-12 23:26:25 +00001524 if (A->getValue()[0] == '\0') {
1525 // It has to have a value.
1526 Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
Stephen Hines176edba2014-12-01 14:53:08 -08001527 Args.eraseArg(options::OPT__SLASH_o);
Hans Wennborg9c0ed912013-08-12 23:26:25 +00001528 }
1529 }
1530
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001531 // Diagnose unsupported forms of /Yc /Yu. Ignore /Yc/Yu for now if:
1532 // * no filename after it
1533 // * both /Yc and /Yu passed but with different filenames
1534 // * corresponding file not also passed as /FI
1535 Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
1536 Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
1537 if (YcArg && YcArg->getValue()[0] == '\0') {
1538 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YcArg->getSpelling();
1539 Args.eraseArg(options::OPT__SLASH_Yc);
1540 YcArg = nullptr;
1541 }
1542 if (YuArg && YuArg->getValue()[0] == '\0') {
1543 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YuArg->getSpelling();
1544 Args.eraseArg(options::OPT__SLASH_Yu);
1545 YuArg = nullptr;
1546 }
1547 if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
1548 Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
1549 Args.eraseArg(options::OPT__SLASH_Yc);
1550 Args.eraseArg(options::OPT__SLASH_Yu);
1551 YcArg = YuArg = nullptr;
1552 }
1553 if (YcArg || YuArg) {
1554 StringRef Val = YcArg ? YcArg->getValue() : YuArg->getValue();
1555 bool FoundMatchingInclude = false;
1556 for (const Arg *Inc : Args.filtered(options::OPT_include)) {
1557 // FIXME: Do case-insensitive matching and consider / and \ as equal.
1558 if (Inc->getValue() == Val)
1559 FoundMatchingInclude = true;
1560 }
1561 if (!FoundMatchingInclude) {
1562 Diag(clang::diag::warn_drv_ycyu_no_fi_arg_clang_cl)
1563 << (YcArg ? YcArg : YuArg)->getSpelling();
1564 Args.eraseArg(options::OPT__SLASH_Yc);
1565 Args.eraseArg(options::OPT__SLASH_Yu);
1566 YcArg = YuArg = nullptr;
1567 }
1568 }
1569 if (YcArg && Inputs.size() > 1) {
1570 Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
1571 Args.eraseArg(options::OPT__SLASH_Yc);
1572 YcArg = nullptr;
1573 }
1574 if (Args.hasArg(options::OPT__SLASH_Y_)) {
1575 // /Y- disables all pch handling. Rather than check for it everywhere,
1576 // just remove clang-cl pch-related flags here.
1577 Args.eraseArg(options::OPT__SLASH_Fp);
1578 Args.eraseArg(options::OPT__SLASH_Yc);
1579 Args.eraseArg(options::OPT__SLASH_Yu);
1580 YcArg = YuArg = nullptr;
1581 }
1582
Daniel Dunbarad2a9af2009-03-13 11:38:42 +00001583 // Construct the actions to perform.
1584 ActionList LinkerInputs;
Stephen Hines651f13c2014-04-23 16:59:28 -07001585
Matthew Curtisb9aa6732013-03-07 12:32:26 +00001586 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL;
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001587 for (auto &I : Inputs) {
1588 types::ID InputType = I.first;
1589 const Arg *InputArg = I.second;
Daniel Dunbarad2a9af2009-03-13 11:38:42 +00001590
Matthew Curtisb9aa6732013-03-07 12:32:26 +00001591 PL.clear();
1592 types::getCompilationPhases(InputType, PL);
Daniel Dunbarad2a9af2009-03-13 11:38:42 +00001593
Daniel Dunbara8231832009-09-08 23:36:43 +00001594 // If the first step comes after the final phase we are doing as part of
1595 // this compilation, warn the user about it.
Matthew Curtisb9aa6732013-03-07 12:32:26 +00001596 phases::ID InitialPhase = PL[0];
Daniel Dunbarad2a9af2009-03-13 11:38:42 +00001597 if (InitialPhase > FinalPhase) {
Daniel Dunbar05494a72009-03-19 07:57:08 +00001598 // Claim here to avoid the more general unused warning.
1599 InputArg->claim();
Daniel Dunbar634b2452009-09-17 04:13:26 +00001600
Daniel Dunbar32c8cb62011-04-20 15:44:48 +00001601 // Suppress all unused style warnings with -Qunused-arguments
1602 if (Args.hasArg(options::OPT_Qunused_arguments))
1603 continue;
1604
Richard Smith04c3a252012-08-06 04:09:06 +00001605 // Special case when final phase determined by binary name, rather than
1606 // by a command-line argument with a corresponding Arg.
Hans Wennborg76b86c22013-07-18 20:29:38 +00001607 if (CCCIsCPP())
Richard Smith04c3a252012-08-06 04:09:06 +00001608 Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001609 << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
Daniel Dunbar634b2452009-09-17 04:13:26 +00001610 // Special case '-E' warning on a previously preprocessed file to make
1611 // more sense.
Richard Smith04c3a252012-08-06 04:09:06 +00001612 else if (InitialPhase == phases::Compile &&
1613 FinalPhase == phases::Preprocess &&
1614 getPreprocessedType(InputType) == types::TY_INVALID)
Daniel Dunbar634b2452009-09-17 04:13:26 +00001615 Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001616 << InputArg->getAsString(Args) << !!FinalPhaseArg
1617 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
Daniel Dunbar634b2452009-09-17 04:13:26 +00001618 else
1619 Diag(clang::diag::warn_drv_input_file_unused)
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001620 << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
1621 << !!FinalPhaseArg
1622 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
Daniel Dunbarad2a9af2009-03-13 11:38:42 +00001623 continue;
1624 }
Daniel Dunbara8231832009-09-08 23:36:43 +00001625
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001626 if (YcArg) {
1627 // Add a separate precompile phase for the compile phase.
1628 if (FinalPhase >= phases::Compile) {
1629 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PCHPL;
1630 types::getCompilationPhases(types::TY_CXXHeader, PCHPL);
1631 Arg *PchInputArg = MakeInputArg(Args, Opts, YcArg->getValue());
1632
1633 // Build the pipeline for the pch file.
1634 Action *ClangClPch = C.MakeAction<InputAction>(*PchInputArg, InputType);
1635 for (phases::ID Phase : PCHPL)
1636 ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
1637 assert(ClangClPch);
1638 Actions.push_back(ClangClPch);
1639 // The driver currently exits after the first failed command. This
1640 // relies on that behavior, to make sure if the pch generation fails,
1641 // the main compilation won't run.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001642 }
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001643 }
1644
1645 phases::ID CudaInjectionPhase =
1646 (phases::Compile < FinalPhase &&
1647 llvm::find(PL, phases::Compile) != PL.end())
1648 ? phases::Compile
1649 : FinalPhase;
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001650
Daniel Dunbarad2a9af2009-03-13 11:38:42 +00001651 // Build the pipeline for this file.
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001652 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001653 for (SmallVectorImpl<phases::ID>::iterator i = PL.begin(), e = PL.end();
1654 i != e; ++i) {
Matthew Curtisb9aa6732013-03-07 12:32:26 +00001655 phases::ID Phase = *i;
Daniel Dunbarad2a9af2009-03-13 11:38:42 +00001656
1657 // We are done if this step is past what the user requested.
1658 if (Phase > FinalPhase)
1659 break;
1660
1661 // Queue linker inputs.
1662 if (Phase == phases::Link) {
Matthew Curtisb9aa6732013-03-07 12:32:26 +00001663 assert((i + 1) == e && "linking must be final compilation step.");
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001664 LinkerInputs.push_back(Current);
1665 Current = nullptr;
Daniel Dunbarad2a9af2009-03-13 11:38:42 +00001666 break;
1667 }
1668
Daniel Dunbara8231832009-09-08 23:36:43 +00001669 // Some types skip the assembler phase (e.g., llvm-bc), but we can't
1670 // encode this in the steps because the intermediate type depends on
1671 // arguments. Just special case here.
Daniel Dunbar337a6272009-03-24 20:17:30 +00001672 if (Phase == phases::Assemble && Current->getType() != types::TY_PP_Asm)
1673 continue;
1674
Daniel Dunbarad2a9af2009-03-13 11:38:42 +00001675 // Otherwise construct the appropriate action.
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001676 Current = ConstructPhaseAction(C, Args, Phase, Current);
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001677
1678 if (InputType == types::TY_CUDA && Phase == CudaInjectionPhase) {
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001679 Current = buildCudaActions(C, Args, InputArg, Current, Actions);
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001680 if (!Current)
1681 break;
1682 }
1683
Daniel Dunbarad2a9af2009-03-13 11:38:42 +00001684 if (Current->getType() == types::TY_Nothing)
1685 break;
1686 }
1687
1688 // If we ended with something, add to the output list.
1689 if (Current)
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001690 Actions.push_back(Current);
Daniel Dunbar53ec5522009-03-12 07:58:46 +00001691 }
Daniel Dunbarad2a9af2009-03-13 11:38:42 +00001692
1693 // Add a link action if necessary.
1694 if (!LinkerInputs.empty())
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001695 Actions.push_back(
1696 C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image));
Daniel Dunbarf3601382009-12-22 23:19:32 +00001697
1698 // If we are linking, claim any options which are obviously only used for
1699 // compilation.
Hans Wennborgd8df3f72013-09-17 00:03:41 +00001700 if (FinalPhase == phases::Link && PL.size() == 1) {
Daniel Dunbarf3601382009-12-22 23:19:32 +00001701 Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
Hans Wennborgd8df3f72013-09-17 00:03:41 +00001702 Args.ClaimAllArgs(options::OPT_cl_compile_Group);
1703 }
1704
1705 // Claim ignored clang-cl options.
1706 Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001707
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001708 // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed
1709 // to non-CUDA compilations and should not trigger warnings there.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001710 Args.ClaimAllArgs(options::OPT_cuda_host_only);
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001711 Args.ClaimAllArgs(options::OPT_cuda_compile_host_device);
Daniel Dunbarad2a9af2009-03-13 11:38:42 +00001712}
1713
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001714Action *Driver::ConstructPhaseAction(Compilation &C, const ArgList &Args,
1715 phases::ID Phase, Action *Input) const {
Daniel Dunbar8f25c792009-03-18 01:38:48 +00001716 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
Daniel Dunbarad2a9af2009-03-13 11:38:42 +00001717 // Build the appropriate action.
1718 switch (Phase) {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001719 case phases::Link:
1720 llvm_unreachable("link action invalid here.");
Daniel Dunbarad2a9af2009-03-13 11:38:42 +00001721 case phases::Preprocess: {
Daniel Dunbarcd8e4c42009-03-30 06:36:42 +00001722 types::ID OutputTy;
1723 // -{M, MM} alter the output type.
Daniel Dunbar9eb93b02010-12-08 21:33:40 +00001724 if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
Daniel Dunbarcd8e4c42009-03-30 06:36:42 +00001725 OutputTy = types::TY_Dependencies;
1726 } else {
David Blaikiee75d9cf2012-06-29 22:03:56 +00001727 OutputTy = Input->getType();
1728 if (!Args.hasFlag(options::OPT_frewrite_includes,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001729 options::OPT_fno_rewrite_includes, false) &&
1730 !CCGenDiagnostics)
David Blaikiee75d9cf2012-06-29 22:03:56 +00001731 OutputTy = types::getPreprocessedType(OutputTy);
Daniel Dunbarcd8e4c42009-03-30 06:36:42 +00001732 assert(OutputTy != types::TY_INVALID &&
1733 "Cannot preprocess this input type!");
1734 }
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001735 return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
Daniel Dunbarad2a9af2009-03-13 11:38:42 +00001736 }
Aaron Ballman761322b2012-07-31 01:21:00 +00001737 case phases::Precompile: {
1738 types::ID OutputTy = types::TY_PCH;
1739 if (Args.hasArg(options::OPT_fsyntax_only)) {
1740 // Syntax checks should not emit a PCH file
1741 OutputTy = types::TY_Nothing;
1742 }
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001743 return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
Aaron Ballman761322b2012-07-31 01:21:00 +00001744 }
Daniel Dunbarad2a9af2009-03-13 11:38:42 +00001745 case phases::Compile: {
Stephen Hines176edba2014-12-01 14:53:08 -08001746 if (Args.hasArg(options::OPT_fsyntax_only))
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001747 return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
Stephen Hines176edba2014-12-01 14:53:08 -08001748 if (Args.hasArg(options::OPT_rewrite_objc))
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001749 return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
Stephen Hines176edba2014-12-01 14:53:08 -08001750 if (Args.hasArg(options::OPT_rewrite_legacy_objc))
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001751 return C.MakeAction<CompileJobAction>(Input,
1752 types::TY_RewrittenLegacyObjC);
Stephen Hines176edba2014-12-01 14:53:08 -08001753 if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto))
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001754 return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
Stephen Hines176edba2014-12-01 14:53:08 -08001755 if (Args.hasArg(options::OPT__migrate))
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001756 return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
Stephen Hines176edba2014-12-01 14:53:08 -08001757 if (Args.hasArg(options::OPT_emit_ast))
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001758 return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
Stephen Hines176edba2014-12-01 14:53:08 -08001759 if (Args.hasArg(options::OPT_module_file_info))
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001760 return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
Stephen Hines176edba2014-12-01 14:53:08 -08001761 if (Args.hasArg(options::OPT_verify_pch))
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001762 return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
1763 return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001764 }
1765 case phases::Backend: {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001766 if (isUsingLTO()) {
Daniel Dunbara8231832009-09-08 23:36:43 +00001767 types::ID Output =
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001768 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001769 return C.MakeAction<BackendJobAction>(Input, Output);
Stephen Hines176edba2014-12-01 14:53:08 -08001770 }
1771 if (Args.hasArg(options::OPT_emit_llvm)) {
Shuxin Yang223ccb42013-08-23 21:34:57 +00001772 types::ID Output =
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001773 Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001774 return C.MakeAction<BackendJobAction>(Input, Output);
Daniel Dunbarad2a9af2009-03-13 11:38:42 +00001775 }
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001776 return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
Daniel Dunbarad2a9af2009-03-13 11:38:42 +00001777 }
1778 case phases::Assemble:
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001779 return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
Daniel Dunbarad2a9af2009-03-13 11:38:42 +00001780 }
1781
David Blaikieb219cfc2011-09-23 05:06:16 +00001782 llvm_unreachable("invalid phase in ConstructPhaseAction");
Daniel Dunbar53ec5522009-03-12 07:58:46 +00001783}
1784
Daniel Dunbar21549232009-03-18 02:55:38 +00001785void Driver::BuildJobs(Compilation &C) const {
Daniel Dunbar8f25c792009-03-18 01:38:48 +00001786 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
Daniel Dunbarf353c8c2009-03-16 06:56:51 +00001787
1788 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
1789
Daniel Dunbara8231832009-09-08 23:36:43 +00001790 // It is an error to provide a -o option if we are making multiple output
1791 // files.
Daniel Dunbarf353c8c2009-03-16 06:56:51 +00001792 if (FinalOutput) {
1793 unsigned NumOutputs = 0;
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001794 for (const Action *A : C.getActions())
1795 if (A->getType() != types::TY_Nothing)
Daniel Dunbarf353c8c2009-03-16 06:56:51 +00001796 ++NumOutputs;
Daniel Dunbara8231832009-09-08 23:36:43 +00001797
Daniel Dunbarf353c8c2009-03-16 06:56:51 +00001798 if (NumOutputs > 1) {
1799 Diag(clang::diag::err_drv_output_argument_with_multiple_files);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001800 FinalOutput = nullptr;
Daniel Dunbarf353c8c2009-03-16 06:56:51 +00001801 }
1802 }
1803
Chad Rosier1c187592013-04-30 22:01:21 +00001804 // Collect the list of architectures.
1805 llvm::StringSet<> ArchNames;
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001806 if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO())
1807 for (const Arg *A : C.getArgs())
Chad Rosier1c187592013-04-30 22:01:21 +00001808 if (A->getOption().matches(options::OPT_arch))
1809 ArchNames.insert(A->getValue());
Chad Rosier1c187592013-04-30 22:01:21 +00001810
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001811 // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
1812 std::map<std::pair<const Action *, std::string>, InputInfo> CachedResults;
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001813 for (Action *A : C.getActions()) {
Daniel Dunbara8231832009-09-08 23:36:43 +00001814 // If we are linking an image for multiple archs then the linker wants
1815 // -arch_multiple and -final_output <final image name>. Unfortunately, this
1816 // doesn't fit in cleanly because we have to pass this information down.
Daniel Dunbarf353c8c2009-03-16 06:56:51 +00001817 //
Daniel Dunbara8231832009-09-08 23:36:43 +00001818 // FIXME: This is a hack; find a cleaner way to integrate this into the
1819 // process.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001820 const char *LinkingOutput = nullptr;
Daniel Dunbard7b88c22009-03-26 16:12:09 +00001821 if (isa<LipoJobAction>(A)) {
Daniel Dunbarf353c8c2009-03-16 06:56:51 +00001822 if (FinalOutput)
Richard Smith1d489cf2012-11-01 04:30:05 +00001823 LinkingOutput = FinalOutput->getValue();
Daniel Dunbarf353c8c2009-03-16 06:56:51 +00001824 else
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001825 LinkingOutput = getDefaultImageName();
Daniel Dunbarf353c8c2009-03-16 06:56:51 +00001826 }
1827
Daniel Dunbara8231832009-09-08 23:36:43 +00001828 BuildJobsForAction(C, A, &C.getDefaultToolChain(),
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001829 /*BoundArch*/ nullptr,
Daniel Dunbarf353c8c2009-03-16 06:56:51 +00001830 /*AtTopLevel*/ true,
Chad Rosier1c187592013-04-30 22:01:21 +00001831 /*MultipleArchs*/ ArchNames.size() > 1,
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001832 /*LinkingOutput*/ LinkingOutput, CachedResults);
Daniel Dunbarf353c8c2009-03-16 06:56:51 +00001833 }
Daniel Dunbar586dc232009-03-16 06:42:30 +00001834
Daniel Dunbara8231832009-09-08 23:36:43 +00001835 // If the user passed -Qunused-arguments or there were errors, don't warn
1836 // about any unused arguments.
Argyrios Kyrtzidisbe3aab62010-11-18 21:47:07 +00001837 if (Diags.hasErrorOccurred() ||
Daniel Dunbar1e23f5f2009-04-07 19:04:18 +00001838 C.getArgs().hasArg(options::OPT_Qunused_arguments))
Daniel Dunbaraf2e4ba2009-03-18 18:03:46 +00001839 return;
1840
Daniel Dunbara2094e72009-03-29 22:24:54 +00001841 // Claim -### here.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001842 (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
Daniel Dunbara8231832009-09-08 23:36:43 +00001843
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001844 // Claim --driver-mode, --rsp-quoting, it was handled earlier.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001845 (void)C.getArgs().hasArg(options::OPT_driver_mode);
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001846 (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
Hans Wennborg76b86c22013-07-18 20:29:38 +00001847
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001848 for (Arg *A : C.getArgs()) {
Daniel Dunbar586dc232009-03-16 06:42:30 +00001849 // FIXME: It would be nice to be able to send the argument to the
David Blaikied6471f72011-09-25 23:23:43 +00001850 // DiagnosticsEngine, so that extra values, position, and so on could be
1851 // printed.
Daniel Dunbar4f53b292009-04-04 00:52:26 +00001852 if (!A->isClaimed()) {
Michael J. Spencer91e06da2012-10-19 22:37:06 +00001853 if (A->getOption().hasFlag(options::NoArgumentUnused))
Daniel Dunbar1e23f5f2009-04-07 19:04:18 +00001854 continue;
1855
Daniel Dunbara8231832009-09-08 23:36:43 +00001856 // Suppress the warning automatically if this is just a flag, and it is an
1857 // instance of an argument we already claimed.
Daniel Dunbar4f53b292009-04-04 00:52:26 +00001858 const Option &Opt = A->getOption();
Michael J. Spencer43275572012-08-20 21:41:17 +00001859 if (Opt.getKind() == Option::FlagClass) {
Daniel Dunbar4f53b292009-04-04 00:52:26 +00001860 bool DuplicateClaimed = false;
1861
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -07001862 for (const Arg *AA : C.getArgs().filtered(&Opt)) {
1863 if (AA->isClaimed()) {
Daniel Dunbar4f53b292009-04-04 00:52:26 +00001864 DuplicateClaimed = true;
1865 break;
1866 }
1867 }
1868
1869 if (DuplicateClaimed)
1870 continue;
1871 }
1872
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001873 // In clang-cl, don't mention unknown arguments here since they have
1874 // already been warned about.
1875 if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN))
1876 Diag(clang::diag::warn_drv_unused_argument)
1877 << A->getAsString(C.getArgs());
Daniel Dunbar4f53b292009-04-04 00:52:26 +00001878 }
Daniel Dunbar586dc232009-03-16 06:42:30 +00001879 }
Daniel Dunbar57b704d2009-03-13 22:12:33 +00001880}
1881
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001882// Returns a Tool for a given JobAction. In case the action and its
1883// predecessors can be combined, updates Inputs with the inputs of the
1884// first combined action. If one of the collapsed actions is a
1885// CudaHostAction, updates CollapsedCHA with the pointer to it so the
1886// caller can deal with extra handling such action requires.
1887static const Tool *selectToolForJob(Compilation &C, bool SaveTemps,
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001888 bool EmbedBitcode, const ToolChain *TC,
1889 const JobAction *JA,
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001890 const ActionList *&Inputs,
1891 const CudaHostAction *&CollapsedCHA) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001892 const Tool *ToolForJob = nullptr;
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001893 CollapsedCHA = nullptr;
Daniel Dunbar8767cbc2010-02-03 03:07:56 +00001894
1895 // See if we should look for a compiler with an integrated assembler. We match
1896 // bottom up, so what we are actually looking for is an assembler job with a
1897 // compiler input.
Daniel Dunbareb840bd2010-05-14 02:03:00 +00001898
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001899 if (TC->useIntegratedAs() && !SaveTemps &&
Stephen Hines651f13c2014-04-23 16:59:28 -07001900 !C.getArgs().hasArg(options::OPT_via_file_asm) &&
Hans Wennborg82a29112013-10-17 16:16:23 +00001901 !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
1902 !C.getArgs().hasArg(options::OPT__SLASH_Fa) &&
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001903 isa<AssembleJobAction>(JA) && Inputs->size() == 1 &&
1904 isa<BackendJobAction>(*Inputs->begin())) {
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001905 // A BackendJob is always preceded by a CompileJob, and without -save-temps
1906 // or -fembed-bitcode, they will always get combined together, so instead of
1907 // checking the backend tool, check if the tool for the CompileJob has an
1908 // integrated assembler. For -fembed-bitcode, CompileJob is still used to
1909 // look up tools for BackendJob, but they need to match before we can split
1910 // them.
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001911 const ActionList *BackendInputs = &(*Inputs)[0]->getInputs();
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001912 // Compile job may be wrapped in CudaHostAction, extract it if
1913 // that's the case and update CollapsedCHA if we combine phases.
1914 CudaHostAction *CHA = dyn_cast<CudaHostAction>(*BackendInputs->begin());
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001915 JobAction *CompileJA = cast<CompileJobAction>(
1916 CHA ? *CHA->input_begin() : *BackendInputs->begin());
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001917 assert(CompileJA && "Backend job is not preceeded by compile job.");
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001918 const Tool *Compiler = TC->SelectTool(*CompileJA);
Rafael Espindola29511872013-03-24 15:06:53 +00001919 if (!Compiler)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001920 return nullptr;
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001921 // When using -fembed-bitcode, it is required to have the same tool (clang)
1922 // for both CompilerJA and BackendJA. Otherwise, combine two stages.
1923 if (EmbedBitcode) {
1924 JobAction *InputJA = cast<JobAction>(*Inputs->begin());
1925 const Tool *BackendTool = TC->SelectTool(*InputJA);
1926 if (BackendTool == Compiler)
1927 CompileJA = InputJA;
1928 }
Rafael Espindola29511872013-03-24 15:06:53 +00001929 if (Compiler->hasIntegratedAssembler()) {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001930 Inputs = &CompileJA->getInputs();
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001931 ToolForJob = Compiler;
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001932 CollapsedCHA = CHA;
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001933 }
1934 }
1935
1936 // A backend job should always be combined with the preceding compile job
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001937 // unless OPT_save_temps or OPT_fembed_bitcode is enabled and the compiler is
1938 // capable of emitting LLVM IR as an intermediate output.
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001939 if (isa<BackendJobAction>(JA)) {
1940 // Check if the compiler supports emitting LLVM IR.
1941 assert(Inputs->size() == 1);
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001942 // Compile job may be wrapped in CudaHostAction, extract it if
1943 // that's the case and update CollapsedCHA if we combine phases.
1944 CudaHostAction *CHA = dyn_cast<CudaHostAction>(*Inputs->begin());
1945 JobAction *CompileJA =
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001946 cast<CompileJobAction>(CHA ? *CHA->input_begin() : *Inputs->begin());
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001947 assert(CompileJA && "Backend job is not preceeded by compile job.");
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001948 const Tool *Compiler = TC->SelectTool(*CompileJA);
1949 if (!Compiler)
1950 return nullptr;
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001951 if (!Compiler->canEmitIR() ||
1952 (!SaveTemps && !EmbedBitcode)) {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001953 Inputs = &CompileJA->getInputs();
Rafael Espindola29511872013-03-24 15:06:53 +00001954 ToolForJob = Compiler;
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001955 CollapsedCHA = CHA;
Daniel Dunbar8767cbc2010-02-03 03:07:56 +00001956 }
1957 }
1958
1959 // Otherwise use the tool for the current job.
1960 if (!ToolForJob)
Rafael Espindola29511872013-03-24 15:06:53 +00001961 ToolForJob = TC->SelectTool(*JA);
Daniel Dunbar8767cbc2010-02-03 03:07:56 +00001962
1963 // See if we should use an integrated preprocessor. We do so when we have
1964 // exactly one input, since this is the only use case we care about
1965 // (irrelevant since we don't support combine yet).
1966 if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin()) &&
1967 !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001968 !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
Fariborz Jahaniana5ee0892012-09-28 19:05:17 +00001969 !C.getArgs().hasArg(options::OPT_rewrite_objc) &&
Daniel Dunbar8767cbc2010-02-03 03:07:56 +00001970 ToolForJob->hasIntegratedCPP())
1971 Inputs = &(*Inputs)[0]->getInputs();
1972
Rafael Espindola29511872013-03-24 15:06:53 +00001973 return ToolForJob;
Daniel Dunbar8767cbc2010-02-03 03:07:56 +00001974}
1975
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001976InputInfo Driver::BuildJobsForAction(
1977 Compilation &C, const Action *A, const ToolChain *TC, const char *BoundArch,
1978 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
1979 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults)
1980 const {
1981 // The bound arch is not necessarily represented in the toolchain's triple --
1982 // for example, armv7 and armv7s both map to the same triple -- so we need
1983 // both in our map.
1984 std::string TriplePlusArch = TC->getTriple().normalize();
1985 if (BoundArch) {
1986 TriplePlusArch += "-";
1987 TriplePlusArch += BoundArch;
1988 }
1989 std::pair<const Action *, std::string> ActionTC = {A, TriplePlusArch};
1990 auto CachedResult = CachedResults.find(ActionTC);
1991 if (CachedResult != CachedResults.end()) {
1992 return CachedResult->second;
1993 }
1994 InputInfo Result =
1995 BuildJobsForActionNoCache(C, A, TC, BoundArch, AtTopLevel, MultipleArchs,
1996 LinkingOutput, CachedResults);
1997 CachedResults[ActionTC] = Result;
1998 return Result;
1999}
2000
2001InputInfo Driver::BuildJobsForActionNoCache(
2002 Compilation &C, const Action *A, const ToolChain *TC, const char *BoundArch,
2003 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
2004 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults)
2005 const {
Daniel Dunbara8231832009-09-08 23:36:43 +00002006 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
Daniel Dunbar60ccc762009-03-18 23:18:19 +00002007
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002008 InputInfoList CudaDeviceInputInfos;
2009 if (const CudaHostAction *CHA = dyn_cast<CudaHostAction>(A)) {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002010 // Append outputs of device jobs to the input list.
2011 for (const Action *DA : CHA->getDeviceActions()) {
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002012 CudaDeviceInputInfos.push_back(BuildJobsForAction(
2013 C, DA, TC, nullptr, AtTopLevel,
2014 /*MultipleArchs*/ false, LinkingOutput, CachedResults));
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002015 }
2016 // Override current action with a real host compile action and continue
2017 // processing it.
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002018 A = *CHA->input_begin();
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002019 }
2020
Daniel Dunbarf353c8c2009-03-16 06:56:51 +00002021 if (const InputAction *IA = dyn_cast<InputAction>(A)) {
Daniel Dunbara8231832009-09-08 23:36:43 +00002022 // FIXME: It would be nice to not claim this here; maybe the old scheme of
2023 // just using Args was better?
Daniel Dunbar115a7922009-03-19 07:29:38 +00002024 const Arg &Input = IA->getInputArg();
2025 Input.claim();
Daniel Dunbar532c1ec2010-06-09 22:31:08 +00002026 if (Input.getOption().matches(options::OPT_INPUT)) {
Richard Smith1d489cf2012-11-01 04:30:05 +00002027 const char *Name = Input.getValue();
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002028 return InputInfo(A, Name, /* BaseInput = */ Name);
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002029 }
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002030 return InputInfo(A, &Input, /* BaseInput = */ "");
Daniel Dunbarf353c8c2009-03-16 06:56:51 +00002031 }
2032
2033 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
Chad Rosier4e47dee2012-04-27 16:50:38 +00002034 const ToolChain *TC;
Chad Rosier1dcfe342012-04-27 16:48:16 +00002035 const char *ArchName = BAA->getArchName();
Daniel Dunbard7502d02009-09-08 23:37:19 +00002036
Chad Rosier1dcfe342012-04-27 16:48:16 +00002037 if (ArchName)
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002038 TC = &getToolChain(C.getArgs(),
2039 computeTargetTriple(*this, DefaultTargetTriple,
2040 C.getArgs(), ArchName));
Chad Rosier4e47dee2012-04-27 16:50:38 +00002041 else
2042 TC = &C.getDefaultToolChain();
Daniel Dunbard7502d02009-09-08 23:37:19 +00002043
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002044 return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
2045 MultipleArchs, LinkingOutput, CachedResults);
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002046 }
2047
2048 if (const CudaDeviceAction *CDA = dyn_cast<CudaDeviceAction>(A)) {
2049 // Initial processing of CudaDeviceAction carries host params.
2050 // Call BuildJobsForAction() again, now with correct device parameters.
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002051 InputInfo II = BuildJobsForAction(
2052 C, *CDA->input_begin(), C.getSingleOffloadToolChain<Action::OFK_Cuda>(),
2053 CudaArchToString(CDA->getGpuArch()), CDA->isAtTopLevel(),
2054 /*MultipleArchs=*/true, LinkingOutput, CachedResults);
2055 // Currently II's Action is *CDA->input_begin(). Set it to CDA instead, so
2056 // that one can retrieve II's GPU arch.
2057 II.setAction(A);
2058 return II;
Daniel Dunbarf353c8c2009-03-16 06:56:51 +00002059 }
2060
Daniel Dunbarf353c8c2009-03-16 06:56:51 +00002061 const ActionList *Inputs = &A->getInputs();
Daniel Dunbar8767cbc2010-02-03 03:07:56 +00002062
2063 const JobAction *JA = cast<JobAction>(A);
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002064 const CudaHostAction *CollapsedCHA = nullptr;
2065 const Tool *T =
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002066 selectToolForJob(C, isSaveTempsEnabled(), embedBitcodeEnabled(), TC, JA,
2067 Inputs, CollapsedCHA);
Rafael Espindola29511872013-03-24 15:06:53 +00002068 if (!T)
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002069 return InputInfo();
Daniel Dunbarf353c8c2009-03-16 06:56:51 +00002070
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002071 // If we've collapsed action list that contained CudaHostAction we
2072 // need to build jobs for device-side inputs it may have held.
2073 if (CollapsedCHA) {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002074 for (const Action *DA : CollapsedCHA->getDeviceActions()) {
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002075 CudaDeviceInputInfos.push_back(BuildJobsForAction(
2076 C, DA, TC, "", AtTopLevel,
2077 /*MultipleArchs*/ false, LinkingOutput, CachedResults));
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002078 }
2079 }
2080
Daniel Dunbarf353c8c2009-03-16 06:56:51 +00002081 // Only use pipes when there is exactly one input.
Daniel Dunbar47ac7d22009-03-18 06:00:36 +00002082 InputInfoList InputInfos;
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002083 for (const Action *Input : *Inputs) {
Eric Christopher0798b692013-02-18 00:38:25 +00002084 // Treat dsymutil and verify sub-jobs as being at the top-level too, they
2085 // shouldn't get temporary output names.
Daniel Dunbarbe1cc3e2010-06-04 18:28:41 +00002086 // FIXME: Clean this up.
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002087 bool SubJobAtTopLevel =
2088 AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
2089 InputInfos.push_back(BuildJobsForAction(C, Input, TC, BoundArch,
2090 SubJobAtTopLevel, MultipleArchs,
2091 LinkingOutput, CachedResults));
Daniel Dunbarf353c8c2009-03-16 06:56:51 +00002092 }
2093
Daniel Dunbarf353c8c2009-03-16 06:56:51 +00002094 // Always use the first input as the base input.
2095 const char *BaseInput = InputInfos[0].getBaseInput();
Daniel Dunbar441d0602009-03-17 17:53:55 +00002096
Daniel Dunbarbe1cc3e2010-06-04 18:28:41 +00002097 // ... except dsymutil actions, which use their actual input as the base
2098 // input.
2099 if (JA->getType() == types::TY_dSYM)
2100 BaseInput = InputInfos[0].getFilename();
2101
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002102 // Append outputs of cuda device jobs to the input list
2103 if (CudaDeviceInputInfos.size())
2104 InputInfos.append(CudaDeviceInputInfos.begin(), CudaDeviceInputInfos.end());
2105
Daniel Dunbar9b18cca2010-08-02 02:38:15 +00002106 // Determine the place to write output to, if any.
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002107 InputInfo Result;
Eric Christopherc706c8e2013-02-05 07:29:57 +00002108 if (JA->getType() == types::TY_Nothing)
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002109 Result = InputInfo(A, BaseInput);
Eric Christopherc706c8e2013-02-05 07:29:57 +00002110 else
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002111 Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
2112 AtTopLevel, MultipleArchs),
2113 BaseInput);
Daniel Dunbar441d0602009-03-17 17:53:55 +00002114
Chad Rosier2b819102011-08-02 17:58:04 +00002115 if (CCCPrintBindings && !CCGenDiagnostics) {
Rafael Espindola29511872013-03-24 15:06:53 +00002116 llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
2117 << " - \"" << T->getName() << "\", inputs: [";
Daniel Dunbar5c3c1d72009-03-17 22:47:06 +00002118 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
2119 llvm::errs() << InputInfos[i].getAsString();
2120 if (i + 1 != e)
2121 llvm::errs() << ", ";
2122 }
2123 llvm::errs() << "], output: " << Result.getAsString() << "\n";
2124 } else {
Rafael Espindola29511872013-03-24 15:06:53 +00002125 T->ConstructJob(C, *JA, Result, InputInfos,
2126 C.getArgsForToolChain(TC, BoundArch), LinkingOutput);
Daniel Dunbar5c3c1d72009-03-17 22:47:06 +00002127 }
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002128 return Result;
Daniel Dunbarf353c8c2009-03-16 06:56:51 +00002129}
2130
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002131const char *Driver::getDefaultImageName() const {
2132 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
2133 return Target.isOSWindows() ? "a.exe" : "a.out";
2134}
2135
Hans Wennborg82a29112013-10-17 16:16:23 +00002136/// \brief Create output filename based on ArgValue, which could either be a
2137/// full filename, filename without extension, or a directory. If ArgValue
2138/// does not provide a filename, then use BaseName, and use the extension
2139/// suitable for FileType.
Hans Wennborgc65c72d2013-08-12 21:56:42 +00002140static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002141 StringRef BaseName,
2142 types::ID FileType) {
Hans Wennborgc65c72d2013-08-12 21:56:42 +00002143 SmallString<128> Filename = ArgValue;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002144
Hans Wennborg6d0a8d52013-09-10 20:18:04 +00002145 if (ArgValue.empty()) {
2146 // If the argument is empty, output to BaseName in the current dir.
2147 Filename = BaseName;
2148 } else if (llvm::sys::path::is_separator(Filename.back())) {
Hans Wennborgc65c72d2013-08-12 21:56:42 +00002149 // If the argument is a directory, output to BaseName in that dir.
2150 llvm::sys::path::append(Filename, BaseName);
2151 }
2152
2153 if (!llvm::sys::path::has_extension(ArgValue)) {
2154 // If the argument didn't provide an extension, then set it.
2155 const char *Extension = types::getTypeTempSuffix(FileType, true);
Hans Wennborg6d0a8d52013-09-10 20:18:04 +00002156
2157 if (FileType == types::TY_Image &&
2158 Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
2159 // The output file is a dll.
2160 Extension = "dll";
2161 }
2162
Hans Wennborgc65c72d2013-08-12 21:56:42 +00002163 llvm::sys::path::replace_extension(Filename, Extension);
2164 }
2165
2166 return Args.MakeArgString(Filename.c_str());
2167}
2168
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002169const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
Daniel Dunbar441d0602009-03-17 17:53:55 +00002170 const char *BaseInput,
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002171 const char *BoundArch, bool AtTopLevel,
Chad Rosier1c187592013-04-30 22:01:21 +00002172 bool MultipleArchs) const {
Daniel Dunbar8f25c792009-03-18 01:38:48 +00002173 llvm::PrettyStackTraceString CrashInfo("Computing output path");
Daniel Dunbar441d0602009-03-17 17:53:55 +00002174 // Output to a user requested destination?
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002175 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
Daniel Dunbar441d0602009-03-17 17:53:55 +00002176 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
Chad Rosier9d718632013-01-24 19:14:47 +00002177 return C.addResultFile(FinalOutput->getValue(), &JA);
Daniel Dunbar441d0602009-03-17 17:53:55 +00002178 }
2179
Stephen Hines651f13c2014-04-23 16:59:28 -07002180 // For /P, preprocess to file named after BaseInput.
2181 if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
2182 assert(AtTopLevel && isa<PreprocessJobAction>(JA));
2183 StringRef BaseName = llvm::sys::path::filename(BaseInput);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002184 StringRef NameArg;
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -07002185 if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002186 NameArg = A->getValue();
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002187 return C.addResultFile(
2188 MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
2189 &JA);
Stephen Hines651f13c2014-04-23 16:59:28 -07002190 }
2191
Nick Lewyckybfd21242010-09-24 00:46:53 +00002192 // Default to writing to stdout?
Douglas Gregorc544ba02013-03-27 16:47:18 +00002193 if (AtTopLevel && !CCGenDiagnostics &&
2194 (isa<PreprocessJobAction>(JA) || JA.getType() == types::TY_ModuleFile))
Nick Lewyckybfd21242010-09-24 00:46:53 +00002195 return "-";
2196
Hans Wennborg82a29112013-10-17 16:16:23 +00002197 // Is this the assembly listing for /FA?
2198 if (JA.getType() == types::TY_PP_Asm &&
2199 (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
2200 C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
2201 // Use /Fa and the input filename to determine the asm file name.
2202 StringRef BaseName = llvm::sys::path::filename(BaseInput);
2203 StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002204 return C.addResultFile(
2205 MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
2206 &JA);
Hans Wennborg82a29112013-10-17 16:16:23 +00002207 }
2208
Daniel Dunbar441d0602009-03-17 17:53:55 +00002209 // Output to a temporary file?
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002210 if ((!AtTopLevel && !isSaveTempsEnabled() &&
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002211 !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
Chad Rosier2b819102011-08-02 17:58:04 +00002212 CCGenDiagnostics) {
Chad Rosierf43b5e82011-08-26 22:27:02 +00002213 StringRef Name = llvm::sys::path::filename(BaseInput);
2214 std::pair<StringRef, StringRef> Split = Name.split('.');
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002215 std::string TmpName = GetTemporaryPath(
2216 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
Daniel Dunbar214399e2009-03-18 19:34:39 +00002217 return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
Daniel Dunbar441d0602009-03-17 17:53:55 +00002218 }
2219
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002220 SmallString<128> BasePath(BaseInput);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002221 StringRef BaseName;
Daniel Dunbar59f90462011-03-25 18:16:51 +00002222
2223 // Dsymutil actions should use the full path.
Eric Christopherf8571862011-08-23 17:56:55 +00002224 if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
Daniel Dunbar59f90462011-03-25 18:16:51 +00002225 BaseName = BasePath;
2226 else
2227 BaseName = llvm::sys::path::filename(BasePath);
Daniel Dunbar441d0602009-03-17 17:53:55 +00002228
2229 // Determine what the derived output name should be.
2230 const char *NamedOutput;
Hans Wennborgab50ccd2013-08-06 22:11:28 +00002231
2232 if (JA.getType() == types::TY_Object &&
Stephen Hines176edba2014-12-01 14:53:08 -08002233 C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
2234 // The /Fo or /o flag decides the object filename.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002235 StringRef Val =
2236 C.getArgs()
2237 .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
2238 ->getValue();
2239 NamedOutput =
2240 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
Hans Wennborgc65c72d2013-08-12 21:56:42 +00002241 } else if (JA.getType() == types::TY_Image &&
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002242 C.getArgs().hasArg(options::OPT__SLASH_Fe,
2243 options::OPT__SLASH_o)) {
Stephen Hines176edba2014-12-01 14:53:08 -08002244 // The /Fe or /o flag names the linked file.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002245 StringRef Val =
2246 C.getArgs()
2247 .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
2248 ->getValue();
2249 NamedOutput =
2250 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
Hans Wennborg6d0a8d52013-09-10 20:18:04 +00002251 } else if (JA.getType() == types::TY_Image) {
Hans Wennborgc65c72d2013-08-12 21:56:42 +00002252 if (IsCLMode()) {
2253 // clang-cl uses BaseName for the executable name.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002254 NamedOutput =
2255 MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
Hans Wennborgc65c72d2013-08-12 21:56:42 +00002256 } else if (MultipleArchs && BoundArch) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002257 SmallString<128> Output(getDefaultImageName());
Chad Rosier1c187592013-04-30 22:01:21 +00002258 Output += "-";
2259 Output.append(BoundArch);
2260 NamedOutput = C.getArgs().MakeArgString(Output.c_str());
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002261 } else {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002262 NamedOutput = getDefaultImageName();
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002263 }
2264 } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
2265 NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName).c_str());
Daniel Dunbar441d0602009-03-17 17:53:55 +00002266 } else {
Hans Wennborga6e7e492013-09-05 17:05:56 +00002267 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
Daniel Dunbar441d0602009-03-17 17:53:55 +00002268 assert(Suffix && "All types used for output should have a suffix.");
2269
2270 std::string::size_type End = std::string::npos;
2271 if (!types::appendSuffixForType(JA.getType()))
2272 End = BaseName.rfind('.');
Chad Rosier1c187592013-04-30 22:01:21 +00002273 SmallString<128> Suffixed(BaseName.substr(0, End));
2274 if (MultipleArchs && BoundArch) {
2275 Suffixed += "-";
2276 Suffixed.append(BoundArch);
2277 }
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002278 // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
2279 // the unoptimized bitcode so that it does not get overwritten by the ".bc"
2280 // optimized bitcode output.
2281 if (!AtTopLevel && C.getArgs().hasArg(options::OPT_emit_llvm) &&
2282 JA.getType() == types::TY_LLVM_BC)
2283 Suffixed += ".tmp";
Daniel Dunbar441d0602009-03-17 17:53:55 +00002284 Suffixed += '.';
2285 Suffixed += Suffix;
2286 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
2287 }
2288
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002289 // Prepend object file path if -save-temps=obj
2290 if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
2291 JA.getType() != types::TY_PCH) {
2292 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
2293 SmallString<128> TempPath(FinalOutput->getValue());
2294 llvm::sys::path::remove_filename(TempPath);
2295 StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
2296 llvm::sys::path::append(TempPath, OutputFileName);
2297 NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
2298 }
2299
Chad Rosier6467c9b2012-07-09 17:31:28 +00002300 // If we're saving temps and the temp file conflicts with the input file,
Chad Rosier61ada0a2012-04-20 20:05:08 +00002301 // then avoid overwriting input file.
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002302 if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
Chad Rosier61ada0a2012-04-20 20:05:08 +00002303 bool SameFile = false;
2304 SmallString<256> Result;
2305 llvm::sys::fs::current_path(Result);
2306 llvm::sys::path::append(Result, BaseName);
2307 llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
2308 // Must share the same path to conflict.
2309 if (SameFile) {
2310 StringRef Name = llvm::sys::path::filename(BaseInput);
2311 std::pair<StringRef, StringRef> Split = Name.split('.');
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002312 std::string TmpName = GetTemporaryPath(
2313 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
Chad Rosier61ada0a2012-04-20 20:05:08 +00002314 return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
2315 }
Chad Rosier3e4d1092011-07-15 21:54:29 +00002316 }
2317
Daniel Dunbara8231832009-09-08 23:36:43 +00002318 // As an annoying special case, PCH generation doesn't strip the pathname.
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002319 if (JA.getType() == types::TY_PCH && !IsCLMode()) {
Michael J. Spencer472ccff2010-12-18 00:19:12 +00002320 llvm::sys::path::remove_filename(BasePath);
2321 if (BasePath.empty())
Daniel Dunbar56c55942009-03-18 09:58:30 +00002322 BasePath = NamedOutput;
2323 else
Michael J. Spencer472ccff2010-12-18 00:19:12 +00002324 llvm::sys::path::append(BasePath, NamedOutput);
Chad Rosier9d718632013-01-24 19:14:47 +00002325 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
Daniel Dunbar441d0602009-03-17 17:53:55 +00002326 } else {
Chad Rosier9d718632013-01-24 19:14:47 +00002327 return C.addResultFile(NamedOutput, &JA);
Daniel Dunbar441d0602009-03-17 17:53:55 +00002328 }
2329}
2330
Daniel Dunbar5ed34f42009-09-09 22:33:00 +00002331std::string Driver::GetFilePath(const char *Name, const ToolChain &TC) const {
Chandler Carruth48ad6092010-03-22 01:52:07 +00002332 // Respect a limited subset of the '-Bprefix' functionality in GCC by
Logan Chien429fce92012-10-04 08:08:56 +00002333 // attempting to use this prefix when looking for file paths.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002334 for (const std::string &Dir : PrefixDirs) {
Joerg Sonnenberger8ab2bdc2011-03-21 13:51:29 +00002335 if (Dir.empty())
2336 continue;
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002337 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
Rafael Espindolae8486302013-06-24 18:33:43 +00002338 llvm::sys::path::append(P, Name);
2339 if (llvm::sys::fs::exists(Twine(P)))
Chandler Carruth48ad6092010-03-22 01:52:07 +00002340 return P.str();
2341 }
2342
Rafael Espindolae8486302013-06-24 18:33:43 +00002343 SmallString<128> P(ResourceDir);
2344 llvm::sys::path::append(P, Name);
2345 if (llvm::sys::fs::exists(Twine(P)))
Peter Collingbourne41ee7a32011-09-06 02:08:31 +00002346 return P.str();
2347
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002348 for (const std::string &Dir : TC.getFilePaths()) {
Joerg Sonnenberger8ab2bdc2011-03-21 13:51:29 +00002349 if (Dir.empty())
2350 continue;
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002351 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
Rafael Espindolae8486302013-06-24 18:33:43 +00002352 llvm::sys::path::append(P, Name);
2353 if (llvm::sys::fs::exists(Twine(P)))
Daniel Dunbar5ed34f42009-09-09 22:33:00 +00002354 return P.str();
Daniel Dunbar0edefeb2009-03-18 20:26:19 +00002355 }
2356
Daniel Dunbar5ed34f42009-09-09 22:33:00 +00002357 return Name;
Daniel Dunbarcb881672009-03-13 00:51:18 +00002358}
2359
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002360void Driver::generatePrefixedToolNames(
2361 const char *Tool, const ToolChain &TC,
2362 SmallVectorImpl<std::string> &Names) const {
Stephen Hines176edba2014-12-01 14:53:08 -08002363 // FIXME: Needs a better variable than DefaultTargetTriple
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -07002364 Names.emplace_back(DefaultTargetTriple + "-" + Tool);
2365 Names.emplace_back(Tool);
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002366
2367 // Allow the discovery of tools prefixed with LLVM's default target triple.
2368 std::string LLVMDefaultTargetTriple = llvm::sys::getDefaultTargetTriple();
2369 if (LLVMDefaultTargetTriple != DefaultTargetTriple)
2370 Names.emplace_back(LLVMDefaultTargetTriple + "-" + Tool);
Stephen Hines176edba2014-12-01 14:53:08 -08002371}
2372
2373static bool ScanDirForExecutable(SmallString<128> &Dir,
2374 ArrayRef<std::string> Names) {
2375 for (const auto &Name : Names) {
2376 llvm::sys::path::append(Dir, Name);
2377 if (llvm::sys::fs::can_execute(Twine(Dir)))
2378 return true;
2379 llvm::sys::path::remove_filename(Dir);
2380 }
2381 return false;
2382}
2383
Simon Atanasyanfc44e882012-10-03 19:52:37 +00002384std::string Driver::GetProgramPath(const char *Name,
2385 const ToolChain &TC) const {
Stephen Hines176edba2014-12-01 14:53:08 -08002386 SmallVector<std::string, 2> TargetSpecificExecutables;
2387 generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
2388
Chandler Carruth48ad6092010-03-22 01:52:07 +00002389 // Respect a limited subset of the '-Bprefix' functionality in GCC by
Logan Chien429fce92012-10-04 08:08:56 +00002390 // attempting to use this prefix when looking for program paths.
Stephen Hines176edba2014-12-01 14:53:08 -08002391 for (const auto &PrefixDir : PrefixDirs) {
2392 if (llvm::sys::fs::is_directory(PrefixDir)) {
2393 SmallString<128> P(PrefixDir);
2394 if (ScanDirForExecutable(P, TargetSpecificExecutables))
Rafael Espindola9ff463e2013-06-19 13:24:29 +00002395 return P.str();
Simon Atanasyanbfd452e2012-10-31 14:39:28 +00002396 } else {
Stephen Hines176edba2014-12-01 14:53:08 -08002397 SmallString<128> P(PrefixDir + Name);
Rafael Espindolae8486302013-06-24 18:33:43 +00002398 if (llvm::sys::fs::can_execute(Twine(P)))
Rafael Espindola9ff463e2013-06-19 13:24:29 +00002399 return P.str();
Simon Atanasyane0157542012-10-31 12:01:53 +00002400 }
Chandler Carruth48ad6092010-03-22 01:52:07 +00002401 }
2402
Daniel Dunbar0edefeb2009-03-18 20:26:19 +00002403 const ToolChain::path_list &List = TC.getProgramPaths();
Stephen Hines176edba2014-12-01 14:53:08 -08002404 for (const auto &Path : List) {
2405 SmallString<128> P(Path);
2406 if (ScanDirForExecutable(P, TargetSpecificExecutables))
Rafael Espindola9ff463e2013-06-19 13:24:29 +00002407 return P.str();
Daniel Dunbar0edefeb2009-03-18 20:26:19 +00002408 }
2409
Daniel Dunbarc50b00d2009-03-23 16:15:50 +00002410 // If all else failed, search the path.
Stephen Hines176edba2014-12-01 14:53:08 -08002411 for (const auto &TargetSpecificExecutable : TargetSpecificExecutables)
2412 if (llvm::ErrorOr<std::string> P =
2413 llvm::sys::findProgramByName(TargetSpecificExecutable))
2414 return *P;
Daniel Dunbar632f50e2009-03-18 21:34:08 +00002415
Daniel Dunbar5ed34f42009-09-09 22:33:00 +00002416 return Name;
Daniel Dunbarcb881672009-03-13 00:51:18 +00002417}
2418
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002419std::string Driver::GetTemporaryPath(StringRef Prefix,
2420 const char *Suffix) const {
Rafael Espindola4ea53ae2013-06-25 04:26:55 +00002421 SmallString<128> Path;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002422 std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
Rafael Espindola4ea53ae2013-06-25 04:26:55 +00002423 if (EC) {
2424 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
Daniel Dunbar214399e2009-03-18 19:34:39 +00002425 return "";
2426 }
2427
Rafael Espindola4ea53ae2013-06-25 04:26:55 +00002428 return Path.str();
Daniel Dunbar214399e2009-03-18 19:34:39 +00002429}
2430
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002431std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
2432 SmallString<128> Output;
2433 if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
2434 // FIXME: If anybody needs it, implement this obscure rule:
2435 // "If you specify a directory without a file name, the default file name
2436 // is VCx0.pch., where x is the major version of Visual C++ in use."
2437 Output = FpArg->getValue();
2438
2439 // "If you do not specify an extension as part of the path name, an
2440 // extension of .pch is assumed. "
2441 if (!llvm::sys::path::has_extension(Output))
2442 Output += ".pch";
2443 } else {
2444 Output = BaseName;
2445 llvm::sys::path::replace_extension(Output, ".pch");
2446 }
2447 return Output.str();
2448}
2449
Chandler Carruth18d7f3a2012-01-25 11:01:57 +00002450const ToolChain &Driver::getToolChain(const ArgList &Args,
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002451 const llvm::Triple &Target) const {
Chandler Carruth18d7f3a2012-01-25 11:01:57 +00002452
Chandler Carruth1d16f0f2012-01-31 02:21:20 +00002453 ToolChain *&TC = ToolChains[Target.str()];
Chandler Carruth18d7f3a2012-01-25 11:01:57 +00002454 if (!TC) {
2455 switch (Target.getOS()) {
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002456 case llvm::Triple::Haiku:
2457 TC = new toolchains::Haiku(*this, Target, Args);
2458 break;
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07002459 case llvm::Triple::CloudABI:
2460 TC = new toolchains::CloudABI(*this, Target, Args);
2461 break;
Chandler Carruth18d7f3a2012-01-25 11:01:57 +00002462 case llvm::Triple::Darwin:
2463 case llvm::Triple::MacOSX:
2464 case llvm::Triple::IOS:
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002465 case llvm::Triple::TvOS:
2466 case llvm::Triple::WatchOS:
Stephen Hines651f13c2014-04-23 16:59:28 -07002467 TC = new toolchains::DarwinClang(*this, Target, Args);
Chandler Carruth18d7f3a2012-01-25 11:01:57 +00002468 break;
2469 case llvm::Triple::DragonFly:
Rafael Espindola0e659592012-02-19 01:38:32 +00002470 TC = new toolchains::DragonFly(*this, Target, Args);
Chandler Carruth18d7f3a2012-01-25 11:01:57 +00002471 break;
2472 case llvm::Triple::OpenBSD:
Rafael Espindola0e659592012-02-19 01:38:32 +00002473 TC = new toolchains::OpenBSD(*this, Target, Args);
Chandler Carruth18d7f3a2012-01-25 11:01:57 +00002474 break;
Eli Friedman42f74f22012-08-08 23:57:20 +00002475 case llvm::Triple::Bitrig:
2476 TC = new toolchains::Bitrig(*this, Target, Args);
2477 break;
Chandler Carruth18d7f3a2012-01-25 11:01:57 +00002478 case llvm::Triple::NetBSD:
Rafael Espindola0e659592012-02-19 01:38:32 +00002479 TC = new toolchains::NetBSD(*this, Target, Args);
Chandler Carruth18d7f3a2012-01-25 11:01:57 +00002480 break;
2481 case llvm::Triple::FreeBSD:
Rafael Espindola0e659592012-02-19 01:38:32 +00002482 TC = new toolchains::FreeBSD(*this, Target, Args);
Chandler Carruth18d7f3a2012-01-25 11:01:57 +00002483 break;
2484 case llvm::Triple::Minix:
Rafael Espindola0e659592012-02-19 01:38:32 +00002485 TC = new toolchains::Minix(*this, Target, Args);
Chandler Carruth18d7f3a2012-01-25 11:01:57 +00002486 break;
2487 case llvm::Triple::Linux:
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002488 case llvm::Triple::ELFIAMCU:
Chandler Carruth1621e752012-01-25 21:03:58 +00002489 if (Target.getArch() == llvm::Triple::hexagon)
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002490 TC = new toolchains::HexagonToolChain(*this, Target, Args);
2491 else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
2492 !Target.hasEnvironment())
2493 TC = new toolchains::MipsLLVMToolChain(*this, Target, Args);
Chandler Carruth1621e752012-01-25 21:03:58 +00002494 else
Rafael Espindola0e659592012-02-19 01:38:32 +00002495 TC = new toolchains::Linux(*this, Target, Args);
Chandler Carruth18d7f3a2012-01-25 11:01:57 +00002496 break;
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07002497 case llvm::Triple::NaCl:
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002498 TC = new toolchains::NaClToolChain(*this, Target, Args);
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07002499 break;
David Chisnall31c46902012-02-15 13:39:01 +00002500 case llvm::Triple::Solaris:
Rafael Espindola0e659592012-02-19 01:38:32 +00002501 TC = new toolchains::Solaris(*this, Target, Args);
David Chisnall31c46902012-02-15 13:39:01 +00002502 break;
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002503 case llvm::Triple::AMDHSA:
2504 TC = new toolchains::AMDGPUToolChain(*this, Target, Args);
2505 break;
Chandler Carruth18d7f3a2012-01-25 11:01:57 +00002506 case llvm::Triple::Win32:
Stephen Hines651f13c2014-04-23 16:59:28 -07002507 switch (Target.getEnvironment()) {
2508 default:
2509 if (Target.isOSBinFormatELF())
2510 TC = new toolchains::Generic_ELF(*this, Target, Args);
2511 else if (Target.isOSBinFormatMachO())
2512 TC = new toolchains::MachO(*this, Target, Args);
2513 else
2514 TC = new toolchains::Generic_GCC(*this, Target, Args);
2515 break;
2516 case llvm::Triple::GNU:
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002517 TC = new toolchains::MinGW(*this, Target, Args);
Stephen Hines651f13c2014-04-23 16:59:28 -07002518 break;
Stephen Hines176edba2014-12-01 14:53:08 -08002519 case llvm::Triple::Itanium:
2520 TC = new toolchains::CrossWindowsToolChain(*this, Target, Args);
2521 break;
Stephen Hines651f13c2014-04-23 16:59:28 -07002522 case llvm::Triple::MSVC:
2523 case llvm::Triple::UnknownEnvironment:
Stephen Hines176edba2014-12-01 14:53:08 -08002524 TC = new toolchains::MSVCToolChain(*this, Target, Args);
Stephen Hines651f13c2014-04-23 16:59:28 -07002525 break;
2526 }
Chandler Carruth18d7f3a2012-01-25 11:01:57 +00002527 break;
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002528 case llvm::Triple::CUDA:
2529 TC = new toolchains::CudaToolChain(*this, Target, Args);
2530 break;
2531 case llvm::Triple::PS4:
2532 TC = new toolchains::PS4CPU(*this, Target, Args);
2533 break;
Chandler Carruth18d7f3a2012-01-25 11:01:57 +00002534 default:
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -07002535 // Of these targets, Hexagon is the only one that might have
2536 // an OS of Linux, in which case it got handled above already.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002537 switch (Target.getArch()) {
2538 case llvm::Triple::tce:
Rafael Espindolaaf370e62013-03-18 18:10:27 +00002539 TC = new toolchains::TCEToolChain(*this, Target, Args);
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002540 break;
2541 case llvm::Triple::hexagon:
2542 TC = new toolchains::HexagonToolChain(*this, Target, Args);
2543 break;
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002544 case llvm::Triple::lanai:
2545 TC = new toolchains::LanaiToolChain(*this, Target, Args);
2546 break;
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002547 case llvm::Triple::xcore:
2548 TC = new toolchains::XCoreToolChain(*this, Target, Args);
2549 break;
2550 case llvm::Triple::wasm32:
2551 case llvm::Triple::wasm64:
2552 TC = new toolchains::WebAssembly(*this, Target, Args);
2553 break;
2554 default:
2555 if (Target.getVendor() == llvm::Triple::Myriad)
2556 TC = new toolchains::MyriadToolChain(*this, Target, Args);
2557 else if (Target.isOSBinFormatELF())
2558 TC = new toolchains::Generic_ELF(*this, Target, Args);
2559 else if (Target.isOSBinFormatMachO())
2560 TC = new toolchains::MachO(*this, Target, Args);
2561 else
2562 TC = new toolchains::Generic_GCC(*this, Target, Args);
2563 }
Chandler Carruth18d7f3a2012-01-25 11:01:57 +00002564 }
2565 }
2566 return *TC;
Daniel Dunbardd98e2c2009-03-10 23:41:59 +00002567}
Daniel Dunbaraf80e1f2009-03-24 18:57:02 +00002568
Rafael Espindolad5320182013-03-18 15:33:26 +00002569bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -07002570 // Say "no" if there is not exactly one input of a type clang understands.
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002571 if (JA.size() != 1 ||
2572 !types::isAcceptedByClang((*JA.input_begin())->getType()))
Nick Lewycky5bab9ae2012-11-15 05:36:36 +00002573 return false;
2574
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -07002575 // And say "no" if this is not a kind of action clang understands.
Nick Lewycky5bab9ae2012-11-15 05:36:36 +00002576 if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002577 !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
Nick Lewycky5bab9ae2012-11-15 05:36:36 +00002578 return false;
2579
2580 return true;
2581}
2582
Daniel Dunbara8231832009-09-08 23:36:43 +00002583/// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
2584/// grouped values as integers. Numbers which are not provided are set to 0.
Daniel Dunbard73fe9b2009-03-26 15:58:36 +00002585///
Daniel Dunbara8231832009-09-08 23:36:43 +00002586/// \return True if the entire string was parsed (9.2), or all groups were
2587/// parsed (10.3.5extrastuff).
2588bool Driver::GetReleaseVersion(const char *Str, unsigned &Major,
Daniel Dunbard73fe9b2009-03-26 15:58:36 +00002589 unsigned &Minor, unsigned &Micro,
2590 bool &HadExtra) {
2591 HadExtra = false;
2592
2593 Major = Minor = Micro = 0;
Daniel Dunbara8231832009-09-08 23:36:43 +00002594 if (*Str == '\0')
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07002595 return false;
Daniel Dunbard73fe9b2009-03-26 15:58:36 +00002596
2597 char *End;
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002598 Major = (unsigned)strtol(Str, &End, 10);
Daniel Dunbard73fe9b2009-03-26 15:58:36 +00002599 if (*Str != '\0' && *End == '\0')
2600 return true;
2601 if (*End != '.')
2602 return false;
Daniel Dunbara8231832009-09-08 23:36:43 +00002603
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002604 Str = End + 1;
2605 Minor = (unsigned)strtol(Str, &End, 10);
Daniel Dunbard73fe9b2009-03-26 15:58:36 +00002606 if (*Str != '\0' && *End == '\0')
2607 return true;
2608 if (*End != '.')
2609 return false;
2610
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002611 Str = End + 1;
2612 Micro = (unsigned)strtol(Str, &End, 10);
Daniel Dunbard73fe9b2009-03-26 15:58:36 +00002613 if (*Str != '\0' && *End == '\0')
2614 return true;
2615 if (Str == End)
2616 return false;
2617 HadExtra = true;
2618 return true;
2619}
Hans Wennborg69813302013-07-27 00:23:45 +00002620
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002621/// Parse digits from a string \p Str and fulfill \p Digits with
2622/// the parsed numbers. This method assumes that the max number of
2623/// digits to look for is equal to Digits.size().
2624///
2625/// \return True if the entire string was parsed and there are
2626/// no extra characters remaining at the end.
2627bool Driver::GetReleaseVersion(const char *Str,
2628 MutableArrayRef<unsigned> Digits) {
2629 if (*Str == '\0')
2630 return false;
2631
2632 char *End;
2633 unsigned CurDigit = 0;
2634 while (CurDigit < Digits.size()) {
2635 unsigned Digit = (unsigned)strtol(Str, &End, 10);
2636 Digits[CurDigit] = Digit;
2637 if (*Str != '\0' && *End == '\0')
2638 return true;
2639 if (*End != '.' || Str == End)
2640 return false;
2641 Str = End + 1;
2642 CurDigit++;
2643 }
2644
2645 // More digits than requested, bail out...
2646 return false;
2647}
2648
Hans Wennborg69813302013-07-27 00:23:45 +00002649std::pair<unsigned, unsigned> Driver::getIncludeExcludeOptionFlagMasks() const {
2650 unsigned IncludedFlagsBitmask = 0;
Rafael Espindola4ab39de2013-09-25 15:54:41 +00002651 unsigned ExcludedFlagsBitmask = options::NoDriverOption;
Hans Wennborg69813302013-07-27 00:23:45 +00002652
2653 if (Mode == CLMode) {
Hans Wennborg78d0fbf2013-07-31 20:51:53 +00002654 // Include CL and Core options.
2655 IncludedFlagsBitmask |= options::CLOption;
2656 IncludedFlagsBitmask |= options::CoreOption;
Hans Wennborg69813302013-07-27 00:23:45 +00002657 } else {
2658 ExcludedFlagsBitmask |= options::CLOption;
2659 }
2660
2661 return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
2662}
Stephen Hines651f13c2014-04-23 16:59:28 -07002663
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -07002664bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002665 return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);
2666}