1 //===--- CompilerInstance.cpp ---------------------------------------------===// 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/Frontend/CompilerInstance.h" 11 #include "clang/Sema/Sema.h" 12 #include "clang/AST/ASTConsumer.h" 13 #include "clang/AST/ASTContext.h" 14 #include "clang/AST/Decl.h" 15 #include "clang/Basic/Diagnostic.h" 16 #include "clang/Basic/FileManager.h" 17 #include "clang/Basic/SourceManager.h" 18 #include "clang/Basic/TargetInfo.h" 19 #include "clang/Basic/Version.h" 20 #include "clang/Lex/HeaderSearch.h" 21 #include "clang/Lex/Preprocessor.h" 22 #include "clang/Lex/PTHManager.h" 23 #include "clang/Frontend/ChainedDiagnosticConsumer.h" 24 #include "clang/Frontend/FrontendAction.h" 25 #include "clang/Frontend/FrontendActions.h" 26 #include "clang/Frontend/FrontendDiagnostic.h" 27 #include "clang/Frontend/LogDiagnosticPrinter.h" 28 #include "clang/Frontend/SerializedDiagnosticPrinter.h" 29 #include "clang/Frontend/TextDiagnosticPrinter.h" 30 #include "clang/Frontend/VerifyDiagnosticConsumer.h" 31 #include "clang/Frontend/Utils.h" 32 #include "clang/Serialization/ASTReader.h" 33 #include "clang/Sema/CodeCompleteConsumer.h" 34 #include "llvm/Support/FileSystem.h" 35 #include "llvm/Support/MemoryBuffer.h" 36 #include "llvm/Support/raw_ostream.h" 37 #include "llvm/ADT/Statistic.h" 38 #include "llvm/Support/Timer.h" 39 #include "llvm/Support/Host.h" 40 #include "llvm/Support/LockFileManager.h" 41 #include "llvm/Support/Path.h" 42 #include "llvm/Support/Program.h" 43 #include "llvm/Support/Signals.h" 44 #include "llvm/Support/system_error.h" 45 #include "llvm/Support/CrashRecoveryContext.h" 46 #include "llvm/Config/config.h" 47 48 using namespace clang; 49 50 CompilerInstance::CompilerInstance() 51 : Invocation(new CompilerInvocation()), ModuleManager(0) { 52 } 53 54 CompilerInstance::~CompilerInstance() { 55 assert(OutputFiles.empty() && "Still output files in flight?"); 56 } 57 58 void CompilerInstance::setInvocation(CompilerInvocation *Value) { 59 Invocation = Value; 60 } 61 62 void CompilerInstance::setDiagnostics(DiagnosticsEngine *Value) { 63 Diagnostics = Value; 64 } 65 66 void CompilerInstance::setTarget(TargetInfo *Value) { 67 Target = Value; 68 } 69 70 void CompilerInstance::setFileManager(FileManager *Value) { 71 FileMgr = Value; 72 } 73 74 void CompilerInstance::setSourceManager(SourceManager *Value) { 75 SourceMgr = Value; 76 } 77 78 void CompilerInstance::setPreprocessor(Preprocessor *Value) { PP = Value; } 79 80 void CompilerInstance::setASTContext(ASTContext *Value) { Context = Value; } 81 82 void CompilerInstance::setSema(Sema *S) { 83 TheSema.reset(S); 84 } 85 86 void CompilerInstance::setASTConsumer(ASTConsumer *Value) { 87 Consumer.reset(Value); 88 } 89 90 void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) { 91 CompletionConsumer.reset(Value); 92 } 93 94 // Diagnostics 95 static void SetUpBuildDumpLog(DiagnosticOptions *DiagOpts, 96 unsigned argc, const char* const *argv, 97 DiagnosticsEngine &Diags) { 98 std::string ErrorInfo; 99 OwningPtr<raw_ostream> OS( 100 new llvm::raw_fd_ostream(DiagOpts->DumpBuildInformation.c_str(),ErrorInfo)); 101 if (!ErrorInfo.empty()) { 102 Diags.Report(diag::err_fe_unable_to_open_logfile) 103 << DiagOpts->DumpBuildInformation << ErrorInfo; 104 return; 105 } 106 107 (*OS) << "clang -cc1 command line arguments: "; 108 for (unsigned i = 0; i != argc; ++i) 109 (*OS) << argv[i] << ' '; 110 (*OS) << '\n'; 111 112 // Chain in a diagnostic client which will log the diagnostics. 113 DiagnosticConsumer *Logger = 114 new TextDiagnosticPrinter(*OS.take(), DiagOpts, /*OwnsOutputStream=*/true); 115 Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), Logger)); 116 } 117 118 static void SetUpDiagnosticLog(DiagnosticOptions *DiagOpts, 119 const CodeGenOptions *CodeGenOpts, 120 DiagnosticsEngine &Diags) { 121 std::string ErrorInfo; 122 bool OwnsStream = false; 123 raw_ostream *OS = &llvm::errs(); 124 if (DiagOpts->DiagnosticLogFile != "-") { 125 // Create the output stream. 126 llvm::raw_fd_ostream *FileOS( 127 new llvm::raw_fd_ostream(DiagOpts->DiagnosticLogFile.c_str(), 128 ErrorInfo, llvm::raw_fd_ostream::F_Append)); 129 if (!ErrorInfo.empty()) { 130 Diags.Report(diag::warn_fe_cc_log_diagnostics_failure) 131 << DiagOpts->DumpBuildInformation << ErrorInfo; 132 } else { 133 FileOS->SetUnbuffered(); 134 FileOS->SetUseAtomicWrites(true); 135 OS = FileOS; 136 OwnsStream = true; 137 } 138 } 139 140 // Chain in the diagnostic client which will log the diagnostics. 141 LogDiagnosticPrinter *Logger = new LogDiagnosticPrinter(*OS, DiagOpts, 142 OwnsStream); 143 if (CodeGenOpts) 144 Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags); 145 Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), Logger)); 146 } 147 148 static void SetupSerializedDiagnostics(DiagnosticOptions *DiagOpts, 149 DiagnosticsEngine &Diags, 150 StringRef OutputFile) { 151 std::string ErrorInfo; 152 OwningPtr<llvm::raw_fd_ostream> OS; 153 OS.reset(new llvm::raw_fd_ostream(OutputFile.str().c_str(), ErrorInfo, 154 llvm::raw_fd_ostream::F_Binary)); 155 156 if (!ErrorInfo.empty()) { 157 Diags.Report(diag::warn_fe_serialized_diag_failure) 158 << OutputFile << ErrorInfo; 159 return; 160 } 161 162 DiagnosticConsumer *SerializedConsumer = 163 clang::serialized_diags::create(OS.take(), DiagOpts); 164 165 166 Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), 167 SerializedConsumer)); 168 } 169 170 void CompilerInstance::createDiagnostics(int Argc, const char* const *Argv, 171 DiagnosticConsumer *Client, 172 bool ShouldOwnClient, 173 bool ShouldCloneClient) { 174 Diagnostics = createDiagnostics(&getDiagnosticOpts(), Argc, Argv, Client, 175 ShouldOwnClient, ShouldCloneClient, 176 &getCodeGenOpts()); 177 } 178 179 IntrusiveRefCntPtr<DiagnosticsEngine> 180 CompilerInstance::createDiagnostics(DiagnosticOptions *Opts, 181 int Argc, const char* const *Argv, 182 DiagnosticConsumer *Client, 183 bool ShouldOwnClient, 184 bool ShouldCloneClient, 185 const CodeGenOptions *CodeGenOpts) { 186 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs()); 187 IntrusiveRefCntPtr<DiagnosticsEngine> 188 Diags(new DiagnosticsEngine(DiagID, Opts)); 189 190 // Create the diagnostic client for reporting errors or for 191 // implementing -verify. 192 if (Client) { 193 if (ShouldCloneClient) 194 Diags->setClient(Client->clone(*Diags), ShouldOwnClient); 195 else 196 Diags->setClient(Client, ShouldOwnClient); 197 } else 198 Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts)); 199 200 // Chain in -verify checker, if requested. 201 if (Opts->VerifyDiagnostics) 202 Diags->setClient(new VerifyDiagnosticConsumer(*Diags)); 203 204 // Chain in -diagnostic-log-file dumper, if requested. 205 if (!Opts->DiagnosticLogFile.empty()) 206 SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags); 207 208 if (!Opts->DumpBuildInformation.empty()) 209 SetUpBuildDumpLog(Opts, Argc, Argv, *Diags); 210 211 if (!Opts->DiagnosticSerializationFile.empty()) 212 SetupSerializedDiagnostics(Opts, *Diags, 213 Opts->DiagnosticSerializationFile); 214 215 // Configure our handling of diagnostics. 216 ProcessWarningOptions(*Diags, *Opts); 217 218 return Diags; 219 } 220 221 // File Manager 222 223 void CompilerInstance::createFileManager() { 224 FileMgr = new FileManager(getFileSystemOpts()); 225 } 226 227 // Source Manager 228 229 void CompilerInstance::createSourceManager(FileManager &FileMgr) { 230 SourceMgr = new SourceManager(getDiagnostics(), FileMgr); 231 } 232 233 // Preprocessor 234 235 void CompilerInstance::createPreprocessor() { 236 const PreprocessorOptions &PPOpts = getPreprocessorOpts(); 237 238 // Create a PTH manager if we are using some form of a token cache. 239 PTHManager *PTHMgr = 0; 240 if (!PPOpts.TokenCache.empty()) 241 PTHMgr = PTHManager::Create(PPOpts.TokenCache, getDiagnostics()); 242 243 // Create the Preprocessor. 244 HeaderSearch *HeaderInfo = new HeaderSearch(&getHeaderSearchOpts(), 245 getFileManager(), 246 getDiagnostics(), 247 getLangOpts(), 248 &getTarget()); 249 PP = new Preprocessor(&getPreprocessorOpts(), 250 getDiagnostics(), getLangOpts(), &getTarget(), 251 getSourceManager(), *HeaderInfo, *this, PTHMgr, 252 /*OwnsHeaderSearch=*/true); 253 254 // Note that this is different then passing PTHMgr to Preprocessor's ctor. 255 // That argument is used as the IdentifierInfoLookup argument to 256 // IdentifierTable's ctor. 257 if (PTHMgr) { 258 PTHMgr->setPreprocessor(&*PP); 259 PP->setPTHManager(PTHMgr); 260 } 261 262 if (PPOpts.DetailedRecord) 263 PP->createPreprocessingRecord(PPOpts.DetailedRecordConditionalDirectives); 264 265 InitializePreprocessor(*PP, PPOpts, getHeaderSearchOpts(), getFrontendOpts()); 266 267 // Set up the module path, including the hash for the 268 // module-creation options. 269 SmallString<256> SpecificModuleCache( 270 getHeaderSearchOpts().ModuleCachePath); 271 if (!getHeaderSearchOpts().DisableModuleHash) 272 llvm::sys::path::append(SpecificModuleCache, 273 getInvocation().getModuleHash()); 274 PP->getHeaderSearchInfo().setModuleCachePath(SpecificModuleCache); 275 276 // Handle generating dependencies, if requested. 277 const DependencyOutputOptions &DepOpts = getDependencyOutputOpts(); 278 if (!DepOpts.OutputFile.empty()) 279 AttachDependencyFileGen(*PP, DepOpts); 280 if (!DepOpts.DOTOutputFile.empty()) 281 AttachDependencyGraphGen(*PP, DepOpts.DOTOutputFile, 282 getHeaderSearchOpts().Sysroot); 283 284 285 // Handle generating header include information, if requested. 286 if (DepOpts.ShowHeaderIncludes) 287 AttachHeaderIncludeGen(*PP); 288 if (!DepOpts.HeaderIncludeOutputFile.empty()) { 289 StringRef OutputPath = DepOpts.HeaderIncludeOutputFile; 290 if (OutputPath == "-") 291 OutputPath = ""; 292 AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/true, OutputPath, 293 /*ShowDepth=*/false); 294 } 295 } 296 297 // ASTContext 298 299 void CompilerInstance::createASTContext() { 300 Preprocessor &PP = getPreprocessor(); 301 Context = new ASTContext(getLangOpts(), PP.getSourceManager(), 302 &getTarget(), PP.getIdentifierTable(), 303 PP.getSelectorTable(), PP.getBuiltinInfo(), 304 /*size_reserve=*/ 0); 305 } 306 307 // ExternalASTSource 308 309 void CompilerInstance::createPCHExternalASTSource(StringRef Path, 310 bool DisablePCHValidation, 311 bool AllowPCHWithCompilerErrors, 312 void *DeserializationListener){ 313 OwningPtr<ExternalASTSource> Source; 314 bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0; 315 Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot, 316 DisablePCHValidation, 317 AllowPCHWithCompilerErrors, 318 getPreprocessor(), getASTContext(), 319 DeserializationListener, 320 Preamble)); 321 ModuleManager = static_cast<ASTReader*>(Source.get()); 322 getASTContext().setExternalSource(Source); 323 } 324 325 ExternalASTSource * 326 CompilerInstance::createPCHExternalASTSource(StringRef Path, 327 const std::string &Sysroot, 328 bool DisablePCHValidation, 329 bool AllowPCHWithCompilerErrors, 330 Preprocessor &PP, 331 ASTContext &Context, 332 void *DeserializationListener, 333 bool Preamble) { 334 OwningPtr<ASTReader> Reader; 335 Reader.reset(new ASTReader(PP, Context, 336 Sysroot.empty() ? "" : Sysroot.c_str(), 337 DisablePCHValidation, 338 AllowPCHWithCompilerErrors)); 339 340 Reader->setDeserializationListener( 341 static_cast<ASTDeserializationListener *>(DeserializationListener)); 342 switch (Reader->ReadAST(Path, 343 Preamble ? serialization::MK_Preamble 344 : serialization::MK_PCH, 345 ASTReader::ARR_None)) { 346 case ASTReader::Success: 347 // Set the predefines buffer as suggested by the PCH reader. Typically, the 348 // predefines buffer will be empty. 349 PP.setPredefines(Reader->getSuggestedPredefines()); 350 return Reader.take(); 351 352 case ASTReader::Failure: 353 // Unrecoverable failure: don't even try to process the input file. 354 break; 355 356 case ASTReader::OutOfDate: 357 case ASTReader::VersionMismatch: 358 case ASTReader::ConfigurationMismatch: 359 case ASTReader::HadErrors: 360 // No suitable PCH file could be found. Return an error. 361 break; 362 } 363 364 return 0; 365 } 366 367 // Code Completion 368 369 static bool EnableCodeCompletion(Preprocessor &PP, 370 const std::string &Filename, 371 unsigned Line, 372 unsigned Column) { 373 // Tell the source manager to chop off the given file at a specific 374 // line and column. 375 const FileEntry *Entry = PP.getFileManager().getFile(Filename); 376 if (!Entry) { 377 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file) 378 << Filename; 379 return true; 380 } 381 382 // Truncate the named file at the given line/column. 383 PP.SetCodeCompletionPoint(Entry, Line, Column); 384 return false; 385 } 386 387 void CompilerInstance::createCodeCompletionConsumer() { 388 const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt; 389 if (!CompletionConsumer) { 390 setCodeCompletionConsumer( 391 createCodeCompletionConsumer(getPreprocessor(), 392 Loc.FileName, Loc.Line, Loc.Column, 393 getFrontendOpts().CodeCompleteOpts, 394 llvm::outs())); 395 if (!CompletionConsumer) 396 return; 397 } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName, 398 Loc.Line, Loc.Column)) { 399 setCodeCompletionConsumer(0); 400 return; 401 } 402 403 if (CompletionConsumer->isOutputBinary() && 404 llvm::sys::Program::ChangeStdoutToBinary()) { 405 getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary); 406 setCodeCompletionConsumer(0); 407 } 408 } 409 410 void CompilerInstance::createFrontendTimer() { 411 FrontendTimer.reset(new llvm::Timer("Clang front-end timer")); 412 } 413 414 CodeCompleteConsumer * 415 CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP, 416 const std::string &Filename, 417 unsigned Line, 418 unsigned Column, 419 const CodeCompleteOptions &Opts, 420 raw_ostream &OS) { 421 if (EnableCodeCompletion(PP, Filename, Line, Column)) 422 return 0; 423 424 // Set up the creation routine for code-completion. 425 return new PrintingCodeCompleteConsumer(Opts, OS); 426 } 427 428 void CompilerInstance::createSema(TranslationUnitKind TUKind, 429 CodeCompleteConsumer *CompletionConsumer) { 430 TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(), 431 TUKind, CompletionConsumer)); 432 } 433 434 // Output Files 435 436 void CompilerInstance::addOutputFile(const OutputFile &OutFile) { 437 assert(OutFile.OS && "Attempt to add empty stream to output list!"); 438 OutputFiles.push_back(OutFile); 439 } 440 441 void CompilerInstance::clearOutputFiles(bool EraseFiles) { 442 for (std::list<OutputFile>::iterator 443 it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) { 444 delete it->OS; 445 if (!it->TempFilename.empty()) { 446 if (EraseFiles) { 447 bool existed; 448 llvm::sys::fs::remove(it->TempFilename, existed); 449 } else { 450 SmallString<128> NewOutFile(it->Filename); 451 452 // If '-working-directory' was passed, the output filename should be 453 // relative to that. 454 FileMgr->FixupRelativePath(NewOutFile); 455 if (llvm::error_code ec = llvm::sys::fs::rename(it->TempFilename, 456 NewOutFile.str())) { 457 getDiagnostics().Report(diag::err_unable_to_rename_temp) 458 << it->TempFilename << it->Filename << ec.message(); 459 460 bool existed; 461 llvm::sys::fs::remove(it->TempFilename, existed); 462 } 463 } 464 } else if (!it->Filename.empty() && EraseFiles) 465 llvm::sys::Path(it->Filename).eraseFromDisk(); 466 467 } 468 OutputFiles.clear(); 469 } 470 471 llvm::raw_fd_ostream * 472 CompilerInstance::createDefaultOutputFile(bool Binary, 473 StringRef InFile, 474 StringRef Extension) { 475 return createOutputFile(getFrontendOpts().OutputFile, Binary, 476 /*RemoveFileOnSignal=*/true, InFile, Extension, 477 /*UseTemporary=*/true); 478 } 479 480 llvm::raw_fd_ostream * 481 CompilerInstance::createOutputFile(StringRef OutputPath, 482 bool Binary, bool RemoveFileOnSignal, 483 StringRef InFile, 484 StringRef Extension, 485 bool UseTemporary, 486 bool CreateMissingDirectories) { 487 std::string Error, OutputPathName, TempPathName; 488 llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary, 489 RemoveFileOnSignal, 490 InFile, Extension, 491 UseTemporary, 492 CreateMissingDirectories, 493 &OutputPathName, 494 &TempPathName); 495 if (!OS) { 496 getDiagnostics().Report(diag::err_fe_unable_to_open_output) 497 << OutputPath << Error; 498 return 0; 499 } 500 501 // Add the output file -- but don't try to remove "-", since this means we are 502 // using stdin. 503 addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "", 504 TempPathName, OS)); 505 506 return OS; 507 } 508 509 llvm::raw_fd_ostream * 510 CompilerInstance::createOutputFile(StringRef OutputPath, 511 std::string &Error, 512 bool Binary, 513 bool RemoveFileOnSignal, 514 StringRef InFile, 515 StringRef Extension, 516 bool UseTemporary, 517 bool CreateMissingDirectories, 518 std::string *ResultPathName, 519 std::string *TempPathName) { 520 assert((!CreateMissingDirectories || UseTemporary) && 521 "CreateMissingDirectories is only allowed when using temporary files"); 522 523 std::string OutFile, TempFile; 524 if (!OutputPath.empty()) { 525 OutFile = OutputPath; 526 } else if (InFile == "-") { 527 OutFile = "-"; 528 } else if (!Extension.empty()) { 529 llvm::sys::Path Path(InFile); 530 Path.eraseSuffix(); 531 Path.appendSuffix(Extension); 532 OutFile = Path.str(); 533 } else { 534 OutFile = "-"; 535 } 536 537 OwningPtr<llvm::raw_fd_ostream> OS; 538 std::string OSFile; 539 540 if (UseTemporary && OutFile != "-") { 541 // Only create the temporary if the parent directory exists (or create 542 // missing directories is true) and we can actually write to OutPath, 543 // otherwise we want to fail early. 544 SmallString<256> AbsPath(OutputPath); 545 llvm::sys::fs::make_absolute(AbsPath); 546 llvm::sys::Path OutPath(AbsPath); 547 bool ParentExists = false; 548 if (llvm::sys::fs::exists(llvm::sys::path::parent_path(AbsPath.str()), 549 ParentExists)) 550 ParentExists = false; 551 bool Exists; 552 if ((CreateMissingDirectories || ParentExists) && 553 ((llvm::sys::fs::exists(AbsPath.str(), Exists) || !Exists) || 554 (OutPath.isRegularFile() && OutPath.canWrite()))) { 555 // Create a temporary file. 556 SmallString<128> TempPath; 557 TempPath = OutFile; 558 TempPath += "-%%%%%%%%"; 559 int fd; 560 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath, 561 /*makeAbsolute=*/false, 0664) 562 == llvm::errc::success) { 563 OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true)); 564 OSFile = TempFile = TempPath.str(); 565 } 566 } 567 } 568 569 if (!OS) { 570 OSFile = OutFile; 571 OS.reset( 572 new llvm::raw_fd_ostream(OSFile.c_str(), Error, 573 (Binary ? llvm::raw_fd_ostream::F_Binary : 0))); 574 if (!Error.empty()) 575 return 0; 576 } 577 578 // Make sure the out stream file gets removed if we crash. 579 if (RemoveFileOnSignal) 580 llvm::sys::RemoveFileOnSignal(llvm::sys::Path(OSFile)); 581 582 if (ResultPathName) 583 *ResultPathName = OutFile; 584 if (TempPathName) 585 *TempPathName = TempFile; 586 587 return OS.take(); 588 } 589 590 // Initialization Utilities 591 592 bool CompilerInstance::InitializeSourceManager(StringRef InputFile, 593 SrcMgr::CharacteristicKind Kind){ 594 return InitializeSourceManager(InputFile, Kind, getDiagnostics(), 595 getFileManager(), getSourceManager(), 596 getFrontendOpts()); 597 } 598 599 bool CompilerInstance::InitializeSourceManager(StringRef InputFile, 600 SrcMgr::CharacteristicKind Kind, 601 DiagnosticsEngine &Diags, 602 FileManager &FileMgr, 603 SourceManager &SourceMgr, 604 const FrontendOptions &Opts) { 605 // Figure out where to get and map in the main file. 606 if (InputFile != "-") { 607 const FileEntry *File = FileMgr.getFile(InputFile); 608 if (!File) { 609 Diags.Report(diag::err_fe_error_reading) << InputFile; 610 return false; 611 } 612 SourceMgr.createMainFileID(File, Kind); 613 } else { 614 OwningPtr<llvm::MemoryBuffer> SB; 615 if (llvm::MemoryBuffer::getSTDIN(SB)) { 616 // FIXME: Give ec.message() in this diag. 617 Diags.Report(diag::err_fe_error_reading_stdin); 618 return false; 619 } 620 const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(), 621 SB->getBufferSize(), 0); 622 SourceMgr.createMainFileID(File, Kind); 623 SourceMgr.overrideFileContents(File, SB.take()); 624 } 625 626 assert(!SourceMgr.getMainFileID().isInvalid() && 627 "Couldn't establish MainFileID!"); 628 return true; 629 } 630 631 // High-Level Operations 632 633 bool CompilerInstance::ExecuteAction(FrontendAction &Act) { 634 assert(hasDiagnostics() && "Diagnostics engine is not initialized!"); 635 assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!"); 636 assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!"); 637 638 // FIXME: Take this as an argument, once all the APIs we used have moved to 639 // taking it as an input instead of hard-coding llvm::errs. 640 raw_ostream &OS = llvm::errs(); 641 642 // Create the target instance. 643 setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), getTargetOpts())); 644 if (!hasTarget()) 645 return false; 646 647 // Inform the target of the language options. 648 // 649 // FIXME: We shouldn't need to do this, the target should be immutable once 650 // created. This complexity should be lifted elsewhere. 651 getTarget().setForcedLangOptions(getLangOpts()); 652 653 // rewriter project will change target built-in bool type from its default. 654 if (getFrontendOpts().ProgramAction == frontend::RewriteObjC) 655 getTarget().noSignedCharForObjCBool(); 656 657 // Validate/process some options. 658 if (getHeaderSearchOpts().Verbose) 659 OS << "clang -cc1 version " CLANG_VERSION_STRING 660 << " based upon " << PACKAGE_STRING 661 << " default target " << llvm::sys::getDefaultTargetTriple() << "\n"; 662 663 if (getFrontendOpts().ShowTimers) 664 createFrontendTimer(); 665 666 if (getFrontendOpts().ShowStats) 667 llvm::EnableStatistics(); 668 669 for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) { 670 // Reset the ID tables if we are reusing the SourceManager. 671 if (hasSourceManager()) 672 getSourceManager().clearIDTables(); 673 674 if (Act.BeginSourceFile(*this, getFrontendOpts().Inputs[i])) { 675 Act.Execute(); 676 Act.EndSourceFile(); 677 } 678 } 679 680 // Notify the diagnostic client that all files were processed. 681 getDiagnostics().getClient()->finish(); 682 683 if (getDiagnosticOpts().ShowCarets) { 684 // We can have multiple diagnostics sharing one diagnostic client. 685 // Get the total number of warnings/errors from the client. 686 unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings(); 687 unsigned NumErrors = getDiagnostics().getClient()->getNumErrors(); 688 689 if (NumWarnings) 690 OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s"); 691 if (NumWarnings && NumErrors) 692 OS << " and "; 693 if (NumErrors) 694 OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s"); 695 if (NumWarnings || NumErrors) 696 OS << " generated.\n"; 697 } 698 699 if (getFrontendOpts().ShowStats && hasFileManager()) { 700 getFileManager().PrintStats(); 701 OS << "\n"; 702 } 703 704 return !getDiagnostics().getClient()->getNumErrors(); 705 } 706 707 /// \brief Determine the appropriate source input kind based on language 708 /// options. 709 static InputKind getSourceInputKindFromOptions(const LangOptions &LangOpts) { 710 if (LangOpts.OpenCL) 711 return IK_OpenCL; 712 if (LangOpts.CUDA) 713 return IK_CUDA; 714 if (LangOpts.ObjC1) 715 return LangOpts.CPlusPlus? IK_ObjCXX : IK_ObjC; 716 return LangOpts.CPlusPlus? IK_CXX : IK_C; 717 } 718 719 namespace { 720 struct CompileModuleMapData { 721 CompilerInstance &Instance; 722 GenerateModuleAction &CreateModuleAction; 723 }; 724 } 725 726 /// \brief Helper function that executes the module-generating action under 727 /// a crash recovery context. 728 static void doCompileMapModule(void *UserData) { 729 CompileModuleMapData &Data 730 = *reinterpret_cast<CompileModuleMapData *>(UserData); 731 Data.Instance.ExecuteAction(Data.CreateModuleAction); 732 } 733 734 /// \brief Compile a module file for the given module, using the options 735 /// provided by the importing compiler instance. 736 static void compileModule(CompilerInstance &ImportingInstance, 737 Module *Module, 738 StringRef ModuleFileName) { 739 llvm::LockFileManager Locked(ModuleFileName); 740 switch (Locked) { 741 case llvm::LockFileManager::LFS_Error: 742 return; 743 744 case llvm::LockFileManager::LFS_Owned: 745 // We're responsible for building the module ourselves. Do so below. 746 break; 747 748 case llvm::LockFileManager::LFS_Shared: 749 // Someone else is responsible for building the module. Wait for them to 750 // finish. 751 Locked.waitForUnlock(); 752 break; 753 } 754 755 ModuleMap &ModMap 756 = ImportingInstance.getPreprocessor().getHeaderSearchInfo().getModuleMap(); 757 758 // Construct a compiler invocation for creating this module. 759 IntrusiveRefCntPtr<CompilerInvocation> Invocation 760 (new CompilerInvocation(ImportingInstance.getInvocation())); 761 762 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts(); 763 764 // For any options that aren't intended to affect how a module is built, 765 // reset them to their default values. 766 Invocation->getLangOpts()->resetNonModularOptions(); 767 PPOpts.resetNonModularOptions(); 768 769 // Note the name of the module we're building. 770 Invocation->getLangOpts()->CurrentModule = Module->getTopLevelModuleName(); 771 772 // Note that this module is part of the module build path, so that we 773 // can detect cycles in the module graph. 774 PPOpts.ModuleBuildPath.push_back(Module->getTopLevelModuleName()); 775 776 // If there is a module map file, build the module using the module map. 777 // Set up the inputs/outputs so that we build the module from its umbrella 778 // header. 779 FrontendOptions &FrontendOpts = Invocation->getFrontendOpts(); 780 FrontendOpts.OutputFile = ModuleFileName.str(); 781 FrontendOpts.DisableFree = false; 782 FrontendOpts.Inputs.clear(); 783 InputKind IK = getSourceInputKindFromOptions(*Invocation->getLangOpts()); 784 785 // Get or create the module map that we'll use to build this module. 786 SmallString<128> TempModuleMapFileName; 787 if (const FileEntry *ModuleMapFile 788 = ModMap.getContainingModuleMapFile(Module)) { 789 // Use the module map where this module resides. 790 FrontendOpts.Inputs.push_back(FrontendInputFile(ModuleMapFile->getName(), 791 IK)); 792 } else { 793 // Create a temporary module map file. 794 TempModuleMapFileName = Module->Name; 795 TempModuleMapFileName += "-%%%%%%%%.map"; 796 int FD; 797 if (llvm::sys::fs::unique_file(TempModuleMapFileName.str(), FD, 798 TempModuleMapFileName, 799 /*makeAbsolute=*/true) 800 != llvm::errc::success) { 801 ImportingInstance.getDiagnostics().Report(diag::err_module_map_temp_file) 802 << TempModuleMapFileName; 803 return; 804 } 805 // Print the module map to this file. 806 llvm::raw_fd_ostream OS(FD, /*shouldClose=*/true); 807 Module->print(OS); 808 FrontendOpts.Inputs.push_back( 809 FrontendInputFile(TempModuleMapFileName.str().str(), IK)); 810 } 811 812 // Don't free the remapped file buffers; they are owned by our caller. 813 PPOpts.RetainRemappedFileBuffers = true; 814 815 Invocation->getDiagnosticOpts().VerifyDiagnostics = 0; 816 assert(ImportingInstance.getInvocation().getModuleHash() == 817 Invocation->getModuleHash() && "Module hash mismatch!"); 818 819 // Construct a compiler instance that will be used to actually create the 820 // module. 821 CompilerInstance Instance; 822 Instance.setInvocation(&*Invocation); 823 Instance.createDiagnostics(/*argc=*/0, /*argv=*/0, 824 &ImportingInstance.getDiagnosticClient(), 825 /*ShouldOwnClient=*/true, 826 /*ShouldCloneClient=*/true); 827 828 // Construct a module-generating action. 829 GenerateModuleAction CreateModuleAction; 830 831 // Execute the action to actually build the module in-place. Use a separate 832 // thread so that we get a stack large enough. 833 const unsigned ThreadStackSize = 8 << 20; 834 llvm::CrashRecoveryContext CRC; 835 CompileModuleMapData Data = { Instance, CreateModuleAction }; 836 CRC.RunSafelyOnThread(&doCompileMapModule, &Data, ThreadStackSize); 837 838 // Delete the temporary module map file. 839 // FIXME: Even though we're executing under crash protection, it would still 840 // be nice to do this with RemoveFileOnSignal when we can. However, that 841 // doesn't make sense for all clients, so clean this up manually. 842 Instance.clearOutputFiles(/*EraseFiles=*/true); 843 if (!TempModuleMapFileName.empty()) 844 llvm::sys::Path(TempModuleMapFileName).eraseFromDisk(); 845 } 846 847 Module *CompilerInstance::loadModule(SourceLocation ImportLoc, 848 ModuleIdPath Path, 849 Module::NameVisibilityKind Visibility, 850 bool IsInclusionDirective) { 851 // If we've already handled this import, just return the cached result. 852 // This one-element cache is important to eliminate redundant diagnostics 853 // when both the preprocessor and parser see the same import declaration. 854 if (!ImportLoc.isInvalid() && LastModuleImportLoc == ImportLoc) { 855 // Make the named module visible. 856 if (LastModuleImportResult) 857 ModuleManager->makeModuleVisible(LastModuleImportResult, Visibility); 858 return LastModuleImportResult; 859 } 860 861 // Determine what file we're searching from. 862 StringRef ModuleName = Path[0].first->getName(); 863 SourceLocation ModuleNameLoc = Path[0].second; 864 865 clang::Module *Module = 0; 866 867 // If we don't already have information on this module, load the module now. 868 llvm::DenseMap<const IdentifierInfo *, clang::Module *>::iterator Known 869 = KnownModules.find(Path[0].first); 870 if (Known != KnownModules.end()) { 871 // Retrieve the cached top-level module. 872 Module = Known->second; 873 } else if (ModuleName == getLangOpts().CurrentModule) { 874 // This is the module we're building. 875 Module = PP->getHeaderSearchInfo().getModuleMap().findModule(ModuleName); 876 Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first; 877 } else { 878 // Search for a module with the given name. 879 Module = PP->getHeaderSearchInfo().lookupModule(ModuleName); 880 std::string ModuleFileName; 881 if (Module) 882 ModuleFileName = PP->getHeaderSearchInfo().getModuleFileName(Module); 883 else 884 ModuleFileName = PP->getHeaderSearchInfo().getModuleFileName(ModuleName); 885 886 if (ModuleFileName.empty()) { 887 getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found) 888 << ModuleName 889 << SourceRange(ImportLoc, ModuleNameLoc); 890 LastModuleImportLoc = ImportLoc; 891 LastModuleImportResult = 0; 892 return 0; 893 } 894 895 const FileEntry *ModuleFile 896 = getFileManager().getFile(ModuleFileName, /*OpenFile=*/false, 897 /*CacheFailure=*/false); 898 bool BuildingModule = false; 899 if (!ModuleFile && Module) { 900 // The module is not cached, but we have a module map from which we can 901 // build the module. 902 903 // Check whether there is a cycle in the module graph. 904 SmallVectorImpl<std::string> &ModuleBuildPath 905 = getPreprocessorOpts().ModuleBuildPath; 906 SmallVectorImpl<std::string>::iterator Pos 907 = std::find(ModuleBuildPath.begin(), ModuleBuildPath.end(), ModuleName); 908 if (Pos != ModuleBuildPath.end()) { 909 SmallString<256> CyclePath; 910 for (; Pos != ModuleBuildPath.end(); ++Pos) { 911 CyclePath += *Pos; 912 CyclePath += " -> "; 913 } 914 CyclePath += ModuleName; 915 916 getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle) 917 << ModuleName << CyclePath; 918 return 0; 919 } 920 921 getDiagnostics().Report(ModuleNameLoc, diag::warn_module_build) 922 << ModuleName; 923 BuildingModule = true; 924 compileModule(*this, Module, ModuleFileName); 925 ModuleFile = FileMgr->getFile(ModuleFileName); 926 } 927 928 if (!ModuleFile) { 929 getDiagnostics().Report(ModuleNameLoc, 930 BuildingModule? diag::err_module_not_built 931 : diag::err_module_not_found) 932 << ModuleName 933 << SourceRange(ImportLoc, ModuleNameLoc); 934 return 0; 935 } 936 937 // If we don't already have an ASTReader, create one now. 938 if (!ModuleManager) { 939 if (!hasASTContext()) 940 createASTContext(); 941 942 std::string Sysroot = getHeaderSearchOpts().Sysroot; 943 const PreprocessorOptions &PPOpts = getPreprocessorOpts(); 944 ModuleManager = new ASTReader(getPreprocessor(), *Context, 945 Sysroot.empty() ? "" : Sysroot.c_str(), 946 PPOpts.DisablePCHValidation); 947 if (hasASTConsumer()) { 948 ModuleManager->setDeserializationListener( 949 getASTConsumer().GetASTDeserializationListener()); 950 getASTContext().setASTMutationListener( 951 getASTConsumer().GetASTMutationListener()); 952 getPreprocessor().setPPMutationListener( 953 getASTConsumer().GetPPMutationListener()); 954 } 955 OwningPtr<ExternalASTSource> Source; 956 Source.reset(ModuleManager); 957 getASTContext().setExternalSource(Source); 958 if (hasSema()) 959 ModuleManager->InitializeSema(getSema()); 960 if (hasASTConsumer()) 961 ModuleManager->StartTranslationUnit(&getASTConsumer()); 962 } 963 964 // Try to load the module we found. 965 switch (ModuleManager->ReadAST(ModuleFile->getName(), 966 serialization::MK_Module, 967 ASTReader::ARR_None)) { 968 case ASTReader::Success: 969 break; 970 971 case ASTReader::OutOfDate: 972 case ASTReader::VersionMismatch: 973 case ASTReader::ConfigurationMismatch: 974 case ASTReader::HadErrors: 975 // FIXME: The ASTReader will already have complained, but can we showhorn 976 // that diagnostic information into a more useful form? 977 KnownModules[Path[0].first] = 0; 978 return 0; 979 980 case ASTReader::Failure: 981 // Already complained, but note now that we failed. 982 KnownModules[Path[0].first] = 0; 983 return 0; 984 } 985 986 if (!Module) { 987 // If we loaded the module directly, without finding a module map first, 988 // we'll have loaded the module's information from the module itself. 989 Module = PP->getHeaderSearchInfo().getModuleMap() 990 .findModule((Path[0].first->getName())); 991 } 992 993 if (Module) 994 Module->setASTFile(ModuleFile); 995 996 // Cache the result of this top-level module lookup for later. 997 Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first; 998 } 999 1000 // If we never found the module, fail. 1001 if (!Module) 1002 return 0; 1003 1004 // Verify that the rest of the module path actually corresponds to 1005 // a submodule. 1006 if (Path.size() > 1) { 1007 for (unsigned I = 1, N = Path.size(); I != N; ++I) { 1008 StringRef Name = Path[I].first->getName(); 1009 clang::Module *Sub = Module->findSubmodule(Name); 1010 1011 if (!Sub) { 1012 // Attempt to perform typo correction to find a module name that works. 1013 llvm::SmallVector<StringRef, 2> Best; 1014 unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)(); 1015 1016 for (clang::Module::submodule_iterator J = Module->submodule_begin(), 1017 JEnd = Module->submodule_end(); 1018 J != JEnd; ++J) { 1019 unsigned ED = Name.edit_distance((*J)->Name, 1020 /*AllowReplacements=*/true, 1021 BestEditDistance); 1022 if (ED <= BestEditDistance) { 1023 if (ED < BestEditDistance) { 1024 Best.clear(); 1025 BestEditDistance = ED; 1026 } 1027 1028 Best.push_back((*J)->Name); 1029 } 1030 } 1031 1032 // If there was a clear winner, user it. 1033 if (Best.size() == 1) { 1034 getDiagnostics().Report(Path[I].second, 1035 diag::err_no_submodule_suggest) 1036 << Path[I].first << Module->getFullModuleName() << Best[0] 1037 << SourceRange(Path[0].second, Path[I-1].second) 1038 << FixItHint::CreateReplacement(SourceRange(Path[I].second), 1039 Best[0]); 1040 1041 Sub = Module->findSubmodule(Best[0]); 1042 } 1043 } 1044 1045 if (!Sub) { 1046 // No submodule by this name. Complain, and don't look for further 1047 // submodules. 1048 getDiagnostics().Report(Path[I].second, diag::err_no_submodule) 1049 << Path[I].first << Module->getFullModuleName() 1050 << SourceRange(Path[0].second, Path[I-1].second); 1051 break; 1052 } 1053 1054 Module = Sub; 1055 } 1056 } 1057 1058 // Make the named module visible, if it's not already part of the module 1059 // we are parsing. 1060 if (ModuleName != getLangOpts().CurrentModule) { 1061 if (!Module->IsFromModuleFile) { 1062 // We have an umbrella header or directory that doesn't actually include 1063 // all of the headers within the directory it covers. Complain about 1064 // this missing submodule and recover by forgetting that we ever saw 1065 // this submodule. 1066 // FIXME: Should we detect this at module load time? It seems fairly 1067 // expensive (and rare). 1068 getDiagnostics().Report(ImportLoc, diag::warn_missing_submodule) 1069 << Module->getFullModuleName() 1070 << SourceRange(Path.front().second, Path.back().second); 1071 1072 return 0; 1073 } 1074 1075 // Check whether this module is available. 1076 StringRef Feature; 1077 if (!Module->isAvailable(getLangOpts(), getTarget(), Feature)) { 1078 getDiagnostics().Report(ImportLoc, diag::err_module_unavailable) 1079 << Module->getFullModuleName() 1080 << Feature 1081 << SourceRange(Path.front().second, Path.back().second); 1082 LastModuleImportLoc = ImportLoc; 1083 LastModuleImportResult = 0; 1084 return 0; 1085 } 1086 1087 ModuleManager->makeModuleVisible(Module, Visibility); 1088 } 1089 1090 // If this module import was due to an inclusion directive, create an 1091 // implicit import declaration to capture it in the AST. 1092 if (IsInclusionDirective && hasASTContext()) { 1093 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 1094 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 1095 ImportLoc, Module, 1096 Path.back().second); 1097 TU->addDecl(ImportD); 1098 if (Consumer) 1099 Consumer->HandleImplicitImportDecl(ImportD); 1100 } 1101 1102 LastModuleImportLoc = ImportLoc; 1103 LastModuleImportResult = Module; 1104 return Module; 1105 } 1106