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