Driver.cpp revision 60ccc7677a5416df3a8f8bde79ab35f85cb66e14
1//===--- 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
10#include "clang/Driver/Driver.h"
11
12#include "clang/Driver/Action.h"
13#include "clang/Driver/Arg.h"
14#include "clang/Driver/ArgList.h"
15#include "clang/Driver/Compilation.h"
16#include "clang/Driver/DriverDiagnostic.h"
17#include "clang/Driver/HostInfo.h"
18#include "clang/Driver/Job.h"
19#include "clang/Driver/Option.h"
20#include "clang/Driver/Options.h"
21#include "clang/Driver/Tool.h"
22#include "clang/Driver/ToolChain.h"
23#include "clang/Driver/Types.h"
24
25#include "llvm/ADT/StringSet.h"
26#include "llvm/Support/PrettyStackTrace.h"
27#include "llvm/Support/raw_ostream.h"
28#include "llvm/System/Path.h"
29#include "llvm/System/Program.h"
30
31#include "InputInfo.h"
32
33#include <map>
34
35using namespace clang::driver;
36
37Driver::Driver(const char *_Name, const char *_Dir,
38               const char *_DefaultHostTriple,
39               const char *_DefaultImageName,
40               Diagnostic &_Diags)
41  : Opts(new OptTable()), Diags(_Diags),
42    Name(_Name), Dir(_Dir), DefaultHostTriple(_DefaultHostTriple),
43    DefaultImageName(_DefaultImageName),
44    Host(0),
45    CCCIsCXX(false), CCCEcho(false), CCCPrintBindings(false),
46    CCCNoClang(false), CCCNoClangCXX(false), CCCNoClangCPP(false),
47    SuppressMissingInputWarning(false)
48{
49}
50
51Driver::~Driver() {
52  delete Opts;
53  delete Host;
54}
55
56ArgList *Driver::ParseArgStrings(const char **ArgBegin, const char **ArgEnd) {
57  llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
58  ArgList *Args = new ArgList(ArgBegin, ArgEnd);
59
60  // FIXME: Handle '@' args (or at least error on them).
61
62  unsigned Index = 0, End = ArgEnd - ArgBegin;
63  while (Index < End) {
64    // gcc's handling of empty arguments doesn't make
65    // sense, but this is not a common use case. :)
66    //
67    // We just ignore them here (note that other things may
68    // still take them as arguments).
69    if (Args->getArgString(Index)[0] == '\0') {
70      ++Index;
71      continue;
72    }
73
74    unsigned Prev = Index;
75    Arg *A = getOpts().ParseOneArg(*Args, Index, End);
76    if (A) {
77      if (A->getOption().isUnsupported()) {
78        Diag(clang::diag::err_drv_unsupported_opt) << A->getOption().getName();
79        continue;
80      }
81
82      Args->append(A);
83    }
84
85    assert(Index > Prev && "Parser failed to consume argument.");
86    (void) Prev;
87  }
88
89  return Args;
90}
91
92Compilation *Driver::BuildCompilation(int argc, const char **argv) {
93  llvm::PrettyStackTraceString CrashInfo("Compilation construction");
94
95  // FIXME: Handle environment options which effect driver behavior,
96  // somewhere (client?). GCC_EXEC_PREFIX, COMPILER_PATH,
97  // LIBRARY_PATH, LPATH, CC_PRINT_OPTIONS, QA_OVERRIDE_GCC3_OPTIONS.
98
99  // FIXME: What are we going to do with -V and -b?
100
101  // FIXME: Handle CCC_ADD_ARGS.
102
103  // FIXME: This stuff needs to go into the Compilation, not the
104  // driver.
105  bool CCCPrintOptions = false, CCCPrintActions = false;
106
107  const char **Start = argv + 1, **End = argv + argc;
108  const char *HostTriple = DefaultHostTriple.c_str();
109
110  // Read -ccc args.
111  //
112  // FIXME: We need to figure out where this behavior should
113  // live. Most of it should be outside in the client; the parts that
114  // aren't should have proper options, either by introducing new ones
115  // or by overloading gcc ones like -V or -b.
116  for (; Start != End && memcmp(*Start, "-ccc-", 5) == 0; ++Start) {
117    const char *Opt = *Start + 5;
118
119    if (!strcmp(Opt, "print-options")) {
120      CCCPrintOptions = true;
121    } else if (!strcmp(Opt, "print-phases")) {
122      CCCPrintActions = true;
123    } else if (!strcmp(Opt, "print-bindings")) {
124      CCCPrintBindings = true;
125    } else if (!strcmp(Opt, "cxx")) {
126      CCCIsCXX = true;
127    } else if (!strcmp(Opt, "echo")) {
128      CCCEcho = true;
129
130    } else if (!strcmp(Opt, "no-clang")) {
131      CCCNoClang = true;
132    } else if (!strcmp(Opt, "no-clang-cxx")) {
133      CCCNoClangCXX = true;
134    } else if (!strcmp(Opt, "no-clang-cpp")) {
135      CCCNoClangCPP = true;
136    } else if (!strcmp(Opt, "clang-archs")) {
137      assert(Start+1 < End && "FIXME: -ccc- argument handling.");
138      const char *Cur = *++Start;
139
140      for (;;) {
141        const char *Next = strchr(Cur, ',');
142
143        if (Next) {
144          CCCClangArchs.insert(std::string(Cur, Next));
145          Cur = Next + 1;
146        } else {
147          CCCClangArchs.insert(std::string(Cur));
148          break;
149        }
150      }
151
152    } else if (!strcmp(Opt, "host-triple")) {
153      assert(Start+1 < End && "FIXME: -ccc- argument handling.");
154      HostTriple = *++Start;
155
156    } else {
157      // FIXME: Error handling.
158      llvm::errs() << "invalid option: " << *Start << "\n";
159      exit(1);
160    }
161  }
162
163  ArgList *Args = ParseArgStrings(Start, End);
164
165  Host = GetHostInfo(HostTriple);
166
167  // The compilation takes ownership of Args.
168  Compilation *C = new Compilation(*this, *Host->getToolChain(*Args), Args);
169
170  // FIXME: This behavior shouldn't be here.
171  if (CCCPrintOptions) {
172    PrintOptions(C->getArgs());
173    return C;
174  }
175
176  if (!HandleImmediateArgs(*C))
177    return C;
178
179  // Construct the list of abstract actions to perform for this
180  // compilation. We avoid passing a Compilation here simply to
181  // enforce the abstraction that pipelining is not host or toolchain
182  // dependent (other than the driver driver test).
183  if (Host->useDriverDriver())
184    BuildUniversalActions(C->getArgs(), C->getActions());
185  else
186    BuildActions(C->getArgs(), C->getActions());
187
188  if (CCCPrintActions) {
189    PrintActions(*C);
190    return C;
191  }
192
193  BuildJobs(*C);
194
195  return C;
196}
197
198void Driver::PrintOptions(const ArgList &Args) const {
199  unsigned i = 0;
200  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
201       it != ie; ++it, ++i) {
202    Arg *A = *it;
203    llvm::errs() << "Option " << i << " - "
204                 << "Name: \"" << A->getOption().getName() << "\", "
205                 << "Values: {";
206    for (unsigned j = 0; j < A->getNumValues(); ++j) {
207      if (j)
208        llvm::errs() << ", ";
209      llvm::errs() << '"' << A->getValue(Args, j) << '"';
210    }
211    llvm::errs() << "}\n";
212  }
213}
214
215void Driver::PrintVersion() const {
216  static char buf[] = "$URL$";
217  char *zap = strstr(buf, "/lib/Driver");
218  if (zap)
219    *zap = 0;
220  zap = strstr(buf, "/clang/tools/clang");
221  if (zap)
222    *zap = 0;
223  const char *vers = buf+6;
224  // FIXME: Add cmake support and remove #ifdef
225#ifdef SVN_REVISION
226  const char *revision = SVN_REVISION;
227#else
228  const char *revision = "";
229#endif
230  // FIXME: The following handlers should use a callback mechanism, we
231  // don't know what the client would like to do.
232  llvm::errs() << "clang version 1.0 (" << vers << " " << revision << ")" << "\n";
233  // FIXME: Add cmake support and remove #ifdef
234#ifdef TARGET_TRIPLE
235  llvm::errs() << "Target: " << TARGET_TRIPLE << "\n";
236#endif
237}
238
239bool Driver::HandleImmediateArgs(const Compilation &C) {
240  // The order these options are handled in in gcc is all over the
241  // place, but we don't expect inconsistencies w.r.t. that to matter
242  // in practice.
243  if (C.getArgs().hasArg(options::OPT_v) ||
244      C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
245    PrintVersion();
246    SuppressMissingInputWarning = true;
247  }
248
249  const ToolChain &TC = C.getDefaultToolChain();
250  // FIXME: The following handlers should use a callback mechanism, we
251  // don't know what the client would like to do.
252  if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
253    llvm::outs() << GetFilePath(A->getValue(C.getArgs()), TC).toString()
254                 << "\n";
255    return false;
256  }
257
258  if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
259    llvm::outs() << GetProgramPath(A->getValue(C.getArgs()), TC).toString()
260                 << "\n";
261    return false;
262  }
263
264  if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
265    llvm::outs() << GetProgramPath("libgcc.a", TC).toString() << "\n";
266    return false;
267  }
268
269  return true;
270}
271
272static unsigned PrintActions1(const Compilation &C,
273                              Action *A,
274                              std::map<Action*, unsigned> &Ids) {
275  if (Ids.count(A))
276    return Ids[A];
277
278  std::string str;
279  llvm::raw_string_ostream os(str);
280
281  os << Action::getClassName(A->getKind()) << ", ";
282  if (InputAction *IA = dyn_cast<InputAction>(A)) {
283    os << "\"" << IA->getInputArg().getValue(C.getArgs()) << "\"";
284  } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
285    os << '"' << (BIA->getArchName() ? BIA->getArchName() :
286                  C.getDefaultToolChain().getArchName()) << '"'
287       << ", {" << PrintActions1(C, *BIA->begin(), Ids) << "}";
288  } else {
289    os << "{";
290    for (Action::iterator it = A->begin(), ie = A->end(); it != ie;) {
291      os << PrintActions1(C, *it, Ids);
292      ++it;
293      if (it != ie)
294        os << ", ";
295    }
296    os << "}";
297  }
298
299  unsigned Id = Ids.size();
300  Ids[A] = Id;
301  llvm::errs() << Id << ": " << os.str() << ", "
302               << types::getTypeName(A->getType()) << "\n";
303
304  return Id;
305}
306
307void Driver::PrintActions(const Compilation &C) const {
308  std::map<Action*, unsigned> Ids;
309  for (ActionList::const_iterator it = C.getActions().begin(),
310         ie = C.getActions().end(); it != ie; ++it)
311    PrintActions1(C, *it, Ids);
312}
313
314void Driver::BuildUniversalActions(const ArgList &Args,
315                                   ActionList &Actions) const {
316  llvm::PrettyStackTraceString CrashInfo("Building actions for universal build");
317  // Collect the list of architectures. Duplicates are allowed, but
318  // should only be handled once (in the order seen).
319  llvm::StringSet<> ArchNames;
320  llvm::SmallVector<const char *, 4> Archs;
321  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
322       it != ie; ++it) {
323    Arg *A = *it;
324
325    if (A->getOption().getId() == options::OPT_arch) {
326      const char *Name = A->getValue(Args);
327
328      // FIXME: We need to handle canonicalization of the specified
329      // arch?
330
331      if (ArchNames.insert(Name))
332        Archs.push_back(Name);
333    }
334  }
335
336  // When there is no explicit arch for this platform, make sure we
337  // still bind the architecture (to the default) so that -Xarch_ is
338  // handled correctly.
339  if (!Archs.size())
340    Archs.push_back(0);
341
342  // FIXME: We killed off some others but these aren't yet detected in
343  // a functional manner. If we added information to jobs about which
344  // "auxiliary" files they wrote then we could detect the conflict
345  // these cause downstream.
346  if (Archs.size() > 1) {
347    // No recovery needed, the point of this is just to prevent
348    // overwriting the same files.
349    if (const Arg *A = Args.getLastArg(options::OPT_M_Group))
350      Diag(clang::diag::err_drv_invalid_opt_with_multiple_archs)
351        << A->getOption().getName();
352    if (const Arg *A = Args.getLastArg(options::OPT_save_temps))
353      Diag(clang::diag::err_drv_invalid_opt_with_multiple_archs)
354        << A->getOption().getName();
355  }
356
357  ActionList SingleActions;
358  BuildActions(Args, SingleActions);
359
360  // Add in arch binding and lipo (if necessary) for every top level
361  // action.
362  for (unsigned i = 0, e = SingleActions.size(); i != e; ++i) {
363    Action *Act = SingleActions[i];
364
365    // Make sure we can lipo this kind of output. If not (and it is an
366    // actual output) then we disallow, since we can't create an
367    // output file with the right name without overwriting it. We
368    // could remove this oddity by just changing the output names to
369    // include the arch, which would also fix
370    // -save-temps. Compatibility wins for now.
371
372    if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
373      Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
374        << types::getTypeName(Act->getType());
375
376    ActionList Inputs;
377    for (unsigned i = 0, e = Archs.size(); i != e; ++i )
378      Inputs.push_back(new BindArchAction(Act, Archs[i]));
379
380    // Lipo if necessary, We do it this way because we need to set the
381    // arch flag so that -Xarch_ gets overwritten.
382    if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
383      Actions.append(Inputs.begin(), Inputs.end());
384    else
385      Actions.push_back(new LipoJobAction(Inputs, Act->getType()));
386  }
387}
388
389void Driver::BuildActions(const ArgList &Args, ActionList &Actions) const {
390  llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
391  // Start by constructing the list of inputs and their types.
392
393  // Track the current user specified (-x) input. We also explicitly
394  // track the argument used to set the type; we only want to claim
395  // the type when we actually use it, so we warn about unused -x
396  // arguments.
397  types::ID InputType = types::TY_Nothing;
398  Arg *InputTypeArg = 0;
399
400  llvm::SmallVector<std::pair<types::ID, const Arg*>, 16> Inputs;
401  for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
402       it != ie; ++it) {
403    Arg *A = *it;
404
405    if (isa<InputOption>(A->getOption())) {
406      const char *Value = A->getValue(Args);
407      types::ID Ty = types::TY_INVALID;
408
409      // Infer the input type if necessary.
410      if (InputType == types::TY_Nothing) {
411        // If there was an explicit arg for this, claim it.
412        if (InputTypeArg)
413          InputTypeArg->claim();
414
415        // stdin must be handled specially.
416        if (memcmp(Value, "-", 2) == 0) {
417          // If running with -E, treat as a C input (this changes the
418          // builtin macros, for example). This may be overridden by
419          // -ObjC below.
420          //
421          // Otherwise emit an error but still use a valid type to
422          // avoid spurious errors (e.g., no inputs).
423          if (!Args.hasArg(options::OPT_E, false))
424            Diag(clang::diag::err_drv_unknown_stdin_type);
425          Ty = types::TY_C;
426        } else {
427          // Otherwise lookup by extension, and fallback to ObjectType
428          // if not found.
429          if (const char *Ext = strrchr(Value, '.'))
430            Ty = types::lookupTypeForExtension(Ext + 1);
431          if (Ty == types::TY_INVALID)
432            Ty = types::TY_Object;
433        }
434
435        // -ObjC and -ObjC++ override the default language, but only
436        // -for "source files". We just treat everything that isn't a
437        // -linker input as a source file.
438        //
439        // FIXME: Clean this up if we move the phase sequence into the
440        // type.
441        if (Ty != types::TY_Object) {
442          if (Args.hasArg(options::OPT_ObjC))
443            Ty = types::TY_ObjC;
444          else if (Args.hasArg(options::OPT_ObjCXX))
445            Ty = types::TY_ObjCXX;
446        }
447      } else {
448        assert(InputTypeArg && "InputType set w/o InputTypeArg");
449        InputTypeArg->claim();
450        Ty = InputType;
451      }
452
453      // Check that the file exists. It isn't clear this is worth
454      // doing, since the tool presumably does this anyway, and this
455      // just adds an extra stat to the equation, but this is gcc
456      // compatible.
457      if (memcmp(Value, "-", 2) != 0 && !llvm::sys::Path(Value).exists())
458        Diag(clang::diag::err_drv_no_such_file) << A->getValue(Args);
459      else
460        Inputs.push_back(std::make_pair(Ty, A));
461
462    } else if (A->getOption().isLinkerInput()) {
463      // Just treat as object type, we could make a special type for
464      // this if necessary.
465      Inputs.push_back(std::make_pair(types::TY_Object, A));
466
467    } else if (A->getOption().getId() == options::OPT_x) {
468      InputTypeArg = A;
469      InputType = types::lookupTypeForTypeSpecifier(A->getValue(Args));
470
471      // Follow gcc behavior and treat as linker input for invalid -x
472      // options. Its not clear why we shouldn't just revert to
473      // unknown; but this isn't very important, we might as well be
474      // bug comatible.
475      if (!InputType) {
476        Diag(clang::diag::err_drv_unknown_language) << A->getValue(Args);
477        InputType = types::TY_Object;
478      }
479    }
480  }
481
482  if (!SuppressMissingInputWarning && Inputs.empty()) {
483    Diag(clang::diag::err_drv_no_input_files);
484    return;
485  }
486
487  // Determine which compilation mode we are in. We look for options
488  // which affect the phase, starting with the earliest phases, and
489  // record which option we used to determine the final phase.
490  Arg *FinalPhaseArg = 0;
491  phases::ID FinalPhase;
492
493  // -{E,M,MM} only run the preprocessor.
494  if ((FinalPhaseArg = Args.getLastArg(options::OPT_E)) ||
495      (FinalPhaseArg = Args.getLastArg(options::OPT_M)) ||
496      (FinalPhaseArg = Args.getLastArg(options::OPT_MM))) {
497    FinalPhase = phases::Preprocess;
498
499    // -{fsyntax-only,-analyze,emit-llvm,S} only run up to the compiler.
500  } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_fsyntax_only)) ||
501             (FinalPhaseArg = Args.getLastArg(options::OPT__analyze)) ||
502             (FinalPhaseArg = Args.getLastArg(options::OPT_emit_llvm)) ||
503             (FinalPhaseArg = Args.getLastArg(options::OPT_S))) {
504    FinalPhase = phases::Compile;
505
506    // -c only runs up to the assembler.
507  } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_c))) {
508    FinalPhase = phases::Assemble;
509
510    // Otherwise do everything.
511  } else
512    FinalPhase = phases::Link;
513
514  // Reject -Z* at the top level, these options should never have been
515  // exposed by gcc.
516  if (Arg *A = Args.getLastArg(options::OPT_Z))
517    Diag(clang::diag::err_drv_use_of_Z_option) << A->getValue(Args);
518
519  // Construct the actions to perform.
520  ActionList LinkerInputs;
521  for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
522    types::ID InputType = Inputs[i].first;
523    const Arg *InputArg = Inputs[i].second;
524
525    unsigned NumSteps = types::getNumCompilationPhases(InputType);
526    assert(NumSteps && "Invalid number of steps!");
527
528    // If the first step comes after the final phase we are doing as
529    // part of this compilation, warn the user about it.
530    phases::ID InitialPhase = types::getCompilationPhase(InputType, 0);
531    if (InitialPhase > FinalPhase) {
532      Diag(clang::diag::warn_drv_input_file_unused)
533        << InputArg->getValue(Args)
534        << getPhaseName(InitialPhase)
535        << FinalPhaseArg->getOption().getName();
536      continue;
537    }
538
539    // Build the pipeline for this file.
540    Action *Current = new InputAction(*InputArg, InputType);
541    for (unsigned i = 0; i != NumSteps; ++i) {
542      phases::ID Phase = types::getCompilationPhase(InputType, i);
543
544      // We are done if this step is past what the user requested.
545      if (Phase > FinalPhase)
546        break;
547
548      // Queue linker inputs.
549      if (Phase == phases::Link) {
550        assert(i + 1 == NumSteps && "linking must be final compilation step.");
551        LinkerInputs.push_back(Current);
552        Current = 0;
553        break;
554      }
555
556      // Otherwise construct the appropriate action.
557      Current = ConstructPhaseAction(Args, Phase, Current);
558      if (Current->getType() == types::TY_Nothing)
559        break;
560    }
561
562    // If we ended with something, add to the output list.
563    if (Current)
564      Actions.push_back(Current);
565  }
566
567  // Add a link action if necessary.
568  if (!LinkerInputs.empty())
569    Actions.push_back(new LinkJobAction(LinkerInputs, types::TY_Image));
570}
571
572Action *Driver::ConstructPhaseAction(const ArgList &Args, phases::ID Phase,
573                                     Action *Input) const {
574  llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
575  // Build the appropriate action.
576  switch (Phase) {
577  case phases::Link: assert(0 && "link action invalid here.");
578  case phases::Preprocess: {
579    types::ID OutputTy = types::getPreprocessedType(Input->getType());
580    assert(OutputTy != types::TY_INVALID &&
581           "Cannot preprocess this input type!");
582    return new PreprocessJobAction(Input, OutputTy);
583  }
584  case phases::Precompile:
585    return new PrecompileJobAction(Input, types::TY_PCH);
586  case phases::Compile: {
587    if (Args.hasArg(options::OPT_fsyntax_only)) {
588      return new CompileJobAction(Input, types::TY_Nothing);
589    } else if (Args.hasArg(options::OPT__analyze)) {
590      return new AnalyzeJobAction(Input, types::TY_Plist);
591    } else if (Args.hasArg(options::OPT_emit_llvm)) {
592      types::ID Output =
593        Args.hasArg(options::OPT_S) ? types::TY_LLVMAsm : types::TY_LLVMBC;
594      return new CompileJobAction(Input, Output);
595    } else {
596      return new CompileJobAction(Input, types::TY_PP_Asm);
597    }
598  }
599  case phases::Assemble:
600    return new AssembleJobAction(Input, types::TY_Object);
601  }
602
603  assert(0 && "invalid phase in ConstructPhaseAction");
604  return 0;
605}
606
607void Driver::BuildJobs(Compilation &C) const {
608  llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
609  bool SaveTemps = C.getArgs().hasArg(options::OPT_save_temps);
610  bool UsePipes = C.getArgs().hasArg(options::OPT_pipe);
611
612  // FIXME: Pipes are forcibly disabled until we support executing
613  // them.
614  if (!CCCPrintBindings)
615    UsePipes = false;
616
617  // -save-temps inhibits pipes.
618  if (SaveTemps && UsePipes) {
619    Diag(clang::diag::warn_drv_pipe_ignored_with_save_temps);
620    UsePipes = true;
621  }
622
623  Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
624
625  // It is an error to provide a -o option if we are making multiple
626  // output files.
627  if (FinalOutput) {
628    unsigned NumOutputs = 0;
629    for (ActionList::const_iterator it = C.getActions().begin(),
630           ie = C.getActions().end(); it != ie; ++it)
631      if ((*it)->getType() != types::TY_Nothing)
632        ++NumOutputs;
633
634    if (NumOutputs > 1) {
635      Diag(clang::diag::err_drv_output_argument_with_multiple_files);
636      FinalOutput = 0;
637    }
638  }
639
640  for (ActionList::const_iterator it = C.getActions().begin(),
641         ie = C.getActions().end(); it != ie; ++it) {
642    Action *A = *it;
643
644    // If we are linking an image for multiple archs then the linker
645    // wants -arch_multiple and -final_output <final image
646    // name>. Unfortunately, this doesn't fit in cleanly because we
647    // have to pass this information down.
648    //
649    // FIXME: This is a hack; find a cleaner way to integrate this
650    // into the process.
651    const char *LinkingOutput = 0;
652    if (isa<LinkJobAction>(A)) {
653      if (FinalOutput)
654        LinkingOutput = FinalOutput->getValue(C.getArgs());
655      else
656        LinkingOutput = DefaultImageName.c_str();
657    }
658
659    InputInfo II;
660    BuildJobsForAction(C, A, &C.getDefaultToolChain(),
661                       /*CanAcceptPipe*/ true,
662                       /*AtTopLevel*/ true,
663                       /*LinkingOutput*/ LinkingOutput,
664                       II);
665  }
666
667  // If there were errors, don't warn about any unused arguments.
668  if (Diags.getNumErrors())
669    return;
670
671  for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
672       it != ie; ++it) {
673    Arg *A = *it;
674
675    // FIXME: It would be nice to be able to send the argument to the
676    // Diagnostic, so that extra values, position, and so on could be
677    // printed.
678    if (!A->isClaimed())
679      Diag(clang::diag::warn_drv_unused_argument)
680        << A->getOption().getName();
681  }
682}
683
684void Driver::BuildJobsForAction(Compilation &C,
685                                const Action *A,
686                                const ToolChain *TC,
687                                bool CanAcceptPipe,
688                                bool AtTopLevel,
689                                const char *LinkingOutput,
690                                InputInfo &Result) const {
691  llvm::PrettyStackTraceString CrashInfo("Building compilation jobs for action");
692
693  bool UsePipes = C.getArgs().hasArg(options::OPT_pipe);
694  // FIXME: Pipes are forcibly disabled until we support executing
695  // them.
696  if (!CCCPrintBindings)
697    UsePipes = false;
698
699  if (const InputAction *IA = dyn_cast<InputAction>(A)) {
700    // FIXME: This is broken, linker inputs won't work here.
701    assert(isa<PositionalArg>(IA->getInputArg()) && "FIXME: Linker inputs");
702
703    IA->getInputArg().claim();
704    const char *Name = IA->getInputArg().getValue(C.getArgs());
705    Result = InputInfo(Name, A->getType(), Name);
706    return;
707  }
708
709  if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
710    const char *ArchName = BAA->getArchName();
711    if (!ArchName)
712      ArchName = C.getDefaultToolChain().getArchName().c_str();
713    BuildJobsForAction(C,
714                       *BAA->begin(),
715                       Host->getToolChain(C.getArgs(), ArchName),
716                       CanAcceptPipe,
717                       AtTopLevel,
718                       LinkingOutput,
719                       Result);
720    return;
721  }
722
723  const JobAction *JA = cast<JobAction>(A);
724  const Tool &T = TC->SelectTool(C, *JA);
725
726  // See if we should use an integrated preprocessor. We do so when we
727  // have exactly one input, since this is the only use case we care
728  // about (irrelevant since we don't support combine yet).
729  bool UseIntegratedCPP = false;
730  const ActionList *Inputs = &A->getInputs();
731  if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin())) {
732    if (!C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
733        !C.getArgs().hasArg(options::OPT_traditional_cpp) &&
734        !C.getArgs().hasArg(options::OPT_save_temps) &&
735        T.hasIntegratedCPP()) {
736      UseIntegratedCPP = true;
737      Inputs = &(*Inputs)[0]->getInputs();
738    }
739  }
740
741  // Only use pipes when there is exactly one input.
742  bool TryToUsePipeInput = Inputs->size() == 1 && T.acceptsPipedInput();
743  InputInfoList InputInfos;
744  for (ActionList::const_iterator it = Inputs->begin(), ie = Inputs->end();
745       it != ie; ++it) {
746    InputInfo II;
747    BuildJobsForAction(C, *it, TC, TryToUsePipeInput,
748                       /*AtTopLevel*/false,
749                       LinkingOutput,
750                       II);
751    InputInfos.push_back(II);
752  }
753
754  // Determine if we should output to a pipe.
755  bool OutputToPipe = false;
756  if (CanAcceptPipe && T.canPipeOutput()) {
757    // Some actions default to writing to a pipe if they are the top
758    // level phase and there was no user override.
759    //
760    // FIXME: Is there a better way to handle this?
761    if (AtTopLevel) {
762      if (isa<PreprocessJobAction>(A) && !C.getArgs().hasArg(options::OPT_o))
763        OutputToPipe = true;
764    } else if (UsePipes)
765      OutputToPipe = true;
766  }
767
768  // Figure out where to put the job (pipes).
769  Job *Dest = &C.getJobs();
770  if (InputInfos[0].isPipe()) {
771    assert(TryToUsePipeInput && "Unrequested pipe!");
772    assert(InputInfos.size() == 1 && "Unexpected pipe with multiple inputs.");
773    Dest = &InputInfos[0].getPipe();
774  }
775
776  // Always use the first input as the base input.
777  const char *BaseInput = InputInfos[0].getBaseInput();
778
779  // Determine the place to write output to (nothing, pipe, or
780  // filename) and where to put the new job.
781  if (JA->getType() == types::TY_Nothing) {
782    Result = InputInfo(A->getType(), BaseInput);
783  } else if (OutputToPipe) {
784    // Append to current piped job or create a new one as appropriate.
785    PipedJob *PJ = dyn_cast<PipedJob>(Dest);
786    if (!PJ) {
787      PJ = new PipedJob();
788      cast<JobList>(Dest)->addJob(PJ);
789      Dest = PJ;
790    }
791    Result = InputInfo(PJ, A->getType(), BaseInput);
792  } else {
793    Result = InputInfo(GetNamedOutputPath(C, *JA, BaseInput, AtTopLevel),
794                       A->getType(), BaseInput);
795  }
796
797  if (CCCPrintBindings) {
798    llvm::errs() << "bind - \"" << T.getName() << "\", inputs: [";
799    for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
800      llvm::errs() << InputInfos[i].getAsString();
801      if (i + 1 != e)
802        llvm::errs() << ", ";
803    }
804    llvm::errs() << "], output: " << Result.getAsString() << "\n";
805  } else {
806    const ArgList &TCArgs = C.getArgsForToolChain(TC);
807    T.ConstructJob(C, *JA, *Dest, Result, InputInfos, TCArgs, LinkingOutput);
808  }
809}
810
811const char *Driver::GetNamedOutputPath(Compilation &C,
812                                       const JobAction &JA,
813                                       const char *BaseInput,
814                                       bool AtTopLevel) const {
815  llvm::PrettyStackTraceString CrashInfo("Computing output path");
816  // Output to a user requested destination?
817  if (AtTopLevel) {
818    if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
819      return C.addResultFile(FinalOutput->getValue(C.getArgs()));
820  }
821
822  // Output to a temporary file?
823  if (!AtTopLevel && !C.getArgs().hasArg(options::OPT_save_temps)) {
824    std::string TmpName =
825      GetTemporaryPath(types::getTypeTempSuffix(JA.getType()));
826    return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
827  }
828
829  llvm::sys::Path BasePath(BaseInput);
830  std::string BaseName(BasePath.getLast());
831
832  // Determine what the derived output name should be.
833  const char *NamedOutput;
834  if (JA.getType() == types::TY_Image) {
835    NamedOutput = DefaultImageName.c_str();
836  } else {
837    const char *Suffix = types::getTypeTempSuffix(JA.getType());
838    assert(Suffix && "All types used for output should have a suffix.");
839
840    std::string::size_type End = std::string::npos;
841    if (!types::appendSuffixForType(JA.getType()))
842      End = BaseName.rfind('.');
843    std::string Suffixed(BaseName.substr(0, End));
844    Suffixed += '.';
845    Suffixed += Suffix;
846    NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
847  }
848
849  // As an annoying special case, PCH generation doesn't strip the
850  // pathname.
851  if (JA.getType() == types::TY_PCH) {
852    BasePath.eraseComponent();
853    if (BasePath.isEmpty())
854      BasePath = NamedOutput;
855    else
856      BasePath.appendComponent(NamedOutput);
857    return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()));
858  } else {
859    return C.addResultFile(NamedOutput);
860  }
861}
862
863llvm::sys::Path Driver::GetFilePath(const char *Name,
864                                    const ToolChain &TC) const {
865  const ToolChain::path_list &List = TC.getFilePaths();
866  for (ToolChain::path_list::const_iterator
867         it = List.begin(), ie = List.end(); it != ie; ++it) {
868    llvm::sys::Path P(*it);
869    P.appendComponent(Name);
870    if (P.exists())
871      return P;
872  }
873
874  return llvm::sys::Path(Name);
875}
876
877llvm::sys::Path Driver::GetProgramPath(const char *Name,
878                                       const ToolChain &TC) const {
879  const ToolChain::path_list &List = TC.getProgramPaths();
880  for (ToolChain::path_list::const_iterator
881         it = List.begin(), ie = List.end(); it != ie; ++it) {
882    llvm::sys::Path P(*it);
883    P.appendComponent(Name);
884    if (P.exists())
885      return P;
886  }
887
888  // As a last resort, always search in our directory before pulling
889  // from the path.
890  llvm::sys::Path P(Dir);
891  P.appendComponent(Name);
892  if (P.exists())
893    return P;
894
895  // Search path to increase accuracy of logging output.
896  P = llvm::sys::Program::FindProgramByName(Name);
897  if (!P.empty())
898    return P;
899
900  return llvm::sys::Path(Name);
901}
902
903std::string Driver::GetTemporaryPath(const char *Suffix) const {
904  // FIXME: This is lame; sys::Path should provide this function (in
905  // particular, it should know how to find the temporary files dir).
906  std::string Error;
907  llvm::sys::Path P("/tmp/cc");
908  if (P.makeUnique(false, &Error)) {
909    Diag(clang::diag::err_drv_unable_to_make_temp) << Error;
910    return "";
911  }
912
913  // FIXME: Grumble, makeUnique sometimes leaves the file around!?
914  // PR3837.
915  P.eraseFromDisk(false, 0);
916
917  P.appendSuffix(Suffix);
918  return P.toString();
919}
920
921const HostInfo *Driver::GetHostInfo(const char *Triple) const {
922  llvm::PrettyStackTraceString CrashInfo("Constructing host");
923  // Dice into arch, platform, and OS. This matches
924  //  arch,platform,os = '(.*?)-(.*?)-(.*?)'
925  // and missing fields are left empty.
926  std::string Arch, Platform, OS;
927
928  if (const char *ArchEnd = strchr(Triple, '-')) {
929    Arch = std::string(Triple, ArchEnd);
930
931    if (const char *PlatformEnd = strchr(ArchEnd+1, '-')) {
932      Platform = std::string(ArchEnd+1, PlatformEnd);
933      OS = PlatformEnd+1;
934    } else
935      Platform = ArchEnd+1;
936  } else
937    Arch = Triple;
938
939  // Normalize Arch a bit.
940  //
941  // FIXME: This is very incomplete.
942  if (Arch == "i686")
943    Arch = "i386";
944  else if (Arch == "amd64")
945    Arch = "x86_64";
946  else if (Arch == "powerpc" || Arch == "Power Macintosh")
947    Arch = "ppc";
948
949  if (memcmp(&OS[0], "darwin", 6) == 0)
950    return createDarwinHostInfo(*this, Arch.c_str(), Platform.c_str(),
951                                OS.c_str());
952
953  return createUnknownHostInfo(*this, Arch.c_str(), Platform.c_str(),
954                               OS.c_str());
955}
956