ASTUnit.cpp revision 7ae2faafd30524ef5f863bb3b8701977888839bb
1//===--- ASTUnit.cpp - ASTUnit utility ------------------------------------===// 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// ASTUnit Implementation. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/Frontend/ASTUnit.h" 15#include "clang/Frontend/PCHWriter.h" 16#include "clang/AST/ASTContext.h" 17#include "clang/AST/ASTConsumer.h" 18#include "clang/AST/DeclVisitor.h" 19#include "clang/AST/StmtVisitor.h" 20#include "clang/Driver/Compilation.h" 21#include "clang/Driver/Driver.h" 22#include "clang/Driver/Job.h" 23#include "clang/Driver/Tool.h" 24#include "clang/Frontend/CompilerInstance.h" 25#include "clang/Frontend/FrontendActions.h" 26#include "clang/Frontend/FrontendDiagnostic.h" 27#include "clang/Frontend/FrontendOptions.h" 28#include "clang/Frontend/PCHReader.h" 29#include "clang/Lex/HeaderSearch.h" 30#include "clang/Lex/Preprocessor.h" 31#include "clang/Basic/TargetOptions.h" 32#include "clang/Basic/TargetInfo.h" 33#include "clang/Basic/Diagnostic.h" 34#include "llvm/Support/MemoryBuffer.h" 35#include "llvm/System/Host.h" 36#include "llvm/System/Path.h" 37#include "llvm/Support/raw_ostream.h" 38#include "llvm/Support/Timer.h" 39#include <cstdlib> 40#include <cstdio> 41#include <sys/stat.h> 42using namespace clang; 43 44/// \brief After failing to build a precompiled preamble (due to 45/// errors in the source that occurs in the preamble), the number of 46/// reparses during which we'll skip even trying to precompile the 47/// preamble. 48const unsigned DefaultPreambleRebuildInterval = 5; 49 50ASTUnit::ASTUnit(bool _MainFileIsAST) 51 : CaptureDiagnostics(false), MainFileIsAST(_MainFileIsAST), 52 CompleteTranslationUnit(true), ConcurrencyCheckValue(CheckUnlocked), 53 PreambleRebuildCounter(0), SavedMainFileBuffer(0) { 54} 55 56ASTUnit::~ASTUnit() { 57 ConcurrencyCheckValue = CheckLocked; 58 CleanTemporaryFiles(); 59 if (!PreambleFile.empty()) 60 llvm::sys::Path(PreambleFile).eraseFromDisk(); 61 62 // Free the buffers associated with remapped files. We are required to 63 // perform this operation here because we explicitly request that the 64 // compiler instance *not* free these buffers for each invocation of the 65 // parser. 66 if (Invocation.get()) { 67 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts(); 68 for (PreprocessorOptions::remapped_file_buffer_iterator 69 FB = PPOpts.remapped_file_buffer_begin(), 70 FBEnd = PPOpts.remapped_file_buffer_end(); 71 FB != FBEnd; 72 ++FB) 73 delete FB->second; 74 } 75 76 delete SavedMainFileBuffer; 77 78 for (unsigned I = 0, N = Timers.size(); I != N; ++I) 79 delete Timers[I]; 80} 81 82void ASTUnit::CleanTemporaryFiles() { 83 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I) 84 TemporaryFiles[I].eraseFromDisk(); 85 TemporaryFiles.clear(); 86} 87 88namespace { 89 90/// \brief Gathers information from PCHReader that will be used to initialize 91/// a Preprocessor. 92class PCHInfoCollector : public PCHReaderListener { 93 LangOptions &LangOpt; 94 HeaderSearch &HSI; 95 std::string &TargetTriple; 96 std::string &Predefines; 97 unsigned &Counter; 98 99 unsigned NumHeaderInfos; 100 101public: 102 PCHInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI, 103 std::string &TargetTriple, std::string &Predefines, 104 unsigned &Counter) 105 : LangOpt(LangOpt), HSI(HSI), TargetTriple(TargetTriple), 106 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0) {} 107 108 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) { 109 LangOpt = LangOpts; 110 return false; 111 } 112 113 virtual bool ReadTargetTriple(llvm::StringRef Triple) { 114 TargetTriple = Triple; 115 return false; 116 } 117 118 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers, 119 llvm::StringRef OriginalFileName, 120 std::string &SuggestedPredefines) { 121 Predefines = Buffers[0].Data; 122 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) { 123 Predefines += Buffers[I].Data; 124 } 125 return false; 126 } 127 128 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) { 129 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++); 130 } 131 132 virtual void ReadCounter(unsigned Value) { 133 Counter = Value; 134 } 135}; 136 137class StoredDiagnosticClient : public DiagnosticClient { 138 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags; 139 140public: 141 explicit StoredDiagnosticClient( 142 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags) 143 : StoredDiags(StoredDiags) { } 144 145 virtual void HandleDiagnostic(Diagnostic::Level Level, 146 const DiagnosticInfo &Info); 147}; 148 149/// \brief RAII object that optionally captures diagnostics, if 150/// there is no diagnostic client to capture them already. 151class CaptureDroppedDiagnostics { 152 Diagnostic &Diags; 153 StoredDiagnosticClient Client; 154 DiagnosticClient *PreviousClient; 155 156public: 157 CaptureDroppedDiagnostics(bool RequestCapture, Diagnostic &Diags, 158 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags) 159 : Diags(Diags), Client(StoredDiags), PreviousClient(Diags.getClient()) 160 { 161 if (RequestCapture || Diags.getClient() == 0) 162 Diags.setClient(&Client); 163 } 164 165 ~CaptureDroppedDiagnostics() { 166 Diags.setClient(PreviousClient); 167 } 168}; 169 170} // anonymous namespace 171 172void StoredDiagnosticClient::HandleDiagnostic(Diagnostic::Level Level, 173 const DiagnosticInfo &Info) { 174 StoredDiags.push_back(StoredDiagnostic(Level, Info)); 175} 176 177const std::string &ASTUnit::getOriginalSourceFileName() { 178 return OriginalSourceFile; 179} 180 181const std::string &ASTUnit::getPCHFileName() { 182 assert(isMainFileAST() && "Not an ASTUnit from a PCH file!"); 183 return static_cast<PCHReader *>(Ctx->getExternalSource())->getFileName(); 184} 185 186ASTUnit *ASTUnit::LoadFromPCHFile(const std::string &Filename, 187 llvm::IntrusiveRefCntPtr<Diagnostic> Diags, 188 bool OnlyLocalDecls, 189 RemappedFile *RemappedFiles, 190 unsigned NumRemappedFiles, 191 bool CaptureDiagnostics) { 192 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true)); 193 194 if (!Diags.getPtr()) { 195 // No diagnostics engine was provided, so create our own diagnostics object 196 // with the default options. 197 DiagnosticOptions DiagOpts; 198 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0); 199 } 200 201 AST->CaptureDiagnostics = CaptureDiagnostics; 202 AST->OnlyLocalDecls = OnlyLocalDecls; 203 AST->Diagnostics = Diags; 204 AST->FileMgr.reset(new FileManager); 205 AST->SourceMgr.reset(new SourceManager(AST->getDiagnostics())); 206 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager())); 207 208 // If requested, capture diagnostics in the ASTUnit. 209 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, AST->getDiagnostics(), 210 AST->StoredDiagnostics); 211 212 for (unsigned I = 0; I != NumRemappedFiles; ++I) { 213 // Create the file entry for the file that we're mapping from. 214 const FileEntry *FromFile 215 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first, 216 RemappedFiles[I].second->getBufferSize(), 217 0); 218 if (!FromFile) { 219 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file) 220 << RemappedFiles[I].first; 221 delete RemappedFiles[I].second; 222 continue; 223 } 224 225 // Override the contents of the "from" file with the contents of 226 // the "to" file. 227 AST->getSourceManager().overrideFileContents(FromFile, 228 RemappedFiles[I].second); 229 } 230 231 // Gather Info for preprocessor construction later on. 232 233 LangOptions LangInfo; 234 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get(); 235 std::string TargetTriple; 236 std::string Predefines; 237 unsigned Counter; 238 239 llvm::OwningPtr<PCHReader> Reader; 240 241 Reader.reset(new PCHReader(AST->getSourceManager(), AST->getFileManager(), 242 AST->getDiagnostics())); 243 Reader->setListener(new PCHInfoCollector(LangInfo, HeaderInfo, TargetTriple, 244 Predefines, Counter)); 245 246 switch (Reader->ReadPCH(Filename)) { 247 case PCHReader::Success: 248 break; 249 250 case PCHReader::Failure: 251 case PCHReader::IgnorePCH: 252 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch); 253 return NULL; 254 } 255 256 AST->OriginalSourceFile = Reader->getOriginalSourceFile(); 257 258 // PCH loaded successfully. Now create the preprocessor. 259 260 // Get information about the target being compiled for. 261 // 262 // FIXME: This is broken, we should store the TargetOptions in the PCH. 263 TargetOptions TargetOpts; 264 TargetOpts.ABI = ""; 265 TargetOpts.CXXABI = "itanium"; 266 TargetOpts.CPU = ""; 267 TargetOpts.Features.clear(); 268 TargetOpts.Triple = TargetTriple; 269 AST->Target.reset(TargetInfo::CreateTargetInfo(AST->getDiagnostics(), 270 TargetOpts)); 271 AST->PP.reset(new Preprocessor(AST->getDiagnostics(), LangInfo, 272 *AST->Target.get(), 273 AST->getSourceManager(), HeaderInfo)); 274 Preprocessor &PP = *AST->PP.get(); 275 276 PP.setPredefines(Reader->getSuggestedPredefines()); 277 PP.setCounterValue(Counter); 278 Reader->setPreprocessor(PP); 279 280 // Create and initialize the ASTContext. 281 282 AST->Ctx.reset(new ASTContext(LangInfo, 283 AST->getSourceManager(), 284 *AST->Target.get(), 285 PP.getIdentifierTable(), 286 PP.getSelectorTable(), 287 PP.getBuiltinInfo(), 288 /* size_reserve = */0)); 289 ASTContext &Context = *AST->Ctx.get(); 290 291 Reader->InitializeContext(Context); 292 293 // Attach the PCH reader to the AST context as an external AST 294 // source, so that declarations will be deserialized from the 295 // PCH file as needed. 296 PCHReader *ReaderPtr = Reader.get(); 297 llvm::OwningPtr<ExternalASTSource> Source(Reader.take()); 298 Context.setExternalSource(Source); 299 300 // Create an AST consumer, even though it isn't used. 301 AST->Consumer.reset(new ASTConsumer); 302 303 // Create a semantic analysis object and tell the PCH reader about it. 304 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer)); 305 AST->TheSema->Initialize(); 306 ReaderPtr->InitializeSema(*AST->TheSema); 307 308 return AST.take(); 309} 310 311namespace { 312 313class TopLevelDeclTrackerConsumer : public ASTConsumer { 314 ASTUnit &Unit; 315 316public: 317 TopLevelDeclTrackerConsumer(ASTUnit &_Unit) : Unit(_Unit) {} 318 319 void HandleTopLevelDecl(DeclGroupRef D) { 320 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) { 321 Decl *D = *it; 322 // FIXME: Currently ObjC method declarations are incorrectly being 323 // reported as top-level declarations, even though their DeclContext 324 // is the containing ObjC @interface/@implementation. This is a 325 // fundamental problem in the parser right now. 326 if (isa<ObjCMethodDecl>(D)) 327 continue; 328 Unit.addTopLevelDecl(D); 329 } 330 } 331 332 // We're not interested in "interesting" decls. 333 void HandleInterestingDecl(DeclGroupRef) {} 334}; 335 336class TopLevelDeclTrackerAction : public ASTFrontendAction { 337public: 338 ASTUnit &Unit; 339 340 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI, 341 llvm::StringRef InFile) { 342 return new TopLevelDeclTrackerConsumer(Unit); 343 } 344 345public: 346 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {} 347 348 virtual bool hasCodeCompletionSupport() const { return false; } 349 virtual bool usesCompleteTranslationUnit() { 350 return Unit.isCompleteTranslationUnit(); 351 } 352}; 353 354class PrecompilePreambleConsumer : public PCHGenerator { 355 ASTUnit &Unit; 356 std::vector<Decl *> TopLevelDecls; 357 358public: 359 PrecompilePreambleConsumer(ASTUnit &Unit, 360 const Preprocessor &PP, bool Chaining, 361 const char *isysroot, llvm::raw_ostream *Out) 362 : PCHGenerator(PP, Chaining, isysroot, Out), Unit(Unit) { } 363 364 virtual void HandleTopLevelDecl(DeclGroupRef D) { 365 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) { 366 Decl *D = *it; 367 // FIXME: Currently ObjC method declarations are incorrectly being 368 // reported as top-level declarations, even though their DeclContext 369 // is the containing ObjC @interface/@implementation. This is a 370 // fundamental problem in the parser right now. 371 if (isa<ObjCMethodDecl>(D)) 372 continue; 373 TopLevelDecls.push_back(D); 374 } 375 } 376 377 virtual void HandleTranslationUnit(ASTContext &Ctx) { 378 PCHGenerator::HandleTranslationUnit(Ctx); 379 if (!Unit.getDiagnostics().hasErrorOccurred()) { 380 // Translate the top-level declarations we captured during 381 // parsing into declaration IDs in the precompiled 382 // preamble. This will allow us to deserialize those top-level 383 // declarations when requested. 384 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I) 385 Unit.addTopLevelDeclFromPreamble( 386 getWriter().getDeclID(TopLevelDecls[I])); 387 } 388 } 389}; 390 391class PrecompilePreambleAction : public ASTFrontendAction { 392 ASTUnit &Unit; 393 394public: 395 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {} 396 397 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI, 398 llvm::StringRef InFile) { 399 std::string Sysroot; 400 llvm::raw_ostream *OS = 0; 401 bool Chaining; 402 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot, 403 OS, Chaining)) 404 return 0; 405 406 const char *isysroot = CI.getFrontendOpts().RelocatablePCH ? 407 Sysroot.c_str() : 0; 408 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Chaining, 409 isysroot, OS); 410 } 411 412 virtual bool hasCodeCompletionSupport() const { return false; } 413 virtual bool hasASTFileSupport() const { return false; } 414 virtual bool usesCompleteTranslationUnit() { return false; } 415}; 416 417} 418 419/// Parse the source file into a translation unit using the given compiler 420/// invocation, replacing the current translation unit. 421/// 422/// \returns True if a failure occurred that causes the ASTUnit not to 423/// contain any translation-unit information, false otherwise. 424bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) { 425 delete SavedMainFileBuffer; 426 SavedMainFileBuffer = 0; 427 428 if (!Invocation.get()) 429 return true; 430 431 // Create the compiler instance to use for building the AST. 432 CompilerInstance Clang; 433 Clang.setInvocation(Invocation.take()); 434 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second; 435 436 // Set up diagnostics, capturing any diagnostics that would 437 // otherwise be dropped. 438 Clang.setDiagnostics(&getDiagnostics()); 439 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, 440 getDiagnostics(), 441 StoredDiagnostics); 442 Clang.setDiagnosticClient(getDiagnostics().getClient()); 443 444 // Create the target instance. 445 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(), 446 Clang.getTargetOpts())); 447 if (!Clang.hasTarget()) { 448 Clang.takeDiagnosticClient(); 449 return true; 450 } 451 452 // Inform the target of the language options. 453 // 454 // FIXME: We shouldn't need to do this, the target should be immutable once 455 // created. This complexity should be lifted elsewhere. 456 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts()); 457 458 assert(Clang.getFrontendOpts().Inputs.size() == 1 && 459 "Invocation must have exactly one source file!"); 460 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST && 461 "FIXME: AST inputs not yet supported here!"); 462 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR && 463 "IR inputs not support here!"); 464 465 // Configure the various subsystems. 466 // FIXME: Should we retain the previous file manager? 467 FileMgr.reset(new FileManager); 468 SourceMgr.reset(new SourceManager(getDiagnostics())); 469 TheSema.reset(); 470 Ctx.reset(); 471 PP.reset(); 472 473 // Clear out old caches and data. 474 TopLevelDecls.clear(); 475 CleanTemporaryFiles(); 476 PreprocessedEntitiesByFile.clear(); 477 478 if (!OverrideMainBuffer) 479 StoredDiagnostics.clear(); 480 481 // Create a file manager object to provide access to and cache the filesystem. 482 Clang.setFileManager(&getFileManager()); 483 484 // Create the source manager. 485 Clang.setSourceManager(&getSourceManager()); 486 487 // If the main file has been overridden due to the use of a preamble, 488 // make that override happen and introduce the preamble. 489 PreprocessorOptions &PreprocessorOpts = Clang.getPreprocessorOpts(); 490 std::string PriorImplicitPCHInclude; 491 if (OverrideMainBuffer) { 492 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer); 493 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size(); 494 PreprocessorOpts.PrecompiledPreambleBytes.second 495 = PreambleEndsAtStartOfLine; 496 PriorImplicitPCHInclude = PreprocessorOpts.ImplicitPCHInclude; 497 PreprocessorOpts.ImplicitPCHInclude = PreambleFile; 498 PreprocessorOpts.DisablePCHValidation = true; 499 500 // Keep track of the override buffer; 501 SavedMainFileBuffer = OverrideMainBuffer; 502 503 // The stored diagnostic has the old source manager in it; update 504 // the locations to refer into the new source manager. Since we've 505 // been careful to make sure that the source manager's state 506 // before and after are identical, so that we can reuse the source 507 // location itself. 508 for (unsigned I = 0, N = StoredDiagnostics.size(); I != N; ++I) { 509 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), 510 getSourceManager()); 511 StoredDiagnostics[I].setLocation(Loc); 512 } 513 } 514 515 llvm::OwningPtr<TopLevelDeclTrackerAction> Act; 516 Act.reset(new TopLevelDeclTrackerAction(*this)); 517 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second, 518 Clang.getFrontendOpts().Inputs[0].first)) 519 goto error; 520 521 Act->Execute(); 522 523 // Steal the created target, context, and preprocessor, and take back the 524 // source and file managers. 525 TheSema.reset(Clang.takeSema()); 526 Consumer.reset(Clang.takeASTConsumer()); 527 Ctx.reset(Clang.takeASTContext()); 528 PP.reset(Clang.takePreprocessor()); 529 Clang.takeSourceManager(); 530 Clang.takeFileManager(); 531 Target.reset(Clang.takeTarget()); 532 533 Act->EndSourceFile(); 534 535 // Remove the overridden buffer we used for the preamble. 536 if (OverrideMainBuffer) { 537 PreprocessorOpts.eraseRemappedFile( 538 PreprocessorOpts.remapped_file_buffer_end() - 1); 539 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude; 540 } 541 542 Clang.takeDiagnosticClient(); 543 544 Invocation.reset(Clang.takeInvocation()); 545 return false; 546 547error: 548 // Remove the overridden buffer we used for the preamble. 549 if (OverrideMainBuffer) { 550 PreprocessorOpts.eraseRemappedFile( 551 PreprocessorOpts.remapped_file_buffer_end() - 1); 552 PreprocessorOpts.DisablePCHValidation = true; 553 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude; 554 } 555 556 Clang.takeSourceManager(); 557 Clang.takeFileManager(); 558 Clang.takeDiagnosticClient(); 559 Invocation.reset(Clang.takeInvocation()); 560 return true; 561} 562 563/// \brief Simple function to retrieve a path for a preamble precompiled header. 564static std::string GetPreamblePCHPath() { 565 // FIXME: This is lame; sys::Path should provide this function (in particular, 566 // it should know how to find the temporary files dir). 567 // FIXME: This is really lame. I copied this code from the Driver! 568 std::string Error; 569 const char *TmpDir = ::getenv("TMPDIR"); 570 if (!TmpDir) 571 TmpDir = ::getenv("TEMP"); 572 if (!TmpDir) 573 TmpDir = ::getenv("TMP"); 574 if (!TmpDir) 575 TmpDir = "/tmp"; 576 llvm::sys::Path P(TmpDir); 577 P.appendComponent("preamble"); 578 P.appendSuffix("pch"); 579 if (P.createTemporaryFileOnDisk()) 580 return std::string(); 581 582 fprintf(stderr, "Preamble file: %s\n", P.str().c_str()); 583 return P.str(); 584} 585 586/// \brief Compute the preamble for the main file, providing the source buffer 587/// that corresponds to the main file along with a pair (bytes, start-of-line) 588/// that describes the preamble. 589std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > 590ASTUnit::ComputePreamble(CompilerInvocation &Invocation, 591 unsigned MaxLines, bool &CreatedBuffer) { 592 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts(); 593 PreprocessorOptions &PreprocessorOpts 594 = Invocation.getPreprocessorOpts(); 595 CreatedBuffer = false; 596 597 // Try to determine if the main file has been remapped, either from the 598 // command line (to another file) or directly through the compiler invocation 599 // (to a memory buffer). 600 llvm::MemoryBuffer *Buffer = 0; 601 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second); 602 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) { 603 // Check whether there is a file-file remapping of the main file 604 for (PreprocessorOptions::remapped_file_iterator 605 M = PreprocessorOpts.remapped_file_begin(), 606 E = PreprocessorOpts.remapped_file_end(); 607 M != E; 608 ++M) { 609 llvm::sys::PathWithStatus MPath(M->first); 610 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) { 611 if (MainFileStatus->uniqueID == MStatus->uniqueID) { 612 // We found a remapping. Try to load the resulting, remapped source. 613 if (CreatedBuffer) { 614 delete Buffer; 615 CreatedBuffer = false; 616 } 617 618 Buffer = llvm::MemoryBuffer::getFile(M->second); 619 if (!Buffer) 620 return std::make_pair((llvm::MemoryBuffer*)0, 621 std::make_pair(0, true)); 622 CreatedBuffer = true; 623 624 // Remove this remapping. We've captured the buffer already. 625 M = PreprocessorOpts.eraseRemappedFile(M); 626 E = PreprocessorOpts.remapped_file_end(); 627 } 628 } 629 } 630 631 // Check whether there is a file-buffer remapping. It supercedes the 632 // file-file remapping. 633 for (PreprocessorOptions::remapped_file_buffer_iterator 634 M = PreprocessorOpts.remapped_file_buffer_begin(), 635 E = PreprocessorOpts.remapped_file_buffer_end(); 636 M != E; 637 ++M) { 638 llvm::sys::PathWithStatus MPath(M->first); 639 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) { 640 if (MainFileStatus->uniqueID == MStatus->uniqueID) { 641 // We found a remapping. 642 if (CreatedBuffer) { 643 delete Buffer; 644 CreatedBuffer = false; 645 } 646 647 Buffer = const_cast<llvm::MemoryBuffer *>(M->second); 648 649 // Remove this remapping. We've captured the buffer already. 650 M = PreprocessorOpts.eraseRemappedFile(M); 651 E = PreprocessorOpts.remapped_file_buffer_end(); 652 } 653 } 654 } 655 } 656 657 // If the main source file was not remapped, load it now. 658 if (!Buffer) { 659 Buffer = llvm::MemoryBuffer::getFile(FrontendOpts.Inputs[0].second); 660 if (!Buffer) 661 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true)); 662 663 CreatedBuffer = true; 664 } 665 666 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer, MaxLines)); 667} 668 669static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old, 670 bool DeleteOld, 671 unsigned NewSize, 672 llvm::StringRef NewName) { 673 llvm::MemoryBuffer *Result 674 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName); 675 memcpy(const_cast<char*>(Result->getBufferStart()), 676 Old->getBufferStart(), Old->getBufferSize()); 677 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(), 678 ' ', NewSize - Old->getBufferSize() - 1); 679 const_cast<char*>(Result->getBufferEnd())[-1] = '\n'; 680 681 if (DeleteOld) 682 delete Old; 683 684 return Result; 685} 686 687/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing 688/// the source file. 689/// 690/// This routine will compute the preamble of the main source file. If a 691/// non-trivial preamble is found, it will precompile that preamble into a 692/// precompiled header so that the precompiled preamble can be used to reduce 693/// reparsing time. If a precompiled preamble has already been constructed, 694/// this routine will determine if it is still valid and, if so, avoid 695/// rebuilding the precompiled preamble. 696/// 697/// \param AllowRebuild When true (the default), this routine is 698/// allowed to rebuild the precompiled preamble if it is found to be 699/// out-of-date. 700/// 701/// \param MaxLines When non-zero, the maximum number of lines that 702/// can occur within the preamble. 703/// 704/// \returns If the precompiled preamble can be used, returns a newly-allocated 705/// buffer that should be used in place of the main file when doing so. 706/// Otherwise, returns a NULL pointer. 707llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble( 708 bool AllowRebuild, 709 unsigned MaxLines) { 710 CompilerInvocation PreambleInvocation(*Invocation); 711 FrontendOptions &FrontendOpts = PreambleInvocation.getFrontendOpts(); 712 PreprocessorOptions &PreprocessorOpts 713 = PreambleInvocation.getPreprocessorOpts(); 714 715 bool CreatedPreambleBuffer = false; 716 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble 717 = ComputePreamble(PreambleInvocation, MaxLines, CreatedPreambleBuffer); 718 719 if (!NewPreamble.second.first) { 720 // We couldn't find a preamble in the main source. Clear out the current 721 // preamble, if we have one. It's obviously no good any more. 722 Preamble.clear(); 723 if (!PreambleFile.empty()) { 724 llvm::sys::Path(PreambleFile).eraseFromDisk(); 725 PreambleFile.clear(); 726 } 727 if (CreatedPreambleBuffer) 728 delete NewPreamble.first; 729 730 // The next time we actually see a preamble, precompile it. 731 PreambleRebuildCounter = 1; 732 return 0; 733 } 734 735 if (!Preamble.empty()) { 736 // We've previously computed a preamble. Check whether we have the same 737 // preamble now that we did before, and that there's enough space in 738 // the main-file buffer within the precompiled preamble to fit the 739 // new main file. 740 if (Preamble.size() == NewPreamble.second.first && 741 PreambleEndsAtStartOfLine == NewPreamble.second.second && 742 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 && 743 memcmp(&Preamble[0], NewPreamble.first->getBufferStart(), 744 NewPreamble.second.first) == 0) { 745 // The preamble has not changed. We may be able to re-use the precompiled 746 // preamble. 747 748 // Check that none of the files used by the preamble have changed. 749 bool AnyFileChanged = false; 750 751 // First, make a record of those files that have been overridden via 752 // remapping or unsaved_files. 753 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles; 754 for (PreprocessorOptions::remapped_file_iterator 755 R = PreprocessorOpts.remapped_file_begin(), 756 REnd = PreprocessorOpts.remapped_file_end(); 757 !AnyFileChanged && R != REnd; 758 ++R) { 759 struct stat StatBuf; 760 if (stat(R->second.c_str(), &StatBuf)) { 761 // If we can't stat the file we're remapping to, assume that something 762 // horrible happened. 763 AnyFileChanged = true; 764 break; 765 } 766 767 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size, 768 StatBuf.st_mtime); 769 } 770 for (PreprocessorOptions::remapped_file_buffer_iterator 771 R = PreprocessorOpts.remapped_file_buffer_begin(), 772 REnd = PreprocessorOpts.remapped_file_buffer_end(); 773 !AnyFileChanged && R != REnd; 774 ++R) { 775 // FIXME: Should we actually compare the contents of file->buffer 776 // remappings? 777 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(), 778 0); 779 } 780 781 // Check whether anything has changed. 782 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator 783 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end(); 784 !AnyFileChanged && F != FEnd; 785 ++F) { 786 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden 787 = OverriddenFiles.find(F->first()); 788 if (Overridden != OverriddenFiles.end()) { 789 // This file was remapped; check whether the newly-mapped file 790 // matches up with the previous mapping. 791 if (Overridden->second != F->second) 792 AnyFileChanged = true; 793 continue; 794 } 795 796 // The file was not remapped; check whether it has changed on disk. 797 struct stat StatBuf; 798 if (stat(F->first(), &StatBuf)) { 799 // If we can't stat the file, assume that something horrible happened. 800 AnyFileChanged = true; 801 } else if (StatBuf.st_size != F->second.first || 802 StatBuf.st_mtime != F->second.second) 803 AnyFileChanged = true; 804 } 805 806 if (!AnyFileChanged) { 807 // Okay! We can re-use the precompiled preamble. 808 809 // Set the state of the diagnostic object to mimic its state 810 // after parsing the preamble. 811 getDiagnostics().Reset(); 812 getDiagnostics().setNumWarnings(NumWarningsInPreamble); 813 if (StoredDiagnostics.size() > NumStoredDiagnosticsInPreamble) 814 StoredDiagnostics.erase( 815 StoredDiagnostics.begin() + NumStoredDiagnosticsInPreamble, 816 StoredDiagnostics.end()); 817 818 // Create a version of the main file buffer that is padded to 819 // buffer size we reserved when creating the preamble. 820 return CreatePaddedMainFileBuffer(NewPreamble.first, 821 CreatedPreambleBuffer, 822 PreambleReservedSize, 823 FrontendOpts.Inputs[0].second); 824 } 825 } 826 827 // If we aren't allowed to rebuild the precompiled preamble, just 828 // return now. 829 if (!AllowRebuild) 830 return 0; 831 832 // We can't reuse the previously-computed preamble. Build a new one. 833 Preamble.clear(); 834 llvm::sys::Path(PreambleFile).eraseFromDisk(); 835 PreambleRebuildCounter = 1; 836 } else if (!AllowRebuild) { 837 // We aren't allowed to rebuild the precompiled preamble; just 838 // return now. 839 return 0; 840 } 841 842 // If the preamble rebuild counter > 1, it's because we previously 843 // failed to build a preamble and we're not yet ready to try 844 // again. Decrement the counter and return a failure. 845 if (PreambleRebuildCounter > 1) { 846 --PreambleRebuildCounter; 847 return 0; 848 } 849 850 // We did not previously compute a preamble, or it can't be reused anyway. 851 llvm::Timer *PreambleTimer = 0; 852 if (TimerGroup.get()) { 853 PreambleTimer = new llvm::Timer("Precompiling preamble", *TimerGroup); 854 PreambleTimer->startTimer(); 855 Timers.push_back(PreambleTimer); 856 } 857 858 // Create a new buffer that stores the preamble. The buffer also contains 859 // extra space for the original contents of the file (which will be present 860 // when we actually parse the file) along with more room in case the file 861 // grows. 862 PreambleReservedSize = NewPreamble.first->getBufferSize(); 863 if (PreambleReservedSize < 4096) 864 PreambleReservedSize = 8191; 865 else 866 PreambleReservedSize *= 2; 867 868 // Save the preamble text for later; we'll need to compare against it for 869 // subsequent reparses. 870 Preamble.assign(NewPreamble.first->getBufferStart(), 871 NewPreamble.first->getBufferStart() 872 + NewPreamble.second.first); 873 PreambleEndsAtStartOfLine = NewPreamble.second.second; 874 875 llvm::MemoryBuffer *PreambleBuffer 876 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize, 877 FrontendOpts.Inputs[0].second); 878 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()), 879 NewPreamble.first->getBufferStart(), Preamble.size()); 880 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(), 881 ' ', PreambleReservedSize - Preamble.size() - 1); 882 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n'; 883 884 // Remap the main source file to the preamble buffer. 885 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second); 886 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer); 887 888 // Tell the compiler invocation to generate a temporary precompiled header. 889 FrontendOpts.ProgramAction = frontend::GeneratePCH; 890 // FIXME: Set ChainedPCH unconditionally, once it is ready. 891 if (::getenv("LIBCLANG_CHAINING")) 892 FrontendOpts.ChainedPCH = true; 893 // FIXME: Generate the precompiled header into memory? 894 FrontendOpts.OutputFile = GetPreamblePCHPath(); 895 896 // Create the compiler instance to use for building the precompiled preamble. 897 CompilerInstance Clang; 898 Clang.setInvocation(&PreambleInvocation); 899 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second; 900 901 // Set up diagnostics, capturing all of the diagnostics produced. 902 Clang.setDiagnostics(&getDiagnostics()); 903 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, 904 getDiagnostics(), 905 StoredDiagnostics); 906 Clang.setDiagnosticClient(getDiagnostics().getClient()); 907 908 // Create the target instance. 909 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(), 910 Clang.getTargetOpts())); 911 if (!Clang.hasTarget()) { 912 Clang.takeDiagnosticClient(); 913 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk(); 914 Preamble.clear(); 915 if (CreatedPreambleBuffer) 916 delete NewPreamble.first; 917 if (PreambleTimer) 918 PreambleTimer->stopTimer(); 919 PreambleRebuildCounter = DefaultPreambleRebuildInterval; 920 return 0; 921 } 922 923 // Inform the target of the language options. 924 // 925 // FIXME: We shouldn't need to do this, the target should be immutable once 926 // created. This complexity should be lifted elsewhere. 927 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts()); 928 929 assert(Clang.getFrontendOpts().Inputs.size() == 1 && 930 "Invocation must have exactly one source file!"); 931 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST && 932 "FIXME: AST inputs not yet supported here!"); 933 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR && 934 "IR inputs not support here!"); 935 936 // Clear out old caches and data. 937 StoredDiagnostics.clear(); 938 TopLevelDecls.clear(); 939 TopLevelDeclsInPreamble.clear(); 940 941 // Create a file manager object to provide access to and cache the filesystem. 942 Clang.setFileManager(new FileManager); 943 944 // Create the source manager. 945 Clang.setSourceManager(new SourceManager(getDiagnostics())); 946 947 llvm::OwningPtr<PrecompilePreambleAction> Act; 948 Act.reset(new PrecompilePreambleAction(*this)); 949 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second, 950 Clang.getFrontendOpts().Inputs[0].first)) { 951 Clang.takeDiagnosticClient(); 952 Clang.takeInvocation(); 953 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk(); 954 Preamble.clear(); 955 if (CreatedPreambleBuffer) 956 delete NewPreamble.first; 957 if (PreambleTimer) 958 PreambleTimer->stopTimer(); 959 PreambleRebuildCounter = DefaultPreambleRebuildInterval; 960 961 return 0; 962 } 963 964 Act->Execute(); 965 Act->EndSourceFile(); 966 Clang.takeDiagnosticClient(); 967 Clang.takeInvocation(); 968 969 if (Diagnostics->hasErrorOccurred()) { 970 // There were errors parsing the preamble, so no precompiled header was 971 // generated. Forget that we even tried. 972 // FIXME: Should we leave a note for ourselves to try again? 973 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk(); 974 Preamble.clear(); 975 if (CreatedPreambleBuffer) 976 delete NewPreamble.first; 977 if (PreambleTimer) 978 PreambleTimer->stopTimer(); 979 TopLevelDeclsInPreamble.clear(); 980 PreambleRebuildCounter = DefaultPreambleRebuildInterval; 981 return 0; 982 } 983 984 // Keep track of the preamble we precompiled. 985 PreambleFile = FrontendOpts.OutputFile; 986 NumStoredDiagnosticsInPreamble = StoredDiagnostics.size(); 987 NumWarningsInPreamble = getDiagnostics().getNumWarnings(); 988 989 // Keep track of all of the files that the source manager knows about, 990 // so we can verify whether they have changed or not. 991 FilesInPreamble.clear(); 992 SourceManager &SourceMgr = Clang.getSourceManager(); 993 const llvm::MemoryBuffer *MainFileBuffer 994 = SourceMgr.getBuffer(SourceMgr.getMainFileID()); 995 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(), 996 FEnd = SourceMgr.fileinfo_end(); 997 F != FEnd; 998 ++F) { 999 const FileEntry *File = F->second->Entry; 1000 if (!File || F->second->getRawBuffer() == MainFileBuffer) 1001 continue; 1002 1003 FilesInPreamble[File->getName()] 1004 = std::make_pair(F->second->getSize(), File->getModificationTime()); 1005 } 1006 1007 if (PreambleTimer) 1008 PreambleTimer->stopTimer(); 1009 1010 PreambleRebuildCounter = 1; 1011 return CreatePaddedMainFileBuffer(NewPreamble.first, 1012 CreatedPreambleBuffer, 1013 PreambleReservedSize, 1014 FrontendOpts.Inputs[0].second); 1015} 1016 1017void ASTUnit::RealizeTopLevelDeclsFromPreamble() { 1018 std::vector<Decl *> Resolved; 1019 Resolved.reserve(TopLevelDeclsInPreamble.size()); 1020 ExternalASTSource &Source = *getASTContext().getExternalSource(); 1021 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) { 1022 // Resolve the declaration ID to an actual declaration, possibly 1023 // deserializing the declaration in the process. 1024 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]); 1025 if (D) 1026 Resolved.push_back(D); 1027 } 1028 TopLevelDeclsInPreamble.clear(); 1029 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end()); 1030} 1031 1032unsigned ASTUnit::getMaxPCHLevel() const { 1033 if (!getOnlyLocalDecls()) 1034 return Decl::MaxPCHLevel; 1035 1036 unsigned Result = 0; 1037 if (isMainFileAST() || SavedMainFileBuffer) 1038 ++Result; 1039 return Result; 1040} 1041 1042ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI, 1043 llvm::IntrusiveRefCntPtr<Diagnostic> Diags, 1044 bool OnlyLocalDecls, 1045 bool CaptureDiagnostics, 1046 bool PrecompilePreamble, 1047 bool CompleteTranslationUnit) { 1048 if (!Diags.getPtr()) { 1049 // No diagnostics engine was provided, so create our own diagnostics object 1050 // with the default options. 1051 DiagnosticOptions DiagOpts; 1052 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0); 1053 } 1054 1055 // Create the AST unit. 1056 llvm::OwningPtr<ASTUnit> AST; 1057 AST.reset(new ASTUnit(false)); 1058 AST->Diagnostics = Diags; 1059 AST->CaptureDiagnostics = CaptureDiagnostics; 1060 AST->OnlyLocalDecls = OnlyLocalDecls; 1061 AST->CompleteTranslationUnit = CompleteTranslationUnit; 1062 AST->Invocation.reset(CI); 1063 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true; 1064 1065 if (getenv("LIBCLANG_TIMING")) 1066 AST->TimerGroup.reset( 1067 new llvm::TimerGroup(CI->getFrontendOpts().Inputs[0].second)); 1068 1069 1070 llvm::MemoryBuffer *OverrideMainBuffer = 0; 1071 // FIXME: When C++ PCH is ready, allow use of it for a precompiled preamble. 1072 if (PrecompilePreamble && !CI->getLangOpts().CPlusPlus) { 1073 AST->PreambleRebuildCounter = 1; 1074 OverrideMainBuffer = AST->getMainBufferWithPrecompiledPreamble(); 1075 } 1076 1077 llvm::Timer *ParsingTimer = 0; 1078 if (AST->TimerGroup.get()) { 1079 ParsingTimer = new llvm::Timer("Initial parse", *AST->TimerGroup); 1080 ParsingTimer->startTimer(); 1081 AST->Timers.push_back(ParsingTimer); 1082 } 1083 1084 bool Failed = AST->Parse(OverrideMainBuffer); 1085 if (ParsingTimer) 1086 ParsingTimer->stopTimer(); 1087 1088 return Failed? 0 : AST.take(); 1089} 1090 1091ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin, 1092 const char **ArgEnd, 1093 llvm::IntrusiveRefCntPtr<Diagnostic> Diags, 1094 llvm::StringRef ResourceFilesPath, 1095 bool OnlyLocalDecls, 1096 RemappedFile *RemappedFiles, 1097 unsigned NumRemappedFiles, 1098 bool CaptureDiagnostics, 1099 bool PrecompilePreamble, 1100 bool CompleteTranslationUnit) { 1101 if (!Diags.getPtr()) { 1102 // No diagnostics engine was provided, so create our own diagnostics object 1103 // with the default options. 1104 DiagnosticOptions DiagOpts; 1105 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0); 1106 } 1107 1108 llvm::SmallVector<const char *, 16> Args; 1109 Args.push_back("<clang>"); // FIXME: Remove dummy argument. 1110 Args.insert(Args.end(), ArgBegin, ArgEnd); 1111 1112 // FIXME: Find a cleaner way to force the driver into restricted modes. We 1113 // also want to force it to use clang. 1114 Args.push_back("-fsyntax-only"); 1115 1116 // FIXME: We shouldn't have to pass in the path info. 1117 driver::Driver TheDriver("clang", llvm::sys::getHostTriple(), 1118 "a.out", false, false, *Diags); 1119 1120 // Don't check that inputs exist, they have been remapped. 1121 TheDriver.setCheckInputsExist(false); 1122 1123 llvm::OwningPtr<driver::Compilation> C( 1124 TheDriver.BuildCompilation(Args.size(), Args.data())); 1125 1126 // We expect to get back exactly one command job, if we didn't something 1127 // failed. 1128 const driver::JobList &Jobs = C->getJobs(); 1129 if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) { 1130 llvm::SmallString<256> Msg; 1131 llvm::raw_svector_ostream OS(Msg); 1132 C->PrintJob(OS, C->getJobs(), "; ", true); 1133 Diags->Report(diag::err_fe_expected_compiler_job) << OS.str(); 1134 return 0; 1135 } 1136 1137 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin()); 1138 if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") { 1139 Diags->Report(diag::err_fe_expected_clang_command); 1140 return 0; 1141 } 1142 1143 const driver::ArgStringList &CCArgs = Cmd->getArguments(); 1144 llvm::OwningPtr<CompilerInvocation> CI(new CompilerInvocation); 1145 CompilerInvocation::CreateFromArgs(*CI, 1146 const_cast<const char **>(CCArgs.data()), 1147 const_cast<const char **>(CCArgs.data()) + 1148 CCArgs.size(), 1149 *Diags); 1150 1151 // Override any files that need remapping 1152 for (unsigned I = 0; I != NumRemappedFiles; ++I) 1153 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, 1154 RemappedFiles[I].second); 1155 1156 // Override the resources path. 1157 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath; 1158 1159 CI->getFrontendOpts().DisableFree = true; 1160 return LoadFromCompilerInvocation(CI.take(), Diags, OnlyLocalDecls, 1161 CaptureDiagnostics, PrecompilePreamble, 1162 CompleteTranslationUnit); 1163} 1164 1165bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) { 1166 if (!Invocation.get()) 1167 return true; 1168 1169 llvm::Timer *ReparsingTimer = 0; 1170 if (TimerGroup.get()) { 1171 ReparsingTimer = new llvm::Timer("Reparse", *TimerGroup); 1172 ReparsingTimer->startTimer(); 1173 Timers.push_back(ReparsingTimer); 1174 } 1175 1176 // Remap files. 1177 Invocation->getPreprocessorOpts().clearRemappedFiles(); 1178 for (unsigned I = 0; I != NumRemappedFiles; ++I) 1179 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, 1180 RemappedFiles[I].second); 1181 1182 // If we have a preamble file lying around, or if we might try to 1183 // build a precompiled preamble, do so now. 1184 llvm::MemoryBuffer *OverrideMainBuffer = 0; 1185 if (!PreambleFile.empty() || PreambleRebuildCounter > 0) 1186 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(); 1187 1188 // Clear out the diagnostics state. 1189 if (!OverrideMainBuffer) 1190 getDiagnostics().Reset(); 1191 1192 // Parse the sources 1193 bool Result = Parse(OverrideMainBuffer); 1194 if (ReparsingTimer) 1195 ReparsingTimer->stopTimer(); 1196 return Result; 1197} 1198 1199void ASTUnit::CodeComplete(llvm::StringRef File, unsigned Line, unsigned Column, 1200 RemappedFile *RemappedFiles, 1201 unsigned NumRemappedFiles, 1202 bool IncludeMacros, 1203 bool IncludeCodePatterns, 1204 CodeCompleteConsumer &Consumer, 1205 Diagnostic &Diag, LangOptions &LangOpts, 1206 SourceManager &SourceMgr, FileManager &FileMgr, 1207 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics) { 1208 if (!Invocation.get()) 1209 return; 1210 1211 llvm::Timer *CompletionTimer = 0; 1212 if (TimerGroup.get()) { 1213 llvm::SmallString<128> TimerName; 1214 llvm::raw_svector_ostream TimerNameOut(TimerName); 1215 TimerNameOut << "Code completion @ " << File << ":" << Line << ":" 1216 << Column; 1217 CompletionTimer = new llvm::Timer(TimerNameOut.str(), *TimerGroup); 1218 CompletionTimer->startTimer(); 1219 Timers.push_back(CompletionTimer); 1220 } 1221 1222 CompilerInvocation CCInvocation(*Invocation); 1223 FrontendOptions &FrontendOpts = CCInvocation.getFrontendOpts(); 1224 PreprocessorOptions &PreprocessorOpts = CCInvocation.getPreprocessorOpts(); 1225 1226 FrontendOpts.ShowMacrosInCodeCompletion = IncludeMacros; 1227 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns; 1228 FrontendOpts.CodeCompletionAt.FileName = File; 1229 FrontendOpts.CodeCompletionAt.Line = Line; 1230 FrontendOpts.CodeCompletionAt.Column = Column; 1231 1232 // Turn on spell-checking when performing code completion. It leads 1233 // to better results. 1234 unsigned SpellChecking = CCInvocation.getLangOpts().SpellChecking; 1235 CCInvocation.getLangOpts().SpellChecking = 1; 1236 1237 // Set the language options appropriately. 1238 LangOpts = CCInvocation.getLangOpts(); 1239 1240 CompilerInstance Clang; 1241 Clang.setInvocation(&CCInvocation); 1242 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second; 1243 1244 // Set up diagnostics, capturing any diagnostics produced. 1245 Clang.setDiagnostics(&Diag); 1246 CaptureDroppedDiagnostics Capture(true, 1247 Clang.getDiagnostics(), 1248 StoredDiagnostics); 1249 Clang.setDiagnosticClient(Diag.getClient()); 1250 1251 // Create the target instance. 1252 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(), 1253 Clang.getTargetOpts())); 1254 if (!Clang.hasTarget()) { 1255 Clang.takeDiagnosticClient(); 1256 Clang.takeInvocation(); 1257 } 1258 1259 // Inform the target of the language options. 1260 // 1261 // FIXME: We shouldn't need to do this, the target should be immutable once 1262 // created. This complexity should be lifted elsewhere. 1263 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts()); 1264 1265 assert(Clang.getFrontendOpts().Inputs.size() == 1 && 1266 "Invocation must have exactly one source file!"); 1267 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST && 1268 "FIXME: AST inputs not yet supported here!"); 1269 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR && 1270 "IR inputs not support here!"); 1271 1272 1273 // Use the source and file managers that we were given. 1274 Clang.setFileManager(&FileMgr); 1275 Clang.setSourceManager(&SourceMgr); 1276 1277 // Remap files. 1278 PreprocessorOpts.clearRemappedFiles(); 1279 PreprocessorOpts.RetainRemappedFileBuffers = true; 1280 for (unsigned I = 0; I != NumRemappedFiles; ++I) 1281 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, 1282 RemappedFiles[I].second); 1283 1284 // Use the code completion consumer we were given. 1285 Clang.setCodeCompletionConsumer(&Consumer); 1286 1287 // If we have a precompiled preamble, try to use it. We only allow 1288 // the use of the precompiled preamble if we're if the completion 1289 // point is within the main file, after the end of the precompiled 1290 // preamble. 1291 llvm::MemoryBuffer *OverrideMainBuffer = 0; 1292 if (!PreambleFile.empty()) { 1293 using llvm::sys::FileStatus; 1294 llvm::sys::PathWithStatus CompleteFilePath(File); 1295 llvm::sys::PathWithStatus MainPath(OriginalSourceFile); 1296 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus()) 1297 if (const FileStatus *MainStatus = MainPath.getFileStatus()) 1298 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID()) 1299 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(false, 1300 Line); 1301 } 1302 1303 // If the main file has been overridden due to the use of a preamble, 1304 // make that override happen and introduce the preamble. 1305 if (OverrideMainBuffer) { 1306 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer); 1307 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size(); 1308 PreprocessorOpts.PrecompiledPreambleBytes.second 1309 = PreambleEndsAtStartOfLine; 1310 PreprocessorOpts.ImplicitPCHInclude = PreambleFile; 1311 PreprocessorOpts.DisablePCHValidation = true; 1312 1313 // The stored diagnostics have the old source manager. Copy them 1314 // to our output set of stored diagnostics, updating the source 1315 // manager to the one we were given. 1316 for (unsigned I = 0, N = this->StoredDiagnostics.size(); I != N; ++I) { 1317 StoredDiagnostics.push_back(this->StoredDiagnostics[I]); 1318 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SourceMgr); 1319 StoredDiagnostics[I].setLocation(Loc); 1320 } 1321 } 1322 1323 llvm::OwningPtr<SyntaxOnlyAction> Act; 1324 Act.reset(new SyntaxOnlyAction); 1325 if (Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second, 1326 Clang.getFrontendOpts().Inputs[0].first)) { 1327 Act->Execute(); 1328 Act->EndSourceFile(); 1329 } 1330 1331 if (CompletionTimer) 1332 CompletionTimer->stopTimer(); 1333 1334 // Steal back our resources. 1335 delete OverrideMainBuffer; 1336 Clang.takeFileManager(); 1337 Clang.takeSourceManager(); 1338 Clang.takeInvocation(); 1339 Clang.takeDiagnosticClient(); 1340 Clang.takeCodeCompletionConsumer(); 1341 CCInvocation.getLangOpts().SpellChecking = SpellChecking; 1342} 1343 1344bool ASTUnit::Save(llvm::StringRef File) { 1345 if (getDiagnostics().hasErrorOccurred()) 1346 return true; 1347 1348 // FIXME: Can we somehow regenerate the stat cache here, or do we need to 1349 // unconditionally create a stat cache when we parse the file? 1350 std::string ErrorInfo; 1351 llvm::raw_fd_ostream Out(File.str().c_str(), ErrorInfo); 1352 if (!ErrorInfo.empty() || Out.has_error()) 1353 return true; 1354 1355 std::vector<unsigned char> Buffer; 1356 llvm::BitstreamWriter Stream(Buffer); 1357 PCHWriter Writer(Stream); 1358 Writer.WritePCH(getSema(), 0, 0); 1359 1360 // Write the generated bitstream to "Out". 1361 Out.write((char *)&Buffer.front(), Buffer.size()); 1362 Out.flush(); 1363 Out.close(); 1364 return Out.has_error(); 1365} 1366