Indexing.cpp revision 838eb7e8652e451d93494a4e583e4d11809bcb4a
1//===- CIndexHigh.cpp - Higher level API functions ------------------------===// 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 "IndexingContext.h" 11#include "CIndexDiagnostic.h" 12#include "CIndexer.h" 13#include "CXCursor.h" 14#include "CXSourceLocation.h" 15#include "CXString.h" 16#include "CXTranslationUnit.h" 17#include "clang/AST/ASTConsumer.h" 18#include "clang/AST/DeclVisitor.h" 19#include "clang/Frontend/ASTUnit.h" 20#include "clang/Frontend/CompilerInstance.h" 21#include "clang/Frontend/CompilerInvocation.h" 22#include "clang/Frontend/FrontendAction.h" 23#include "clang/Frontend/Utils.h" 24#include "clang/Lex/PPCallbacks.h" 25#include "clang/Lex/Preprocessor.h" 26#include "clang/Lex/PPConditionalDirectiveRecord.h" 27#include "clang/Lex/HeaderSearch.h" 28#include "clang/Sema/SemaConsumer.h" 29#include "llvm/Support/CrashRecoveryContext.h" 30#include "llvm/Support/MemoryBuffer.h" 31#include "llvm/Support/Mutex.h" 32#include "llvm/Support/MutexGuard.h" 33 34using namespace clang; 35using namespace cxstring; 36using namespace cxtu; 37using namespace cxindex; 38 39static void indexDiagnostics(CXTranslationUnit TU, IndexingContext &IdxCtx); 40 41namespace { 42 43//===----------------------------------------------------------------------===// 44// Skip Parsed Bodies 45//===----------------------------------------------------------------------===// 46 47#ifdef LLVM_ON_WIN32 48 49// FIXME: On windows it is disabled since current implementation depends on 50// file inodes. 51 52class SessionSkipBodyData { }; 53 54class TUSkipBodyControl { 55public: 56 TUSkipBodyControl(SessionSkipBodyData &sessionData, 57 PPConditionalDirectiveRecord &ppRec) { } 58 bool isParsed(SourceLocation Loc, FileID FID, const FileEntry *FE) { 59 return false; 60 } 61 void finished() { } 62}; 63 64#else 65 66/// \brief A "region" in source code identified by the file/offset of the 67/// preprocessor conditional directive that it belongs to. 68/// Multiple, non-consecutive ranges can be parts of the same region. 69/// 70/// As an example of different regions separated by preprocessor directives: 71/// 72/// \code 73/// #1 74/// #ifdef BLAH 75/// #2 76/// #ifdef CAKE 77/// #3 78/// #endif 79/// #2 80/// #endif 81/// #1 82/// \endcode 83/// 84/// There are 3 regions, with non-consecutive parts: 85/// #1 is identified as the beginning of the file 86/// #2 is identified as the location of "#ifdef BLAH" 87/// #3 is identified as the location of "#ifdef CAKE" 88/// 89class PPRegion { 90 ino_t ino; 91 time_t ModTime; 92 dev_t dev; 93 unsigned Offset; 94public: 95 PPRegion() : ino(), ModTime(), dev(), Offset() {} 96 PPRegion(dev_t dev, ino_t ino, unsigned offset, time_t modTime) 97 : ino(ino), ModTime(modTime), dev(dev), Offset(offset) {} 98 99 ino_t getIno() const { return ino; } 100 dev_t getDev() const { return dev; } 101 unsigned getOffset() const { return Offset; } 102 time_t getModTime() const { return ModTime; } 103 104 bool isInvalid() const { return *this == PPRegion(); } 105 106 friend bool operator==(const PPRegion &lhs, const PPRegion &rhs) { 107 return lhs.dev == rhs.dev && lhs.ino == rhs.ino && 108 lhs.Offset == rhs.Offset && lhs.ModTime == rhs.ModTime; 109 } 110}; 111 112typedef llvm::DenseSet<PPRegion> PPRegionSetTy; 113 114} // end anonymous namespace 115 116namespace llvm { 117 template <> struct isPodLike<PPRegion> { 118 static const bool value = true; 119 }; 120 121 template <> 122 struct DenseMapInfo<PPRegion> { 123 static inline PPRegion getEmptyKey() { 124 return PPRegion(0, 0, unsigned(-1), 0); 125 } 126 static inline PPRegion getTombstoneKey() { 127 return PPRegion(0, 0, unsigned(-2), 0); 128 } 129 130 static unsigned getHashValue(const PPRegion &S) { 131 llvm::FoldingSetNodeID ID; 132 ID.AddInteger(S.getIno()); 133 ID.AddInteger(S.getDev()); 134 ID.AddInteger(S.getOffset()); 135 ID.AddInteger(S.getModTime()); 136 return ID.ComputeHash(); 137 } 138 139 static bool isEqual(const PPRegion &LHS, const PPRegion &RHS) { 140 return LHS == RHS; 141 } 142 }; 143} 144 145namespace { 146 147class SessionSkipBodyData { 148 llvm::sys::Mutex Mux; 149 PPRegionSetTy ParsedRegions; 150 151public: 152 SessionSkipBodyData() : Mux(/*recursive=*/false) {} 153 ~SessionSkipBodyData() { 154 //llvm::errs() << "RegionData: " << Skipped.size() << " - " << Skipped.getMemorySize() << "\n"; 155 } 156 157 void copyTo(PPRegionSetTy &Set) { 158 llvm::MutexGuard MG(Mux); 159 Set = ParsedRegions; 160 } 161 162 void update(ArrayRef<PPRegion> Regions) { 163 llvm::MutexGuard MG(Mux); 164 ParsedRegions.insert(Regions.begin(), Regions.end()); 165 } 166}; 167 168class TUSkipBodyControl { 169 SessionSkipBodyData &SessionData; 170 PPConditionalDirectiveRecord &PPRec; 171 Preprocessor &PP; 172 173 PPRegionSetTy ParsedRegions; 174 SmallVector<PPRegion, 32> NewParsedRegions; 175 PPRegion LastRegion; 176 bool LastIsParsed; 177 178public: 179 TUSkipBodyControl(SessionSkipBodyData &sessionData, 180 PPConditionalDirectiveRecord &ppRec, 181 Preprocessor &pp) 182 : SessionData(sessionData), PPRec(ppRec), PP(pp) { 183 SessionData.copyTo(ParsedRegions); 184 } 185 186 bool isParsed(SourceLocation Loc, FileID FID, const FileEntry *FE) { 187 PPRegion region = getRegion(Loc, FID, FE); 188 if (region.isInvalid()) 189 return false; 190 191 // Check common case, consecutive functions in the same region. 192 if (LastRegion == region) 193 return LastIsParsed; 194 195 LastRegion = region; 196 LastIsParsed = ParsedRegions.count(region); 197 if (!LastIsParsed) 198 NewParsedRegions.push_back(region); 199 return LastIsParsed; 200 } 201 202 void finished() { 203 SessionData.update(NewParsedRegions); 204 } 205 206private: 207 PPRegion getRegion(SourceLocation Loc, FileID FID, const FileEntry *FE) { 208 SourceLocation RegionLoc = PPRec.findConditionalDirectiveRegionLoc(Loc); 209 if (RegionLoc.isInvalid()) { 210 if (isParsedOnceInclude(FE)) 211 return PPRegion(FE->getDevice(), FE->getInode(), 0, 212 FE->getModificationTime()); 213 return PPRegion(); 214 } 215 216 const SourceManager &SM = PPRec.getSourceManager(); 217 assert(RegionLoc.isFileID()); 218 FileID RegionFID; 219 unsigned RegionOffset; 220 llvm::tie(RegionFID, RegionOffset) = SM.getDecomposedLoc(RegionLoc); 221 222 if (RegionFID != FID) { 223 if (isParsedOnceInclude(FE)) 224 return PPRegion(FE->getDevice(), FE->getInode(), 0, 225 FE->getModificationTime()); 226 return PPRegion(); 227 } 228 229 return PPRegion(FE->getDevice(), FE->getInode(), RegionOffset, 230 FE->getModificationTime()); 231 } 232 233 bool isParsedOnceInclude(const FileEntry *FE) { 234 return PP.getHeaderSearchInfo().isFileMultipleIncludeGuarded(FE); 235 } 236}; 237 238#endif 239 240//===----------------------------------------------------------------------===// 241// IndexPPCallbacks 242//===----------------------------------------------------------------------===// 243 244class IndexPPCallbacks : public PPCallbacks { 245 Preprocessor &PP; 246 IndexingContext &IndexCtx; 247 bool IsMainFileEntered; 248 249public: 250 IndexPPCallbacks(Preprocessor &PP, IndexingContext &indexCtx) 251 : PP(PP), IndexCtx(indexCtx), IsMainFileEntered(false) { } 252 253 virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason, 254 SrcMgr::CharacteristicKind FileType, FileID PrevFID) { 255 if (IsMainFileEntered) 256 return; 257 258 SourceManager &SM = PP.getSourceManager(); 259 SourceLocation MainFileLoc = SM.getLocForStartOfFile(SM.getMainFileID()); 260 261 if (Loc == MainFileLoc && Reason == PPCallbacks::EnterFile) { 262 IsMainFileEntered = true; 263 IndexCtx.enteredMainFile(SM.getFileEntryForID(SM.getMainFileID())); 264 } 265 } 266 267 virtual void InclusionDirective(SourceLocation HashLoc, 268 const Token &IncludeTok, 269 StringRef FileName, 270 bool IsAngled, 271 CharSourceRange FilenameRange, 272 const FileEntry *File, 273 StringRef SearchPath, 274 StringRef RelativePath, 275 const Module *Imported) { 276 bool isImport = (IncludeTok.is(tok::identifier) && 277 IncludeTok.getIdentifierInfo()->getPPKeywordID() == tok::pp_import); 278 IndexCtx.ppIncludedFile(HashLoc, FileName, File, isImport, IsAngled, 279 Imported); 280 } 281 282 /// MacroDefined - This hook is called whenever a macro definition is seen. 283 virtual void MacroDefined(const Token &Id, const MacroInfo *MI) { 284 } 285 286 /// MacroUndefined - This hook is called whenever a macro #undef is seen. 287 /// MI is released immediately following this callback. 288 virtual void MacroUndefined(const Token &MacroNameTok, const MacroInfo *MI) { 289 } 290 291 /// MacroExpands - This is called by when a macro invocation is found. 292 virtual void MacroExpands(const Token &MacroNameTok, const MacroInfo* MI, 293 SourceRange Range) { 294 } 295 296 /// SourceRangeSkipped - This hook is called when a source range is skipped. 297 /// \param Range The SourceRange that was skipped. The range begins at the 298 /// #if/#else directive and ends after the #endif/#else directive. 299 virtual void SourceRangeSkipped(SourceRange Range) { 300 } 301}; 302 303//===----------------------------------------------------------------------===// 304// IndexingConsumer 305//===----------------------------------------------------------------------===// 306 307class IndexingConsumer : public ASTConsumer { 308 IndexingContext &IndexCtx; 309 TUSkipBodyControl *SKCtrl; 310 311public: 312 IndexingConsumer(IndexingContext &indexCtx, TUSkipBodyControl *skCtrl) 313 : IndexCtx(indexCtx), SKCtrl(skCtrl) { } 314 315 // ASTConsumer Implementation 316 317 virtual void Initialize(ASTContext &Context) { 318 IndexCtx.setASTContext(Context); 319 IndexCtx.startedTranslationUnit(); 320 } 321 322 virtual void HandleTranslationUnit(ASTContext &Ctx) { 323 if (SKCtrl) 324 SKCtrl->finished(); 325 } 326 327 virtual bool HandleTopLevelDecl(DeclGroupRef DG) { 328 IndexCtx.indexDeclGroupRef(DG); 329 return !IndexCtx.shouldAbort(); 330 } 331 332 /// \brief Handle the specified top-level declaration that occurred inside 333 /// and ObjC container. 334 virtual void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) { 335 // They will be handled after the interface is seen first. 336 IndexCtx.addTUDeclInObjCContainer(D); 337 } 338 339 /// \brief This is called by the AST reader when deserializing things. 340 /// The default implementation forwards to HandleTopLevelDecl but we don't 341 /// care about them when indexing, so have an empty definition. 342 virtual void HandleInterestingDecl(DeclGroupRef D) {} 343 344 virtual void HandleTagDeclDefinition(TagDecl *D) { 345 if (!IndexCtx.shouldIndexImplicitTemplateInsts()) 346 return; 347 348 if (IndexCtx.isTemplateImplicitInstantiation(D)) 349 IndexCtx.indexDecl(D); 350 } 351 352 virtual void HandleCXXImplicitFunctionInstantiation(FunctionDecl *D) { 353 if (!IndexCtx.shouldIndexImplicitTemplateInsts()) 354 return; 355 356 IndexCtx.indexDecl(D); 357 } 358 359 virtual bool shouldSkipFunctionBody(Decl *D) { 360 if (!SKCtrl) { 361 // Always skip bodies. 362 return true; 363 } 364 365 const SourceManager &SM = IndexCtx.getASTContext().getSourceManager(); 366 SourceLocation Loc = D->getLocation(); 367 if (Loc.isMacroID()) 368 return false; 369 if (SM.isInSystemHeader(Loc)) 370 return true; // always skip bodies from system headers. 371 372 FileID FID; 373 unsigned Offset; 374 llvm::tie(FID, Offset) = SM.getDecomposedLoc(Loc); 375 // Don't skip bodies from main files; this may be revisited. 376 if (SM.getMainFileID() == FID) 377 return false; 378 const FileEntry *FE = SM.getFileEntryForID(FID); 379 if (!FE) 380 return false; 381 382 return SKCtrl->isParsed(Loc, FID, FE); 383 } 384}; 385 386//===----------------------------------------------------------------------===// 387// CaptureDiagnosticConsumer 388//===----------------------------------------------------------------------===// 389 390class CaptureDiagnosticConsumer : public DiagnosticConsumer { 391 SmallVector<StoredDiagnostic, 4> Errors; 392public: 393 394 virtual void HandleDiagnostic(DiagnosticsEngine::Level level, 395 const Diagnostic &Info) { 396 if (level >= DiagnosticsEngine::Error) 397 Errors.push_back(StoredDiagnostic(level, Info)); 398 } 399 400 DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const { 401 return new IgnoringDiagConsumer(); 402 } 403}; 404 405//===----------------------------------------------------------------------===// 406// IndexingFrontendAction 407//===----------------------------------------------------------------------===// 408 409class IndexingFrontendAction : public ASTFrontendAction { 410 IndexingContext IndexCtx; 411 CXTranslationUnit CXTU; 412 413 SessionSkipBodyData *SKData; 414 OwningPtr<TUSkipBodyControl> SKCtrl; 415 416public: 417 IndexingFrontendAction(CXClientData clientData, 418 IndexerCallbacks &indexCallbacks, 419 unsigned indexOptions, 420 CXTranslationUnit cxTU, 421 SessionSkipBodyData *skData) 422 : IndexCtx(clientData, indexCallbacks, indexOptions, cxTU), 423 CXTU(cxTU), SKData(skData) { } 424 425 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI, 426 StringRef InFile) { 427 PreprocessorOptions &PPOpts = CI.getPreprocessorOpts(); 428 429 if (!PPOpts.ImplicitPCHInclude.empty()) { 430 IndexCtx.importedPCH( 431 CI.getFileManager().getFile(PPOpts.ImplicitPCHInclude)); 432 } 433 434 IndexCtx.setASTContext(CI.getASTContext()); 435 Preprocessor &PP = CI.getPreprocessor(); 436 PP.addPPCallbacks(new IndexPPCallbacks(PP, IndexCtx)); 437 IndexCtx.setPreprocessor(PP); 438 439 if (SKData) { 440 PPConditionalDirectiveRecord * 441 PPRec = new PPConditionalDirectiveRecord(PP.getSourceManager()); 442 PP.addPPCallbacks(PPRec); 443 SKCtrl.reset(new TUSkipBodyControl(*SKData, *PPRec, PP)); 444 } 445 446 return new IndexingConsumer(IndexCtx, SKCtrl.get()); 447 } 448 449 virtual void EndSourceFileAction() { 450 indexDiagnostics(CXTU, IndexCtx); 451 } 452 453 virtual TranslationUnitKind getTranslationUnitKind() { 454 if (IndexCtx.shouldIndexImplicitTemplateInsts()) 455 return TU_Complete; 456 else 457 return TU_Prefix; 458 } 459 virtual bool hasCodeCompletionSupport() const { return false; } 460}; 461 462//===----------------------------------------------------------------------===// 463// clang_indexSourceFileUnit Implementation 464//===----------------------------------------------------------------------===// 465 466struct IndexSessionData { 467 CXIndex CIdx; 468 OwningPtr<SessionSkipBodyData> SkipBodyData; 469 470 explicit IndexSessionData(CXIndex cIdx) 471 : CIdx(cIdx), SkipBodyData(new SessionSkipBodyData) {} 472}; 473 474struct IndexSourceFileInfo { 475 CXIndexAction idxAction; 476 CXClientData client_data; 477 IndexerCallbacks *index_callbacks; 478 unsigned index_callbacks_size; 479 unsigned index_options; 480 const char *source_filename; 481 const char *const *command_line_args; 482 int num_command_line_args; 483 struct CXUnsavedFile *unsaved_files; 484 unsigned num_unsaved_files; 485 CXTranslationUnit *out_TU; 486 unsigned TU_options; 487 int result; 488}; 489 490struct MemBufferOwner { 491 SmallVector<const llvm::MemoryBuffer *, 8> Buffers; 492 493 ~MemBufferOwner() { 494 for (SmallVectorImpl<const llvm::MemoryBuffer *>::iterator 495 I = Buffers.begin(), E = Buffers.end(); I != E; ++I) 496 delete *I; 497 } 498}; 499 500} // anonymous namespace 501 502static void clang_indexSourceFile_Impl(void *UserData) { 503 IndexSourceFileInfo *ITUI = 504 static_cast<IndexSourceFileInfo*>(UserData); 505 CXIndexAction cxIdxAction = ITUI->idxAction; 506 CXClientData client_data = ITUI->client_data; 507 IndexerCallbacks *client_index_callbacks = ITUI->index_callbacks; 508 unsigned index_callbacks_size = ITUI->index_callbacks_size; 509 unsigned index_options = ITUI->index_options; 510 const char *source_filename = ITUI->source_filename; 511 const char * const *command_line_args = ITUI->command_line_args; 512 int num_command_line_args = ITUI->num_command_line_args; 513 struct CXUnsavedFile *unsaved_files = ITUI->unsaved_files; 514 unsigned num_unsaved_files = ITUI->num_unsaved_files; 515 CXTranslationUnit *out_TU = ITUI->out_TU; 516 unsigned TU_options = ITUI->TU_options; 517 ITUI->result = 1; // init as error. 518 519 if (out_TU) 520 *out_TU = 0; 521 bool requestedToGetTU = (out_TU != 0); 522 523 if (!cxIdxAction) 524 return; 525 if (!client_index_callbacks || index_callbacks_size == 0) 526 return; 527 528 IndexerCallbacks CB; 529 memset(&CB, 0, sizeof(CB)); 530 unsigned ClientCBSize = index_callbacks_size < sizeof(CB) 531 ? index_callbacks_size : sizeof(CB); 532 memcpy(&CB, client_index_callbacks, ClientCBSize); 533 534 IndexSessionData *IdxSession = static_cast<IndexSessionData *>(cxIdxAction); 535 CIndexer *CXXIdx = static_cast<CIndexer *>(IdxSession->CIdx); 536 537 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing)) 538 setThreadBackgroundPriority(); 539 540 CaptureDiagnosticConsumer *CaptureDiag = new CaptureDiagnosticConsumer(); 541 542 // Configure the diagnostics. 543 IntrusiveRefCntPtr<DiagnosticsEngine> 544 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions, 545 num_command_line_args, 546 command_line_args, 547 CaptureDiag, 548 /*ShouldOwnClient=*/true, 549 /*ShouldCloneClient=*/false)); 550 551 // Recover resources if we crash before exiting this function. 552 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine, 553 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> > 554 DiagCleanup(Diags.getPtr()); 555 556 OwningPtr<std::vector<const char *> > 557 Args(new std::vector<const char*>()); 558 559 // Recover resources if we crash before exiting this method. 560 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> > 561 ArgsCleanup(Args.get()); 562 563 Args->insert(Args->end(), command_line_args, 564 command_line_args + num_command_line_args); 565 566 // The 'source_filename' argument is optional. If the caller does not 567 // specify it then it is assumed that the source file is specified 568 // in the actual argument list. 569 // Put the source file after command_line_args otherwise if '-x' flag is 570 // present it will be unused. 571 if (source_filename) 572 Args->push_back(source_filename); 573 574 IntrusiveRefCntPtr<CompilerInvocation> 575 CInvok(createInvocationFromCommandLine(*Args, Diags)); 576 577 if (!CInvok) 578 return; 579 580 // Recover resources if we crash before exiting this function. 581 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInvocation, 582 llvm::CrashRecoveryContextReleaseRefCleanup<CompilerInvocation> > 583 CInvokCleanup(CInvok.getPtr()); 584 585 if (CInvok->getFrontendOpts().Inputs.empty()) 586 return; 587 588 OwningPtr<MemBufferOwner> BufOwner(new MemBufferOwner()); 589 590 // Recover resources if we crash before exiting this method. 591 llvm::CrashRecoveryContextCleanupRegistrar<MemBufferOwner> 592 BufOwnerCleanup(BufOwner.get()); 593 594 for (unsigned I = 0; I != num_unsaved_files; ++I) { 595 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length); 596 const llvm::MemoryBuffer *Buffer 597 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename); 598 CInvok->getPreprocessorOpts().addRemappedFile(unsaved_files[I].Filename, Buffer); 599 BufOwner->Buffers.push_back(Buffer); 600 } 601 602 // Since libclang is primarily used by batch tools dealing with 603 // (often very broken) source code, where spell-checking can have a 604 // significant negative impact on performance (particularly when 605 // precompiled headers are involved), we disable it. 606 CInvok->getLangOpts()->SpellChecking = false; 607 608 if (index_options & CXIndexOpt_SuppressWarnings) 609 CInvok->getDiagnosticOpts().IgnoreWarnings = true; 610 611 ASTUnit *Unit = ASTUnit::create(CInvok.getPtr(), Diags, 612 /*CaptureDiagnostics=*/true, 613 /*UserFilesAreVolatile=*/true); 614 OwningPtr<CXTUOwner> CXTU(new CXTUOwner(MakeCXTranslationUnit(CXXIdx, Unit))); 615 616 // Recover resources if we crash before exiting this method. 617 llvm::CrashRecoveryContextCleanupRegistrar<CXTUOwner> 618 CXTUCleanup(CXTU.get()); 619 620 // Enable the skip-parsed-bodies optimization only for C++; this may be 621 // revisited. 622 bool SkipBodies = (index_options & CXIndexOpt_SkipParsedBodiesInSession) && 623 CInvok->getLangOpts()->CPlusPlus; 624 if (SkipBodies) 625 CInvok->getFrontendOpts().SkipFunctionBodies = true; 626 627 OwningPtr<IndexingFrontendAction> IndexAction; 628 IndexAction.reset(new IndexingFrontendAction(client_data, CB, 629 index_options, CXTU->getTU(), 630 SkipBodies ? IdxSession->SkipBodyData.get() : 0)); 631 632 // Recover resources if we crash before exiting this method. 633 llvm::CrashRecoveryContextCleanupRegistrar<IndexingFrontendAction> 634 IndexActionCleanup(IndexAction.get()); 635 636 bool Persistent = requestedToGetTU; 637 bool OnlyLocalDecls = false; 638 bool PrecompilePreamble = false; 639 bool CacheCodeCompletionResults = false; 640 PreprocessorOptions &PPOpts = CInvok->getPreprocessorOpts(); 641 PPOpts.AllowPCHWithCompilerErrors = true; 642 643 if (requestedToGetTU) { 644 OnlyLocalDecls = CXXIdx->getOnlyLocalDecls(); 645 PrecompilePreamble = TU_options & CXTranslationUnit_PrecompiledPreamble; 646 // FIXME: Add a flag for modules. 647 CacheCodeCompletionResults 648 = TU_options & CXTranslationUnit_CacheCompletionResults; 649 } 650 651 if (TU_options & CXTranslationUnit_DetailedPreprocessingRecord) { 652 PPOpts.DetailedRecord = true; 653 } 654 655 if (!requestedToGetTU && !CInvok->getLangOpts()->Modules) 656 PPOpts.DetailedRecord = false; 657 658 DiagnosticErrorTrap DiagTrap(*Diags); 659 bool Success = ASTUnit::LoadFromCompilerInvocationAction(CInvok.getPtr(), Diags, 660 IndexAction.get(), 661 Unit, 662 Persistent, 663 CXXIdx->getClangResourcesPath(), 664 OnlyLocalDecls, 665 /*CaptureDiagnostics=*/true, 666 PrecompilePreamble, 667 CacheCodeCompletionResults, 668 /*IncludeBriefCommentsInCodeCompletion=*/false, 669 /*UserFilesAreVolatile=*/true); 670 if (DiagTrap.hasErrorOccurred() && CXXIdx->getDisplayDiagnostics()) 671 printDiagsToStderr(Unit); 672 673 if (!Success) 674 return; 675 676 if (out_TU) 677 *out_TU = CXTU->takeTU(); 678 679 ITUI->result = 0; // success. 680} 681 682//===----------------------------------------------------------------------===// 683// clang_indexTranslationUnit Implementation 684//===----------------------------------------------------------------------===// 685 686namespace { 687 688struct IndexTranslationUnitInfo { 689 CXIndexAction idxAction; 690 CXClientData client_data; 691 IndexerCallbacks *index_callbacks; 692 unsigned index_callbacks_size; 693 unsigned index_options; 694 CXTranslationUnit TU; 695 int result; 696}; 697 698} // anonymous namespace 699 700static void indexPreprocessingRecord(ASTUnit &Unit, IndexingContext &IdxCtx) { 701 Preprocessor &PP = Unit.getPreprocessor(); 702 if (!PP.getPreprocessingRecord()) 703 return; 704 705 // FIXME: Only deserialize inclusion directives. 706 707 PreprocessingRecord::iterator I, E; 708 llvm::tie(I, E) = Unit.getLocalPreprocessingEntities(); 709 710 bool isModuleFile = Unit.isModuleFile(); 711 for (; I != E; ++I) { 712 PreprocessedEntity *PPE = *I; 713 714 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) { 715 SourceLocation Loc = ID->getSourceRange().getBegin(); 716 // Modules have synthetic main files as input, give an invalid location 717 // if the location points to such a file. 718 if (isModuleFile && Unit.isInMainFileID(Loc)) 719 Loc = SourceLocation(); 720 IdxCtx.ppIncludedFile(Loc, ID->getFileName(), 721 ID->getFile(), 722 ID->getKind() == InclusionDirective::Import, 723 !ID->wasInQuotes(), ID->importedModule()); 724 } 725 } 726} 727 728static bool topLevelDeclVisitor(void *context, const Decl *D) { 729 IndexingContext &IdxCtx = *static_cast<IndexingContext*>(context); 730 IdxCtx.indexTopLevelDecl(D); 731 if (IdxCtx.shouldAbort()) 732 return false; 733 return true; 734} 735 736static void indexTranslationUnit(ASTUnit &Unit, IndexingContext &IdxCtx) { 737 Unit.visitLocalTopLevelDecls(&IdxCtx, topLevelDeclVisitor); 738} 739 740static void indexDiagnostics(CXTranslationUnit TU, IndexingContext &IdxCtx) { 741 if (!IdxCtx.hasDiagnosticCallback()) 742 return; 743 744 CXDiagnosticSetImpl *DiagSet = cxdiag::lazyCreateDiags(TU); 745 IdxCtx.handleDiagnosticSet(DiagSet); 746} 747 748static void clang_indexTranslationUnit_Impl(void *UserData) { 749 IndexTranslationUnitInfo *ITUI = 750 static_cast<IndexTranslationUnitInfo*>(UserData); 751 CXTranslationUnit TU = ITUI->TU; 752 CXClientData client_data = ITUI->client_data; 753 IndexerCallbacks *client_index_callbacks = ITUI->index_callbacks; 754 unsigned index_callbacks_size = ITUI->index_callbacks_size; 755 unsigned index_options = ITUI->index_options; 756 ITUI->result = 1; // init as error. 757 758 if (!TU) 759 return; 760 if (!client_index_callbacks || index_callbacks_size == 0) 761 return; 762 763 CIndexer *CXXIdx = (CIndexer*)TU->CIdx; 764 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing)) 765 setThreadBackgroundPriority(); 766 767 IndexerCallbacks CB; 768 memset(&CB, 0, sizeof(CB)); 769 unsigned ClientCBSize = index_callbacks_size < sizeof(CB) 770 ? index_callbacks_size : sizeof(CB); 771 memcpy(&CB, client_index_callbacks, ClientCBSize); 772 773 OwningPtr<IndexingContext> IndexCtx; 774 IndexCtx.reset(new IndexingContext(client_data, CB, index_options, TU)); 775 776 // Recover resources if we crash before exiting this method. 777 llvm::CrashRecoveryContextCleanupRegistrar<IndexingContext> 778 IndexCtxCleanup(IndexCtx.get()); 779 780 OwningPtr<IndexingConsumer> IndexConsumer; 781 IndexConsumer.reset(new IndexingConsumer(*IndexCtx, 0)); 782 783 // Recover resources if we crash before exiting this method. 784 llvm::CrashRecoveryContextCleanupRegistrar<IndexingConsumer> 785 IndexConsumerCleanup(IndexConsumer.get()); 786 787 ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData); 788 if (!Unit) 789 return; 790 791 ASTUnit::ConcurrencyCheck Check(*Unit); 792 793 if (const FileEntry *PCHFile = Unit->getPCHFile()) 794 IndexCtx->importedPCH(PCHFile); 795 796 FileManager &FileMgr = Unit->getFileManager(); 797 798 if (Unit->getOriginalSourceFileName().empty()) 799 IndexCtx->enteredMainFile(0); 800 else 801 IndexCtx->enteredMainFile(FileMgr.getFile(Unit->getOriginalSourceFileName())); 802 803 IndexConsumer->Initialize(Unit->getASTContext()); 804 805 indexPreprocessingRecord(*Unit, *IndexCtx); 806 indexTranslationUnit(*Unit, *IndexCtx); 807 indexDiagnostics(TU, *IndexCtx); 808 809 ITUI->result = 0; 810} 811 812//===----------------------------------------------------------------------===// 813// libclang public APIs. 814//===----------------------------------------------------------------------===// 815 816extern "C" { 817 818int clang_index_isEntityObjCContainerKind(CXIdxEntityKind K) { 819 return CXIdxEntity_ObjCClass <= K && K <= CXIdxEntity_ObjCCategory; 820} 821 822const CXIdxObjCContainerDeclInfo * 823clang_index_getObjCContainerDeclInfo(const CXIdxDeclInfo *DInfo) { 824 if (!DInfo) 825 return 0; 826 827 const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo); 828 if (const ObjCContainerDeclInfo * 829 ContInfo = dyn_cast<ObjCContainerDeclInfo>(DI)) 830 return &ContInfo->ObjCContDeclInfo; 831 832 return 0; 833} 834 835const CXIdxObjCInterfaceDeclInfo * 836clang_index_getObjCInterfaceDeclInfo(const CXIdxDeclInfo *DInfo) { 837 if (!DInfo) 838 return 0; 839 840 const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo); 841 if (const ObjCInterfaceDeclInfo * 842 InterInfo = dyn_cast<ObjCInterfaceDeclInfo>(DI)) 843 return &InterInfo->ObjCInterDeclInfo; 844 845 return 0; 846} 847 848const CXIdxObjCCategoryDeclInfo * 849clang_index_getObjCCategoryDeclInfo(const CXIdxDeclInfo *DInfo){ 850 if (!DInfo) 851 return 0; 852 853 const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo); 854 if (const ObjCCategoryDeclInfo * 855 CatInfo = dyn_cast<ObjCCategoryDeclInfo>(DI)) 856 return &CatInfo->ObjCCatDeclInfo; 857 858 return 0; 859} 860 861const CXIdxObjCProtocolRefListInfo * 862clang_index_getObjCProtocolRefListInfo(const CXIdxDeclInfo *DInfo) { 863 if (!DInfo) 864 return 0; 865 866 const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo); 867 868 if (const ObjCInterfaceDeclInfo * 869 InterInfo = dyn_cast<ObjCInterfaceDeclInfo>(DI)) 870 return InterInfo->ObjCInterDeclInfo.protocols; 871 872 if (const ObjCProtocolDeclInfo * 873 ProtInfo = dyn_cast<ObjCProtocolDeclInfo>(DI)) 874 return &ProtInfo->ObjCProtoRefListInfo; 875 876 if (const ObjCCategoryDeclInfo *CatInfo = dyn_cast<ObjCCategoryDeclInfo>(DI)) 877 return CatInfo->ObjCCatDeclInfo.protocols; 878 879 return 0; 880} 881 882const CXIdxObjCPropertyDeclInfo * 883clang_index_getObjCPropertyDeclInfo(const CXIdxDeclInfo *DInfo) { 884 if (!DInfo) 885 return 0; 886 887 const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo); 888 if (const ObjCPropertyDeclInfo *PropInfo = dyn_cast<ObjCPropertyDeclInfo>(DI)) 889 return &PropInfo->ObjCPropDeclInfo; 890 891 return 0; 892} 893 894const CXIdxIBOutletCollectionAttrInfo * 895clang_index_getIBOutletCollectionAttrInfo(const CXIdxAttrInfo *AInfo) { 896 if (!AInfo) 897 return 0; 898 899 const AttrInfo *DI = static_cast<const AttrInfo *>(AInfo); 900 if (const IBOutletCollectionInfo * 901 IBInfo = dyn_cast<IBOutletCollectionInfo>(DI)) 902 return &IBInfo->IBCollInfo; 903 904 return 0; 905} 906 907const CXIdxCXXClassDeclInfo * 908clang_index_getCXXClassDeclInfo(const CXIdxDeclInfo *DInfo) { 909 if (!DInfo) 910 return 0; 911 912 const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo); 913 if (const CXXClassDeclInfo *ClassInfo = dyn_cast<CXXClassDeclInfo>(DI)) 914 return &ClassInfo->CXXClassInfo; 915 916 return 0; 917} 918 919CXIdxClientContainer 920clang_index_getClientContainer(const CXIdxContainerInfo *info) { 921 if (!info) 922 return 0; 923 const ContainerInfo *Container = static_cast<const ContainerInfo *>(info); 924 return Container->IndexCtx->getClientContainerForDC(Container->DC); 925} 926 927void clang_index_setClientContainer(const CXIdxContainerInfo *info, 928 CXIdxClientContainer client) { 929 if (!info) 930 return; 931 const ContainerInfo *Container = static_cast<const ContainerInfo *>(info); 932 Container->IndexCtx->addContainerInMap(Container->DC, client); 933} 934 935CXIdxClientEntity clang_index_getClientEntity(const CXIdxEntityInfo *info) { 936 if (!info) 937 return 0; 938 const EntityInfo *Entity = static_cast<const EntityInfo *>(info); 939 return Entity->IndexCtx->getClientEntity(Entity->Dcl); 940} 941 942void clang_index_setClientEntity(const CXIdxEntityInfo *info, 943 CXIdxClientEntity client) { 944 if (!info) 945 return; 946 const EntityInfo *Entity = static_cast<const EntityInfo *>(info); 947 Entity->IndexCtx->setClientEntity(Entity->Dcl, client); 948} 949 950CXIndexAction clang_IndexAction_create(CXIndex CIdx) { 951 return new IndexSessionData(CIdx); 952} 953 954void clang_IndexAction_dispose(CXIndexAction idxAction) { 955 if (idxAction) 956 delete static_cast<IndexSessionData *>(idxAction); 957} 958 959int clang_indexSourceFile(CXIndexAction idxAction, 960 CXClientData client_data, 961 IndexerCallbacks *index_callbacks, 962 unsigned index_callbacks_size, 963 unsigned index_options, 964 const char *source_filename, 965 const char * const *command_line_args, 966 int num_command_line_args, 967 struct CXUnsavedFile *unsaved_files, 968 unsigned num_unsaved_files, 969 CXTranslationUnit *out_TU, 970 unsigned TU_options) { 971 972 IndexSourceFileInfo ITUI = { idxAction, client_data, index_callbacks, 973 index_callbacks_size, index_options, 974 source_filename, command_line_args, 975 num_command_line_args, unsaved_files, 976 num_unsaved_files, out_TU, TU_options, 0 }; 977 978 if (getenv("LIBCLANG_NOTHREADS")) { 979 clang_indexSourceFile_Impl(&ITUI); 980 return ITUI.result; 981 } 982 983 llvm::CrashRecoveryContext CRC; 984 985 if (!RunSafely(CRC, clang_indexSourceFile_Impl, &ITUI)) { 986 fprintf(stderr, "libclang: crash detected during indexing source file: {\n"); 987 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename); 988 fprintf(stderr, " 'command_line_args' : ["); 989 for (int i = 0; i != num_command_line_args; ++i) { 990 if (i) 991 fprintf(stderr, ", "); 992 fprintf(stderr, "'%s'", command_line_args[i]); 993 } 994 fprintf(stderr, "],\n"); 995 fprintf(stderr, " 'unsaved_files' : ["); 996 for (unsigned i = 0; i != num_unsaved_files; ++i) { 997 if (i) 998 fprintf(stderr, ", "); 999 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename, 1000 unsaved_files[i].Length); 1001 } 1002 fprintf(stderr, "],\n"); 1003 fprintf(stderr, " 'options' : %d,\n", TU_options); 1004 fprintf(stderr, "}\n"); 1005 1006 return 1; 1007 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) { 1008 if (out_TU) 1009 PrintLibclangResourceUsage(*out_TU); 1010 } 1011 1012 return ITUI.result; 1013} 1014 1015int clang_indexTranslationUnit(CXIndexAction idxAction, 1016 CXClientData client_data, 1017 IndexerCallbacks *index_callbacks, 1018 unsigned index_callbacks_size, 1019 unsigned index_options, 1020 CXTranslationUnit TU) { 1021 1022 IndexTranslationUnitInfo ITUI = { idxAction, client_data, index_callbacks, 1023 index_callbacks_size, index_options, TU, 1024 0 }; 1025 1026 if (getenv("LIBCLANG_NOTHREADS")) { 1027 clang_indexTranslationUnit_Impl(&ITUI); 1028 return ITUI.result; 1029 } 1030 1031 llvm::CrashRecoveryContext CRC; 1032 1033 if (!RunSafely(CRC, clang_indexTranslationUnit_Impl, &ITUI)) { 1034 fprintf(stderr, "libclang: crash detected during indexing TU\n"); 1035 1036 return 1; 1037 } 1038 1039 return ITUI.result; 1040} 1041 1042void clang_indexLoc_getFileLocation(CXIdxLoc location, 1043 CXIdxClientFile *indexFile, 1044 CXFile *file, 1045 unsigned *line, 1046 unsigned *column, 1047 unsigned *offset) { 1048 if (indexFile) *indexFile = 0; 1049 if (file) *file = 0; 1050 if (line) *line = 0; 1051 if (column) *column = 0; 1052 if (offset) *offset = 0; 1053 1054 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data); 1055 if (!location.ptr_data[0] || Loc.isInvalid()) 1056 return; 1057 1058 IndexingContext &IndexCtx = 1059 *static_cast<IndexingContext*>(location.ptr_data[0]); 1060 IndexCtx.translateLoc(Loc, indexFile, file, line, column, offset); 1061} 1062 1063CXSourceLocation clang_indexLoc_getCXSourceLocation(CXIdxLoc location) { 1064 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data); 1065 if (!location.ptr_data[0] || Loc.isInvalid()) 1066 return clang_getNullLocation(); 1067 1068 IndexingContext &IndexCtx = 1069 *static_cast<IndexingContext*>(location.ptr_data[0]); 1070 return cxloc::translateSourceLocation(IndexCtx.getASTContext(), Loc); 1071} 1072 1073} // end: extern "C" 1074 1075