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