blob: 8768629625dafab516026dc943c0294288a53a5f [file] [log] [blame]
Daniel Dunbar63c4da92009-03-02 19:59:07 +00001//===--- Driver.cpp - Clang GCC Compatible Driver -----------------------*-===//
2//
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 Dunbar63c4da92009-03-02 19:59:07 +000010#include "clang/Driver/Driver.h"
Daniel Dunbar63c4da92009-03-02 19:59:07 +000011
Daniel Dunbardb62cc32009-03-12 07:58:46 +000012#include "clang/Driver/Action.h"
Daniel Dunbard6f0e372009-03-04 20:49:20 +000013#include "clang/Driver/Arg.h"
14#include "clang/Driver/ArgList.h"
15#include "clang/Driver/Compilation.h"
Daniel Dunbar93468492009-03-12 08:55:43 +000016#include "clang/Driver/DriverDiagnostic.h"
Daniel Dunbard25acaa2009-03-10 23:41:59 +000017#include "clang/Driver/HostInfo.h"
Daniel Dunbar7ce6add2009-03-16 06:56:51 +000018#include "clang/Driver/Job.h"
Daniel Dunbar7dc2a042009-03-05 06:38:47 +000019#include "clang/Driver/Option.h"
Daniel Dunbard6f0e372009-03-04 20:49:20 +000020#include "clang/Driver/Options.h"
Daniel Dunbar7ce6add2009-03-16 06:56:51 +000021#include "clang/Driver/Tool.h"
22#include "clang/Driver/ToolChain.h"
Daniel Dunbardb62cc32009-03-12 07:58:46 +000023#include "clang/Driver/Types.h"
Daniel Dunbar7dc2a042009-03-05 06:38:47 +000024
Daniel Dunbarb1873cd2009-03-13 20:33:35 +000025#include "llvm/ADT/StringSet.h"
Daniel Dunbar16e04ff2009-03-18 01:38:48 +000026#include "llvm/Support/PrettyStackTrace.h"
Daniel Dunbar7dc2a042009-03-05 06:38:47 +000027#include "llvm/Support/raw_ostream.h"
Daniel Dunbardb62cc32009-03-12 07:58:46 +000028#include "llvm/System/Path.h"
Daniel Dunbarcb84b9a2009-03-18 21:34:08 +000029#include "llvm/System/Program.h"
Daniel Dunbar494646b2009-03-13 12:19:02 +000030
Daniel Dunbar7ce6add2009-03-16 06:56:51 +000031#include "InputInfo.h"
32
Daniel Dunbar494646b2009-03-13 12:19:02 +000033#include <map>
34
Daniel Dunbard6f0e372009-03-04 20:49:20 +000035using namespace clang::driver;
Chris Lattnerc272d262009-03-26 05:56:24 +000036using namespace clang;
Daniel Dunbard6f0e372009-03-04 20:49:20 +000037
Daniel Dunbard25acaa2009-03-10 23:41:59 +000038Driver::Driver(const char *_Name, const char *_Dir,
Daniel Dunbar93468492009-03-12 08:55:43 +000039 const char *_DefaultHostTriple,
Daniel Dunbar7ce6add2009-03-16 06:56:51 +000040 const char *_DefaultImageName,
Daniel Dunbar93468492009-03-12 08:55:43 +000041 Diagnostic &_Diags)
42 : Opts(new OptTable()), Diags(_Diags),
Daniel Dunbard25acaa2009-03-10 23:41:59 +000043 Name(_Name), Dir(_Dir), DefaultHostTriple(_DefaultHostTriple),
Daniel Dunbar7ce6add2009-03-16 06:56:51 +000044 DefaultImageName(_DefaultImageName),
Daniel Dunbard25acaa2009-03-10 23:41:59 +000045 Host(0),
Daniel Dunbar07c9a1d2009-03-17 22:47:06 +000046 CCCIsCXX(false), CCCEcho(false), CCCPrintBindings(false),
Daniel Dunbar126da5e2009-04-01 23:34:41 +000047 CCCGenericGCCName("gcc"), CCCUseClang(true), CCCUseClangCXX(false),
48 CCCUseClangCPP(true),
Daniel Dunbar5a5ec5c2009-03-13 00:17:48 +000049 SuppressMissingInputWarning(false)
Daniel Dunbarb282ced2009-03-10 20:52:46 +000050{
Daniel Dunbar0ea85f72009-03-24 19:02:31 +000051 // Only use clang on i386 and x86_64 by default.
52 CCCClangArchs.insert("i386");
53 CCCClangArchs.insert("x86_64");
Daniel Dunbar63c4da92009-03-02 19:59:07 +000054}
55
56Driver::~Driver() {
Daniel Dunbard6f0e372009-03-04 20:49:20 +000057 delete Opts;
Daniel Dunbar2f8b37e2009-03-18 01:09:40 +000058 delete Host;
Daniel Dunbar63c4da92009-03-02 19:59:07 +000059}
60
Daniel Dunbara16e4fe2009-03-25 04:13:45 +000061InputArgList *Driver::ParseArgStrings(const char **ArgBegin,
62 const char **ArgEnd) {
Daniel Dunbar16e04ff2009-03-18 01:38:48 +000063 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
Daniel Dunbara16e4fe2009-03-25 04:13:45 +000064 InputArgList *Args = new InputArgList(ArgBegin, ArgEnd);
Daniel Dunbar7dc2a042009-03-05 06:38:47 +000065
Daniel Dunbar85cb3592009-03-13 11:38:42 +000066 // FIXME: Handle '@' args (or at least error on them).
67
Daniel Dunbar7dc2a042009-03-05 06:38:47 +000068 unsigned Index = 0, End = ArgEnd - ArgBegin;
69 while (Index < End) {
Daniel Dunbarb043ebd2009-03-13 01:01:44 +000070 // gcc's handling of empty arguments doesn't make
71 // sense, but this is not a common use case. :)
72 //
73 // We just ignore them here (note that other things may
74 // still take them as arguments).
75 if (Args->getArgString(Index)[0] == '\0') {
76 ++Index;
77 continue;
78 }
79
Daniel Dunbar7dc2a042009-03-05 06:38:47 +000080 unsigned Prev = Index;
Daniel Dunbarfb88ce02009-03-22 23:26:43 +000081 Arg *A = getOpts().ParseOneArg(*Args, Index);
82 assert(Index > Prev && "Parser failed to consume argument.");
Daniel Dunbardb62cc32009-03-12 07:58:46 +000083
Daniel Dunbarfb88ce02009-03-22 23:26:43 +000084 // Check for missing argument error.
85 if (!A) {
86 assert(Index >= End && "Unexpected parser error.");
87 Diag(clang::diag::err_drv_missing_argument)
88 << Args->getArgString(Prev)
89 << (Index - Prev - 1);
90 break;
Daniel Dunbardb62cc32009-03-12 07:58:46 +000091 }
Daniel Dunbar7dc2a042009-03-05 06:38:47 +000092
Daniel Dunbarfb88ce02009-03-22 23:26:43 +000093 if (A->getOption().isUnsupported()) {
94 Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(*Args);
95 continue;
96 }
97 Args->append(A);
Daniel Dunbar7dc2a042009-03-05 06:38:47 +000098 }
99
100 return Args;
101}
102
Daniel Dunbar63c4da92009-03-02 19:59:07 +0000103Compilation *Driver::BuildCompilation(int argc, const char **argv) {
Daniel Dunbar16e04ff2009-03-18 01:38:48 +0000104 llvm::PrettyStackTraceString CrashInfo("Compilation construction");
105
Daniel Dunbarcc006892009-03-13 00:51:18 +0000106 // FIXME: Handle environment options which effect driver behavior,
107 // somewhere (client?). GCC_EXEC_PREFIX, COMPILER_PATH,
108 // LIBRARY_PATH, LPATH, CC_PRINT_OPTIONS, QA_OVERRIDE_GCC3_OPTIONS.
109
110 // FIXME: What are we going to do with -V and -b?
111
Daniel Dunbarb282ced2009-03-10 20:52:46 +0000112 // FIXME: This stuff needs to go into the Compilation, not the
113 // driver.
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000114 bool CCCPrintOptions = false, CCCPrintActions = false;
Daniel Dunbar7dc2a042009-03-05 06:38:47 +0000115
Daniel Dunbarb282ced2009-03-10 20:52:46 +0000116 const char **Start = argv + 1, **End = argv + argc;
Daniel Dunbard25acaa2009-03-10 23:41:59 +0000117 const char *HostTriple = DefaultHostTriple.c_str();
Daniel Dunbarb282ced2009-03-10 20:52:46 +0000118
119 // Read -ccc args.
120 //
121 // FIXME: We need to figure out where this behavior should
122 // live. Most of it should be outside in the client; the parts that
123 // aren't should have proper options, either by introducing new ones
124 // or by overloading gcc ones like -V or -b.
125 for (; Start != End && memcmp(*Start, "-ccc-", 5) == 0; ++Start) {
126 const char *Opt = *Start + 5;
127
128 if (!strcmp(Opt, "print-options")) {
129 CCCPrintOptions = true;
130 } else if (!strcmp(Opt, "print-phases")) {
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000131 CCCPrintActions = true;
Daniel Dunbar07c9a1d2009-03-17 22:47:06 +0000132 } else if (!strcmp(Opt, "print-bindings")) {
133 CCCPrintBindings = true;
Daniel Dunbarb282ced2009-03-10 20:52:46 +0000134 } else if (!strcmp(Opt, "cxx")) {
135 CCCIsCXX = true;
136 } else if (!strcmp(Opt, "echo")) {
137 CCCEcho = true;
138
Daniel Dunbar126da5e2009-04-01 23:34:41 +0000139 } else if (!strcmp(Opt, "gcc-name")) {
140 assert(Start+1 < End && "FIXME: -ccc- argument handling.");
141 CCCGenericGCCName = *++Start;
142
Daniel Dunbar0ea85f72009-03-24 19:02:31 +0000143 } else if (!strcmp(Opt, "clang-cxx")) {
144 CCCUseClangCXX = true;
Daniel Dunbarb282ced2009-03-10 20:52:46 +0000145 } else if (!strcmp(Opt, "no-clang")) {
Daniel Dunbar0ea85f72009-03-24 19:02:31 +0000146 CCCUseClang = false;
Daniel Dunbarb282ced2009-03-10 20:52:46 +0000147 } else if (!strcmp(Opt, "no-clang-cpp")) {
Daniel Dunbar0ea85f72009-03-24 19:02:31 +0000148 CCCUseClangCPP = false;
Daniel Dunbarb282ced2009-03-10 20:52:46 +0000149 } else if (!strcmp(Opt, "clang-archs")) {
150 assert(Start+1 < End && "FIXME: -ccc- argument handling.");
151 const char *Cur = *++Start;
152
Daniel Dunbar0ea85f72009-03-24 19:02:31 +0000153 CCCClangArchs.clear();
Daniel Dunbarb282ced2009-03-10 20:52:46 +0000154 for (;;) {
155 const char *Next = strchr(Cur, ',');
156
157 if (Next) {
Daniel Dunbar0ea85f72009-03-24 19:02:31 +0000158 if (Cur != Next)
159 CCCClangArchs.insert(std::string(Cur, Next));
Daniel Dunbarb282ced2009-03-10 20:52:46 +0000160 Cur = Next + 1;
161 } else {
Daniel Dunbar0ea85f72009-03-24 19:02:31 +0000162 if (*Cur != '\0')
163 CCCClangArchs.insert(std::string(Cur));
Daniel Dunbarb282ced2009-03-10 20:52:46 +0000164 break;
165 }
166 }
167
Daniel Dunbard25acaa2009-03-10 23:41:59 +0000168 } else if (!strcmp(Opt, "host-triple")) {
Daniel Dunbarb282ced2009-03-10 20:52:46 +0000169 assert(Start+1 < End && "FIXME: -ccc- argument handling.");
Daniel Dunbard25acaa2009-03-10 23:41:59 +0000170 HostTriple = *++Start;
Daniel Dunbarb282ced2009-03-10 20:52:46 +0000171
172 } else {
173 // FIXME: Error handling.
174 llvm::errs() << "invalid option: " << *Start << "\n";
175 exit(1);
176 }
177 }
Daniel Dunbard25acaa2009-03-10 23:41:59 +0000178
Daniel Dunbara16e4fe2009-03-25 04:13:45 +0000179 InputArgList *Args = ParseArgStrings(Start, End);
Daniel Dunbarb282ced2009-03-10 20:52:46 +0000180
Daniel Dunbar08966ca2009-03-17 20:45:45 +0000181 Host = GetHostInfo(HostTriple);
Daniel Dunbarcc006892009-03-13 00:51:18 +0000182
Daniel Dunbar9d625e12009-03-16 06:42:30 +0000183 // The compilation takes ownership of Args.
Daniel Dunbar31a76e32009-03-18 22:16:03 +0000184 Compilation *C = new Compilation(*this, *Host->getToolChain(*Args), Args);
Daniel Dunbar73f7b8c2009-03-18 02:55:38 +0000185
186 // FIXME: This behavior shouldn't be here.
187 if (CCCPrintOptions) {
188 PrintOptions(C->getArgs());
189 return C;
190 }
191
192 if (!HandleImmediateArgs(*C))
193 return C;
194
195 // Construct the list of abstract actions to perform for this
196 // compilation. We avoid passing a Compilation here simply to
197 // enforce the abstraction that pipelining is not host or toolchain
198 // dependent (other than the driver driver test).
199 if (Host->useDriverDriver())
200 BuildUniversalActions(C->getArgs(), C->getActions());
201 else
202 BuildActions(C->getArgs(), C->getActions());
203
204 if (CCCPrintActions) {
Daniel Dunbar2b856ce2009-03-18 03:13:20 +0000205 PrintActions(*C);
Daniel Dunbar73f7b8c2009-03-18 02:55:38 +0000206 return C;
207 }
208
209 BuildJobs(*C);
Daniel Dunbarc413f822009-03-15 01:38:15 +0000210
211 return C;
Daniel Dunbarb282ced2009-03-10 20:52:46 +0000212}
213
Daniel Dunbara790d372009-03-12 18:24:49 +0000214void Driver::PrintOptions(const ArgList &Args) const {
Daniel Dunbar7dc2a042009-03-05 06:38:47 +0000215 unsigned i = 0;
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000216 for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
Daniel Dunbar7dc2a042009-03-05 06:38:47 +0000217 it != ie; ++it, ++i) {
218 Arg *A = *it;
219 llvm::errs() << "Option " << i << " - "
220 << "Name: \"" << A->getOption().getName() << "\", "
221 << "Values: {";
222 for (unsigned j = 0; j < A->getNumValues(); ++j) {
223 if (j)
224 llvm::errs() << ", ";
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000225 llvm::errs() << '"' << A->getValue(Args, j) << '"';
Daniel Dunbar7dc2a042009-03-05 06:38:47 +0000226 }
227 llvm::errs() << "}\n";
Daniel Dunbar7dc2a042009-03-05 06:38:47 +0000228 }
Daniel Dunbar63c4da92009-03-02 19:59:07 +0000229}
Daniel Dunbard25acaa2009-03-10 23:41:59 +0000230
Daniel Dunbare627b682009-03-31 21:38:17 +0000231static std::string getOptionHelpName(const OptTable &Opts, options::ID Id) {
232 std::string Name = Opts.getOptionName(Id);
233
234 // Add metavar, if used.
235 switch (Opts.getOptionKind(Id)) {
236 case Option::GroupClass: case Option::InputClass: case Option::UnknownClass:
237 assert(0 && "Invalid option with help text.");
238
239 case Option::MultiArgClass: case Option::JoinedAndSeparateClass:
240 assert(0 && "Cannot print metavar for this kind of option.");
241
242 case Option::FlagClass:
243 break;
244
245 case Option::SeparateClass: case Option::JoinedOrSeparateClass:
246 Name += ' ';
247 // FALLTHROUGH
248 case Option::JoinedClass: case Option::CommaJoinedClass:
249 Name += Opts.getOptionMetaVar(Id);
250 break;
251 }
252
253 return Name;
254}
255
256void Driver::PrintHelp() const {
257 llvm::raw_ostream &OS = llvm::outs();
258
259 OS << "OVERVIEW: clang \"gcc-compatible\" driver\n";
260 OS << '\n';
261 OS << "USAGE: " << Name << " [options] <input files>\n";
262 OS << '\n';
263 OS << "OPTIONS:\n";
264
265 // Render help text into (option, help) pairs.
266 std::vector< std::pair<std::string, const char*> > OptionHelp;
267
268 for (unsigned i = options::OPT_INPUT, e = options::LastOption; i != e; ++i) {
269 options::ID Id = (options::ID) i;
270 if (const char *Text = getOpts().getOptionHelpText(Id))
271 OptionHelp.push_back(std::make_pair(getOptionHelpName(getOpts(), Id),
272 Text));
273 }
274
275 // Find the maximum option length.
276 unsigned OptionFieldWidth = 0;
277 for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
278 // Limit the amount of padding we are willing to give up for
279 // alignment.
280 unsigned Length = OptionHelp[i].first.size();
281 if (Length <= 23)
282 OptionFieldWidth = std::max(OptionFieldWidth, Length);
283 }
284
285 for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
286 const std::string &Option = OptionHelp[i].first;
287 OS << " " << Option;
288 for (int j = Option.length(), e = OptionFieldWidth; j < e; ++j)
289 OS << ' ';
290 OS << ' ' << OptionHelp[i].second << '\n';
291 }
292
293 OS.flush();
294}
295
Daniel Dunbar0ded7de2009-03-26 16:09:13 +0000296void Driver::PrintVersion(const Compilation &C) const {
Mike Stump74d94472009-03-18 14:00:02 +0000297 static char buf[] = "$URL$";
298 char *zap = strstr(buf, "/lib/Driver");
299 if (zap)
300 *zap = 0;
301 zap = strstr(buf, "/clang/tools/clang");
302 if (zap)
303 *zap = 0;
Mike Stumpbc927292009-03-18 15:19:35 +0000304 const char *vers = buf+6;
Mike Stump3fc58f02009-03-18 18:45:55 +0000305 // FIXME: Add cmake support and remove #ifdef
306#ifdef SVN_REVISION
307 const char *revision = SVN_REVISION;
308#else
309 const char *revision = "";
310#endif
Daniel Dunbarcc006892009-03-13 00:51:18 +0000311 // FIXME: The following handlers should use a callback mechanism, we
312 // don't know what the client would like to do.
Daniel Dunbar9a553c42009-04-04 05:17:38 +0000313
314 // FIXME: Do not hardcode clang version.
Mike Stump1207fae2009-03-18 21:19:11 +0000315 llvm::errs() << "clang version 1.0 (" << vers << " " << revision << ")" << "\n";
Daniel Dunbar0ded7de2009-03-26 16:09:13 +0000316
317 const ToolChain &TC = C.getDefaultToolChain();
Daniel Dunbar049b7242009-03-30 06:36:42 +0000318 llvm::errs() << "Target: " << TC.getTripleString() << '\n';
Daniel Dunbarcc006892009-03-13 00:51:18 +0000319}
320
Daniel Dunbar73f7b8c2009-03-18 02:55:38 +0000321bool Driver::HandleImmediateArgs(const Compilation &C) {
Daniel Dunbarcc006892009-03-13 00:51:18 +0000322 // The order these options are handled in in gcc is all over the
323 // place, but we don't expect inconsistencies w.r.t. that to matter
324 // in practice.
Daniel Dunbare627b682009-03-31 21:38:17 +0000325
Daniel Dunbar9a553c42009-04-04 05:17:38 +0000326 if (C.getArgs().hasArg(options::OPT_dumpversion)) {
327 // FIXME: Do not hardcode clang version.
328 llvm::outs() << "1.0\n";
329 return false;
330 }
331
Daniel Dunbare627b682009-03-31 21:38:17 +0000332 if (C.getArgs().hasArg(options::OPT__help)) {
333 PrintHelp();
334 return false;
335 }
336
Daniel Dunbar3b7c84c2009-04-02 15:05:41 +0000337 if (C.getArgs().hasArg(options::OPT__version)) {
338 PrintVersion(C);
339 return false;
340 }
341
Daniel Dunbar73f7b8c2009-03-18 02:55:38 +0000342 if (C.getArgs().hasArg(options::OPT_v) ||
343 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
Daniel Dunbar0ded7de2009-03-26 16:09:13 +0000344 PrintVersion(C);
Daniel Dunbarcc006892009-03-13 00:51:18 +0000345 SuppressMissingInputWarning = true;
346 }
347
Daniel Dunbar73f7b8c2009-03-18 02:55:38 +0000348 const ToolChain &TC = C.getDefaultToolChain();
Daniel Dunbar91b9e202009-03-20 04:37:21 +0000349 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
350 llvm::outs() << "programs: =";
351 for (ToolChain::path_list::const_iterator it = TC.getProgramPaths().begin(),
352 ie = TC.getProgramPaths().end(); it != ie; ++it) {
353 if (it != TC.getProgramPaths().begin())
354 llvm::outs() << ':';
355 llvm::outs() << *it;
356 }
357 llvm::outs() << "\n";
358 llvm::outs() << "libraries: =";
359 for (ToolChain::path_list::const_iterator it = TC.getFilePaths().begin(),
360 ie = TC.getFilePaths().end(); it != ie; ++it) {
361 if (it != TC.getFilePaths().begin())
362 llvm::outs() << ':';
363 llvm::outs() << *it;
364 }
365 llvm::outs() << "\n";
Daniel Dunbare627b682009-03-31 21:38:17 +0000366 return false;
Daniel Dunbar91b9e202009-03-20 04:37:21 +0000367 }
368
Daniel Dunbarcc006892009-03-13 00:51:18 +0000369 // FIXME: The following handlers should use a callback mechanism, we
370 // don't know what the client would like to do.
Daniel Dunbar73f7b8c2009-03-18 02:55:38 +0000371 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
372 llvm::outs() << GetFilePath(A->getValue(C.getArgs()), TC).toString()
373 << "\n";
Daniel Dunbarcc006892009-03-13 00:51:18 +0000374 return false;
375 }
376
Daniel Dunbar73f7b8c2009-03-18 02:55:38 +0000377 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
378 llvm::outs() << GetProgramPath(A->getValue(C.getArgs()), TC).toString()
379 << "\n";
Daniel Dunbarcc006892009-03-13 00:51:18 +0000380 return false;
381 }
382
Daniel Dunbar73f7b8c2009-03-18 02:55:38 +0000383 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
Daniel Dunbaref68dd32009-03-27 14:26:33 +0000384 llvm::outs() << GetFilePath("libgcc.a", TC).toString() << "\n";
Daniel Dunbarcc006892009-03-13 00:51:18 +0000385 return false;
386 }
387
388 return true;
389}
390
Daniel Dunbar2b856ce2009-03-18 03:13:20 +0000391static unsigned PrintActions1(const Compilation &C,
Daniel Dunbar494646b2009-03-13 12:19:02 +0000392 Action *A,
393 std::map<Action*, unsigned> &Ids) {
394 if (Ids.count(A))
395 return Ids[A];
396
397 std::string str;
398 llvm::raw_string_ostream os(str);
399
400 os << Action::getClassName(A->getKind()) << ", ";
401 if (InputAction *IA = dyn_cast<InputAction>(A)) {
Daniel Dunbar2b856ce2009-03-18 03:13:20 +0000402 os << "\"" << IA->getInputArg().getValue(C.getArgs()) << "\"";
Daniel Dunbar494646b2009-03-13 12:19:02 +0000403 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
Daniel Dunbar2b856ce2009-03-18 03:13:20 +0000404 os << '"' << (BIA->getArchName() ? BIA->getArchName() :
405 C.getDefaultToolChain().getArchName()) << '"'
406 << ", {" << PrintActions1(C, *BIA->begin(), Ids) << "}";
Daniel Dunbar494646b2009-03-13 12:19:02 +0000407 } else {
408 os << "{";
409 for (Action::iterator it = A->begin(), ie = A->end(); it != ie;) {
Daniel Dunbar2b856ce2009-03-18 03:13:20 +0000410 os << PrintActions1(C, *it, Ids);
Daniel Dunbar494646b2009-03-13 12:19:02 +0000411 ++it;
412 if (it != ie)
413 os << ", ";
414 }
415 os << "}";
416 }
417
418 unsigned Id = Ids.size();
419 Ids[A] = Id;
Daniel Dunbar9dc28b82009-03-13 17:20:20 +0000420 llvm::errs() << Id << ": " << os.str() << ", "
Daniel Dunbar494646b2009-03-13 12:19:02 +0000421 << types::getTypeName(A->getType()) << "\n";
422
423 return Id;
424}
425
Daniel Dunbar2b856ce2009-03-18 03:13:20 +0000426void Driver::PrintActions(const Compilation &C) const {
Daniel Dunbar494646b2009-03-13 12:19:02 +0000427 std::map<Action*, unsigned> Ids;
Daniel Dunbar2b856ce2009-03-18 03:13:20 +0000428 for (ActionList::const_iterator it = C.getActions().begin(),
429 ie = C.getActions().end(); it != ie; ++it)
430 PrintActions1(C, *it, Ids);
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000431}
432
Daniel Dunbar73f7b8c2009-03-18 02:55:38 +0000433void Driver::BuildUniversalActions(const ArgList &Args,
434 ActionList &Actions) const {
Daniel Dunbar16e04ff2009-03-18 01:38:48 +0000435 llvm::PrettyStackTraceString CrashInfo("Building actions for universal build");
Daniel Dunbarb1873cd2009-03-13 20:33:35 +0000436 // Collect the list of architectures. Duplicates are allowed, but
437 // should only be handled once (in the order seen).
438 llvm::StringSet<> ArchNames;
439 llvm::SmallVector<const char *, 4> Archs;
Daniel Dunbarfba157b2009-03-12 18:40:18 +0000440 for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
441 it != ie; ++it) {
442 Arg *A = *it;
443
444 if (A->getOption().getId() == options::OPT_arch) {
Daniel Dunbarb1873cd2009-03-13 20:33:35 +0000445 const char *Name = A->getValue(Args);
446
Daniel Dunbarfba157b2009-03-12 18:40:18 +0000447 // FIXME: We need to handle canonicalization of the specified
448 // arch?
449
Daniel Dunbara345a442009-03-19 07:55:12 +0000450 A->claim();
Daniel Dunbarb1873cd2009-03-13 20:33:35 +0000451 if (ArchNames.insert(Name))
452 Archs.push_back(Name);
Daniel Dunbarfba157b2009-03-12 18:40:18 +0000453 }
454 }
455
Daniel Dunbar2b856ce2009-03-18 03:13:20 +0000456 // When there is no explicit arch for this platform, make sure we
457 // still bind the architecture (to the default) so that -Xarch_ is
458 // handled correctly.
459 if (!Archs.size())
460 Archs.push_back(0);
Daniel Dunbarfba157b2009-03-12 18:40:18 +0000461
462 // FIXME: We killed off some others but these aren't yet detected in
463 // a functional manner. If we added information to jobs about which
464 // "auxiliary" files they wrote then we could detect the conflict
465 // these cause downstream.
466 if (Archs.size() > 1) {
467 // No recovery needed, the point of this is just to prevent
468 // overwriting the same files.
Daniel Dunbarfba157b2009-03-12 18:40:18 +0000469 if (const Arg *A = Args.getLastArg(options::OPT_save_temps))
470 Diag(clang::diag::err_drv_invalid_opt_with_multiple_archs)
Daniel Dunbar73225932009-03-20 06:14:23 +0000471 << A->getAsString(Args);
Daniel Dunbarfba157b2009-03-12 18:40:18 +0000472 }
473
474 ActionList SingleActions;
475 BuildActions(Args, SingleActions);
476
477 // Add in arch binding and lipo (if necessary) for every top level
478 // action.
479 for (unsigned i = 0, e = SingleActions.size(); i != e; ++i) {
480 Action *Act = SingleActions[i];
481
482 // Make sure we can lipo this kind of output. If not (and it is an
483 // actual output) then we disallow, since we can't create an
484 // output file with the right name without overwriting it. We
485 // could remove this oddity by just changing the output names to
486 // include the arch, which would also fix
487 // -save-temps. Compatibility wins for now.
488
Daniel Dunbardd863aa2009-03-13 17:46:02 +0000489 if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
Daniel Dunbarfba157b2009-03-12 18:40:18 +0000490 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
491 << types::getTypeName(Act->getType());
492
493 ActionList Inputs;
Daniel Dunbara345a442009-03-19 07:55:12 +0000494 for (unsigned i = 0, e = Archs.size(); i != e; ++i)
Daniel Dunbarb1873cd2009-03-13 20:33:35 +0000495 Inputs.push_back(new BindArchAction(Act, Archs[i]));
Daniel Dunbarfba157b2009-03-12 18:40:18 +0000496
497 // Lipo if necessary, We do it this way because we need to set the
498 // arch flag so that -Xarch_ gets overwritten.
499 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
500 Actions.append(Inputs.begin(), Inputs.end());
501 else
502 Actions.push_back(new LipoJobAction(Inputs, Act->getType()));
503 }
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000504}
505
Daniel Dunbar73f7b8c2009-03-18 02:55:38 +0000506void Driver::BuildActions(const ArgList &Args, ActionList &Actions) const {
Daniel Dunbar16e04ff2009-03-18 01:38:48 +0000507 llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
Daniel Dunbar207a56d2009-03-12 23:55:14 +0000508 // Start by constructing the list of inputs and their types.
509
Daniel Dunbar5cb75d62009-03-13 17:57:10 +0000510 // Track the current user specified (-x) input. We also explicitly
511 // track the argument used to set the type; we only want to claim
512 // the type when we actually use it, so we warn about unused -x
513 // arguments.
514 types::ID InputType = types::TY_Nothing;
515 Arg *InputTypeArg = 0;
516
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000517 llvm::SmallVector<std::pair<types::ID, const Arg*>, 16> Inputs;
518 for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
519 it != ie; ++it) {
520 Arg *A = *it;
521
522 if (isa<InputOption>(A->getOption())) {
523 const char *Value = A->getValue(Args);
524 types::ID Ty = types::TY_INVALID;
525
526 // Infer the input type if necessary.
Daniel Dunbar5cb75d62009-03-13 17:57:10 +0000527 if (InputType == types::TY_Nothing) {
528 // If there was an explicit arg for this, claim it.
529 if (InputTypeArg)
530 InputTypeArg->claim();
531
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000532 // stdin must be handled specially.
533 if (memcmp(Value, "-", 2) == 0) {
534 // If running with -E, treat as a C input (this changes the
535 // builtin macros, for example). This may be overridden by
536 // -ObjC below.
537 //
538 // Otherwise emit an error but still use a valid type to
539 // avoid spurious errors (e.g., no inputs).
Daniel Dunbare9c70fa2009-03-15 00:48:16 +0000540 if (!Args.hasArg(options::OPT_E, false))
Daniel Dunbard724e332009-03-12 09:13:48 +0000541 Diag(clang::diag::err_drv_unknown_stdin_type);
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000542 Ty = types::TY_C;
543 } else {
544 // Otherwise lookup by extension, and fallback to ObjectType
Daniel Dunbar7b6dfbd2009-03-20 23:39:23 +0000545 // if not found. We use a host hook here because Darwin at
546 // least has its own idea of what .s is.
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000547 if (const char *Ext = strrchr(Value, '.'))
Daniel Dunbar7b6dfbd2009-03-20 23:39:23 +0000548 Ty = Host->lookupTypeForExtension(Ext + 1);
549
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000550 if (Ty == types::TY_INVALID)
551 Ty = types::TY_Object;
552 }
553
554 // -ObjC and -ObjC++ override the default language, but only
555 // -for "source files". We just treat everything that isn't a
556 // -linker input as a source file.
557 //
558 // FIXME: Clean this up if we move the phase sequence into the
559 // type.
560 if (Ty != types::TY_Object) {
561 if (Args.hasArg(options::OPT_ObjC))
562 Ty = types::TY_ObjC;
563 else if (Args.hasArg(options::OPT_ObjCXX))
564 Ty = types::TY_ObjCXX;
565 }
566 } else {
567 assert(InputTypeArg && "InputType set w/o InputTypeArg");
568 InputTypeArg->claim();
569 Ty = InputType;
570 }
571
572 // Check that the file exists. It isn't clear this is worth
573 // doing, since the tool presumably does this anyway, and this
574 // just adds an extra stat to the equation, but this is gcc
575 // compatible.
576 if (memcmp(Value, "-", 2) != 0 && !llvm::sys::Path(Value).exists())
Daniel Dunbard724e332009-03-12 09:13:48 +0000577 Diag(clang::diag::err_drv_no_such_file) << A->getValue(Args);
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000578 else
579 Inputs.push_back(std::make_pair(Ty, A));
580
581 } else if (A->getOption().isLinkerInput()) {
582 // Just treat as object type, we could make a special type for
583 // this if necessary.
584 Inputs.push_back(std::make_pair(types::TY_Object, A));
585
586 } else if (A->getOption().getId() == options::OPT_x) {
587 InputTypeArg = A;
588 InputType = types::lookupTypeForTypeSpecifier(A->getValue(Args));
589
590 // Follow gcc behavior and treat as linker input for invalid -x
591 // options. Its not clear why we shouldn't just revert to
592 // unknown; but this isn't very important, we might as well be
593 // bug comatible.
594 if (!InputType) {
Daniel Dunbard724e332009-03-12 09:13:48 +0000595 Diag(clang::diag::err_drv_unknown_language) << A->getValue(Args);
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000596 InputType = types::TY_Object;
597 }
598 }
599 }
600
Daniel Dunbar5a5ec5c2009-03-13 00:17:48 +0000601 if (!SuppressMissingInputWarning && Inputs.empty()) {
Daniel Dunbar207a56d2009-03-12 23:55:14 +0000602 Diag(clang::diag::err_drv_no_input_files);
603 return;
604 }
605
606 // Determine which compilation mode we are in. We look for options
607 // which affect the phase, starting with the earliest phases, and
608 // record which option we used to determine the final phase.
Daniel Dunbar85cb3592009-03-13 11:38:42 +0000609 Arg *FinalPhaseArg = 0;
610 phases::ID FinalPhase;
Daniel Dunbar207a56d2009-03-12 23:55:14 +0000611
612 // -{E,M,MM} only run the preprocessor.
Daniel Dunbar85cb3592009-03-13 11:38:42 +0000613 if ((FinalPhaseArg = Args.getLastArg(options::OPT_E)) ||
614 (FinalPhaseArg = Args.getLastArg(options::OPT_M)) ||
615 (FinalPhaseArg = Args.getLastArg(options::OPT_MM))) {
616 FinalPhase = phases::Preprocess;
Daniel Dunbar207a56d2009-03-12 23:55:14 +0000617
Daniel Dunbare9c70fa2009-03-15 00:48:16 +0000618 // -{fsyntax-only,-analyze,emit-llvm,S} only run up to the compiler.
619 } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_fsyntax_only)) ||
620 (FinalPhaseArg = Args.getLastArg(options::OPT__analyze)) ||
Daniel Dunbar85cb3592009-03-13 11:38:42 +0000621 (FinalPhaseArg = Args.getLastArg(options::OPT_S))) {
622 FinalPhase = phases::Compile;
Daniel Dunbar207a56d2009-03-12 23:55:14 +0000623
624 // -c only runs up to the assembler.
Daniel Dunbar85cb3592009-03-13 11:38:42 +0000625 } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_c))) {
626 FinalPhase = phases::Assemble;
Daniel Dunbar207a56d2009-03-12 23:55:14 +0000627
628 // Otherwise do everything.
629 } else
Daniel Dunbar85cb3592009-03-13 11:38:42 +0000630 FinalPhase = phases::Link;
Daniel Dunbar207a56d2009-03-12 23:55:14 +0000631
Daniel Dunbar207a56d2009-03-12 23:55:14 +0000632 // Reject -Z* at the top level, these options should never have been
633 // exposed by gcc.
Daniel Dunbar55e34e32009-03-26 16:12:09 +0000634 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
Daniel Dunbar73225932009-03-20 06:14:23 +0000635 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
Daniel Dunbar207a56d2009-03-12 23:55:14 +0000636
Daniel Dunbar85cb3592009-03-13 11:38:42 +0000637 // Construct the actions to perform.
638 ActionList LinkerInputs;
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000639 for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
Daniel Dunbar85cb3592009-03-13 11:38:42 +0000640 types::ID InputType = Inputs[i].first;
641 const Arg *InputArg = Inputs[i].second;
642
643 unsigned NumSteps = types::getNumCompilationPhases(InputType);
644 assert(NumSteps && "Invalid number of steps!");
645
646 // If the first step comes after the final phase we are doing as
647 // part of this compilation, warn the user about it.
648 phases::ID InitialPhase = types::getCompilationPhase(InputType, 0);
649 if (InitialPhase > FinalPhase) {
Daniel Dunbar923e7032009-03-19 07:57:08 +0000650 // Claim here to avoid the more general unused warning.
651 InputArg->claim();
Daniel Dunbar85cb3592009-03-13 11:38:42 +0000652 Diag(clang::diag::warn_drv_input_file_unused)
Daniel Dunbar73225932009-03-20 06:14:23 +0000653 << InputArg->getAsString(Args)
Daniel Dunbar85cb3592009-03-13 11:38:42 +0000654 << getPhaseName(InitialPhase)
655 << FinalPhaseArg->getOption().getName();
656 continue;
657 }
658
659 // Build the pipeline for this file.
660 Action *Current = new InputAction(*InputArg, InputType);
661 for (unsigned i = 0; i != NumSteps; ++i) {
662 phases::ID Phase = types::getCompilationPhase(InputType, i);
663
664 // We are done if this step is past what the user requested.
665 if (Phase > FinalPhase)
666 break;
667
668 // Queue linker inputs.
669 if (Phase == phases::Link) {
670 assert(i + 1 == NumSteps && "linking must be final compilation step.");
671 LinkerInputs.push_back(Current);
672 Current = 0;
673 break;
674 }
675
Daniel Dunbardec14452009-03-24 20:17:30 +0000676 // Some types skip the assembler phase (e.g., llvm-bc), but we
677 // can't encode this in the steps because the intermediate type
678 // depends on arguments. Just special case here.
679 if (Phase == phases::Assemble && Current->getType() != types::TY_PP_Asm)
680 continue;
681
Daniel Dunbar85cb3592009-03-13 11:38:42 +0000682 // Otherwise construct the appropriate action.
683 Current = ConstructPhaseAction(Args, Phase, Current);
684 if (Current->getType() == types::TY_Nothing)
685 break;
686 }
687
688 // If we ended with something, add to the output list.
689 if (Current)
690 Actions.push_back(Current);
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000691 }
Daniel Dunbar85cb3592009-03-13 11:38:42 +0000692
693 // Add a link action if necessary.
694 if (!LinkerInputs.empty())
695 Actions.push_back(new LinkJobAction(LinkerInputs, types::TY_Image));
696}
697
698Action *Driver::ConstructPhaseAction(const ArgList &Args, phases::ID Phase,
699 Action *Input) const {
Daniel Dunbar16e04ff2009-03-18 01:38:48 +0000700 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
Daniel Dunbar85cb3592009-03-13 11:38:42 +0000701 // Build the appropriate action.
702 switch (Phase) {
703 case phases::Link: assert(0 && "link action invalid here.");
704 case phases::Preprocess: {
Daniel Dunbar049b7242009-03-30 06:36:42 +0000705 types::ID OutputTy;
706 // -{M, MM} alter the output type.
707 if (Args.hasArg(options::OPT_M) || Args.hasArg(options::OPT_MM)) {
708 OutputTy = types::TY_Dependencies;
709 } else {
710 OutputTy = types::getPreprocessedType(Input->getType());
711 assert(OutputTy != types::TY_INVALID &&
712 "Cannot preprocess this input type!");
713 }
Daniel Dunbar85cb3592009-03-13 11:38:42 +0000714 return new PreprocessJobAction(Input, OutputTy);
715 }
716 case phases::Precompile:
717 return new PrecompileJobAction(Input, types::TY_PCH);
718 case phases::Compile: {
719 if (Args.hasArg(options::OPT_fsyntax_only)) {
720 return new CompileJobAction(Input, types::TY_Nothing);
721 } else if (Args.hasArg(options::OPT__analyze)) {
722 return new AnalyzeJobAction(Input, types::TY_Plist);
Daniel Dunbardec14452009-03-24 20:17:30 +0000723 } else if (Args.hasArg(options::OPT_emit_llvm) ||
724 Args.hasArg(options::OPT_flto) ||
725 Args.hasArg(options::OPT_O4)) {
Daniel Dunbar85cb3592009-03-13 11:38:42 +0000726 types::ID Output =
727 Args.hasArg(options::OPT_S) ? types::TY_LLVMAsm : types::TY_LLVMBC;
728 return new CompileJobAction(Input, Output);
729 } else {
730 return new CompileJobAction(Input, types::TY_PP_Asm);
731 }
732 }
733 case phases::Assemble:
734 return new AssembleJobAction(Input, types::TY_Object);
735 }
736
737 assert(0 && "invalid phase in ConstructPhaseAction");
738 return 0;
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000739}
740
Daniel Dunbar73f7b8c2009-03-18 02:55:38 +0000741void Driver::BuildJobs(Compilation &C) const {
Daniel Dunbar16e04ff2009-03-18 01:38:48 +0000742 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
Daniel Dunbar7ce6add2009-03-16 06:56:51 +0000743 bool SaveTemps = C.getArgs().hasArg(options::OPT_save_temps);
744 bool UsePipes = C.getArgs().hasArg(options::OPT_pipe);
Daniel Dunbarbac6b642009-03-18 23:18:19 +0000745
746 // FIXME: Pipes are forcibly disabled until we support executing
747 // them.
748 if (!CCCPrintBindings)
749 UsePipes = false;
Daniel Dunbar7ce6add2009-03-16 06:56:51 +0000750
751 // -save-temps inhibits pipes.
752 if (SaveTemps && UsePipes) {
753 Diag(clang::diag::warn_drv_pipe_ignored_with_save_temps);
754 UsePipes = true;
755 }
756
757 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
758
759 // It is an error to provide a -o option if we are making multiple
760 // output files.
761 if (FinalOutput) {
762 unsigned NumOutputs = 0;
Daniel Dunbar73f7b8c2009-03-18 02:55:38 +0000763 for (ActionList::const_iterator it = C.getActions().begin(),
764 ie = C.getActions().end(); it != ie; ++it)
Daniel Dunbar7ce6add2009-03-16 06:56:51 +0000765 if ((*it)->getType() != types::TY_Nothing)
766 ++NumOutputs;
767
768 if (NumOutputs > 1) {
769 Diag(clang::diag::err_drv_output_argument_with_multiple_files);
770 FinalOutput = 0;
771 }
772 }
773
Daniel Dunbar73f7b8c2009-03-18 02:55:38 +0000774 for (ActionList::const_iterator it = C.getActions().begin(),
775 ie = C.getActions().end(); it != ie; ++it) {
Daniel Dunbar7ce6add2009-03-16 06:56:51 +0000776 Action *A = *it;
777
778 // If we are linking an image for multiple archs then the linker
779 // wants -arch_multiple and -final_output <final image
780 // name>. Unfortunately, this doesn't fit in cleanly because we
781 // have to pass this information down.
782 //
783 // FIXME: This is a hack; find a cleaner way to integrate this
784 // into the process.
785 const char *LinkingOutput = 0;
Daniel Dunbar55e34e32009-03-26 16:12:09 +0000786 if (isa<LipoJobAction>(A)) {
Daniel Dunbar7ce6add2009-03-16 06:56:51 +0000787 if (FinalOutput)
788 LinkingOutput = FinalOutput->getValue(C.getArgs());
789 else
790 LinkingOutput = DefaultImageName.c_str();
791 }
792
793 InputInfo II;
Daniel Dunbar2b856ce2009-03-18 03:13:20 +0000794 BuildJobsForAction(C, A, &C.getDefaultToolChain(),
Daniel Dunbar7ce6add2009-03-16 06:56:51 +0000795 /*CanAcceptPipe*/ true,
796 /*AtTopLevel*/ true,
797 /*LinkingOutput*/ LinkingOutput,
798 II);
799 }
Daniel Dunbar9d625e12009-03-16 06:42:30 +0000800
Daniel Dunbar025de202009-04-03 22:09:23 +0000801 // If the user passed -Qunused-arguments or there were errors, don't
802 // warn about any unused arguments.
Daniel Dunbar1cfd8912009-04-07 19:04:18 +0000803 if (Diags.getNumErrors() ||
804 C.getArgs().hasArg(options::OPT_Qunused_arguments))
Daniel Dunbar46c70822009-03-18 18:03:46 +0000805 return;
806
Daniel Dunbar1e6f9ff2009-03-29 22:24:54 +0000807 // Claim -### here.
808 (void) C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
809
Daniel Dunbar9d625e12009-03-16 06:42:30 +0000810 for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
811 it != ie; ++it) {
812 Arg *A = *it;
Daniel Dunbar46c70822009-03-18 18:03:46 +0000813
Daniel Dunbar9d625e12009-03-16 06:42:30 +0000814 // FIXME: It would be nice to be able to send the argument to the
815 // Diagnostic, so that extra values, position, and so on could be
816 // printed.
Daniel Dunbar6c6e3f72009-04-04 00:52:26 +0000817 if (!A->isClaimed()) {
Daniel Dunbar1cfd8912009-04-07 19:04:18 +0000818 if (A->getOption().hasNoArgumentUnused())
819 continue;
820
Daniel Dunbar6c6e3f72009-04-04 00:52:26 +0000821 // Suppress the warning automatically if this is just a flag,
822 // and it is an instance of an argument we already claimed.
823 const Option &Opt = A->getOption();
824 if (isa<FlagOption>(Opt)) {
825 bool DuplicateClaimed = false;
826
827 // FIXME: Use iterator.
828 for (ArgList::const_iterator it = C.getArgs().begin(),
829 ie = C.getArgs().end(); it != ie; ++it) {
830 if ((*it)->isClaimed() && (*it)->getOption().matches(Opt.getId())) {
831 DuplicateClaimed = true;
832 break;
833 }
834 }
835
836 if (DuplicateClaimed)
837 continue;
838 }
839
Daniel Dunbar9d625e12009-03-16 06:42:30 +0000840 Diag(clang::diag::warn_drv_unused_argument)
Daniel Dunbar73225932009-03-20 06:14:23 +0000841 << A->getAsString(C.getArgs());
Daniel Dunbar6c6e3f72009-04-04 00:52:26 +0000842 }
Daniel Dunbar9d625e12009-03-16 06:42:30 +0000843 }
Daniel Dunbar47d762e2009-03-13 22:12:33 +0000844}
845
Daniel Dunbar7ce6add2009-03-16 06:56:51 +0000846void Driver::BuildJobsForAction(Compilation &C,
847 const Action *A,
848 const ToolChain *TC,
849 bool CanAcceptPipe,
850 bool AtTopLevel,
851 const char *LinkingOutput,
852 InputInfo &Result) const {
Daniel Dunbar16e04ff2009-03-18 01:38:48 +0000853 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs for action");
Daniel Dunbarbac6b642009-03-18 23:18:19 +0000854
855 bool UsePipes = C.getArgs().hasArg(options::OPT_pipe);
856 // FIXME: Pipes are forcibly disabled until we support executing
857 // them.
858 if (!CCCPrintBindings)
859 UsePipes = false;
860
Daniel Dunbar7ce6add2009-03-16 06:56:51 +0000861 if (const InputAction *IA = dyn_cast<InputAction>(A)) {
Daniel Dunbarc3be67b2009-03-19 07:29:38 +0000862 // FIXME: It would be nice to not claim this here; maybe the old
863 // scheme of just using Args was better?
864 const Arg &Input = IA->getInputArg();
865 Input.claim();
866 if (isa<PositionalArg>(Input)) {
867 const char *Name = Input.getValue(C.getArgs());
868 Result = InputInfo(Name, A->getType(), Name);
869 } else
870 Result = InputInfo(&Input, A->getType(), "");
Daniel Dunbar7ce6add2009-03-16 06:56:51 +0000871 return;
872 }
873
874 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
875 const char *ArchName = BAA->getArchName();
Daniel Dunbar2b856ce2009-03-18 03:13:20 +0000876 if (!ArchName)
877 ArchName = C.getDefaultToolChain().getArchName().c_str();
Daniel Dunbar7ce6add2009-03-16 06:56:51 +0000878 BuildJobsForAction(C,
879 *BAA->begin(),
880 Host->getToolChain(C.getArgs(), ArchName),
881 CanAcceptPipe,
882 AtTopLevel,
883 LinkingOutput,
884 Result);
885 return;
886 }
887
888 const JobAction *JA = cast<JobAction>(A);
889 const Tool &T = TC->SelectTool(C, *JA);
890
891 // See if we should use an integrated preprocessor. We do so when we
892 // have exactly one input, since this is the only use case we care
893 // about (irrelevant since we don't support combine yet).
894 bool UseIntegratedCPP = false;
895 const ActionList *Inputs = &A->getInputs();
896 if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin())) {
897 if (!C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
898 !C.getArgs().hasArg(options::OPT_traditional_cpp) &&
899 !C.getArgs().hasArg(options::OPT_save_temps) &&
900 T.hasIntegratedCPP()) {
901 UseIntegratedCPP = true;
902 Inputs = &(*Inputs)[0]->getInputs();
903 }
904 }
905
906 // Only use pipes when there is exactly one input.
907 bool TryToUsePipeInput = Inputs->size() == 1 && T.acceptsPipedInput();
Daniel Dunbar00fd3792009-03-18 06:00:36 +0000908 InputInfoList InputInfos;
Daniel Dunbar7ce6add2009-03-16 06:56:51 +0000909 for (ActionList::const_iterator it = Inputs->begin(), ie = Inputs->end();
910 it != ie; ++it) {
911 InputInfo II;
912 BuildJobsForAction(C, *it, TC, TryToUsePipeInput,
913 /*AtTopLevel*/false,
914 LinkingOutput,
915 II);
916 InputInfos.push_back(II);
917 }
918
919 // Determine if we should output to a pipe.
920 bool OutputToPipe = false;
921 if (CanAcceptPipe && T.canPipeOutput()) {
922 // Some actions default to writing to a pipe if they are the top
923 // level phase and there was no user override.
924 //
925 // FIXME: Is there a better way to handle this?
926 if (AtTopLevel) {
927 if (isa<PreprocessJobAction>(A) && !C.getArgs().hasArg(options::OPT_o))
928 OutputToPipe = true;
Daniel Dunbarbac6b642009-03-18 23:18:19 +0000929 } else if (UsePipes)
Daniel Dunbar7ce6add2009-03-16 06:56:51 +0000930 OutputToPipe = true;
931 }
932
933 // Figure out where to put the job (pipes).
934 Job *Dest = &C.getJobs();
935 if (InputInfos[0].isPipe()) {
Daniel Dunbar01fb26a2009-03-17 17:53:55 +0000936 assert(TryToUsePipeInput && "Unrequested pipe!");
Daniel Dunbar7ce6add2009-03-16 06:56:51 +0000937 assert(InputInfos.size() == 1 && "Unexpected pipe with multiple inputs.");
938 Dest = &InputInfos[0].getPipe();
939 }
940
941 // Always use the first input as the base input.
942 const char *BaseInput = InputInfos[0].getBaseInput();
Daniel Dunbar01fb26a2009-03-17 17:53:55 +0000943
944 // Determine the place to write output to (nothing, pipe, or
945 // filename) and where to put the new job.
Daniel Dunbar01fb26a2009-03-17 17:53:55 +0000946 if (JA->getType() == types::TY_Nothing) {
Daniel Dunbar07c9a1d2009-03-17 22:47:06 +0000947 Result = InputInfo(A->getType(), BaseInput);
Daniel Dunbar01fb26a2009-03-17 17:53:55 +0000948 } else if (OutputToPipe) {
949 // Append to current piped job or create a new one as appropriate.
Daniel Dunbar07c9a1d2009-03-17 22:47:06 +0000950 PipedJob *PJ = dyn_cast<PipedJob>(Dest);
951 if (!PJ) {
952 PJ = new PipedJob();
Daniel Dunbar8eeb5a32009-03-20 00:11:04 +0000953 // FIXME: Temporary hack so that -ccc-print-bindings work until
954 // we have pipe support. Please remove later.
955 if (!CCCPrintBindings)
956 cast<JobList>(Dest)->addJob(PJ);
Daniel Dunbar933ac452009-03-18 07:06:02 +0000957 Dest = PJ;
Daniel Dunbar01fb26a2009-03-17 17:53:55 +0000958 }
Daniel Dunbar07c9a1d2009-03-17 22:47:06 +0000959 Result = InputInfo(PJ, A->getType(), BaseInput);
Daniel Dunbar01fb26a2009-03-17 17:53:55 +0000960 } else {
Daniel Dunbar07c9a1d2009-03-17 22:47:06 +0000961 Result = InputInfo(GetNamedOutputPath(C, *JA, BaseInput, AtTopLevel),
962 A->getType(), BaseInput);
Daniel Dunbar01fb26a2009-03-17 17:53:55 +0000963 }
964
Daniel Dunbar07c9a1d2009-03-17 22:47:06 +0000965 if (CCCPrintBindings) {
Daniel Dunbar049b7242009-03-30 06:36:42 +0000966 llvm::errs() << "# \"" << T.getToolChain().getTripleString() << '"'
967 << " - \"" << T.getName() << "\", inputs: [";
Daniel Dunbar07c9a1d2009-03-17 22:47:06 +0000968 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
969 llvm::errs() << InputInfos[i].getAsString();
970 if (i + 1 != e)
971 llvm::errs() << ", ";
972 }
973 llvm::errs() << "], output: " << Result.getAsString() << "\n";
974 } else {
Daniel Dunbara16e4fe2009-03-25 04:13:45 +0000975 T.ConstructJob(C, *JA, *Dest, Result, InputInfos,
976 C.getArgsForToolChain(TC), LinkingOutput);
Daniel Dunbar07c9a1d2009-03-17 22:47:06 +0000977 }
Daniel Dunbar7ce6add2009-03-16 06:56:51 +0000978}
979
Daniel Dunbar01fb26a2009-03-17 17:53:55 +0000980const char *Driver::GetNamedOutputPath(Compilation &C,
981 const JobAction &JA,
982 const char *BaseInput,
983 bool AtTopLevel) const {
Daniel Dunbar16e04ff2009-03-18 01:38:48 +0000984 llvm::PrettyStackTraceString CrashInfo("Computing output path");
Daniel Dunbar01fb26a2009-03-17 17:53:55 +0000985 // Output to a user requested destination?
986 if (AtTopLevel) {
987 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
988 return C.addResultFile(FinalOutput->getValue(C.getArgs()));
989 }
990
991 // Output to a temporary file?
992 if (!AtTopLevel && !C.getArgs().hasArg(options::OPT_save_temps)) {
Daniel Dunbarb6ddc952009-03-18 19:34:39 +0000993 std::string TmpName =
994 GetTemporaryPath(types::getTypeTempSuffix(JA.getType()));
995 return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
Daniel Dunbar01fb26a2009-03-17 17:53:55 +0000996 }
997
998 llvm::sys::Path BasePath(BaseInput);
Daniel Dunbarfb5e3332009-03-18 02:00:31 +0000999 std::string BaseName(BasePath.getLast());
Daniel Dunbar01fb26a2009-03-17 17:53:55 +00001000
1001 // Determine what the derived output name should be.
1002 const char *NamedOutput;
1003 if (JA.getType() == types::TY_Image) {
1004 NamedOutput = DefaultImageName.c_str();
1005 } else {
1006 const char *Suffix = types::getTypeTempSuffix(JA.getType());
1007 assert(Suffix && "All types used for output should have a suffix.");
1008
1009 std::string::size_type End = std::string::npos;
1010 if (!types::appendSuffixForType(JA.getType()))
1011 End = BaseName.rfind('.');
1012 std::string Suffixed(BaseName.substr(0, End));
1013 Suffixed += '.';
1014 Suffixed += Suffix;
1015 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
1016 }
1017
1018 // As an annoying special case, PCH generation doesn't strip the
1019 // pathname.
1020 if (JA.getType() == types::TY_PCH) {
1021 BasePath.eraseComponent();
Daniel Dunbar58a51262009-03-18 09:58:30 +00001022 if (BasePath.isEmpty())
1023 BasePath = NamedOutput;
1024 else
1025 BasePath.appendComponent(NamedOutput);
Daniel Dunbar01fb26a2009-03-17 17:53:55 +00001026 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()));
1027 } else {
1028 return C.addResultFile(NamedOutput);
1029 }
1030}
1031
Daniel Dunbare1cef7d2009-03-16 05:25:36 +00001032llvm::sys::Path Driver::GetFilePath(const char *Name,
Daniel Dunbar73f7b8c2009-03-18 02:55:38 +00001033 const ToolChain &TC) const {
Daniel Dunbarcc7600c2009-03-18 20:26:19 +00001034 const ToolChain::path_list &List = TC.getFilePaths();
1035 for (ToolChain::path_list::const_iterator
1036 it = List.begin(), ie = List.end(); it != ie; ++it) {
1037 llvm::sys::Path P(*it);
1038 P.appendComponent(Name);
1039 if (P.exists())
1040 return P;
1041 }
1042
Daniel Dunbarcc006892009-03-13 00:51:18 +00001043 return llvm::sys::Path(Name);
1044}
1045
Daniel Dunbare1cef7d2009-03-16 05:25:36 +00001046llvm::sys::Path Driver::GetProgramPath(const char *Name,
Mike Stump32b1bbe2009-03-27 00:40:20 +00001047 const ToolChain &TC,
1048 bool WantFile) const {
Daniel Dunbarcc7600c2009-03-18 20:26:19 +00001049 const ToolChain::path_list &List = TC.getProgramPaths();
1050 for (ToolChain::path_list::const_iterator
1051 it = List.begin(), ie = List.end(); it != ie; ++it) {
1052 llvm::sys::Path P(*it);
1053 P.appendComponent(Name);
Mike Stump32b1bbe2009-03-27 00:40:20 +00001054 if (WantFile ? P.exists() : P.canExecute())
Daniel Dunbarcc7600c2009-03-18 20:26:19 +00001055 return P;
1056 }
1057
Daniel Dunbar49a35de2009-03-23 16:15:50 +00001058 // If all else failed, search the path.
1059 llvm::sys::Path P(llvm::sys::Program::FindProgramByName(Name));
Daniel Dunbarcb84b9a2009-03-18 21:34:08 +00001060 if (!P.empty())
1061 return P;
1062
Daniel Dunbarcc006892009-03-13 00:51:18 +00001063 return llvm::sys::Path(Name);
1064}
1065
Daniel Dunbarb6ddc952009-03-18 19:34:39 +00001066std::string Driver::GetTemporaryPath(const char *Suffix) const {
1067 // FIXME: This is lame; sys::Path should provide this function (in
1068 // particular, it should know how to find the temporary files dir).
1069 std::string Error;
1070 llvm::sys::Path P("/tmp/cc");
1071 if (P.makeUnique(false, &Error)) {
1072 Diag(clang::diag::err_drv_unable_to_make_temp) << Error;
1073 return "";
1074 }
1075
Daniel Dunbar9083abe2009-03-18 23:08:52 +00001076 // FIXME: Grumble, makeUnique sometimes leaves the file around!?
1077 // PR3837.
1078 P.eraseFromDisk(false, 0);
1079
Daniel Dunbarb6ddc952009-03-18 19:34:39 +00001080 P.appendSuffix(Suffix);
1081 return P.toString();
1082}
1083
Daniel Dunbar08966ca2009-03-17 20:45:45 +00001084const HostInfo *Driver::GetHostInfo(const char *Triple) const {
Daniel Dunbar16e04ff2009-03-18 01:38:48 +00001085 llvm::PrettyStackTraceString CrashInfo("Constructing host");
Daniel Dunbard25acaa2009-03-10 23:41:59 +00001086 // Dice into arch, platform, and OS. This matches
1087 // arch,platform,os = '(.*?)-(.*?)-(.*?)'
1088 // and missing fields are left empty.
1089 std::string Arch, Platform, OS;
1090
1091 if (const char *ArchEnd = strchr(Triple, '-')) {
1092 Arch = std::string(Triple, ArchEnd);
1093
1094 if (const char *PlatformEnd = strchr(ArchEnd+1, '-')) {
1095 Platform = std::string(ArchEnd+1, PlatformEnd);
1096 OS = PlatformEnd+1;
1097 } else
1098 Platform = ArchEnd+1;
1099 } else
1100 Arch = Triple;
1101
Daniel Dunbar7424b8a2009-03-17 19:00:50 +00001102 // Normalize Arch a bit.
1103 //
1104 // FIXME: This is very incomplete.
1105 if (Arch == "i686")
1106 Arch = "i386";
1107 else if (Arch == "amd64")
1108 Arch = "x86_64";
Daniel Dunbarb7daa2d2009-04-01 20:33:11 +00001109 else if (Arch == "ppc" || Arch == "Power Macintosh")
1110 Arch = "powerpc";
1111 else if (Arch == "ppc64")
1112 Arch = "powerpc64";
Daniel Dunbar7424b8a2009-03-17 19:00:50 +00001113
Daniel Dunbar44119a12009-03-13 12:23:29 +00001114 if (memcmp(&OS[0], "darwin", 6) == 0)
Daniel Dunbar08966ca2009-03-17 20:45:45 +00001115 return createDarwinHostInfo(*this, Arch.c_str(), Platform.c_str(),
1116 OS.c_str());
Daniel Dunbar606f6142009-03-30 21:06:03 +00001117 if (memcmp(&OS[0], "freebsd", 7) == 0)
1118 return createFreeBSDHostInfo(*this, Arch.c_str(), Platform.c_str(),
1119 OS.c_str());
Daniel Dunbard25acaa2009-03-10 23:41:59 +00001120
Daniel Dunbar08966ca2009-03-17 20:45:45 +00001121 return createUnknownHostInfo(*this, Arch.c_str(), Platform.c_str(),
1122 OS.c_str());
Daniel Dunbard25acaa2009-03-10 23:41:59 +00001123}
Daniel Dunbar1a9c8ca2009-03-24 18:57:02 +00001124
1125bool Driver::ShouldUseClangCompiler(const Compilation &C, const JobAction &JA,
Daniel Dunbarb7daa2d2009-04-01 20:33:11 +00001126 const std::string &ArchNameStr) const {
1127 // FIXME: Remove this hack.
1128 const char *ArchName = ArchNameStr.c_str();
1129 if (ArchNameStr == "powerpc")
1130 ArchName = "ppc";
1131 else if (ArchNameStr == "powerpc64")
1132 ArchName = "ppc64";
1133
Daniel Dunbar1a9c8ca2009-03-24 18:57:02 +00001134 // Check if user requested no clang, or clang doesn't understand
1135 // this type (we only handle single inputs for now).
Daniel Dunbar0ea85f72009-03-24 19:02:31 +00001136 if (!CCCUseClang || JA.size() != 1 ||
Daniel Dunbar1a9c8ca2009-03-24 18:57:02 +00001137 !types::isAcceptedByClang((*JA.begin())->getType()))
1138 return false;
1139
Daniel Dunbar0ea85f72009-03-24 19:02:31 +00001140 // Otherwise make sure this is an action clang understands.
Daniel Dunbar1a9c8ca2009-03-24 18:57:02 +00001141 if (isa<PreprocessJobAction>(JA)) {
Daniel Dunbarb1ae14d2009-03-24 19:14:56 +00001142 if (!CCCUseClangCPP) {
1143 Diag(clang::diag::warn_drv_not_using_clang_cpp);
Daniel Dunbar1a9c8ca2009-03-24 18:57:02 +00001144 return false;
Daniel Dunbarb1ae14d2009-03-24 19:14:56 +00001145 }
Daniel Dunbar1a9c8ca2009-03-24 18:57:02 +00001146 } else if (!isa<PrecompileJobAction>(JA) && !isa<CompileJobAction>(JA))
1147 return false;
1148
Daniel Dunbar0ea85f72009-03-24 19:02:31 +00001149 // Use clang for C++?
Daniel Dunbarb1ae14d2009-03-24 19:14:56 +00001150 if (!CCCUseClangCXX && types::isCXX((*JA.begin())->getType())) {
1151 Diag(clang::diag::warn_drv_not_using_clang_cxx);
Daniel Dunbar1a9c8ca2009-03-24 18:57:02 +00001152 return false;
Daniel Dunbarb1ae14d2009-03-24 19:14:56 +00001153 }
Daniel Dunbar1a9c8ca2009-03-24 18:57:02 +00001154
1155 // Finally, don't use clang if this isn't one of the user specified
1156 // archs to build.
Daniel Dunbarb1ae14d2009-03-24 19:14:56 +00001157 if (!CCCClangArchs.empty() && !CCCClangArchs.count(ArchName)) {
1158 Diag(clang::diag::warn_drv_not_using_clang_arch) << ArchName;
Daniel Dunbar1a9c8ca2009-03-24 18:57:02 +00001159 return false;
Daniel Dunbarb1ae14d2009-03-24 19:14:56 +00001160 }
Daniel Dunbar1a9c8ca2009-03-24 18:57:02 +00001161
1162 return true;
1163}
Daniel Dunbar9cdd4d42009-03-26 15:58:36 +00001164
1165/// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and
1166/// return the grouped values as integers. Numbers which are not
1167/// provided are set to 0.
1168///
1169/// \return True if the entire string was parsed (9.2), or all groups
1170/// were parsed (10.3.5extrastuff).
1171bool Driver::GetReleaseVersion(const char *Str, unsigned &Major,
1172 unsigned &Minor, unsigned &Micro,
1173 bool &HadExtra) {
1174 HadExtra = false;
1175
1176 Major = Minor = Micro = 0;
1177 if (*Str == '\0')
1178 return true;
1179
1180 char *End;
1181 Major = (unsigned) strtol(Str, &End, 10);
1182 if (*Str != '\0' && *End == '\0')
1183 return true;
1184 if (*End != '.')
1185 return false;
1186
1187 Str = End+1;
1188 Minor = (unsigned) strtol(Str, &End, 10);
1189 if (*Str != '\0' && *End == '\0')
1190 return true;
1191 if (*End != '.')
1192 return false;
1193
1194 Str = End+1;
1195 Micro = (unsigned) strtol(Str, &End, 10);
1196 if (*Str != '\0' && *End == '\0')
1197 return true;
1198 if (Str == End)
1199 return false;
1200 HadExtra = true;
1201 return true;
1202}