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