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