1 //===--- Driver.cpp - Clang GCC Compatible Driver -------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "clang/Driver/Driver.h"
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/Job.h"
18 #include "clang/Driver/OptTable.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"
24 #include "clang/Basic/Version.h"
26 #include "llvm/ADT/ArrayRef.h"
27 #include "llvm/ADT/StringSet.h"
28 #include "llvm/ADT/OwningPtr.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/PrettyStackTrace.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/Support/FileSystem.h"
33 #include "llvm/Support/Path.h"
34 #include "llvm/Support/Program.h"
36 #include "InputInfo.h"
37 #include "ToolChains.h"
41 #include "clang/Config/config.h"
43 using namespace clang::driver
;
44 using namespace clang
;
46 Driver::Driver(StringRef ClangExecutable
,
47 StringRef DefaultTargetTriple
,
48 StringRef DefaultImageName
,
50 DiagnosticsEngine
&Diags
)
51 : Opts(createDriverOptTable()), Diags(Diags
),
52 ClangExecutable(ClangExecutable
), SysRoot(DEFAULT_SYSROOT
),
53 UseStdLib(true), DefaultTargetTriple(DefaultTargetTriple
),
54 DefaultImageName(DefaultImageName
),
55 DriverTitle("clang LLVM compiler"),
56 CCPrintOptionsFilename(0), CCPrintHeadersFilename(0),
57 CCLogDiagnosticsFilename(0), CCCIsCXX(false),
58 CCCIsCPP(false),CCCEcho(false), CCCPrintBindings(false),
59 CCPrintOptions(false), CCPrintHeaders(false), CCLogDiagnostics(false),
60 CCGenDiagnostics(false), CCCGenericGCCName(""), CheckInputsExist(true),
61 CCCUseClang(true), CCCUseClangCXX(true), CCCUseClangCPP(true),
62 ForcedClangUse(false), CCCUsePCH(true), SuppressMissingInputWarning(false) {
64 // In a "production" build, only use clang on architectures we expect to
67 // During development its more convenient to always have the driver use
68 // clang, but we don't want users to be confused when things don't work, or
69 // to file bugs for things we don't support.
70 CCCClangArchs
.insert(llvm::Triple::x86
);
71 CCCClangArchs
.insert(llvm::Triple::x86_64
);
72 CCCClangArchs
.insert(llvm::Triple::arm
);
75 Name
= llvm::sys::path::stem(ClangExecutable
);
76 Dir
= llvm::sys::path::parent_path(ClangExecutable
);
78 // Compute the path to the resource directory.
79 StringRef
ClangResourceDir(CLANG_RESOURCE_DIR
);
80 SmallString
<128> P(Dir
);
81 if (ClangResourceDir
!= "")
82 llvm::sys::path::append(P
, ClangResourceDir
);
84 llvm::sys::path::append(P
, "..", "lib", "clang", CLANG_VERSION_STRING
);
85 ResourceDir
= P
.str();
91 for (llvm::StringMap
<ToolChain
*>::iterator I
= ToolChains
.begin(),
97 InputArgList
*Driver::ParseArgStrings(ArrayRef
<const char *> ArgList
) {
98 llvm::PrettyStackTraceString
CrashInfo("Command line argument parsing");
99 unsigned MissingArgIndex
, MissingArgCount
;
100 InputArgList
*Args
= getOpts().ParseArgs(ArgList
.begin(), ArgList
.end(),
101 MissingArgIndex
, MissingArgCount
);
103 // Check for missing argument error.
105 Diag(clang::diag::err_drv_missing_argument
)
106 << Args
->getArgString(MissingArgIndex
) << MissingArgCount
;
108 // Check for unsupported options.
109 for (ArgList::const_iterator it
= Args
->begin(), ie
= Args
->end();
112 if (A
->getOption().isUnsupported()) {
113 Diag(clang::diag::err_drv_unsupported_opt
) << A
->getAsString(*Args
);
117 // Warn about -mcpu= without an argument.
118 if (A
->getOption().matches(options::OPT_mcpu_EQ
) &&
119 A
->containsValue("")) {
120 Diag(clang::diag::warn_drv_empty_joined_argument
) <<
121 A
->getAsString(*Args
);
128 // Determine which compilation mode we are in. We look for options which
129 // affect the phase, starting with the earliest phases, and record which
130 // option we used to determine the final phase.
131 phases::ID
Driver::getFinalPhase(const DerivedArgList
&DAL
, Arg
**FinalPhaseArg
)
134 phases::ID FinalPhase
;
136 // -{E,M,MM} only run the preprocessor.
138 (PhaseArg
= DAL
.getLastArg(options::OPT_E
)) ||
139 (PhaseArg
= DAL
.getLastArg(options::OPT_M
, options::OPT_MM
))) {
140 FinalPhase
= phases::Preprocess
;
142 // -{fsyntax-only,-analyze,emit-ast,S} only run up to the compiler.
143 } else if ((PhaseArg
= DAL
.getLastArg(options::OPT_fsyntax_only
)) ||
144 (PhaseArg
= DAL
.getLastArg(options::OPT_rewrite_objc
)) ||
145 (PhaseArg
= DAL
.getLastArg(options::OPT_rewrite_legacy_objc
)) ||
146 (PhaseArg
= DAL
.getLastArg(options::OPT__migrate
)) ||
147 (PhaseArg
= DAL
.getLastArg(options::OPT__analyze
,
148 options::OPT__analyze_auto
)) ||
149 (PhaseArg
= DAL
.getLastArg(options::OPT_emit_ast
)) ||
150 (PhaseArg
= DAL
.getLastArg(options::OPT_S
))) {
151 FinalPhase
= phases::Compile
;
153 // -c only runs up to the assembler.
154 } else if ((PhaseArg
= DAL
.getLastArg(options::OPT_c
))) {
155 FinalPhase
= phases::Assemble
;
157 // Otherwise do everything.
159 FinalPhase
= phases::Link
;
162 *FinalPhaseArg
= PhaseArg
;
167 DerivedArgList
*Driver::TranslateInputArgs(const InputArgList
&Args
) const {
168 DerivedArgList
*DAL
= new DerivedArgList(Args
);
170 bool HasNostdlib
= Args
.hasArg(options::OPT_nostdlib
);
171 for (ArgList::const_iterator it
= Args
.begin(),
172 ie
= Args
.end(); it
!= ie
; ++it
) {
175 // Unfortunately, we have to parse some forwarding options (-Xassembler,
176 // -Xlinker, -Xpreprocessor) because we either integrate their functionality
177 // (assembler and preprocessor), or bypass a previous driver ('collect2').
179 // Rewrite linker options, to replace --no-demangle with a custom internal
181 if ((A
->getOption().matches(options::OPT_Wl_COMMA
) ||
182 A
->getOption().matches(options::OPT_Xlinker
)) &&
183 A
->containsValue("--no-demangle")) {
184 // Add the rewritten no-demangle argument.
185 DAL
->AddFlagArg(A
, Opts
->getOption(options::OPT_Z_Xlinker__no_demangle
));
187 // Add the remaining values as Xlinker arguments.
188 for (unsigned i
= 0, e
= A
->getNumValues(); i
!= e
; ++i
)
189 if (StringRef(A
->getValue(Args
, i
)) != "--no-demangle")
190 DAL
->AddSeparateArg(A
, Opts
->getOption(options::OPT_Xlinker
),
191 A
->getValue(Args
, i
));
196 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
197 // some build systems. We don't try to be complete here because we don't
198 // care to encourage this usage model.
199 if (A
->getOption().matches(options::OPT_Wp_COMMA
) &&
200 A
->getNumValues() == 2 &&
201 (A
->getValue(Args
, 0) == StringRef("-MD") ||
202 A
->getValue(Args
, 0) == StringRef("-MMD"))) {
203 // Rewrite to -MD/-MMD along with -MF.
204 if (A
->getValue(Args
, 0) == StringRef("-MD"))
205 DAL
->AddFlagArg(A
, Opts
->getOption(options::OPT_MD
));
207 DAL
->AddFlagArg(A
, Opts
->getOption(options::OPT_MMD
));
208 DAL
->AddSeparateArg(A
, Opts
->getOption(options::OPT_MF
),
209 A
->getValue(Args
, 1));
213 // Rewrite reserved library names.
214 if (A
->getOption().matches(options::OPT_l
)) {
215 StringRef Value
= A
->getValue(Args
);
217 // Rewrite unless -nostdlib is present.
218 if (!HasNostdlib
&& Value
== "stdc++") {
219 DAL
->AddFlagArg(A
, Opts
->getOption(
220 options::OPT_Z_reserved_lib_stdcxx
));
224 // Rewrite unconditionally.
225 if (Value
== "cc_kext") {
226 DAL
->AddFlagArg(A
, Opts
->getOption(
227 options::OPT_Z_reserved_lib_cckext
));
235 // Add a default value of -mlinker-version=, if one was given and the user
236 // didn't specify one.
237 #if defined(HOST_LINK_VERSION)
238 if (!Args
.hasArg(options::OPT_mlinker_version_EQ
)) {
239 DAL
->AddJoinedArg(0, Opts
->getOption(options::OPT_mlinker_version_EQ
),
241 DAL
->getLastArg(options::OPT_mlinker_version_EQ
)->claim();
248 Compilation
*Driver::BuildCompilation(ArrayRef
<const char *> ArgList
) {
249 llvm::PrettyStackTraceString
CrashInfo("Compilation construction");
251 // FIXME: Handle environment options which affect driver behavior, somewhere
252 // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
254 if (char *env
= ::getenv("COMPILER_PATH")) {
255 StringRef CompilerPath
= env
;
256 while (!CompilerPath
.empty()) {
257 std::pair
<StringRef
, StringRef
> Split
= CompilerPath
.split(':');
258 PrefixDirs
.push_back(Split
.first
);
259 CompilerPath
= Split
.second
;
263 // FIXME: What are we going to do with -V and -b?
265 // FIXME: This stuff needs to go into the Compilation, not the driver.
266 bool CCCPrintOptions
= false, CCCPrintActions
= false;
268 InputArgList
*Args
= ParseArgStrings(ArgList
.slice(1));
270 // -no-canonical-prefixes is used very early in main.
271 Args
->ClaimAllArgs(options::OPT_no_canonical_prefixes
);
274 Args
->ClaimAllArgs(options::OPT_pipe
);
276 // Extract -ccc args.
278 // FIXME: We need to figure out where this behavior should live. Most of it
279 // should be outside in the client; the parts that aren't should have proper
280 // options, either by introducing new ones or by overloading gcc ones like -V
282 CCCPrintOptions
= Args
->hasArg(options::OPT_ccc_print_options
);
283 CCCPrintActions
= Args
->hasArg(options::OPT_ccc_print_phases
);
284 CCCPrintBindings
= Args
->hasArg(options::OPT_ccc_print_bindings
);
285 CCCIsCXX
= Args
->hasArg(options::OPT_ccc_cxx
) || CCCIsCXX
;
286 CCCEcho
= Args
->hasArg(options::OPT_ccc_echo
);
287 if (const Arg
*A
= Args
->getLastArg(options::OPT_ccc_gcc_name
))
288 CCCGenericGCCName
= A
->getValue(*Args
);
289 CCCUseClangCXX
= Args
->hasFlag(options::OPT_ccc_clang_cxx
,
290 options::OPT_ccc_no_clang_cxx
,
292 CCCUsePCH
= Args
->hasFlag(options::OPT_ccc_pch_is_pch
,
293 options::OPT_ccc_pch_is_pth
);
294 CCCUseClang
= !Args
->hasArg(options::OPT_ccc_no_clang
);
295 CCCUseClangCPP
= !Args
->hasArg(options::OPT_ccc_no_clang_cpp
);
296 if (const Arg
*A
= Args
->getLastArg(options::OPT_ccc_clang_archs
)) {
297 StringRef Cur
= A
->getValue(*Args
);
299 CCCClangArchs
.clear();
300 while (!Cur
.empty()) {
301 std::pair
<StringRef
, StringRef
> Split
= Cur
.split(',');
303 if (!Split
.first
.empty()) {
304 llvm::Triple::ArchType Arch
=
305 llvm::Triple(Split
.first
, "", "").getArch();
307 if (Arch
== llvm::Triple::UnknownArch
)
308 Diag(clang::diag::err_drv_invalid_arch_name
) << Split
.first
;
310 CCCClangArchs
.insert(Arch
);
316 // FIXME: DefaultTargetTriple is used by the target-prefixed calls to as/ld
317 // and getToolChain is const.
318 if (const Arg
*A
= Args
->getLastArg(options::OPT_target
))
319 DefaultTargetTriple
= A
->getValue(*Args
);
320 if (const Arg
*A
= Args
->getLastArg(options::OPT_ccc_install_dir
))
321 Dir
= InstalledDir
= A
->getValue(*Args
);
322 for (arg_iterator it
= Args
->filtered_begin(options::OPT_B
),
323 ie
= Args
->filtered_end(); it
!= ie
; ++it
) {
326 PrefixDirs
.push_back(A
->getValue(*Args
, 0));
328 if (const Arg
*A
= Args
->getLastArg(options::OPT__sysroot_EQ
))
329 SysRoot
= A
->getValue(*Args
);
330 if (Args
->hasArg(options::OPT_nostdlib
))
333 // Perform the default argument translations.
334 DerivedArgList
*TranslatedArgs
= TranslateInputArgs(*Args
);
336 // Owned by the host.
337 const ToolChain
&TC
= getToolChain(*Args
);
339 // The compilation takes ownership of Args.
340 Compilation
*C
= new Compilation(*this, TC
, Args
, TranslatedArgs
);
342 // FIXME: This behavior shouldn't be here.
343 if (CCCPrintOptions
) {
344 PrintOptions(C
->getInputArgs());
348 if (!HandleImmediateArgs(*C
))
351 // Construct the list of inputs.
353 BuildInputs(C
->getDefaultToolChain(), C
->getArgs(), Inputs
);
355 // Construct the list of abstract actions to perform for this compilation. On
356 // Darwin target OSes this uses the driver-driver and universal actions.
357 if (TC
.getTriple().isOSDarwin())
358 BuildUniversalActions(C
->getDefaultToolChain(), C
->getArgs(),
359 Inputs
, C
->getActions());
361 BuildActions(C
->getDefaultToolChain(), C
->getArgs(), Inputs
,
364 if (CCCPrintActions
) {
374 // When clang crashes, produce diagnostic information including the fully
375 // preprocessed source file(s). Request that the developer attach the
376 // diagnostic information to a bug report.
377 void Driver::generateCompilationDiagnostics(Compilation
&C
,
378 const Command
*FailingCommand
) {
379 if (C
.getArgs().hasArg(options::OPT_fno_crash_diagnostics
))
382 // Don't try to generate diagnostics for link jobs.
383 if (FailingCommand
&& FailingCommand
->getCreator().isLinkJob())
386 // Print the version of the compiler.
387 PrintVersion(C
, llvm::errs());
389 Diag(clang::diag::note_drv_command_failed_diag_msg
)
390 << "PLEASE submit a bug report to " BUG_REPORT_URL
" and include the "
391 "crash backtrace, preprocessed source, and associated run script.";
393 // Suppress driver output and emit preprocessor output to temp file.
395 CCGenDiagnostics
= true;
396 C
.getArgs().AddFlagArg(0, Opts
->getOption(options::OPT_frewrite_includes
));
398 // Save the original job command(s).
400 llvm::raw_string_ostream
OS(Cmd
);
402 C
.PrintJob(OS
, *FailingCommand
, "\n", false);
404 // Crash triggered by FORCE_CLANG_DIAGNOSTICS_CRASH, which doesn't have an
405 // associated FailingCommand, so just pass all jobs.
406 C
.PrintJob(OS
, C
.getJobs(), "\n", false);
409 // Clear stale state and suppress tool output.
410 C
.initCompilationForDiagnostics();
413 // Construct the list of inputs.
415 BuildInputs(C
.getDefaultToolChain(), C
.getArgs(), Inputs
);
417 for (InputList::iterator it
= Inputs
.begin(), ie
= Inputs
.end(); it
!= ie
;) {
418 bool IgnoreInput
= false;
420 // Ignore input from stdin or any inputs that cannot be preprocessed.
421 if (!strcmp(it
->second
->getValue(C
.getArgs()), "-")) {
422 Diag(clang::diag::note_drv_command_failed_diag_msg
)
423 << "Error generating preprocessed source(s) - ignoring input from stdin"
426 } else if (types::getPreprocessedType(it
->first
) == types::TY_INVALID
) {
431 it
= Inputs
.erase(it
);
438 // Don't attempt to generate preprocessed files if multiple -arch options are
439 // used, unless they're all duplicates.
440 llvm::StringSet
<> ArchNames
;
441 for (ArgList::const_iterator it
= C
.getArgs().begin(), ie
= C
.getArgs().end();
444 if (A
->getOption().matches(options::OPT_arch
)) {
445 StringRef ArchName
= A
->getValue(C
.getArgs());
446 ArchNames
.insert(ArchName
);
449 if (ArchNames
.size() > 1) {
450 Diag(clang::diag::note_drv_command_failed_diag_msg
)
451 << "Error generating preprocessed source(s) - cannot generate "
452 "preprocessed source with multiple -arch options.";
456 if (Inputs
.empty()) {
457 Diag(clang::diag::note_drv_command_failed_diag_msg
)
458 << "Error generating preprocessed source(s) - no preprocessable inputs.";
462 // Construct the list of abstract actions to perform for this compilation. On
463 // Darwin OSes this uses the driver-driver and builds universal actions.
464 const ToolChain
&TC
= C
.getDefaultToolChain();
465 if (TC
.getTriple().isOSDarwin())
466 BuildUniversalActions(TC
, C
.getArgs(), Inputs
, C
.getActions());
468 BuildActions(TC
, C
.getArgs(), Inputs
, C
.getActions());
472 // If there were errors building the compilation, quit now.
473 if (Diags
.hasErrorOccurred()) {
474 Diag(clang::diag::note_drv_command_failed_diag_msg
)
475 << "Error generating preprocessed source(s).";
479 // Generate preprocessed output.
481 int Res
= C
.ExecuteJob(C
.getJobs(), FailingCommand
);
483 // If the command succeeded, we are done.
485 Diag(clang::diag::note_drv_command_failed_diag_msg
)
486 << "\n********************\n\n"
487 "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
488 "Preprocessed source(s) and associated run script(s) are located at:";
489 ArgStringList Files
= C
.getTempFiles();
490 for (ArgStringList::const_iterator it
= Files
.begin(), ie
= Files
.end();
492 Diag(clang::diag::note_drv_command_failed_diag_msg
) << *it
;
495 std::string Script
= StringRef(*it
).rsplit('.').first
;
497 llvm::raw_fd_ostream
ScriptOS(Script
.c_str(), Err
,
498 llvm::raw_fd_ostream::F_Excl
|
499 llvm::raw_fd_ostream::F_Binary
);
501 Diag(clang::diag::note_drv_command_failed_diag_msg
)
502 << "Error generating run script: " + Script
+ " " + Err
;
504 // Strip away options not necessary to reproduce the crash.
505 // FIXME: This doesn't work with quotes (e.g., -D "foo bar").
506 SmallVector
<std::string
, 16> Flag
;
507 Flag
.push_back("-D ");
508 Flag
.push_back("-F");
509 Flag
.push_back("-I ");
510 Flag
.push_back("-M ");
511 Flag
.push_back("-MD ");
512 Flag
.push_back("-MF ");
513 Flag
.push_back("-MG ");
514 Flag
.push_back("-MM ");
515 Flag
.push_back("-MMD ");
516 Flag
.push_back("-MP ");
517 Flag
.push_back("-MQ ");
518 Flag
.push_back("-MT ");
519 Flag
.push_back("-o ");
520 Flag
.push_back("-coverage-file ");
521 Flag
.push_back("-dependency-file ");
522 Flag
.push_back("-fdebug-compilation-dir ");
523 Flag
.push_back("-fmodule-cache-path ");
524 Flag
.push_back("-idirafter ");
525 Flag
.push_back("-include ");
526 Flag
.push_back("-include-pch ");
527 Flag
.push_back("-internal-isystem ");
528 Flag
.push_back("-internal-externc-isystem ");
529 Flag
.push_back("-iprefix ");
530 Flag
.push_back("-iwithprefix ");
531 Flag
.push_back("-iwithprefixbefore ");
532 Flag
.push_back("-isysroot ");
533 Flag
.push_back("-isystem ");
534 Flag
.push_back("-iquote ");
535 Flag
.push_back("-resource-dir ");
536 Flag
.push_back("-serialize-diagnostic-file ");
537 for (unsigned i
= 0, e
= Flag
.size(); i
< e
; ++i
) {
540 I
= Cmd
.find(Flag
[i
], I
);
541 if (I
== std::string::npos
) break;
543 E
= Cmd
.find(" ", I
+ Flag
[i
].length());
544 if (E
== std::string::npos
) break;
545 // The -D option is not removed. Instead, the argument is quoted.
546 if (Flag
[i
] != "-D ") {
547 Cmd
.erase(I
, E
- I
+ 1);
549 Cmd
.insert(I
+3, "\"");
550 Cmd
.insert(++E
, "\"");
555 // Append the new filename with correct preprocessed suffix.
557 I
= Cmd
.find("-main-file-name ");
558 assert (I
!= std::string::npos
&& "Expected to find -main-file-name");
560 E
= Cmd
.find(" ", I
);
561 assert (E
!= std::string::npos
&& "-main-file-name missing argument?");
562 StringRef OldFilename
= StringRef(Cmd
).slice(I
, E
);
563 StringRef NewFilename
= llvm::sys::path::filename(*it
);
564 I
= StringRef(Cmd
).rfind(OldFilename
);
565 E
= I
+ OldFilename
.size();
566 I
= Cmd
.rfind(" ", I
) + 1;
567 Cmd
.replace(I
, E
- I
, NewFilename
.data(), NewFilename
.size());
569 Diag(clang::diag::note_drv_command_failed_diag_msg
) << Script
;
572 Diag(clang::diag::note_drv_command_failed_diag_msg
)
573 << "\n\n********************";
575 // Failure, remove preprocessed files.
576 if (!C
.getArgs().hasArg(options::OPT_save_temps
))
577 C
.CleanupFileList(C
.getTempFiles(), true);
579 Diag(clang::diag::note_drv_command_failed_diag_msg
)
580 << "Error generating preprocessed source(s).";
584 int Driver::ExecuteCompilation(const Compilation
&C
,
585 const Command
*&FailingCommand
) const {
586 // Just print if -### was present.
587 if (C
.getArgs().hasArg(options::OPT__HASH_HASH_HASH
)) {
588 C
.PrintJob(llvm::errs(), C
.getJobs(), "\n", true);
592 // If there were errors building the compilation, quit now.
593 if (Diags
.hasErrorOccurred())
596 int Res
= C
.ExecuteJob(C
.getJobs(), FailingCommand
);
598 // Remove temp files.
599 C
.CleanupFileList(C
.getTempFiles());
601 // If the command succeeded, we are done.
605 // Otherwise, remove result files as well.
606 if (!C
.getArgs().hasArg(options::OPT_save_temps
)) {
607 C
.CleanupFileList(C
.getResultFiles(), true);
609 // Failure result files are valid unless we crashed.
611 C
.CleanupFileList(C
.getFailureResultFiles(), true);
614 // Print extra information about abnormal failures, if possible.
616 // This is ad-hoc, but we don't want to be excessively noisy. If the result
617 // status was 1, assume the command failed normally. In particular, if it was
618 // the compiler then assume it gave a reasonable error code. Failures in other
619 // tools are less common, and they generally have worse diagnostics, so always
620 // print the diagnostic there.
621 const Tool
&FailingTool
= FailingCommand
->getCreator();
623 if (!FailingCommand
->getCreator().hasGoodDiagnostics() || Res
!= 1) {
624 // FIXME: See FIXME above regarding result code interpretation.
626 Diag(clang::diag::err_drv_command_signalled
)
627 << FailingTool
.getShortName();
629 Diag(clang::diag::err_drv_command_failed
)
630 << FailingTool
.getShortName() << Res
;
636 void Driver::PrintOptions(const ArgList
&Args
) const {
638 for (ArgList::const_iterator it
= Args
.begin(), ie
= Args
.end();
639 it
!= ie
; ++it
, ++i
) {
641 llvm::errs() << "Option " << i
<< " - "
642 << "Name: \"" << A
->getOption().getName() << "\", "
644 for (unsigned j
= 0; j
< A
->getNumValues(); ++j
) {
646 llvm::errs() << ", ";
647 llvm::errs() << '"' << A
->getValue(Args
, j
) << '"';
649 llvm::errs() << "}\n";
653 void Driver::PrintHelp(bool ShowHidden
) const {
654 getOpts().PrintHelp(llvm::outs(), Name
.c_str(), DriverTitle
.c_str(),
658 void Driver::PrintVersion(const Compilation
&C
, raw_ostream
&OS
) const {
659 // FIXME: The following handlers should use a callback mechanism, we don't
660 // know what the client would like to do.
661 OS
<< getClangFullVersion() << '\n';
662 const ToolChain
&TC
= C
.getDefaultToolChain();
663 OS
<< "Target: " << TC
.getTripleString() << '\n';
665 // Print the threading model.
667 // FIXME: Implement correctly.
668 OS
<< "Thread model: " << "posix" << '\n';
671 /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
673 static void PrintDiagnosticCategories(raw_ostream
&OS
) {
674 // Skip the empty category.
675 for (unsigned i
= 1, max
= DiagnosticIDs::getNumberOfCategories();
677 OS
<< i
<< ',' << DiagnosticIDs::getCategoryNameFromID(i
) << '\n';
680 bool Driver::HandleImmediateArgs(const Compilation
&C
) {
681 // The order these options are handled in gcc is all over the place, but we
682 // don't expect inconsistencies w.r.t. that to matter in practice.
684 if (C
.getArgs().hasArg(options::OPT_dumpmachine
)) {
685 llvm::outs() << C
.getDefaultToolChain().getTripleString() << '\n';
689 if (C
.getArgs().hasArg(options::OPT_dumpversion
)) {
690 // Since -dumpversion is only implemented for pedantic GCC compatibility, we
691 // return an answer which matches our definition of __VERSION__.
693 // If we want to return a more correct answer some day, then we should
694 // introduce a non-pedantically GCC compatible mode to Clang in which we
695 // provide sensible definitions for -dumpversion, __VERSION__, etc.
696 llvm::outs() << "4.2.1\n";
700 if (C
.getArgs().hasArg(options::OPT__print_diagnostic_categories
)) {
701 PrintDiagnosticCategories(llvm::outs());
705 if (C
.getArgs().hasArg(options::OPT_help
) ||
706 C
.getArgs().hasArg(options::OPT__help_hidden
)) {
707 PrintHelp(C
.getArgs().hasArg(options::OPT__help_hidden
));
711 if (C
.getArgs().hasArg(options::OPT__version
)) {
712 // Follow gcc behavior and use stdout for --version and stderr for -v.
713 PrintVersion(C
, llvm::outs());
717 if (C
.getArgs().hasArg(options::OPT_v
) ||
718 C
.getArgs().hasArg(options::OPT__HASH_HASH_HASH
)) {
719 PrintVersion(C
, llvm::errs());
720 SuppressMissingInputWarning
= true;
723 const ToolChain
&TC
= C
.getDefaultToolChain();
724 if (C
.getArgs().hasArg(options::OPT_print_search_dirs
)) {
725 llvm::outs() << "programs: =";
726 for (ToolChain::path_list::const_iterator it
= TC
.getProgramPaths().begin(),
727 ie
= TC
.getProgramPaths().end(); it
!= ie
; ++it
) {
728 if (it
!= TC
.getProgramPaths().begin())
732 llvm::outs() << "\n";
733 llvm::outs() << "libraries: =" << ResourceDir
;
735 StringRef sysroot
= C
.getSysRoot();
737 for (ToolChain::path_list::const_iterator it
= TC
.getFilePaths().begin(),
738 ie
= TC
.getFilePaths().end(); it
!= ie
; ++it
) {
740 const char *path
= it
->c_str();
742 llvm::outs() << sysroot
<< path
+ 1;
744 llvm::outs() << path
;
746 llvm::outs() << "\n";
750 // FIXME: The following handlers should use a callback mechanism, we don't
751 // know what the client would like to do.
752 if (Arg
*A
= C
.getArgs().getLastArg(options::OPT_print_file_name_EQ
)) {
753 llvm::outs() << GetFilePath(A
->getValue(C
.getArgs()), TC
) << "\n";
757 if (Arg
*A
= C
.getArgs().getLastArg(options::OPT_print_prog_name_EQ
)) {
758 llvm::outs() << GetProgramPath(A
->getValue(C
.getArgs()), TC
) << "\n";
762 if (C
.getArgs().hasArg(options::OPT_print_libgcc_file_name
)) {
763 llvm::outs() << GetFilePath("libgcc.a", TC
) << "\n";
767 if (C
.getArgs().hasArg(options::OPT_print_multi_lib
)) {
768 // FIXME: We need tool chain support for this.
769 llvm::outs() << ".;\n";
771 switch (C
.getDefaultToolChain().getTriple().getArch()) {
775 case llvm::Triple::x86_64
:
776 llvm::outs() << "x86_64;@m64" << "\n";
779 case llvm::Triple::ppc64
:
780 llvm::outs() << "ppc64;@m64" << "\n";
786 // FIXME: What is the difference between print-multi-directory and
787 // print-multi-os-directory?
788 if (C
.getArgs().hasArg(options::OPT_print_multi_directory
) ||
789 C
.getArgs().hasArg(options::OPT_print_multi_os_directory
)) {
790 switch (C
.getDefaultToolChain().getTriple().getArch()) {
792 case llvm::Triple::x86
:
793 case llvm::Triple::ppc
:
794 llvm::outs() << "." << "\n";
797 case llvm::Triple::x86_64
:
798 llvm::outs() << "x86_64" << "\n";
801 case llvm::Triple::ppc64
:
802 llvm::outs() << "ppc64" << "\n";
811 static unsigned PrintActions1(const Compilation
&C
, Action
*A
,
812 std::map
<Action
*, unsigned> &Ids
) {
817 llvm::raw_string_ostream
os(str
);
819 os
<< Action::getClassName(A
->getKind()) << ", ";
820 if (InputAction
*IA
= dyn_cast
<InputAction
>(A
)) {
821 os
<< "\"" << IA
->getInputArg().getValue(C
.getArgs()) << "\"";
822 } else if (BindArchAction
*BIA
= dyn_cast
<BindArchAction
>(A
)) {
823 os
<< '"' << BIA
->getArchName() << '"'
824 << ", {" << PrintActions1(C
, *BIA
->begin(), Ids
) << "}";
827 for (Action::iterator it
= A
->begin(), ie
= A
->end(); it
!= ie
;) {
828 os
<< PrintActions1(C
, *it
, Ids
);
836 unsigned Id
= Ids
.size();
838 llvm::errs() << Id
<< ": " << os
.str() << ", "
839 << types::getTypeName(A
->getType()) << "\n";
844 void Driver::PrintActions(const Compilation
&C
) const {
845 std::map
<Action
*, unsigned> Ids
;
846 for (ActionList::const_iterator it
= C
.getActions().begin(),
847 ie
= C
.getActions().end(); it
!= ie
; ++it
)
848 PrintActions1(C
, *it
, Ids
);
851 /// \brief Check whether the given input tree contains any compilation or
852 /// assembly actions.
853 static bool ContainsCompileOrAssembleAction(const Action
*A
) {
854 if (isa
<CompileJobAction
>(A
) || isa
<AssembleJobAction
>(A
))
857 for (Action::const_iterator it
= A
->begin(), ie
= A
->end(); it
!= ie
; ++it
)
858 if (ContainsCompileOrAssembleAction(*it
))
864 void Driver::BuildUniversalActions(const ToolChain
&TC
,
865 const DerivedArgList
&Args
,
866 const InputList
&BAInputs
,
867 ActionList
&Actions
) const {
868 llvm::PrettyStackTraceString
CrashInfo("Building universal build actions");
869 // Collect the list of architectures. Duplicates are allowed, but should only
870 // be handled once (in the order seen).
871 llvm::StringSet
<> ArchNames
;
872 SmallVector
<const char *, 4> Archs
;
873 for (ArgList::const_iterator it
= Args
.begin(), ie
= Args
.end();
877 if (A
->getOption().matches(options::OPT_arch
)) {
878 // Validate the option here; we don't save the type here because its
879 // particular spelling may participate in other driver choices.
880 llvm::Triple::ArchType Arch
=
881 llvm::Triple::getArchTypeForDarwinArchName(A
->getValue(Args
));
882 if (Arch
== llvm::Triple::UnknownArch
) {
883 Diag(clang::diag::err_drv_invalid_arch_name
)
884 << A
->getAsString(Args
);
889 if (ArchNames
.insert(A
->getValue(Args
)))
890 Archs
.push_back(A
->getValue(Args
));
894 // When there is no explicit arch for this platform, make sure we still bind
895 // the architecture (to the default) so that -Xarch_ is handled correctly.
897 Archs
.push_back(Args
.MakeArgString(TC
.getArchName()));
899 // FIXME: We killed off some others but these aren't yet detected in a
900 // functional manner. If we added information to jobs about which "auxiliary"
901 // files they wrote then we could detect the conflict these cause downstream.
902 if (Archs
.size() > 1) {
903 // No recovery needed, the point of this is just to prevent
904 // overwriting the same files.
905 if (const Arg
*A
= Args
.getLastArg(options::OPT_save_temps
))
906 Diag(clang::diag::err_drv_invalid_opt_with_multiple_archs
)
907 << A
->getAsString(Args
);
910 ActionList SingleActions
;
911 BuildActions(TC
, Args
, BAInputs
, SingleActions
);
913 // Add in arch bindings for every top level action, as well as lipo and
914 // dsymutil steps if needed.
915 for (unsigned i
= 0, e
= SingleActions
.size(); i
!= e
; ++i
) {
916 Action
*Act
= SingleActions
[i
];
918 // Make sure we can lipo this kind of output. If not (and it is an actual
919 // output) then we disallow, since we can't create an output file with the
920 // right name without overwriting it. We could remove this oddity by just
921 // changing the output names to include the arch, which would also fix
922 // -save-temps. Compatibility wins for now.
924 if (Archs
.size() > 1 && !types::canLipoType(Act
->getType()))
925 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs
)
926 << types::getTypeName(Act
->getType());
929 for (unsigned i
= 0, e
= Archs
.size(); i
!= e
; ++i
) {
930 Inputs
.push_back(new BindArchAction(Act
, Archs
[i
]));
932 Inputs
.back()->setOwnsInputs(false);
935 // Lipo if necessary, we do it this way because we need to set the arch flag
936 // so that -Xarch_ gets overwritten.
937 if (Inputs
.size() == 1 || Act
->getType() == types::TY_Nothing
)
938 Actions
.append(Inputs
.begin(), Inputs
.end());
940 Actions
.push_back(new LipoJobAction(Inputs
, Act
->getType()));
942 // Handle debug info queries.
943 Arg
*A
= Args
.getLastArg(options::OPT_g_Group
);
944 if (A
&& !A
->getOption().matches(options::OPT_g0
) &&
945 !A
->getOption().matches(options::OPT_gstabs
) &&
946 ContainsCompileOrAssembleAction(Actions
.back())) {
948 // Add a 'dsymutil' step if necessary, when debug info is enabled and we
949 // have a compile input. We need to run 'dsymutil' ourselves in such cases
950 // because the debug info will refer to a temporary object file which is
951 // will be removed at the end of the compilation process.
952 if (Act
->getType() == types::TY_Image
) {
954 Inputs
.push_back(Actions
.back());
956 Actions
.push_back(new DsymutilJobAction(Inputs
, types::TY_dSYM
));
959 // Verify the output (debug information only) if we passed '-verify'.
960 if (Args
.hasArg(options::OPT_verify
)) {
961 ActionList VerifyInputs
;
962 VerifyInputs
.push_back(Actions
.back());
964 Actions
.push_back(new VerifyJobAction(VerifyInputs
,
971 // Construct a the list of inputs and their types.
972 void Driver::BuildInputs(const ToolChain
&TC
, const DerivedArgList
&Args
,
973 InputList
&Inputs
) const {
974 // Track the current user specified (-x) input. We also explicitly track the
975 // argument used to set the type; we only want to claim the type when we
976 // actually use it, so we warn about unused -x arguments.
977 types::ID InputType
= types::TY_Nothing
;
978 Arg
*InputTypeArg
= 0;
980 for (ArgList::const_iterator it
= Args
.begin(), ie
= Args
.end();
984 if (A
->getOption().getKind() == Option::InputClass
) {
985 const char *Value
= A
->getValue(Args
);
986 types::ID Ty
= types::TY_INVALID
;
988 // Infer the input type if necessary.
989 if (InputType
== types::TY_Nothing
) {
990 // If there was an explicit arg for this, claim it.
992 InputTypeArg
->claim();
994 // stdin must be handled specially.
995 if (memcmp(Value
, "-", 2) == 0) {
996 // If running with -E, treat as a C input (this changes the builtin
997 // macros, for example). This may be overridden by -ObjC below.
999 // Otherwise emit an error but still use a valid type to avoid
1000 // spurious errors (e.g., no inputs).
1001 if (!Args
.hasArgNoClaim(options::OPT_E
) && !CCCIsCPP
)
1002 Diag(clang::diag::err_drv_unknown_stdin_type
);
1005 // Otherwise lookup by extension.
1006 // Fallback is C if invoked as C preprocessor or Object otherwise.
1007 // We use a host hook here because Darwin at least has its own
1008 // idea of what .s is.
1009 if (const char *Ext
= strrchr(Value
, '.'))
1010 Ty
= TC
.LookupTypeForExtension(Ext
+ 1);
1012 if (Ty
== types::TY_INVALID
) {
1016 Ty
= types::TY_Object
;
1019 // If the driver is invoked as C++ compiler (like clang++ or c++) it
1020 // should autodetect some input files as C++ for g++ compatibility.
1022 types::ID OldTy
= Ty
;
1023 Ty
= types::lookupCXXTypeForCType(Ty
);
1026 Diag(clang::diag::warn_drv_treating_input_as_cxx
)
1027 << getTypeName(OldTy
) << getTypeName(Ty
);
1031 // -ObjC and -ObjC++ override the default language, but only for "source
1032 // files". We just treat everything that isn't a linker input as a
1035 // FIXME: Clean this up if we move the phase sequence into the type.
1036 if (Ty
!= types::TY_Object
) {
1037 if (Args
.hasArg(options::OPT_ObjC
))
1038 Ty
= types::TY_ObjC
;
1039 else if (Args
.hasArg(options::OPT_ObjCXX
))
1040 Ty
= types::TY_ObjCXX
;
1043 assert(InputTypeArg
&& "InputType set w/o InputTypeArg");
1044 InputTypeArg
->claim();
1048 // Check that the file exists, if enabled.
1049 if (CheckInputsExist
&& memcmp(Value
, "-", 2) != 0) {
1050 SmallString
<64> Path(Value
);
1051 if (Arg
*WorkDir
= Args
.getLastArg(options::OPT_working_directory
)) {
1052 SmallString
<64> Directory(WorkDir
->getValue(Args
));
1053 if (llvm::sys::path::is_absolute(Directory
.str())) {
1054 llvm::sys::path::append(Directory
, Value
);
1055 Path
.assign(Directory
);
1059 bool exists
= false;
1060 if (llvm::sys::fs::exists(Path
.c_str(), exists
) || !exists
)
1061 Diag(clang::diag::err_drv_no_such_file
) << Path
.str();
1063 Inputs
.push_back(std::make_pair(Ty
, A
));
1065 Inputs
.push_back(std::make_pair(Ty
, A
));
1067 } else if (A
->getOption().isLinkerInput()) {
1068 // Just treat as object type, we could make a special type for this if
1070 Inputs
.push_back(std::make_pair(types::TY_Object
, A
));
1072 } else if (A
->getOption().matches(options::OPT_x
)) {
1074 InputType
= types::lookupTypeForTypeSpecifier(A
->getValue(Args
));
1077 // Follow gcc behavior and treat as linker input for invalid -x
1078 // options. Its not clear why we shouldn't just revert to unknown; but
1079 // this isn't very important, we might as well be bug compatible.
1081 Diag(clang::diag::err_drv_unknown_language
) << A
->getValue(Args
);
1082 InputType
= types::TY_Object
;
1086 if (CCCIsCPP
&& Inputs
.empty()) {
1087 // If called as standalone preprocessor, stdin is processed
1088 // if no other input is present.
1089 unsigned Index
= Args
.getBaseArgs().MakeIndex("-");
1090 Arg
*A
= Opts
->ParseOneArg(Args
, Index
);
1092 Inputs
.push_back(std::make_pair(types::TY_C
, A
));
1096 void Driver::BuildActions(const ToolChain
&TC
, const DerivedArgList
&Args
,
1097 const InputList
&Inputs
, ActionList
&Actions
) const {
1098 llvm::PrettyStackTraceString
CrashInfo("Building compilation actions");
1100 if (!SuppressMissingInputWarning
&& Inputs
.empty()) {
1101 Diag(clang::diag::err_drv_no_input_files
);
1106 phases::ID FinalPhase
= getFinalPhase(Args
, &FinalPhaseArg
);
1108 // Reject -Z* at the top level, these options should never have been exposed
1110 if (Arg
*A
= Args
.getLastArg(options::OPT_Z_Joined
))
1111 Diag(clang::diag::err_drv_use_of_Z_option
) << A
->getAsString(Args
);
1113 // Construct the actions to perform.
1114 ActionList LinkerInputs
;
1115 unsigned NumSteps
= 0;
1116 for (unsigned i
= 0, e
= Inputs
.size(); i
!= e
; ++i
) {
1117 types::ID InputType
= Inputs
[i
].first
;
1118 const Arg
*InputArg
= Inputs
[i
].second
;
1120 NumSteps
= types::getNumCompilationPhases(InputType
);
1121 assert(NumSteps
&& "Invalid number of steps!");
1123 // If the first step comes after the final phase we are doing as part of
1124 // this compilation, warn the user about it.
1125 phases::ID InitialPhase
= types::getCompilationPhase(InputType
, 0);
1126 if (InitialPhase
> FinalPhase
) {
1127 // Claim here to avoid the more general unused warning.
1130 // Suppress all unused style warnings with -Qunused-arguments
1131 if (Args
.hasArg(options::OPT_Qunused_arguments
))
1134 // Special case when final phase determined by binary name, rather than
1135 // by a command-line argument with a corresponding Arg.
1137 Diag(clang::diag::warn_drv_input_file_unused_by_cpp
)
1138 << InputArg
->getAsString(Args
)
1139 << getPhaseName(InitialPhase
);
1140 // Special case '-E' warning on a previously preprocessed file to make
1142 else if (InitialPhase
== phases::Compile
&&
1143 FinalPhase
== phases::Preprocess
&&
1144 getPreprocessedType(InputType
) == types::TY_INVALID
)
1145 Diag(clang::diag::warn_drv_preprocessed_input_file_unused
)
1146 << InputArg
->getAsString(Args
)
1148 << FinalPhaseArg
? FinalPhaseArg
->getOption().getName() : "";
1150 Diag(clang::diag::warn_drv_input_file_unused
)
1151 << InputArg
->getAsString(Args
)
1152 << getPhaseName(InitialPhase
)
1154 << FinalPhaseArg
? FinalPhaseArg
->getOption().getName() : "";
1158 // Build the pipeline for this file.
1159 OwningPtr
<Action
> Current(new InputAction(*InputArg
, InputType
));
1160 for (unsigned i
= 0; i
!= NumSteps
; ++i
) {
1161 phases::ID Phase
= types::getCompilationPhase(InputType
, i
);
1163 // We are done if this step is past what the user requested.
1164 if (Phase
> FinalPhase
)
1167 // Queue linker inputs.
1168 if (Phase
== phases::Link
) {
1169 assert(i
+ 1 == NumSteps
&& "linking must be final compilation step.");
1170 LinkerInputs
.push_back(Current
.take());
1174 // Some types skip the assembler phase (e.g., llvm-bc), but we can't
1175 // encode this in the steps because the intermediate type depends on
1176 // arguments. Just special case here.
1177 if (Phase
== phases::Assemble
&& Current
->getType() != types::TY_PP_Asm
)
1180 // Otherwise construct the appropriate action.
1181 Current
.reset(ConstructPhaseAction(Args
, Phase
, Current
.take()));
1182 if (Current
->getType() == types::TY_Nothing
)
1186 // If we ended with something, add to the output list.
1188 Actions
.push_back(Current
.take());
1191 // Add a link action if necessary.
1192 if (!LinkerInputs
.empty())
1193 Actions
.push_back(new LinkJobAction(LinkerInputs
, types::TY_Image
));
1195 // If we are linking, claim any options which are obviously only used for
1197 if (FinalPhase
== phases::Link
&& (NumSteps
== 1))
1198 Args
.ClaimAllArgs(options::OPT_CompileOnly_Group
);
1201 Action
*Driver::ConstructPhaseAction(const ArgList
&Args
, phases::ID Phase
,
1202 Action
*Input
) const {
1203 llvm::PrettyStackTraceString
CrashInfo("Constructing phase actions");
1204 // Build the appropriate action.
1206 case phases::Link
: llvm_unreachable("link action invalid here.");
1207 case phases::Preprocess
: {
1209 // -{M, MM} alter the output type.
1210 if (Args
.hasArg(options::OPT_M
, options::OPT_MM
)) {
1211 OutputTy
= types::TY_Dependencies
;
1213 OutputTy
= Input
->getType();
1214 if (!Args
.hasFlag(options::OPT_frewrite_includes
,
1215 options::OPT_fno_rewrite_includes
, false))
1216 OutputTy
= types::getPreprocessedType(OutputTy
);
1217 assert(OutputTy
!= types::TY_INVALID
&&
1218 "Cannot preprocess this input type!");
1220 return new PreprocessJobAction(Input
, OutputTy
);
1222 case phases::Precompile
: {
1223 types::ID OutputTy
= types::TY_PCH
;
1224 if (Args
.hasArg(options::OPT_fsyntax_only
)) {
1225 // Syntax checks should not emit a PCH file
1226 OutputTy
= types::TY_Nothing
;
1228 return new PrecompileJobAction(Input
, OutputTy
);
1230 case phases::Compile
: {
1231 if (Args
.hasArg(options::OPT_fsyntax_only
)) {
1232 return new CompileJobAction(Input
, types::TY_Nothing
);
1233 } else if (Args
.hasArg(options::OPT_rewrite_objc
)) {
1234 return new CompileJobAction(Input
, types::TY_RewrittenObjC
);
1235 } else if (Args
.hasArg(options::OPT_rewrite_legacy_objc
)) {
1236 return new CompileJobAction(Input
, types::TY_RewrittenLegacyObjC
);
1237 } else if (Args
.hasArg(options::OPT__analyze
, options::OPT__analyze_auto
)) {
1238 return new AnalyzeJobAction(Input
, types::TY_Plist
);
1239 } else if (Args
.hasArg(options::OPT__migrate
)) {
1240 return new MigrateJobAction(Input
, types::TY_Remap
);
1241 } else if (Args
.hasArg(options::OPT_emit_ast
)) {
1242 return new CompileJobAction(Input
, types::TY_AST
);
1243 } else if (IsUsingLTO(Args
)) {
1245 Args
.hasArg(options::OPT_S
) ? types::TY_LTO_IR
: types::TY_LTO_BC
;
1246 return new CompileJobAction(Input
, Output
);
1248 return new CompileJobAction(Input
, types::TY_PP_Asm
);
1251 case phases::Assemble
:
1252 return new AssembleJobAction(Input
, types::TY_Object
);
1255 llvm_unreachable("invalid phase in ConstructPhaseAction");
1258 bool Driver::IsUsingLTO(const ArgList
&Args
) const {
1259 // Check for -emit-llvm or -flto.
1260 if (Args
.hasArg(options::OPT_emit_llvm
) ||
1261 Args
.hasFlag(options::OPT_flto
, options::OPT_fno_lto
, false))
1265 if (const Arg
*A
= Args
.getLastArg(options::OPT_O_Group
))
1266 return A
->getOption().matches(options::OPT_O4
);
1271 void Driver::BuildJobs(Compilation
&C
) const {
1272 llvm::PrettyStackTraceString
CrashInfo("Building compilation jobs");
1274 Arg
*FinalOutput
= C
.getArgs().getLastArg(options::OPT_o
);
1276 // It is an error to provide a -o option if we are making multiple output
1279 unsigned NumOutputs
= 0;
1280 for (ActionList::const_iterator it
= C
.getActions().begin(),
1281 ie
= C
.getActions().end(); it
!= ie
; ++it
)
1282 if ((*it
)->getType() != types::TY_Nothing
)
1285 if (NumOutputs
> 1) {
1286 Diag(clang::diag::err_drv_output_argument_with_multiple_files
);
1291 for (ActionList::const_iterator it
= C
.getActions().begin(),
1292 ie
= C
.getActions().end(); it
!= ie
; ++it
) {
1295 // If we are linking an image for multiple archs then the linker wants
1296 // -arch_multiple and -final_output <final image name>. Unfortunately, this
1297 // doesn't fit in cleanly because we have to pass this information down.
1299 // FIXME: This is a hack; find a cleaner way to integrate this into the
1301 const char *LinkingOutput
= 0;
1302 if (isa
<LipoJobAction
>(A
)) {
1304 LinkingOutput
= FinalOutput
->getValue(C
.getArgs());
1306 LinkingOutput
= DefaultImageName
.c_str();
1310 BuildJobsForAction(C
, A
, &C
.getDefaultToolChain(),
1312 /*AtTopLevel*/ true,
1313 /*LinkingOutput*/ LinkingOutput
,
1317 // If the user passed -Qunused-arguments or there were errors, don't warn
1318 // about any unused arguments.
1319 if (Diags
.hasErrorOccurred() ||
1320 C
.getArgs().hasArg(options::OPT_Qunused_arguments
))
1324 (void) C
.getArgs().hasArg(options::OPT__HASH_HASH_HASH
);
1326 for (ArgList::const_iterator it
= C
.getArgs().begin(), ie
= C
.getArgs().end();
1330 // FIXME: It would be nice to be able to send the argument to the
1331 // DiagnosticsEngine, so that extra values, position, and so on could be
1333 if (!A
->isClaimed()) {
1334 if (A
->getOption().hasNoArgumentUnused())
1337 // Suppress the warning automatically if this is just a flag, and it is an
1338 // instance of an argument we already claimed.
1339 const Option
&Opt
= A
->getOption();
1340 if (Opt
.getKind() == Option::FlagClass
) {
1341 bool DuplicateClaimed
= false;
1343 for (arg_iterator it
= C
.getArgs().filtered_begin(&Opt
),
1344 ie
= C
.getArgs().filtered_end(); it
!= ie
; ++it
) {
1345 if ((*it
)->isClaimed()) {
1346 DuplicateClaimed
= true;
1351 if (DuplicateClaimed
)
1355 Diag(clang::diag::warn_drv_unused_argument
)
1356 << A
->getAsString(C
.getArgs());
1361 static const Tool
&SelectToolForJob(Compilation
&C
, const ToolChain
*TC
,
1362 const JobAction
*JA
,
1363 const ActionList
*&Inputs
) {
1364 const Tool
*ToolForJob
= 0;
1366 // See if we should look for a compiler with an integrated assembler. We match
1367 // bottom up, so what we are actually looking for is an assembler job with a
1370 if (C
.getArgs().hasFlag(options::OPT_integrated_as
,
1371 options::OPT_no_integrated_as
,
1372 TC
->IsIntegratedAssemblerDefault()) &&
1373 !C
.getArgs().hasArg(options::OPT_save_temps
) &&
1374 isa
<AssembleJobAction
>(JA
) &&
1375 Inputs
->size() == 1 && isa
<CompileJobAction
>(*Inputs
->begin())) {
1376 const Tool
&Compiler
= TC
->SelectTool(
1377 C
, cast
<JobAction
>(**Inputs
->begin()), (*Inputs
)[0]->getInputs());
1378 if (Compiler
.hasIntegratedAssembler()) {
1379 Inputs
= &(*Inputs
)[0]->getInputs();
1380 ToolForJob
= &Compiler
;
1384 // Otherwise use the tool for the current job.
1386 ToolForJob
= &TC
->SelectTool(C
, *JA
, *Inputs
);
1388 // See if we should use an integrated preprocessor. We do so when we have
1389 // exactly one input, since this is the only use case we care about
1390 // (irrelevant since we don't support combine yet).
1391 if (Inputs
->size() == 1 && isa
<PreprocessJobAction
>(*Inputs
->begin()) &&
1392 !C
.getArgs().hasArg(options::OPT_no_integrated_cpp
) &&
1393 !C
.getArgs().hasArg(options::OPT_traditional_cpp
) &&
1394 !C
.getArgs().hasArg(options::OPT_save_temps
) &&
1395 !C
.getArgs().hasArg(options::OPT_rewrite_objc
) &&
1396 ToolForJob
->hasIntegratedCPP())
1397 Inputs
= &(*Inputs
)[0]->getInputs();
1402 void Driver::BuildJobsForAction(Compilation
&C
,
1404 const ToolChain
*TC
,
1405 const char *BoundArch
,
1407 const char *LinkingOutput
,
1408 InputInfo
&Result
) const {
1409 llvm::PrettyStackTraceString
CrashInfo("Building compilation jobs");
1411 if (const InputAction
*IA
= dyn_cast
<InputAction
>(A
)) {
1412 // FIXME: It would be nice to not claim this here; maybe the old scheme of
1413 // just using Args was better?
1414 const Arg
&Input
= IA
->getInputArg();
1416 if (Input
.getOption().matches(options::OPT_INPUT
)) {
1417 const char *Name
= Input
.getValue(C
.getArgs());
1418 Result
= InputInfo(Name
, A
->getType(), Name
);
1420 Result
= InputInfo(&Input
, A
->getType(), "");
1424 if (const BindArchAction
*BAA
= dyn_cast
<BindArchAction
>(A
)) {
1425 const ToolChain
*TC
;
1426 const char *ArchName
= BAA
->getArchName();
1429 TC
= &getToolChain(C
.getArgs(), ArchName
);
1431 TC
= &C
.getDefaultToolChain();
1433 BuildJobsForAction(C
, *BAA
->begin(), TC
, BAA
->getArchName(),
1434 AtTopLevel
, LinkingOutput
, Result
);
1438 const ActionList
*Inputs
= &A
->getInputs();
1440 const JobAction
*JA
= cast
<JobAction
>(A
);
1441 const Tool
&T
= SelectToolForJob(C
, TC
, JA
, Inputs
);
1443 // Only use pipes when there is exactly one input.
1444 InputInfoList InputInfos
;
1445 for (ActionList::const_iterator it
= Inputs
->begin(), ie
= Inputs
->end();
1447 // Treat dsymutil sub-jobs as being at the top-level too, they shouldn't get
1448 // temporary output names.
1450 // FIXME: Clean this up.
1451 bool SubJobAtTopLevel
= false;
1452 if (AtTopLevel
&& isa
<DsymutilJobAction
>(A
))
1453 SubJobAtTopLevel
= true;
1455 // Also treat verify sub-jobs as being at the top-level. They don't
1456 // produce any output and so don't need temporary output names.
1457 if (AtTopLevel
&& isa
<VerifyJobAction
>(A
))
1458 SubJobAtTopLevel
= true;
1461 BuildJobsForAction(C
, *it
, TC
, BoundArch
,
1462 SubJobAtTopLevel
, LinkingOutput
, II
);
1463 InputInfos
.push_back(II
);
1466 // Always use the first input as the base input.
1467 const char *BaseInput
= InputInfos
[0].getBaseInput();
1469 // ... except dsymutil actions, which use their actual input as the base
1471 if (JA
->getType() == types::TY_dSYM
)
1472 BaseInput
= InputInfos
[0].getFilename();
1474 // Determine the place to write output to, if any.
1475 if (JA
->getType() == types::TY_Nothing
) {
1476 Result
= InputInfo(A
->getType(), BaseInput
);
1478 Result
= InputInfo(GetNamedOutputPath(C
, *JA
, BaseInput
, AtTopLevel
),
1479 A
->getType(), BaseInput
);
1482 if (CCCPrintBindings
&& !CCGenDiagnostics
) {
1483 llvm::errs() << "# \"" << T
.getToolChain().getTripleString() << '"'
1484 << " - \"" << T
.getName() << "\", inputs: [";
1485 for (unsigned i
= 0, e
= InputInfos
.size(); i
!= e
; ++i
) {
1486 llvm::errs() << InputInfos
[i
].getAsString();
1488 llvm::errs() << ", ";
1490 llvm::errs() << "], output: " << Result
.getAsString() << "\n";
1492 T
.ConstructJob(C
, *JA
, Result
, InputInfos
,
1493 C
.getArgsForToolChain(TC
, BoundArch
), LinkingOutput
);
1497 const char *Driver::GetNamedOutputPath(Compilation
&C
,
1498 const JobAction
&JA
,
1499 const char *BaseInput
,
1500 bool AtTopLevel
) const {
1501 llvm::PrettyStackTraceString
CrashInfo("Computing output path");
1502 // Output to a user requested destination?
1503 if (AtTopLevel
&& !isa
<DsymutilJobAction
>(JA
) &&
1504 !isa
<VerifyJobAction
>(JA
)) {
1505 if (Arg
*FinalOutput
= C
.getArgs().getLastArg(options::OPT_o
))
1506 return C
.addResultFile(FinalOutput
->getValue(C
.getArgs()));
1509 // Default to writing to stdout?
1510 if (AtTopLevel
&& isa
<PreprocessJobAction
>(JA
) && !CCGenDiagnostics
)
1513 // Output to a temporary file?
1514 if ((!AtTopLevel
&& !C
.getArgs().hasArg(options::OPT_save_temps
)) ||
1516 StringRef Name
= llvm::sys::path::filename(BaseInput
);
1517 std::pair
<StringRef
, StringRef
> Split
= Name
.split('.');
1518 std::string TmpName
=
1519 GetTemporaryPath(Split
.first
, types::getTypeTempSuffix(JA
.getType()));
1520 return C
.addTempFile(C
.getArgs().MakeArgString(TmpName
.c_str()));
1523 SmallString
<128> BasePath(BaseInput
);
1526 // Dsymutil actions should use the full path.
1527 if (isa
<DsymutilJobAction
>(JA
) || isa
<VerifyJobAction
>(JA
))
1528 BaseName
= BasePath
;
1530 BaseName
= llvm::sys::path::filename(BasePath
);
1532 // Determine what the derived output name should be.
1533 const char *NamedOutput
;
1534 if (JA
.getType() == types::TY_Image
) {
1535 NamedOutput
= DefaultImageName
.c_str();
1537 const char *Suffix
= types::getTypeTempSuffix(JA
.getType());
1538 assert(Suffix
&& "All types used for output should have a suffix.");
1540 std::string::size_type End
= std::string::npos
;
1541 if (!types::appendSuffixForType(JA
.getType()))
1542 End
= BaseName
.rfind('.');
1543 std::string
Suffixed(BaseName
.substr(0, End
));
1546 NamedOutput
= C
.getArgs().MakeArgString(Suffixed
.c_str());
1549 // If we're saving temps and the temp file conflicts with the input file,
1550 // then avoid overwriting input file.
1551 if (!AtTopLevel
&& C
.getArgs().hasArg(options::OPT_save_temps
) &&
1552 NamedOutput
== BaseName
) {
1554 bool SameFile
= false;
1555 SmallString
<256> Result
;
1556 llvm::sys::fs::current_path(Result
);
1557 llvm::sys::path::append(Result
, BaseName
);
1558 llvm::sys::fs::equivalent(BaseInput
, Result
.c_str(), SameFile
);
1559 // Must share the same path to conflict.
1561 StringRef Name
= llvm::sys::path::filename(BaseInput
);
1562 std::pair
<StringRef
, StringRef
> Split
= Name
.split('.');
1563 std::string TmpName
=
1564 GetTemporaryPath(Split
.first
, types::getTypeTempSuffix(JA
.getType()));
1565 return C
.addTempFile(C
.getArgs().MakeArgString(TmpName
.c_str()));
1569 // As an annoying special case, PCH generation doesn't strip the pathname.
1570 if (JA
.getType() == types::TY_PCH
) {
1571 llvm::sys::path::remove_filename(BasePath
);
1572 if (BasePath
.empty())
1573 BasePath
= NamedOutput
;
1575 llvm::sys::path::append(BasePath
, NamedOutput
);
1576 return C
.addResultFile(C
.getArgs().MakeArgString(BasePath
.c_str()));
1578 return C
.addResultFile(NamedOutput
);
1582 std::string
Driver::GetFilePath(const char *Name
, const ToolChain
&TC
) const {
1583 // Respect a limited subset of the '-Bprefix' functionality in GCC by
1584 // attempting to use this prefix when lokup up program paths.
1585 for (Driver::prefix_list::const_iterator it
= PrefixDirs
.begin(),
1586 ie
= PrefixDirs
.end(); it
!= ie
; ++it
) {
1587 std::string
Dir(*it
);
1591 Dir
= SysRoot
+ Dir
.substr(1);
1592 llvm::sys::Path
P(Dir
);
1593 P
.appendComponent(Name
);
1595 if (!llvm::sys::fs::exists(P
.str(), Exists
) && Exists
)
1599 llvm::sys::Path
P(ResourceDir
);
1600 P
.appendComponent(Name
);
1602 if (!llvm::sys::fs::exists(P
.str(), Exists
) && Exists
)
1605 const ToolChain::path_list
&List
= TC
.getFilePaths();
1606 for (ToolChain::path_list::const_iterator
1607 it
= List
.begin(), ie
= List
.end(); it
!= ie
; ++it
) {
1608 std::string
Dir(*it
);
1612 Dir
= SysRoot
+ Dir
.substr(1);
1613 llvm::sys::Path
P(Dir
);
1614 P
.appendComponent(Name
);
1616 if (!llvm::sys::fs::exists(P
.str(), Exists
) && Exists
)
1623 static bool isPathExecutable(llvm::sys::Path
&P
, bool WantFile
) {
1625 return (WantFile
? !llvm::sys::fs::exists(P
.str(), Exists
) && Exists
1629 std::string
Driver::GetProgramPath(const char *Name
, const ToolChain
&TC
,
1630 bool WantFile
) const {
1631 // FIXME: Needs a better variable than DefaultTargetTriple
1632 std::string
TargetSpecificExecutable(DefaultTargetTriple
+ "-" + Name
);
1633 // Respect a limited subset of the '-Bprefix' functionality in GCC by
1634 // attempting to use this prefix when lokup up program paths.
1635 for (Driver::prefix_list::const_iterator it
= PrefixDirs
.begin(),
1636 ie
= PrefixDirs
.end(); it
!= ie
; ++it
) {
1637 llvm::sys::Path
P(*it
);
1638 P
.appendComponent(TargetSpecificExecutable
);
1639 if (isPathExecutable(P
, WantFile
)) return P
.str();
1641 P
.appendComponent(Name
);
1642 if (isPathExecutable(P
, WantFile
)) return P
.str();
1645 const ToolChain::path_list
&List
= TC
.getProgramPaths();
1646 for (ToolChain::path_list::const_iterator
1647 it
= List
.begin(), ie
= List
.end(); it
!= ie
; ++it
) {
1648 llvm::sys::Path
P(*it
);
1649 P
.appendComponent(TargetSpecificExecutable
);
1650 if (isPathExecutable(P
, WantFile
)) return P
.str();
1652 P
.appendComponent(Name
);
1653 if (isPathExecutable(P
, WantFile
)) return P
.str();
1656 // If all else failed, search the path.
1658 P(llvm::sys::Program::FindProgramByName(TargetSpecificExecutable
));
1662 P
= llvm::sys::Path(llvm::sys::Program::FindProgramByName(Name
));
1669 std::string
Driver::GetTemporaryPath(StringRef Prefix
, const char *Suffix
)
1671 // FIXME: This is lame; sys::Path should provide this function (in particular,
1672 // it should know how to find the temporary files dir).
1674 const char *TmpDir
= ::getenv("TMPDIR");
1676 TmpDir
= ::getenv("TEMP");
1678 TmpDir
= ::getenv("TMP");
1681 llvm::sys::Path
P(TmpDir
);
1682 P
.appendComponent(Prefix
);
1683 if (P
.makeUnique(false, &Error
)) {
1684 Diag(clang::diag::err_unable_to_make_temp
) << Error
;
1688 // FIXME: Grumble, makeUnique sometimes leaves the file around!? PR3837.
1689 P
.eraseFromDisk(false, 0);
1692 P
.appendSuffix(Suffix
);
1696 /// \brief Compute target triple from args.
1698 /// This routine provides the logic to compute a target triple from various
1699 /// args passed to the driver and the default triple string.
1700 static llvm::Triple
computeTargetTriple(StringRef DefaultTargetTriple
,
1701 const ArgList
&Args
,
1702 StringRef DarwinArchName
) {
1703 // FIXME: Already done in Compilation *Driver::BuildCompilation
1704 if (const Arg
*A
= Args
.getLastArg(options::OPT_target
))
1705 DefaultTargetTriple
= A
->getValue(Args
);
1707 llvm::Triple
Target(llvm::Triple::normalize(DefaultTargetTriple
));
1709 // Handle Darwin-specific options available here.
1710 if (Target
.isOSDarwin()) {
1711 // If an explict Darwin arch name is given, that trumps all.
1712 if (!DarwinArchName
.empty()) {
1714 llvm::Triple::getArchTypeForDarwinArchName(DarwinArchName
));
1718 // Handle the Darwin '-arch' flag.
1719 if (Arg
*A
= Args
.getLastArg(options::OPT_arch
)) {
1720 llvm::Triple::ArchType DarwinArch
1721 = llvm::Triple::getArchTypeForDarwinArchName(A
->getValue(Args
));
1722 if (DarwinArch
!= llvm::Triple::UnknownArch
)
1723 Target
.setArch(DarwinArch
);
1727 // Skip further flag support on OSes which don't support '-m32' or '-m64'.
1728 if (Target
.getArchName() == "tce" ||
1729 Target
.getOS() == llvm::Triple::AuroraUX
||
1730 Target
.getOS() == llvm::Triple::Minix
)
1733 // Handle pseudo-target flags '-m32' and '-m64'.
1734 // FIXME: Should this information be in llvm::Triple?
1735 if (Arg
*A
= Args
.getLastArg(options::OPT_m32
, options::OPT_m64
)) {
1736 if (A
->getOption().matches(options::OPT_m32
)) {
1737 if (Target
.getArch() == llvm::Triple::x86_64
)
1738 Target
.setArch(llvm::Triple::x86
);
1739 if (Target
.getArch() == llvm::Triple::ppc64
)
1740 Target
.setArch(llvm::Triple::ppc
);
1742 if (Target
.getArch() == llvm::Triple::x86
)
1743 Target
.setArch(llvm::Triple::x86_64
);
1744 if (Target
.getArch() == llvm::Triple::ppc
)
1745 Target
.setArch(llvm::Triple::ppc64
);
1752 const ToolChain
&Driver::getToolChain(const ArgList
&Args
,
1753 StringRef DarwinArchName
) const {
1754 llvm::Triple Target
= computeTargetTriple(DefaultTargetTriple
, Args
,
1757 ToolChain
*&TC
= ToolChains
[Target
.str()];
1759 switch (Target
.getOS()) {
1760 case llvm::Triple::AuroraUX
:
1761 TC
= new toolchains::AuroraUX(*this, Target
, Args
);
1763 case llvm::Triple::Darwin
:
1764 case llvm::Triple::MacOSX
:
1765 case llvm::Triple::IOS
:
1766 if (Target
.getArch() == llvm::Triple::x86
||
1767 Target
.getArch() == llvm::Triple::x86_64
||
1768 Target
.getArch() == llvm::Triple::arm
||
1769 Target
.getArch() == llvm::Triple::thumb
)
1770 TC
= new toolchains::DarwinClang(*this, Target
);
1772 TC
= new toolchains::Darwin_Generic_GCC(*this, Target
, Args
);
1774 case llvm::Triple::DragonFly
:
1775 TC
= new toolchains::DragonFly(*this, Target
, Args
);
1777 case llvm::Triple::OpenBSD
:
1778 TC
= new toolchains::OpenBSD(*this, Target
, Args
);
1780 case llvm::Triple::Bitrig
:
1781 TC
= new toolchains::Bitrig(*this, Target
, Args
);
1783 case llvm::Triple::NetBSD
:
1784 TC
= new toolchains::NetBSD(*this, Target
, Args
);
1786 case llvm::Triple::FreeBSD
:
1787 TC
= new toolchains::FreeBSD(*this, Target
, Args
);
1789 case llvm::Triple::Minix
:
1790 TC
= new toolchains::Minix(*this, Target
, Args
);
1792 case llvm::Triple::Linux
:
1793 if (Target
.getArch() == llvm::Triple::hexagon
)
1794 TC
= new toolchains::Hexagon_TC(*this, Target
);
1796 TC
= new toolchains::Linux(*this, Target
, Args
);
1798 case llvm::Triple::Solaris
:
1799 TC
= new toolchains::Solaris(*this, Target
, Args
);
1801 case llvm::Triple::Win32
:
1802 TC
= new toolchains::Windows(*this, Target
);
1804 case llvm::Triple::MinGW32
:
1805 // FIXME: We need a MinGW toolchain. Fallthrough for now.
1807 // TCE is an OSless target
1808 if (Target
.getArchName() == "tce") {
1809 TC
= new toolchains::TCEToolChain(*this, Target
);
1813 TC
= new toolchains::Generic_GCC(*this, Target
, Args
);
1820 bool Driver::ShouldUseClangCompiler(const Compilation
&C
, const JobAction
&JA
,
1821 const llvm::Triple
&Triple
) const {
1822 // Check if user requested no clang, or clang doesn't understand this type (we
1823 // only handle single inputs for now).
1824 if (!CCCUseClang
|| JA
.size() != 1 ||
1825 !types::isAcceptedByClang((*JA
.begin())->getType()))
1828 // Otherwise make sure this is an action clang understands.
1829 if (isa
<PreprocessJobAction
>(JA
)) {
1830 if (!CCCUseClangCPP
) {
1831 Diag(clang::diag::warn_drv_not_using_clang_cpp
);
1834 } else if (!isa
<PrecompileJobAction
>(JA
) && !isa
<CompileJobAction
>(JA
))
1837 // Use clang for C++?
1838 if (!CCCUseClangCXX
&& types::isCXX((*JA
.begin())->getType())) {
1839 Diag(clang::diag::warn_drv_not_using_clang_cxx
);
1843 // Always use clang for precompiling, AST generation, and rewriting,
1844 // regardless of archs.
1845 if (isa
<PrecompileJobAction
>(JA
) ||
1846 types::isOnlyAcceptedByClang(JA
.getType()))
1849 // Finally, don't use clang if this isn't one of the user specified archs to
1851 if (!CCCClangArchs
.empty() && !CCCClangArchs
.count(Triple
.getArch())) {
1852 Diag(clang::diag::warn_drv_not_using_clang_arch
) << Triple
.getArchName();
1859 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
1860 /// grouped values as integers. Numbers which are not provided are set to 0.
1862 /// \return True if the entire string was parsed (9.2), or all groups were
1863 /// parsed (10.3.5extrastuff).
1864 bool Driver::GetReleaseVersion(const char *Str
, unsigned &Major
,
1865 unsigned &Minor
, unsigned &Micro
,
1869 Major
= Minor
= Micro
= 0;
1874 Major
= (unsigned) strtol(Str
, &End
, 10);
1875 if (*Str
!= '\0' && *End
== '\0')
1881 Minor
= (unsigned) strtol(Str
, &End
, 10);
1882 if (*Str
!= '\0' && *End
== '\0')
1888 Micro
= (unsigned) strtol(Str
, &End
, 10);
1889 if (*Str
!= '\0' && *End
== '\0')