1 //===- CIndexHigh.cpp - Higher level API functions ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "IndexingContext.h"
11 #include "CIndexDiagnostic.h"
15 #include "CXSourceLocation.h"
17 #include "CXTranslationUnit.h"
18 #include "clang/AST/ASTConsumer.h"
19 #include "clang/AST/DeclVisitor.h"
20 #include "clang/Frontend/ASTUnit.h"
21 #include "clang/Frontend/CompilerInstance.h"
22 #include "clang/Frontend/CompilerInvocation.h"
23 #include "clang/Frontend/FrontendAction.h"
24 #include "clang/Frontend/Utils.h"
25 #include "clang/Lex/HeaderSearch.h"
26 #include "clang/Lex/PPCallbacks.h"
27 #include "clang/Lex/PPConditionalDirectiveRecord.h"
28 #include "clang/Lex/Preprocessor.h"
29 #include "clang/Sema/SemaConsumer.h"
30 #include "llvm/Support/CrashRecoveryContext.h"
31 #include "llvm/Support/MemoryBuffer.h"
32 #include "llvm/Support/Mutex.h"
33 #include "llvm/Support/MutexGuard.h"
35 using namespace clang;
37 using namespace cxindex;
39 static void indexDiagnostics(CXTranslationUnit TU, IndexingContext &IdxCtx);
43 //===----------------------------------------------------------------------===//
45 //===----------------------------------------------------------------------===//
49 // FIXME: On windows it is disabled since current implementation depends on
52 class SessionSkipBodyData { };
54 class TUSkipBodyControl {
56 TUSkipBodyControl(SessionSkipBodyData &sessionData,
57 PPConditionalDirectiveRecord &ppRec,
59 bool isParsed(SourceLocation Loc, FileID FID, const FileEntry *FE) {
67 /// \brief A "region" in source code identified by the file/offset of the
68 /// preprocessor conditional directive that it belongs to.
69 /// Multiple, non-consecutive ranges can be parts of the same region.
71 /// As an example of different regions separated by preprocessor directives:
85 /// There are 3 regions, with non-consecutive parts:
86 /// #1 is identified as the beginning of the file
87 /// #2 is identified as the location of "#ifdef BLAH"
88 /// #3 is identified as the location of "#ifdef CAKE"
96 PPRegion() : ino(), ModTime(), dev(), Offset() {}
97 PPRegion(dev_t dev, ino_t ino, unsigned offset, time_t modTime)
98 : ino(ino), ModTime(modTime), dev(dev), Offset(offset) {}
100 ino_t getIno() const { return ino; }
101 dev_t getDev() const { return dev; }
102 unsigned getOffset() const { return Offset; }
103 time_t getModTime() const { return ModTime; }
105 bool isInvalid() const { return *this == PPRegion(); }
107 friend bool operator==(const PPRegion &lhs, const PPRegion &rhs) {
108 return lhs.dev == rhs.dev && lhs.ino == rhs.ino &&
109 lhs.Offset == rhs.Offset && lhs.ModTime == rhs.ModTime;
113 typedef llvm::DenseSet<PPRegion> PPRegionSetTy;
115 } // end anonymous namespace
118 template <> struct isPodLike<PPRegion> {
119 static const bool value = true;
123 struct DenseMapInfo<PPRegion> {
124 static inline PPRegion getEmptyKey() {
125 return PPRegion(0, 0, unsigned(-1), 0);
127 static inline PPRegion getTombstoneKey() {
128 return PPRegion(0, 0, unsigned(-2), 0);
131 static unsigned getHashValue(const PPRegion &S) {
132 llvm::FoldingSetNodeID ID;
133 ID.AddInteger(S.getIno());
134 ID.AddInteger(S.getDev());
135 ID.AddInteger(S.getOffset());
136 ID.AddInteger(S.getModTime());
137 return ID.ComputeHash();
140 static bool isEqual(const PPRegion &LHS, const PPRegion &RHS) {
148 class SessionSkipBodyData {
149 llvm::sys::Mutex Mux;
150 PPRegionSetTy ParsedRegions;
153 SessionSkipBodyData() : Mux(/*recursive=*/false) {}
154 ~SessionSkipBodyData() {
155 //llvm::errs() << "RegionData: " << Skipped.size() << " - " << Skipped.getMemorySize() << "\n";
158 void copyTo(PPRegionSetTy &Set) {
159 llvm::MutexGuard MG(Mux);
163 void update(ArrayRef<PPRegion> Regions) {
164 llvm::MutexGuard MG(Mux);
165 ParsedRegions.insert(Regions.begin(), Regions.end());
169 class TUSkipBodyControl {
170 SessionSkipBodyData &SessionData;
171 PPConditionalDirectiveRecord &PPRec;
174 PPRegionSetTy ParsedRegions;
175 SmallVector<PPRegion, 32> NewParsedRegions;
180 TUSkipBodyControl(SessionSkipBodyData &sessionData,
181 PPConditionalDirectiveRecord &ppRec,
183 : SessionData(sessionData), PPRec(ppRec), PP(pp) {
184 SessionData.copyTo(ParsedRegions);
187 bool isParsed(SourceLocation Loc, FileID FID, const FileEntry *FE) {
188 PPRegion region = getRegion(Loc, FID, FE);
189 if (region.isInvalid())
192 // Check common case, consecutive functions in the same region.
193 if (LastRegion == region)
197 LastIsParsed = ParsedRegions.count(region);
199 NewParsedRegions.push_back(region);
204 SessionData.update(NewParsedRegions);
208 PPRegion getRegion(SourceLocation Loc, FileID FID, const FileEntry *FE) {
209 SourceLocation RegionLoc = PPRec.findConditionalDirectiveRegionLoc(Loc);
210 if (RegionLoc.isInvalid()) {
211 if (isParsedOnceInclude(FE))
212 return PPRegion(FE->getDevice(), FE->getInode(), 0,
213 FE->getModificationTime());
217 const SourceManager &SM = PPRec.getSourceManager();
218 assert(RegionLoc.isFileID());
220 unsigned RegionOffset;
221 llvm::tie(RegionFID, RegionOffset) = SM.getDecomposedLoc(RegionLoc);
223 if (RegionFID != FID) {
224 if (isParsedOnceInclude(FE))
225 return PPRegion(FE->getDevice(), FE->getInode(), 0,
226 FE->getModificationTime());
230 return PPRegion(FE->getDevice(), FE->getInode(), RegionOffset,
231 FE->getModificationTime());
234 bool isParsedOnceInclude(const FileEntry *FE) {
235 return PP.getHeaderSearchInfo().isFileMultipleIncludeGuarded(FE);
241 //===----------------------------------------------------------------------===//
243 //===----------------------------------------------------------------------===//
245 class IndexPPCallbacks : public PPCallbacks {
247 IndexingContext &IndexCtx;
248 bool IsMainFileEntered;
251 IndexPPCallbacks(Preprocessor &PP, IndexingContext &indexCtx)
252 : PP(PP), IndexCtx(indexCtx), IsMainFileEntered(false) { }
254 virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
255 SrcMgr::CharacteristicKind FileType, FileID PrevFID) {
256 if (IsMainFileEntered)
259 SourceManager &SM = PP.getSourceManager();
260 SourceLocation MainFileLoc = SM.getLocForStartOfFile(SM.getMainFileID());
262 if (Loc == MainFileLoc && Reason == PPCallbacks::EnterFile) {
263 IsMainFileEntered = true;
264 IndexCtx.enteredMainFile(SM.getFileEntryForID(SM.getMainFileID()));
268 virtual void InclusionDirective(SourceLocation HashLoc,
269 const Token &IncludeTok,
272 CharSourceRange FilenameRange,
273 const FileEntry *File,
274 StringRef SearchPath,
275 StringRef RelativePath,
276 const Module *Imported) {
277 bool isImport = (IncludeTok.is(tok::identifier) &&
278 IncludeTok.getIdentifierInfo()->getPPKeywordID() == tok::pp_import);
279 IndexCtx.ppIncludedFile(HashLoc, FileName, File, isImport, IsAngled,
283 /// MacroDefined - This hook is called whenever a macro definition is seen.
284 virtual void MacroDefined(const Token &Id, const MacroDirective *MD) {
287 /// MacroUndefined - This hook is called whenever a macro #undef is seen.
288 /// MI is released immediately following this callback.
289 virtual void MacroUndefined(const Token &MacroNameTok,
290 const MacroDirective *MD) {
293 /// MacroExpands - This is called by when a macro invocation is found.
294 virtual void MacroExpands(const Token &MacroNameTok, const MacroDirective *MD,
295 SourceRange Range, const MacroArgs *Args) {
298 /// SourceRangeSkipped - This hook is called when a source range is skipped.
299 /// \param Range The SourceRange that was skipped. The range begins at the
300 /// #if/#else directive and ends after the #endif/#else directive.
301 virtual void SourceRangeSkipped(SourceRange Range) {
305 //===----------------------------------------------------------------------===//
307 //===----------------------------------------------------------------------===//
309 class IndexingConsumer : public ASTConsumer {
310 IndexingContext &IndexCtx;
311 TUSkipBodyControl *SKCtrl;
314 IndexingConsumer(IndexingContext &indexCtx, TUSkipBodyControl *skCtrl)
315 : IndexCtx(indexCtx), SKCtrl(skCtrl) { }
317 // ASTConsumer Implementation
319 virtual void Initialize(ASTContext &Context) {
320 IndexCtx.setASTContext(Context);
321 IndexCtx.startedTranslationUnit();
324 virtual void HandleTranslationUnit(ASTContext &Ctx) {
329 virtual bool HandleTopLevelDecl(DeclGroupRef DG) {
330 IndexCtx.indexDeclGroupRef(DG);
331 return !IndexCtx.shouldAbort();
334 /// \brief Handle the specified top-level declaration that occurred inside
335 /// and ObjC container.
336 virtual void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {
337 // They will be handled after the interface is seen first.
338 IndexCtx.addTUDeclInObjCContainer(D);
341 /// \brief This is called by the AST reader when deserializing things.
342 /// The default implementation forwards to HandleTopLevelDecl but we don't
343 /// care about them when indexing, so have an empty definition.
344 virtual void HandleInterestingDecl(DeclGroupRef D) {}
346 virtual void HandleTagDeclDefinition(TagDecl *D) {
347 if (!IndexCtx.shouldIndexImplicitTemplateInsts())
350 if (IndexCtx.isTemplateImplicitInstantiation(D))
351 IndexCtx.indexDecl(D);
354 virtual void HandleCXXImplicitFunctionInstantiation(FunctionDecl *D) {
355 if (!IndexCtx.shouldIndexImplicitTemplateInsts())
358 IndexCtx.indexDecl(D);
361 virtual bool shouldSkipFunctionBody(Decl *D) {
363 // Always skip bodies.
367 const SourceManager &SM = IndexCtx.getASTContext().getSourceManager();
368 SourceLocation Loc = D->getLocation();
371 if (SM.isInSystemHeader(Loc))
372 return true; // always skip bodies from system headers.
376 llvm::tie(FID, Offset) = SM.getDecomposedLoc(Loc);
377 // Don't skip bodies from main files; this may be revisited.
378 if (SM.getMainFileID() == FID)
380 const FileEntry *FE = SM.getFileEntryForID(FID);
384 return SKCtrl->isParsed(Loc, FID, FE);
388 //===----------------------------------------------------------------------===//
389 // CaptureDiagnosticConsumer
390 //===----------------------------------------------------------------------===//
392 class CaptureDiagnosticConsumer : public DiagnosticConsumer {
393 SmallVector<StoredDiagnostic, 4> Errors;
396 virtual void HandleDiagnostic(DiagnosticsEngine::Level level,
397 const Diagnostic &Info) {
398 if (level >= DiagnosticsEngine::Error)
399 Errors.push_back(StoredDiagnostic(level, Info));
403 //===----------------------------------------------------------------------===//
404 // IndexingFrontendAction
405 //===----------------------------------------------------------------------===//
407 class IndexingFrontendAction : public ASTFrontendAction {
408 IndexingContext IndexCtx;
409 CXTranslationUnit CXTU;
411 SessionSkipBodyData *SKData;
412 OwningPtr<TUSkipBodyControl> SKCtrl;
415 IndexingFrontendAction(CXClientData clientData,
416 IndexerCallbacks &indexCallbacks,
417 unsigned indexOptions,
418 CXTranslationUnit cxTU,
419 SessionSkipBodyData *skData)
420 : IndexCtx(clientData, indexCallbacks, indexOptions, cxTU),
421 CXTU(cxTU), SKData(skData) { }
423 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
425 PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
427 if (!PPOpts.ImplicitPCHInclude.empty()) {
428 IndexCtx.importedPCH(
429 CI.getFileManager().getFile(PPOpts.ImplicitPCHInclude));
432 IndexCtx.setASTContext(CI.getASTContext());
433 Preprocessor &PP = CI.getPreprocessor();
434 PP.addPPCallbacks(new IndexPPCallbacks(PP, IndexCtx));
435 IndexCtx.setPreprocessor(PP);
438 PPConditionalDirectiveRecord *
439 PPRec = new PPConditionalDirectiveRecord(PP.getSourceManager());
440 PP.addPPCallbacks(PPRec);
441 SKCtrl.reset(new TUSkipBodyControl(*SKData, *PPRec, PP));
444 return new IndexingConsumer(IndexCtx, SKCtrl.get());
447 virtual void EndSourceFileAction() {
448 indexDiagnostics(CXTU, IndexCtx);
451 virtual TranslationUnitKind getTranslationUnitKind() {
452 if (IndexCtx.shouldIndexImplicitTemplateInsts())
457 virtual bool hasCodeCompletionSupport() const { return false; }
460 //===----------------------------------------------------------------------===//
461 // clang_indexSourceFileUnit Implementation
462 //===----------------------------------------------------------------------===//
464 struct IndexSessionData {
466 OwningPtr<SessionSkipBodyData> SkipBodyData;
468 explicit IndexSessionData(CXIndex cIdx)
469 : CIdx(cIdx), SkipBodyData(new SessionSkipBodyData) {}
472 struct IndexSourceFileInfo {
473 CXIndexAction idxAction;
474 CXClientData client_data;
475 IndexerCallbacks *index_callbacks;
476 unsigned index_callbacks_size;
477 unsigned index_options;
478 const char *source_filename;
479 const char *const *command_line_args;
480 int num_command_line_args;
481 struct CXUnsavedFile *unsaved_files;
482 unsigned num_unsaved_files;
483 CXTranslationUnit *out_TU;
488 struct MemBufferOwner {
489 SmallVector<const llvm::MemoryBuffer *, 8> Buffers;
492 for (SmallVectorImpl<const llvm::MemoryBuffer *>::iterator
493 I = Buffers.begin(), E = Buffers.end(); I != E; ++I)
498 } // anonymous namespace
500 static void clang_indexSourceFile_Impl(void *UserData) {
501 IndexSourceFileInfo *ITUI =
502 static_cast<IndexSourceFileInfo*>(UserData);
503 CXIndexAction cxIdxAction = ITUI->idxAction;
504 CXClientData client_data = ITUI->client_data;
505 IndexerCallbacks *client_index_callbacks = ITUI->index_callbacks;
506 unsigned index_callbacks_size = ITUI->index_callbacks_size;
507 unsigned index_options = ITUI->index_options;
508 const char *source_filename = ITUI->source_filename;
509 const char * const *command_line_args = ITUI->command_line_args;
510 int num_command_line_args = ITUI->num_command_line_args;
511 struct CXUnsavedFile *unsaved_files = ITUI->unsaved_files;
512 unsigned num_unsaved_files = ITUI->num_unsaved_files;
513 CXTranslationUnit *out_TU = ITUI->out_TU;
514 unsigned TU_options = ITUI->TU_options;
515 ITUI->result = 1; // init as error.
519 bool requestedToGetTU = (out_TU != 0);
523 if (!client_index_callbacks || index_callbacks_size == 0)
527 memset(&CB, 0, sizeof(CB));
528 unsigned ClientCBSize = index_callbacks_size < sizeof(CB)
529 ? index_callbacks_size : sizeof(CB);
530 memcpy(&CB, client_index_callbacks, ClientCBSize);
532 IndexSessionData *IdxSession = static_cast<IndexSessionData *>(cxIdxAction);
533 CIndexer *CXXIdx = static_cast<CIndexer *>(IdxSession->CIdx);
535 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
536 setThreadBackgroundPriority();
538 bool CaptureDiagnostics = !Logger::isLoggingEnabled();
540 CaptureDiagnosticConsumer *CaptureDiag = 0;
541 if (CaptureDiagnostics)
542 CaptureDiag = new CaptureDiagnosticConsumer();
544 // Configure the diagnostics.
545 IntrusiveRefCntPtr<DiagnosticsEngine>
546 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions,
548 /*ShouldOwnClient=*/true));
550 // Recover resources if we crash before exiting this function.
551 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
552 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
553 DiagCleanup(Diags.getPtr());
555 OwningPtr<std::vector<const char *> >
556 Args(new std::vector<const char*>());
558 // Recover resources if we crash before exiting this method.
559 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
560 ArgsCleanup(Args.get());
562 Args->insert(Args->end(), command_line_args,
563 command_line_args + num_command_line_args);
565 // The 'source_filename' argument is optional. If the caller does not
566 // specify it then it is assumed that the source file is specified
567 // in the actual argument list.
568 // Put the source file after command_line_args otherwise if '-x' flag is
569 // present it will be unused.
571 Args->push_back(source_filename);
573 IntrusiveRefCntPtr<CompilerInvocation>
574 CInvok(createInvocationFromCommandLine(*Args, Diags));
579 // Recover resources if we crash before exiting this function.
580 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInvocation,
581 llvm::CrashRecoveryContextReleaseRefCleanup<CompilerInvocation> >
582 CInvokCleanup(CInvok.getPtr());
584 if (CInvok->getFrontendOpts().Inputs.empty())
587 OwningPtr<MemBufferOwner> BufOwner(new MemBufferOwner());
589 // Recover resources if we crash before exiting this method.
590 llvm::CrashRecoveryContextCleanupRegistrar<MemBufferOwner>
591 BufOwnerCleanup(BufOwner.get());
593 for (unsigned I = 0; I != num_unsaved_files; ++I) {
594 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
595 const llvm::MemoryBuffer *Buffer
596 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
597 CInvok->getPreprocessorOpts().addRemappedFile(unsaved_files[I].Filename, Buffer);
598 BufOwner->Buffers.push_back(Buffer);
601 // Since libclang is primarily used by batch tools dealing with
602 // (often very broken) source code, where spell-checking can have a
603 // significant negative impact on performance (particularly when
604 // precompiled headers are involved), we disable it.
605 CInvok->getLangOpts()->SpellChecking = false;
607 if (index_options & CXIndexOpt_SuppressWarnings)
608 CInvok->getDiagnosticOpts().IgnoreWarnings = true;
610 ASTUnit *Unit = ASTUnit::create(CInvok.getPtr(), Diags,
612 /*UserFilesAreVolatile=*/true);
613 OwningPtr<CXTUOwner> CXTU(new CXTUOwner(MakeCXTranslationUnit(CXXIdx, Unit)));
615 // Recover resources if we crash before exiting this method.
616 llvm::CrashRecoveryContextCleanupRegistrar<CXTUOwner>
617 CXTUCleanup(CXTU.get());
619 // Enable the skip-parsed-bodies optimization only for C++; this may be
621 bool SkipBodies = (index_options & CXIndexOpt_SkipParsedBodiesInSession) &&
622 CInvok->getLangOpts()->CPlusPlus;
624 CInvok->getFrontendOpts().SkipFunctionBodies = true;
626 OwningPtr<IndexingFrontendAction> IndexAction;
627 IndexAction.reset(new IndexingFrontendAction(client_data, CB,
628 index_options, CXTU->getTU(),
629 SkipBodies ? IdxSession->SkipBodyData.get() : 0));
631 // Recover resources if we crash before exiting this method.
632 llvm::CrashRecoveryContextCleanupRegistrar<IndexingFrontendAction>
633 IndexActionCleanup(IndexAction.get());
635 bool Persistent = requestedToGetTU;
636 bool OnlyLocalDecls = false;
637 bool PrecompilePreamble = false;
638 bool CacheCodeCompletionResults = false;
639 PreprocessorOptions &PPOpts = CInvok->getPreprocessorOpts();
640 PPOpts.AllowPCHWithCompilerErrors = true;
642 if (requestedToGetTU) {
643 OnlyLocalDecls = CXXIdx->getOnlyLocalDecls();
644 PrecompilePreamble = TU_options & CXTranslationUnit_PrecompiledPreamble;
645 // FIXME: Add a flag for modules.
646 CacheCodeCompletionResults
647 = TU_options & CXTranslationUnit_CacheCompletionResults;
650 if (TU_options & CXTranslationUnit_DetailedPreprocessingRecord) {
651 PPOpts.DetailedRecord = true;
654 if (!requestedToGetTU && !CInvok->getLangOpts()->Modules)
655 PPOpts.DetailedRecord = false;
657 DiagnosticErrorTrap DiagTrap(*Diags);
658 bool Success = ASTUnit::LoadFromCompilerInvocationAction(CInvok.getPtr(), Diags,
662 CXXIdx->getClangResourcesPath(),
666 CacheCodeCompletionResults,
667 /*IncludeBriefCommentsInCodeCompletion=*/false,
668 /*UserFilesAreVolatile=*/true);
669 if (DiagTrap.hasErrorOccurred() && CXXIdx->getDisplayDiagnostics())
670 printDiagsToStderr(Unit);
676 *out_TU = CXTU->takeTU();
678 ITUI->result = 0; // success.
681 //===----------------------------------------------------------------------===//
682 // clang_indexTranslationUnit Implementation
683 //===----------------------------------------------------------------------===//
687 struct IndexTranslationUnitInfo {
688 CXIndexAction idxAction;
689 CXClientData client_data;
690 IndexerCallbacks *index_callbacks;
691 unsigned index_callbacks_size;
692 unsigned index_options;
693 CXTranslationUnit TU;
697 } // anonymous namespace
699 static void indexPreprocessingRecord(ASTUnit &Unit, IndexingContext &IdxCtx) {
700 Preprocessor &PP = Unit.getPreprocessor();
701 if (!PP.getPreprocessingRecord())
704 // FIXME: Only deserialize inclusion directives.
706 PreprocessingRecord::iterator I, E;
707 llvm::tie(I, E) = Unit.getLocalPreprocessingEntities();
709 bool isModuleFile = Unit.isModuleFile();
710 for (; I != E; ++I) {
711 PreprocessedEntity *PPE = *I;
713 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
714 SourceLocation Loc = ID->getSourceRange().getBegin();
715 // Modules have synthetic main files as input, give an invalid location
716 // if the location points to such a file.
717 if (isModuleFile && Unit.isInMainFileID(Loc))
718 Loc = SourceLocation();
719 IdxCtx.ppIncludedFile(Loc, ID->getFileName(),
721 ID->getKind() == InclusionDirective::Import,
722 !ID->wasInQuotes(), ID->importedModule());
727 static bool topLevelDeclVisitor(void *context, const Decl *D) {
728 IndexingContext &IdxCtx = *static_cast<IndexingContext*>(context);
729 IdxCtx.indexTopLevelDecl(D);
730 if (IdxCtx.shouldAbort())
735 static void indexTranslationUnit(ASTUnit &Unit, IndexingContext &IdxCtx) {
736 Unit.visitLocalTopLevelDecls(&IdxCtx, topLevelDeclVisitor);
739 static void indexDiagnostics(CXTranslationUnit TU, IndexingContext &IdxCtx) {
740 if (!IdxCtx.hasDiagnosticCallback())
743 CXDiagnosticSetImpl *DiagSet = cxdiag::lazyCreateDiags(TU);
744 IdxCtx.handleDiagnosticSet(DiagSet);
747 static void clang_indexTranslationUnit_Impl(void *UserData) {
748 IndexTranslationUnitInfo *ITUI =
749 static_cast<IndexTranslationUnitInfo*>(UserData);
750 CXTranslationUnit TU = ITUI->TU;
751 CXClientData client_data = ITUI->client_data;
752 IndexerCallbacks *client_index_callbacks = ITUI->index_callbacks;
753 unsigned index_callbacks_size = ITUI->index_callbacks_size;
754 unsigned index_options = ITUI->index_options;
755 ITUI->result = 1; // init as error.
759 if (!client_index_callbacks || index_callbacks_size == 0)
762 CIndexer *CXXIdx = TU->CIdx;
763 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
764 setThreadBackgroundPriority();
767 memset(&CB, 0, sizeof(CB));
768 unsigned ClientCBSize = index_callbacks_size < sizeof(CB)
769 ? index_callbacks_size : sizeof(CB);
770 memcpy(&CB, client_index_callbacks, ClientCBSize);
772 OwningPtr<IndexingContext> IndexCtx;
773 IndexCtx.reset(new IndexingContext(client_data, CB, index_options, TU));
775 // Recover resources if we crash before exiting this method.
776 llvm::CrashRecoveryContextCleanupRegistrar<IndexingContext>
777 IndexCtxCleanup(IndexCtx.get());
779 OwningPtr<IndexingConsumer> IndexConsumer;
780 IndexConsumer.reset(new IndexingConsumer(*IndexCtx, 0));
782 // Recover resources if we crash before exiting this method.
783 llvm::CrashRecoveryContextCleanupRegistrar<IndexingConsumer>
784 IndexConsumerCleanup(IndexConsumer.get());
786 ASTUnit *Unit = cxtu::getASTUnit(TU);
790 ASTUnit::ConcurrencyCheck Check(*Unit);
792 if (const FileEntry *PCHFile = Unit->getPCHFile())
793 IndexCtx->importedPCH(PCHFile);
795 FileManager &FileMgr = Unit->getFileManager();
797 if (Unit->getOriginalSourceFileName().empty())
798 IndexCtx->enteredMainFile(0);
800 IndexCtx->enteredMainFile(FileMgr.getFile(Unit->getOriginalSourceFileName()));
802 IndexConsumer->Initialize(Unit->getASTContext());
804 indexPreprocessingRecord(*Unit, *IndexCtx);
805 indexTranslationUnit(*Unit, *IndexCtx);
806 indexDiagnostics(TU, *IndexCtx);
811 //===----------------------------------------------------------------------===//
812 // libclang public APIs.
813 //===----------------------------------------------------------------------===//
817 int clang_index_isEntityObjCContainerKind(CXIdxEntityKind K) {
818 return CXIdxEntity_ObjCClass <= K && K <= CXIdxEntity_ObjCCategory;
821 const CXIdxObjCContainerDeclInfo *
822 clang_index_getObjCContainerDeclInfo(const CXIdxDeclInfo *DInfo) {
826 const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo);
827 if (const ObjCContainerDeclInfo *
828 ContInfo = dyn_cast<ObjCContainerDeclInfo>(DI))
829 return &ContInfo->ObjCContDeclInfo;
834 const CXIdxObjCInterfaceDeclInfo *
835 clang_index_getObjCInterfaceDeclInfo(const CXIdxDeclInfo *DInfo) {
839 const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo);
840 if (const ObjCInterfaceDeclInfo *
841 InterInfo = dyn_cast<ObjCInterfaceDeclInfo>(DI))
842 return &InterInfo->ObjCInterDeclInfo;
847 const CXIdxObjCCategoryDeclInfo *
848 clang_index_getObjCCategoryDeclInfo(const CXIdxDeclInfo *DInfo){
852 const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo);
853 if (const ObjCCategoryDeclInfo *
854 CatInfo = dyn_cast<ObjCCategoryDeclInfo>(DI))
855 return &CatInfo->ObjCCatDeclInfo;
860 const CXIdxObjCProtocolRefListInfo *
861 clang_index_getObjCProtocolRefListInfo(const CXIdxDeclInfo *DInfo) {
865 const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo);
867 if (const ObjCInterfaceDeclInfo *
868 InterInfo = dyn_cast<ObjCInterfaceDeclInfo>(DI))
869 return InterInfo->ObjCInterDeclInfo.protocols;
871 if (const ObjCProtocolDeclInfo *
872 ProtInfo = dyn_cast<ObjCProtocolDeclInfo>(DI))
873 return &ProtInfo->ObjCProtoRefListInfo;
875 if (const ObjCCategoryDeclInfo *CatInfo = dyn_cast<ObjCCategoryDeclInfo>(DI))
876 return CatInfo->ObjCCatDeclInfo.protocols;
881 const CXIdxObjCPropertyDeclInfo *
882 clang_index_getObjCPropertyDeclInfo(const CXIdxDeclInfo *DInfo) {
886 const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo);
887 if (const ObjCPropertyDeclInfo *PropInfo = dyn_cast<ObjCPropertyDeclInfo>(DI))
888 return &PropInfo->ObjCPropDeclInfo;
893 const CXIdxIBOutletCollectionAttrInfo *
894 clang_index_getIBOutletCollectionAttrInfo(const CXIdxAttrInfo *AInfo) {
898 const AttrInfo *DI = static_cast<const AttrInfo *>(AInfo);
899 if (const IBOutletCollectionInfo *
900 IBInfo = dyn_cast<IBOutletCollectionInfo>(DI))
901 return &IBInfo->IBCollInfo;
906 const CXIdxCXXClassDeclInfo *
907 clang_index_getCXXClassDeclInfo(const CXIdxDeclInfo *DInfo) {
911 const DeclInfo *DI = static_cast<const DeclInfo *>(DInfo);
912 if (const CXXClassDeclInfo *ClassInfo = dyn_cast<CXXClassDeclInfo>(DI))
913 return &ClassInfo->CXXClassInfo;
919 clang_index_getClientContainer(const CXIdxContainerInfo *info) {
922 const ContainerInfo *Container = static_cast<const ContainerInfo *>(info);
923 return Container->IndexCtx->getClientContainerForDC(Container->DC);
926 void clang_index_setClientContainer(const CXIdxContainerInfo *info,
927 CXIdxClientContainer client) {
930 const ContainerInfo *Container = static_cast<const ContainerInfo *>(info);
931 Container->IndexCtx->addContainerInMap(Container->DC, client);
934 CXIdxClientEntity clang_index_getClientEntity(const CXIdxEntityInfo *info) {
937 const EntityInfo *Entity = static_cast<const EntityInfo *>(info);
938 return Entity->IndexCtx->getClientEntity(Entity->Dcl);
941 void clang_index_setClientEntity(const CXIdxEntityInfo *info,
942 CXIdxClientEntity client) {
945 const EntityInfo *Entity = static_cast<const EntityInfo *>(info);
946 Entity->IndexCtx->setClientEntity(Entity->Dcl, client);
949 CXIndexAction clang_IndexAction_create(CXIndex CIdx) {
950 return new IndexSessionData(CIdx);
953 void clang_IndexAction_dispose(CXIndexAction idxAction) {
955 delete static_cast<IndexSessionData *>(idxAction);
958 int clang_indexSourceFile(CXIndexAction idxAction,
959 CXClientData client_data,
960 IndexerCallbacks *index_callbacks,
961 unsigned index_callbacks_size,
962 unsigned index_options,
963 const char *source_filename,
964 const char * const *command_line_args,
965 int num_command_line_args,
966 struct CXUnsavedFile *unsaved_files,
967 unsigned num_unsaved_files,
968 CXTranslationUnit *out_TU,
969 unsigned TU_options) {
971 *Log << source_filename << ": ";
972 for (int i = 0; i != num_command_line_args; ++i)
973 *Log << command_line_args[i] << " ";
976 IndexSourceFileInfo ITUI = { idxAction, client_data, index_callbacks,
977 index_callbacks_size, index_options,
978 source_filename, command_line_args,
979 num_command_line_args, unsaved_files,
980 num_unsaved_files, out_TU, TU_options, 0 };
982 if (getenv("LIBCLANG_NOTHREADS")) {
983 clang_indexSourceFile_Impl(&ITUI);
987 llvm::CrashRecoveryContext CRC;
989 if (!RunSafely(CRC, clang_indexSourceFile_Impl, &ITUI)) {
990 fprintf(stderr, "libclang: crash detected during indexing source file: {\n");
991 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
992 fprintf(stderr, " 'command_line_args' : [");
993 for (int i = 0; i != num_command_line_args; ++i) {
995 fprintf(stderr, ", ");
996 fprintf(stderr, "'%s'", command_line_args[i]);
998 fprintf(stderr, "],\n");
999 fprintf(stderr, " 'unsaved_files' : [");
1000 for (unsigned i = 0; i != num_unsaved_files; ++i) {
1002 fprintf(stderr, ", ");
1003 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
1004 unsaved_files[i].Length);
1006 fprintf(stderr, "],\n");
1007 fprintf(stderr, " 'options' : %d,\n", TU_options);
1008 fprintf(stderr, "}\n");
1011 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
1013 PrintLibclangResourceUsage(*out_TU);
1019 int clang_indexTranslationUnit(CXIndexAction idxAction,
1020 CXClientData client_data,
1021 IndexerCallbacks *index_callbacks,
1022 unsigned index_callbacks_size,
1023 unsigned index_options,
1024 CXTranslationUnit TU) {
1029 IndexTranslationUnitInfo ITUI = { idxAction, client_data, index_callbacks,
1030 index_callbacks_size, index_options, TU,
1033 if (getenv("LIBCLANG_NOTHREADS")) {
1034 clang_indexTranslationUnit_Impl(&ITUI);
1038 llvm::CrashRecoveryContext CRC;
1040 if (!RunSafely(CRC, clang_indexTranslationUnit_Impl, &ITUI)) {
1041 fprintf(stderr, "libclang: crash detected during indexing TU\n");
1049 void clang_indexLoc_getFileLocation(CXIdxLoc location,
1050 CXIdxClientFile *indexFile,
1055 if (indexFile) *indexFile = 0;
1056 if (file) *file = 0;
1057 if (line) *line = 0;
1058 if (column) *column = 0;
1059 if (offset) *offset = 0;
1061 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1062 if (!location.ptr_data[0] || Loc.isInvalid())
1065 IndexingContext &IndexCtx =
1066 *static_cast<IndexingContext*>(location.ptr_data[0]);
1067 IndexCtx.translateLoc(Loc, indexFile, file, line, column, offset);
1070 CXSourceLocation clang_indexLoc_getCXSourceLocation(CXIdxLoc location) {
1071 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1072 if (!location.ptr_data[0] || Loc.isInvalid())
1073 return clang_getNullLocation();
1075 IndexingContext &IndexCtx =
1076 *static_cast<IndexingContext*>(location.ptr_data[0]);
1077 return cxloc::translateSourceLocation(IndexCtx.getASTContext(), Loc);
1080 } // end: extern "C"