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