blob: f60271c02e03eb98665bd08b23e2b4180a99330e [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 Dunbar494646b2009-03-13 12:19:02 +000029
Daniel Dunbar7ce6add2009-03-16 06:56:51 +000030#include "InputInfo.h"
31
Daniel Dunbar494646b2009-03-13 12:19:02 +000032#include <map>
33
Daniel Dunbard6f0e372009-03-04 20:49:20 +000034using namespace clang::driver;
35
Daniel Dunbard25acaa2009-03-10 23:41:59 +000036Driver::Driver(const char *_Name, const char *_Dir,
Daniel Dunbar93468492009-03-12 08:55:43 +000037 const char *_DefaultHostTriple,
Daniel Dunbar7ce6add2009-03-16 06:56:51 +000038 const char *_DefaultImageName,
Daniel Dunbar93468492009-03-12 08:55:43 +000039 Diagnostic &_Diags)
40 : Opts(new OptTable()), Diags(_Diags),
Daniel Dunbard25acaa2009-03-10 23:41:59 +000041 Name(_Name), Dir(_Dir), DefaultHostTriple(_DefaultHostTriple),
Daniel Dunbar7ce6add2009-03-16 06:56:51 +000042 DefaultImageName(_DefaultImageName),
Daniel Dunbard25acaa2009-03-10 23:41:59 +000043 Host(0),
Daniel Dunbar07c9a1d2009-03-17 22:47:06 +000044 CCCIsCXX(false), CCCEcho(false), CCCPrintBindings(false),
Daniel Dunbar5a5ec5c2009-03-13 00:17:48 +000045 CCCNoClang(false), CCCNoClangCXX(false), CCCNoClangCPP(false),
46 SuppressMissingInputWarning(false)
Daniel Dunbarb282ced2009-03-10 20:52:46 +000047{
Daniel Dunbar63c4da92009-03-02 19:59:07 +000048}
49
50Driver::~Driver() {
Daniel Dunbard6f0e372009-03-04 20:49:20 +000051 delete Opts;
Daniel Dunbar2f8b37e2009-03-18 01:09:40 +000052 delete Host;
Daniel Dunbar63c4da92009-03-02 19:59:07 +000053}
54
Daniel Dunbar7dc2a042009-03-05 06:38:47 +000055ArgList *Driver::ParseArgStrings(const char **ArgBegin, const char **ArgEnd) {
Daniel Dunbar16e04ff2009-03-18 01:38:48 +000056 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
Daniel Dunbar7dc2a042009-03-05 06:38:47 +000057 ArgList *Args = new ArgList(ArgBegin, ArgEnd);
58
Daniel Dunbar85cb3592009-03-13 11:38:42 +000059 // FIXME: Handle '@' args (or at least error on them).
60
Daniel Dunbar7dc2a042009-03-05 06:38:47 +000061 unsigned Index = 0, End = ArgEnd - ArgBegin;
62 while (Index < End) {
Daniel Dunbarb043ebd2009-03-13 01:01:44 +000063 // gcc's handling of empty arguments doesn't make
64 // sense, but this is not a common use case. :)
65 //
66 // We just ignore them here (note that other things may
67 // still take them as arguments).
68 if (Args->getArgString(Index)[0] == '\0') {
69 ++Index;
70 continue;
71 }
72
Daniel Dunbar7dc2a042009-03-05 06:38:47 +000073 unsigned Prev = Index;
74 Arg *A = getOpts().ParseOneArg(*Args, Index, End);
Daniel Dunbardb62cc32009-03-12 07:58:46 +000075 if (A) {
76 if (A->getOption().isUnsupported()) {
Daniel Dunbard724e332009-03-12 09:13:48 +000077 Diag(clang::diag::err_drv_unsupported_opt) << A->getOption().getName();
Daniel Dunbardb62cc32009-03-12 07:58:46 +000078 continue;
79 }
80
Daniel Dunbar7dc2a042009-03-05 06:38:47 +000081 Args->append(A);
Daniel Dunbardb62cc32009-03-12 07:58:46 +000082 }
Daniel Dunbar7dc2a042009-03-05 06:38:47 +000083
84 assert(Index > Prev && "Parser failed to consume argument.");
Daniel Dunbarbb087552009-03-17 04:12:06 +000085 (void) Prev;
Daniel Dunbar7dc2a042009-03-05 06:38:47 +000086 }
87
88 return Args;
89}
90
Daniel Dunbar63c4da92009-03-02 19:59:07 +000091Compilation *Driver::BuildCompilation(int argc, const char **argv) {
Daniel Dunbar16e04ff2009-03-18 01:38:48 +000092 llvm::PrettyStackTraceString CrashInfo("Compilation construction");
93
Daniel Dunbarcc006892009-03-13 00:51:18 +000094 // FIXME: Handle environment options which effect driver behavior,
95 // somewhere (client?). GCC_EXEC_PREFIX, COMPILER_PATH,
96 // LIBRARY_PATH, LPATH, CC_PRINT_OPTIONS, QA_OVERRIDE_GCC3_OPTIONS.
97
98 // FIXME: What are we going to do with -V and -b?
99
100 // FIXME: Handle CCC_ADD_ARGS.
101
Daniel Dunbarb282ced2009-03-10 20:52:46 +0000102 // FIXME: This stuff needs to go into the Compilation, not the
103 // driver.
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000104 bool CCCPrintOptions = false, CCCPrintActions = false;
Daniel Dunbar7dc2a042009-03-05 06:38:47 +0000105
Daniel Dunbarb282ced2009-03-10 20:52:46 +0000106 const char **Start = argv + 1, **End = argv + argc;
Daniel Dunbard25acaa2009-03-10 23:41:59 +0000107 const char *HostTriple = DefaultHostTriple.c_str();
Daniel Dunbarb282ced2009-03-10 20:52:46 +0000108
109 // Read -ccc args.
110 //
111 // FIXME: We need to figure out where this behavior should
112 // live. Most of it should be outside in the client; the parts that
113 // aren't should have proper options, either by introducing new ones
114 // or by overloading gcc ones like -V or -b.
115 for (; Start != End && memcmp(*Start, "-ccc-", 5) == 0; ++Start) {
116 const char *Opt = *Start + 5;
117
118 if (!strcmp(Opt, "print-options")) {
119 CCCPrintOptions = true;
120 } else if (!strcmp(Opt, "print-phases")) {
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000121 CCCPrintActions = true;
Daniel Dunbar07c9a1d2009-03-17 22:47:06 +0000122 } else if (!strcmp(Opt, "print-bindings")) {
123 CCCPrintBindings = true;
Daniel Dunbarb282ced2009-03-10 20:52:46 +0000124 } else if (!strcmp(Opt, "cxx")) {
125 CCCIsCXX = true;
126 } else if (!strcmp(Opt, "echo")) {
127 CCCEcho = true;
128
129 } else if (!strcmp(Opt, "no-clang")) {
130 CCCNoClang = true;
131 } else if (!strcmp(Opt, "no-clang-cxx")) {
132 CCCNoClangCXX = true;
133 } else if (!strcmp(Opt, "no-clang-cpp")) {
134 CCCNoClangCPP = true;
135 } else if (!strcmp(Opt, "clang-archs")) {
136 assert(Start+1 < End && "FIXME: -ccc- argument handling.");
137 const char *Cur = *++Start;
138
139 for (;;) {
140 const char *Next = strchr(Cur, ',');
141
142 if (Next) {
143 CCCClangArchs.insert(std::string(Cur, Next));
144 Cur = Next + 1;
145 } else {
146 CCCClangArchs.insert(std::string(Cur));
147 break;
148 }
149 }
150
Daniel Dunbard25acaa2009-03-10 23:41:59 +0000151 } else if (!strcmp(Opt, "host-triple")) {
Daniel Dunbarb282ced2009-03-10 20:52:46 +0000152 assert(Start+1 < End && "FIXME: -ccc- argument handling.");
Daniel Dunbard25acaa2009-03-10 23:41:59 +0000153 HostTriple = *++Start;
Daniel Dunbarb282ced2009-03-10 20:52:46 +0000154
155 } else {
156 // FIXME: Error handling.
157 llvm::errs() << "invalid option: " << *Start << "\n";
158 exit(1);
159 }
160 }
Daniel Dunbard25acaa2009-03-10 23:41:59 +0000161
Daniel Dunbarb282ced2009-03-10 20:52:46 +0000162 ArgList *Args = ParseArgStrings(Start, End);
163
Daniel Dunbar08966ca2009-03-17 20:45:45 +0000164 Host = GetHostInfo(HostTriple);
Daniel Dunbar43a36802009-03-17 21:29:52 +0000165 // FIXME: This shouldn't live inside Driver, the default tool chain
166 // is part of the compilation (it is arg dependent).
Daniel Dunbarcc006892009-03-13 00:51:18 +0000167 DefaultToolChain = Host->getToolChain(*Args);
168
Daniel Dunbar9d625e12009-03-16 06:42:30 +0000169 // The compilation takes ownership of Args.
170 Compilation *C = new Compilation(*DefaultToolChain, Args);
Daniel Dunbar73f7b8c2009-03-18 02:55:38 +0000171
172 // FIXME: This behavior shouldn't be here.
173 if (CCCPrintOptions) {
174 PrintOptions(C->getArgs());
175 return C;
176 }
177
178 if (!HandleImmediateArgs(*C))
179 return C;
180
181 // Construct the list of abstract actions to perform for this
182 // compilation. We avoid passing a Compilation here simply to
183 // enforce the abstraction that pipelining is not host or toolchain
184 // dependent (other than the driver driver test).
185 if (Host->useDriverDriver())
186 BuildUniversalActions(C->getArgs(), C->getActions());
187 else
188 BuildActions(C->getArgs(), C->getActions());
189
190 if (CCCPrintActions) {
191 PrintActions(C->getArgs(), C->getActions());
192 return C;
193 }
194
195 BuildJobs(*C);
Daniel Dunbarc413f822009-03-15 01:38:15 +0000196
197 return C;
Daniel Dunbarb282ced2009-03-10 20:52:46 +0000198}
199
Daniel Dunbara790d372009-03-12 18:24:49 +0000200void Driver::PrintOptions(const ArgList &Args) const {
Daniel Dunbar7dc2a042009-03-05 06:38:47 +0000201 unsigned i = 0;
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000202 for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
Daniel Dunbar7dc2a042009-03-05 06:38:47 +0000203 it != ie; ++it, ++i) {
204 Arg *A = *it;
205 llvm::errs() << "Option " << i << " - "
206 << "Name: \"" << A->getOption().getName() << "\", "
207 << "Values: {";
208 for (unsigned j = 0; j < A->getNumValues(); ++j) {
209 if (j)
210 llvm::errs() << ", ";
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000211 llvm::errs() << '"' << A->getValue(Args, j) << '"';
Daniel Dunbar7dc2a042009-03-05 06:38:47 +0000212 }
213 llvm::errs() << "}\n";
Daniel Dunbar7dc2a042009-03-05 06:38:47 +0000214 }
Daniel Dunbar63c4da92009-03-02 19:59:07 +0000215}
Daniel Dunbard25acaa2009-03-10 23:41:59 +0000216
Daniel Dunbarcc006892009-03-13 00:51:18 +0000217void Driver::PrintVersion() const {
218 // FIXME: Get a reasonable version number.
219
220 // FIXME: The following handlers should use a callback mechanism, we
221 // don't know what the client would like to do.
222 llvm::outs() << "ccc version 1.0" << "\n";
223}
224
Daniel Dunbar73f7b8c2009-03-18 02:55:38 +0000225bool Driver::HandleImmediateArgs(const Compilation &C) {
Daniel Dunbarcc006892009-03-13 00:51:18 +0000226 // The order these options are handled in in gcc is all over the
227 // place, but we don't expect inconsistencies w.r.t. that to matter
228 // in practice.
Daniel Dunbar73f7b8c2009-03-18 02:55:38 +0000229 if (C.getArgs().hasArg(options::OPT_v) ||
230 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
Daniel Dunbarcc006892009-03-13 00:51:18 +0000231 PrintVersion();
232 SuppressMissingInputWarning = true;
233 }
234
Daniel Dunbar73f7b8c2009-03-18 02:55:38 +0000235 const ToolChain &TC = C.getDefaultToolChain();
Daniel Dunbarcc006892009-03-13 00:51:18 +0000236 // FIXME: The following handlers should use a callback mechanism, we
237 // don't know what the client would like to do.
Daniel Dunbar73f7b8c2009-03-18 02:55:38 +0000238 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
239 llvm::outs() << GetFilePath(A->getValue(C.getArgs()), TC).toString()
240 << "\n";
Daniel Dunbarcc006892009-03-13 00:51:18 +0000241 return false;
242 }
243
Daniel Dunbar73f7b8c2009-03-18 02:55:38 +0000244 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
245 llvm::outs() << GetProgramPath(A->getValue(C.getArgs()), TC).toString()
246 << "\n";
Daniel Dunbarcc006892009-03-13 00:51:18 +0000247 return false;
248 }
249
Daniel Dunbar73f7b8c2009-03-18 02:55:38 +0000250 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
251 llvm::outs() << GetProgramPath("libgcc.a", TC).toString() << "\n";
Daniel Dunbarcc006892009-03-13 00:51:18 +0000252 return false;
253 }
254
255 return true;
256}
257
Daniel Dunbar494646b2009-03-13 12:19:02 +0000258static unsigned PrintActions1(const ArgList &Args,
259 Action *A,
260 std::map<Action*, unsigned> &Ids) {
261 if (Ids.count(A))
262 return Ids[A];
263
264 std::string str;
265 llvm::raw_string_ostream os(str);
266
267 os << Action::getClassName(A->getKind()) << ", ";
268 if (InputAction *IA = dyn_cast<InputAction>(A)) {
Daniel Dunbardd863aa2009-03-13 17:46:02 +0000269 os << "\"" << IA->getInputArg().getValue(Args) << "\"";
Daniel Dunbar494646b2009-03-13 12:19:02 +0000270 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
271 os << "\"" << BIA->getArchName() << "\", "
272 << "{" << PrintActions1(Args, *BIA->begin(), Ids) << "}";
273 } else {
274 os << "{";
275 for (Action::iterator it = A->begin(), ie = A->end(); it != ie;) {
276 os << PrintActions1(Args, *it, Ids);
277 ++it;
278 if (it != ie)
279 os << ", ";
280 }
281 os << "}";
282 }
283
284 unsigned Id = Ids.size();
285 Ids[A] = Id;
Daniel Dunbar9dc28b82009-03-13 17:20:20 +0000286 llvm::errs() << Id << ": " << os.str() << ", "
Daniel Dunbar494646b2009-03-13 12:19:02 +0000287 << types::getTypeName(A->getType()) << "\n";
288
289 return Id;
290}
291
292void Driver::PrintActions(const ArgList &Args,
293 const ActionList &Actions) const {
294 std::map<Action*, unsigned> Ids;
295 for (ActionList::const_iterator it = Actions.begin(), ie = Actions.end();
Daniel Dunbar9dc28b82009-03-13 17:20:20 +0000296 it != ie; ++it)
Daniel Dunbar494646b2009-03-13 12:19:02 +0000297 PrintActions1(Args, *it, Ids);
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000298}
299
Daniel Dunbar73f7b8c2009-03-18 02:55:38 +0000300void Driver::BuildUniversalActions(const ArgList &Args,
301 ActionList &Actions) const {
Daniel Dunbar16e04ff2009-03-18 01:38:48 +0000302 llvm::PrettyStackTraceString CrashInfo("Building actions for universal build");
Daniel Dunbarb1873cd2009-03-13 20:33:35 +0000303 // Collect the list of architectures. Duplicates are allowed, but
304 // should only be handled once (in the order seen).
305 llvm::StringSet<> ArchNames;
306 llvm::SmallVector<const char *, 4> Archs;
Daniel Dunbarfba157b2009-03-12 18:40:18 +0000307 for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
308 it != ie; ++it) {
309 Arg *A = *it;
310
311 if (A->getOption().getId() == options::OPT_arch) {
Daniel Dunbarb1873cd2009-03-13 20:33:35 +0000312 const char *Name = A->getValue(Args);
313
Daniel Dunbarfba157b2009-03-12 18:40:18 +0000314 // FIXME: We need to handle canonicalization of the specified
315 // arch?
316
Daniel Dunbarb1873cd2009-03-13 20:33:35 +0000317 if (ArchNames.insert(Name))
318 Archs.push_back(Name);
Daniel Dunbarfba157b2009-03-12 18:40:18 +0000319 }
320 }
321
322 // When there is no explicit arch for this platform, get one from
323 // the host so that -Xarch_ is handled correctly.
324 if (!Archs.size()) {
Daniel Dunbar43a36802009-03-17 21:29:52 +0000325 const char *Arch = DefaultToolChain->getArchName().c_str();
Daniel Dunbarb1873cd2009-03-13 20:33:35 +0000326 Archs.push_back(Arch);
Daniel Dunbarfba157b2009-03-12 18:40:18 +0000327 }
328
329 // FIXME: We killed off some others but these aren't yet detected in
330 // a functional manner. If we added information to jobs about which
331 // "auxiliary" files they wrote then we could detect the conflict
332 // these cause downstream.
333 if (Archs.size() > 1) {
334 // No recovery needed, the point of this is just to prevent
335 // overwriting the same files.
336 if (const Arg *A = Args.getLastArg(options::OPT_M_Group))
337 Diag(clang::diag::err_drv_invalid_opt_with_multiple_archs)
338 << A->getOption().getName();
339 if (const Arg *A = Args.getLastArg(options::OPT_save_temps))
340 Diag(clang::diag::err_drv_invalid_opt_with_multiple_archs)
341 << A->getOption().getName();
342 }
343
344 ActionList SingleActions;
345 BuildActions(Args, SingleActions);
346
347 // Add in arch binding and lipo (if necessary) for every top level
348 // action.
349 for (unsigned i = 0, e = SingleActions.size(); i != e; ++i) {
350 Action *Act = SingleActions[i];
351
352 // Make sure we can lipo this kind of output. If not (and it is an
353 // actual output) then we disallow, since we can't create an
354 // output file with the right name without overwriting it. We
355 // could remove this oddity by just changing the output names to
356 // include the arch, which would also fix
357 // -save-temps. Compatibility wins for now.
358
Daniel Dunbardd863aa2009-03-13 17:46:02 +0000359 if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
Daniel Dunbarfba157b2009-03-12 18:40:18 +0000360 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
361 << types::getTypeName(Act->getType());
362
363 ActionList Inputs;
Daniel Dunbarb1873cd2009-03-13 20:33:35 +0000364 for (unsigned i = 0, e = Archs.size(); i != e; ++i )
365 Inputs.push_back(new BindArchAction(Act, Archs[i]));
Daniel Dunbarfba157b2009-03-12 18:40:18 +0000366
367 // Lipo if necessary, We do it this way because we need to set the
368 // arch flag so that -Xarch_ gets overwritten.
369 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
370 Actions.append(Inputs.begin(), Inputs.end());
371 else
372 Actions.push_back(new LipoJobAction(Inputs, Act->getType()));
373 }
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000374}
375
Daniel Dunbar73f7b8c2009-03-18 02:55:38 +0000376void Driver::BuildActions(const ArgList &Args, ActionList &Actions) const {
Daniel Dunbar16e04ff2009-03-18 01:38:48 +0000377 llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
Daniel Dunbar207a56d2009-03-12 23:55:14 +0000378 // Start by constructing the list of inputs and their types.
379
Daniel Dunbar5cb75d62009-03-13 17:57:10 +0000380 // Track the current user specified (-x) input. We also explicitly
381 // track the argument used to set the type; we only want to claim
382 // the type when we actually use it, so we warn about unused -x
383 // arguments.
384 types::ID InputType = types::TY_Nothing;
385 Arg *InputTypeArg = 0;
386
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000387 llvm::SmallVector<std::pair<types::ID, const Arg*>, 16> Inputs;
388 for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
389 it != ie; ++it) {
390 Arg *A = *it;
391
392 if (isa<InputOption>(A->getOption())) {
393 const char *Value = A->getValue(Args);
394 types::ID Ty = types::TY_INVALID;
395
396 // Infer the input type if necessary.
Daniel Dunbar5cb75d62009-03-13 17:57:10 +0000397 if (InputType == types::TY_Nothing) {
398 // If there was an explicit arg for this, claim it.
399 if (InputTypeArg)
400 InputTypeArg->claim();
401
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000402 // stdin must be handled specially.
403 if (memcmp(Value, "-", 2) == 0) {
404 // If running with -E, treat as a C input (this changes the
405 // builtin macros, for example). This may be overridden by
406 // -ObjC below.
407 //
408 // Otherwise emit an error but still use a valid type to
409 // avoid spurious errors (e.g., no inputs).
Daniel Dunbare9c70fa2009-03-15 00:48:16 +0000410 if (!Args.hasArg(options::OPT_E, false))
Daniel Dunbard724e332009-03-12 09:13:48 +0000411 Diag(clang::diag::err_drv_unknown_stdin_type);
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000412 Ty = types::TY_C;
413 } else {
414 // Otherwise lookup by extension, and fallback to ObjectType
415 // if not found.
416 if (const char *Ext = strrchr(Value, '.'))
417 Ty = types::lookupTypeForExtension(Ext + 1);
418 if (Ty == types::TY_INVALID)
419 Ty = types::TY_Object;
420 }
421
422 // -ObjC and -ObjC++ override the default language, but only
423 // -for "source files". We just treat everything that isn't a
424 // -linker input as a source file.
425 //
426 // FIXME: Clean this up if we move the phase sequence into the
427 // type.
428 if (Ty != types::TY_Object) {
429 if (Args.hasArg(options::OPT_ObjC))
430 Ty = types::TY_ObjC;
431 else if (Args.hasArg(options::OPT_ObjCXX))
432 Ty = types::TY_ObjCXX;
433 }
434 } else {
435 assert(InputTypeArg && "InputType set w/o InputTypeArg");
436 InputTypeArg->claim();
437 Ty = InputType;
438 }
439
440 // Check that the file exists. It isn't clear this is worth
441 // doing, since the tool presumably does this anyway, and this
442 // just adds an extra stat to the equation, but this is gcc
443 // compatible.
Daniel Dunbar321c12d2009-03-15 01:40:22 +0000444 A->claim();
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000445 if (memcmp(Value, "-", 2) != 0 && !llvm::sys::Path(Value).exists())
Daniel Dunbard724e332009-03-12 09:13:48 +0000446 Diag(clang::diag::err_drv_no_such_file) << A->getValue(Args);
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000447 else
448 Inputs.push_back(std::make_pair(Ty, A));
449
450 } else if (A->getOption().isLinkerInput()) {
451 // Just treat as object type, we could make a special type for
452 // this if necessary.
Daniel Dunbar321c12d2009-03-15 01:40:22 +0000453 A->claim();
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000454 Inputs.push_back(std::make_pair(types::TY_Object, A));
455
456 } else if (A->getOption().getId() == options::OPT_x) {
457 InputTypeArg = A;
458 InputType = types::lookupTypeForTypeSpecifier(A->getValue(Args));
459
460 // Follow gcc behavior and treat as linker input for invalid -x
461 // options. Its not clear why we shouldn't just revert to
462 // unknown; but this isn't very important, we might as well be
463 // bug comatible.
464 if (!InputType) {
Daniel Dunbard724e332009-03-12 09:13:48 +0000465 Diag(clang::diag::err_drv_unknown_language) << A->getValue(Args);
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000466 InputType = types::TY_Object;
467 }
468 }
469 }
470
Daniel Dunbar5a5ec5c2009-03-13 00:17:48 +0000471 if (!SuppressMissingInputWarning && Inputs.empty()) {
Daniel Dunbar207a56d2009-03-12 23:55:14 +0000472 Diag(clang::diag::err_drv_no_input_files);
473 return;
474 }
475
476 // Determine which compilation mode we are in. We look for options
477 // which affect the phase, starting with the earliest phases, and
478 // record which option we used to determine the final phase.
Daniel Dunbar85cb3592009-03-13 11:38:42 +0000479 Arg *FinalPhaseArg = 0;
480 phases::ID FinalPhase;
Daniel Dunbar207a56d2009-03-12 23:55:14 +0000481
482 // -{E,M,MM} only run the preprocessor.
Daniel Dunbar85cb3592009-03-13 11:38:42 +0000483 if ((FinalPhaseArg = Args.getLastArg(options::OPT_E)) ||
484 (FinalPhaseArg = Args.getLastArg(options::OPT_M)) ||
485 (FinalPhaseArg = Args.getLastArg(options::OPT_MM))) {
486 FinalPhase = phases::Preprocess;
Daniel Dunbar207a56d2009-03-12 23:55:14 +0000487
Daniel Dunbare9c70fa2009-03-15 00:48:16 +0000488 // -{fsyntax-only,-analyze,emit-llvm,S} only run up to the compiler.
489 } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_fsyntax_only)) ||
490 (FinalPhaseArg = Args.getLastArg(options::OPT__analyze)) ||
491 (FinalPhaseArg = Args.getLastArg(options::OPT_emit_llvm)) ||
Daniel Dunbar85cb3592009-03-13 11:38:42 +0000492 (FinalPhaseArg = Args.getLastArg(options::OPT_S))) {
493 FinalPhase = phases::Compile;
Daniel Dunbar207a56d2009-03-12 23:55:14 +0000494
495 // -c only runs up to the assembler.
Daniel Dunbar85cb3592009-03-13 11:38:42 +0000496 } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_c))) {
497 FinalPhase = phases::Assemble;
Daniel Dunbar207a56d2009-03-12 23:55:14 +0000498
499 // Otherwise do everything.
500 } else
Daniel Dunbar85cb3592009-03-13 11:38:42 +0000501 FinalPhase = phases::Link;
Daniel Dunbar207a56d2009-03-12 23:55:14 +0000502
Daniel Dunbar207a56d2009-03-12 23:55:14 +0000503 // Reject -Z* at the top level, these options should never have been
504 // exposed by gcc.
505 if (Arg *A = Args.getLastArg(options::OPT_Z))
506 Diag(clang::diag::err_drv_use_of_Z_option) << A->getValue(Args);
507
Daniel Dunbar85cb3592009-03-13 11:38:42 +0000508 // Construct the actions to perform.
509 ActionList LinkerInputs;
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000510 for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
Daniel Dunbar85cb3592009-03-13 11:38:42 +0000511 types::ID InputType = Inputs[i].first;
512 const Arg *InputArg = Inputs[i].second;
513
514 unsigned NumSteps = types::getNumCompilationPhases(InputType);
515 assert(NumSteps && "Invalid number of steps!");
516
517 // If the first step comes after the final phase we are doing as
518 // part of this compilation, warn the user about it.
519 phases::ID InitialPhase = types::getCompilationPhase(InputType, 0);
520 if (InitialPhase > FinalPhase) {
521 Diag(clang::diag::warn_drv_input_file_unused)
522 << InputArg->getValue(Args)
523 << getPhaseName(InitialPhase)
524 << FinalPhaseArg->getOption().getName();
525 continue;
526 }
527
528 // Build the pipeline for this file.
529 Action *Current = new InputAction(*InputArg, InputType);
530 for (unsigned i = 0; i != NumSteps; ++i) {
531 phases::ID Phase = types::getCompilationPhase(InputType, i);
532
533 // We are done if this step is past what the user requested.
534 if (Phase > FinalPhase)
535 break;
536
537 // Queue linker inputs.
538 if (Phase == phases::Link) {
539 assert(i + 1 == NumSteps && "linking must be final compilation step.");
540 LinkerInputs.push_back(Current);
541 Current = 0;
542 break;
543 }
544
545 // Otherwise construct the appropriate action.
546 Current = ConstructPhaseAction(Args, Phase, Current);
547 if (Current->getType() == types::TY_Nothing)
548 break;
549 }
550
551 // If we ended with something, add to the output list.
552 if (Current)
553 Actions.push_back(Current);
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000554 }
Daniel Dunbar85cb3592009-03-13 11:38:42 +0000555
556 // Add a link action if necessary.
557 if (!LinkerInputs.empty())
558 Actions.push_back(new LinkJobAction(LinkerInputs, types::TY_Image));
559}
560
561Action *Driver::ConstructPhaseAction(const ArgList &Args, phases::ID Phase,
562 Action *Input) const {
Daniel Dunbar16e04ff2009-03-18 01:38:48 +0000563 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
Daniel Dunbar85cb3592009-03-13 11:38:42 +0000564 // Build the appropriate action.
565 switch (Phase) {
566 case phases::Link: assert(0 && "link action invalid here.");
567 case phases::Preprocess: {
568 types::ID OutputTy = types::getPreprocessedType(Input->getType());
569 assert(OutputTy != types::TY_INVALID &&
570 "Cannot preprocess this input type!");
571 return new PreprocessJobAction(Input, OutputTy);
572 }
573 case phases::Precompile:
574 return new PrecompileJobAction(Input, types::TY_PCH);
575 case phases::Compile: {
576 if (Args.hasArg(options::OPT_fsyntax_only)) {
577 return new CompileJobAction(Input, types::TY_Nothing);
578 } else if (Args.hasArg(options::OPT__analyze)) {
579 return new AnalyzeJobAction(Input, types::TY_Plist);
580 } else if (Args.hasArg(options::OPT_emit_llvm)) {
581 types::ID Output =
582 Args.hasArg(options::OPT_S) ? types::TY_LLVMAsm : types::TY_LLVMBC;
583 return new CompileJobAction(Input, Output);
584 } else {
585 return new CompileJobAction(Input, types::TY_PP_Asm);
586 }
587 }
588 case phases::Assemble:
589 return new AssembleJobAction(Input, types::TY_Object);
590 }
591
592 assert(0 && "invalid phase in ConstructPhaseAction");
593 return 0;
Daniel Dunbardb62cc32009-03-12 07:58:46 +0000594}
595
Daniel Dunbar73f7b8c2009-03-18 02:55:38 +0000596void Driver::BuildJobs(Compilation &C) const {
Daniel Dunbar16e04ff2009-03-18 01:38:48 +0000597 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
Daniel Dunbar7ce6add2009-03-16 06:56:51 +0000598 bool SaveTemps = C.getArgs().hasArg(options::OPT_save_temps);
599 bool UsePipes = C.getArgs().hasArg(options::OPT_pipe);
600
601 // -save-temps inhibits pipes.
602 if (SaveTemps && UsePipes) {
603 Diag(clang::diag::warn_drv_pipe_ignored_with_save_temps);
604 UsePipes = true;
605 }
606
607 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
608
609 // It is an error to provide a -o option if we are making multiple
610 // output files.
611 if (FinalOutput) {
612 unsigned NumOutputs = 0;
Daniel Dunbar73f7b8c2009-03-18 02:55:38 +0000613 for (ActionList::const_iterator it = C.getActions().begin(),
614 ie = C.getActions().end(); it != ie; ++it)
Daniel Dunbar7ce6add2009-03-16 06:56:51 +0000615 if ((*it)->getType() != types::TY_Nothing)
616 ++NumOutputs;
617
618 if (NumOutputs > 1) {
619 Diag(clang::diag::err_drv_output_argument_with_multiple_files);
620 FinalOutput = 0;
621 }
622 }
623
Daniel Dunbar73f7b8c2009-03-18 02:55:38 +0000624 for (ActionList::const_iterator it = C.getActions().begin(),
625 ie = C.getActions().end(); it != ie; ++it) {
Daniel Dunbar7ce6add2009-03-16 06:56:51 +0000626 Action *A = *it;
627
628 // If we are linking an image for multiple archs then the linker
629 // wants -arch_multiple and -final_output <final image
630 // name>. Unfortunately, this doesn't fit in cleanly because we
631 // have to pass this information down.
632 //
633 // FIXME: This is a hack; find a cleaner way to integrate this
634 // into the process.
635 const char *LinkingOutput = 0;
636 if (isa<LinkJobAction>(A)) {
637 if (FinalOutput)
638 LinkingOutput = FinalOutput->getValue(C.getArgs());
639 else
640 LinkingOutput = DefaultImageName.c_str();
641 }
642
643 InputInfo II;
644 BuildJobsForAction(C,
645 A, DefaultToolChain,
646 /*CanAcceptPipe*/ true,
647 /*AtTopLevel*/ true,
648 /*LinkingOutput*/ LinkingOutput,
649 II);
650 }
Daniel Dunbar9d625e12009-03-16 06:42:30 +0000651
652 // If there were no errors, warn about any unused arguments.
653 for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
654 it != ie; ++it) {
655 Arg *A = *it;
656
657 // FIXME: It would be nice to be able to send the argument to the
658 // Diagnostic, so that extra values, position, and so on could be
659 // printed.
660 if (!A->isClaimed())
661 Diag(clang::diag::warn_drv_unused_argument)
662 << A->getOption().getName();
663 }
Daniel Dunbar47d762e2009-03-13 22:12:33 +0000664}
665
Daniel Dunbar7ce6add2009-03-16 06:56:51 +0000666void Driver::BuildJobsForAction(Compilation &C,
667 const Action *A,
668 const ToolChain *TC,
669 bool CanAcceptPipe,
670 bool AtTopLevel,
671 const char *LinkingOutput,
672 InputInfo &Result) const {
Daniel Dunbar16e04ff2009-03-18 01:38:48 +0000673 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs for action");
Daniel Dunbar7ce6add2009-03-16 06:56:51 +0000674 if (const InputAction *IA = dyn_cast<InputAction>(A)) {
675 const char *Name = IA->getInputArg().getValue(C.getArgs());
676 Result = InputInfo(Name, A->getType(), Name);
677 return;
678 }
679
680 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
681 const char *ArchName = BAA->getArchName();
682 BuildJobsForAction(C,
683 *BAA->begin(),
684 Host->getToolChain(C.getArgs(), ArchName),
685 CanAcceptPipe,
686 AtTopLevel,
687 LinkingOutput,
688 Result);
689 return;
690 }
691
692 const JobAction *JA = cast<JobAction>(A);
693 const Tool &T = TC->SelectTool(C, *JA);
694
695 // See if we should use an integrated preprocessor. We do so when we
696 // have exactly one input, since this is the only use case we care
697 // about (irrelevant since we don't support combine yet).
698 bool UseIntegratedCPP = false;
699 const ActionList *Inputs = &A->getInputs();
700 if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin())) {
701 if (!C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
702 !C.getArgs().hasArg(options::OPT_traditional_cpp) &&
703 !C.getArgs().hasArg(options::OPT_save_temps) &&
704 T.hasIntegratedCPP()) {
705 UseIntegratedCPP = true;
706 Inputs = &(*Inputs)[0]->getInputs();
707 }
708 }
709
710 // Only use pipes when there is exactly one input.
711 bool TryToUsePipeInput = Inputs->size() == 1 && T.acceptsPipedInput();
712 llvm::SmallVector<InputInfo, 4> InputInfos;
713 for (ActionList::const_iterator it = Inputs->begin(), ie = Inputs->end();
714 it != ie; ++it) {
715 InputInfo II;
716 BuildJobsForAction(C, *it, TC, TryToUsePipeInput,
717 /*AtTopLevel*/false,
718 LinkingOutput,
719 II);
720 InputInfos.push_back(II);
721 }
722
723 // Determine if we should output to a pipe.
724 bool OutputToPipe = false;
725 if (CanAcceptPipe && T.canPipeOutput()) {
726 // Some actions default to writing to a pipe if they are the top
727 // level phase and there was no user override.
728 //
729 // FIXME: Is there a better way to handle this?
730 if (AtTopLevel) {
731 if (isa<PreprocessJobAction>(A) && !C.getArgs().hasArg(options::OPT_o))
732 OutputToPipe = true;
733 } else if (C.getArgs().hasArg(options::OPT_pipe))
734 OutputToPipe = true;
735 }
736
737 // Figure out where to put the job (pipes).
738 Job *Dest = &C.getJobs();
739 if (InputInfos[0].isPipe()) {
Daniel Dunbar01fb26a2009-03-17 17:53:55 +0000740 assert(TryToUsePipeInput && "Unrequested pipe!");
Daniel Dunbar7ce6add2009-03-16 06:56:51 +0000741 assert(InputInfos.size() == 1 && "Unexpected pipe with multiple inputs.");
742 Dest = &InputInfos[0].getPipe();
743 }
744
745 // Always use the first input as the base input.
746 const char *BaseInput = InputInfos[0].getBaseInput();
Daniel Dunbar01fb26a2009-03-17 17:53:55 +0000747
748 // Determine the place to write output to (nothing, pipe, or
749 // filename) and where to put the new job.
Daniel Dunbar01fb26a2009-03-17 17:53:55 +0000750 if (JA->getType() == types::TY_Nothing) {
Daniel Dunbar07c9a1d2009-03-17 22:47:06 +0000751 Result = InputInfo(A->getType(), BaseInput);
Daniel Dunbar01fb26a2009-03-17 17:53:55 +0000752 } else if (OutputToPipe) {
753 // Append to current piped job or create a new one as appropriate.
Daniel Dunbar07c9a1d2009-03-17 22:47:06 +0000754 PipedJob *PJ = dyn_cast<PipedJob>(Dest);
755 if (!PJ) {
756 PJ = new PipedJob();
757 cast<JobList>(Dest)->addJob(PJ);
Daniel Dunbar01fb26a2009-03-17 17:53:55 +0000758 }
Daniel Dunbar07c9a1d2009-03-17 22:47:06 +0000759 Result = InputInfo(PJ, A->getType(), BaseInput);
Daniel Dunbar01fb26a2009-03-17 17:53:55 +0000760 } else {
Daniel Dunbar07c9a1d2009-03-17 22:47:06 +0000761 Result = InputInfo(GetNamedOutputPath(C, *JA, BaseInput, AtTopLevel),
762 A->getType(), BaseInput);
Daniel Dunbar01fb26a2009-03-17 17:53:55 +0000763 }
764
Daniel Dunbar07c9a1d2009-03-17 22:47:06 +0000765 if (CCCPrintBindings) {
766 llvm::errs() << "bind - \"" << T.getName() << "\", inputs: [";
767 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
768 llvm::errs() << InputInfos[i].getAsString();
769 if (i + 1 != e)
770 llvm::errs() << ", ";
771 }
772 llvm::errs() << "], output: " << Result.getAsString() << "\n";
773 } else {
774 assert(0 && "FIXME: Make the job.");
775 }
Daniel Dunbar7ce6add2009-03-16 06:56:51 +0000776}
777
Daniel Dunbar01fb26a2009-03-17 17:53:55 +0000778const char *Driver::GetNamedOutputPath(Compilation &C,
779 const JobAction &JA,
780 const char *BaseInput,
781 bool AtTopLevel) const {
Daniel Dunbar16e04ff2009-03-18 01:38:48 +0000782 llvm::PrettyStackTraceString CrashInfo("Computing output path");
Daniel Dunbar01fb26a2009-03-17 17:53:55 +0000783 // Output to a user requested destination?
784 if (AtTopLevel) {
785 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
786 return C.addResultFile(FinalOutput->getValue(C.getArgs()));
787 }
788
789 // Output to a temporary file?
790 if (!AtTopLevel && !C.getArgs().hasArg(options::OPT_save_temps)) {
791 // FIXME: Get temporary name.
792 std::string Name("/tmp/foo");
793 Name += '.';
794 Name += types::getTypeTempSuffix(JA.getType());
795 return C.addTempFile(C.getArgs().MakeArgString(Name.c_str()));
796 }
797
798 llvm::sys::Path BasePath(BaseInput);
Daniel Dunbarfb5e3332009-03-18 02:00:31 +0000799 std::string BaseName(BasePath.getLast());
Daniel Dunbar01fb26a2009-03-17 17:53:55 +0000800
801 // Determine what the derived output name should be.
802 const char *NamedOutput;
803 if (JA.getType() == types::TY_Image) {
804 NamedOutput = DefaultImageName.c_str();
805 } else {
806 const char *Suffix = types::getTypeTempSuffix(JA.getType());
807 assert(Suffix && "All types used for output should have a suffix.");
808
809 std::string::size_type End = std::string::npos;
810 if (!types::appendSuffixForType(JA.getType()))
811 End = BaseName.rfind('.');
812 std::string Suffixed(BaseName.substr(0, End));
813 Suffixed += '.';
814 Suffixed += Suffix;
815 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
816 }
817
818 // As an annoying special case, PCH generation doesn't strip the
819 // pathname.
820 if (JA.getType() == types::TY_PCH) {
821 BasePath.eraseComponent();
822 BasePath.appendComponent(NamedOutput);
823 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()));
824 } else {
825 return C.addResultFile(NamedOutput);
826 }
827}
828
Daniel Dunbare1cef7d2009-03-16 05:25:36 +0000829llvm::sys::Path Driver::GetFilePath(const char *Name,
Daniel Dunbar73f7b8c2009-03-18 02:55:38 +0000830 const ToolChain &TC) const {
Daniel Dunbarcc006892009-03-13 00:51:18 +0000831 // FIXME: Implement.
832 return llvm::sys::Path(Name);
833}
834
Daniel Dunbare1cef7d2009-03-16 05:25:36 +0000835llvm::sys::Path Driver::GetProgramPath(const char *Name,
Daniel Dunbar73f7b8c2009-03-18 02:55:38 +0000836 const ToolChain &TC) const {
Daniel Dunbarcc006892009-03-13 00:51:18 +0000837 // FIXME: Implement.
838 return llvm::sys::Path(Name);
839}
840
Daniel Dunbar08966ca2009-03-17 20:45:45 +0000841const HostInfo *Driver::GetHostInfo(const char *Triple) const {
Daniel Dunbar16e04ff2009-03-18 01:38:48 +0000842 llvm::PrettyStackTraceString CrashInfo("Constructing host");
Daniel Dunbard25acaa2009-03-10 23:41:59 +0000843 // Dice into arch, platform, and OS. This matches
844 // arch,platform,os = '(.*?)-(.*?)-(.*?)'
845 // and missing fields are left empty.
846 std::string Arch, Platform, OS;
847
848 if (const char *ArchEnd = strchr(Triple, '-')) {
849 Arch = std::string(Triple, ArchEnd);
850
851 if (const char *PlatformEnd = strchr(ArchEnd+1, '-')) {
852 Platform = std::string(ArchEnd+1, PlatformEnd);
853 OS = PlatformEnd+1;
854 } else
855 Platform = ArchEnd+1;
856 } else
857 Arch = Triple;
858
Daniel Dunbar7424b8a2009-03-17 19:00:50 +0000859 // Normalize Arch a bit.
860 //
861 // FIXME: This is very incomplete.
862 if (Arch == "i686")
863 Arch = "i386";
864 else if (Arch == "amd64")
865 Arch = "x86_64";
866
Daniel Dunbar44119a12009-03-13 12:23:29 +0000867 if (memcmp(&OS[0], "darwin", 6) == 0)
Daniel Dunbar08966ca2009-03-17 20:45:45 +0000868 return createDarwinHostInfo(*this, Arch.c_str(), Platform.c_str(),
869 OS.c_str());
Daniel Dunbard25acaa2009-03-10 23:41:59 +0000870
Daniel Dunbar08966ca2009-03-17 20:45:45 +0000871 return createUnknownHostInfo(*this, Arch.c_str(), Platform.c_str(),
872 OS.c_str());
Daniel Dunbard25acaa2009-03-10 23:41:59 +0000873}