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