1 //===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===// 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 // This file implements the main API hooks in the Clang-C Source Indexing 10 // library. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CIndexDiagnostic.h" 15 #include "CIndexer.h" 16 #include "CLog.h" 17 #include "CXCursor.h" 18 #include "CXSourceLocation.h" 19 #include "CXString.h" 20 #include "CXTranslationUnit.h" 21 #include "CXType.h" 22 #include "CursorVisitor.h" 23 #include "clang-c/FatalErrorHandler.h" 24 #include "clang/AST/Attr.h" 25 #include "clang/AST/DeclObjCCommon.h" 26 #include "clang/AST/Mangle.h" 27 #include "clang/AST/OpenMPClause.h" 28 #include "clang/AST/StmtVisitor.h" 29 #include "clang/Basic/Diagnostic.h" 30 #include "clang/Basic/DiagnosticCategories.h" 31 #include "clang/Basic/DiagnosticIDs.h" 32 #include "clang/Basic/Stack.h" 33 #include "clang/Basic/TargetInfo.h" 34 #include "clang/Basic/Version.h" 35 #include "clang/Frontend/ASTUnit.h" 36 #include "clang/Frontend/CompilerInstance.h" 37 #include "clang/Index/CommentToXML.h" 38 #include "clang/Lex/HeaderSearch.h" 39 #include "clang/Lex/Lexer.h" 40 #include "clang/Lex/PreprocessingRecord.h" 41 #include "clang/Lex/Preprocessor.h" 42 #include "llvm/ADT/Optional.h" 43 #include "llvm/ADT/STLExtras.h" 44 #include "llvm/ADT/StringSwitch.h" 45 #include "llvm/Config/llvm-config.h" 46 #include "llvm/Support/Compiler.h" 47 #include "llvm/Support/CrashRecoveryContext.h" 48 #include "llvm/Support/Format.h" 49 #include "llvm/Support/ManagedStatic.h" 50 #include "llvm/Support/MemoryBuffer.h" 51 #include "llvm/Support/Program.h" 52 #include "llvm/Support/SaveAndRestore.h" 53 #include "llvm/Support/Signals.h" 54 #include "llvm/Support/TargetSelect.h" 55 #include "llvm/Support/Threading.h" 56 #include "llvm/Support/Timer.h" 57 #include "llvm/Support/raw_ostream.h" 58 #include "llvm/Support/thread.h" 59 #include <mutex> 60 61 #if LLVM_ENABLE_THREADS != 0 && defined(__APPLE__) 62 #define USE_DARWIN_THREADS 63 #endif 64 65 #ifdef USE_DARWIN_THREADS 66 #include <pthread.h> 67 #endif 68 69 using namespace clang; 70 using namespace clang::cxcursor; 71 using namespace clang::cxtu; 72 using namespace clang::cxindex; 73 74 CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx, 75 std::unique_ptr<ASTUnit> AU) { 76 if (!AU) 77 return nullptr; 78 assert(CIdx); 79 CXTranslationUnit D = new CXTranslationUnitImpl(); 80 D->CIdx = CIdx; 81 D->TheASTUnit = AU.release(); 82 D->StringPool = new cxstring::CXStringPool(); 83 D->Diagnostics = nullptr; 84 D->OverridenCursorsPool = createOverridenCXCursorsPool(); 85 D->CommentToXML = nullptr; 86 D->ParsingOptions = 0; 87 D->Arguments = {}; 88 return D; 89 } 90 91 bool cxtu::isASTReadError(ASTUnit *AU) { 92 for (ASTUnit::stored_diag_iterator D = AU->stored_diag_begin(), 93 DEnd = AU->stored_diag_end(); 94 D != DEnd; ++D) { 95 if (D->getLevel() >= DiagnosticsEngine::Error && 96 DiagnosticIDs::getCategoryNumberForDiag(D->getID()) == 97 diag::DiagCat_AST_Deserialization_Issue) 98 return true; 99 } 100 return false; 101 } 102 103 cxtu::CXTUOwner::~CXTUOwner() { 104 if (TU) 105 clang_disposeTranslationUnit(TU); 106 } 107 108 /// Compare two source ranges to determine their relative position in 109 /// the translation unit. 110 static RangeComparisonResult RangeCompare(SourceManager &SM, SourceRange R1, 111 SourceRange R2) { 112 assert(R1.isValid() && "First range is invalid?"); 113 assert(R2.isValid() && "Second range is invalid?"); 114 if (R1.getEnd() != R2.getBegin() && 115 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin())) 116 return RangeBefore; 117 if (R2.getEnd() != R1.getBegin() && 118 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin())) 119 return RangeAfter; 120 return RangeOverlap; 121 } 122 123 /// Determine if a source location falls within, before, or after a 124 /// a given source range. 125 static RangeComparisonResult LocationCompare(SourceManager &SM, 126 SourceLocation L, SourceRange R) { 127 assert(R.isValid() && "First range is invalid?"); 128 assert(L.isValid() && "Second range is invalid?"); 129 if (L == R.getBegin() || L == R.getEnd()) 130 return RangeOverlap; 131 if (SM.isBeforeInTranslationUnit(L, R.getBegin())) 132 return RangeBefore; 133 if (SM.isBeforeInTranslationUnit(R.getEnd(), L)) 134 return RangeAfter; 135 return RangeOverlap; 136 } 137 138 /// Translate a Clang source range into a CIndex source range. 139 /// 140 /// Clang internally represents ranges where the end location points to the 141 /// start of the token at the end. However, for external clients it is more 142 /// useful to have a CXSourceRange be a proper half-open interval. This routine 143 /// does the appropriate translation. 144 CXSourceRange cxloc::translateSourceRange(const SourceManager &SM, 145 const LangOptions &LangOpts, 146 const CharSourceRange &R) { 147 // We want the last character in this location, so we will adjust the 148 // location accordingly. 149 SourceLocation EndLoc = R.getEnd(); 150 bool IsTokenRange = R.isTokenRange(); 151 if (EndLoc.isValid() && EndLoc.isMacroID() && 152 !SM.isMacroArgExpansion(EndLoc)) { 153 CharSourceRange Expansion = SM.getExpansionRange(EndLoc); 154 EndLoc = Expansion.getEnd(); 155 IsTokenRange = Expansion.isTokenRange(); 156 } 157 if (IsTokenRange && EndLoc.isValid()) { 158 unsigned Length = 159 Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc), SM, LangOpts); 160 EndLoc = EndLoc.getLocWithOffset(Length); 161 } 162 163 CXSourceRange Result = { 164 {&SM, &LangOpts}, R.getBegin().getRawEncoding(), EndLoc.getRawEncoding()}; 165 return Result; 166 } 167 168 CharSourceRange cxloc::translateCXRangeToCharRange(CXSourceRange R) { 169 return CharSourceRange::getCharRange( 170 SourceLocation::getFromRawEncoding(R.begin_int_data), 171 SourceLocation::getFromRawEncoding(R.end_int_data)); 172 } 173 174 //===----------------------------------------------------------------------===// 175 // Cursor visitor. 176 //===----------------------------------------------------------------------===// 177 178 static SourceRange getRawCursorExtent(CXCursor C); 179 static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr); 180 181 RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) { 182 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest); 183 } 184 185 /// Visit the given cursor and, if requested by the visitor, 186 /// its children. 187 /// 188 /// \param Cursor the cursor to visit. 189 /// 190 /// \param CheckedRegionOfInterest if true, then the caller already checked 191 /// that this cursor is within the region of interest. 192 /// 193 /// \returns true if the visitation should be aborted, false if it 194 /// should continue. 195 bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) { 196 if (clang_isInvalid(Cursor.kind)) 197 return false; 198 199 if (clang_isDeclaration(Cursor.kind)) { 200 const Decl *D = getCursorDecl(Cursor); 201 if (!D) { 202 assert(0 && "Invalid declaration cursor"); 203 return true; // abort. 204 } 205 206 // Ignore implicit declarations, unless it's an objc method because 207 // currently we should report implicit methods for properties when indexing. 208 if (D->isImplicit() && !isa<ObjCMethodDecl>(D)) 209 return false; 210 } 211 212 // If we have a range of interest, and this cursor doesn't intersect with it, 213 // we're done. 214 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) { 215 SourceRange Range = getRawCursorExtent(Cursor); 216 if (Range.isInvalid() || CompareRegionOfInterest(Range)) 217 return false; 218 } 219 220 switch (Visitor(Cursor, Parent, ClientData)) { 221 case CXChildVisit_Break: 222 return true; 223 224 case CXChildVisit_Continue: 225 return false; 226 227 case CXChildVisit_Recurse: { 228 bool ret = VisitChildren(Cursor); 229 if (PostChildrenVisitor) 230 if (PostChildrenVisitor(Cursor, ClientData)) 231 return true; 232 return ret; 233 } 234 } 235 236 llvm_unreachable("Invalid CXChildVisitResult!"); 237 } 238 239 static bool visitPreprocessedEntitiesInRange(SourceRange R, 240 PreprocessingRecord &PPRec, 241 CursorVisitor &Visitor) { 242 SourceManager &SM = Visitor.getASTUnit()->getSourceManager(); 243 FileID FID; 244 245 if (!Visitor.shouldVisitIncludedEntities()) { 246 // If the begin/end of the range lie in the same FileID, do the optimization 247 // where we skip preprocessed entities that do not come from the same 248 // FileID. 249 FID = SM.getFileID(SM.getFileLoc(R.getBegin())); 250 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd()))) 251 FID = FileID(); 252 } 253 254 const auto &Entities = PPRec.getPreprocessedEntitiesInRange(R); 255 return Visitor.visitPreprocessedEntities(Entities.begin(), Entities.end(), 256 PPRec, FID); 257 } 258 259 bool CursorVisitor::visitFileRegion() { 260 if (RegionOfInterest.isInvalid()) 261 return false; 262 263 ASTUnit *Unit = cxtu::getASTUnit(TU); 264 SourceManager &SM = Unit->getSourceManager(); 265 266 std::pair<FileID, unsigned> Begin = SM.getDecomposedLoc( 267 SM.getFileLoc(RegionOfInterest.getBegin())), 268 End = SM.getDecomposedLoc( 269 SM.getFileLoc(RegionOfInterest.getEnd())); 270 271 if (End.first != Begin.first) { 272 // If the end does not reside in the same file, try to recover by 273 // picking the end of the file of begin location. 274 End.first = Begin.first; 275 End.second = SM.getFileIDSize(Begin.first); 276 } 277 278 assert(Begin.first == End.first); 279 if (Begin.second > End.second) 280 return false; 281 282 FileID File = Begin.first; 283 unsigned Offset = Begin.second; 284 unsigned Length = End.second - Begin.second; 285 286 if (!VisitDeclsOnly && !VisitPreprocessorLast) 287 if (visitPreprocessedEntitiesInRegion()) 288 return true; // visitation break. 289 290 if (visitDeclsFromFileRegion(File, Offset, Length)) 291 return true; // visitation break. 292 293 if (!VisitDeclsOnly && VisitPreprocessorLast) 294 return visitPreprocessedEntitiesInRegion(); 295 296 return false; 297 } 298 299 static bool isInLexicalContext(Decl *D, DeclContext *DC) { 300 if (!DC) 301 return false; 302 303 for (DeclContext *DeclDC = D->getLexicalDeclContext(); DeclDC; 304 DeclDC = DeclDC->getLexicalParent()) { 305 if (DeclDC == DC) 306 return true; 307 } 308 return false; 309 } 310 311 bool CursorVisitor::visitDeclsFromFileRegion(FileID File, unsigned Offset, 312 unsigned Length) { 313 ASTUnit *Unit = cxtu::getASTUnit(TU); 314 SourceManager &SM = Unit->getSourceManager(); 315 SourceRange Range = RegionOfInterest; 316 317 SmallVector<Decl *, 16> Decls; 318 Unit->findFileRegionDecls(File, Offset, Length, Decls); 319 320 // If we didn't find any file level decls for the file, try looking at the 321 // file that it was included from. 322 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) { 323 bool Invalid = false; 324 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid); 325 if (Invalid) 326 return false; 327 328 SourceLocation Outer; 329 if (SLEntry.isFile()) 330 Outer = SLEntry.getFile().getIncludeLoc(); 331 else 332 Outer = SLEntry.getExpansion().getExpansionLocStart(); 333 if (Outer.isInvalid()) 334 return false; 335 336 std::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer); 337 Length = 0; 338 Unit->findFileRegionDecls(File, Offset, Length, Decls); 339 } 340 341 assert(!Decls.empty()); 342 343 bool VisitedAtLeastOnce = false; 344 DeclContext *CurDC = nullptr; 345 SmallVectorImpl<Decl *>::iterator DIt = Decls.begin(); 346 for (SmallVectorImpl<Decl *>::iterator DE = Decls.end(); DIt != DE; ++DIt) { 347 Decl *D = *DIt; 348 if (D->getSourceRange().isInvalid()) 349 continue; 350 351 if (isInLexicalContext(D, CurDC)) 352 continue; 353 354 CurDC = dyn_cast<DeclContext>(D); 355 356 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 357 if (!TD->isFreeStanding()) 358 continue; 359 360 RangeComparisonResult CompRes = 361 RangeCompare(SM, D->getSourceRange(), Range); 362 if (CompRes == RangeBefore) 363 continue; 364 if (CompRes == RangeAfter) 365 break; 366 367 assert(CompRes == RangeOverlap); 368 VisitedAtLeastOnce = true; 369 370 if (isa<ObjCContainerDecl>(D)) { 371 FileDI_current = &DIt; 372 FileDE_current = DE; 373 } else { 374 FileDI_current = nullptr; 375 } 376 377 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true)) 378 return true; // visitation break. 379 } 380 381 if (VisitedAtLeastOnce) 382 return false; 383 384 // No Decls overlapped with the range. Move up the lexical context until there 385 // is a context that contains the range or we reach the translation unit 386 // level. 387 DeclContext *DC = DIt == Decls.begin() 388 ? (*DIt)->getLexicalDeclContext() 389 : (*(DIt - 1))->getLexicalDeclContext(); 390 391 while (DC && !DC->isTranslationUnit()) { 392 Decl *D = cast<Decl>(DC); 393 SourceRange CurDeclRange = D->getSourceRange(); 394 if (CurDeclRange.isInvalid()) 395 break; 396 397 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) { 398 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true)) 399 return true; // visitation break. 400 } 401 402 DC = D->getLexicalDeclContext(); 403 } 404 405 return false; 406 } 407 408 bool CursorVisitor::visitPreprocessedEntitiesInRegion() { 409 if (!AU->getPreprocessor().getPreprocessingRecord()) 410 return false; 411 412 PreprocessingRecord &PPRec = *AU->getPreprocessor().getPreprocessingRecord(); 413 SourceManager &SM = AU->getSourceManager(); 414 415 if (RegionOfInterest.isValid()) { 416 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest); 417 SourceLocation B = MappedRange.getBegin(); 418 SourceLocation E = MappedRange.getEnd(); 419 420 if (AU->isInPreambleFileID(B)) { 421 if (SM.isLoadedSourceLocation(E)) 422 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, 423 *this); 424 425 // Beginning of range lies in the preamble but it also extends beyond 426 // it into the main file. Split the range into 2 parts, one covering 427 // the preamble and another covering the main file. This allows subsequent 428 // calls to visitPreprocessedEntitiesInRange to accept a source range that 429 // lies in the same FileID, allowing it to skip preprocessed entities that 430 // do not come from the same FileID. 431 bool breaked = visitPreprocessedEntitiesInRange( 432 SourceRange(B, AU->getEndOfPreambleFileID()), PPRec, *this); 433 if (breaked) 434 return true; 435 return visitPreprocessedEntitiesInRange( 436 SourceRange(AU->getStartOfMainFileID(), E), PPRec, *this); 437 } 438 439 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this); 440 } 441 442 bool OnlyLocalDecls = !AU->isMainFileAST() && AU->getOnlyLocalDecls(); 443 444 if (OnlyLocalDecls) 445 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(), 446 PPRec); 447 448 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec); 449 } 450 451 template <typename InputIterator> 452 bool CursorVisitor::visitPreprocessedEntities(InputIterator First, 453 InputIterator Last, 454 PreprocessingRecord &PPRec, 455 FileID FID) { 456 for (; First != Last; ++First) { 457 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID)) 458 continue; 459 460 PreprocessedEntity *PPE = *First; 461 if (!PPE) 462 continue; 463 464 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) { 465 if (Visit(MakeMacroExpansionCursor(ME, TU))) 466 return true; 467 468 continue; 469 } 470 471 if (MacroDefinitionRecord *MD = dyn_cast<MacroDefinitionRecord>(PPE)) { 472 if (Visit(MakeMacroDefinitionCursor(MD, TU))) 473 return true; 474 475 continue; 476 } 477 478 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) { 479 if (Visit(MakeInclusionDirectiveCursor(ID, TU))) 480 return true; 481 482 continue; 483 } 484 } 485 486 return false; 487 } 488 489 /// Visit the children of the given cursor. 490 /// 491 /// \returns true if the visitation should be aborted, false if it 492 /// should continue. 493 bool CursorVisitor::VisitChildren(CXCursor Cursor) { 494 if (clang_isReference(Cursor.kind) && 495 Cursor.kind != CXCursor_CXXBaseSpecifier) { 496 // By definition, references have no children. 497 return false; 498 } 499 500 // Set the Parent field to Cursor, then back to its old value once we're 501 // done. 502 SetParentRAII SetParent(Parent, StmtParent, Cursor); 503 504 if (clang_isDeclaration(Cursor.kind)) { 505 Decl *D = const_cast<Decl *>(getCursorDecl(Cursor)); 506 if (!D) 507 return false; 508 509 return VisitAttributes(D) || Visit(D); 510 } 511 512 if (clang_isStatement(Cursor.kind)) { 513 if (const Stmt *S = getCursorStmt(Cursor)) 514 return Visit(S); 515 516 return false; 517 } 518 519 if (clang_isExpression(Cursor.kind)) { 520 if (const Expr *E = getCursorExpr(Cursor)) 521 return Visit(E); 522 523 return false; 524 } 525 526 if (clang_isTranslationUnit(Cursor.kind)) { 527 CXTranslationUnit TU = getCursorTU(Cursor); 528 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 529 530 int VisitOrder[2] = {VisitPreprocessorLast, !VisitPreprocessorLast}; 531 for (unsigned I = 0; I != 2; ++I) { 532 if (VisitOrder[I]) { 533 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() && 534 RegionOfInterest.isInvalid()) { 535 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(), 536 TLEnd = CXXUnit->top_level_end(); 537 TL != TLEnd; ++TL) { 538 const Optional<bool> V = handleDeclForVisitation(*TL); 539 if (!V.hasValue()) 540 continue; 541 return V.getValue(); 542 } 543 } else if (VisitDeclContext( 544 CXXUnit->getASTContext().getTranslationUnitDecl())) 545 return true; 546 continue; 547 } 548 549 // Walk the preprocessing record. 550 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) 551 visitPreprocessedEntitiesInRegion(); 552 } 553 554 return false; 555 } 556 557 if (Cursor.kind == CXCursor_CXXBaseSpecifier) { 558 if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) { 559 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) { 560 return Visit(BaseTSInfo->getTypeLoc()); 561 } 562 } 563 } 564 565 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) { 566 const IBOutletCollectionAttr *A = 567 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor)); 568 if (const ObjCObjectType *ObjT = A->getInterface()->getAs<ObjCObjectType>()) 569 return Visit(cxcursor::MakeCursorObjCClassRef( 570 ObjT->getInterface(), 571 A->getInterfaceLoc()->getTypeLoc().getBeginLoc(), TU)); 572 } 573 574 // If pointing inside a macro definition, check if the token is an identifier 575 // that was ever defined as a macro. In such a case, create a "pseudo" macro 576 // expansion cursor for that token. 577 SourceLocation BeginLoc = RegionOfInterest.getBegin(); 578 if (Cursor.kind == CXCursor_MacroDefinition && 579 BeginLoc == RegionOfInterest.getEnd()) { 580 SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc); 581 const MacroInfo *MI = 582 getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU); 583 if (MacroDefinitionRecord *MacroDef = 584 checkForMacroInMacroDefinition(MI, Loc, TU)) 585 return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU)); 586 } 587 588 // Nothing to visit at the moment. 589 return false; 590 } 591 592 bool CursorVisitor::VisitBlockDecl(BlockDecl *B) { 593 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten()) 594 if (Visit(TSInfo->getTypeLoc())) 595 return true; 596 597 if (Stmt *Body = B->getBody()) 598 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest)); 599 600 return false; 601 } 602 603 Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) { 604 if (RegionOfInterest.isValid()) { 605 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager()); 606 if (Range.isInvalid()) 607 return None; 608 609 switch (CompareRegionOfInterest(Range)) { 610 case RangeBefore: 611 // This declaration comes before the region of interest; skip it. 612 return None; 613 614 case RangeAfter: 615 // This declaration comes after the region of interest; we're done. 616 return false; 617 618 case RangeOverlap: 619 // This declaration overlaps the region of interest; visit it. 620 break; 621 } 622 } 623 return true; 624 } 625 626 bool CursorVisitor::VisitDeclContext(DeclContext *DC) { 627 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end(); 628 629 // FIXME: Eventually remove. This part of a hack to support proper 630 // iteration over all Decls contained lexically within an ObjC container. 631 SaveAndRestore<DeclContext::decl_iterator *> DI_saved(DI_current, &I); 632 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E); 633 634 for (; I != E; ++I) { 635 Decl *D = *I; 636 if (D->getLexicalDeclContext() != DC) 637 continue; 638 // Filter out synthesized property accessor redeclarations. 639 if (isa<ObjCImplDecl>(DC)) 640 if (auto *OMD = dyn_cast<ObjCMethodDecl>(D)) 641 if (OMD->isSynthesizedAccessorStub()) 642 continue; 643 const Optional<bool> V = handleDeclForVisitation(D); 644 if (!V.hasValue()) 645 continue; 646 return V.getValue(); 647 } 648 return false; 649 } 650 651 Optional<bool> CursorVisitor::handleDeclForVisitation(const Decl *D) { 652 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest); 653 654 // Ignore synthesized ivars here, otherwise if we have something like: 655 // @synthesize prop = _prop; 656 // and '_prop' is not declared, we will encounter a '_prop' ivar before 657 // encountering the 'prop' synthesize declaration and we will think that 658 // we passed the region-of-interest. 659 if (auto *ivarD = dyn_cast<ObjCIvarDecl>(D)) { 660 if (ivarD->getSynthesize()) 661 return None; 662 } 663 664 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol 665 // declarations is a mismatch with the compiler semantics. 666 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) { 667 auto *ID = cast<ObjCInterfaceDecl>(D); 668 if (!ID->isThisDeclarationADefinition()) 669 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU); 670 671 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) { 672 auto *PD = cast<ObjCProtocolDecl>(D); 673 if (!PD->isThisDeclarationADefinition()) 674 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU); 675 } 676 677 const Optional<bool> V = shouldVisitCursor(Cursor); 678 if (!V.hasValue()) 679 return None; 680 if (!V.getValue()) 681 return false; 682 if (Visit(Cursor, true)) 683 return true; 684 return None; 685 } 686 687 bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) { 688 llvm_unreachable("Translation units are visited directly by Visit()"); 689 } 690 691 bool CursorVisitor::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) { 692 if (VisitTemplateParameters(D->getTemplateParameters())) 693 return true; 694 695 return Visit(MakeCXCursor(D->getTemplatedDecl(), TU, RegionOfInterest)); 696 } 697 698 bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) { 699 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo()) 700 return Visit(TSInfo->getTypeLoc()); 701 702 return false; 703 } 704 705 bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) { 706 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo()) 707 return Visit(TSInfo->getTypeLoc()); 708 709 return false; 710 } 711 712 bool CursorVisitor::VisitTagDecl(TagDecl *D) { return VisitDeclContext(D); } 713 714 bool CursorVisitor::VisitClassTemplateSpecializationDecl( 715 ClassTemplateSpecializationDecl *D) { 716 bool ShouldVisitBody = false; 717 switch (D->getSpecializationKind()) { 718 case TSK_Undeclared: 719 case TSK_ImplicitInstantiation: 720 // Nothing to visit 721 return false; 722 723 case TSK_ExplicitInstantiationDeclaration: 724 case TSK_ExplicitInstantiationDefinition: 725 break; 726 727 case TSK_ExplicitSpecialization: 728 ShouldVisitBody = true; 729 break; 730 } 731 732 // Visit the template arguments used in the specialization. 733 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) { 734 TypeLoc TL = SpecType->getTypeLoc(); 735 if (TemplateSpecializationTypeLoc TSTLoc = 736 TL.getAs<TemplateSpecializationTypeLoc>()) { 737 for (unsigned I = 0, N = TSTLoc.getNumArgs(); I != N; ++I) 738 if (VisitTemplateArgumentLoc(TSTLoc.getArgLoc(I))) 739 return true; 740 } 741 } 742 743 return ShouldVisitBody && VisitCXXRecordDecl(D); 744 } 745 746 bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl( 747 ClassTemplatePartialSpecializationDecl *D) { 748 // FIXME: Visit the "outer" template parameter lists on the TagDecl 749 // before visiting these template parameters. 750 if (VisitTemplateParameters(D->getTemplateParameters())) 751 return true; 752 753 // Visit the partial specialization arguments. 754 const ASTTemplateArgumentListInfo *Info = D->getTemplateArgsAsWritten(); 755 const TemplateArgumentLoc *TemplateArgs = Info->getTemplateArgs(); 756 for (unsigned I = 0, N = Info->NumTemplateArgs; I != N; ++I) 757 if (VisitTemplateArgumentLoc(TemplateArgs[I])) 758 return true; 759 760 return VisitCXXRecordDecl(D); 761 } 762 763 bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) { 764 if (const auto *TC = D->getTypeConstraint()) 765 if (Visit(MakeCXCursor(TC->getImmediatelyDeclaredConstraint(), StmtParent, 766 TU, RegionOfInterest))) 767 return true; 768 769 // Visit the default argument. 770 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) 771 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo()) 772 if (Visit(DefArg->getTypeLoc())) 773 return true; 774 775 return false; 776 } 777 778 bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) { 779 if (Expr *Init = D->getInitExpr()) 780 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest)); 781 return false; 782 } 783 784 bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) { 785 unsigned NumParamList = DD->getNumTemplateParameterLists(); 786 for (unsigned i = 0; i < NumParamList; i++) { 787 TemplateParameterList *Params = DD->getTemplateParameterList(i); 788 if (VisitTemplateParameters(Params)) 789 return true; 790 } 791 792 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo()) 793 if (Visit(TSInfo->getTypeLoc())) 794 return true; 795 796 // Visit the nested-name-specifier, if present. 797 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc()) 798 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 799 return true; 800 801 return false; 802 } 803 804 static bool HasTrailingReturnType(FunctionDecl *ND) { 805 const QualType Ty = ND->getType(); 806 if (const FunctionType *AFT = Ty->getAs<FunctionType>()) { 807 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(AFT)) 808 return FT->hasTrailingReturn(); 809 } 810 811 return false; 812 } 813 814 /// Compare two base or member initializers based on their source order. 815 static int CompareCXXCtorInitializers(CXXCtorInitializer *const *X, 816 CXXCtorInitializer *const *Y) { 817 return (*X)->getSourceOrder() - (*Y)->getSourceOrder(); 818 } 819 820 bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) { 821 unsigned NumParamList = ND->getNumTemplateParameterLists(); 822 for (unsigned i = 0; i < NumParamList; i++) { 823 TemplateParameterList *Params = ND->getTemplateParameterList(i); 824 if (VisitTemplateParameters(Params)) 825 return true; 826 } 827 828 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) { 829 // Visit the function declaration's syntactic components in the order 830 // written. This requires a bit of work. 831 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens(); 832 FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>(); 833 const bool HasTrailingRT = HasTrailingReturnType(ND); 834 835 // If we have a function declared directly (without the use of a typedef), 836 // visit just the return type. Otherwise, just visit the function's type 837 // now. 838 if ((FTL && !isa<CXXConversionDecl>(ND) && !HasTrailingRT && 839 Visit(FTL.getReturnLoc())) || 840 (!FTL && Visit(TL))) 841 return true; 842 843 // Visit the nested-name-specifier, if present. 844 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc()) 845 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 846 return true; 847 848 // Visit the declaration name. 849 if (!isa<CXXDestructorDecl>(ND)) 850 if (VisitDeclarationNameInfo(ND->getNameInfo())) 851 return true; 852 853 // FIXME: Visit explicitly-specified template arguments! 854 855 // Visit the function parameters, if we have a function type. 856 if (FTL && VisitFunctionTypeLoc(FTL, true)) 857 return true; 858 859 // Visit the function's trailing return type. 860 if (FTL && HasTrailingRT && Visit(FTL.getReturnLoc())) 861 return true; 862 863 // FIXME: Attributes? 864 } 865 866 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) { 867 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) { 868 // Find the initializers that were written in the source. 869 SmallVector<CXXCtorInitializer *, 4> WrittenInits; 870 for (auto *I : Constructor->inits()) { 871 if (!I->isWritten()) 872 continue; 873 874 WrittenInits.push_back(I); 875 } 876 877 // Sort the initializers in source order 878 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(), 879 &CompareCXXCtorInitializers); 880 881 // Visit the initializers in source order 882 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) { 883 CXXCtorInitializer *Init = WrittenInits[I]; 884 if (Init->isAnyMemberInitializer()) { 885 if (Visit(MakeCursorMemberRef(Init->getAnyMember(), 886 Init->getMemberLocation(), TU))) 887 return true; 888 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) { 889 if (Visit(TInfo->getTypeLoc())) 890 return true; 891 } 892 893 // Visit the initializer value. 894 if (Expr *Initializer = Init->getInit()) 895 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest))) 896 return true; 897 } 898 } 899 900 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest))) 901 return true; 902 } 903 904 return false; 905 } 906 907 bool CursorVisitor::VisitFieldDecl(FieldDecl *D) { 908 if (VisitDeclaratorDecl(D)) 909 return true; 910 911 if (Expr *BitWidth = D->getBitWidth()) 912 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest)); 913 914 if (Expr *Init = D->getInClassInitializer()) 915 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest)); 916 917 return false; 918 } 919 920 bool CursorVisitor::VisitVarDecl(VarDecl *D) { 921 if (VisitDeclaratorDecl(D)) 922 return true; 923 924 if (Expr *Init = D->getInit()) 925 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest)); 926 927 return false; 928 } 929 930 bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) { 931 if (VisitDeclaratorDecl(D)) 932 return true; 933 934 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) 935 if (Expr *DefArg = D->getDefaultArgument()) 936 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest)); 937 938 return false; 939 } 940 941 bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) { 942 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl 943 // before visiting these template parameters. 944 if (VisitTemplateParameters(D->getTemplateParameters())) 945 return true; 946 947 auto *FD = D->getTemplatedDecl(); 948 return VisitAttributes(FD) || VisitFunctionDecl(FD); 949 } 950 951 bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) { 952 // FIXME: Visit the "outer" template parameter lists on the TagDecl 953 // before visiting these template parameters. 954 if (VisitTemplateParameters(D->getTemplateParameters())) 955 return true; 956 957 auto *CD = D->getTemplatedDecl(); 958 return VisitAttributes(CD) || VisitCXXRecordDecl(CD); 959 } 960 961 bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) { 962 if (VisitTemplateParameters(D->getTemplateParameters())) 963 return true; 964 965 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() && 966 VisitTemplateArgumentLoc(D->getDefaultArgument())) 967 return true; 968 969 return false; 970 } 971 972 bool CursorVisitor::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) { 973 // Visit the bound, if it's explicit. 974 if (D->hasExplicitBound()) { 975 if (auto TInfo = D->getTypeSourceInfo()) { 976 if (Visit(TInfo->getTypeLoc())) 977 return true; 978 } 979 } 980 981 return false; 982 } 983 984 bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) { 985 if (TypeSourceInfo *TSInfo = ND->getReturnTypeSourceInfo()) 986 if (Visit(TSInfo->getTypeLoc())) 987 return true; 988 989 for (const auto *P : ND->parameters()) { 990 if (Visit(MakeCXCursor(P, TU, RegionOfInterest))) 991 return true; 992 } 993 994 return ND->isThisDeclarationADefinition() && 995 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)); 996 } 997 998 template <typename DeclIt> 999 static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current, 1000 SourceManager &SM, SourceLocation EndLoc, 1001 SmallVectorImpl<Decl *> &Decls) { 1002 DeclIt next = *DI_current; 1003 while (++next != DE_current) { 1004 Decl *D_next = *next; 1005 if (!D_next) 1006 break; 1007 SourceLocation L = D_next->getBeginLoc(); 1008 if (!L.isValid()) 1009 break; 1010 if (SM.isBeforeInTranslationUnit(L, EndLoc)) { 1011 *DI_current = next; 1012 Decls.push_back(D_next); 1013 continue; 1014 } 1015 break; 1016 } 1017 } 1018 1019 bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) { 1020 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially 1021 // an @implementation can lexically contain Decls that are not properly 1022 // nested in the AST. When we identify such cases, we need to retrofit 1023 // this nesting here. 1024 if (!DI_current && !FileDI_current) 1025 return VisitDeclContext(D); 1026 1027 // Scan the Decls that immediately come after the container 1028 // in the current DeclContext. If any fall within the 1029 // container's lexical region, stash them into a vector 1030 // for later processing. 1031 SmallVector<Decl *, 24> DeclsInContainer; 1032 SourceLocation EndLoc = D->getSourceRange().getEnd(); 1033 SourceManager &SM = AU->getSourceManager(); 1034 if (EndLoc.isValid()) { 1035 if (DI_current) { 1036 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc, 1037 DeclsInContainer); 1038 } else { 1039 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc, 1040 DeclsInContainer); 1041 } 1042 } 1043 1044 // The common case. 1045 if (DeclsInContainer.empty()) 1046 return VisitDeclContext(D); 1047 1048 // Get all the Decls in the DeclContext, and sort them with the 1049 // additional ones we've collected. Then visit them. 1050 for (auto *SubDecl : D->decls()) { 1051 if (!SubDecl || SubDecl->getLexicalDeclContext() != D || 1052 SubDecl->getBeginLoc().isInvalid()) 1053 continue; 1054 DeclsInContainer.push_back(SubDecl); 1055 } 1056 1057 // Now sort the Decls so that they appear in lexical order. 1058 llvm::sort(DeclsInContainer, [&SM](Decl *A, Decl *B) { 1059 SourceLocation L_A = A->getBeginLoc(); 1060 SourceLocation L_B = B->getBeginLoc(); 1061 return L_A != L_B 1062 ? SM.isBeforeInTranslationUnit(L_A, L_B) 1063 : SM.isBeforeInTranslationUnit(A->getEndLoc(), B->getEndLoc()); 1064 }); 1065 1066 // Now visit the decls. 1067 for (SmallVectorImpl<Decl *>::iterator I = DeclsInContainer.begin(), 1068 E = DeclsInContainer.end(); 1069 I != E; ++I) { 1070 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest); 1071 const Optional<bool> &V = shouldVisitCursor(Cursor); 1072 if (!V.hasValue()) 1073 continue; 1074 if (!V.getValue()) 1075 return false; 1076 if (Visit(Cursor, true)) 1077 return true; 1078 } 1079 return false; 1080 } 1081 1082 bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) { 1083 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(), 1084 TU))) 1085 return true; 1086 1087 if (VisitObjCTypeParamList(ND->getTypeParamList())) 1088 return true; 1089 1090 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin(); 1091 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(), 1092 E = ND->protocol_end(); 1093 I != E; ++I, ++PL) 1094 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU))) 1095 return true; 1096 1097 return VisitObjCContainerDecl(ND); 1098 } 1099 1100 bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) { 1101 if (!PID->isThisDeclarationADefinition()) 1102 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU)); 1103 1104 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin(); 1105 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(), 1106 E = PID->protocol_end(); 1107 I != E; ++I, ++PL) 1108 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU))) 1109 return true; 1110 1111 return VisitObjCContainerDecl(PID); 1112 } 1113 1114 bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) { 1115 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc())) 1116 return true; 1117 1118 // FIXME: This implements a workaround with @property declarations also being 1119 // installed in the DeclContext for the @interface. Eventually this code 1120 // should be removed. 1121 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext()); 1122 if (!CDecl || !CDecl->IsClassExtension()) 1123 return false; 1124 1125 ObjCInterfaceDecl *ID = CDecl->getClassInterface(); 1126 if (!ID) 1127 return false; 1128 1129 IdentifierInfo *PropertyId = PD->getIdentifier(); 1130 ObjCPropertyDecl *prevDecl = ObjCPropertyDecl::findPropertyDecl( 1131 cast<DeclContext>(ID), PropertyId, PD->getQueryKind()); 1132 1133 if (!prevDecl) 1134 return false; 1135 1136 // Visit synthesized methods since they will be skipped when visiting 1137 // the @interface. 1138 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl()) 1139 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl) 1140 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest))) 1141 return true; 1142 1143 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl()) 1144 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl) 1145 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest))) 1146 return true; 1147 1148 return false; 1149 } 1150 1151 bool CursorVisitor::VisitObjCTypeParamList(ObjCTypeParamList *typeParamList) { 1152 if (!typeParamList) 1153 return false; 1154 1155 for (auto *typeParam : *typeParamList) { 1156 // Visit the type parameter. 1157 if (Visit(MakeCXCursor(typeParam, TU, RegionOfInterest))) 1158 return true; 1159 } 1160 1161 return false; 1162 } 1163 1164 bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) { 1165 if (!D->isThisDeclarationADefinition()) { 1166 // Forward declaration is treated like a reference. 1167 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU)); 1168 } 1169 1170 // Objective-C type parameters. 1171 if (VisitObjCTypeParamList(D->getTypeParamListAsWritten())) 1172 return true; 1173 1174 // Issue callbacks for super class. 1175 if (D->getSuperClass() && Visit(MakeCursorObjCSuperClassRef( 1176 D->getSuperClass(), D->getSuperClassLoc(), TU))) 1177 return true; 1178 1179 if (TypeSourceInfo *SuperClassTInfo = D->getSuperClassTInfo()) 1180 if (Visit(SuperClassTInfo->getTypeLoc())) 1181 return true; 1182 1183 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin(); 1184 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(), 1185 E = D->protocol_end(); 1186 I != E; ++I, ++PL) 1187 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU))) 1188 return true; 1189 1190 return VisitObjCContainerDecl(D); 1191 } 1192 1193 bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) { 1194 return VisitObjCContainerDecl(D); 1195 } 1196 1197 bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) { 1198 // 'ID' could be null when dealing with invalid code. 1199 if (ObjCInterfaceDecl *ID = D->getClassInterface()) 1200 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU))) 1201 return true; 1202 1203 return VisitObjCImplDecl(D); 1204 } 1205 1206 bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) { 1207 #if 0 1208 // Issue callbacks for super class. 1209 // FIXME: No source location information! 1210 if (D->getSuperClass() && 1211 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(), 1212 D->getSuperClassLoc(), 1213 TU))) 1214 return true; 1215 #endif 1216 1217 return VisitObjCImplDecl(D); 1218 } 1219 1220 bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) { 1221 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl()) 1222 if (PD->isIvarNameSpecified()) 1223 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU)); 1224 1225 return false; 1226 } 1227 1228 bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) { 1229 return VisitDeclContext(D); 1230 } 1231 1232 bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) { 1233 // Visit nested-name-specifier. 1234 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) 1235 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 1236 return true; 1237 1238 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(), 1239 D->getTargetNameLoc(), TU)); 1240 } 1241 1242 bool CursorVisitor::VisitUsingDecl(UsingDecl *D) { 1243 // Visit nested-name-specifier. 1244 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) { 1245 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 1246 return true; 1247 } 1248 1249 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU))) 1250 return true; 1251 1252 return VisitDeclarationNameInfo(D->getNameInfo()); 1253 } 1254 1255 bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) { 1256 // Visit nested-name-specifier. 1257 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) 1258 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 1259 return true; 1260 1261 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(), 1262 D->getIdentLocation(), TU)); 1263 } 1264 1265 bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) { 1266 // Visit nested-name-specifier. 1267 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) { 1268 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 1269 return true; 1270 } 1271 1272 return VisitDeclarationNameInfo(D->getNameInfo()); 1273 } 1274 1275 bool CursorVisitor::VisitUnresolvedUsingTypenameDecl( 1276 UnresolvedUsingTypenameDecl *D) { 1277 // Visit nested-name-specifier. 1278 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) 1279 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 1280 return true; 1281 1282 return false; 1283 } 1284 1285 bool CursorVisitor::VisitStaticAssertDecl(StaticAssertDecl *D) { 1286 if (Visit(MakeCXCursor(D->getAssertExpr(), StmtParent, TU, RegionOfInterest))) 1287 return true; 1288 if (StringLiteral *Message = D->getMessage()) 1289 if (Visit(MakeCXCursor(Message, StmtParent, TU, RegionOfInterest))) 1290 return true; 1291 return false; 1292 } 1293 1294 bool CursorVisitor::VisitFriendDecl(FriendDecl *D) { 1295 if (NamedDecl *FriendD = D->getFriendDecl()) { 1296 if (Visit(MakeCXCursor(FriendD, TU, RegionOfInterest))) 1297 return true; 1298 } else if (TypeSourceInfo *TI = D->getFriendType()) { 1299 if (Visit(TI->getTypeLoc())) 1300 return true; 1301 } 1302 return false; 1303 } 1304 1305 bool CursorVisitor::VisitDecompositionDecl(DecompositionDecl *D) { 1306 for (auto *B : D->bindings()) { 1307 if (Visit(MakeCXCursor(B, TU, RegionOfInterest))) 1308 return true; 1309 } 1310 return VisitVarDecl(D); 1311 } 1312 1313 bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) { 1314 switch (Name.getName().getNameKind()) { 1315 case clang::DeclarationName::Identifier: 1316 case clang::DeclarationName::CXXLiteralOperatorName: 1317 case clang::DeclarationName::CXXDeductionGuideName: 1318 case clang::DeclarationName::CXXOperatorName: 1319 case clang::DeclarationName::CXXUsingDirective: 1320 return false; 1321 1322 case clang::DeclarationName::CXXConstructorName: 1323 case clang::DeclarationName::CXXDestructorName: 1324 case clang::DeclarationName::CXXConversionFunctionName: 1325 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo()) 1326 return Visit(TSInfo->getTypeLoc()); 1327 return false; 1328 1329 case clang::DeclarationName::ObjCZeroArgSelector: 1330 case clang::DeclarationName::ObjCOneArgSelector: 1331 case clang::DeclarationName::ObjCMultiArgSelector: 1332 // FIXME: Per-identifier location info? 1333 return false; 1334 } 1335 1336 llvm_unreachable("Invalid DeclarationName::Kind!"); 1337 } 1338 1339 bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS, 1340 SourceRange Range) { 1341 // FIXME: This whole routine is a hack to work around the lack of proper 1342 // source information in nested-name-specifiers (PR5791). Since we do have 1343 // a beginning source location, we can visit the first component of the 1344 // nested-name-specifier, if it's a single-token component. 1345 if (!NNS) 1346 return false; 1347 1348 // Get the first component in the nested-name-specifier. 1349 while (NestedNameSpecifier *Prefix = NNS->getPrefix()) 1350 NNS = Prefix; 1351 1352 switch (NNS->getKind()) { 1353 case NestedNameSpecifier::Namespace: 1354 return Visit( 1355 MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(), TU)); 1356 1357 case NestedNameSpecifier::NamespaceAlias: 1358 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(), 1359 Range.getBegin(), TU)); 1360 1361 case NestedNameSpecifier::TypeSpec: { 1362 // If the type has a form where we know that the beginning of the source 1363 // range matches up with a reference cursor. Visit the appropriate reference 1364 // cursor. 1365 const Type *T = NNS->getAsType(); 1366 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T)) 1367 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU)); 1368 if (const TagType *Tag = dyn_cast<TagType>(T)) 1369 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU)); 1370 if (const TemplateSpecializationType *TST = 1371 dyn_cast<TemplateSpecializationType>(T)) 1372 return VisitTemplateName(TST->getTemplateName(), Range.getBegin()); 1373 break; 1374 } 1375 1376 case NestedNameSpecifier::TypeSpecWithTemplate: 1377 case NestedNameSpecifier::Global: 1378 case NestedNameSpecifier::Identifier: 1379 case NestedNameSpecifier::Super: 1380 break; 1381 } 1382 1383 return false; 1384 } 1385 1386 bool CursorVisitor::VisitNestedNameSpecifierLoc( 1387 NestedNameSpecifierLoc Qualifier) { 1388 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers; 1389 for (; Qualifier; Qualifier = Qualifier.getPrefix()) 1390 Qualifiers.push_back(Qualifier); 1391 1392 while (!Qualifiers.empty()) { 1393 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val(); 1394 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier(); 1395 switch (NNS->getKind()) { 1396 case NestedNameSpecifier::Namespace: 1397 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), 1398 Q.getLocalBeginLoc(), TU))) 1399 return true; 1400 1401 break; 1402 1403 case NestedNameSpecifier::NamespaceAlias: 1404 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(), 1405 Q.getLocalBeginLoc(), TU))) 1406 return true; 1407 1408 break; 1409 1410 case NestedNameSpecifier::TypeSpec: 1411 case NestedNameSpecifier::TypeSpecWithTemplate: 1412 if (Visit(Q.getTypeLoc())) 1413 return true; 1414 1415 break; 1416 1417 case NestedNameSpecifier::Global: 1418 case NestedNameSpecifier::Identifier: 1419 case NestedNameSpecifier::Super: 1420 break; 1421 } 1422 } 1423 1424 return false; 1425 } 1426 1427 bool CursorVisitor::VisitTemplateParameters( 1428 const TemplateParameterList *Params) { 1429 if (!Params) 1430 return false; 1431 1432 for (TemplateParameterList::const_iterator P = Params->begin(), 1433 PEnd = Params->end(); 1434 P != PEnd; ++P) { 1435 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest))) 1436 return true; 1437 } 1438 1439 return false; 1440 } 1441 1442 bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) { 1443 switch (Name.getKind()) { 1444 case TemplateName::Template: 1445 case TemplateName::UsingTemplate: 1446 case TemplateName::QualifiedTemplate: // FIXME: Visit nested-name-specifier. 1447 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU)); 1448 1449 case TemplateName::OverloadedTemplate: 1450 // Visit the overloaded template set. 1451 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU))) 1452 return true; 1453 1454 return false; 1455 1456 case TemplateName::AssumedTemplate: 1457 // FIXME: Visit DeclarationName? 1458 return false; 1459 1460 case TemplateName::DependentTemplate: 1461 // FIXME: Visit nested-name-specifier. 1462 return false; 1463 1464 case TemplateName::SubstTemplateTemplateParm: 1465 return Visit(MakeCursorTemplateRef( 1466 Name.getAsSubstTemplateTemplateParm()->getParameter(), Loc, TU)); 1467 1468 case TemplateName::SubstTemplateTemplateParmPack: 1469 return Visit(MakeCursorTemplateRef( 1470 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(), Loc, 1471 TU)); 1472 } 1473 1474 llvm_unreachable("Invalid TemplateName::Kind!"); 1475 } 1476 1477 bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) { 1478 switch (TAL.getArgument().getKind()) { 1479 case TemplateArgument::Null: 1480 case TemplateArgument::Integral: 1481 case TemplateArgument::Pack: 1482 return false; 1483 1484 case TemplateArgument::Type: 1485 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo()) 1486 return Visit(TSInfo->getTypeLoc()); 1487 return false; 1488 1489 case TemplateArgument::Declaration: 1490 if (Expr *E = TAL.getSourceDeclExpression()) 1491 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest)); 1492 return false; 1493 1494 case TemplateArgument::NullPtr: 1495 if (Expr *E = TAL.getSourceNullPtrExpression()) 1496 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest)); 1497 return false; 1498 1499 case TemplateArgument::Expression: 1500 if (Expr *E = TAL.getSourceExpression()) 1501 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest)); 1502 return false; 1503 1504 case TemplateArgument::Template: 1505 case TemplateArgument::TemplateExpansion: 1506 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc())) 1507 return true; 1508 1509 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(), 1510 TAL.getTemplateNameLoc()); 1511 } 1512 1513 llvm_unreachable("Invalid TemplateArgument::Kind!"); 1514 } 1515 1516 bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) { 1517 return VisitDeclContext(D); 1518 } 1519 1520 bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 1521 return Visit(TL.getUnqualifiedLoc()); 1522 } 1523 1524 bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { 1525 ASTContext &Context = AU->getASTContext(); 1526 1527 // Some builtin types (such as Objective-C's "id", "sel", and 1528 // "Class") have associated declarations. Create cursors for those. 1529 QualType VisitType; 1530 switch (TL.getTypePtr()->getKind()) { 1531 1532 case BuiltinType::Void: 1533 case BuiltinType::NullPtr: 1534 case BuiltinType::Dependent: 1535 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 1536 case BuiltinType::Id: 1537 #include "clang/Basic/OpenCLImageTypes.def" 1538 #define EXT_OPAQUE_TYPE(ExtTYpe, Id, Ext) case BuiltinType::Id: 1539 #include "clang/Basic/OpenCLExtensionTypes.def" 1540 case BuiltinType::OCLSampler: 1541 case BuiltinType::OCLEvent: 1542 case BuiltinType::OCLClkEvent: 1543 case BuiltinType::OCLQueue: 1544 case BuiltinType::OCLReserveID: 1545 #define SVE_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 1546 #include "clang/Basic/AArch64SVEACLETypes.def" 1547 #define PPC_VECTOR_TYPE(Name, Id, Size) case BuiltinType::Id: 1548 #include "clang/Basic/PPCTypes.def" 1549 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 1550 #include "clang/Basic/RISCVVTypes.def" 1551 #define BUILTIN_TYPE(Id, SingletonId) 1552 #define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id: 1553 #define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id: 1554 #define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id: 1555 #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id: 1556 #include "clang/AST/BuiltinTypes.def" 1557 break; 1558 1559 case BuiltinType::ObjCId: 1560 VisitType = Context.getObjCIdType(); 1561 break; 1562 1563 case BuiltinType::ObjCClass: 1564 VisitType = Context.getObjCClassType(); 1565 break; 1566 1567 case BuiltinType::ObjCSel: 1568 VisitType = Context.getObjCSelType(); 1569 break; 1570 } 1571 1572 if (!VisitType.isNull()) { 1573 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>()) 1574 return Visit( 1575 MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(), TU)); 1576 } 1577 1578 return false; 1579 } 1580 1581 bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) { 1582 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU)); 1583 } 1584 1585 bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) { 1586 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU)); 1587 } 1588 1589 bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) { 1590 if (TL.isDefinition()) 1591 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest)); 1592 1593 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU)); 1594 } 1595 1596 bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) { 1597 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU)); 1598 } 1599 1600 bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { 1601 return Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)); 1602 } 1603 1604 bool CursorVisitor::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) { 1605 if (Visit(MakeCursorTypeRef(TL.getDecl(), TL.getBeginLoc(), TU))) 1606 return true; 1607 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) { 1608 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I), 1609 TU))) 1610 return true; 1611 } 1612 1613 return false; 1614 } 1615 1616 bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { 1617 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc())) 1618 return true; 1619 1620 for (unsigned I = 0, N = TL.getNumTypeArgs(); I != N; ++I) { 1621 if (Visit(TL.getTypeArgTInfo(I)->getTypeLoc())) 1622 return true; 1623 } 1624 1625 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) { 1626 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I), 1627 TU))) 1628 return true; 1629 } 1630 1631 return false; 1632 } 1633 1634 bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 1635 return Visit(TL.getPointeeLoc()); 1636 } 1637 1638 bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) { 1639 return Visit(TL.getInnerLoc()); 1640 } 1641 1642 bool CursorVisitor::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) { 1643 return Visit(TL.getInnerLoc()); 1644 } 1645 1646 bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) { 1647 return Visit(TL.getPointeeLoc()); 1648 } 1649 1650 bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { 1651 return Visit(TL.getPointeeLoc()); 1652 } 1653 1654 bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { 1655 return Visit(TL.getPointeeLoc()); 1656 } 1657 1658 bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { 1659 return Visit(TL.getPointeeLoc()); 1660 } 1661 1662 bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { 1663 return Visit(TL.getPointeeLoc()); 1664 } 1665 1666 bool CursorVisitor::VisitUsingTypeLoc(UsingTypeLoc TL) { return false; } 1667 1668 bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) { 1669 return Visit(TL.getModifiedLoc()); 1670 } 1671 1672 bool CursorVisitor::VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) { 1673 return Visit(TL.getWrappedLoc()); 1674 } 1675 1676 bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL, 1677 bool SkipResultType) { 1678 if (!SkipResultType && Visit(TL.getReturnLoc())) 1679 return true; 1680 1681 for (unsigned I = 0, N = TL.getNumParams(); I != N; ++I) 1682 if (Decl *D = TL.getParam(I)) 1683 if (Visit(MakeCXCursor(D, TU, RegionOfInterest))) 1684 return true; 1685 1686 return false; 1687 } 1688 1689 bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) { 1690 if (Visit(TL.getElementLoc())) 1691 return true; 1692 1693 if (Expr *Size = TL.getSizeExpr()) 1694 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest)); 1695 1696 return false; 1697 } 1698 1699 bool CursorVisitor::VisitDecayedTypeLoc(DecayedTypeLoc TL) { 1700 return Visit(TL.getOriginalLoc()); 1701 } 1702 1703 bool CursorVisitor::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) { 1704 return Visit(TL.getOriginalLoc()); 1705 } 1706 1707 bool CursorVisitor::VisitDeducedTemplateSpecializationTypeLoc( 1708 DeducedTemplateSpecializationTypeLoc TL) { 1709 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(), 1710 TL.getTemplateNameLoc())) 1711 return true; 1712 1713 return false; 1714 } 1715 1716 bool CursorVisitor::VisitTemplateSpecializationTypeLoc( 1717 TemplateSpecializationTypeLoc TL) { 1718 // Visit the template name. 1719 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(), 1720 TL.getTemplateNameLoc())) 1721 return true; 1722 1723 // Visit the template arguments. 1724 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I) 1725 if (VisitTemplateArgumentLoc(TL.getArgLoc(I))) 1726 return true; 1727 1728 return false; 1729 } 1730 1731 bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { 1732 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU)); 1733 } 1734 1735 bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { 1736 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo()) 1737 return Visit(TSInfo->getTypeLoc()); 1738 1739 return false; 1740 } 1741 1742 bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { 1743 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo()) 1744 return Visit(TSInfo->getTypeLoc()); 1745 1746 return false; 1747 } 1748 1749 bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { 1750 return VisitNestedNameSpecifierLoc(TL.getQualifierLoc()); 1751 } 1752 1753 bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc( 1754 DependentTemplateSpecializationTypeLoc TL) { 1755 // Visit the nested-name-specifier, if there is one. 1756 if (TL.getQualifierLoc() && VisitNestedNameSpecifierLoc(TL.getQualifierLoc())) 1757 return true; 1758 1759 // Visit the template arguments. 1760 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I) 1761 if (VisitTemplateArgumentLoc(TL.getArgLoc(I))) 1762 return true; 1763 1764 return false; 1765 } 1766 1767 bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { 1768 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc())) 1769 return true; 1770 1771 return Visit(TL.getNamedTypeLoc()); 1772 } 1773 1774 bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) { 1775 return Visit(TL.getPatternLoc()); 1776 } 1777 1778 bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) { 1779 if (Expr *E = TL.getUnderlyingExpr()) 1780 return Visit(MakeCXCursor(E, StmtParent, TU)); 1781 1782 return false; 1783 } 1784 1785 bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) { 1786 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU)); 1787 } 1788 1789 bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) { 1790 return Visit(TL.getValueLoc()); 1791 } 1792 1793 bool CursorVisitor::VisitPipeTypeLoc(PipeTypeLoc TL) { 1794 return Visit(TL.getValueLoc()); 1795 } 1796 1797 #define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \ 1798 bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \ 1799 return Visit##PARENT##Loc(TL); \ 1800 } 1801 1802 DEFAULT_TYPELOC_IMPL(Complex, Type) 1803 DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType) 1804 DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType) 1805 DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType) 1806 DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType) 1807 DEFAULT_TYPELOC_IMPL(DependentAddressSpace, Type) 1808 DEFAULT_TYPELOC_IMPL(DependentVector, Type) 1809 DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type) 1810 DEFAULT_TYPELOC_IMPL(Vector, Type) 1811 DEFAULT_TYPELOC_IMPL(ExtVector, VectorType) 1812 DEFAULT_TYPELOC_IMPL(ConstantMatrix, MatrixType) 1813 DEFAULT_TYPELOC_IMPL(DependentSizedMatrix, MatrixType) 1814 DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType) 1815 DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType) 1816 DEFAULT_TYPELOC_IMPL(Record, TagType) 1817 DEFAULT_TYPELOC_IMPL(Enum, TagType) 1818 DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type) 1819 DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type) 1820 DEFAULT_TYPELOC_IMPL(Auto, Type) 1821 DEFAULT_TYPELOC_IMPL(BitInt, Type) 1822 DEFAULT_TYPELOC_IMPL(DependentBitInt, Type) 1823 1824 bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) { 1825 // Visit the nested-name-specifier, if present. 1826 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) 1827 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 1828 return true; 1829 1830 if (D->isCompleteDefinition()) { 1831 for (const auto &I : D->bases()) { 1832 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU))) 1833 return true; 1834 } 1835 } 1836 1837 return VisitTagDecl(D); 1838 } 1839 1840 bool CursorVisitor::VisitAttributes(Decl *D) { 1841 for (const auto *I : D->attrs()) 1842 if ((TU->ParsingOptions & CXTranslationUnit_VisitImplicitAttributes || 1843 !I->isImplicit()) && 1844 Visit(MakeCXCursor(I, D, TU))) 1845 return true; 1846 1847 return false; 1848 } 1849 1850 //===----------------------------------------------------------------------===// 1851 // Data-recursive visitor methods. 1852 //===----------------------------------------------------------------------===// 1853 1854 namespace { 1855 #define DEF_JOB(NAME, DATA, KIND) \ 1856 class NAME : public VisitorJob { \ 1857 public: \ 1858 NAME(const DATA *d, CXCursor parent) \ 1859 : VisitorJob(parent, VisitorJob::KIND, d) {} \ 1860 static bool classof(const VisitorJob *VJ) { \ 1861 return VJ->getKind() == KIND; \ 1862 } \ 1863 const DATA *get() const { return static_cast<const DATA *>(data[0]); } \ 1864 }; 1865 1866 DEF_JOB(StmtVisit, Stmt, StmtVisitKind) 1867 DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind) 1868 DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind) 1869 DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind) 1870 DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind) 1871 DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind) 1872 DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind) 1873 #undef DEF_JOB 1874 1875 class ExplicitTemplateArgsVisit : public VisitorJob { 1876 public: 1877 ExplicitTemplateArgsVisit(const TemplateArgumentLoc *Begin, 1878 const TemplateArgumentLoc *End, CXCursor parent) 1879 : VisitorJob(parent, VisitorJob::ExplicitTemplateArgsVisitKind, Begin, 1880 End) {} 1881 static bool classof(const VisitorJob *VJ) { 1882 return VJ->getKind() == ExplicitTemplateArgsVisitKind; 1883 } 1884 const TemplateArgumentLoc *begin() const { 1885 return static_cast<const TemplateArgumentLoc *>(data[0]); 1886 } 1887 const TemplateArgumentLoc *end() { 1888 return static_cast<const TemplateArgumentLoc *>(data[1]); 1889 } 1890 }; 1891 class DeclVisit : public VisitorJob { 1892 public: 1893 DeclVisit(const Decl *D, CXCursor parent, bool isFirst) 1894 : VisitorJob(parent, VisitorJob::DeclVisitKind, D, 1895 isFirst ? (void *)1 : (void *)nullptr) {} 1896 static bool classof(const VisitorJob *VJ) { 1897 return VJ->getKind() == DeclVisitKind; 1898 } 1899 const Decl *get() const { return static_cast<const Decl *>(data[0]); } 1900 bool isFirst() const { return data[1] != nullptr; } 1901 }; 1902 class TypeLocVisit : public VisitorJob { 1903 public: 1904 TypeLocVisit(TypeLoc tl, CXCursor parent) 1905 : VisitorJob(parent, VisitorJob::TypeLocVisitKind, 1906 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {} 1907 1908 static bool classof(const VisitorJob *VJ) { 1909 return VJ->getKind() == TypeLocVisitKind; 1910 } 1911 1912 TypeLoc get() const { 1913 QualType T = QualType::getFromOpaquePtr(data[0]); 1914 return TypeLoc(T, const_cast<void *>(data[1])); 1915 } 1916 }; 1917 1918 class LabelRefVisit : public VisitorJob { 1919 public: 1920 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent) 1921 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD, 1922 labelLoc.getPtrEncoding()) {} 1923 1924 static bool classof(const VisitorJob *VJ) { 1925 return VJ->getKind() == VisitorJob::LabelRefVisitKind; 1926 } 1927 const LabelDecl *get() const { 1928 return static_cast<const LabelDecl *>(data[0]); 1929 } 1930 SourceLocation getLoc() const { 1931 return SourceLocation::getFromPtrEncoding(data[1]); 1932 } 1933 }; 1934 1935 class NestedNameSpecifierLocVisit : public VisitorJob { 1936 public: 1937 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent) 1938 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind, 1939 Qualifier.getNestedNameSpecifier(), 1940 Qualifier.getOpaqueData()) {} 1941 1942 static bool classof(const VisitorJob *VJ) { 1943 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind; 1944 } 1945 1946 NestedNameSpecifierLoc get() const { 1947 return NestedNameSpecifierLoc( 1948 const_cast<NestedNameSpecifier *>( 1949 static_cast<const NestedNameSpecifier *>(data[0])), 1950 const_cast<void *>(data[1])); 1951 } 1952 }; 1953 1954 class DeclarationNameInfoVisit : public VisitorJob { 1955 public: 1956 DeclarationNameInfoVisit(const Stmt *S, CXCursor parent) 1957 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {} 1958 static bool classof(const VisitorJob *VJ) { 1959 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind; 1960 } 1961 DeclarationNameInfo get() const { 1962 const Stmt *S = static_cast<const Stmt *>(data[0]); 1963 switch (S->getStmtClass()) { 1964 default: 1965 llvm_unreachable("Unhandled Stmt"); 1966 case clang::Stmt::MSDependentExistsStmtClass: 1967 return cast<MSDependentExistsStmt>(S)->getNameInfo(); 1968 case Stmt::CXXDependentScopeMemberExprClass: 1969 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo(); 1970 case Stmt::DependentScopeDeclRefExprClass: 1971 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo(); 1972 case Stmt::OMPCriticalDirectiveClass: 1973 return cast<OMPCriticalDirective>(S)->getDirectiveName(); 1974 } 1975 } 1976 }; 1977 class MemberRefVisit : public VisitorJob { 1978 public: 1979 MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent) 1980 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D, 1981 L.getPtrEncoding()) {} 1982 static bool classof(const VisitorJob *VJ) { 1983 return VJ->getKind() == VisitorJob::MemberRefVisitKind; 1984 } 1985 const FieldDecl *get() const { 1986 return static_cast<const FieldDecl *>(data[0]); 1987 } 1988 SourceLocation getLoc() const { 1989 return SourceLocation::getFromRawEncoding( 1990 (SourceLocation::UIntTy)(uintptr_t)data[1]); 1991 } 1992 }; 1993 class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitor, void> { 1994 friend class OMPClauseEnqueue; 1995 VisitorWorkList &WL; 1996 CXCursor Parent; 1997 1998 public: 1999 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent) 2000 : WL(wl), Parent(parent) {} 2001 2002 void VisitAddrLabelExpr(const AddrLabelExpr *E); 2003 void VisitBlockExpr(const BlockExpr *B); 2004 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 2005 void VisitCompoundStmt(const CompoundStmt *S); 2006 void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */ 2007 } 2008 void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S); 2009 void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E); 2010 void VisitCXXNewExpr(const CXXNewExpr *E); 2011 void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E); 2012 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E); 2013 void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E); 2014 void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E); 2015 void VisitCXXTypeidExpr(const CXXTypeidExpr *E); 2016 void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E); 2017 void VisitCXXUuidofExpr(const CXXUuidofExpr *E); 2018 void VisitCXXCatchStmt(const CXXCatchStmt *S); 2019 void VisitCXXForRangeStmt(const CXXForRangeStmt *S); 2020 void VisitDeclRefExpr(const DeclRefExpr *D); 2021 void VisitDeclStmt(const DeclStmt *S); 2022 void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E); 2023 void VisitDesignatedInitExpr(const DesignatedInitExpr *E); 2024 void VisitExplicitCastExpr(const ExplicitCastExpr *E); 2025 void VisitForStmt(const ForStmt *FS); 2026 void VisitGotoStmt(const GotoStmt *GS); 2027 void VisitIfStmt(const IfStmt *If); 2028 void VisitInitListExpr(const InitListExpr *IE); 2029 void VisitMemberExpr(const MemberExpr *M); 2030 void VisitOffsetOfExpr(const OffsetOfExpr *E); 2031 void VisitObjCEncodeExpr(const ObjCEncodeExpr *E); 2032 void VisitObjCMessageExpr(const ObjCMessageExpr *M); 2033 void VisitOverloadExpr(const OverloadExpr *E); 2034 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 2035 void VisitStmt(const Stmt *S); 2036 void VisitSwitchStmt(const SwitchStmt *S); 2037 void VisitWhileStmt(const WhileStmt *W); 2038 void VisitTypeTraitExpr(const TypeTraitExpr *E); 2039 void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E); 2040 void VisitExpressionTraitExpr(const ExpressionTraitExpr *E); 2041 void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U); 2042 void VisitVAArgExpr(const VAArgExpr *E); 2043 void VisitSizeOfPackExpr(const SizeOfPackExpr *E); 2044 void VisitPseudoObjectExpr(const PseudoObjectExpr *E); 2045 void VisitOpaqueValueExpr(const OpaqueValueExpr *E); 2046 void VisitLambdaExpr(const LambdaExpr *E); 2047 void VisitOMPExecutableDirective(const OMPExecutableDirective *D); 2048 void VisitOMPLoopBasedDirective(const OMPLoopBasedDirective *D); 2049 void VisitOMPLoopDirective(const OMPLoopDirective *D); 2050 void VisitOMPParallelDirective(const OMPParallelDirective *D); 2051 void VisitOMPSimdDirective(const OMPSimdDirective *D); 2052 void 2053 VisitOMPLoopTransformationDirective(const OMPLoopTransformationDirective *D); 2054 void VisitOMPTileDirective(const OMPTileDirective *D); 2055 void VisitOMPUnrollDirective(const OMPUnrollDirective *D); 2056 void VisitOMPForDirective(const OMPForDirective *D); 2057 void VisitOMPForSimdDirective(const OMPForSimdDirective *D); 2058 void VisitOMPSectionsDirective(const OMPSectionsDirective *D); 2059 void VisitOMPSectionDirective(const OMPSectionDirective *D); 2060 void VisitOMPSingleDirective(const OMPSingleDirective *D); 2061 void VisitOMPMasterDirective(const OMPMasterDirective *D); 2062 void VisitOMPCriticalDirective(const OMPCriticalDirective *D); 2063 void VisitOMPParallelForDirective(const OMPParallelForDirective *D); 2064 void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D); 2065 void VisitOMPParallelMasterDirective(const OMPParallelMasterDirective *D); 2066 void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D); 2067 void VisitOMPTaskDirective(const OMPTaskDirective *D); 2068 void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D); 2069 void VisitOMPBarrierDirective(const OMPBarrierDirective *D); 2070 void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D); 2071 void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D); 2072 void 2073 VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D); 2074 void VisitOMPCancelDirective(const OMPCancelDirective *D); 2075 void VisitOMPFlushDirective(const OMPFlushDirective *D); 2076 void VisitOMPDepobjDirective(const OMPDepobjDirective *D); 2077 void VisitOMPScanDirective(const OMPScanDirective *D); 2078 void VisitOMPOrderedDirective(const OMPOrderedDirective *D); 2079 void VisitOMPAtomicDirective(const OMPAtomicDirective *D); 2080 void VisitOMPTargetDirective(const OMPTargetDirective *D); 2081 void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D); 2082 void VisitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective *D); 2083 void VisitOMPTargetExitDataDirective(const OMPTargetExitDataDirective *D); 2084 void VisitOMPTargetParallelDirective(const OMPTargetParallelDirective *D); 2085 void 2086 VisitOMPTargetParallelForDirective(const OMPTargetParallelForDirective *D); 2087 void VisitOMPTeamsDirective(const OMPTeamsDirective *D); 2088 void VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D); 2089 void VisitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective *D); 2090 void VisitOMPMasterTaskLoopDirective(const OMPMasterTaskLoopDirective *D); 2091 void 2092 VisitOMPMasterTaskLoopSimdDirective(const OMPMasterTaskLoopSimdDirective *D); 2093 void VisitOMPParallelMasterTaskLoopDirective( 2094 const OMPParallelMasterTaskLoopDirective *D); 2095 void VisitOMPParallelMasterTaskLoopSimdDirective( 2096 const OMPParallelMasterTaskLoopSimdDirective *D); 2097 void VisitOMPDistributeDirective(const OMPDistributeDirective *D); 2098 void VisitOMPDistributeParallelForDirective( 2099 const OMPDistributeParallelForDirective *D); 2100 void VisitOMPDistributeParallelForSimdDirective( 2101 const OMPDistributeParallelForSimdDirective *D); 2102 void VisitOMPDistributeSimdDirective(const OMPDistributeSimdDirective *D); 2103 void VisitOMPTargetParallelForSimdDirective( 2104 const OMPTargetParallelForSimdDirective *D); 2105 void VisitOMPTargetSimdDirective(const OMPTargetSimdDirective *D); 2106 void VisitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective *D); 2107 void VisitOMPTeamsDistributeSimdDirective( 2108 const OMPTeamsDistributeSimdDirective *D); 2109 void VisitOMPTeamsDistributeParallelForSimdDirective( 2110 const OMPTeamsDistributeParallelForSimdDirective *D); 2111 void VisitOMPTeamsDistributeParallelForDirective( 2112 const OMPTeamsDistributeParallelForDirective *D); 2113 void VisitOMPTargetTeamsDirective(const OMPTargetTeamsDirective *D); 2114 void VisitOMPTargetTeamsDistributeDirective( 2115 const OMPTargetTeamsDistributeDirective *D); 2116 void VisitOMPTargetTeamsDistributeParallelForDirective( 2117 const OMPTargetTeamsDistributeParallelForDirective *D); 2118 void VisitOMPTargetTeamsDistributeParallelForSimdDirective( 2119 const OMPTargetTeamsDistributeParallelForSimdDirective *D); 2120 void VisitOMPTargetTeamsDistributeSimdDirective( 2121 const OMPTargetTeamsDistributeSimdDirective *D); 2122 2123 private: 2124 void AddDeclarationNameInfo(const Stmt *S); 2125 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier); 2126 void AddExplicitTemplateArgs(const TemplateArgumentLoc *A, 2127 unsigned NumTemplateArgs); 2128 void AddMemberRef(const FieldDecl *D, SourceLocation L); 2129 void AddStmt(const Stmt *S); 2130 void AddDecl(const Decl *D, bool isFirst = true); 2131 void AddTypeLoc(TypeSourceInfo *TI); 2132 void EnqueueChildren(const Stmt *S); 2133 void EnqueueChildren(const OMPClause *S); 2134 }; 2135 } // namespace 2136 2137 void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) { 2138 // 'S' should always be non-null, since it comes from the 2139 // statement we are visiting. 2140 WL.push_back(DeclarationNameInfoVisit(S, Parent)); 2141 } 2142 2143 void EnqueueVisitor::AddNestedNameSpecifierLoc( 2144 NestedNameSpecifierLoc Qualifier) { 2145 if (Qualifier) 2146 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent)); 2147 } 2148 2149 void EnqueueVisitor::AddStmt(const Stmt *S) { 2150 if (S) 2151 WL.push_back(StmtVisit(S, Parent)); 2152 } 2153 void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) { 2154 if (D) 2155 WL.push_back(DeclVisit(D, Parent, isFirst)); 2156 } 2157 void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A, 2158 unsigned NumTemplateArgs) { 2159 WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent)); 2160 } 2161 void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) { 2162 if (D) 2163 WL.push_back(MemberRefVisit(D, L, Parent)); 2164 } 2165 void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) { 2166 if (TI) 2167 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent)); 2168 } 2169 void EnqueueVisitor::EnqueueChildren(const Stmt *S) { 2170 unsigned size = WL.size(); 2171 for (const Stmt *SubStmt : S->children()) { 2172 AddStmt(SubStmt); 2173 } 2174 if (size == WL.size()) 2175 return; 2176 // Now reverse the entries we just added. This will match the DFS 2177 // ordering performed by the worklist. 2178 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end(); 2179 std::reverse(I, E); 2180 } 2181 namespace { 2182 class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> { 2183 EnqueueVisitor *Visitor; 2184 /// Process clauses with list of variables. 2185 template <typename T> void VisitOMPClauseList(T *Node); 2186 2187 public: 2188 OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) {} 2189 #define GEN_CLANG_CLAUSE_CLASS 2190 #define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(const Class *C); 2191 #include "llvm/Frontend/OpenMP/OMP.inc" 2192 void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C); 2193 void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C); 2194 }; 2195 2196 void OMPClauseEnqueue::VisitOMPClauseWithPreInit( 2197 const OMPClauseWithPreInit *C) { 2198 Visitor->AddStmt(C->getPreInitStmt()); 2199 } 2200 2201 void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate( 2202 const OMPClauseWithPostUpdate *C) { 2203 VisitOMPClauseWithPreInit(C); 2204 Visitor->AddStmt(C->getPostUpdateExpr()); 2205 } 2206 2207 void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) { 2208 VisitOMPClauseWithPreInit(C); 2209 Visitor->AddStmt(C->getCondition()); 2210 } 2211 2212 void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) { 2213 Visitor->AddStmt(C->getCondition()); 2214 } 2215 2216 void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) { 2217 VisitOMPClauseWithPreInit(C); 2218 Visitor->AddStmt(C->getNumThreads()); 2219 } 2220 2221 void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) { 2222 Visitor->AddStmt(C->getSafelen()); 2223 } 2224 2225 void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) { 2226 Visitor->AddStmt(C->getSimdlen()); 2227 } 2228 2229 void OMPClauseEnqueue::VisitOMPSizesClause(const OMPSizesClause *C) { 2230 for (auto E : C->getSizesRefs()) 2231 Visitor->AddStmt(E); 2232 } 2233 2234 void OMPClauseEnqueue::VisitOMPFullClause(const OMPFullClause *C) {} 2235 2236 void OMPClauseEnqueue::VisitOMPPartialClause(const OMPPartialClause *C) { 2237 Visitor->AddStmt(C->getFactor()); 2238 } 2239 2240 void OMPClauseEnqueue::VisitOMPAllocatorClause(const OMPAllocatorClause *C) { 2241 Visitor->AddStmt(C->getAllocator()); 2242 } 2243 2244 void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) { 2245 Visitor->AddStmt(C->getNumForLoops()); 2246 } 2247 2248 void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) {} 2249 2250 void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) {} 2251 2252 void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) { 2253 VisitOMPClauseWithPreInit(C); 2254 Visitor->AddStmt(C->getChunkSize()); 2255 } 2256 2257 void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) { 2258 Visitor->AddStmt(C->getNumForLoops()); 2259 } 2260 2261 void OMPClauseEnqueue::VisitOMPDetachClause(const OMPDetachClause *C) { 2262 Visitor->AddStmt(C->getEventHandler()); 2263 } 2264 2265 void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {} 2266 2267 void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {} 2268 2269 void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {} 2270 2271 void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {} 2272 2273 void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {} 2274 2275 void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {} 2276 2277 void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {} 2278 2279 void OMPClauseEnqueue::VisitOMPCompareClause(const OMPCompareClause *) {} 2280 2281 void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {} 2282 2283 void OMPClauseEnqueue::VisitOMPAcqRelClause(const OMPAcqRelClause *) {} 2284 2285 void OMPClauseEnqueue::VisitOMPAcquireClause(const OMPAcquireClause *) {} 2286 2287 void OMPClauseEnqueue::VisitOMPReleaseClause(const OMPReleaseClause *) {} 2288 2289 void OMPClauseEnqueue::VisitOMPRelaxedClause(const OMPRelaxedClause *) {} 2290 2291 void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {} 2292 2293 void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {} 2294 2295 void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {} 2296 2297 void OMPClauseEnqueue::VisitOMPInitClause(const OMPInitClause *C) { 2298 VisitOMPClauseList(C); 2299 } 2300 2301 void OMPClauseEnqueue::VisitOMPUseClause(const OMPUseClause *C) { 2302 Visitor->AddStmt(C->getInteropVar()); 2303 } 2304 2305 void OMPClauseEnqueue::VisitOMPDestroyClause(const OMPDestroyClause *C) { 2306 if (C->getInteropVar()) 2307 Visitor->AddStmt(C->getInteropVar()); 2308 } 2309 2310 void OMPClauseEnqueue::VisitOMPNovariantsClause(const OMPNovariantsClause *C) { 2311 Visitor->AddStmt(C->getCondition()); 2312 } 2313 2314 void OMPClauseEnqueue::VisitOMPNocontextClause(const OMPNocontextClause *C) { 2315 Visitor->AddStmt(C->getCondition()); 2316 } 2317 2318 void OMPClauseEnqueue::VisitOMPFilterClause(const OMPFilterClause *C) { 2319 VisitOMPClauseWithPreInit(C); 2320 Visitor->AddStmt(C->getThreadID()); 2321 } 2322 2323 void OMPClauseEnqueue::VisitOMPAlignClause(const OMPAlignClause *C) { 2324 Visitor->AddStmt(C->getAlignment()); 2325 } 2326 2327 void OMPClauseEnqueue::VisitOMPUnifiedAddressClause( 2328 const OMPUnifiedAddressClause *) {} 2329 2330 void OMPClauseEnqueue::VisitOMPUnifiedSharedMemoryClause( 2331 const OMPUnifiedSharedMemoryClause *) {} 2332 2333 void OMPClauseEnqueue::VisitOMPReverseOffloadClause( 2334 const OMPReverseOffloadClause *) {} 2335 2336 void OMPClauseEnqueue::VisitOMPDynamicAllocatorsClause( 2337 const OMPDynamicAllocatorsClause *) {} 2338 2339 void OMPClauseEnqueue::VisitOMPAtomicDefaultMemOrderClause( 2340 const OMPAtomicDefaultMemOrderClause *) {} 2341 2342 void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) { 2343 Visitor->AddStmt(C->getDevice()); 2344 } 2345 2346 void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) { 2347 VisitOMPClauseWithPreInit(C); 2348 Visitor->AddStmt(C->getNumTeams()); 2349 } 2350 2351 void OMPClauseEnqueue::VisitOMPThreadLimitClause( 2352 const OMPThreadLimitClause *C) { 2353 VisitOMPClauseWithPreInit(C); 2354 Visitor->AddStmt(C->getThreadLimit()); 2355 } 2356 2357 void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) { 2358 Visitor->AddStmt(C->getPriority()); 2359 } 2360 2361 void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) { 2362 Visitor->AddStmt(C->getGrainsize()); 2363 } 2364 2365 void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) { 2366 Visitor->AddStmt(C->getNumTasks()); 2367 } 2368 2369 void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) { 2370 Visitor->AddStmt(C->getHint()); 2371 } 2372 2373 template <typename T> void OMPClauseEnqueue::VisitOMPClauseList(T *Node) { 2374 for (const auto *I : Node->varlists()) { 2375 Visitor->AddStmt(I); 2376 } 2377 } 2378 2379 void OMPClauseEnqueue::VisitOMPInclusiveClause(const OMPInclusiveClause *C) { 2380 VisitOMPClauseList(C); 2381 } 2382 void OMPClauseEnqueue::VisitOMPExclusiveClause(const OMPExclusiveClause *C) { 2383 VisitOMPClauseList(C); 2384 } 2385 void OMPClauseEnqueue::VisitOMPAllocateClause(const OMPAllocateClause *C) { 2386 VisitOMPClauseList(C); 2387 Visitor->AddStmt(C->getAllocator()); 2388 } 2389 void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) { 2390 VisitOMPClauseList(C); 2391 for (const auto *E : C->private_copies()) { 2392 Visitor->AddStmt(E); 2393 } 2394 } 2395 void OMPClauseEnqueue::VisitOMPFirstprivateClause( 2396 const OMPFirstprivateClause *C) { 2397 VisitOMPClauseList(C); 2398 VisitOMPClauseWithPreInit(C); 2399 for (const auto *E : C->private_copies()) { 2400 Visitor->AddStmt(E); 2401 } 2402 for (const auto *E : C->inits()) { 2403 Visitor->AddStmt(E); 2404 } 2405 } 2406 void OMPClauseEnqueue::VisitOMPLastprivateClause( 2407 const OMPLastprivateClause *C) { 2408 VisitOMPClauseList(C); 2409 VisitOMPClauseWithPostUpdate(C); 2410 for (auto *E : C->private_copies()) { 2411 Visitor->AddStmt(E); 2412 } 2413 for (auto *E : C->source_exprs()) { 2414 Visitor->AddStmt(E); 2415 } 2416 for (auto *E : C->destination_exprs()) { 2417 Visitor->AddStmt(E); 2418 } 2419 for (auto *E : C->assignment_ops()) { 2420 Visitor->AddStmt(E); 2421 } 2422 } 2423 void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) { 2424 VisitOMPClauseList(C); 2425 } 2426 void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) { 2427 VisitOMPClauseList(C); 2428 VisitOMPClauseWithPostUpdate(C); 2429 for (auto *E : C->privates()) { 2430 Visitor->AddStmt(E); 2431 } 2432 for (auto *E : C->lhs_exprs()) { 2433 Visitor->AddStmt(E); 2434 } 2435 for (auto *E : C->rhs_exprs()) { 2436 Visitor->AddStmt(E); 2437 } 2438 for (auto *E : C->reduction_ops()) { 2439 Visitor->AddStmt(E); 2440 } 2441 if (C->getModifier() == clang::OMPC_REDUCTION_inscan) { 2442 for (auto *E : C->copy_ops()) { 2443 Visitor->AddStmt(E); 2444 } 2445 for (auto *E : C->copy_array_temps()) { 2446 Visitor->AddStmt(E); 2447 } 2448 for (auto *E : C->copy_array_elems()) { 2449 Visitor->AddStmt(E); 2450 } 2451 } 2452 } 2453 void OMPClauseEnqueue::VisitOMPTaskReductionClause( 2454 const OMPTaskReductionClause *C) { 2455 VisitOMPClauseList(C); 2456 VisitOMPClauseWithPostUpdate(C); 2457 for (auto *E : C->privates()) { 2458 Visitor->AddStmt(E); 2459 } 2460 for (auto *E : C->lhs_exprs()) { 2461 Visitor->AddStmt(E); 2462 } 2463 for (auto *E : C->rhs_exprs()) { 2464 Visitor->AddStmt(E); 2465 } 2466 for (auto *E : C->reduction_ops()) { 2467 Visitor->AddStmt(E); 2468 } 2469 } 2470 void OMPClauseEnqueue::VisitOMPInReductionClause( 2471 const OMPInReductionClause *C) { 2472 VisitOMPClauseList(C); 2473 VisitOMPClauseWithPostUpdate(C); 2474 for (auto *E : C->privates()) { 2475 Visitor->AddStmt(E); 2476 } 2477 for (auto *E : C->lhs_exprs()) { 2478 Visitor->AddStmt(E); 2479 } 2480 for (auto *E : C->rhs_exprs()) { 2481 Visitor->AddStmt(E); 2482 } 2483 for (auto *E : C->reduction_ops()) { 2484 Visitor->AddStmt(E); 2485 } 2486 for (auto *E : C->taskgroup_descriptors()) 2487 Visitor->AddStmt(E); 2488 } 2489 void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) { 2490 VisitOMPClauseList(C); 2491 VisitOMPClauseWithPostUpdate(C); 2492 for (const auto *E : C->privates()) { 2493 Visitor->AddStmt(E); 2494 } 2495 for (const auto *E : C->inits()) { 2496 Visitor->AddStmt(E); 2497 } 2498 for (const auto *E : C->updates()) { 2499 Visitor->AddStmt(E); 2500 } 2501 for (const auto *E : C->finals()) { 2502 Visitor->AddStmt(E); 2503 } 2504 Visitor->AddStmt(C->getStep()); 2505 Visitor->AddStmt(C->getCalcStep()); 2506 } 2507 void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) { 2508 VisitOMPClauseList(C); 2509 Visitor->AddStmt(C->getAlignment()); 2510 } 2511 void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) { 2512 VisitOMPClauseList(C); 2513 for (auto *E : C->source_exprs()) { 2514 Visitor->AddStmt(E); 2515 } 2516 for (auto *E : C->destination_exprs()) { 2517 Visitor->AddStmt(E); 2518 } 2519 for (auto *E : C->assignment_ops()) { 2520 Visitor->AddStmt(E); 2521 } 2522 } 2523 void OMPClauseEnqueue::VisitOMPCopyprivateClause( 2524 const OMPCopyprivateClause *C) { 2525 VisitOMPClauseList(C); 2526 for (auto *E : C->source_exprs()) { 2527 Visitor->AddStmt(E); 2528 } 2529 for (auto *E : C->destination_exprs()) { 2530 Visitor->AddStmt(E); 2531 } 2532 for (auto *E : C->assignment_ops()) { 2533 Visitor->AddStmt(E); 2534 } 2535 } 2536 void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) { 2537 VisitOMPClauseList(C); 2538 } 2539 void OMPClauseEnqueue::VisitOMPDepobjClause(const OMPDepobjClause *C) { 2540 Visitor->AddStmt(C->getDepobj()); 2541 } 2542 void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) { 2543 VisitOMPClauseList(C); 2544 } 2545 void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) { 2546 VisitOMPClauseList(C); 2547 } 2548 void OMPClauseEnqueue::VisitOMPDistScheduleClause( 2549 const OMPDistScheduleClause *C) { 2550 VisitOMPClauseWithPreInit(C); 2551 Visitor->AddStmt(C->getChunkSize()); 2552 } 2553 void OMPClauseEnqueue::VisitOMPDefaultmapClause( 2554 const OMPDefaultmapClause * /*C*/) {} 2555 void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) { 2556 VisitOMPClauseList(C); 2557 } 2558 void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) { 2559 VisitOMPClauseList(C); 2560 } 2561 void OMPClauseEnqueue::VisitOMPUseDevicePtrClause( 2562 const OMPUseDevicePtrClause *C) { 2563 VisitOMPClauseList(C); 2564 } 2565 void OMPClauseEnqueue::VisitOMPUseDeviceAddrClause( 2566 const OMPUseDeviceAddrClause *C) { 2567 VisitOMPClauseList(C); 2568 } 2569 void OMPClauseEnqueue::VisitOMPIsDevicePtrClause( 2570 const OMPIsDevicePtrClause *C) { 2571 VisitOMPClauseList(C); 2572 } 2573 void OMPClauseEnqueue::VisitOMPHasDeviceAddrClause( 2574 const OMPHasDeviceAddrClause *C) { 2575 VisitOMPClauseList(C); 2576 } 2577 void OMPClauseEnqueue::VisitOMPNontemporalClause( 2578 const OMPNontemporalClause *C) { 2579 VisitOMPClauseList(C); 2580 for (const auto *E : C->private_refs()) 2581 Visitor->AddStmt(E); 2582 } 2583 void OMPClauseEnqueue::VisitOMPOrderClause(const OMPOrderClause *C) {} 2584 void OMPClauseEnqueue::VisitOMPUsesAllocatorsClause( 2585 const OMPUsesAllocatorsClause *C) { 2586 for (unsigned I = 0, E = C->getNumberOfAllocators(); I < E; ++I) { 2587 const OMPUsesAllocatorsClause::Data &D = C->getAllocatorData(I); 2588 Visitor->AddStmt(D.Allocator); 2589 Visitor->AddStmt(D.AllocatorTraits); 2590 } 2591 } 2592 void OMPClauseEnqueue::VisitOMPAffinityClause(const OMPAffinityClause *C) { 2593 Visitor->AddStmt(C->getModifier()); 2594 for (const Expr *E : C->varlists()) 2595 Visitor->AddStmt(E); 2596 } 2597 void OMPClauseEnqueue::VisitOMPBindClause(const OMPBindClause *C) {} 2598 2599 } // namespace 2600 2601 void EnqueueVisitor::EnqueueChildren(const OMPClause *S) { 2602 unsigned size = WL.size(); 2603 OMPClauseEnqueue Visitor(this); 2604 Visitor.Visit(S); 2605 if (size == WL.size()) 2606 return; 2607 // Now reverse the entries we just added. This will match the DFS 2608 // ordering performed by the worklist. 2609 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end(); 2610 std::reverse(I, E); 2611 } 2612 void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) { 2613 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent)); 2614 } 2615 void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) { 2616 AddDecl(B->getBlockDecl()); 2617 } 2618 void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 2619 EnqueueChildren(E); 2620 AddTypeLoc(E->getTypeSourceInfo()); 2621 } 2622 void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) { 2623 for (auto &I : llvm::reverse(S->body())) 2624 AddStmt(I); 2625 } 2626 void EnqueueVisitor::VisitMSDependentExistsStmt( 2627 const MSDependentExistsStmt *S) { 2628 AddStmt(S->getSubStmt()); 2629 AddDeclarationNameInfo(S); 2630 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc()) 2631 AddNestedNameSpecifierLoc(QualifierLoc); 2632 } 2633 2634 void EnqueueVisitor::VisitCXXDependentScopeMemberExpr( 2635 const CXXDependentScopeMemberExpr *E) { 2636 if (E->hasExplicitTemplateArgs()) 2637 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs()); 2638 AddDeclarationNameInfo(E); 2639 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc()) 2640 AddNestedNameSpecifierLoc(QualifierLoc); 2641 if (!E->isImplicitAccess()) 2642 AddStmt(E->getBase()); 2643 } 2644 void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) { 2645 // Enqueue the initializer , if any. 2646 AddStmt(E->getInitializer()); 2647 // Enqueue the array size, if any. 2648 AddStmt(E->getArraySize().getValueOr(nullptr)); 2649 // Enqueue the allocated type. 2650 AddTypeLoc(E->getAllocatedTypeSourceInfo()); 2651 // Enqueue the placement arguments. 2652 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I) 2653 AddStmt(E->getPlacementArg(I - 1)); 2654 } 2655 void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) { 2656 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I) 2657 AddStmt(CE->getArg(I - 1)); 2658 AddStmt(CE->getCallee()); 2659 AddStmt(CE->getArg(0)); 2660 } 2661 void EnqueueVisitor::VisitCXXPseudoDestructorExpr( 2662 const CXXPseudoDestructorExpr *E) { 2663 // Visit the name of the type being destroyed. 2664 AddTypeLoc(E->getDestroyedTypeInfo()); 2665 // Visit the scope type that looks disturbingly like the nested-name-specifier 2666 // but isn't. 2667 AddTypeLoc(E->getScopeTypeInfo()); 2668 // Visit the nested-name-specifier. 2669 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc()) 2670 AddNestedNameSpecifierLoc(QualifierLoc); 2671 // Visit base expression. 2672 AddStmt(E->getBase()); 2673 } 2674 void EnqueueVisitor::VisitCXXScalarValueInitExpr( 2675 const CXXScalarValueInitExpr *E) { 2676 AddTypeLoc(E->getTypeSourceInfo()); 2677 } 2678 void EnqueueVisitor::VisitCXXTemporaryObjectExpr( 2679 const CXXTemporaryObjectExpr *E) { 2680 EnqueueChildren(E); 2681 AddTypeLoc(E->getTypeSourceInfo()); 2682 } 2683 void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 2684 EnqueueChildren(E); 2685 if (E->isTypeOperand()) 2686 AddTypeLoc(E->getTypeOperandSourceInfo()); 2687 } 2688 2689 void EnqueueVisitor::VisitCXXUnresolvedConstructExpr( 2690 const CXXUnresolvedConstructExpr *E) { 2691 EnqueueChildren(E); 2692 AddTypeLoc(E->getTypeSourceInfo()); 2693 } 2694 void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 2695 EnqueueChildren(E); 2696 if (E->isTypeOperand()) 2697 AddTypeLoc(E->getTypeOperandSourceInfo()); 2698 } 2699 2700 void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) { 2701 EnqueueChildren(S); 2702 AddDecl(S->getExceptionDecl()); 2703 } 2704 2705 void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) { 2706 AddStmt(S->getBody()); 2707 AddStmt(S->getRangeInit()); 2708 AddDecl(S->getLoopVariable()); 2709 } 2710 2711 void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) { 2712 if (DR->hasExplicitTemplateArgs()) 2713 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs()); 2714 WL.push_back(DeclRefExprParts(DR, Parent)); 2715 } 2716 void EnqueueVisitor::VisitDependentScopeDeclRefExpr( 2717 const DependentScopeDeclRefExpr *E) { 2718 if (E->hasExplicitTemplateArgs()) 2719 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs()); 2720 AddDeclarationNameInfo(E); 2721 AddNestedNameSpecifierLoc(E->getQualifierLoc()); 2722 } 2723 void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) { 2724 unsigned size = WL.size(); 2725 bool isFirst = true; 2726 for (const auto *D : S->decls()) { 2727 AddDecl(D, isFirst); 2728 isFirst = false; 2729 } 2730 if (size == WL.size()) 2731 return; 2732 // Now reverse the entries we just added. This will match the DFS 2733 // ordering performed by the worklist. 2734 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end(); 2735 std::reverse(I, E); 2736 } 2737 void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) { 2738 AddStmt(E->getInit()); 2739 for (const DesignatedInitExpr::Designator &D : 2740 llvm::reverse(E->designators())) { 2741 if (D.isFieldDesignator()) { 2742 if (FieldDecl *Field = D.getField()) 2743 AddMemberRef(Field, D.getFieldLoc()); 2744 continue; 2745 } 2746 if (D.isArrayDesignator()) { 2747 AddStmt(E->getArrayIndex(D)); 2748 continue; 2749 } 2750 assert(D.isArrayRangeDesignator() && "Unknown designator kind"); 2751 AddStmt(E->getArrayRangeEnd(D)); 2752 AddStmt(E->getArrayRangeStart(D)); 2753 } 2754 } 2755 void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) { 2756 EnqueueChildren(E); 2757 AddTypeLoc(E->getTypeInfoAsWritten()); 2758 } 2759 void EnqueueVisitor::VisitForStmt(const ForStmt *FS) { 2760 AddStmt(FS->getBody()); 2761 AddStmt(FS->getInc()); 2762 AddStmt(FS->getCond()); 2763 AddDecl(FS->getConditionVariable()); 2764 AddStmt(FS->getInit()); 2765 } 2766 void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) { 2767 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent)); 2768 } 2769 void EnqueueVisitor::VisitIfStmt(const IfStmt *If) { 2770 AddStmt(If->getElse()); 2771 AddStmt(If->getThen()); 2772 AddStmt(If->getCond()); 2773 AddStmt(If->getInit()); 2774 AddDecl(If->getConditionVariable()); 2775 } 2776 void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) { 2777 // We care about the syntactic form of the initializer list, only. 2778 if (InitListExpr *Syntactic = IE->getSyntacticForm()) 2779 IE = Syntactic; 2780 EnqueueChildren(IE); 2781 } 2782 void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) { 2783 WL.push_back(MemberExprParts(M, Parent)); 2784 2785 // If the base of the member access expression is an implicit 'this', don't 2786 // visit it. 2787 // FIXME: If we ever want to show these implicit accesses, this will be 2788 // unfortunate. However, clang_getCursor() relies on this behavior. 2789 if (M->isImplicitAccess()) 2790 return; 2791 2792 // Ignore base anonymous struct/union fields, otherwise they will shadow the 2793 // real field that we are interested in. 2794 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) { 2795 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) { 2796 if (FD->isAnonymousStructOrUnion()) { 2797 AddStmt(SubME->getBase()); 2798 return; 2799 } 2800 } 2801 } 2802 2803 AddStmt(M->getBase()); 2804 } 2805 void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { 2806 AddTypeLoc(E->getEncodedTypeSourceInfo()); 2807 } 2808 void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) { 2809 EnqueueChildren(M); 2810 AddTypeLoc(M->getClassReceiverTypeInfo()); 2811 } 2812 void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) { 2813 // Visit the components of the offsetof expression. 2814 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) { 2815 const OffsetOfNode &Node = E->getComponent(I - 1); 2816 switch (Node.getKind()) { 2817 case OffsetOfNode::Array: 2818 AddStmt(E->getIndexExpr(Node.getArrayExprIndex())); 2819 break; 2820 case OffsetOfNode::Field: 2821 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd()); 2822 break; 2823 case OffsetOfNode::Identifier: 2824 case OffsetOfNode::Base: 2825 continue; 2826 } 2827 } 2828 // Visit the type into which we're computing the offset. 2829 AddTypeLoc(E->getTypeSourceInfo()); 2830 } 2831 void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) { 2832 if (E->hasExplicitTemplateArgs()) 2833 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs()); 2834 WL.push_back(OverloadExprParts(E, Parent)); 2835 } 2836 void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr( 2837 const UnaryExprOrTypeTraitExpr *E) { 2838 EnqueueChildren(E); 2839 if (E->isArgumentType()) 2840 AddTypeLoc(E->getArgumentTypeInfo()); 2841 } 2842 void EnqueueVisitor::VisitStmt(const Stmt *S) { EnqueueChildren(S); } 2843 void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) { 2844 AddStmt(S->getBody()); 2845 AddStmt(S->getCond()); 2846 AddDecl(S->getConditionVariable()); 2847 } 2848 2849 void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) { 2850 AddStmt(W->getBody()); 2851 AddStmt(W->getCond()); 2852 AddDecl(W->getConditionVariable()); 2853 } 2854 2855 void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) { 2856 for (unsigned I = E->getNumArgs(); I > 0; --I) 2857 AddTypeLoc(E->getArg(I - 1)); 2858 } 2859 2860 void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 2861 AddTypeLoc(E->getQueriedTypeSourceInfo()); 2862 } 2863 2864 void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 2865 EnqueueChildren(E); 2866 } 2867 2868 void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) { 2869 VisitOverloadExpr(U); 2870 if (!U->isImplicitAccess()) 2871 AddStmt(U->getBase()); 2872 } 2873 void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) { 2874 AddStmt(E->getSubExpr()); 2875 AddTypeLoc(E->getWrittenTypeInfo()); 2876 } 2877 void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 2878 WL.push_back(SizeOfPackExprParts(E, Parent)); 2879 } 2880 void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 2881 // If the opaque value has a source expression, just transparently 2882 // visit that. This is useful for (e.g.) pseudo-object expressions. 2883 if (Expr *SourceExpr = E->getSourceExpr()) 2884 return Visit(SourceExpr); 2885 } 2886 void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) { 2887 AddStmt(E->getBody()); 2888 WL.push_back(LambdaExprParts(E, Parent)); 2889 } 2890 void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) { 2891 // Treat the expression like its syntactic form. 2892 Visit(E->getSyntacticForm()); 2893 } 2894 2895 void EnqueueVisitor::VisitOMPExecutableDirective( 2896 const OMPExecutableDirective *D) { 2897 EnqueueChildren(D); 2898 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(), 2899 E = D->clauses().end(); 2900 I != E; ++I) 2901 EnqueueChildren(*I); 2902 } 2903 2904 void EnqueueVisitor::VisitOMPLoopBasedDirective( 2905 const OMPLoopBasedDirective *D) { 2906 VisitOMPExecutableDirective(D); 2907 } 2908 2909 void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) { 2910 VisitOMPLoopBasedDirective(D); 2911 } 2912 2913 void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) { 2914 VisitOMPExecutableDirective(D); 2915 } 2916 2917 void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) { 2918 VisitOMPLoopDirective(D); 2919 } 2920 2921 void EnqueueVisitor::VisitOMPLoopTransformationDirective( 2922 const OMPLoopTransformationDirective *D) { 2923 VisitOMPLoopBasedDirective(D); 2924 } 2925 2926 void EnqueueVisitor::VisitOMPTileDirective(const OMPTileDirective *D) { 2927 VisitOMPLoopTransformationDirective(D); 2928 } 2929 2930 void EnqueueVisitor::VisitOMPUnrollDirective(const OMPUnrollDirective *D) { 2931 VisitOMPLoopTransformationDirective(D); 2932 } 2933 2934 void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) { 2935 VisitOMPLoopDirective(D); 2936 } 2937 2938 void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) { 2939 VisitOMPLoopDirective(D); 2940 } 2941 2942 void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) { 2943 VisitOMPExecutableDirective(D); 2944 } 2945 2946 void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) { 2947 VisitOMPExecutableDirective(D); 2948 } 2949 2950 void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) { 2951 VisitOMPExecutableDirective(D); 2952 } 2953 2954 void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) { 2955 VisitOMPExecutableDirective(D); 2956 } 2957 2958 void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) { 2959 VisitOMPExecutableDirective(D); 2960 AddDeclarationNameInfo(D); 2961 } 2962 2963 void EnqueueVisitor::VisitOMPParallelForDirective( 2964 const OMPParallelForDirective *D) { 2965 VisitOMPLoopDirective(D); 2966 } 2967 2968 void EnqueueVisitor::VisitOMPParallelForSimdDirective( 2969 const OMPParallelForSimdDirective *D) { 2970 VisitOMPLoopDirective(D); 2971 } 2972 2973 void EnqueueVisitor::VisitOMPParallelMasterDirective( 2974 const OMPParallelMasterDirective *D) { 2975 VisitOMPExecutableDirective(D); 2976 } 2977 2978 void EnqueueVisitor::VisitOMPParallelSectionsDirective( 2979 const OMPParallelSectionsDirective *D) { 2980 VisitOMPExecutableDirective(D); 2981 } 2982 2983 void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) { 2984 VisitOMPExecutableDirective(D); 2985 } 2986 2987 void EnqueueVisitor::VisitOMPTaskyieldDirective( 2988 const OMPTaskyieldDirective *D) { 2989 VisitOMPExecutableDirective(D); 2990 } 2991 2992 void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) { 2993 VisitOMPExecutableDirective(D); 2994 } 2995 2996 void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) { 2997 VisitOMPExecutableDirective(D); 2998 } 2999 3000 void EnqueueVisitor::VisitOMPTaskgroupDirective( 3001 const OMPTaskgroupDirective *D) { 3002 VisitOMPExecutableDirective(D); 3003 if (const Expr *E = D->getReductionRef()) 3004 VisitStmt(E); 3005 } 3006 3007 void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) { 3008 VisitOMPExecutableDirective(D); 3009 } 3010 3011 void EnqueueVisitor::VisitOMPDepobjDirective(const OMPDepobjDirective *D) { 3012 VisitOMPExecutableDirective(D); 3013 } 3014 3015 void EnqueueVisitor::VisitOMPScanDirective(const OMPScanDirective *D) { 3016 VisitOMPExecutableDirective(D); 3017 } 3018 3019 void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) { 3020 VisitOMPExecutableDirective(D); 3021 } 3022 3023 void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) { 3024 VisitOMPExecutableDirective(D); 3025 } 3026 3027 void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) { 3028 VisitOMPExecutableDirective(D); 3029 } 3030 3031 void EnqueueVisitor::VisitOMPTargetDataDirective( 3032 const OMPTargetDataDirective *D) { 3033 VisitOMPExecutableDirective(D); 3034 } 3035 3036 void EnqueueVisitor::VisitOMPTargetEnterDataDirective( 3037 const OMPTargetEnterDataDirective *D) { 3038 VisitOMPExecutableDirective(D); 3039 } 3040 3041 void EnqueueVisitor::VisitOMPTargetExitDataDirective( 3042 const OMPTargetExitDataDirective *D) { 3043 VisitOMPExecutableDirective(D); 3044 } 3045 3046 void EnqueueVisitor::VisitOMPTargetParallelDirective( 3047 const OMPTargetParallelDirective *D) { 3048 VisitOMPExecutableDirective(D); 3049 } 3050 3051 void EnqueueVisitor::VisitOMPTargetParallelForDirective( 3052 const OMPTargetParallelForDirective *D) { 3053 VisitOMPLoopDirective(D); 3054 } 3055 3056 void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) { 3057 VisitOMPExecutableDirective(D); 3058 } 3059 3060 void EnqueueVisitor::VisitOMPCancellationPointDirective( 3061 const OMPCancellationPointDirective *D) { 3062 VisitOMPExecutableDirective(D); 3063 } 3064 3065 void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) { 3066 VisitOMPExecutableDirective(D); 3067 } 3068 3069 void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) { 3070 VisitOMPLoopDirective(D); 3071 } 3072 3073 void EnqueueVisitor::VisitOMPTaskLoopSimdDirective( 3074 const OMPTaskLoopSimdDirective *D) { 3075 VisitOMPLoopDirective(D); 3076 } 3077 3078 void EnqueueVisitor::VisitOMPMasterTaskLoopDirective( 3079 const OMPMasterTaskLoopDirective *D) { 3080 VisitOMPLoopDirective(D); 3081 } 3082 3083 void EnqueueVisitor::VisitOMPMasterTaskLoopSimdDirective( 3084 const OMPMasterTaskLoopSimdDirective *D) { 3085 VisitOMPLoopDirective(D); 3086 } 3087 3088 void EnqueueVisitor::VisitOMPParallelMasterTaskLoopDirective( 3089 const OMPParallelMasterTaskLoopDirective *D) { 3090 VisitOMPLoopDirective(D); 3091 } 3092 3093 void EnqueueVisitor::VisitOMPParallelMasterTaskLoopSimdDirective( 3094 const OMPParallelMasterTaskLoopSimdDirective *D) { 3095 VisitOMPLoopDirective(D); 3096 } 3097 3098 void EnqueueVisitor::VisitOMPDistributeDirective( 3099 const OMPDistributeDirective *D) { 3100 VisitOMPLoopDirective(D); 3101 } 3102 3103 void EnqueueVisitor::VisitOMPDistributeParallelForDirective( 3104 const OMPDistributeParallelForDirective *D) { 3105 VisitOMPLoopDirective(D); 3106 } 3107 3108 void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective( 3109 const OMPDistributeParallelForSimdDirective *D) { 3110 VisitOMPLoopDirective(D); 3111 } 3112 3113 void EnqueueVisitor::VisitOMPDistributeSimdDirective( 3114 const OMPDistributeSimdDirective *D) { 3115 VisitOMPLoopDirective(D); 3116 } 3117 3118 void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective( 3119 const OMPTargetParallelForSimdDirective *D) { 3120 VisitOMPLoopDirective(D); 3121 } 3122 3123 void EnqueueVisitor::VisitOMPTargetSimdDirective( 3124 const OMPTargetSimdDirective *D) { 3125 VisitOMPLoopDirective(D); 3126 } 3127 3128 void EnqueueVisitor::VisitOMPTeamsDistributeDirective( 3129 const OMPTeamsDistributeDirective *D) { 3130 VisitOMPLoopDirective(D); 3131 } 3132 3133 void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective( 3134 const OMPTeamsDistributeSimdDirective *D) { 3135 VisitOMPLoopDirective(D); 3136 } 3137 3138 void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective( 3139 const OMPTeamsDistributeParallelForSimdDirective *D) { 3140 VisitOMPLoopDirective(D); 3141 } 3142 3143 void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective( 3144 const OMPTeamsDistributeParallelForDirective *D) { 3145 VisitOMPLoopDirective(D); 3146 } 3147 3148 void EnqueueVisitor::VisitOMPTargetTeamsDirective( 3149 const OMPTargetTeamsDirective *D) { 3150 VisitOMPExecutableDirective(D); 3151 } 3152 3153 void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective( 3154 const OMPTargetTeamsDistributeDirective *D) { 3155 VisitOMPLoopDirective(D); 3156 } 3157 3158 void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective( 3159 const OMPTargetTeamsDistributeParallelForDirective *D) { 3160 VisitOMPLoopDirective(D); 3161 } 3162 3163 void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective( 3164 const OMPTargetTeamsDistributeParallelForSimdDirective *D) { 3165 VisitOMPLoopDirective(D); 3166 } 3167 3168 void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective( 3169 const OMPTargetTeamsDistributeSimdDirective *D) { 3170 VisitOMPLoopDirective(D); 3171 } 3172 3173 void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) { 3174 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU, RegionOfInterest)) 3175 .Visit(S); 3176 } 3177 3178 bool CursorVisitor::IsInRegionOfInterest(CXCursor C) { 3179 if (RegionOfInterest.isValid()) { 3180 SourceRange Range = getRawCursorExtent(C); 3181 if (Range.isInvalid() || CompareRegionOfInterest(Range)) 3182 return false; 3183 } 3184 return true; 3185 } 3186 3187 bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) { 3188 while (!WL.empty()) { 3189 // Dequeue the worklist item. 3190 VisitorJob LI = WL.pop_back_val(); 3191 3192 // Set the Parent field, then back to its old value once we're done. 3193 SetParentRAII SetParent(Parent, StmtParent, LI.getParent()); 3194 3195 switch (LI.getKind()) { 3196 case VisitorJob::DeclVisitKind: { 3197 const Decl *D = cast<DeclVisit>(&LI)->get(); 3198 if (!D) 3199 continue; 3200 3201 // For now, perform default visitation for Decls. 3202 if (Visit(MakeCXCursor(D, TU, RegionOfInterest, 3203 cast<DeclVisit>(&LI)->isFirst()))) 3204 return true; 3205 3206 continue; 3207 } 3208 case VisitorJob::ExplicitTemplateArgsVisitKind: { 3209 for (const TemplateArgumentLoc &Arg : 3210 *cast<ExplicitTemplateArgsVisit>(&LI)) { 3211 if (VisitTemplateArgumentLoc(Arg)) 3212 return true; 3213 } 3214 continue; 3215 } 3216 case VisitorJob::TypeLocVisitKind: { 3217 // Perform default visitation for TypeLocs. 3218 if (Visit(cast<TypeLocVisit>(&LI)->get())) 3219 return true; 3220 continue; 3221 } 3222 case VisitorJob::LabelRefVisitKind: { 3223 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get(); 3224 if (LabelStmt *stmt = LS->getStmt()) { 3225 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(), 3226 TU))) { 3227 return true; 3228 } 3229 } 3230 continue; 3231 } 3232 3233 case VisitorJob::NestedNameSpecifierLocVisitKind: { 3234 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI); 3235 if (VisitNestedNameSpecifierLoc(V->get())) 3236 return true; 3237 continue; 3238 } 3239 3240 case VisitorJob::DeclarationNameInfoVisitKind: { 3241 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)->get())) 3242 return true; 3243 continue; 3244 } 3245 case VisitorJob::MemberRefVisitKind: { 3246 MemberRefVisit *V = cast<MemberRefVisit>(&LI); 3247 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU))) 3248 return true; 3249 continue; 3250 } 3251 case VisitorJob::StmtVisitKind: { 3252 const Stmt *S = cast<StmtVisit>(&LI)->get(); 3253 if (!S) 3254 continue; 3255 3256 // Update the current cursor. 3257 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest); 3258 if (!IsInRegionOfInterest(Cursor)) 3259 continue; 3260 switch (Visitor(Cursor, Parent, ClientData)) { 3261 case CXChildVisit_Break: 3262 return true; 3263 case CXChildVisit_Continue: 3264 break; 3265 case CXChildVisit_Recurse: 3266 if (PostChildrenVisitor) 3267 WL.push_back(PostChildrenVisit(nullptr, Cursor)); 3268 EnqueueWorkList(WL, S); 3269 break; 3270 } 3271 continue; 3272 } 3273 case VisitorJob::MemberExprPartsKind: { 3274 // Handle the other pieces in the MemberExpr besides the base. 3275 const MemberExpr *M = cast<MemberExprParts>(&LI)->get(); 3276 3277 // Visit the nested-name-specifier 3278 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc()) 3279 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 3280 return true; 3281 3282 // Visit the declaration name. 3283 if (VisitDeclarationNameInfo(M->getMemberNameInfo())) 3284 return true; 3285 3286 // Visit the explicitly-specified template arguments, if any. 3287 if (M->hasExplicitTemplateArgs()) { 3288 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(), 3289 *ArgEnd = Arg + M->getNumTemplateArgs(); 3290 Arg != ArgEnd; ++Arg) { 3291 if (VisitTemplateArgumentLoc(*Arg)) 3292 return true; 3293 } 3294 } 3295 continue; 3296 } 3297 case VisitorJob::DeclRefExprPartsKind: { 3298 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get(); 3299 // Visit nested-name-specifier, if present. 3300 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc()) 3301 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 3302 return true; 3303 // Visit declaration name. 3304 if (VisitDeclarationNameInfo(DR->getNameInfo())) 3305 return true; 3306 continue; 3307 } 3308 case VisitorJob::OverloadExprPartsKind: { 3309 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get(); 3310 // Visit the nested-name-specifier. 3311 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc()) 3312 if (VisitNestedNameSpecifierLoc(QualifierLoc)) 3313 return true; 3314 // Visit the declaration name. 3315 if (VisitDeclarationNameInfo(O->getNameInfo())) 3316 return true; 3317 // Visit the overloaded declaration reference. 3318 if (Visit(MakeCursorOverloadedDeclRef(O, TU))) 3319 return true; 3320 continue; 3321 } 3322 case VisitorJob::SizeOfPackExprPartsKind: { 3323 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get(); 3324 NamedDecl *Pack = E->getPack(); 3325 if (isa<TemplateTypeParmDecl>(Pack)) { 3326 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack), 3327 E->getPackLoc(), TU))) 3328 return true; 3329 3330 continue; 3331 } 3332 3333 if (isa<TemplateTemplateParmDecl>(Pack)) { 3334 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack), 3335 E->getPackLoc(), TU))) 3336 return true; 3337 3338 continue; 3339 } 3340 3341 // Non-type template parameter packs and function parameter packs are 3342 // treated like DeclRefExpr cursors. 3343 continue; 3344 } 3345 3346 case VisitorJob::LambdaExprPartsKind: { 3347 // Visit non-init captures. 3348 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get(); 3349 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(), 3350 CEnd = E->explicit_capture_end(); 3351 C != CEnd; ++C) { 3352 if (!C->capturesVariable()) 3353 continue; 3354 3355 if (Visit(MakeCursorVariableRef(C->getCapturedVar(), C->getLocation(), 3356 TU))) 3357 return true; 3358 } 3359 // Visit init captures 3360 for (auto InitExpr : E->capture_inits()) { 3361 if (InitExpr && Visit(InitExpr)) 3362 return true; 3363 } 3364 3365 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc(); 3366 // Visit parameters and return type, if present. 3367 if (FunctionTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) { 3368 if (E->hasExplicitParameters()) { 3369 // Visit parameters. 3370 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I) 3371 if (Visit(MakeCXCursor(Proto.getParam(I), TU))) 3372 return true; 3373 } 3374 if (E->hasExplicitResultType()) { 3375 // Visit result type. 3376 if (Visit(Proto.getReturnLoc())) 3377 return true; 3378 } 3379 } 3380 break; 3381 } 3382 3383 case VisitorJob::PostChildrenVisitKind: 3384 if (PostChildrenVisitor(Parent, ClientData)) 3385 return true; 3386 break; 3387 } 3388 } 3389 return false; 3390 } 3391 3392 bool CursorVisitor::Visit(const Stmt *S) { 3393 VisitorWorkList *WL = nullptr; 3394 if (!WorkListFreeList.empty()) { 3395 WL = WorkListFreeList.back(); 3396 WL->clear(); 3397 WorkListFreeList.pop_back(); 3398 } else { 3399 WL = new VisitorWorkList(); 3400 WorkListCache.push_back(WL); 3401 } 3402 EnqueueWorkList(*WL, S); 3403 bool result = RunVisitorWorkList(*WL); 3404 WorkListFreeList.push_back(WL); 3405 return result; 3406 } 3407 3408 namespace { 3409 typedef SmallVector<SourceRange, 4> RefNamePieces; 3410 RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr, 3411 const DeclarationNameInfo &NI, SourceRange QLoc, 3412 const SourceRange *TemplateArgsLoc = nullptr) { 3413 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier; 3414 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs; 3415 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece; 3416 3417 const DeclarationName::NameKind Kind = NI.getName().getNameKind(); 3418 3419 RefNamePieces Pieces; 3420 3421 if (WantQualifier && QLoc.isValid()) 3422 Pieces.push_back(QLoc); 3423 3424 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr) 3425 Pieces.push_back(NI.getLoc()); 3426 3427 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid()) 3428 Pieces.push_back(*TemplateArgsLoc); 3429 3430 if (Kind == DeclarationName::CXXOperatorName) { 3431 Pieces.push_back(NI.getInfo().getCXXOperatorNameBeginLoc()); 3432 Pieces.push_back(NI.getInfo().getCXXOperatorNameEndLoc()); 3433 } 3434 3435 if (WantSinglePiece) { 3436 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd()); 3437 Pieces.clear(); 3438 Pieces.push_back(R); 3439 } 3440 3441 return Pieces; 3442 } 3443 } // namespace 3444 3445 //===----------------------------------------------------------------------===// 3446 // Misc. API hooks. 3447 //===----------------------------------------------------------------------===// 3448 3449 namespace { 3450 struct RegisterFatalErrorHandler { 3451 RegisterFatalErrorHandler() { 3452 clang_install_aborting_llvm_fatal_error_handler(); 3453 } 3454 }; 3455 } // namespace 3456 3457 static llvm::ManagedStatic<RegisterFatalErrorHandler> 3458 RegisterFatalErrorHandlerOnce; 3459 3460 CXIndex clang_createIndex(int excludeDeclarationsFromPCH, 3461 int displayDiagnostics) { 3462 // We use crash recovery to make some of our APIs more reliable, implicitly 3463 // enable it. 3464 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY")) 3465 llvm::CrashRecoveryContext::Enable(); 3466 3467 // Look through the managed static to trigger construction of the managed 3468 // static which registers our fatal error handler. This ensures it is only 3469 // registered once. 3470 (void)*RegisterFatalErrorHandlerOnce; 3471 3472 // Initialize targets for clang module support. 3473 llvm::InitializeAllTargets(); 3474 llvm::InitializeAllTargetMCs(); 3475 llvm::InitializeAllAsmPrinters(); 3476 llvm::InitializeAllAsmParsers(); 3477 3478 CIndexer *CIdxr = new CIndexer(); 3479 3480 if (excludeDeclarationsFromPCH) 3481 CIdxr->setOnlyLocalDecls(); 3482 if (displayDiagnostics) 3483 CIdxr->setDisplayDiagnostics(); 3484 3485 if (getenv("LIBCLANG_BGPRIO_INDEX")) 3486 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() | 3487 CXGlobalOpt_ThreadBackgroundPriorityForIndexing); 3488 if (getenv("LIBCLANG_BGPRIO_EDIT")) 3489 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() | 3490 CXGlobalOpt_ThreadBackgroundPriorityForEditing); 3491 3492 return CIdxr; 3493 } 3494 3495 void clang_disposeIndex(CXIndex CIdx) { 3496 if (CIdx) 3497 delete static_cast<CIndexer *>(CIdx); 3498 } 3499 3500 void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) { 3501 if (CIdx) 3502 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options); 3503 } 3504 3505 unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) { 3506 if (CIdx) 3507 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags(); 3508 return 0; 3509 } 3510 3511 void clang_CXIndex_setInvocationEmissionPathOption(CXIndex CIdx, 3512 const char *Path) { 3513 if (CIdx) 3514 static_cast<CIndexer *>(CIdx)->setInvocationEmissionPath(Path ? Path : ""); 3515 } 3516 3517 void clang_toggleCrashRecovery(unsigned isEnabled) { 3518 if (isEnabled) 3519 llvm::CrashRecoveryContext::Enable(); 3520 else 3521 llvm::CrashRecoveryContext::Disable(); 3522 } 3523 3524 CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx, 3525 const char *ast_filename) { 3526 CXTranslationUnit TU; 3527 enum CXErrorCode Result = 3528 clang_createTranslationUnit2(CIdx, ast_filename, &TU); 3529 (void)Result; 3530 assert((TU && Result == CXError_Success) || 3531 (!TU && Result != CXError_Success)); 3532 return TU; 3533 } 3534 3535 enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx, 3536 const char *ast_filename, 3537 CXTranslationUnit *out_TU) { 3538 if (out_TU) 3539 *out_TU = nullptr; 3540 3541 if (!CIdx || !ast_filename || !out_TU) 3542 return CXError_InvalidArguments; 3543 3544 LOG_FUNC_SECTION { *Log << ast_filename; } 3545 3546 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx); 3547 FileSystemOptions FileSystemOpts; 3548 3549 IntrusiveRefCntPtr<DiagnosticsEngine> Diags = 3550 CompilerInstance::createDiagnostics(new DiagnosticOptions()); 3551 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile( 3552 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(), 3553 ASTUnit::LoadEverything, Diags, FileSystemOpts, /*UseDebugInfo=*/false, 3554 CXXIdx->getOnlyLocalDecls(), CaptureDiagsKind::All, 3555 /*AllowASTWithCompilerErrors=*/true, 3556 /*UserFilesAreVolatile=*/true); 3557 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU)); 3558 return *out_TU ? CXError_Success : CXError_Failure; 3559 } 3560 3561 unsigned clang_defaultEditingTranslationUnitOptions() { 3562 return CXTranslationUnit_PrecompiledPreamble | 3563 CXTranslationUnit_CacheCompletionResults; 3564 } 3565 3566 CXTranslationUnit clang_createTranslationUnitFromSourceFile( 3567 CXIndex CIdx, const char *source_filename, int num_command_line_args, 3568 const char *const *command_line_args, unsigned num_unsaved_files, 3569 struct CXUnsavedFile *unsaved_files) { 3570 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord; 3571 return clang_parseTranslationUnit(CIdx, source_filename, command_line_args, 3572 num_command_line_args, unsaved_files, 3573 num_unsaved_files, Options); 3574 } 3575 3576 static CXErrorCode 3577 clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename, 3578 const char *const *command_line_args, 3579 int num_command_line_args, 3580 ArrayRef<CXUnsavedFile> unsaved_files, 3581 unsigned options, CXTranslationUnit *out_TU) { 3582 // Set up the initial return values. 3583 if (out_TU) 3584 *out_TU = nullptr; 3585 3586 // Check arguments. 3587 if (!CIdx || !out_TU) 3588 return CXError_InvalidArguments; 3589 3590 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx); 3591 3592 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing)) 3593 setThreadBackgroundPriority(); 3594 3595 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble; 3596 bool CreatePreambleOnFirstParse = 3597 options & CXTranslationUnit_CreatePreambleOnFirstParse; 3598 // FIXME: Add a flag for modules. 3599 TranslationUnitKind TUKind = (options & (CXTranslationUnit_Incomplete | 3600 CXTranslationUnit_SingleFileParse)) 3601 ? TU_Prefix 3602 : TU_Complete; 3603 bool CacheCodeCompletionResults = 3604 options & CXTranslationUnit_CacheCompletionResults; 3605 bool IncludeBriefCommentsInCodeCompletion = 3606 options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion; 3607 bool SingleFileParse = options & CXTranslationUnit_SingleFileParse; 3608 bool ForSerialization = options & CXTranslationUnit_ForSerialization; 3609 bool RetainExcludedCB = 3610 options & CXTranslationUnit_RetainExcludedConditionalBlocks; 3611 SkipFunctionBodiesScope SkipFunctionBodies = SkipFunctionBodiesScope::None; 3612 if (options & CXTranslationUnit_SkipFunctionBodies) { 3613 SkipFunctionBodies = 3614 (options & CXTranslationUnit_LimitSkipFunctionBodiesToPreamble) 3615 ? SkipFunctionBodiesScope::Preamble 3616 : SkipFunctionBodiesScope::PreambleAndMainFile; 3617 } 3618 3619 // Configure the diagnostics. 3620 IntrusiveRefCntPtr<DiagnosticsEngine> Diags( 3621 CompilerInstance::createDiagnostics(new DiagnosticOptions)); 3622 3623 if (options & CXTranslationUnit_KeepGoing) 3624 Diags->setFatalsAsError(true); 3625 3626 CaptureDiagsKind CaptureDiagnostics = CaptureDiagsKind::All; 3627 if (options & CXTranslationUnit_IgnoreNonErrorsFromIncludedFiles) 3628 CaptureDiagnostics = CaptureDiagsKind::AllWithoutNonErrorsFromIncludes; 3629 3630 // Recover resources if we crash before exiting this function. 3631 llvm::CrashRecoveryContextCleanupRegistrar< 3632 DiagnosticsEngine, 3633 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>> 3634 DiagCleanup(Diags.get()); 3635 3636 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles( 3637 new std::vector<ASTUnit::RemappedFile>()); 3638 3639 // Recover resources if we crash before exiting this function. 3640 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<ASTUnit::RemappedFile>> 3641 RemappedCleanup(RemappedFiles.get()); 3642 3643 for (auto &UF : unsaved_files) { 3644 std::unique_ptr<llvm::MemoryBuffer> MB = 3645 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename); 3646 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release())); 3647 } 3648 3649 std::unique_ptr<std::vector<const char *>> Args( 3650 new std::vector<const char *>()); 3651 3652 // Recover resources if we crash before exiting this method. 3653 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char *>> 3654 ArgsCleanup(Args.get()); 3655 3656 // Since the Clang C library is primarily used by batch tools dealing with 3657 // (often very broken) source code, where spell-checking can have a 3658 // significant negative impact on performance (particularly when 3659 // precompiled headers are involved), we disable it by default. 3660 // Only do this if we haven't found a spell-checking-related argument. 3661 bool FoundSpellCheckingArgument = false; 3662 for (int I = 0; I != num_command_line_args; ++I) { 3663 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 || 3664 strcmp(command_line_args[I], "-fspell-checking") == 0) { 3665 FoundSpellCheckingArgument = true; 3666 break; 3667 } 3668 } 3669 Args->insert(Args->end(), command_line_args, 3670 command_line_args + num_command_line_args); 3671 3672 if (!FoundSpellCheckingArgument) 3673 Args->insert(Args->begin() + 1, "-fno-spell-checking"); 3674 3675 // The 'source_filename' argument is optional. If the caller does not 3676 // specify it then it is assumed that the source file is specified 3677 // in the actual argument list. 3678 // Put the source file after command_line_args otherwise if '-x' flag is 3679 // present it will be unused. 3680 if (source_filename) 3681 Args->push_back(source_filename); 3682 3683 // Do we need the detailed preprocessing record? 3684 if (options & CXTranslationUnit_DetailedPreprocessingRecord) { 3685 Args->push_back("-Xclang"); 3686 Args->push_back("-detailed-preprocessing-record"); 3687 } 3688 3689 // Suppress any editor placeholder diagnostics. 3690 Args->push_back("-fallow-editor-placeholders"); 3691 3692 unsigned NumErrors = Diags->getClient()->getNumErrors(); 3693 std::unique_ptr<ASTUnit> ErrUnit; 3694 // Unless the user specified that they want the preamble on the first parse 3695 // set it up to be created on the first reparse. This makes the first parse 3696 // faster, trading for a slower (first) reparse. 3697 unsigned PrecompilePreambleAfterNParses = 3698 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse; 3699 3700 LibclangInvocationReporter InvocationReporter( 3701 *CXXIdx, LibclangInvocationReporter::OperationKind::ParseOperation, 3702 options, llvm::makeArrayRef(*Args), /*InvocationArgs=*/None, 3703 unsaved_files); 3704 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine( 3705 Args->data(), Args->data() + Args->size(), 3706 CXXIdx->getPCHContainerOperations(), Diags, 3707 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(), 3708 CaptureDiagnostics, *RemappedFiles.get(), 3709 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses, 3710 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion, 3711 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, SingleFileParse, 3712 /*UserFilesAreVolatile=*/true, ForSerialization, RetainExcludedCB, 3713 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(), 3714 &ErrUnit)); 3715 3716 // Early failures in LoadFromCommandLine may return with ErrUnit unset. 3717 if (!Unit && !ErrUnit) 3718 return CXError_ASTReadError; 3719 3720 if (NumErrors != Diags->getClient()->getNumErrors()) { 3721 // Make sure to check that 'Unit' is non-NULL. 3722 if (CXXIdx->getDisplayDiagnostics()) 3723 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get()); 3724 } 3725 3726 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get())) 3727 return CXError_ASTReadError; 3728 3729 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit)); 3730 if (CXTranslationUnitImpl *TU = *out_TU) { 3731 TU->ParsingOptions = options; 3732 TU->Arguments.reserve(Args->size()); 3733 for (const char *Arg : *Args) 3734 TU->Arguments.push_back(Arg); 3735 return CXError_Success; 3736 } 3737 return CXError_Failure; 3738 } 3739 3740 CXTranslationUnit 3741 clang_parseTranslationUnit(CXIndex CIdx, const char *source_filename, 3742 const char *const *command_line_args, 3743 int num_command_line_args, 3744 struct CXUnsavedFile *unsaved_files, 3745 unsigned num_unsaved_files, unsigned options) { 3746 CXTranslationUnit TU; 3747 enum CXErrorCode Result = clang_parseTranslationUnit2( 3748 CIdx, source_filename, command_line_args, num_command_line_args, 3749 unsaved_files, num_unsaved_files, options, &TU); 3750 (void)Result; 3751 assert((TU && Result == CXError_Success) || 3752 (!TU && Result != CXError_Success)); 3753 return TU; 3754 } 3755 3756 enum CXErrorCode clang_parseTranslationUnit2( 3757 CXIndex CIdx, const char *source_filename, 3758 const char *const *command_line_args, int num_command_line_args, 3759 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files, 3760 unsigned options, CXTranslationUnit *out_TU) { 3761 noteBottomOfStack(); 3762 SmallVector<const char *, 4> Args; 3763 Args.push_back("clang"); 3764 Args.append(command_line_args, command_line_args + num_command_line_args); 3765 return clang_parseTranslationUnit2FullArgv( 3766 CIdx, source_filename, Args.data(), Args.size(), unsaved_files, 3767 num_unsaved_files, options, out_TU); 3768 } 3769 3770 enum CXErrorCode clang_parseTranslationUnit2FullArgv( 3771 CXIndex CIdx, const char *source_filename, 3772 const char *const *command_line_args, int num_command_line_args, 3773 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files, 3774 unsigned options, CXTranslationUnit *out_TU) { 3775 LOG_FUNC_SECTION { 3776 *Log << source_filename << ": "; 3777 for (int i = 0; i != num_command_line_args; ++i) 3778 *Log << command_line_args[i] << " "; 3779 } 3780 3781 if (num_unsaved_files && !unsaved_files) 3782 return CXError_InvalidArguments; 3783 3784 CXErrorCode result = CXError_Failure; 3785 auto ParseTranslationUnitImpl = [=, &result] { 3786 noteBottomOfStack(); 3787 result = clang_parseTranslationUnit_Impl( 3788 CIdx, source_filename, command_line_args, num_command_line_args, 3789 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU); 3790 }; 3791 3792 llvm::CrashRecoveryContext CRC; 3793 3794 if (!RunSafely(CRC, ParseTranslationUnitImpl)) { 3795 fprintf(stderr, "libclang: crash detected during parsing: {\n"); 3796 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename); 3797 fprintf(stderr, " 'command_line_args' : ["); 3798 for (int i = 0; i != num_command_line_args; ++i) { 3799 if (i) 3800 fprintf(stderr, ", "); 3801 fprintf(stderr, "'%s'", command_line_args[i]); 3802 } 3803 fprintf(stderr, "],\n"); 3804 fprintf(stderr, " 'unsaved_files' : ["); 3805 for (unsigned i = 0; i != num_unsaved_files; ++i) { 3806 if (i) 3807 fprintf(stderr, ", "); 3808 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename, 3809 unsaved_files[i].Length); 3810 } 3811 fprintf(stderr, "],\n"); 3812 fprintf(stderr, " 'options' : %d,\n", options); 3813 fprintf(stderr, "}\n"); 3814 3815 return CXError_Crashed; 3816 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) { 3817 if (CXTranslationUnit *TU = out_TU) 3818 PrintLibclangResourceUsage(*TU); 3819 } 3820 3821 return result; 3822 } 3823 3824 CXString clang_Type_getObjCEncoding(CXType CT) { 3825 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]); 3826 ASTContext &Ctx = getASTUnit(tu)->getASTContext(); 3827 std::string encoding; 3828 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]), encoding); 3829 3830 return cxstring::createDup(encoding); 3831 } 3832 3833 static const IdentifierInfo *getMacroIdentifier(CXCursor C) { 3834 if (C.kind == CXCursor_MacroDefinition) { 3835 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C)) 3836 return MDR->getName(); 3837 } else if (C.kind == CXCursor_MacroExpansion) { 3838 MacroExpansionCursor ME = getCursorMacroExpansion(C); 3839 return ME.getName(); 3840 } 3841 return nullptr; 3842 } 3843 3844 unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) { 3845 const IdentifierInfo *II = getMacroIdentifier(C); 3846 if (!II) { 3847 return false; 3848 } 3849 ASTUnit *ASTU = getCursorASTUnit(C); 3850 Preprocessor &PP = ASTU->getPreprocessor(); 3851 if (const MacroInfo *MI = PP.getMacroInfo(II)) 3852 return MI->isFunctionLike(); 3853 return false; 3854 } 3855 3856 unsigned clang_Cursor_isMacroBuiltin(CXCursor C) { 3857 const IdentifierInfo *II = getMacroIdentifier(C); 3858 if (!II) { 3859 return false; 3860 } 3861 ASTUnit *ASTU = getCursorASTUnit(C); 3862 Preprocessor &PP = ASTU->getPreprocessor(); 3863 if (const MacroInfo *MI = PP.getMacroInfo(II)) 3864 return MI->isBuiltinMacro(); 3865 return false; 3866 } 3867 3868 unsigned clang_Cursor_isFunctionInlined(CXCursor C) { 3869 const Decl *D = getCursorDecl(C); 3870 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 3871 if (!FD) { 3872 return false; 3873 } 3874 return FD->isInlined(); 3875 } 3876 3877 static StringLiteral *getCFSTR_value(CallExpr *callExpr) { 3878 if (callExpr->getNumArgs() != 1) { 3879 return nullptr; 3880 } 3881 3882 StringLiteral *S = nullptr; 3883 auto *arg = callExpr->getArg(0); 3884 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) { 3885 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg); 3886 auto *subExpr = I->getSubExprAsWritten(); 3887 3888 if (subExpr->getStmtClass() != Stmt::StringLiteralClass) { 3889 return nullptr; 3890 } 3891 3892 S = static_cast<StringLiteral *>(I->getSubExprAsWritten()); 3893 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) { 3894 S = static_cast<StringLiteral *>(callExpr->getArg(0)); 3895 } else { 3896 return nullptr; 3897 } 3898 return S; 3899 } 3900 3901 struct ExprEvalResult { 3902 CXEvalResultKind EvalType; 3903 union { 3904 unsigned long long unsignedVal; 3905 long long intVal; 3906 double floatVal; 3907 char *stringVal; 3908 } EvalData; 3909 bool IsUnsignedInt; 3910 ~ExprEvalResult() { 3911 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float && 3912 EvalType != CXEval_Int) { 3913 delete[] EvalData.stringVal; 3914 } 3915 } 3916 }; 3917 3918 void clang_EvalResult_dispose(CXEvalResult E) { 3919 delete static_cast<ExprEvalResult *>(E); 3920 } 3921 3922 CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) { 3923 if (!E) { 3924 return CXEval_UnExposed; 3925 } 3926 return ((ExprEvalResult *)E)->EvalType; 3927 } 3928 3929 int clang_EvalResult_getAsInt(CXEvalResult E) { 3930 return clang_EvalResult_getAsLongLong(E); 3931 } 3932 3933 long long clang_EvalResult_getAsLongLong(CXEvalResult E) { 3934 if (!E) { 3935 return 0; 3936 } 3937 ExprEvalResult *Result = (ExprEvalResult *)E; 3938 if (Result->IsUnsignedInt) 3939 return Result->EvalData.unsignedVal; 3940 return Result->EvalData.intVal; 3941 } 3942 3943 unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) { 3944 return ((ExprEvalResult *)E)->IsUnsignedInt; 3945 } 3946 3947 unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) { 3948 if (!E) { 3949 return 0; 3950 } 3951 3952 ExprEvalResult *Result = (ExprEvalResult *)E; 3953 if (Result->IsUnsignedInt) 3954 return Result->EvalData.unsignedVal; 3955 return Result->EvalData.intVal; 3956 } 3957 3958 double clang_EvalResult_getAsDouble(CXEvalResult E) { 3959 if (!E) { 3960 return 0; 3961 } 3962 return ((ExprEvalResult *)E)->EvalData.floatVal; 3963 } 3964 3965 const char *clang_EvalResult_getAsStr(CXEvalResult E) { 3966 if (!E) { 3967 return nullptr; 3968 } 3969 return ((ExprEvalResult *)E)->EvalData.stringVal; 3970 } 3971 3972 static const ExprEvalResult *evaluateExpr(Expr *expr, CXCursor C) { 3973 Expr::EvalResult ER; 3974 ASTContext &ctx = getCursorContext(C); 3975 if (!expr) 3976 return nullptr; 3977 3978 expr = expr->IgnoreParens(); 3979 if (expr->isValueDependent()) 3980 return nullptr; 3981 if (!expr->EvaluateAsRValue(ER, ctx)) 3982 return nullptr; 3983 3984 QualType rettype; 3985 CallExpr *callExpr; 3986 auto result = std::make_unique<ExprEvalResult>(); 3987 result->EvalType = CXEval_UnExposed; 3988 result->IsUnsignedInt = false; 3989 3990 if (ER.Val.isInt()) { 3991 result->EvalType = CXEval_Int; 3992 3993 auto &val = ER.Val.getInt(); 3994 if (val.isUnsigned()) { 3995 result->IsUnsignedInt = true; 3996 result->EvalData.unsignedVal = val.getZExtValue(); 3997 } else { 3998 result->EvalData.intVal = val.getExtValue(); 3999 } 4000 4001 return result.release(); 4002 } 4003 4004 if (ER.Val.isFloat()) { 4005 llvm::SmallVector<char, 100> Buffer; 4006 ER.Val.getFloat().toString(Buffer); 4007 std::string floatStr(Buffer.data(), Buffer.size()); 4008 result->EvalType = CXEval_Float; 4009 bool ignored; 4010 llvm::APFloat apFloat = ER.Val.getFloat(); 4011 apFloat.convert(llvm::APFloat::IEEEdouble(), 4012 llvm::APFloat::rmNearestTiesToEven, &ignored); 4013 result->EvalData.floatVal = apFloat.convertToDouble(); 4014 return result.release(); 4015 } 4016 4017 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) { 4018 const auto *I = cast<ImplicitCastExpr>(expr); 4019 auto *subExpr = I->getSubExprAsWritten(); 4020 if (subExpr->getStmtClass() == Stmt::StringLiteralClass || 4021 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) { 4022 const StringLiteral *StrE = nullptr; 4023 const ObjCStringLiteral *ObjCExpr; 4024 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr); 4025 4026 if (ObjCExpr) { 4027 StrE = ObjCExpr->getString(); 4028 result->EvalType = CXEval_ObjCStrLiteral; 4029 } else { 4030 StrE = cast<StringLiteral>(I->getSubExprAsWritten()); 4031 result->EvalType = CXEval_StrLiteral; 4032 } 4033 4034 std::string strRef(StrE->getString().str()); 4035 result->EvalData.stringVal = new char[strRef.size() + 1]; 4036 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), 4037 strRef.size()); 4038 result->EvalData.stringVal[strRef.size()] = '\0'; 4039 return result.release(); 4040 } 4041 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass || 4042 expr->getStmtClass() == Stmt::StringLiteralClass) { 4043 const StringLiteral *StrE = nullptr; 4044 const ObjCStringLiteral *ObjCExpr; 4045 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr); 4046 4047 if (ObjCExpr) { 4048 StrE = ObjCExpr->getString(); 4049 result->EvalType = CXEval_ObjCStrLiteral; 4050 } else { 4051 StrE = cast<StringLiteral>(expr); 4052 result->EvalType = CXEval_StrLiteral; 4053 } 4054 4055 std::string strRef(StrE->getString().str()); 4056 result->EvalData.stringVal = new char[strRef.size() + 1]; 4057 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size()); 4058 result->EvalData.stringVal[strRef.size()] = '\0'; 4059 return result.release(); 4060 } 4061 4062 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) { 4063 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr); 4064 4065 rettype = CC->getType(); 4066 if (rettype.getAsString() == "CFStringRef" && 4067 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) { 4068 4069 callExpr = static_cast<CallExpr *>(CC->getSubExpr()); 4070 StringLiteral *S = getCFSTR_value(callExpr); 4071 if (S) { 4072 std::string strLiteral(S->getString().str()); 4073 result->EvalType = CXEval_CFStr; 4074 4075 result->EvalData.stringVal = new char[strLiteral.size() + 1]; 4076 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(), 4077 strLiteral.size()); 4078 result->EvalData.stringVal[strLiteral.size()] = '\0'; 4079 return result.release(); 4080 } 4081 } 4082 4083 } else if (expr->getStmtClass() == Stmt::CallExprClass) { 4084 callExpr = static_cast<CallExpr *>(expr); 4085 rettype = callExpr->getCallReturnType(ctx); 4086 4087 if (rettype->isVectorType() || callExpr->getNumArgs() > 1) 4088 return nullptr; 4089 4090 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) { 4091 if (callExpr->getNumArgs() == 1 && 4092 !callExpr->getArg(0)->getType()->isIntegralType(ctx)) 4093 return nullptr; 4094 } else if (rettype.getAsString() == "CFStringRef") { 4095 4096 StringLiteral *S = getCFSTR_value(callExpr); 4097 if (S) { 4098 std::string strLiteral(S->getString().str()); 4099 result->EvalType = CXEval_CFStr; 4100 result->EvalData.stringVal = new char[strLiteral.size() + 1]; 4101 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(), 4102 strLiteral.size()); 4103 result->EvalData.stringVal[strLiteral.size()] = '\0'; 4104 return result.release(); 4105 } 4106 } 4107 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) { 4108 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr); 4109 ValueDecl *V = D->getDecl(); 4110 if (V->getKind() == Decl::Function) { 4111 std::string strName = V->getNameAsString(); 4112 result->EvalType = CXEval_Other; 4113 result->EvalData.stringVal = new char[strName.size() + 1]; 4114 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size()); 4115 result->EvalData.stringVal[strName.size()] = '\0'; 4116 return result.release(); 4117 } 4118 } 4119 4120 return nullptr; 4121 } 4122 4123 static const Expr *evaluateDeclExpr(const Decl *D) { 4124 if (!D) 4125 return nullptr; 4126 if (auto *Var = dyn_cast<VarDecl>(D)) 4127 return Var->getInit(); 4128 else if (auto *Field = dyn_cast<FieldDecl>(D)) 4129 return Field->getInClassInitializer(); 4130 return nullptr; 4131 } 4132 4133 static const Expr *evaluateCompoundStmtExpr(const CompoundStmt *CS) { 4134 assert(CS && "invalid compound statement"); 4135 for (auto *bodyIterator : CS->body()) { 4136 if (const auto *E = dyn_cast<Expr>(bodyIterator)) 4137 return E; 4138 } 4139 return nullptr; 4140 } 4141 4142 CXEvalResult clang_Cursor_Evaluate(CXCursor C) { 4143 const Expr *E = nullptr; 4144 if (clang_getCursorKind(C) == CXCursor_CompoundStmt) 4145 E = evaluateCompoundStmtExpr(cast<CompoundStmt>(getCursorStmt(C))); 4146 else if (clang_isDeclaration(C.kind)) 4147 E = evaluateDeclExpr(getCursorDecl(C)); 4148 else if (clang_isExpression(C.kind)) 4149 E = getCursorExpr(C); 4150 if (E) 4151 return const_cast<CXEvalResult>( 4152 reinterpret_cast<const void *>(evaluateExpr(const_cast<Expr *>(E), C))); 4153 return nullptr; 4154 } 4155 4156 unsigned clang_Cursor_hasAttrs(CXCursor C) { 4157 const Decl *D = getCursorDecl(C); 4158 if (!D) { 4159 return 0; 4160 } 4161 4162 if (D->hasAttrs()) { 4163 return 1; 4164 } 4165 4166 return 0; 4167 } 4168 unsigned clang_defaultSaveOptions(CXTranslationUnit TU) { 4169 return CXSaveTranslationUnit_None; 4170 } 4171 4172 static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU, 4173 const char *FileName, 4174 unsigned options) { 4175 CIndexer *CXXIdx = TU->CIdx; 4176 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing)) 4177 setThreadBackgroundPriority(); 4178 4179 bool hadError = cxtu::getASTUnit(TU)->Save(FileName); 4180 return hadError ? CXSaveError_Unknown : CXSaveError_None; 4181 } 4182 4183 int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName, 4184 unsigned options) { 4185 LOG_FUNC_SECTION { *Log << TU << ' ' << FileName; } 4186 4187 if (isNotUsableTU(TU)) { 4188 LOG_BAD_TU(TU); 4189 return CXSaveError_InvalidTU; 4190 } 4191 4192 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 4193 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 4194 if (!CXXUnit->hasSema()) 4195 return CXSaveError_InvalidTU; 4196 4197 CXSaveError result; 4198 auto SaveTranslationUnitImpl = [=, &result]() { 4199 result = clang_saveTranslationUnit_Impl(TU, FileName, options); 4200 }; 4201 4202 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred()) { 4203 SaveTranslationUnitImpl(); 4204 4205 if (getenv("LIBCLANG_RESOURCE_USAGE")) 4206 PrintLibclangResourceUsage(TU); 4207 4208 return result; 4209 } 4210 4211 // We have an AST that has invalid nodes due to compiler errors. 4212 // Use a crash recovery thread for protection. 4213 4214 llvm::CrashRecoveryContext CRC; 4215 4216 if (!RunSafely(CRC, SaveTranslationUnitImpl)) { 4217 fprintf(stderr, "libclang: crash detected during AST saving: {\n"); 4218 fprintf(stderr, " 'filename' : '%s'\n", FileName); 4219 fprintf(stderr, " 'options' : %d,\n", options); 4220 fprintf(stderr, "}\n"); 4221 4222 return CXSaveError_Unknown; 4223 4224 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) { 4225 PrintLibclangResourceUsage(TU); 4226 } 4227 4228 return result; 4229 } 4230 4231 void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) { 4232 if (CTUnit) { 4233 // If the translation unit has been marked as unsafe to free, just discard 4234 // it. 4235 ASTUnit *Unit = cxtu::getASTUnit(CTUnit); 4236 if (Unit && Unit->isUnsafeToFree()) 4237 return; 4238 4239 delete cxtu::getASTUnit(CTUnit); 4240 delete CTUnit->StringPool; 4241 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics); 4242 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool); 4243 delete CTUnit->CommentToXML; 4244 delete CTUnit; 4245 } 4246 } 4247 4248 unsigned clang_suspendTranslationUnit(CXTranslationUnit CTUnit) { 4249 if (CTUnit) { 4250 ASTUnit *Unit = cxtu::getASTUnit(CTUnit); 4251 4252 if (Unit && Unit->isUnsafeToFree()) 4253 return false; 4254 4255 Unit->ResetForParse(); 4256 return true; 4257 } 4258 4259 return false; 4260 } 4261 4262 unsigned clang_defaultReparseOptions(CXTranslationUnit TU) { 4263 return CXReparse_None; 4264 } 4265 4266 static CXErrorCode 4267 clang_reparseTranslationUnit_Impl(CXTranslationUnit TU, 4268 ArrayRef<CXUnsavedFile> unsaved_files, 4269 unsigned options) { 4270 // Check arguments. 4271 if (isNotUsableTU(TU)) { 4272 LOG_BAD_TU(TU); 4273 return CXError_InvalidArguments; 4274 } 4275 4276 // Reset the associated diagnostics. 4277 delete static_cast<CXDiagnosticSetImpl *>(TU->Diagnostics); 4278 TU->Diagnostics = nullptr; 4279 4280 CIndexer *CXXIdx = TU->CIdx; 4281 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing)) 4282 setThreadBackgroundPriority(); 4283 4284 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 4285 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 4286 4287 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles( 4288 new std::vector<ASTUnit::RemappedFile>()); 4289 4290 // Recover resources if we crash before exiting this function. 4291 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<ASTUnit::RemappedFile>> 4292 RemappedCleanup(RemappedFiles.get()); 4293 4294 for (auto &UF : unsaved_files) { 4295 std::unique_ptr<llvm::MemoryBuffer> MB = 4296 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename); 4297 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release())); 4298 } 4299 4300 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(), 4301 *RemappedFiles.get())) 4302 return CXError_Success; 4303 if (isASTReadError(CXXUnit)) 4304 return CXError_ASTReadError; 4305 return CXError_Failure; 4306 } 4307 4308 int clang_reparseTranslationUnit(CXTranslationUnit TU, 4309 unsigned num_unsaved_files, 4310 struct CXUnsavedFile *unsaved_files, 4311 unsigned options) { 4312 LOG_FUNC_SECTION { *Log << TU; } 4313 4314 if (num_unsaved_files && !unsaved_files) 4315 return CXError_InvalidArguments; 4316 4317 CXErrorCode result; 4318 auto ReparseTranslationUnitImpl = [=, &result]() { 4319 result = clang_reparseTranslationUnit_Impl( 4320 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options); 4321 }; 4322 4323 llvm::CrashRecoveryContext CRC; 4324 4325 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) { 4326 fprintf(stderr, "libclang: crash detected during reparsing\n"); 4327 cxtu::getASTUnit(TU)->setUnsafeToFree(true); 4328 return CXError_Crashed; 4329 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) 4330 PrintLibclangResourceUsage(TU); 4331 4332 return result; 4333 } 4334 4335 CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) { 4336 if (isNotUsableTU(CTUnit)) { 4337 LOG_BAD_TU(CTUnit); 4338 return cxstring::createEmpty(); 4339 } 4340 4341 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit); 4342 return cxstring::createDup(CXXUnit->getOriginalSourceFileName()); 4343 } 4344 4345 CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) { 4346 if (isNotUsableTU(TU)) { 4347 LOG_BAD_TU(TU); 4348 return clang_getNullCursor(); 4349 } 4350 4351 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 4352 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU); 4353 } 4354 4355 CXTargetInfo clang_getTranslationUnitTargetInfo(CXTranslationUnit CTUnit) { 4356 if (isNotUsableTU(CTUnit)) { 4357 LOG_BAD_TU(CTUnit); 4358 return nullptr; 4359 } 4360 4361 CXTargetInfoImpl *impl = new CXTargetInfoImpl(); 4362 impl->TranslationUnit = CTUnit; 4363 return impl; 4364 } 4365 4366 CXString clang_TargetInfo_getTriple(CXTargetInfo TargetInfo) { 4367 if (!TargetInfo) 4368 return cxstring::createEmpty(); 4369 4370 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit; 4371 assert(!isNotUsableTU(CTUnit) && 4372 "Unexpected unusable translation unit in TargetInfo"); 4373 4374 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit); 4375 std::string Triple = 4376 CXXUnit->getASTContext().getTargetInfo().getTriple().normalize(); 4377 return cxstring::createDup(Triple); 4378 } 4379 4380 int clang_TargetInfo_getPointerWidth(CXTargetInfo TargetInfo) { 4381 if (!TargetInfo) 4382 return -1; 4383 4384 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit; 4385 assert(!isNotUsableTU(CTUnit) && 4386 "Unexpected unusable translation unit in TargetInfo"); 4387 4388 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit); 4389 return CXXUnit->getASTContext().getTargetInfo().getMaxPointerWidth(); 4390 } 4391 4392 void clang_TargetInfo_dispose(CXTargetInfo TargetInfo) { 4393 if (!TargetInfo) 4394 return; 4395 4396 delete TargetInfo; 4397 } 4398 4399 //===----------------------------------------------------------------------===// 4400 // CXFile Operations. 4401 //===----------------------------------------------------------------------===// 4402 4403 CXString clang_getFileName(CXFile SFile) { 4404 if (!SFile) 4405 return cxstring::createNull(); 4406 4407 FileEntry *FEnt = static_cast<FileEntry *>(SFile); 4408 return cxstring::createRef(FEnt->getName()); 4409 } 4410 4411 time_t clang_getFileTime(CXFile SFile) { 4412 if (!SFile) 4413 return 0; 4414 4415 FileEntry *FEnt = static_cast<FileEntry *>(SFile); 4416 return FEnt->getModificationTime(); 4417 } 4418 4419 CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) { 4420 if (isNotUsableTU(TU)) { 4421 LOG_BAD_TU(TU); 4422 return nullptr; 4423 } 4424 4425 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 4426 4427 FileManager &FMgr = CXXUnit->getFileManager(); 4428 auto File = FMgr.getFile(file_name); 4429 if (!File) 4430 return nullptr; 4431 return const_cast<FileEntry *>(*File); 4432 } 4433 4434 const char *clang_getFileContents(CXTranslationUnit TU, CXFile file, 4435 size_t *size) { 4436 if (isNotUsableTU(TU)) { 4437 LOG_BAD_TU(TU); 4438 return nullptr; 4439 } 4440 4441 const SourceManager &SM = cxtu::getASTUnit(TU)->getSourceManager(); 4442 FileID fid = SM.translateFile(static_cast<FileEntry *>(file)); 4443 llvm::Optional<llvm::MemoryBufferRef> buf = SM.getBufferOrNone(fid); 4444 if (!buf) { 4445 if (size) 4446 *size = 0; 4447 return nullptr; 4448 } 4449 if (size) 4450 *size = buf->getBufferSize(); 4451 return buf->getBufferStart(); 4452 } 4453 4454 unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU, CXFile file) { 4455 if (isNotUsableTU(TU)) { 4456 LOG_BAD_TU(TU); 4457 return 0; 4458 } 4459 4460 if (!file) 4461 return 0; 4462 4463 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 4464 FileEntry *FEnt = static_cast<FileEntry *>(file); 4465 return CXXUnit->getPreprocessor() 4466 .getHeaderSearchInfo() 4467 .isFileMultipleIncludeGuarded(FEnt); 4468 } 4469 4470 int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) { 4471 if (!file || !outID) 4472 return 1; 4473 4474 FileEntry *FEnt = static_cast<FileEntry *>(file); 4475 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID(); 4476 outID->data[0] = ID.getDevice(); 4477 outID->data[1] = ID.getFile(); 4478 outID->data[2] = FEnt->getModificationTime(); 4479 return 0; 4480 } 4481 4482 int clang_File_isEqual(CXFile file1, CXFile file2) { 4483 if (file1 == file2) 4484 return true; 4485 4486 if (!file1 || !file2) 4487 return false; 4488 4489 FileEntry *FEnt1 = static_cast<FileEntry *>(file1); 4490 FileEntry *FEnt2 = static_cast<FileEntry *>(file2); 4491 return FEnt1->getUniqueID() == FEnt2->getUniqueID(); 4492 } 4493 4494 CXString clang_File_tryGetRealPathName(CXFile SFile) { 4495 if (!SFile) 4496 return cxstring::createNull(); 4497 4498 FileEntry *FEnt = static_cast<FileEntry *>(SFile); 4499 return cxstring::createRef(FEnt->tryGetRealPathName()); 4500 } 4501 4502 //===----------------------------------------------------------------------===// 4503 // CXCursor Operations. 4504 //===----------------------------------------------------------------------===// 4505 4506 static const Decl *getDeclFromExpr(const Stmt *E) { 4507 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) 4508 return getDeclFromExpr(CE->getSubExpr()); 4509 4510 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E)) 4511 return RefExpr->getDecl(); 4512 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 4513 return ME->getMemberDecl(); 4514 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E)) 4515 return RE->getDecl(); 4516 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) { 4517 if (PRE->isExplicitProperty()) 4518 return PRE->getExplicitProperty(); 4519 // It could be messaging both getter and setter as in: 4520 // ++myobj.myprop; 4521 // in which case prefer to associate the setter since it is less obvious 4522 // from inspecting the source that the setter is going to get called. 4523 if (PRE->isMessagingSetter()) 4524 return PRE->getImplicitPropertySetter(); 4525 return PRE->getImplicitPropertyGetter(); 4526 } 4527 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 4528 return getDeclFromExpr(POE->getSyntacticForm()); 4529 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) 4530 if (Expr *Src = OVE->getSourceExpr()) 4531 return getDeclFromExpr(Src); 4532 4533 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) 4534 return getDeclFromExpr(CE->getCallee()); 4535 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E)) 4536 if (!CE->isElidable()) 4537 return CE->getConstructor(); 4538 if (const CXXInheritedCtorInitExpr *CE = 4539 dyn_cast<CXXInheritedCtorInitExpr>(E)) 4540 return CE->getConstructor(); 4541 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E)) 4542 return OME->getMethodDecl(); 4543 4544 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E)) 4545 return PE->getProtocol(); 4546 if (const SubstNonTypeTemplateParmPackExpr *NTTP = 4547 dyn_cast<SubstNonTypeTemplateParmPackExpr>(E)) 4548 return NTTP->getParameterPack(); 4549 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E)) 4550 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) || 4551 isa<ParmVarDecl>(SizeOfPack->getPack())) 4552 return SizeOfPack->getPack(); 4553 4554 return nullptr; 4555 } 4556 4557 static SourceLocation getLocationFromExpr(const Expr *E) { 4558 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) 4559 return getLocationFromExpr(CE->getSubExpr()); 4560 4561 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) 4562 return /*FIXME:*/ Msg->getLeftLoc(); 4563 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 4564 return DRE->getLocation(); 4565 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E)) 4566 return Member->getMemberLoc(); 4567 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) 4568 return Ivar->getLocation(); 4569 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E)) 4570 return SizeOfPack->getPackLoc(); 4571 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E)) 4572 return PropRef->getLocation(); 4573 4574 return E->getBeginLoc(); 4575 } 4576 4577 extern "C" { 4578 4579 unsigned clang_visitChildren(CXCursor parent, CXCursorVisitor visitor, 4580 CXClientData client_data) { 4581 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data, 4582 /*VisitPreprocessorLast=*/false); 4583 return CursorVis.VisitChildren(parent); 4584 } 4585 4586 #ifndef __has_feature 4587 #define __has_feature(x) 0 4588 #endif 4589 #if __has_feature(blocks) 4590 typedef enum CXChildVisitResult (^CXCursorVisitorBlock)(CXCursor cursor, 4591 CXCursor parent); 4592 4593 static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent, 4594 CXClientData client_data) { 4595 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data; 4596 return block(cursor, parent); 4597 } 4598 #else 4599 // If we are compiled with a compiler that doesn't have native blocks support, 4600 // define and call the block manually, so the 4601 typedef struct _CXChildVisitResult { 4602 void *isa; 4603 int flags; 4604 int reserved; 4605 enum CXChildVisitResult (*invoke)(struct _CXChildVisitResult *, CXCursor, 4606 CXCursor); 4607 } * CXCursorVisitorBlock; 4608 4609 static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent, 4610 CXClientData client_data) { 4611 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data; 4612 return block->invoke(block, cursor, parent); 4613 } 4614 #endif 4615 4616 unsigned clang_visitChildrenWithBlock(CXCursor parent, 4617 CXCursorVisitorBlock block) { 4618 return clang_visitChildren(parent, visitWithBlock, block); 4619 } 4620 4621 static CXString getDeclSpelling(const Decl *D) { 4622 if (!D) 4623 return cxstring::createEmpty(); 4624 4625 const NamedDecl *ND = dyn_cast<NamedDecl>(D); 4626 if (!ND) { 4627 if (const ObjCPropertyImplDecl *PropImpl = 4628 dyn_cast<ObjCPropertyImplDecl>(D)) 4629 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl()) 4630 return cxstring::createDup(Property->getIdentifier()->getName()); 4631 4632 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D)) 4633 if (Module *Mod = ImportD->getImportedModule()) 4634 return cxstring::createDup(Mod->getFullModuleName()); 4635 4636 return cxstring::createEmpty(); 4637 } 4638 4639 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND)) 4640 return cxstring::createDup(OMD->getSelector().getAsString()); 4641 4642 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND)) 4643 // No, this isn't the same as the code below. getIdentifier() is non-virtual 4644 // and returns different names. NamedDecl returns the class name and 4645 // ObjCCategoryImplDecl returns the category name. 4646 return cxstring::createRef(CIMP->getIdentifier()->getNameStart()); 4647 4648 if (isa<UsingDirectiveDecl>(D)) 4649 return cxstring::createEmpty(); 4650 4651 SmallString<1024> S; 4652 llvm::raw_svector_ostream os(S); 4653 ND->printName(os); 4654 4655 return cxstring::createDup(os.str()); 4656 } 4657 4658 CXString clang_getCursorSpelling(CXCursor C) { 4659 if (clang_isTranslationUnit(C.kind)) 4660 return clang_getTranslationUnitSpelling(getCursorTU(C)); 4661 4662 if (clang_isReference(C.kind)) { 4663 switch (C.kind) { 4664 case CXCursor_ObjCSuperClassRef: { 4665 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first; 4666 return cxstring::createRef(Super->getIdentifier()->getNameStart()); 4667 } 4668 case CXCursor_ObjCClassRef: { 4669 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first; 4670 return cxstring::createRef(Class->getIdentifier()->getNameStart()); 4671 } 4672 case CXCursor_ObjCProtocolRef: { 4673 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first; 4674 assert(OID && "getCursorSpelling(): Missing protocol decl"); 4675 return cxstring::createRef(OID->getIdentifier()->getNameStart()); 4676 } 4677 case CXCursor_CXXBaseSpecifier: { 4678 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C); 4679 return cxstring::createDup(B->getType().getAsString()); 4680 } 4681 case CXCursor_TypeRef: { 4682 const TypeDecl *Type = getCursorTypeRef(C).first; 4683 assert(Type && "Missing type decl"); 4684 4685 return cxstring::createDup( 4686 getCursorContext(C).getTypeDeclType(Type).getAsString()); 4687 } 4688 case CXCursor_TemplateRef: { 4689 const TemplateDecl *Template = getCursorTemplateRef(C).first; 4690 assert(Template && "Missing template decl"); 4691 4692 return cxstring::createDup(Template->getNameAsString()); 4693 } 4694 4695 case CXCursor_NamespaceRef: { 4696 const NamedDecl *NS = getCursorNamespaceRef(C).first; 4697 assert(NS && "Missing namespace decl"); 4698 4699 return cxstring::createDup(NS->getNameAsString()); 4700 } 4701 4702 case CXCursor_MemberRef: { 4703 const FieldDecl *Field = getCursorMemberRef(C).first; 4704 assert(Field && "Missing member decl"); 4705 4706 return cxstring::createDup(Field->getNameAsString()); 4707 } 4708 4709 case CXCursor_LabelRef: { 4710 const LabelStmt *Label = getCursorLabelRef(C).first; 4711 assert(Label && "Missing label"); 4712 4713 return cxstring::createRef(Label->getName()); 4714 } 4715 4716 case CXCursor_OverloadedDeclRef: { 4717 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first; 4718 if (const Decl *D = Storage.dyn_cast<const Decl *>()) { 4719 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) 4720 return cxstring::createDup(ND->getNameAsString()); 4721 return cxstring::createEmpty(); 4722 } 4723 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>()) 4724 return cxstring::createDup(E->getName().getAsString()); 4725 OverloadedTemplateStorage *Ovl = 4726 Storage.get<OverloadedTemplateStorage *>(); 4727 if (Ovl->size() == 0) 4728 return cxstring::createEmpty(); 4729 return cxstring::createDup((*Ovl->begin())->getNameAsString()); 4730 } 4731 4732 case CXCursor_VariableRef: { 4733 const VarDecl *Var = getCursorVariableRef(C).first; 4734 assert(Var && "Missing variable decl"); 4735 4736 return cxstring::createDup(Var->getNameAsString()); 4737 } 4738 4739 default: 4740 return cxstring::createRef("<not implemented>"); 4741 } 4742 } 4743 4744 if (clang_isExpression(C.kind)) { 4745 const Expr *E = getCursorExpr(C); 4746 4747 if (C.kind == CXCursor_ObjCStringLiteral || 4748 C.kind == CXCursor_StringLiteral) { 4749 const StringLiteral *SLit; 4750 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) { 4751 SLit = OSL->getString(); 4752 } else { 4753 SLit = cast<StringLiteral>(E); 4754 } 4755 SmallString<256> Buf; 4756 llvm::raw_svector_ostream OS(Buf); 4757 SLit->outputString(OS); 4758 return cxstring::createDup(OS.str()); 4759 } 4760 4761 const Decl *D = getDeclFromExpr(getCursorExpr(C)); 4762 if (D) 4763 return getDeclSpelling(D); 4764 return cxstring::createEmpty(); 4765 } 4766 4767 if (clang_isStatement(C.kind)) { 4768 const Stmt *S = getCursorStmt(C); 4769 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) 4770 return cxstring::createRef(Label->getName()); 4771 4772 return cxstring::createEmpty(); 4773 } 4774 4775 if (C.kind == CXCursor_MacroExpansion) 4776 return cxstring::createRef( 4777 getCursorMacroExpansion(C).getName()->getNameStart()); 4778 4779 if (C.kind == CXCursor_MacroDefinition) 4780 return cxstring::createRef( 4781 getCursorMacroDefinition(C)->getName()->getNameStart()); 4782 4783 if (C.kind == CXCursor_InclusionDirective) 4784 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName()); 4785 4786 if (clang_isDeclaration(C.kind)) 4787 return getDeclSpelling(getCursorDecl(C)); 4788 4789 if (C.kind == CXCursor_AnnotateAttr) { 4790 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C)); 4791 return cxstring::createDup(AA->getAnnotation()); 4792 } 4793 4794 if (C.kind == CXCursor_AsmLabelAttr) { 4795 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C)); 4796 return cxstring::createDup(AA->getLabel()); 4797 } 4798 4799 if (C.kind == CXCursor_PackedAttr) { 4800 return cxstring::createRef("packed"); 4801 } 4802 4803 if (C.kind == CXCursor_VisibilityAttr) { 4804 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C)); 4805 switch (AA->getVisibility()) { 4806 case VisibilityAttr::VisibilityType::Default: 4807 return cxstring::createRef("default"); 4808 case VisibilityAttr::VisibilityType::Hidden: 4809 return cxstring::createRef("hidden"); 4810 case VisibilityAttr::VisibilityType::Protected: 4811 return cxstring::createRef("protected"); 4812 } 4813 llvm_unreachable("unknown visibility type"); 4814 } 4815 4816 return cxstring::createEmpty(); 4817 } 4818 4819 CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C, unsigned pieceIndex, 4820 unsigned options) { 4821 if (clang_Cursor_isNull(C)) 4822 return clang_getNullRange(); 4823 4824 ASTContext &Ctx = getCursorContext(C); 4825 4826 if (clang_isStatement(C.kind)) { 4827 const Stmt *S = getCursorStmt(C); 4828 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) { 4829 if (pieceIndex > 0) 4830 return clang_getNullRange(); 4831 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc()); 4832 } 4833 4834 return clang_getNullRange(); 4835 } 4836 4837 if (C.kind == CXCursor_ObjCMessageExpr) { 4838 if (const ObjCMessageExpr *ME = 4839 dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) { 4840 if (pieceIndex >= ME->getNumSelectorLocs()) 4841 return clang_getNullRange(); 4842 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex)); 4843 } 4844 } 4845 4846 if (C.kind == CXCursor_ObjCInstanceMethodDecl || 4847 C.kind == CXCursor_ObjCClassMethodDecl) { 4848 if (const ObjCMethodDecl *MD = 4849 dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) { 4850 if (pieceIndex >= MD->getNumSelectorLocs()) 4851 return clang_getNullRange(); 4852 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex)); 4853 } 4854 } 4855 4856 if (C.kind == CXCursor_ObjCCategoryDecl || 4857 C.kind == CXCursor_ObjCCategoryImplDecl) { 4858 if (pieceIndex > 0) 4859 return clang_getNullRange(); 4860 if (const ObjCCategoryDecl *CD = 4861 dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C))) 4862 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc()); 4863 if (const ObjCCategoryImplDecl *CID = 4864 dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C))) 4865 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc()); 4866 } 4867 4868 if (C.kind == CXCursor_ModuleImportDecl) { 4869 if (pieceIndex > 0) 4870 return clang_getNullRange(); 4871 if (const ImportDecl *ImportD = 4872 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) { 4873 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs(); 4874 if (!Locs.empty()) 4875 return cxloc::translateSourceRange( 4876 Ctx, SourceRange(Locs.front(), Locs.back())); 4877 } 4878 return clang_getNullRange(); 4879 } 4880 4881 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor || 4882 C.kind == CXCursor_ConversionFunction || 4883 C.kind == CXCursor_FunctionDecl) { 4884 if (pieceIndex > 0) 4885 return clang_getNullRange(); 4886 if (const FunctionDecl *FD = 4887 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) { 4888 DeclarationNameInfo FunctionName = FD->getNameInfo(); 4889 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange()); 4890 } 4891 return clang_getNullRange(); 4892 } 4893 4894 // FIXME: A CXCursor_InclusionDirective should give the location of the 4895 // filename, but we don't keep track of this. 4896 4897 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation 4898 // but we don't keep track of this. 4899 4900 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label 4901 // but we don't keep track of this. 4902 4903 // Default handling, give the location of the cursor. 4904 4905 if (pieceIndex > 0) 4906 return clang_getNullRange(); 4907 4908 CXSourceLocation CXLoc = clang_getCursorLocation(C); 4909 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc); 4910 return cxloc::translateSourceRange(Ctx, Loc); 4911 } 4912 4913 CXString clang_Cursor_getMangling(CXCursor C) { 4914 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind)) 4915 return cxstring::createEmpty(); 4916 4917 // Mangling only works for functions and variables. 4918 const Decl *D = getCursorDecl(C); 4919 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D))) 4920 return cxstring::createEmpty(); 4921 4922 ASTContext &Ctx = D->getASTContext(); 4923 ASTNameGenerator ASTNameGen(Ctx); 4924 return cxstring::createDup(ASTNameGen.getName(D)); 4925 } 4926 4927 CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) { 4928 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind)) 4929 return nullptr; 4930 4931 const Decl *D = getCursorDecl(C); 4932 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D))) 4933 return nullptr; 4934 4935 ASTContext &Ctx = D->getASTContext(); 4936 ASTNameGenerator ASTNameGen(Ctx); 4937 std::vector<std::string> Manglings = ASTNameGen.getAllManglings(D); 4938 return cxstring::createSet(Manglings); 4939 } 4940 4941 CXStringSet *clang_Cursor_getObjCManglings(CXCursor C) { 4942 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind)) 4943 return nullptr; 4944 4945 const Decl *D = getCursorDecl(C); 4946 if (!(isa<ObjCInterfaceDecl>(D) || isa<ObjCImplementationDecl>(D))) 4947 return nullptr; 4948 4949 ASTContext &Ctx = D->getASTContext(); 4950 ASTNameGenerator ASTNameGen(Ctx); 4951 std::vector<std::string> Manglings = ASTNameGen.getAllManglings(D); 4952 return cxstring::createSet(Manglings); 4953 } 4954 4955 CXPrintingPolicy clang_getCursorPrintingPolicy(CXCursor C) { 4956 if (clang_Cursor_isNull(C)) 4957 return nullptr; 4958 return new PrintingPolicy(getCursorContext(C).getPrintingPolicy()); 4959 } 4960 4961 void clang_PrintingPolicy_dispose(CXPrintingPolicy Policy) { 4962 if (Policy) 4963 delete static_cast<PrintingPolicy *>(Policy); 4964 } 4965 4966 unsigned 4967 clang_PrintingPolicy_getProperty(CXPrintingPolicy Policy, 4968 enum CXPrintingPolicyProperty Property) { 4969 if (!Policy) 4970 return 0; 4971 4972 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy); 4973 switch (Property) { 4974 case CXPrintingPolicy_Indentation: 4975 return P->Indentation; 4976 case CXPrintingPolicy_SuppressSpecifiers: 4977 return P->SuppressSpecifiers; 4978 case CXPrintingPolicy_SuppressTagKeyword: 4979 return P->SuppressTagKeyword; 4980 case CXPrintingPolicy_IncludeTagDefinition: 4981 return P->IncludeTagDefinition; 4982 case CXPrintingPolicy_SuppressScope: 4983 return P->SuppressScope; 4984 case CXPrintingPolicy_SuppressUnwrittenScope: 4985 return P->SuppressUnwrittenScope; 4986 case CXPrintingPolicy_SuppressInitializers: 4987 return P->SuppressInitializers; 4988 case CXPrintingPolicy_ConstantArraySizeAsWritten: 4989 return P->ConstantArraySizeAsWritten; 4990 case CXPrintingPolicy_AnonymousTagLocations: 4991 return P->AnonymousTagLocations; 4992 case CXPrintingPolicy_SuppressStrongLifetime: 4993 return P->SuppressStrongLifetime; 4994 case CXPrintingPolicy_SuppressLifetimeQualifiers: 4995 return P->SuppressLifetimeQualifiers; 4996 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors: 4997 return P->SuppressTemplateArgsInCXXConstructors; 4998 case CXPrintingPolicy_Bool: 4999 return P->Bool; 5000 case CXPrintingPolicy_Restrict: 5001 return P->Restrict; 5002 case CXPrintingPolicy_Alignof: 5003 return P->Alignof; 5004 case CXPrintingPolicy_UnderscoreAlignof: 5005 return P->UnderscoreAlignof; 5006 case CXPrintingPolicy_UseVoidForZeroParams: 5007 return P->UseVoidForZeroParams; 5008 case CXPrintingPolicy_TerseOutput: 5009 return P->TerseOutput; 5010 case CXPrintingPolicy_PolishForDeclaration: 5011 return P->PolishForDeclaration; 5012 case CXPrintingPolicy_Half: 5013 return P->Half; 5014 case CXPrintingPolicy_MSWChar: 5015 return P->MSWChar; 5016 case CXPrintingPolicy_IncludeNewlines: 5017 return P->IncludeNewlines; 5018 case CXPrintingPolicy_MSVCFormatting: 5019 return P->MSVCFormatting; 5020 case CXPrintingPolicy_ConstantsAsWritten: 5021 return P->ConstantsAsWritten; 5022 case CXPrintingPolicy_SuppressImplicitBase: 5023 return P->SuppressImplicitBase; 5024 case CXPrintingPolicy_FullyQualifiedName: 5025 return P->FullyQualifiedName; 5026 } 5027 5028 assert(false && "Invalid CXPrintingPolicyProperty"); 5029 return 0; 5030 } 5031 5032 void clang_PrintingPolicy_setProperty(CXPrintingPolicy Policy, 5033 enum CXPrintingPolicyProperty Property, 5034 unsigned Value) { 5035 if (!Policy) 5036 return; 5037 5038 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy); 5039 switch (Property) { 5040 case CXPrintingPolicy_Indentation: 5041 P->Indentation = Value; 5042 return; 5043 case CXPrintingPolicy_SuppressSpecifiers: 5044 P->SuppressSpecifiers = Value; 5045 return; 5046 case CXPrintingPolicy_SuppressTagKeyword: 5047 P->SuppressTagKeyword = Value; 5048 return; 5049 case CXPrintingPolicy_IncludeTagDefinition: 5050 P->IncludeTagDefinition = Value; 5051 return; 5052 case CXPrintingPolicy_SuppressScope: 5053 P->SuppressScope = Value; 5054 return; 5055 case CXPrintingPolicy_SuppressUnwrittenScope: 5056 P->SuppressUnwrittenScope = Value; 5057 return; 5058 case CXPrintingPolicy_SuppressInitializers: 5059 P->SuppressInitializers = Value; 5060 return; 5061 case CXPrintingPolicy_ConstantArraySizeAsWritten: 5062 P->ConstantArraySizeAsWritten = Value; 5063 return; 5064 case CXPrintingPolicy_AnonymousTagLocations: 5065 P->AnonymousTagLocations = Value; 5066 return; 5067 case CXPrintingPolicy_SuppressStrongLifetime: 5068 P->SuppressStrongLifetime = Value; 5069 return; 5070 case CXPrintingPolicy_SuppressLifetimeQualifiers: 5071 P->SuppressLifetimeQualifiers = Value; 5072 return; 5073 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors: 5074 P->SuppressTemplateArgsInCXXConstructors = Value; 5075 return; 5076 case CXPrintingPolicy_Bool: 5077 P->Bool = Value; 5078 return; 5079 case CXPrintingPolicy_Restrict: 5080 P->Restrict = Value; 5081 return; 5082 case CXPrintingPolicy_Alignof: 5083 P->Alignof = Value; 5084 return; 5085 case CXPrintingPolicy_UnderscoreAlignof: 5086 P->UnderscoreAlignof = Value; 5087 return; 5088 case CXPrintingPolicy_UseVoidForZeroParams: 5089 P->UseVoidForZeroParams = Value; 5090 return; 5091 case CXPrintingPolicy_TerseOutput: 5092 P->TerseOutput = Value; 5093 return; 5094 case CXPrintingPolicy_PolishForDeclaration: 5095 P->PolishForDeclaration = Value; 5096 return; 5097 case CXPrintingPolicy_Half: 5098 P->Half = Value; 5099 return; 5100 case CXPrintingPolicy_MSWChar: 5101 P->MSWChar = Value; 5102 return; 5103 case CXPrintingPolicy_IncludeNewlines: 5104 P->IncludeNewlines = Value; 5105 return; 5106 case CXPrintingPolicy_MSVCFormatting: 5107 P->MSVCFormatting = Value; 5108 return; 5109 case CXPrintingPolicy_ConstantsAsWritten: 5110 P->ConstantsAsWritten = Value; 5111 return; 5112 case CXPrintingPolicy_SuppressImplicitBase: 5113 P->SuppressImplicitBase = Value; 5114 return; 5115 case CXPrintingPolicy_FullyQualifiedName: 5116 P->FullyQualifiedName = Value; 5117 return; 5118 } 5119 5120 assert(false && "Invalid CXPrintingPolicyProperty"); 5121 } 5122 5123 CXString clang_getCursorPrettyPrinted(CXCursor C, CXPrintingPolicy cxPolicy) { 5124 if (clang_Cursor_isNull(C)) 5125 return cxstring::createEmpty(); 5126 5127 if (clang_isDeclaration(C.kind)) { 5128 const Decl *D = getCursorDecl(C); 5129 if (!D) 5130 return cxstring::createEmpty(); 5131 5132 SmallString<128> Str; 5133 llvm::raw_svector_ostream OS(Str); 5134 PrintingPolicy *UserPolicy = static_cast<PrintingPolicy *>(cxPolicy); 5135 D->print(OS, UserPolicy ? *UserPolicy 5136 : getCursorContext(C).getPrintingPolicy()); 5137 5138 return cxstring::createDup(OS.str()); 5139 } 5140 5141 return cxstring::createEmpty(); 5142 } 5143 5144 CXString clang_getCursorDisplayName(CXCursor C) { 5145 if (!clang_isDeclaration(C.kind)) 5146 return clang_getCursorSpelling(C); 5147 5148 const Decl *D = getCursorDecl(C); 5149 if (!D) 5150 return cxstring::createEmpty(); 5151 5152 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy(); 5153 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 5154 D = FunTmpl->getTemplatedDecl(); 5155 5156 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 5157 SmallString<64> Str; 5158 llvm::raw_svector_ostream OS(Str); 5159 OS << *Function; 5160 if (Function->getPrimaryTemplate()) 5161 OS << "<>"; 5162 OS << "("; 5163 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) { 5164 if (I) 5165 OS << ", "; 5166 OS << Function->getParamDecl(I)->getType().getAsString(Policy); 5167 } 5168 5169 if (Function->isVariadic()) { 5170 if (Function->getNumParams()) 5171 OS << ", "; 5172 OS << "..."; 5173 } 5174 OS << ")"; 5175 return cxstring::createDup(OS.str()); 5176 } 5177 5178 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) { 5179 SmallString<64> Str; 5180 llvm::raw_svector_ostream OS(Str); 5181 OS << *ClassTemplate; 5182 OS << "<"; 5183 TemplateParameterList *Params = ClassTemplate->getTemplateParameters(); 5184 for (unsigned I = 0, N = Params->size(); I != N; ++I) { 5185 if (I) 5186 OS << ", "; 5187 5188 NamedDecl *Param = Params->getParam(I); 5189 if (Param->getIdentifier()) { 5190 OS << Param->getIdentifier()->getName(); 5191 continue; 5192 } 5193 5194 // There is no parameter name, which makes this tricky. Try to come up 5195 // with something useful that isn't too long. 5196 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) 5197 if (const auto *TC = TTP->getTypeConstraint()) { 5198 TC->getConceptNameInfo().printName(OS, Policy); 5199 if (TC->hasExplicitTemplateArgs()) 5200 OS << "<...>"; 5201 } else 5202 OS << (TTP->wasDeclaredWithTypename() ? "typename" : "class"); 5203 else if (NonTypeTemplateParmDecl *NTTP = 5204 dyn_cast<NonTypeTemplateParmDecl>(Param)) 5205 OS << NTTP->getType().getAsString(Policy); 5206 else 5207 OS << "template<...> class"; 5208 } 5209 5210 OS << ">"; 5211 return cxstring::createDup(OS.str()); 5212 } 5213 5214 if (const ClassTemplateSpecializationDecl *ClassSpec = 5215 dyn_cast<ClassTemplateSpecializationDecl>(D)) { 5216 // If the type was explicitly written, use that. 5217 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten()) 5218 return cxstring::createDup(TSInfo->getType().getAsString(Policy)); 5219 5220 SmallString<128> Str; 5221 llvm::raw_svector_ostream OS(Str); 5222 OS << *ClassSpec; 5223 printTemplateArgumentList( 5224 OS, ClassSpec->getTemplateArgs().asArray(), Policy, 5225 ClassSpec->getSpecializedTemplate()->getTemplateParameters()); 5226 return cxstring::createDup(OS.str()); 5227 } 5228 5229 return clang_getCursorSpelling(C); 5230 } 5231 5232 CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) { 5233 switch (Kind) { 5234 case CXCursor_FunctionDecl: 5235 return cxstring::createRef("FunctionDecl"); 5236 case CXCursor_TypedefDecl: 5237 return cxstring::createRef("TypedefDecl"); 5238 case CXCursor_EnumDecl: 5239 return cxstring::createRef("EnumDecl"); 5240 case CXCursor_EnumConstantDecl: 5241 return cxstring::createRef("EnumConstantDecl"); 5242 case CXCursor_StructDecl: 5243 return cxstring::createRef("StructDecl"); 5244 case CXCursor_UnionDecl: 5245 return cxstring::createRef("UnionDecl"); 5246 case CXCursor_ClassDecl: 5247 return cxstring::createRef("ClassDecl"); 5248 case CXCursor_FieldDecl: 5249 return cxstring::createRef("FieldDecl"); 5250 case CXCursor_VarDecl: 5251 return cxstring::createRef("VarDecl"); 5252 case CXCursor_ParmDecl: 5253 return cxstring::createRef("ParmDecl"); 5254 case CXCursor_ObjCInterfaceDecl: 5255 return cxstring::createRef("ObjCInterfaceDecl"); 5256 case CXCursor_ObjCCategoryDecl: 5257 return cxstring::createRef("ObjCCategoryDecl"); 5258 case CXCursor_ObjCProtocolDecl: 5259 return cxstring::createRef("ObjCProtocolDecl"); 5260 case CXCursor_ObjCPropertyDecl: 5261 return cxstring::createRef("ObjCPropertyDecl"); 5262 case CXCursor_ObjCIvarDecl: 5263 return cxstring::createRef("ObjCIvarDecl"); 5264 case CXCursor_ObjCInstanceMethodDecl: 5265 return cxstring::createRef("ObjCInstanceMethodDecl"); 5266 case CXCursor_ObjCClassMethodDecl: 5267 return cxstring::createRef("ObjCClassMethodDecl"); 5268 case CXCursor_ObjCImplementationDecl: 5269 return cxstring::createRef("ObjCImplementationDecl"); 5270 case CXCursor_ObjCCategoryImplDecl: 5271 return cxstring::createRef("ObjCCategoryImplDecl"); 5272 case CXCursor_CXXMethod: 5273 return cxstring::createRef("CXXMethod"); 5274 case CXCursor_UnexposedDecl: 5275 return cxstring::createRef("UnexposedDecl"); 5276 case CXCursor_ObjCSuperClassRef: 5277 return cxstring::createRef("ObjCSuperClassRef"); 5278 case CXCursor_ObjCProtocolRef: 5279 return cxstring::createRef("ObjCProtocolRef"); 5280 case CXCursor_ObjCClassRef: 5281 return cxstring::createRef("ObjCClassRef"); 5282 case CXCursor_TypeRef: 5283 return cxstring::createRef("TypeRef"); 5284 case CXCursor_TemplateRef: 5285 return cxstring::createRef("TemplateRef"); 5286 case CXCursor_NamespaceRef: 5287 return cxstring::createRef("NamespaceRef"); 5288 case CXCursor_MemberRef: 5289 return cxstring::createRef("MemberRef"); 5290 case CXCursor_LabelRef: 5291 return cxstring::createRef("LabelRef"); 5292 case CXCursor_OverloadedDeclRef: 5293 return cxstring::createRef("OverloadedDeclRef"); 5294 case CXCursor_VariableRef: 5295 return cxstring::createRef("VariableRef"); 5296 case CXCursor_IntegerLiteral: 5297 return cxstring::createRef("IntegerLiteral"); 5298 case CXCursor_FixedPointLiteral: 5299 return cxstring::createRef("FixedPointLiteral"); 5300 case CXCursor_FloatingLiteral: 5301 return cxstring::createRef("FloatingLiteral"); 5302 case CXCursor_ImaginaryLiteral: 5303 return cxstring::createRef("ImaginaryLiteral"); 5304 case CXCursor_StringLiteral: 5305 return cxstring::createRef("StringLiteral"); 5306 case CXCursor_CharacterLiteral: 5307 return cxstring::createRef("CharacterLiteral"); 5308 case CXCursor_ParenExpr: 5309 return cxstring::createRef("ParenExpr"); 5310 case CXCursor_UnaryOperator: 5311 return cxstring::createRef("UnaryOperator"); 5312 case CXCursor_ArraySubscriptExpr: 5313 return cxstring::createRef("ArraySubscriptExpr"); 5314 case CXCursor_OMPArraySectionExpr: 5315 return cxstring::createRef("OMPArraySectionExpr"); 5316 case CXCursor_OMPArrayShapingExpr: 5317 return cxstring::createRef("OMPArrayShapingExpr"); 5318 case CXCursor_OMPIteratorExpr: 5319 return cxstring::createRef("OMPIteratorExpr"); 5320 case CXCursor_BinaryOperator: 5321 return cxstring::createRef("BinaryOperator"); 5322 case CXCursor_CompoundAssignOperator: 5323 return cxstring::createRef("CompoundAssignOperator"); 5324 case CXCursor_ConditionalOperator: 5325 return cxstring::createRef("ConditionalOperator"); 5326 case CXCursor_CStyleCastExpr: 5327 return cxstring::createRef("CStyleCastExpr"); 5328 case CXCursor_CompoundLiteralExpr: 5329 return cxstring::createRef("CompoundLiteralExpr"); 5330 case CXCursor_InitListExpr: 5331 return cxstring::createRef("InitListExpr"); 5332 case CXCursor_AddrLabelExpr: 5333 return cxstring::createRef("AddrLabelExpr"); 5334 case CXCursor_StmtExpr: 5335 return cxstring::createRef("StmtExpr"); 5336 case CXCursor_GenericSelectionExpr: 5337 return cxstring::createRef("GenericSelectionExpr"); 5338 case CXCursor_GNUNullExpr: 5339 return cxstring::createRef("GNUNullExpr"); 5340 case CXCursor_CXXStaticCastExpr: 5341 return cxstring::createRef("CXXStaticCastExpr"); 5342 case CXCursor_CXXDynamicCastExpr: 5343 return cxstring::createRef("CXXDynamicCastExpr"); 5344 case CXCursor_CXXReinterpretCastExpr: 5345 return cxstring::createRef("CXXReinterpretCastExpr"); 5346 case CXCursor_CXXConstCastExpr: 5347 return cxstring::createRef("CXXConstCastExpr"); 5348 case CXCursor_CXXFunctionalCastExpr: 5349 return cxstring::createRef("CXXFunctionalCastExpr"); 5350 case CXCursor_CXXAddrspaceCastExpr: 5351 return cxstring::createRef("CXXAddrspaceCastExpr"); 5352 case CXCursor_CXXTypeidExpr: 5353 return cxstring::createRef("CXXTypeidExpr"); 5354 case CXCursor_CXXBoolLiteralExpr: 5355 return cxstring::createRef("CXXBoolLiteralExpr"); 5356 case CXCursor_CXXNullPtrLiteralExpr: 5357 return cxstring::createRef("CXXNullPtrLiteralExpr"); 5358 case CXCursor_CXXThisExpr: 5359 return cxstring::createRef("CXXThisExpr"); 5360 case CXCursor_CXXThrowExpr: 5361 return cxstring::createRef("CXXThrowExpr"); 5362 case CXCursor_CXXNewExpr: 5363 return cxstring::createRef("CXXNewExpr"); 5364 case CXCursor_CXXDeleteExpr: 5365 return cxstring::createRef("CXXDeleteExpr"); 5366 case CXCursor_UnaryExpr: 5367 return cxstring::createRef("UnaryExpr"); 5368 case CXCursor_ObjCStringLiteral: 5369 return cxstring::createRef("ObjCStringLiteral"); 5370 case CXCursor_ObjCBoolLiteralExpr: 5371 return cxstring::createRef("ObjCBoolLiteralExpr"); 5372 case CXCursor_ObjCAvailabilityCheckExpr: 5373 return cxstring::createRef("ObjCAvailabilityCheckExpr"); 5374 case CXCursor_ObjCSelfExpr: 5375 return cxstring::createRef("ObjCSelfExpr"); 5376 case CXCursor_ObjCEncodeExpr: 5377 return cxstring::createRef("ObjCEncodeExpr"); 5378 case CXCursor_ObjCSelectorExpr: 5379 return cxstring::createRef("ObjCSelectorExpr"); 5380 case CXCursor_ObjCProtocolExpr: 5381 return cxstring::createRef("ObjCProtocolExpr"); 5382 case CXCursor_ObjCBridgedCastExpr: 5383 return cxstring::createRef("ObjCBridgedCastExpr"); 5384 case CXCursor_BlockExpr: 5385 return cxstring::createRef("BlockExpr"); 5386 case CXCursor_PackExpansionExpr: 5387 return cxstring::createRef("PackExpansionExpr"); 5388 case CXCursor_SizeOfPackExpr: 5389 return cxstring::createRef("SizeOfPackExpr"); 5390 case CXCursor_LambdaExpr: 5391 return cxstring::createRef("LambdaExpr"); 5392 case CXCursor_UnexposedExpr: 5393 return cxstring::createRef("UnexposedExpr"); 5394 case CXCursor_DeclRefExpr: 5395 return cxstring::createRef("DeclRefExpr"); 5396 case CXCursor_MemberRefExpr: 5397 return cxstring::createRef("MemberRefExpr"); 5398 case CXCursor_CallExpr: 5399 return cxstring::createRef("CallExpr"); 5400 case CXCursor_ObjCMessageExpr: 5401 return cxstring::createRef("ObjCMessageExpr"); 5402 case CXCursor_BuiltinBitCastExpr: 5403 return cxstring::createRef("BuiltinBitCastExpr"); 5404 case CXCursor_UnexposedStmt: 5405 return cxstring::createRef("UnexposedStmt"); 5406 case CXCursor_DeclStmt: 5407 return cxstring::createRef("DeclStmt"); 5408 case CXCursor_LabelStmt: 5409 return cxstring::createRef("LabelStmt"); 5410 case CXCursor_CompoundStmt: 5411 return cxstring::createRef("CompoundStmt"); 5412 case CXCursor_CaseStmt: 5413 return cxstring::createRef("CaseStmt"); 5414 case CXCursor_DefaultStmt: 5415 return cxstring::createRef("DefaultStmt"); 5416 case CXCursor_IfStmt: 5417 return cxstring::createRef("IfStmt"); 5418 case CXCursor_SwitchStmt: 5419 return cxstring::createRef("SwitchStmt"); 5420 case CXCursor_WhileStmt: 5421 return cxstring::createRef("WhileStmt"); 5422 case CXCursor_DoStmt: 5423 return cxstring::createRef("DoStmt"); 5424 case CXCursor_ForStmt: 5425 return cxstring::createRef("ForStmt"); 5426 case CXCursor_GotoStmt: 5427 return cxstring::createRef("GotoStmt"); 5428 case CXCursor_IndirectGotoStmt: 5429 return cxstring::createRef("IndirectGotoStmt"); 5430 case CXCursor_ContinueStmt: 5431 return cxstring::createRef("ContinueStmt"); 5432 case CXCursor_BreakStmt: 5433 return cxstring::createRef("BreakStmt"); 5434 case CXCursor_ReturnStmt: 5435 return cxstring::createRef("ReturnStmt"); 5436 case CXCursor_GCCAsmStmt: 5437 return cxstring::createRef("GCCAsmStmt"); 5438 case CXCursor_MSAsmStmt: 5439 return cxstring::createRef("MSAsmStmt"); 5440 case CXCursor_ObjCAtTryStmt: 5441 return cxstring::createRef("ObjCAtTryStmt"); 5442 case CXCursor_ObjCAtCatchStmt: 5443 return cxstring::createRef("ObjCAtCatchStmt"); 5444 case CXCursor_ObjCAtFinallyStmt: 5445 return cxstring::createRef("ObjCAtFinallyStmt"); 5446 case CXCursor_ObjCAtThrowStmt: 5447 return cxstring::createRef("ObjCAtThrowStmt"); 5448 case CXCursor_ObjCAtSynchronizedStmt: 5449 return cxstring::createRef("ObjCAtSynchronizedStmt"); 5450 case CXCursor_ObjCAutoreleasePoolStmt: 5451 return cxstring::createRef("ObjCAutoreleasePoolStmt"); 5452 case CXCursor_ObjCForCollectionStmt: 5453 return cxstring::createRef("ObjCForCollectionStmt"); 5454 case CXCursor_CXXCatchStmt: 5455 return cxstring::createRef("CXXCatchStmt"); 5456 case CXCursor_CXXTryStmt: 5457 return cxstring::createRef("CXXTryStmt"); 5458 case CXCursor_CXXForRangeStmt: 5459 return cxstring::createRef("CXXForRangeStmt"); 5460 case CXCursor_SEHTryStmt: 5461 return cxstring::createRef("SEHTryStmt"); 5462 case CXCursor_SEHExceptStmt: 5463 return cxstring::createRef("SEHExceptStmt"); 5464 case CXCursor_SEHFinallyStmt: 5465 return cxstring::createRef("SEHFinallyStmt"); 5466 case CXCursor_SEHLeaveStmt: 5467 return cxstring::createRef("SEHLeaveStmt"); 5468 case CXCursor_NullStmt: 5469 return cxstring::createRef("NullStmt"); 5470 case CXCursor_InvalidFile: 5471 return cxstring::createRef("InvalidFile"); 5472 case CXCursor_InvalidCode: 5473 return cxstring::createRef("InvalidCode"); 5474 case CXCursor_NoDeclFound: 5475 return cxstring::createRef("NoDeclFound"); 5476 case CXCursor_NotImplemented: 5477 return cxstring::createRef("NotImplemented"); 5478 case CXCursor_TranslationUnit: 5479 return cxstring::createRef("TranslationUnit"); 5480 case CXCursor_UnexposedAttr: 5481 return cxstring::createRef("UnexposedAttr"); 5482 case CXCursor_IBActionAttr: 5483 return cxstring::createRef("attribute(ibaction)"); 5484 case CXCursor_IBOutletAttr: 5485 return cxstring::createRef("attribute(iboutlet)"); 5486 case CXCursor_IBOutletCollectionAttr: 5487 return cxstring::createRef("attribute(iboutletcollection)"); 5488 case CXCursor_CXXFinalAttr: 5489 return cxstring::createRef("attribute(final)"); 5490 case CXCursor_CXXOverrideAttr: 5491 return cxstring::createRef("attribute(override)"); 5492 case CXCursor_AnnotateAttr: 5493 return cxstring::createRef("attribute(annotate)"); 5494 case CXCursor_AsmLabelAttr: 5495 return cxstring::createRef("asm label"); 5496 case CXCursor_PackedAttr: 5497 return cxstring::createRef("attribute(packed)"); 5498 case CXCursor_PureAttr: 5499 return cxstring::createRef("attribute(pure)"); 5500 case CXCursor_ConstAttr: 5501 return cxstring::createRef("attribute(const)"); 5502 case CXCursor_NoDuplicateAttr: 5503 return cxstring::createRef("attribute(noduplicate)"); 5504 case CXCursor_CUDAConstantAttr: 5505 return cxstring::createRef("attribute(constant)"); 5506 case CXCursor_CUDADeviceAttr: 5507 return cxstring::createRef("attribute(device)"); 5508 case CXCursor_CUDAGlobalAttr: 5509 return cxstring::createRef("attribute(global)"); 5510 case CXCursor_CUDAHostAttr: 5511 return cxstring::createRef("attribute(host)"); 5512 case CXCursor_CUDASharedAttr: 5513 return cxstring::createRef("attribute(shared)"); 5514 case CXCursor_VisibilityAttr: 5515 return cxstring::createRef("attribute(visibility)"); 5516 case CXCursor_DLLExport: 5517 return cxstring::createRef("attribute(dllexport)"); 5518 case CXCursor_DLLImport: 5519 return cxstring::createRef("attribute(dllimport)"); 5520 case CXCursor_NSReturnsRetained: 5521 return cxstring::createRef("attribute(ns_returns_retained)"); 5522 case CXCursor_NSReturnsNotRetained: 5523 return cxstring::createRef("attribute(ns_returns_not_retained)"); 5524 case CXCursor_NSReturnsAutoreleased: 5525 return cxstring::createRef("attribute(ns_returns_autoreleased)"); 5526 case CXCursor_NSConsumesSelf: 5527 return cxstring::createRef("attribute(ns_consumes_self)"); 5528 case CXCursor_NSConsumed: 5529 return cxstring::createRef("attribute(ns_consumed)"); 5530 case CXCursor_ObjCException: 5531 return cxstring::createRef("attribute(objc_exception)"); 5532 case CXCursor_ObjCNSObject: 5533 return cxstring::createRef("attribute(NSObject)"); 5534 case CXCursor_ObjCIndependentClass: 5535 return cxstring::createRef("attribute(objc_independent_class)"); 5536 case CXCursor_ObjCPreciseLifetime: 5537 return cxstring::createRef("attribute(objc_precise_lifetime)"); 5538 case CXCursor_ObjCReturnsInnerPointer: 5539 return cxstring::createRef("attribute(objc_returns_inner_pointer)"); 5540 case CXCursor_ObjCRequiresSuper: 5541 return cxstring::createRef("attribute(objc_requires_super)"); 5542 case CXCursor_ObjCRootClass: 5543 return cxstring::createRef("attribute(objc_root_class)"); 5544 case CXCursor_ObjCSubclassingRestricted: 5545 return cxstring::createRef("attribute(objc_subclassing_restricted)"); 5546 case CXCursor_ObjCExplicitProtocolImpl: 5547 return cxstring::createRef( 5548 "attribute(objc_protocol_requires_explicit_implementation)"); 5549 case CXCursor_ObjCDesignatedInitializer: 5550 return cxstring::createRef("attribute(objc_designated_initializer)"); 5551 case CXCursor_ObjCRuntimeVisible: 5552 return cxstring::createRef("attribute(objc_runtime_visible)"); 5553 case CXCursor_ObjCBoxable: 5554 return cxstring::createRef("attribute(objc_boxable)"); 5555 case CXCursor_FlagEnum: 5556 return cxstring::createRef("attribute(flag_enum)"); 5557 case CXCursor_PreprocessingDirective: 5558 return cxstring::createRef("preprocessing directive"); 5559 case CXCursor_MacroDefinition: 5560 return cxstring::createRef("macro definition"); 5561 case CXCursor_MacroExpansion: 5562 return cxstring::createRef("macro expansion"); 5563 case CXCursor_InclusionDirective: 5564 return cxstring::createRef("inclusion directive"); 5565 case CXCursor_Namespace: 5566 return cxstring::createRef("Namespace"); 5567 case CXCursor_LinkageSpec: 5568 return cxstring::createRef("LinkageSpec"); 5569 case CXCursor_CXXBaseSpecifier: 5570 return cxstring::createRef("C++ base class specifier"); 5571 case CXCursor_Constructor: 5572 return cxstring::createRef("CXXConstructor"); 5573 case CXCursor_Destructor: 5574 return cxstring::createRef("CXXDestructor"); 5575 case CXCursor_ConversionFunction: 5576 return cxstring::createRef("CXXConversion"); 5577 case CXCursor_TemplateTypeParameter: 5578 return cxstring::createRef("TemplateTypeParameter"); 5579 case CXCursor_NonTypeTemplateParameter: 5580 return cxstring::createRef("NonTypeTemplateParameter"); 5581 case CXCursor_TemplateTemplateParameter: 5582 return cxstring::createRef("TemplateTemplateParameter"); 5583 case CXCursor_FunctionTemplate: 5584 return cxstring::createRef("FunctionTemplate"); 5585 case CXCursor_ClassTemplate: 5586 return cxstring::createRef("ClassTemplate"); 5587 case CXCursor_ClassTemplatePartialSpecialization: 5588 return cxstring::createRef("ClassTemplatePartialSpecialization"); 5589 case CXCursor_NamespaceAlias: 5590 return cxstring::createRef("NamespaceAlias"); 5591 case CXCursor_UsingDirective: 5592 return cxstring::createRef("UsingDirective"); 5593 case CXCursor_UsingDeclaration: 5594 return cxstring::createRef("UsingDeclaration"); 5595 case CXCursor_TypeAliasDecl: 5596 return cxstring::createRef("TypeAliasDecl"); 5597 case CXCursor_ObjCSynthesizeDecl: 5598 return cxstring::createRef("ObjCSynthesizeDecl"); 5599 case CXCursor_ObjCDynamicDecl: 5600 return cxstring::createRef("ObjCDynamicDecl"); 5601 case CXCursor_CXXAccessSpecifier: 5602 return cxstring::createRef("CXXAccessSpecifier"); 5603 case CXCursor_ModuleImportDecl: 5604 return cxstring::createRef("ModuleImport"); 5605 case CXCursor_OMPCanonicalLoop: 5606 return cxstring::createRef("OMPCanonicalLoop"); 5607 case CXCursor_OMPMetaDirective: 5608 return cxstring::createRef("OMPMetaDirective"); 5609 case CXCursor_OMPParallelDirective: 5610 return cxstring::createRef("OMPParallelDirective"); 5611 case CXCursor_OMPSimdDirective: 5612 return cxstring::createRef("OMPSimdDirective"); 5613 case CXCursor_OMPTileDirective: 5614 return cxstring::createRef("OMPTileDirective"); 5615 case CXCursor_OMPUnrollDirective: 5616 return cxstring::createRef("OMPUnrollDirective"); 5617 case CXCursor_OMPForDirective: 5618 return cxstring::createRef("OMPForDirective"); 5619 case CXCursor_OMPForSimdDirective: 5620 return cxstring::createRef("OMPForSimdDirective"); 5621 case CXCursor_OMPSectionsDirective: 5622 return cxstring::createRef("OMPSectionsDirective"); 5623 case CXCursor_OMPSectionDirective: 5624 return cxstring::createRef("OMPSectionDirective"); 5625 case CXCursor_OMPSingleDirective: 5626 return cxstring::createRef("OMPSingleDirective"); 5627 case CXCursor_OMPMasterDirective: 5628 return cxstring::createRef("OMPMasterDirective"); 5629 case CXCursor_OMPCriticalDirective: 5630 return cxstring::createRef("OMPCriticalDirective"); 5631 case CXCursor_OMPParallelForDirective: 5632 return cxstring::createRef("OMPParallelForDirective"); 5633 case CXCursor_OMPParallelForSimdDirective: 5634 return cxstring::createRef("OMPParallelForSimdDirective"); 5635 case CXCursor_OMPParallelMasterDirective: 5636 return cxstring::createRef("OMPParallelMasterDirective"); 5637 case CXCursor_OMPParallelSectionsDirective: 5638 return cxstring::createRef("OMPParallelSectionsDirective"); 5639 case CXCursor_OMPTaskDirective: 5640 return cxstring::createRef("OMPTaskDirective"); 5641 case CXCursor_OMPTaskyieldDirective: 5642 return cxstring::createRef("OMPTaskyieldDirective"); 5643 case CXCursor_OMPBarrierDirective: 5644 return cxstring::createRef("OMPBarrierDirective"); 5645 case CXCursor_OMPTaskwaitDirective: 5646 return cxstring::createRef("OMPTaskwaitDirective"); 5647 case CXCursor_OMPTaskgroupDirective: 5648 return cxstring::createRef("OMPTaskgroupDirective"); 5649 case CXCursor_OMPFlushDirective: 5650 return cxstring::createRef("OMPFlushDirective"); 5651 case CXCursor_OMPDepobjDirective: 5652 return cxstring::createRef("OMPDepobjDirective"); 5653 case CXCursor_OMPScanDirective: 5654 return cxstring::createRef("OMPScanDirective"); 5655 case CXCursor_OMPOrderedDirective: 5656 return cxstring::createRef("OMPOrderedDirective"); 5657 case CXCursor_OMPAtomicDirective: 5658 return cxstring::createRef("OMPAtomicDirective"); 5659 case CXCursor_OMPTargetDirective: 5660 return cxstring::createRef("OMPTargetDirective"); 5661 case CXCursor_OMPTargetDataDirective: 5662 return cxstring::createRef("OMPTargetDataDirective"); 5663 case CXCursor_OMPTargetEnterDataDirective: 5664 return cxstring::createRef("OMPTargetEnterDataDirective"); 5665 case CXCursor_OMPTargetExitDataDirective: 5666 return cxstring::createRef("OMPTargetExitDataDirective"); 5667 case CXCursor_OMPTargetParallelDirective: 5668 return cxstring::createRef("OMPTargetParallelDirective"); 5669 case CXCursor_OMPTargetParallelForDirective: 5670 return cxstring::createRef("OMPTargetParallelForDirective"); 5671 case CXCursor_OMPTargetUpdateDirective: 5672 return cxstring::createRef("OMPTargetUpdateDirective"); 5673 case CXCursor_OMPTeamsDirective: 5674 return cxstring::createRef("OMPTeamsDirective"); 5675 case CXCursor_OMPCancellationPointDirective: 5676 return cxstring::createRef("OMPCancellationPointDirective"); 5677 case CXCursor_OMPCancelDirective: 5678 return cxstring::createRef("OMPCancelDirective"); 5679 case CXCursor_OMPTaskLoopDirective: 5680 return cxstring::createRef("OMPTaskLoopDirective"); 5681 case CXCursor_OMPTaskLoopSimdDirective: 5682 return cxstring::createRef("OMPTaskLoopSimdDirective"); 5683 case CXCursor_OMPMasterTaskLoopDirective: 5684 return cxstring::createRef("OMPMasterTaskLoopDirective"); 5685 case CXCursor_OMPMasterTaskLoopSimdDirective: 5686 return cxstring::createRef("OMPMasterTaskLoopSimdDirective"); 5687 case CXCursor_OMPParallelMasterTaskLoopDirective: 5688 return cxstring::createRef("OMPParallelMasterTaskLoopDirective"); 5689 case CXCursor_OMPParallelMasterTaskLoopSimdDirective: 5690 return cxstring::createRef("OMPParallelMasterTaskLoopSimdDirective"); 5691 case CXCursor_OMPDistributeDirective: 5692 return cxstring::createRef("OMPDistributeDirective"); 5693 case CXCursor_OMPDistributeParallelForDirective: 5694 return cxstring::createRef("OMPDistributeParallelForDirective"); 5695 case CXCursor_OMPDistributeParallelForSimdDirective: 5696 return cxstring::createRef("OMPDistributeParallelForSimdDirective"); 5697 case CXCursor_OMPDistributeSimdDirective: 5698 return cxstring::createRef("OMPDistributeSimdDirective"); 5699 case CXCursor_OMPTargetParallelForSimdDirective: 5700 return cxstring::createRef("OMPTargetParallelForSimdDirective"); 5701 case CXCursor_OMPTargetSimdDirective: 5702 return cxstring::createRef("OMPTargetSimdDirective"); 5703 case CXCursor_OMPTeamsDistributeDirective: 5704 return cxstring::createRef("OMPTeamsDistributeDirective"); 5705 case CXCursor_OMPTeamsDistributeSimdDirective: 5706 return cxstring::createRef("OMPTeamsDistributeSimdDirective"); 5707 case CXCursor_OMPTeamsDistributeParallelForSimdDirective: 5708 return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective"); 5709 case CXCursor_OMPTeamsDistributeParallelForDirective: 5710 return cxstring::createRef("OMPTeamsDistributeParallelForDirective"); 5711 case CXCursor_OMPTargetTeamsDirective: 5712 return cxstring::createRef("OMPTargetTeamsDirective"); 5713 case CXCursor_OMPTargetTeamsDistributeDirective: 5714 return cxstring::createRef("OMPTargetTeamsDistributeDirective"); 5715 case CXCursor_OMPTargetTeamsDistributeParallelForDirective: 5716 return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective"); 5717 case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective: 5718 return cxstring::createRef( 5719 "OMPTargetTeamsDistributeParallelForSimdDirective"); 5720 case CXCursor_OMPTargetTeamsDistributeSimdDirective: 5721 return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective"); 5722 case CXCursor_OMPInteropDirective: 5723 return cxstring::createRef("OMPInteropDirective"); 5724 case CXCursor_OMPDispatchDirective: 5725 return cxstring::createRef("OMPDispatchDirective"); 5726 case CXCursor_OMPMaskedDirective: 5727 return cxstring::createRef("OMPMaskedDirective"); 5728 case CXCursor_OMPGenericLoopDirective: 5729 return cxstring::createRef("OMPGenericLoopDirective"); 5730 case CXCursor_OMPTeamsGenericLoopDirective: 5731 return cxstring::createRef("OMPTeamsGenericLoopDirective"); 5732 case CXCursor_OMPTargetTeamsGenericLoopDirective: 5733 return cxstring::createRef("OMPTargetTeamsGenericLoopDirective"); 5734 case CXCursor_OMPParallelGenericLoopDirective: 5735 return cxstring::createRef("OMPParallelGenericLoopDirective"); 5736 case CXCursor_OMPTargetParallelGenericLoopDirective: 5737 return cxstring::createRef("OMPTargetParallelGenericLoopDirective"); 5738 case CXCursor_OverloadCandidate: 5739 return cxstring::createRef("OverloadCandidate"); 5740 case CXCursor_TypeAliasTemplateDecl: 5741 return cxstring::createRef("TypeAliasTemplateDecl"); 5742 case CXCursor_StaticAssert: 5743 return cxstring::createRef("StaticAssert"); 5744 case CXCursor_FriendDecl: 5745 return cxstring::createRef("FriendDecl"); 5746 case CXCursor_ConvergentAttr: 5747 return cxstring::createRef("attribute(convergent)"); 5748 case CXCursor_WarnUnusedAttr: 5749 return cxstring::createRef("attribute(warn_unused)"); 5750 case CXCursor_WarnUnusedResultAttr: 5751 return cxstring::createRef("attribute(warn_unused_result)"); 5752 case CXCursor_AlignedAttr: 5753 return cxstring::createRef("attribute(aligned)"); 5754 } 5755 5756 llvm_unreachable("Unhandled CXCursorKind"); 5757 } 5758 5759 struct GetCursorData { 5760 SourceLocation TokenBeginLoc; 5761 bool PointsAtMacroArgExpansion; 5762 bool VisitedObjCPropertyImplDecl; 5763 SourceLocation VisitedDeclaratorDeclStartLoc; 5764 CXCursor &BestCursor; 5765 5766 GetCursorData(SourceManager &SM, SourceLocation tokenBegin, 5767 CXCursor &outputCursor) 5768 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) { 5769 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin); 5770 VisitedObjCPropertyImplDecl = false; 5771 } 5772 }; 5773 5774 static enum CXChildVisitResult 5775 GetCursorVisitor(CXCursor cursor, CXCursor parent, CXClientData client_data) { 5776 GetCursorData *Data = static_cast<GetCursorData *>(client_data); 5777 CXCursor *BestCursor = &Data->BestCursor; 5778 5779 // If we point inside a macro argument we should provide info of what the 5780 // token is so use the actual cursor, don't replace it with a macro expansion 5781 // cursor. 5782 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion) 5783 return CXChildVisit_Recurse; 5784 5785 if (clang_isDeclaration(cursor.kind)) { 5786 // Avoid having the implicit methods override the property decls. 5787 if (const ObjCMethodDecl *MD = 5788 dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) { 5789 if (MD->isImplicit()) 5790 return CXChildVisit_Break; 5791 5792 } else if (const ObjCInterfaceDecl *ID = 5793 dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) { 5794 // Check that when we have multiple @class references in the same line, 5795 // that later ones do not override the previous ones. 5796 // If we have: 5797 // @class Foo, Bar; 5798 // source ranges for both start at '@', so 'Bar' will end up overriding 5799 // 'Foo' even though the cursor location was at 'Foo'. 5800 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl || 5801 BestCursor->kind == CXCursor_ObjCClassRef) 5802 if (const ObjCInterfaceDecl *PrevID = 5803 dyn_cast_or_null<ObjCInterfaceDecl>( 5804 getCursorDecl(*BestCursor))) { 5805 if (PrevID != ID && !PrevID->isThisDeclarationADefinition() && 5806 !ID->isThisDeclarationADefinition()) 5807 return CXChildVisit_Break; 5808 } 5809 5810 } else if (const DeclaratorDecl *DD = 5811 dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) { 5812 SourceLocation StartLoc = DD->getSourceRange().getBegin(); 5813 // Check that when we have multiple declarators in the same line, 5814 // that later ones do not override the previous ones. 5815 // If we have: 5816 // int Foo, Bar; 5817 // source ranges for both start at 'int', so 'Bar' will end up overriding 5818 // 'Foo' even though the cursor location was at 'Foo'. 5819 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc) 5820 return CXChildVisit_Break; 5821 Data->VisitedDeclaratorDeclStartLoc = StartLoc; 5822 5823 } else if (const ObjCPropertyImplDecl *PropImp = 5824 dyn_cast_or_null<ObjCPropertyImplDecl>( 5825 getCursorDecl(cursor))) { 5826 (void)PropImp; 5827 // Check that when we have multiple @synthesize in the same line, 5828 // that later ones do not override the previous ones. 5829 // If we have: 5830 // @synthesize Foo, Bar; 5831 // source ranges for both start at '@', so 'Bar' will end up overriding 5832 // 'Foo' even though the cursor location was at 'Foo'. 5833 if (Data->VisitedObjCPropertyImplDecl) 5834 return CXChildVisit_Break; 5835 Data->VisitedObjCPropertyImplDecl = true; 5836 } 5837 } 5838 5839 if (clang_isExpression(cursor.kind) && 5840 clang_isDeclaration(BestCursor->kind)) { 5841 if (const Decl *D = getCursorDecl(*BestCursor)) { 5842 // Avoid having the cursor of an expression replace the declaration cursor 5843 // when the expression source range overlaps the declaration range. 5844 // This can happen for C++ constructor expressions whose range generally 5845 // include the variable declaration, e.g.: 5846 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl 5847 // cursor. 5848 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() && 5849 D->getLocation() == Data->TokenBeginLoc) 5850 return CXChildVisit_Break; 5851 } 5852 } 5853 5854 // If our current best cursor is the construction of a temporary object, 5855 // don't replace that cursor with a type reference, because we want 5856 // clang_getCursor() to point at the constructor. 5857 if (clang_isExpression(BestCursor->kind) && 5858 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) && 5859 cursor.kind == CXCursor_TypeRef) { 5860 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it 5861 // as having the actual point on the type reference. 5862 *BestCursor = getTypeRefedCallExprCursor(*BestCursor); 5863 return CXChildVisit_Recurse; 5864 } 5865 5866 // If we already have an Objective-C superclass reference, don't 5867 // update it further. 5868 if (BestCursor->kind == CXCursor_ObjCSuperClassRef) 5869 return CXChildVisit_Break; 5870 5871 *BestCursor = cursor; 5872 return CXChildVisit_Recurse; 5873 } 5874 5875 CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) { 5876 if (isNotUsableTU(TU)) { 5877 LOG_BAD_TU(TU); 5878 return clang_getNullCursor(); 5879 } 5880 5881 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 5882 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 5883 5884 SourceLocation SLoc = cxloc::translateSourceLocation(Loc); 5885 CXCursor Result = cxcursor::getCursor(TU, SLoc); 5886 5887 LOG_FUNC_SECTION { 5888 CXFile SearchFile; 5889 unsigned SearchLine, SearchColumn; 5890 CXFile ResultFile; 5891 unsigned ResultLine, ResultColumn; 5892 CXString SearchFileName, ResultFileName, KindSpelling, USR; 5893 const char *IsDef = clang_isCursorDefinition(Result) ? " (Definition)" : ""; 5894 CXSourceLocation ResultLoc = clang_getCursorLocation(Result); 5895 5896 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 5897 nullptr); 5898 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine, &ResultColumn, 5899 nullptr); 5900 SearchFileName = clang_getFileName(SearchFile); 5901 ResultFileName = clang_getFileName(ResultFile); 5902 KindSpelling = clang_getCursorKindSpelling(Result.kind); 5903 USR = clang_getCursorUSR(Result); 5904 *Log << llvm::format("(%s:%d:%d) = %s", clang_getCString(SearchFileName), 5905 SearchLine, SearchColumn, 5906 clang_getCString(KindSpelling)) 5907 << llvm::format("(%s:%d:%d):%s%s", clang_getCString(ResultFileName), 5908 ResultLine, ResultColumn, clang_getCString(USR), 5909 IsDef); 5910 clang_disposeString(SearchFileName); 5911 clang_disposeString(ResultFileName); 5912 clang_disposeString(KindSpelling); 5913 clang_disposeString(USR); 5914 5915 CXCursor Definition = clang_getCursorDefinition(Result); 5916 if (!clang_equalCursors(Definition, clang_getNullCursor())) { 5917 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition); 5918 CXString DefinitionKindSpelling = 5919 clang_getCursorKindSpelling(Definition.kind); 5920 CXFile DefinitionFile; 5921 unsigned DefinitionLine, DefinitionColumn; 5922 clang_getFileLocation(DefinitionLoc, &DefinitionFile, &DefinitionLine, 5923 &DefinitionColumn, nullptr); 5924 CXString DefinitionFileName = clang_getFileName(DefinitionFile); 5925 *Log << llvm::format(" -> %s(%s:%d:%d)", 5926 clang_getCString(DefinitionKindSpelling), 5927 clang_getCString(DefinitionFileName), DefinitionLine, 5928 DefinitionColumn); 5929 clang_disposeString(DefinitionFileName); 5930 clang_disposeString(DefinitionKindSpelling); 5931 } 5932 } 5933 5934 return Result; 5935 } 5936 5937 CXCursor clang_getNullCursor(void) { 5938 return MakeCXCursorInvalid(CXCursor_InvalidFile); 5939 } 5940 5941 unsigned clang_equalCursors(CXCursor X, CXCursor Y) { 5942 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we 5943 // can't set consistently. For example, when visiting a DeclStmt we will set 5944 // it but we don't set it on the result of clang_getCursorDefinition for 5945 // a reference of the same declaration. 5946 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works 5947 // when visiting a DeclStmt currently, the AST should be enhanced to be able 5948 // to provide that kind of info. 5949 if (clang_isDeclaration(X.kind)) 5950 X.data[1] = nullptr; 5951 if (clang_isDeclaration(Y.kind)) 5952 Y.data[1] = nullptr; 5953 5954 return X == Y; 5955 } 5956 5957 unsigned clang_hashCursor(CXCursor C) { 5958 unsigned Index = 0; 5959 if (clang_isExpression(C.kind) || clang_isStatement(C.kind)) 5960 Index = 1; 5961 5962 return llvm::DenseMapInfo<std::pair<unsigned, const void *>>::getHashValue( 5963 std::make_pair(C.kind, C.data[Index])); 5964 } 5965 5966 unsigned clang_isInvalid(enum CXCursorKind K) { 5967 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid; 5968 } 5969 5970 unsigned clang_isDeclaration(enum CXCursorKind K) { 5971 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) || 5972 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl); 5973 } 5974 5975 unsigned clang_isInvalidDeclaration(CXCursor C) { 5976 if (clang_isDeclaration(C.kind)) { 5977 if (const Decl *D = getCursorDecl(C)) 5978 return D->isInvalidDecl(); 5979 } 5980 5981 return 0; 5982 } 5983 5984 unsigned clang_isReference(enum CXCursorKind K) { 5985 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef; 5986 } 5987 5988 unsigned clang_isExpression(enum CXCursorKind K) { 5989 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr; 5990 } 5991 5992 unsigned clang_isStatement(enum CXCursorKind K) { 5993 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt; 5994 } 5995 5996 unsigned clang_isAttribute(enum CXCursorKind K) { 5997 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr; 5998 } 5999 6000 unsigned clang_isTranslationUnit(enum CXCursorKind K) { 6001 return K == CXCursor_TranslationUnit; 6002 } 6003 6004 unsigned clang_isPreprocessing(enum CXCursorKind K) { 6005 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing; 6006 } 6007 6008 unsigned clang_isUnexposed(enum CXCursorKind K) { 6009 switch (K) { 6010 case CXCursor_UnexposedDecl: 6011 case CXCursor_UnexposedExpr: 6012 case CXCursor_UnexposedStmt: 6013 case CXCursor_UnexposedAttr: 6014 return true; 6015 default: 6016 return false; 6017 } 6018 } 6019 6020 CXCursorKind clang_getCursorKind(CXCursor C) { return C.kind; } 6021 6022 CXSourceLocation clang_getCursorLocation(CXCursor C) { 6023 if (clang_isReference(C.kind)) { 6024 switch (C.kind) { 6025 case CXCursor_ObjCSuperClassRef: { 6026 std::pair<const ObjCInterfaceDecl *, SourceLocation> P = 6027 getCursorObjCSuperClassRef(C); 6028 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 6029 } 6030 6031 case CXCursor_ObjCProtocolRef: { 6032 std::pair<const ObjCProtocolDecl *, SourceLocation> P = 6033 getCursorObjCProtocolRef(C); 6034 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 6035 } 6036 6037 case CXCursor_ObjCClassRef: { 6038 std::pair<const ObjCInterfaceDecl *, SourceLocation> P = 6039 getCursorObjCClassRef(C); 6040 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 6041 } 6042 6043 case CXCursor_TypeRef: { 6044 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C); 6045 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 6046 } 6047 6048 case CXCursor_TemplateRef: { 6049 std::pair<const TemplateDecl *, SourceLocation> P = 6050 getCursorTemplateRef(C); 6051 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 6052 } 6053 6054 case CXCursor_NamespaceRef: { 6055 std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C); 6056 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 6057 } 6058 6059 case CXCursor_MemberRef: { 6060 std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C); 6061 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 6062 } 6063 6064 case CXCursor_VariableRef: { 6065 std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C); 6066 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); 6067 } 6068 6069 case CXCursor_CXXBaseSpecifier: { 6070 const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C); 6071 if (!BaseSpec) 6072 return clang_getNullLocation(); 6073 6074 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo()) 6075 return cxloc::translateSourceLocation( 6076 getCursorContext(C), TSInfo->getTypeLoc().getBeginLoc()); 6077 6078 return cxloc::translateSourceLocation(getCursorContext(C), 6079 BaseSpec->getBeginLoc()); 6080 } 6081 6082 case CXCursor_LabelRef: { 6083 std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C); 6084 return cxloc::translateSourceLocation(getCursorContext(C), P.second); 6085 } 6086 6087 case CXCursor_OverloadedDeclRef: 6088 return cxloc::translateSourceLocation( 6089 getCursorContext(C), getCursorOverloadedDeclRef(C).second); 6090 6091 default: 6092 // FIXME: Need a way to enumerate all non-reference cases. 6093 llvm_unreachable("Missed a reference kind"); 6094 } 6095 } 6096 6097 if (clang_isExpression(C.kind)) 6098 return cxloc::translateSourceLocation( 6099 getCursorContext(C), getLocationFromExpr(getCursorExpr(C))); 6100 6101 if (clang_isStatement(C.kind)) 6102 return cxloc::translateSourceLocation(getCursorContext(C), 6103 getCursorStmt(C)->getBeginLoc()); 6104 6105 if (C.kind == CXCursor_PreprocessingDirective) { 6106 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin(); 6107 return cxloc::translateSourceLocation(getCursorContext(C), L); 6108 } 6109 6110 if (C.kind == CXCursor_MacroExpansion) { 6111 SourceLocation L = 6112 cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin(); 6113 return cxloc::translateSourceLocation(getCursorContext(C), L); 6114 } 6115 6116 if (C.kind == CXCursor_MacroDefinition) { 6117 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation(); 6118 return cxloc::translateSourceLocation(getCursorContext(C), L); 6119 } 6120 6121 if (C.kind == CXCursor_InclusionDirective) { 6122 SourceLocation L = 6123 cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin(); 6124 return cxloc::translateSourceLocation(getCursorContext(C), L); 6125 } 6126 6127 if (clang_isAttribute(C.kind)) { 6128 SourceLocation L = cxcursor::getCursorAttr(C)->getLocation(); 6129 return cxloc::translateSourceLocation(getCursorContext(C), L); 6130 } 6131 6132 if (!clang_isDeclaration(C.kind)) 6133 return clang_getNullLocation(); 6134 6135 const Decl *D = getCursorDecl(C); 6136 if (!D) 6137 return clang_getNullLocation(); 6138 6139 SourceLocation Loc = D->getLocation(); 6140 // FIXME: Multiple variables declared in a single declaration 6141 // currently lack the information needed to correctly determine their 6142 // ranges when accounting for the type-specifier. We use context 6143 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup, 6144 // and if so, whether it is the first decl. 6145 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 6146 if (!cxcursor::isFirstInDeclGroup(C)) 6147 Loc = VD->getLocation(); 6148 } 6149 6150 // For ObjC methods, give the start location of the method name. 6151 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) 6152 Loc = MD->getSelectorStartLoc(); 6153 6154 return cxloc::translateSourceLocation(getCursorContext(C), Loc); 6155 } 6156 6157 } // end extern "C" 6158 6159 CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) { 6160 assert(TU); 6161 6162 // Guard against an invalid SourceLocation, or we may assert in one 6163 // of the following calls. 6164 if (SLoc.isInvalid()) 6165 return clang_getNullCursor(); 6166 6167 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 6168 6169 // Translate the given source location to make it point at the beginning of 6170 // the token under the cursor. 6171 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(), 6172 CXXUnit->getASTContext().getLangOpts()); 6173 6174 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound); 6175 if (SLoc.isValid()) { 6176 GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result); 6177 CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData, 6178 /*VisitPreprocessorLast=*/true, 6179 /*VisitIncludedEntities=*/false, 6180 SourceLocation(SLoc)); 6181 CursorVis.visitFileRegion(); 6182 } 6183 6184 return Result; 6185 } 6186 6187 static SourceRange getRawCursorExtent(CXCursor C) { 6188 if (clang_isReference(C.kind)) { 6189 switch (C.kind) { 6190 case CXCursor_ObjCSuperClassRef: 6191 return getCursorObjCSuperClassRef(C).second; 6192 6193 case CXCursor_ObjCProtocolRef: 6194 return getCursorObjCProtocolRef(C).second; 6195 6196 case CXCursor_ObjCClassRef: 6197 return getCursorObjCClassRef(C).second; 6198 6199 case CXCursor_TypeRef: 6200 return getCursorTypeRef(C).second; 6201 6202 case CXCursor_TemplateRef: 6203 return getCursorTemplateRef(C).second; 6204 6205 case CXCursor_NamespaceRef: 6206 return getCursorNamespaceRef(C).second; 6207 6208 case CXCursor_MemberRef: 6209 return getCursorMemberRef(C).second; 6210 6211 case CXCursor_CXXBaseSpecifier: 6212 return getCursorCXXBaseSpecifier(C)->getSourceRange(); 6213 6214 case CXCursor_LabelRef: 6215 return getCursorLabelRef(C).second; 6216 6217 case CXCursor_OverloadedDeclRef: 6218 return getCursorOverloadedDeclRef(C).second; 6219 6220 case CXCursor_VariableRef: 6221 return getCursorVariableRef(C).second; 6222 6223 default: 6224 // FIXME: Need a way to enumerate all non-reference cases. 6225 llvm_unreachable("Missed a reference kind"); 6226 } 6227 } 6228 6229 if (clang_isExpression(C.kind)) 6230 return getCursorExpr(C)->getSourceRange(); 6231 6232 if (clang_isStatement(C.kind)) 6233 return getCursorStmt(C)->getSourceRange(); 6234 6235 if (clang_isAttribute(C.kind)) 6236 return getCursorAttr(C)->getRange(); 6237 6238 if (C.kind == CXCursor_PreprocessingDirective) 6239 return cxcursor::getCursorPreprocessingDirective(C); 6240 6241 if (C.kind == CXCursor_MacroExpansion) { 6242 ASTUnit *TU = getCursorASTUnit(C); 6243 SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange(); 6244 return TU->mapRangeFromPreamble(Range); 6245 } 6246 6247 if (C.kind == CXCursor_MacroDefinition) { 6248 ASTUnit *TU = getCursorASTUnit(C); 6249 SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange(); 6250 return TU->mapRangeFromPreamble(Range); 6251 } 6252 6253 if (C.kind == CXCursor_InclusionDirective) { 6254 ASTUnit *TU = getCursorASTUnit(C); 6255 SourceRange Range = 6256 cxcursor::getCursorInclusionDirective(C)->getSourceRange(); 6257 return TU->mapRangeFromPreamble(Range); 6258 } 6259 6260 if (C.kind == CXCursor_TranslationUnit) { 6261 ASTUnit *TU = getCursorASTUnit(C); 6262 FileID MainID = TU->getSourceManager().getMainFileID(); 6263 SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID); 6264 SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID); 6265 return SourceRange(Start, End); 6266 } 6267 6268 if (clang_isDeclaration(C.kind)) { 6269 const Decl *D = cxcursor::getCursorDecl(C); 6270 if (!D) 6271 return SourceRange(); 6272 6273 SourceRange R = D->getSourceRange(); 6274 // FIXME: Multiple variables declared in a single declaration 6275 // currently lack the information needed to correctly determine their 6276 // ranges when accounting for the type-specifier. We use context 6277 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup, 6278 // and if so, whether it is the first decl. 6279 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 6280 if (!cxcursor::isFirstInDeclGroup(C)) 6281 R.setBegin(VD->getLocation()); 6282 } 6283 return R; 6284 } 6285 return SourceRange(); 6286 } 6287 6288 /// Retrieves the "raw" cursor extent, which is then extended to include 6289 /// the decl-specifier-seq for declarations. 6290 static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) { 6291 if (clang_isDeclaration(C.kind)) { 6292 const Decl *D = cxcursor::getCursorDecl(C); 6293 if (!D) 6294 return SourceRange(); 6295 6296 SourceRange R = D->getSourceRange(); 6297 6298 // Adjust the start of the location for declarations preceded by 6299 // declaration specifiers. 6300 SourceLocation StartLoc; 6301 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 6302 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) 6303 StartLoc = TI->getTypeLoc().getBeginLoc(); 6304 } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) { 6305 if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo()) 6306 StartLoc = TI->getTypeLoc().getBeginLoc(); 6307 } 6308 6309 if (StartLoc.isValid() && R.getBegin().isValid() && 6310 SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin())) 6311 R.setBegin(StartLoc); 6312 6313 // FIXME: Multiple variables declared in a single declaration 6314 // currently lack the information needed to correctly determine their 6315 // ranges when accounting for the type-specifier. We use context 6316 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup, 6317 // and if so, whether it is the first decl. 6318 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 6319 if (!cxcursor::isFirstInDeclGroup(C)) 6320 R.setBegin(VD->getLocation()); 6321 } 6322 6323 return R; 6324 } 6325 6326 return getRawCursorExtent(C); 6327 } 6328 6329 CXSourceRange clang_getCursorExtent(CXCursor C) { 6330 SourceRange R = getRawCursorExtent(C); 6331 if (R.isInvalid()) 6332 return clang_getNullRange(); 6333 6334 return cxloc::translateSourceRange(getCursorContext(C), R); 6335 } 6336 6337 CXCursor clang_getCursorReferenced(CXCursor C) { 6338 if (clang_isInvalid(C.kind)) 6339 return clang_getNullCursor(); 6340 6341 CXTranslationUnit tu = getCursorTU(C); 6342 if (clang_isDeclaration(C.kind)) { 6343 const Decl *D = getCursorDecl(C); 6344 if (!D) 6345 return clang_getNullCursor(); 6346 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) 6347 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu); 6348 if (const ObjCPropertyImplDecl *PropImpl = 6349 dyn_cast<ObjCPropertyImplDecl>(D)) 6350 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl()) 6351 return MakeCXCursor(Property, tu); 6352 6353 return C; 6354 } 6355 6356 if (clang_isExpression(C.kind)) { 6357 const Expr *E = getCursorExpr(C); 6358 const Decl *D = getDeclFromExpr(E); 6359 if (D) { 6360 CXCursor declCursor = MakeCXCursor(D, tu); 6361 declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C), 6362 declCursor); 6363 return declCursor; 6364 } 6365 6366 if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E)) 6367 return MakeCursorOverloadedDeclRef(Ovl, tu); 6368 6369 return clang_getNullCursor(); 6370 } 6371 6372 if (clang_isStatement(C.kind)) { 6373 const Stmt *S = getCursorStmt(C); 6374 if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S)) 6375 if (LabelDecl *label = Goto->getLabel()) 6376 if (LabelStmt *labelS = label->getStmt()) 6377 return MakeCXCursor(labelS, getCursorDecl(C), tu); 6378 6379 return clang_getNullCursor(); 6380 } 6381 6382 if (C.kind == CXCursor_MacroExpansion) { 6383 if (const MacroDefinitionRecord *Def = 6384 getCursorMacroExpansion(C).getDefinition()) 6385 return MakeMacroDefinitionCursor(Def, tu); 6386 } 6387 6388 if (!clang_isReference(C.kind)) 6389 return clang_getNullCursor(); 6390 6391 switch (C.kind) { 6392 case CXCursor_ObjCSuperClassRef: 6393 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu); 6394 6395 case CXCursor_ObjCProtocolRef: { 6396 const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first; 6397 if (const ObjCProtocolDecl *Def = Prot->getDefinition()) 6398 return MakeCXCursor(Def, tu); 6399 6400 return MakeCXCursor(Prot, tu); 6401 } 6402 6403 case CXCursor_ObjCClassRef: { 6404 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first; 6405 if (const ObjCInterfaceDecl *Def = Class->getDefinition()) 6406 return MakeCXCursor(Def, tu); 6407 6408 return MakeCXCursor(Class, tu); 6409 } 6410 6411 case CXCursor_TypeRef: 6412 return MakeCXCursor(getCursorTypeRef(C).first, tu); 6413 6414 case CXCursor_TemplateRef: 6415 return MakeCXCursor(getCursorTemplateRef(C).first, tu); 6416 6417 case CXCursor_NamespaceRef: 6418 return MakeCXCursor(getCursorNamespaceRef(C).first, tu); 6419 6420 case CXCursor_MemberRef: 6421 return MakeCXCursor(getCursorMemberRef(C).first, tu); 6422 6423 case CXCursor_CXXBaseSpecifier: { 6424 const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C); 6425 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(), tu)); 6426 } 6427 6428 case CXCursor_LabelRef: 6429 // FIXME: We end up faking the "parent" declaration here because we 6430 // don't want to make CXCursor larger. 6431 return MakeCXCursor( 6432 getCursorLabelRef(C).first, 6433 cxtu::getASTUnit(tu)->getASTContext().getTranslationUnitDecl(), tu); 6434 6435 case CXCursor_OverloadedDeclRef: 6436 return C; 6437 6438 case CXCursor_VariableRef: 6439 return MakeCXCursor(getCursorVariableRef(C).first, tu); 6440 6441 default: 6442 // We would prefer to enumerate all non-reference cursor kinds here. 6443 llvm_unreachable("Unhandled reference cursor kind"); 6444 } 6445 } 6446 6447 CXCursor clang_getCursorDefinition(CXCursor C) { 6448 if (clang_isInvalid(C.kind)) 6449 return clang_getNullCursor(); 6450 6451 CXTranslationUnit TU = getCursorTU(C); 6452 6453 bool WasReference = false; 6454 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) { 6455 C = clang_getCursorReferenced(C); 6456 WasReference = true; 6457 } 6458 6459 if (C.kind == CXCursor_MacroExpansion) 6460 return clang_getCursorReferenced(C); 6461 6462 if (!clang_isDeclaration(C.kind)) 6463 return clang_getNullCursor(); 6464 6465 const Decl *D = getCursorDecl(C); 6466 if (!D) 6467 return clang_getNullCursor(); 6468 6469 switch (D->getKind()) { 6470 // Declaration kinds that don't really separate the notions of 6471 // declaration and definition. 6472 case Decl::Namespace: 6473 case Decl::Typedef: 6474 case Decl::TypeAlias: 6475 case Decl::TypeAliasTemplate: 6476 case Decl::TemplateTypeParm: 6477 case Decl::EnumConstant: 6478 case Decl::Field: 6479 case Decl::Binding: 6480 case Decl::MSProperty: 6481 case Decl::MSGuid: 6482 case Decl::UnnamedGlobalConstant: 6483 case Decl::TemplateParamObject: 6484 case Decl::IndirectField: 6485 case Decl::ObjCIvar: 6486 case Decl::ObjCAtDefsField: 6487 case Decl::ImplicitParam: 6488 case Decl::ParmVar: 6489 case Decl::NonTypeTemplateParm: 6490 case Decl::TemplateTemplateParm: 6491 case Decl::ObjCCategoryImpl: 6492 case Decl::ObjCImplementation: 6493 case Decl::AccessSpec: 6494 case Decl::LinkageSpec: 6495 case Decl::Export: 6496 case Decl::ObjCPropertyImpl: 6497 case Decl::FileScopeAsm: 6498 case Decl::StaticAssert: 6499 case Decl::Block: 6500 case Decl::Captured: 6501 case Decl::OMPCapturedExpr: 6502 case Decl::Label: // FIXME: Is this right?? 6503 case Decl::ClassScopeFunctionSpecialization: 6504 case Decl::CXXDeductionGuide: 6505 case Decl::Import: 6506 case Decl::OMPThreadPrivate: 6507 case Decl::OMPAllocate: 6508 case Decl::OMPDeclareReduction: 6509 case Decl::OMPDeclareMapper: 6510 case Decl::OMPRequires: 6511 case Decl::ObjCTypeParam: 6512 case Decl::BuiltinTemplate: 6513 case Decl::PragmaComment: 6514 case Decl::PragmaDetectMismatch: 6515 case Decl::UsingPack: 6516 case Decl::Concept: 6517 case Decl::LifetimeExtendedTemporary: 6518 case Decl::RequiresExprBody: 6519 case Decl::UnresolvedUsingIfExists: 6520 return C; 6521 6522 // Declaration kinds that don't make any sense here, but are 6523 // nonetheless harmless. 6524 case Decl::Empty: 6525 case Decl::TranslationUnit: 6526 case Decl::ExternCContext: 6527 break; 6528 6529 // Declaration kinds for which the definition is not resolvable. 6530 case Decl::UnresolvedUsingTypename: 6531 case Decl::UnresolvedUsingValue: 6532 break; 6533 6534 case Decl::UsingDirective: 6535 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(), 6536 TU); 6537 6538 case Decl::NamespaceAlias: 6539 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU); 6540 6541 case Decl::Enum: 6542 case Decl::Record: 6543 case Decl::CXXRecord: 6544 case Decl::ClassTemplateSpecialization: 6545 case Decl::ClassTemplatePartialSpecialization: 6546 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition()) 6547 return MakeCXCursor(Def, TU); 6548 return clang_getNullCursor(); 6549 6550 case Decl::Function: 6551 case Decl::CXXMethod: 6552 case Decl::CXXConstructor: 6553 case Decl::CXXDestructor: 6554 case Decl::CXXConversion: { 6555 const FunctionDecl *Def = nullptr; 6556 if (cast<FunctionDecl>(D)->getBody(Def)) 6557 return MakeCXCursor(Def, TU); 6558 return clang_getNullCursor(); 6559 } 6560 6561 case Decl::Var: 6562 case Decl::VarTemplateSpecialization: 6563 case Decl::VarTemplatePartialSpecialization: 6564 case Decl::Decomposition: { 6565 // Ask the variable if it has a definition. 6566 if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition()) 6567 return MakeCXCursor(Def, TU); 6568 return clang_getNullCursor(); 6569 } 6570 6571 case Decl::FunctionTemplate: { 6572 const FunctionDecl *Def = nullptr; 6573 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def)) 6574 return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU); 6575 return clang_getNullCursor(); 6576 } 6577 6578 case Decl::ClassTemplate: { 6579 if (RecordDecl *Def = 6580 cast<ClassTemplateDecl>(D)->getTemplatedDecl()->getDefinition()) 6581 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(), 6582 TU); 6583 return clang_getNullCursor(); 6584 } 6585 6586 case Decl::VarTemplate: { 6587 if (VarDecl *Def = 6588 cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition()) 6589 return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU); 6590 return clang_getNullCursor(); 6591 } 6592 6593 case Decl::Using: 6594 case Decl::UsingEnum: 6595 return MakeCursorOverloadedDeclRef(cast<BaseUsingDecl>(D), D->getLocation(), 6596 TU); 6597 6598 case Decl::UsingShadow: 6599 case Decl::ConstructorUsingShadow: 6600 return clang_getCursorDefinition( 6601 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(), TU)); 6602 6603 case Decl::ObjCMethod: { 6604 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D); 6605 if (Method->isThisDeclarationADefinition()) 6606 return C; 6607 6608 // Dig out the method definition in the associated 6609 // @implementation, if we have it. 6610 // FIXME: The ASTs should make finding the definition easier. 6611 if (const ObjCInterfaceDecl *Class = 6612 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) 6613 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation()) 6614 if (ObjCMethodDecl *Def = ClassImpl->getMethod( 6615 Method->getSelector(), Method->isInstanceMethod())) 6616 if (Def->isThisDeclarationADefinition()) 6617 return MakeCXCursor(Def, TU); 6618 6619 return clang_getNullCursor(); 6620 } 6621 6622 case Decl::ObjCCategory: 6623 if (ObjCCategoryImplDecl *Impl = 6624 cast<ObjCCategoryDecl>(D)->getImplementation()) 6625 return MakeCXCursor(Impl, TU); 6626 return clang_getNullCursor(); 6627 6628 case Decl::ObjCProtocol: 6629 if (const ObjCProtocolDecl *Def = 6630 cast<ObjCProtocolDecl>(D)->getDefinition()) 6631 return MakeCXCursor(Def, TU); 6632 return clang_getNullCursor(); 6633 6634 case Decl::ObjCInterface: { 6635 // There are two notions of a "definition" for an Objective-C 6636 // class: the interface and its implementation. When we resolved a 6637 // reference to an Objective-C class, produce the @interface as 6638 // the definition; when we were provided with the interface, 6639 // produce the @implementation as the definition. 6640 const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D); 6641 if (WasReference) { 6642 if (const ObjCInterfaceDecl *Def = IFace->getDefinition()) 6643 return MakeCXCursor(Def, TU); 6644 } else if (ObjCImplementationDecl *Impl = IFace->getImplementation()) 6645 return MakeCXCursor(Impl, TU); 6646 return clang_getNullCursor(); 6647 } 6648 6649 case Decl::ObjCProperty: 6650 // FIXME: We don't really know where to find the 6651 // ObjCPropertyImplDecls that implement this property. 6652 return clang_getNullCursor(); 6653 6654 case Decl::ObjCCompatibleAlias: 6655 if (const ObjCInterfaceDecl *Class = 6656 cast<ObjCCompatibleAliasDecl>(D)->getClassInterface()) 6657 if (const ObjCInterfaceDecl *Def = Class->getDefinition()) 6658 return MakeCXCursor(Def, TU); 6659 6660 return clang_getNullCursor(); 6661 6662 case Decl::Friend: 6663 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl()) 6664 return clang_getCursorDefinition(MakeCXCursor(Friend, TU)); 6665 return clang_getNullCursor(); 6666 6667 case Decl::FriendTemplate: 6668 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl()) 6669 return clang_getCursorDefinition(MakeCXCursor(Friend, TU)); 6670 return clang_getNullCursor(); 6671 } 6672 6673 return clang_getNullCursor(); 6674 } 6675 6676 unsigned clang_isCursorDefinition(CXCursor C) { 6677 if (!clang_isDeclaration(C.kind)) 6678 return 0; 6679 6680 return clang_getCursorDefinition(C) == C; 6681 } 6682 6683 CXCursor clang_getCanonicalCursor(CXCursor C) { 6684 if (!clang_isDeclaration(C.kind)) 6685 return C; 6686 6687 if (const Decl *D = getCursorDecl(C)) { 6688 if (const ObjCCategoryImplDecl *CatImplD = 6689 dyn_cast<ObjCCategoryImplDecl>(D)) 6690 if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl()) 6691 return MakeCXCursor(CatD, getCursorTU(C)); 6692 6693 if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D)) 6694 if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface()) 6695 return MakeCXCursor(IFD, getCursorTU(C)); 6696 6697 return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C)); 6698 } 6699 6700 return C; 6701 } 6702 6703 int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) { 6704 return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first; 6705 } 6706 6707 unsigned clang_getNumOverloadedDecls(CXCursor C) { 6708 if (C.kind != CXCursor_OverloadedDeclRef) 6709 return 0; 6710 6711 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first; 6712 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>()) 6713 return E->getNumDecls(); 6714 6715 if (OverloadedTemplateStorage *S = 6716 Storage.dyn_cast<OverloadedTemplateStorage *>()) 6717 return S->size(); 6718 6719 const Decl *D = Storage.get<const Decl *>(); 6720 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) 6721 return Using->shadow_size(); 6722 6723 return 0; 6724 } 6725 6726 CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) { 6727 if (cursor.kind != CXCursor_OverloadedDeclRef) 6728 return clang_getNullCursor(); 6729 6730 if (index >= clang_getNumOverloadedDecls(cursor)) 6731 return clang_getNullCursor(); 6732 6733 CXTranslationUnit TU = getCursorTU(cursor); 6734 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first; 6735 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>()) 6736 return MakeCXCursor(E->decls_begin()[index], TU); 6737 6738 if (OverloadedTemplateStorage *S = 6739 Storage.dyn_cast<OverloadedTemplateStorage *>()) 6740 return MakeCXCursor(S->begin()[index], TU); 6741 6742 const Decl *D = Storage.get<const Decl *>(); 6743 if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) { 6744 // FIXME: This is, unfortunately, linear time. 6745 UsingDecl::shadow_iterator Pos = Using->shadow_begin(); 6746 std::advance(Pos, index); 6747 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU); 6748 } 6749 6750 return clang_getNullCursor(); 6751 } 6752 6753 void clang_getDefinitionSpellingAndExtent( 6754 CXCursor C, const char **startBuf, const char **endBuf, unsigned *startLine, 6755 unsigned *startColumn, unsigned *endLine, unsigned *endColumn) { 6756 assert(getCursorDecl(C) && "CXCursor has null decl"); 6757 const auto *FD = cast<FunctionDecl>(getCursorDecl(C)); 6758 const auto *Body = cast<CompoundStmt>(FD->getBody()); 6759 6760 SourceManager &SM = FD->getASTContext().getSourceManager(); 6761 *startBuf = SM.getCharacterData(Body->getLBracLoc()); 6762 *endBuf = SM.getCharacterData(Body->getRBracLoc()); 6763 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc()); 6764 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc()); 6765 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc()); 6766 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc()); 6767 } 6768 6769 CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags, 6770 unsigned PieceIndex) { 6771 RefNamePieces Pieces; 6772 6773 switch (C.kind) { 6774 case CXCursor_MemberRefExpr: 6775 if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C))) 6776 Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(), 6777 E->getQualifierLoc().getSourceRange()); 6778 break; 6779 6780 case CXCursor_DeclRefExpr: 6781 if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) { 6782 SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc()); 6783 Pieces = 6784 buildPieces(NameFlags, false, E->getNameInfo(), 6785 E->getQualifierLoc().getSourceRange(), &TemplateArgLoc); 6786 } 6787 break; 6788 6789 case CXCursor_CallExpr: 6790 if (const CXXOperatorCallExpr *OCE = 6791 dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) { 6792 const Expr *Callee = OCE->getCallee(); 6793 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee)) 6794 Callee = ICE->getSubExpr(); 6795 6796 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee)) 6797 Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(), 6798 DRE->getQualifierLoc().getSourceRange()); 6799 } 6800 break; 6801 6802 default: 6803 break; 6804 } 6805 6806 if (Pieces.empty()) { 6807 if (PieceIndex == 0) 6808 return clang_getCursorExtent(C); 6809 } else if (PieceIndex < Pieces.size()) { 6810 SourceRange R = Pieces[PieceIndex]; 6811 if (R.isValid()) 6812 return cxloc::translateSourceRange(getCursorContext(C), R); 6813 } 6814 6815 return clang_getNullRange(); 6816 } 6817 6818 void clang_enableStackTraces(void) { 6819 // FIXME: Provide an argv0 here so we can find llvm-symbolizer. 6820 llvm::sys::PrintStackTraceOnErrorSignal(StringRef()); 6821 } 6822 6823 void clang_executeOnThread(void (*fn)(void *), void *user_data, 6824 unsigned stack_size) { 6825 llvm::thread Thread(stack_size == 0 ? clang::DesiredStackSize 6826 : llvm::Optional<unsigned>(stack_size), 6827 fn, user_data); 6828 Thread.join(); 6829 } 6830 6831 //===----------------------------------------------------------------------===// 6832 // Token-based Operations. 6833 //===----------------------------------------------------------------------===// 6834 6835 /* CXToken layout: 6836 * int_data[0]: a CXTokenKind 6837 * int_data[1]: starting token location 6838 * int_data[2]: token length 6839 * int_data[3]: reserved 6840 * ptr_data: for identifiers and keywords, an IdentifierInfo*. 6841 * otherwise unused. 6842 */ 6843 CXTokenKind clang_getTokenKind(CXToken CXTok) { 6844 return static_cast<CXTokenKind>(CXTok.int_data[0]); 6845 } 6846 6847 CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) { 6848 switch (clang_getTokenKind(CXTok)) { 6849 case CXToken_Identifier: 6850 case CXToken_Keyword: 6851 // We know we have an IdentifierInfo*, so use that. 6852 return cxstring::createRef( 6853 static_cast<IdentifierInfo *>(CXTok.ptr_data)->getNameStart()); 6854 6855 case CXToken_Literal: { 6856 // We have stashed the starting pointer in the ptr_data field. Use it. 6857 const char *Text = static_cast<const char *>(CXTok.ptr_data); 6858 return cxstring::createDup(StringRef(Text, CXTok.int_data[2])); 6859 } 6860 6861 case CXToken_Punctuation: 6862 case CXToken_Comment: 6863 break; 6864 } 6865 6866 if (isNotUsableTU(TU)) { 6867 LOG_BAD_TU(TU); 6868 return cxstring::createEmpty(); 6869 } 6870 6871 // We have to find the starting buffer pointer the hard way, by 6872 // deconstructing the source location. 6873 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 6874 if (!CXXUnit) 6875 return cxstring::createEmpty(); 6876 6877 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]); 6878 std::pair<FileID, unsigned> LocInfo = 6879 CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc); 6880 bool Invalid = false; 6881 StringRef Buffer = 6882 CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid); 6883 if (Invalid) 6884 return cxstring::createEmpty(); 6885 6886 return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2])); 6887 } 6888 6889 CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) { 6890 if (isNotUsableTU(TU)) { 6891 LOG_BAD_TU(TU); 6892 return clang_getNullLocation(); 6893 } 6894 6895 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 6896 if (!CXXUnit) 6897 return clang_getNullLocation(); 6898 6899 return cxloc::translateSourceLocation( 6900 CXXUnit->getASTContext(), 6901 SourceLocation::getFromRawEncoding(CXTok.int_data[1])); 6902 } 6903 6904 CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) { 6905 if (isNotUsableTU(TU)) { 6906 LOG_BAD_TU(TU); 6907 return clang_getNullRange(); 6908 } 6909 6910 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 6911 if (!CXXUnit) 6912 return clang_getNullRange(); 6913 6914 return cxloc::translateSourceRange( 6915 CXXUnit->getASTContext(), 6916 SourceLocation::getFromRawEncoding(CXTok.int_data[1])); 6917 } 6918 6919 static void getTokens(ASTUnit *CXXUnit, SourceRange Range, 6920 SmallVectorImpl<CXToken> &CXTokens) { 6921 SourceManager &SourceMgr = CXXUnit->getSourceManager(); 6922 std::pair<FileID, unsigned> BeginLocInfo = 6923 SourceMgr.getDecomposedSpellingLoc(Range.getBegin()); 6924 std::pair<FileID, unsigned> EndLocInfo = 6925 SourceMgr.getDecomposedSpellingLoc(Range.getEnd()); 6926 6927 // Cannot tokenize across files. 6928 if (BeginLocInfo.first != EndLocInfo.first) 6929 return; 6930 6931 // Create a lexer 6932 bool Invalid = false; 6933 StringRef Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid); 6934 if (Invalid) 6935 return; 6936 6937 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first), 6938 CXXUnit->getASTContext().getLangOpts(), Buffer.begin(), 6939 Buffer.data() + BeginLocInfo.second, Buffer.end()); 6940 Lex.SetCommentRetentionState(true); 6941 6942 // Lex tokens until we hit the end of the range. 6943 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second; 6944 Token Tok; 6945 bool previousWasAt = false; 6946 do { 6947 // Lex the next token 6948 Lex.LexFromRawLexer(Tok); 6949 if (Tok.is(tok::eof)) 6950 break; 6951 6952 // Initialize the CXToken. 6953 CXToken CXTok; 6954 6955 // - Common fields 6956 CXTok.int_data[1] = Tok.getLocation().getRawEncoding(); 6957 CXTok.int_data[2] = Tok.getLength(); 6958 CXTok.int_data[3] = 0; 6959 6960 // - Kind-specific fields 6961 if (Tok.isLiteral()) { 6962 CXTok.int_data[0] = CXToken_Literal; 6963 CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData()); 6964 } else if (Tok.is(tok::raw_identifier)) { 6965 // Lookup the identifier to determine whether we have a keyword. 6966 IdentifierInfo *II = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok); 6967 6968 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) { 6969 CXTok.int_data[0] = CXToken_Keyword; 6970 } else { 6971 CXTok.int_data[0] = 6972 Tok.is(tok::identifier) ? CXToken_Identifier : CXToken_Keyword; 6973 } 6974 CXTok.ptr_data = II; 6975 } else if (Tok.is(tok::comment)) { 6976 CXTok.int_data[0] = CXToken_Comment; 6977 CXTok.ptr_data = nullptr; 6978 } else { 6979 CXTok.int_data[0] = CXToken_Punctuation; 6980 CXTok.ptr_data = nullptr; 6981 } 6982 CXTokens.push_back(CXTok); 6983 previousWasAt = Tok.is(tok::at); 6984 } while (Lex.getBufferLocation() < EffectiveBufferEnd); 6985 } 6986 6987 CXToken *clang_getToken(CXTranslationUnit TU, CXSourceLocation Location) { 6988 LOG_FUNC_SECTION { *Log << TU << ' ' << Location; } 6989 6990 if (isNotUsableTU(TU)) { 6991 LOG_BAD_TU(TU); 6992 return nullptr; 6993 } 6994 6995 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 6996 if (!CXXUnit) 6997 return nullptr; 6998 6999 SourceLocation Begin = cxloc::translateSourceLocation(Location); 7000 if (Begin.isInvalid()) 7001 return nullptr; 7002 SourceManager &SM = CXXUnit->getSourceManager(); 7003 std::pair<FileID, unsigned> DecomposedEnd = SM.getDecomposedLoc(Begin); 7004 DecomposedEnd.second += 7005 Lexer::MeasureTokenLength(Begin, SM, CXXUnit->getLangOpts()); 7006 7007 SourceLocation End = 7008 SM.getComposedLoc(DecomposedEnd.first, DecomposedEnd.second); 7009 7010 SmallVector<CXToken, 32> CXTokens; 7011 getTokens(CXXUnit, SourceRange(Begin, End), CXTokens); 7012 7013 if (CXTokens.empty()) 7014 return nullptr; 7015 7016 CXTokens.resize(1); 7017 CXToken *Token = static_cast<CXToken *>(llvm::safe_malloc(sizeof(CXToken))); 7018 7019 memmove(Token, CXTokens.data(), sizeof(CXToken)); 7020 return Token; 7021 } 7022 7023 void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range, CXToken **Tokens, 7024 unsigned *NumTokens) { 7025 LOG_FUNC_SECTION { *Log << TU << ' ' << Range; } 7026 7027 if (Tokens) 7028 *Tokens = nullptr; 7029 if (NumTokens) 7030 *NumTokens = 0; 7031 7032 if (isNotUsableTU(TU)) { 7033 LOG_BAD_TU(TU); 7034 return; 7035 } 7036 7037 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 7038 if (!CXXUnit || !Tokens || !NumTokens) 7039 return; 7040 7041 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 7042 7043 SourceRange R = cxloc::translateCXSourceRange(Range); 7044 if (R.isInvalid()) 7045 return; 7046 7047 SmallVector<CXToken, 32> CXTokens; 7048 getTokens(CXXUnit, R, CXTokens); 7049 7050 if (CXTokens.empty()) 7051 return; 7052 7053 *Tokens = static_cast<CXToken *>( 7054 llvm::safe_malloc(sizeof(CXToken) * CXTokens.size())); 7055 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size()); 7056 *NumTokens = CXTokens.size(); 7057 } 7058 7059 void clang_disposeTokens(CXTranslationUnit TU, CXToken *Tokens, 7060 unsigned NumTokens) { 7061 free(Tokens); 7062 } 7063 7064 //===----------------------------------------------------------------------===// 7065 // Token annotation APIs. 7066 //===----------------------------------------------------------------------===// 7067 7068 static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor, 7069 CXCursor parent, 7070 CXClientData client_data); 7071 static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor, 7072 CXClientData client_data); 7073 7074 namespace { 7075 class AnnotateTokensWorker { 7076 CXToken *Tokens; 7077 CXCursor *Cursors; 7078 unsigned NumTokens; 7079 unsigned TokIdx; 7080 unsigned PreprocessingTokIdx; 7081 CursorVisitor AnnotateVis; 7082 SourceManager &SrcMgr; 7083 bool HasContextSensitiveKeywords; 7084 7085 struct PostChildrenAction { 7086 CXCursor cursor; 7087 enum Action { Invalid, Ignore, Postpone } action; 7088 }; 7089 using PostChildrenActions = SmallVector<PostChildrenAction, 0>; 7090 7091 struct PostChildrenInfo { 7092 CXCursor Cursor; 7093 SourceRange CursorRange; 7094 unsigned BeforeReachingCursorIdx; 7095 unsigned BeforeChildrenTokenIdx; 7096 PostChildrenActions ChildActions; 7097 }; 7098 SmallVector<PostChildrenInfo, 8> PostChildrenInfos; 7099 7100 CXToken &getTok(unsigned Idx) { 7101 assert(Idx < NumTokens); 7102 return Tokens[Idx]; 7103 } 7104 const CXToken &getTok(unsigned Idx) const { 7105 assert(Idx < NumTokens); 7106 return Tokens[Idx]; 7107 } 7108 bool MoreTokens() const { return TokIdx < NumTokens; } 7109 unsigned NextToken() const { return TokIdx; } 7110 void AdvanceToken() { ++TokIdx; } 7111 SourceLocation GetTokenLoc(unsigned tokI) { 7112 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]); 7113 } 7114 bool isFunctionMacroToken(unsigned tokI) const { 7115 return getTok(tokI).int_data[3] != 0; 7116 } 7117 SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const { 7118 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]); 7119 } 7120 7121 void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange); 7122 bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult, 7123 SourceRange); 7124 7125 public: 7126 AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens, 7127 CXTranslationUnit TU, SourceRange RegionOfInterest) 7128 : Tokens(tokens), Cursors(cursors), NumTokens(numTokens), TokIdx(0), 7129 PreprocessingTokIdx(0), 7130 AnnotateVis(TU, AnnotateTokensVisitor, this, 7131 /*VisitPreprocessorLast=*/true, 7132 /*VisitIncludedEntities=*/false, RegionOfInterest, 7133 /*VisitDeclsOnly=*/false, 7134 AnnotateTokensPostChildrenVisitor), 7135 SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()), 7136 HasContextSensitiveKeywords(false) {} 7137 7138 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); } 7139 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent); 7140 bool IsIgnoredChildCursor(CXCursor cursor) const; 7141 PostChildrenActions DetermineChildActions(CXCursor Cursor) const; 7142 7143 bool postVisitChildren(CXCursor cursor); 7144 void HandlePostPonedChildCursors(const PostChildrenInfo &Info); 7145 void HandlePostPonedChildCursor(CXCursor Cursor, unsigned StartTokenIndex); 7146 7147 void AnnotateTokens(); 7148 7149 /// Determine whether the annotator saw any cursors that have 7150 /// context-sensitive keywords. 7151 bool hasContextSensitiveKeywords() const { 7152 return HasContextSensitiveKeywords; 7153 } 7154 7155 ~AnnotateTokensWorker() { assert(PostChildrenInfos.empty()); } 7156 }; 7157 } // namespace 7158 7159 void AnnotateTokensWorker::AnnotateTokens() { 7160 // Walk the AST within the region of interest, annotating tokens 7161 // along the way. 7162 AnnotateVis.visitFileRegion(); 7163 } 7164 7165 bool AnnotateTokensWorker::IsIgnoredChildCursor(CXCursor cursor) const { 7166 if (PostChildrenInfos.empty()) 7167 return false; 7168 7169 for (const auto &ChildAction : PostChildrenInfos.back().ChildActions) { 7170 if (ChildAction.cursor == cursor && 7171 ChildAction.action == PostChildrenAction::Ignore) { 7172 return true; 7173 } 7174 } 7175 7176 return false; 7177 } 7178 7179 const CXXOperatorCallExpr *GetSubscriptOrCallOperator(CXCursor Cursor) { 7180 if (!clang_isExpression(Cursor.kind)) 7181 return nullptr; 7182 7183 const Expr *E = getCursorExpr(Cursor); 7184 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) { 7185 const OverloadedOperatorKind Kind = OCE->getOperator(); 7186 if (Kind == OO_Call || Kind == OO_Subscript) 7187 return OCE; 7188 } 7189 7190 return nullptr; 7191 } 7192 7193 AnnotateTokensWorker::PostChildrenActions 7194 AnnotateTokensWorker::DetermineChildActions(CXCursor Cursor) const { 7195 PostChildrenActions actions; 7196 7197 // The DeclRefExpr of CXXOperatorCallExpr refering to the custom operator is 7198 // visited before the arguments to the operator call. For the Call and 7199 // Subscript operator the range of this DeclRefExpr includes the whole call 7200 // expression, so that all tokens in that range would be mapped to the 7201 // operator function, including the tokens of the arguments. To avoid that, 7202 // ensure to visit this DeclRefExpr as last node. 7203 if (const auto *OCE = GetSubscriptOrCallOperator(Cursor)) { 7204 const Expr *Callee = OCE->getCallee(); 7205 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee)) { 7206 const Expr *SubExpr = ICE->getSubExpr(); 7207 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr)) { 7208 const Decl *parentDecl = getCursorDecl(Cursor); 7209 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor); 7210 7211 // Visit the DeclRefExpr as last. 7212 CXCursor cxChild = MakeCXCursor(DRE, parentDecl, TU); 7213 actions.push_back({cxChild, PostChildrenAction::Postpone}); 7214 7215 // The parent of the DeclRefExpr, an ImplicitCastExpr, has an equally 7216 // wide range as the DeclRefExpr. We can skip visiting this entirely. 7217 cxChild = MakeCXCursor(ICE, parentDecl, TU); 7218 actions.push_back({cxChild, PostChildrenAction::Ignore}); 7219 } 7220 } 7221 } 7222 7223 return actions; 7224 } 7225 7226 static inline void updateCursorAnnotation(CXCursor &Cursor, 7227 const CXCursor &updateC) { 7228 if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind)) 7229 return; 7230 Cursor = updateC; 7231 } 7232 7233 /// It annotates and advances tokens with a cursor until the comparison 7234 //// between the cursor location and the source range is the same as 7235 /// \arg compResult. 7236 /// 7237 /// Pass RangeBefore to annotate tokens with a cursor until a range is reached. 7238 /// Pass RangeOverlap to annotate tokens inside a range. 7239 void AnnotateTokensWorker::annotateAndAdvanceTokens( 7240 CXCursor updateC, RangeComparisonResult compResult, SourceRange range) { 7241 while (MoreTokens()) { 7242 const unsigned I = NextToken(); 7243 if (isFunctionMacroToken(I)) 7244 if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range)) 7245 return; 7246 7247 SourceLocation TokLoc = GetTokenLoc(I); 7248 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) { 7249 updateCursorAnnotation(Cursors[I], updateC); 7250 AdvanceToken(); 7251 continue; 7252 } 7253 break; 7254 } 7255 } 7256 7257 /// Special annotation handling for macro argument tokens. 7258 /// \returns true if it advanced beyond all macro tokens, false otherwise. 7259 bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens( 7260 CXCursor updateC, RangeComparisonResult compResult, SourceRange range) { 7261 assert(MoreTokens()); 7262 assert(isFunctionMacroToken(NextToken()) && 7263 "Should be called only for macro arg tokens"); 7264 7265 // This works differently than annotateAndAdvanceTokens; because expanded 7266 // macro arguments can have arbitrary translation-unit source order, we do not 7267 // advance the token index one by one until a token fails the range test. 7268 // We only advance once past all of the macro arg tokens if all of them 7269 // pass the range test. If one of them fails we keep the token index pointing 7270 // at the start of the macro arg tokens so that the failing token will be 7271 // annotated by a subsequent annotation try. 7272 7273 bool atLeastOneCompFail = false; 7274 7275 unsigned I = NextToken(); 7276 for (; I < NumTokens && isFunctionMacroToken(I); ++I) { 7277 SourceLocation TokLoc = getFunctionMacroTokenLoc(I); 7278 if (TokLoc.isFileID()) 7279 continue; // not macro arg token, it's parens or comma. 7280 if (LocationCompare(SrcMgr, TokLoc, range) == compResult) { 7281 if (clang_isInvalid(clang_getCursorKind(Cursors[I]))) 7282 Cursors[I] = updateC; 7283 } else 7284 atLeastOneCompFail = true; 7285 } 7286 7287 if (atLeastOneCompFail) 7288 return false; 7289 7290 TokIdx = I; // All of the tokens were handled, advance beyond all of them. 7291 return true; 7292 } 7293 7294 enum CXChildVisitResult AnnotateTokensWorker::Visit(CXCursor cursor, 7295 CXCursor parent) { 7296 SourceRange cursorRange = getRawCursorExtent(cursor); 7297 if (cursorRange.isInvalid()) 7298 return CXChildVisit_Recurse; 7299 7300 if (IsIgnoredChildCursor(cursor)) 7301 return CXChildVisit_Continue; 7302 7303 if (!HasContextSensitiveKeywords) { 7304 // Objective-C properties can have context-sensitive keywords. 7305 if (cursor.kind == CXCursor_ObjCPropertyDecl) { 7306 if (const ObjCPropertyDecl *Property = 7307 dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor))) 7308 HasContextSensitiveKeywords = 7309 Property->getPropertyAttributesAsWritten() != 0; 7310 } 7311 // Objective-C methods can have context-sensitive keywords. 7312 else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl || 7313 cursor.kind == CXCursor_ObjCClassMethodDecl) { 7314 if (const ObjCMethodDecl *Method = 7315 dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) { 7316 if (Method->getObjCDeclQualifier()) 7317 HasContextSensitiveKeywords = true; 7318 else { 7319 for (const auto *P : Method->parameters()) { 7320 if (P->getObjCDeclQualifier()) { 7321 HasContextSensitiveKeywords = true; 7322 break; 7323 } 7324 } 7325 } 7326 } 7327 } 7328 // C++ methods can have context-sensitive keywords. 7329 else if (cursor.kind == CXCursor_CXXMethod) { 7330 if (const CXXMethodDecl *Method = 7331 dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) { 7332 if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>()) 7333 HasContextSensitiveKeywords = true; 7334 } 7335 } 7336 // C++ classes can have context-sensitive keywords. 7337 else if (cursor.kind == CXCursor_StructDecl || 7338 cursor.kind == CXCursor_ClassDecl || 7339 cursor.kind == CXCursor_ClassTemplate || 7340 cursor.kind == CXCursor_ClassTemplatePartialSpecialization) { 7341 if (const Decl *D = getCursorDecl(cursor)) 7342 if (D->hasAttr<FinalAttr>()) 7343 HasContextSensitiveKeywords = true; 7344 } 7345 } 7346 7347 // Don't override a property annotation with its getter/setter method. 7348 if (cursor.kind == CXCursor_ObjCInstanceMethodDecl && 7349 parent.kind == CXCursor_ObjCPropertyDecl) 7350 return CXChildVisit_Continue; 7351 7352 if (clang_isPreprocessing(cursor.kind)) { 7353 // Items in the preprocessing record are kept separate from items in 7354 // declarations, so we keep a separate token index. 7355 unsigned SavedTokIdx = TokIdx; 7356 TokIdx = PreprocessingTokIdx; 7357 7358 // Skip tokens up until we catch up to the beginning of the preprocessing 7359 // entry. 7360 while (MoreTokens()) { 7361 const unsigned I = NextToken(); 7362 SourceLocation TokLoc = GetTokenLoc(I); 7363 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) { 7364 case RangeBefore: 7365 AdvanceToken(); 7366 continue; 7367 case RangeAfter: 7368 case RangeOverlap: 7369 break; 7370 } 7371 break; 7372 } 7373 7374 // Look at all of the tokens within this range. 7375 while (MoreTokens()) { 7376 const unsigned I = NextToken(); 7377 SourceLocation TokLoc = GetTokenLoc(I); 7378 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) { 7379 case RangeBefore: 7380 llvm_unreachable("Infeasible"); 7381 case RangeAfter: 7382 break; 7383 case RangeOverlap: 7384 // For macro expansions, just note where the beginning of the macro 7385 // expansion occurs. 7386 if (cursor.kind == CXCursor_MacroExpansion) { 7387 if (TokLoc == cursorRange.getBegin()) 7388 Cursors[I] = cursor; 7389 AdvanceToken(); 7390 break; 7391 } 7392 // We may have already annotated macro names inside macro definitions. 7393 if (Cursors[I].kind != CXCursor_MacroExpansion) 7394 Cursors[I] = cursor; 7395 AdvanceToken(); 7396 continue; 7397 } 7398 break; 7399 } 7400 7401 // Save the preprocessing token index; restore the non-preprocessing 7402 // token index. 7403 PreprocessingTokIdx = TokIdx; 7404 TokIdx = SavedTokIdx; 7405 return CXChildVisit_Recurse; 7406 } 7407 7408 if (cursorRange.isInvalid()) 7409 return CXChildVisit_Continue; 7410 7411 unsigned BeforeReachingCursorIdx = NextToken(); 7412 const enum CXCursorKind cursorK = clang_getCursorKind(cursor); 7413 const enum CXCursorKind K = clang_getCursorKind(parent); 7414 const CXCursor updateC = 7415 (clang_isInvalid(K) || K == CXCursor_TranslationUnit || 7416 // Attributes are annotated out-of-order, skip tokens until we reach it. 7417 clang_isAttribute(cursor.kind)) 7418 ? clang_getNullCursor() 7419 : parent; 7420 7421 annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange); 7422 7423 // Avoid having the cursor of an expression "overwrite" the annotation of the 7424 // variable declaration that it belongs to. 7425 // This can happen for C++ constructor expressions whose range generally 7426 // include the variable declaration, e.g.: 7427 // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor. 7428 if (clang_isExpression(cursorK) && MoreTokens()) { 7429 const Expr *E = getCursorExpr(cursor); 7430 if (const Decl *D = getCursorDecl(cursor)) { 7431 const unsigned I = NextToken(); 7432 if (E->getBeginLoc().isValid() && D->getLocation().isValid() && 7433 E->getBeginLoc() == D->getLocation() && 7434 E->getBeginLoc() == GetTokenLoc(I)) { 7435 updateCursorAnnotation(Cursors[I], updateC); 7436 AdvanceToken(); 7437 } 7438 } 7439 } 7440 7441 // Before recursing into the children keep some state that we are going 7442 // to use in the AnnotateTokensWorker::postVisitChildren callback to do some 7443 // extra work after the child nodes are visited. 7444 // Note that we don't call VisitChildren here to avoid traversing statements 7445 // code-recursively which can blow the stack. 7446 7447 PostChildrenInfo Info; 7448 Info.Cursor = cursor; 7449 Info.CursorRange = cursorRange; 7450 Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx; 7451 Info.BeforeChildrenTokenIdx = NextToken(); 7452 Info.ChildActions = DetermineChildActions(cursor); 7453 PostChildrenInfos.push_back(Info); 7454 7455 return CXChildVisit_Recurse; 7456 } 7457 7458 bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) { 7459 if (PostChildrenInfos.empty()) 7460 return false; 7461 const PostChildrenInfo &Info = PostChildrenInfos.back(); 7462 if (!clang_equalCursors(Info.Cursor, cursor)) 7463 return false; 7464 7465 HandlePostPonedChildCursors(Info); 7466 7467 const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx; 7468 const unsigned AfterChildren = NextToken(); 7469 SourceRange cursorRange = Info.CursorRange; 7470 7471 // Scan the tokens that are at the end of the cursor, but are not captured 7472 // but the child cursors. 7473 annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange); 7474 7475 // Scan the tokens that are at the beginning of the cursor, but are not 7476 // capture by the child cursors. 7477 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) { 7478 if (!clang_isInvalid(clang_getCursorKind(Cursors[I]))) 7479 break; 7480 7481 Cursors[I] = cursor; 7482 } 7483 7484 // Attributes are annotated out-of-order, rewind TokIdx to when we first 7485 // encountered the attribute cursor. 7486 if (clang_isAttribute(cursor.kind)) 7487 TokIdx = Info.BeforeReachingCursorIdx; 7488 7489 PostChildrenInfos.pop_back(); 7490 return false; 7491 } 7492 7493 void AnnotateTokensWorker::HandlePostPonedChildCursors( 7494 const PostChildrenInfo &Info) { 7495 for (const auto &ChildAction : Info.ChildActions) { 7496 if (ChildAction.action == PostChildrenAction::Postpone) { 7497 HandlePostPonedChildCursor(ChildAction.cursor, 7498 Info.BeforeChildrenTokenIdx); 7499 } 7500 } 7501 } 7502 7503 void AnnotateTokensWorker::HandlePostPonedChildCursor( 7504 CXCursor Cursor, unsigned StartTokenIndex) { 7505 unsigned I = StartTokenIndex; 7506 7507 // The bracket tokens of a Call or Subscript operator are mapped to 7508 // CallExpr/CXXOperatorCallExpr because we skipped visiting the corresponding 7509 // DeclRefExpr. Remap these tokens to the DeclRefExpr cursors. 7510 for (unsigned RefNameRangeNr = 0; I < NumTokens; RefNameRangeNr++) { 7511 const CXSourceRange CXRefNameRange = clang_getCursorReferenceNameRange( 7512 Cursor, CXNameRange_WantQualifier, RefNameRangeNr); 7513 if (clang_Range_isNull(CXRefNameRange)) 7514 break; // All ranges handled. 7515 7516 SourceRange RefNameRange = cxloc::translateCXSourceRange(CXRefNameRange); 7517 while (I < NumTokens) { 7518 const SourceLocation TokenLocation = GetTokenLoc(I); 7519 if (!TokenLocation.isValid()) 7520 break; 7521 7522 // Adapt the end range, because LocationCompare() reports 7523 // RangeOverlap even for the not-inclusive end location. 7524 const SourceLocation fixedEnd = 7525 RefNameRange.getEnd().getLocWithOffset(-1); 7526 RefNameRange = SourceRange(RefNameRange.getBegin(), fixedEnd); 7527 7528 const RangeComparisonResult ComparisonResult = 7529 LocationCompare(SrcMgr, TokenLocation, RefNameRange); 7530 7531 if (ComparisonResult == RangeOverlap) { 7532 Cursors[I++] = Cursor; 7533 } else if (ComparisonResult == RangeBefore) { 7534 ++I; // Not relevant token, check next one. 7535 } else if (ComparisonResult == RangeAfter) { 7536 break; // All tokens updated for current range, check next. 7537 } 7538 } 7539 } 7540 } 7541 7542 static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor, 7543 CXCursor parent, 7544 CXClientData client_data) { 7545 return static_cast<AnnotateTokensWorker *>(client_data) 7546 ->Visit(cursor, parent); 7547 } 7548 7549 static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor, 7550 CXClientData client_data) { 7551 return static_cast<AnnotateTokensWorker *>(client_data) 7552 ->postVisitChildren(cursor); 7553 } 7554 7555 namespace { 7556 7557 /// Uses the macro expansions in the preprocessing record to find 7558 /// and mark tokens that are macro arguments. This info is used by the 7559 /// AnnotateTokensWorker. 7560 class MarkMacroArgTokensVisitor { 7561 SourceManager &SM; 7562 CXToken *Tokens; 7563 unsigned NumTokens; 7564 unsigned CurIdx; 7565 7566 public: 7567 MarkMacroArgTokensVisitor(SourceManager &SM, CXToken *tokens, 7568 unsigned numTokens) 7569 : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) {} 7570 7571 CXChildVisitResult visit(CXCursor cursor, CXCursor parent) { 7572 if (cursor.kind != CXCursor_MacroExpansion) 7573 return CXChildVisit_Continue; 7574 7575 SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange(); 7576 if (macroRange.getBegin() == macroRange.getEnd()) 7577 return CXChildVisit_Continue; // it's not a function macro. 7578 7579 for (; CurIdx < NumTokens; ++CurIdx) { 7580 if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx), 7581 macroRange.getBegin())) 7582 break; 7583 } 7584 7585 if (CurIdx == NumTokens) 7586 return CXChildVisit_Break; 7587 7588 for (; CurIdx < NumTokens; ++CurIdx) { 7589 SourceLocation tokLoc = getTokenLoc(CurIdx); 7590 if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd())) 7591 break; 7592 7593 setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc)); 7594 } 7595 7596 if (CurIdx == NumTokens) 7597 return CXChildVisit_Break; 7598 7599 return CXChildVisit_Continue; 7600 } 7601 7602 private: 7603 CXToken &getTok(unsigned Idx) { 7604 assert(Idx < NumTokens); 7605 return Tokens[Idx]; 7606 } 7607 const CXToken &getTok(unsigned Idx) const { 7608 assert(Idx < NumTokens); 7609 return Tokens[Idx]; 7610 } 7611 7612 SourceLocation getTokenLoc(unsigned tokI) { 7613 return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]); 7614 } 7615 7616 void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) { 7617 // The third field is reserved and currently not used. Use it here 7618 // to mark macro arg expanded tokens with their expanded locations. 7619 getTok(tokI).int_data[3] = loc.getRawEncoding(); 7620 } 7621 }; 7622 7623 } // end anonymous namespace 7624 7625 static CXChildVisitResult 7626 MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent, 7627 CXClientData client_data) { 7628 return static_cast<MarkMacroArgTokensVisitor *>(client_data) 7629 ->visit(cursor, parent); 7630 } 7631 7632 /// Used by \c annotatePreprocessorTokens. 7633 /// \returns true if lexing was finished, false otherwise. 7634 static bool lexNext(Lexer &Lex, Token &Tok, unsigned &NextIdx, 7635 unsigned NumTokens) { 7636 if (NextIdx >= NumTokens) 7637 return true; 7638 7639 ++NextIdx; 7640 Lex.LexFromRawLexer(Tok); 7641 return Tok.is(tok::eof); 7642 } 7643 7644 static void annotatePreprocessorTokens(CXTranslationUnit TU, 7645 SourceRange RegionOfInterest, 7646 CXCursor *Cursors, CXToken *Tokens, 7647 unsigned NumTokens) { 7648 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 7649 7650 Preprocessor &PP = CXXUnit->getPreprocessor(); 7651 SourceManager &SourceMgr = CXXUnit->getSourceManager(); 7652 std::pair<FileID, unsigned> BeginLocInfo = 7653 SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin()); 7654 std::pair<FileID, unsigned> EndLocInfo = 7655 SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd()); 7656 7657 if (BeginLocInfo.first != EndLocInfo.first) 7658 return; 7659 7660 StringRef Buffer; 7661 bool Invalid = false; 7662 Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid); 7663 if (Buffer.empty() || Invalid) 7664 return; 7665 7666 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first), 7667 CXXUnit->getASTContext().getLangOpts(), Buffer.begin(), 7668 Buffer.data() + BeginLocInfo.second, Buffer.end()); 7669 Lex.SetCommentRetentionState(true); 7670 7671 unsigned NextIdx = 0; 7672 // Lex tokens in raw mode until we hit the end of the range, to avoid 7673 // entering #includes or expanding macros. 7674 while (true) { 7675 Token Tok; 7676 if (lexNext(Lex, Tok, NextIdx, NumTokens)) 7677 break; 7678 unsigned TokIdx = NextIdx - 1; 7679 assert(Tok.getLocation() == 7680 SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1])); 7681 7682 reprocess: 7683 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) { 7684 // We have found a preprocessing directive. Annotate the tokens 7685 // appropriately. 7686 // 7687 // FIXME: Some simple tests here could identify macro definitions and 7688 // #undefs, to provide specific cursor kinds for those. 7689 7690 SourceLocation BeginLoc = Tok.getLocation(); 7691 if (lexNext(Lex, Tok, NextIdx, NumTokens)) 7692 break; 7693 7694 MacroInfo *MI = nullptr; 7695 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") { 7696 if (lexNext(Lex, Tok, NextIdx, NumTokens)) 7697 break; 7698 7699 if (Tok.is(tok::raw_identifier)) { 7700 IdentifierInfo &II = 7701 PP.getIdentifierTable().get(Tok.getRawIdentifier()); 7702 SourceLocation MappedTokLoc = 7703 CXXUnit->mapLocationToPreamble(Tok.getLocation()); 7704 MI = getMacroInfo(II, MappedTokLoc, TU); 7705 } 7706 } 7707 7708 bool finished = false; 7709 do { 7710 if (lexNext(Lex, Tok, NextIdx, NumTokens)) { 7711 finished = true; 7712 break; 7713 } 7714 // If we are in a macro definition, check if the token was ever a 7715 // macro name and annotate it if that's the case. 7716 if (MI) { 7717 SourceLocation SaveLoc = Tok.getLocation(); 7718 Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc)); 7719 MacroDefinitionRecord *MacroDef = 7720 checkForMacroInMacroDefinition(MI, Tok, TU); 7721 Tok.setLocation(SaveLoc); 7722 if (MacroDef) 7723 Cursors[NextIdx - 1] = 7724 MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU); 7725 } 7726 } while (!Tok.isAtStartOfLine()); 7727 7728 unsigned LastIdx = finished ? NextIdx - 1 : NextIdx - 2; 7729 assert(TokIdx <= LastIdx); 7730 SourceLocation EndLoc = 7731 SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]); 7732 CXCursor Cursor = 7733 MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU); 7734 7735 for (; TokIdx <= LastIdx; ++TokIdx) 7736 updateCursorAnnotation(Cursors[TokIdx], Cursor); 7737 7738 if (finished) 7739 break; 7740 goto reprocess; 7741 } 7742 } 7743 } 7744 7745 // This gets run a separate thread to avoid stack blowout. 7746 static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit, 7747 CXToken *Tokens, unsigned NumTokens, 7748 CXCursor *Cursors) { 7749 CIndexer *CXXIdx = TU->CIdx; 7750 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing)) 7751 setThreadBackgroundPriority(); 7752 7753 // Determine the region of interest, which contains all of the tokens. 7754 SourceRange RegionOfInterest; 7755 RegionOfInterest.setBegin( 7756 cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0]))); 7757 RegionOfInterest.setEnd(cxloc::translateSourceLocation( 7758 clang_getTokenLocation(TU, Tokens[NumTokens - 1]))); 7759 7760 // Relex the tokens within the source range to look for preprocessing 7761 // directives. 7762 annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens); 7763 7764 // If begin location points inside a macro argument, set it to the expansion 7765 // location so we can have the full context when annotating semantically. 7766 { 7767 SourceManager &SM = CXXUnit->getSourceManager(); 7768 SourceLocation Loc = 7769 SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin()); 7770 if (Loc.isMacroID()) 7771 RegionOfInterest.setBegin(SM.getExpansionLoc(Loc)); 7772 } 7773 7774 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) { 7775 // Search and mark tokens that are macro argument expansions. 7776 MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(), Tokens, 7777 NumTokens); 7778 CursorVisitor MacroArgMarker( 7779 TU, MarkMacroArgTokensVisitorDelegate, &Visitor, 7780 /*VisitPreprocessorLast=*/true, 7781 /*VisitIncludedEntities=*/false, RegionOfInterest); 7782 MacroArgMarker.visitPreprocessedEntitiesInRegion(); 7783 } 7784 7785 // Annotate all of the source locations in the region of interest that map to 7786 // a specific cursor. 7787 AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest); 7788 7789 // FIXME: We use a ridiculous stack size here because the data-recursion 7790 // algorithm uses a large stack frame than the non-data recursive version, 7791 // and AnnotationTokensWorker currently transforms the data-recursion 7792 // algorithm back into a traditional recursion by explicitly calling 7793 // VisitChildren(). We will need to remove this explicit recursive call. 7794 W.AnnotateTokens(); 7795 7796 // If we ran into any entities that involve context-sensitive keywords, 7797 // take another pass through the tokens to mark them as such. 7798 if (W.hasContextSensitiveKeywords()) { 7799 for (unsigned I = 0; I != NumTokens; ++I) { 7800 if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier) 7801 continue; 7802 7803 if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) { 7804 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data); 7805 if (const ObjCPropertyDecl *Property = 7806 dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) { 7807 if (Property->getPropertyAttributesAsWritten() != 0 && 7808 llvm::StringSwitch<bool>(II->getName()) 7809 .Case("readonly", true) 7810 .Case("assign", true) 7811 .Case("unsafe_unretained", true) 7812 .Case("readwrite", true) 7813 .Case("retain", true) 7814 .Case("copy", true) 7815 .Case("nonatomic", true) 7816 .Case("atomic", true) 7817 .Case("getter", true) 7818 .Case("setter", true) 7819 .Case("strong", true) 7820 .Case("weak", true) 7821 .Case("class", true) 7822 .Default(false)) 7823 Tokens[I].int_data[0] = CXToken_Keyword; 7824 } 7825 continue; 7826 } 7827 7828 if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl || 7829 Cursors[I].kind == CXCursor_ObjCClassMethodDecl) { 7830 IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data); 7831 if (llvm::StringSwitch<bool>(II->getName()) 7832 .Case("in", true) 7833 .Case("out", true) 7834 .Case("inout", true) 7835 .Case("oneway", true) 7836 .Case("bycopy", true) 7837 .Case("byref", true) 7838 .Default(false)) 7839 Tokens[I].int_data[0] = CXToken_Keyword; 7840 continue; 7841 } 7842 7843 if (Cursors[I].kind == CXCursor_CXXFinalAttr || 7844 Cursors[I].kind == CXCursor_CXXOverrideAttr) { 7845 Tokens[I].int_data[0] = CXToken_Keyword; 7846 continue; 7847 } 7848 } 7849 } 7850 } 7851 7852 void clang_annotateTokens(CXTranslationUnit TU, CXToken *Tokens, 7853 unsigned NumTokens, CXCursor *Cursors) { 7854 if (isNotUsableTU(TU)) { 7855 LOG_BAD_TU(TU); 7856 return; 7857 } 7858 if (NumTokens == 0 || !Tokens || !Cursors) { 7859 LOG_FUNC_SECTION { *Log << "<null input>"; } 7860 return; 7861 } 7862 7863 LOG_FUNC_SECTION { 7864 *Log << TU << ' '; 7865 CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]); 7866 CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens - 1]); 7867 *Log << clang_getRange(bloc, eloc); 7868 } 7869 7870 // Any token we don't specifically annotate will have a NULL cursor. 7871 CXCursor C = clang_getNullCursor(); 7872 for (unsigned I = 0; I != NumTokens; ++I) 7873 Cursors[I] = C; 7874 7875 ASTUnit *CXXUnit = cxtu::getASTUnit(TU); 7876 if (!CXXUnit) 7877 return; 7878 7879 ASTUnit::ConcurrencyCheck Check(*CXXUnit); 7880 7881 auto AnnotateTokensImpl = [=]() { 7882 clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors); 7883 }; 7884 llvm::CrashRecoveryContext CRC; 7885 if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) { 7886 fprintf(stderr, "libclang: crash detected while annotating tokens\n"); 7887 } 7888 } 7889 7890 //===----------------------------------------------------------------------===// 7891 // Operations for querying linkage of a cursor. 7892 //===----------------------------------------------------------------------===// 7893 7894 CXLinkageKind clang_getCursorLinkage(CXCursor cursor) { 7895 if (!clang_isDeclaration(cursor.kind)) 7896 return CXLinkage_Invalid; 7897 7898 const Decl *D = cxcursor::getCursorDecl(cursor); 7899 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D)) 7900 switch (ND->getLinkageInternal()) { 7901 case NoLinkage: 7902 case VisibleNoLinkage: 7903 return CXLinkage_NoLinkage; 7904 case ModuleInternalLinkage: 7905 case InternalLinkage: 7906 return CXLinkage_Internal; 7907 case UniqueExternalLinkage: 7908 return CXLinkage_UniqueExternal; 7909 case ModuleLinkage: 7910 case ExternalLinkage: 7911 return CXLinkage_External; 7912 }; 7913 7914 return CXLinkage_Invalid; 7915 } 7916 7917 //===----------------------------------------------------------------------===// 7918 // Operations for querying visibility of a cursor. 7919 //===----------------------------------------------------------------------===// 7920 7921 CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) { 7922 if (!clang_isDeclaration(cursor.kind)) 7923 return CXVisibility_Invalid; 7924 7925 const Decl *D = cxcursor::getCursorDecl(cursor); 7926 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D)) 7927 switch (ND->getVisibility()) { 7928 case HiddenVisibility: 7929 return CXVisibility_Hidden; 7930 case ProtectedVisibility: 7931 return CXVisibility_Protected; 7932 case DefaultVisibility: 7933 return CXVisibility_Default; 7934 }; 7935 7936 return CXVisibility_Invalid; 7937 } 7938 7939 //===----------------------------------------------------------------------===// 7940 // Operations for querying language of a cursor. 7941 //===----------------------------------------------------------------------===// 7942 7943 static CXLanguageKind getDeclLanguage(const Decl *D) { 7944 if (!D) 7945 return CXLanguage_C; 7946 7947 switch (D->getKind()) { 7948 default: 7949 break; 7950 case Decl::ImplicitParam: 7951 case Decl::ObjCAtDefsField: 7952 case Decl::ObjCCategory: 7953 case Decl::ObjCCategoryImpl: 7954 case Decl::ObjCCompatibleAlias: 7955 case Decl::ObjCImplementation: 7956 case Decl::ObjCInterface: 7957 case Decl::ObjCIvar: 7958 case Decl::ObjCMethod: 7959 case Decl::ObjCProperty: 7960 case Decl::ObjCPropertyImpl: 7961 case Decl::ObjCProtocol: 7962 case Decl::ObjCTypeParam: 7963 return CXLanguage_ObjC; 7964 case Decl::CXXConstructor: 7965 case Decl::CXXConversion: 7966 case Decl::CXXDestructor: 7967 case Decl::CXXMethod: 7968 case Decl::CXXRecord: 7969 case Decl::ClassTemplate: 7970 case Decl::ClassTemplatePartialSpecialization: 7971 case Decl::ClassTemplateSpecialization: 7972 case Decl::Friend: 7973 case Decl::FriendTemplate: 7974 case Decl::FunctionTemplate: 7975 case Decl::LinkageSpec: 7976 case Decl::Namespace: 7977 case Decl::NamespaceAlias: 7978 case Decl::NonTypeTemplateParm: 7979 case Decl::StaticAssert: 7980 case Decl::TemplateTemplateParm: 7981 case Decl::TemplateTypeParm: 7982 case Decl::UnresolvedUsingTypename: 7983 case Decl::UnresolvedUsingValue: 7984 case Decl::Using: 7985 case Decl::UsingDirective: 7986 case Decl::UsingShadow: 7987 return CXLanguage_CPlusPlus; 7988 } 7989 7990 return CXLanguage_C; 7991 } 7992 7993 static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) { 7994 if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()) 7995 return CXAvailability_NotAvailable; 7996 7997 switch (D->getAvailability()) { 7998 case AR_Available: 7999 case AR_NotYetIntroduced: 8000 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D)) 8001 return getCursorAvailabilityForDecl( 8002 cast<Decl>(EnumConst->getDeclContext())); 8003 return CXAvailability_Available; 8004 8005 case AR_Deprecated: 8006 return CXAvailability_Deprecated; 8007 8008 case AR_Unavailable: 8009 return CXAvailability_NotAvailable; 8010 } 8011 8012 llvm_unreachable("Unknown availability kind!"); 8013 } 8014 8015 enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) { 8016 if (clang_isDeclaration(cursor.kind)) 8017 if (const Decl *D = cxcursor::getCursorDecl(cursor)) 8018 return getCursorAvailabilityForDecl(D); 8019 8020 return CXAvailability_Available; 8021 } 8022 8023 static CXVersion convertVersion(VersionTuple In) { 8024 CXVersion Out = {-1, -1, -1}; 8025 if (In.empty()) 8026 return Out; 8027 8028 Out.Major = In.getMajor(); 8029 8030 Optional<unsigned> Minor = In.getMinor(); 8031 if (Minor.hasValue()) 8032 Out.Minor = *Minor; 8033 else 8034 return Out; 8035 8036 Optional<unsigned> Subminor = In.getSubminor(); 8037 if (Subminor.hasValue()) 8038 Out.Subminor = *Subminor; 8039 8040 return Out; 8041 } 8042 8043 static void getCursorPlatformAvailabilityForDecl( 8044 const Decl *D, int *always_deprecated, CXString *deprecated_message, 8045 int *always_unavailable, CXString *unavailable_message, 8046 SmallVectorImpl<AvailabilityAttr *> &AvailabilityAttrs) { 8047 bool HadAvailAttr = false; 8048 for (auto A : D->attrs()) { 8049 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) { 8050 HadAvailAttr = true; 8051 if (always_deprecated) 8052 *always_deprecated = 1; 8053 if (deprecated_message) { 8054 clang_disposeString(*deprecated_message); 8055 *deprecated_message = cxstring::createDup(Deprecated->getMessage()); 8056 } 8057 continue; 8058 } 8059 8060 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) { 8061 HadAvailAttr = true; 8062 if (always_unavailable) 8063 *always_unavailable = 1; 8064 if (unavailable_message) { 8065 clang_disposeString(*unavailable_message); 8066 *unavailable_message = cxstring::createDup(Unavailable->getMessage()); 8067 } 8068 continue; 8069 } 8070 8071 if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) { 8072 AvailabilityAttrs.push_back(Avail); 8073 HadAvailAttr = true; 8074 } 8075 } 8076 8077 if (!HadAvailAttr) 8078 if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D)) 8079 return getCursorPlatformAvailabilityForDecl( 8080 cast<Decl>(EnumConst->getDeclContext()), always_deprecated, 8081 deprecated_message, always_unavailable, unavailable_message, 8082 AvailabilityAttrs); 8083 8084 if (AvailabilityAttrs.empty()) 8085 return; 8086 8087 llvm::sort( 8088 AvailabilityAttrs, [](AvailabilityAttr *LHS, AvailabilityAttr *RHS) { 8089 return LHS->getPlatform()->getName() < RHS->getPlatform()->getName(); 8090 }); 8091 ASTContext &Ctx = D->getASTContext(); 8092 auto It = std::unique( 8093 AvailabilityAttrs.begin(), AvailabilityAttrs.end(), 8094 [&Ctx](AvailabilityAttr *LHS, AvailabilityAttr *RHS) { 8095 if (LHS->getPlatform() != RHS->getPlatform()) 8096 return false; 8097 8098 if (LHS->getIntroduced() == RHS->getIntroduced() && 8099 LHS->getDeprecated() == RHS->getDeprecated() && 8100 LHS->getObsoleted() == RHS->getObsoleted() && 8101 LHS->getMessage() == RHS->getMessage() && 8102 LHS->getReplacement() == RHS->getReplacement()) 8103 return true; 8104 8105 if ((!LHS->getIntroduced().empty() && !RHS->getIntroduced().empty()) || 8106 (!LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) || 8107 (!LHS->getObsoleted().empty() && !RHS->getObsoleted().empty())) 8108 return false; 8109 8110 if (LHS->getIntroduced().empty() && !RHS->getIntroduced().empty()) 8111 LHS->setIntroduced(Ctx, RHS->getIntroduced()); 8112 8113 if (LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) { 8114 LHS->setDeprecated(Ctx, RHS->getDeprecated()); 8115 if (LHS->getMessage().empty()) 8116 LHS->setMessage(Ctx, RHS->getMessage()); 8117 if (LHS->getReplacement().empty()) 8118 LHS->setReplacement(Ctx, RHS->getReplacement()); 8119 } 8120 8121 if (LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()) { 8122 LHS->setObsoleted(Ctx, RHS->getObsoleted()); 8123 if (LHS->getMessage().empty()) 8124 LHS->setMessage(Ctx, RHS->getMessage()); 8125 if (LHS->getReplacement().empty()) 8126 LHS->setReplacement(Ctx, RHS->getReplacement()); 8127 } 8128 8129 return true; 8130 }); 8131 AvailabilityAttrs.erase(It, AvailabilityAttrs.end()); 8132 } 8133 8134 int clang_getCursorPlatformAvailability(CXCursor cursor, int *always_deprecated, 8135 CXString *deprecated_message, 8136 int *always_unavailable, 8137 CXString *unavailable_message, 8138 CXPlatformAvailability *availability, 8139 int availability_size) { 8140 if (always_deprecated) 8141 *always_deprecated = 0; 8142 if (deprecated_message) 8143 *deprecated_message = cxstring::createEmpty(); 8144 if (always_unavailable) 8145 *always_unavailable = 0; 8146 if (unavailable_message) 8147 *unavailable_message = cxstring::createEmpty(); 8148 8149 if (!clang_isDeclaration(cursor.kind)) 8150 return 0; 8151 8152 const Decl *D = cxcursor::getCursorDecl(cursor); 8153 if (!D) 8154 return 0; 8155 8156 SmallVector<AvailabilityAttr *, 8> AvailabilityAttrs; 8157 getCursorPlatformAvailabilityForDecl(D, always_deprecated, deprecated_message, 8158 always_unavailable, unavailable_message, 8159 AvailabilityAttrs); 8160 for (const auto &Avail : 8161 llvm::enumerate(llvm::makeArrayRef(AvailabilityAttrs) 8162 .take_front(availability_size))) { 8163 availability[Avail.index()].Platform = 8164 cxstring::createDup(Avail.value()->getPlatform()->getName()); 8165 availability[Avail.index()].Introduced = 8166 convertVersion(Avail.value()->getIntroduced()); 8167 availability[Avail.index()].Deprecated = 8168 convertVersion(Avail.value()->getDeprecated()); 8169 availability[Avail.index()].Obsoleted = 8170 convertVersion(Avail.value()->getObsoleted()); 8171 availability[Avail.index()].Unavailable = Avail.value()->getUnavailable(); 8172 availability[Avail.index()].Message = 8173 cxstring::createDup(Avail.value()->getMessage()); 8174 } 8175 8176 return AvailabilityAttrs.size(); 8177 } 8178 8179 void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) { 8180 clang_disposeString(availability->Platform); 8181 clang_disposeString(availability->Message); 8182 } 8183 8184 CXLanguageKind clang_getCursorLanguage(CXCursor cursor) { 8185 if (clang_isDeclaration(cursor.kind)) 8186 return getDeclLanguage(cxcursor::getCursorDecl(cursor)); 8187 8188 return CXLanguage_Invalid; 8189 } 8190 8191 CXTLSKind clang_getCursorTLSKind(CXCursor cursor) { 8192 const Decl *D = cxcursor::getCursorDecl(cursor); 8193 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 8194 switch (VD->getTLSKind()) { 8195 case VarDecl::TLS_None: 8196 return CXTLS_None; 8197 case VarDecl::TLS_Dynamic: 8198 return CXTLS_Dynamic; 8199 case VarDecl::TLS_Static: 8200 return CXTLS_Static; 8201 } 8202 } 8203 8204 return CXTLS_None; 8205 } 8206 8207 /// If the given cursor is the "templated" declaration 8208 /// describing a class or function template, return the class or 8209 /// function template. 8210 static const Decl *maybeGetTemplateCursor(const Decl *D) { 8211 if (!D) 8212 return nullptr; 8213 8214 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 8215 if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate()) 8216 return FunTmpl; 8217 8218 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) 8219 if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate()) 8220 return ClassTmpl; 8221 8222 return D; 8223 } 8224 8225 enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) { 8226 StorageClass sc = SC_None; 8227 const Decl *D = getCursorDecl(C); 8228 if (D) { 8229 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 8230 sc = FD->getStorageClass(); 8231 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 8232 sc = VD->getStorageClass(); 8233 } else { 8234 return CX_SC_Invalid; 8235 } 8236 } else { 8237 return CX_SC_Invalid; 8238 } 8239 switch (sc) { 8240 case SC_None: 8241 return CX_SC_None; 8242 case SC_Extern: 8243 return CX_SC_Extern; 8244 case SC_Static: 8245 return CX_SC_Static; 8246 case SC_PrivateExtern: 8247 return CX_SC_PrivateExtern; 8248 case SC_Auto: 8249 return CX_SC_Auto; 8250 case SC_Register: 8251 return CX_SC_Register; 8252 } 8253 llvm_unreachable("Unhandled storage class!"); 8254 } 8255 8256 CXCursor clang_getCursorSemanticParent(CXCursor cursor) { 8257 if (clang_isDeclaration(cursor.kind)) { 8258 if (const Decl *D = getCursorDecl(cursor)) { 8259 const DeclContext *DC = D->getDeclContext(); 8260 if (!DC) 8261 return clang_getNullCursor(); 8262 8263 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)), 8264 getCursorTU(cursor)); 8265 } 8266 } 8267 8268 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) { 8269 if (const Decl *D = getCursorDecl(cursor)) 8270 return MakeCXCursor(D, getCursorTU(cursor)); 8271 } 8272 8273 return clang_getNullCursor(); 8274 } 8275 8276 CXCursor clang_getCursorLexicalParent(CXCursor cursor) { 8277 if (clang_isDeclaration(cursor.kind)) { 8278 if (const Decl *D = getCursorDecl(cursor)) { 8279 const DeclContext *DC = D->getLexicalDeclContext(); 8280 if (!DC) 8281 return clang_getNullCursor(); 8282 8283 return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)), 8284 getCursorTU(cursor)); 8285 } 8286 } 8287 8288 // FIXME: Note that we can't easily compute the lexical context of a 8289 // statement or expression, so we return nothing. 8290 return clang_getNullCursor(); 8291 } 8292 8293 CXFile clang_getIncludedFile(CXCursor cursor) { 8294 if (cursor.kind != CXCursor_InclusionDirective) 8295 return nullptr; 8296 8297 const InclusionDirective *ID = getCursorInclusionDirective(cursor); 8298 Optional<FileEntryRef> File = ID->getFile(); 8299 return const_cast<FileEntry *>(File ? &File->getFileEntry() : nullptr); 8300 } 8301 8302 unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) { 8303 if (C.kind != CXCursor_ObjCPropertyDecl) 8304 return CXObjCPropertyAttr_noattr; 8305 8306 unsigned Result = CXObjCPropertyAttr_noattr; 8307 const auto *PD = cast<ObjCPropertyDecl>(getCursorDecl(C)); 8308 ObjCPropertyAttribute::Kind Attr = PD->getPropertyAttributesAsWritten(); 8309 8310 #define SET_CXOBJCPROP_ATTR(A) \ 8311 if (Attr & ObjCPropertyAttribute::kind_##A) \ 8312 Result |= CXObjCPropertyAttr_##A 8313 SET_CXOBJCPROP_ATTR(readonly); 8314 SET_CXOBJCPROP_ATTR(getter); 8315 SET_CXOBJCPROP_ATTR(assign); 8316 SET_CXOBJCPROP_ATTR(readwrite); 8317 SET_CXOBJCPROP_ATTR(retain); 8318 SET_CXOBJCPROP_ATTR(copy); 8319 SET_CXOBJCPROP_ATTR(nonatomic); 8320 SET_CXOBJCPROP_ATTR(setter); 8321 SET_CXOBJCPROP_ATTR(atomic); 8322 SET_CXOBJCPROP_ATTR(weak); 8323 SET_CXOBJCPROP_ATTR(strong); 8324 SET_CXOBJCPROP_ATTR(unsafe_unretained); 8325 SET_CXOBJCPROP_ATTR(class); 8326 #undef SET_CXOBJCPROP_ATTR 8327 8328 return Result; 8329 } 8330 8331 CXString clang_Cursor_getObjCPropertyGetterName(CXCursor C) { 8332 if (C.kind != CXCursor_ObjCPropertyDecl) 8333 return cxstring::createNull(); 8334 8335 const auto *PD = cast<ObjCPropertyDecl>(getCursorDecl(C)); 8336 Selector sel = PD->getGetterName(); 8337 if (sel.isNull()) 8338 return cxstring::createNull(); 8339 8340 return cxstring::createDup(sel.getAsString()); 8341 } 8342 8343 CXString clang_Cursor_getObjCPropertySetterName(CXCursor C) { 8344 if (C.kind != CXCursor_ObjCPropertyDecl) 8345 return cxstring::createNull(); 8346 8347 const auto *PD = cast<ObjCPropertyDecl>(getCursorDecl(C)); 8348 Selector sel = PD->getSetterName(); 8349 if (sel.isNull()) 8350 return cxstring::createNull(); 8351 8352 return cxstring::createDup(sel.getAsString()); 8353 } 8354 8355 unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) { 8356 if (!clang_isDeclaration(C.kind)) 8357 return CXObjCDeclQualifier_None; 8358 8359 Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None; 8360 const Decl *D = getCursorDecl(C); 8361 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) 8362 QT = MD->getObjCDeclQualifier(); 8363 else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D)) 8364 QT = PD->getObjCDeclQualifier(); 8365 if (QT == Decl::OBJC_TQ_None) 8366 return CXObjCDeclQualifier_None; 8367 8368 unsigned Result = CXObjCDeclQualifier_None; 8369 if (QT & Decl::OBJC_TQ_In) 8370 Result |= CXObjCDeclQualifier_In; 8371 if (QT & Decl::OBJC_TQ_Inout) 8372 Result |= CXObjCDeclQualifier_Inout; 8373 if (QT & Decl::OBJC_TQ_Out) 8374 Result |= CXObjCDeclQualifier_Out; 8375 if (QT & Decl::OBJC_TQ_Bycopy) 8376 Result |= CXObjCDeclQualifier_Bycopy; 8377 if (QT & Decl::OBJC_TQ_Byref) 8378 Result |= CXObjCDeclQualifier_Byref; 8379 if (QT & Decl::OBJC_TQ_Oneway) 8380 Result |= CXObjCDeclQualifier_Oneway; 8381 8382 return Result; 8383 } 8384 8385 unsigned clang_Cursor_isObjCOptional(CXCursor C) { 8386 if (!clang_isDeclaration(C.kind)) 8387 return 0; 8388 8389 const Decl *D = getCursorDecl(C); 8390 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) 8391 return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional; 8392 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) 8393 return MD->getImplementationControl() == ObjCMethodDecl::Optional; 8394 8395 return 0; 8396 } 8397 8398 unsigned clang_Cursor_isVariadic(CXCursor C) { 8399 if (!clang_isDeclaration(C.kind)) 8400 return 0; 8401 8402 const Decl *D = getCursorDecl(C); 8403 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 8404 return FD->isVariadic(); 8405 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) 8406 return MD->isVariadic(); 8407 8408 return 0; 8409 } 8410 8411 unsigned clang_Cursor_isExternalSymbol(CXCursor C, CXString *language, 8412 CXString *definedIn, 8413 unsigned *isGenerated) { 8414 if (!clang_isDeclaration(C.kind)) 8415 return 0; 8416 8417 const Decl *D = getCursorDecl(C); 8418 8419 if (auto *attr = D->getExternalSourceSymbolAttr()) { 8420 if (language) 8421 *language = cxstring::createDup(attr->getLanguage()); 8422 if (definedIn) 8423 *definedIn = cxstring::createDup(attr->getDefinedIn()); 8424 if (isGenerated) 8425 *isGenerated = attr->getGeneratedDeclaration(); 8426 return 1; 8427 } 8428 return 0; 8429 } 8430 8431 CXSourceRange clang_Cursor_getCommentRange(CXCursor C) { 8432 if (!clang_isDeclaration(C.kind)) 8433 return clang_getNullRange(); 8434 8435 const Decl *D = getCursorDecl(C); 8436 ASTContext &Context = getCursorContext(C); 8437 const RawComment *RC = Context.getRawCommentForAnyRedecl(D); 8438 if (!RC) 8439 return clang_getNullRange(); 8440 8441 return cxloc::translateSourceRange(Context, RC->getSourceRange()); 8442 } 8443 8444 CXString clang_Cursor_getRawCommentText(CXCursor C) { 8445 if (!clang_isDeclaration(C.kind)) 8446 return cxstring::createNull(); 8447 8448 const Decl *D = getCursorDecl(C); 8449 ASTContext &Context = getCursorContext(C); 8450 const RawComment *RC = Context.getRawCommentForAnyRedecl(D); 8451 StringRef RawText = 8452 RC ? RC->getRawText(Context.getSourceManager()) : StringRef(); 8453 8454 // Don't duplicate the string because RawText points directly into source 8455 // code. 8456 return cxstring::createRef(RawText); 8457 } 8458 8459 CXString clang_Cursor_getBriefCommentText(CXCursor C) { 8460 if (!clang_isDeclaration(C.kind)) 8461 return cxstring::createNull(); 8462 8463 const Decl *D = getCursorDecl(C); 8464 const ASTContext &Context = getCursorContext(C); 8465 const RawComment *RC = Context.getRawCommentForAnyRedecl(D); 8466 8467 if (RC) { 8468 StringRef BriefText = RC->getBriefText(Context); 8469 8470 // Don't duplicate the string because RawComment ensures that this memory 8471 // will not go away. 8472 return cxstring::createRef(BriefText); 8473 } 8474 8475 return cxstring::createNull(); 8476 } 8477 8478 CXModule clang_Cursor_getModule(CXCursor C) { 8479 if (C.kind == CXCursor_ModuleImportDecl) { 8480 if (const ImportDecl *ImportD = 8481 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) 8482 return ImportD->getImportedModule(); 8483 } 8484 8485 return nullptr; 8486 } 8487 8488 CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) { 8489 if (isNotUsableTU(TU)) { 8490 LOG_BAD_TU(TU); 8491 return nullptr; 8492 } 8493 if (!File) 8494 return nullptr; 8495 FileEntry *FE = static_cast<FileEntry *>(File); 8496 8497 ASTUnit &Unit = *cxtu::getASTUnit(TU); 8498 HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo(); 8499 ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE); 8500 8501 return Header.getModule(); 8502 } 8503 8504 CXFile clang_Module_getASTFile(CXModule CXMod) { 8505 if (!CXMod) 8506 return nullptr; 8507 Module *Mod = static_cast<Module *>(CXMod); 8508 if (auto File = Mod->getASTFile()) 8509 return const_cast<FileEntry *>(&File->getFileEntry()); 8510 return nullptr; 8511 } 8512 8513 CXModule clang_Module_getParent(CXModule CXMod) { 8514 if (!CXMod) 8515 return nullptr; 8516 Module *Mod = static_cast<Module *>(CXMod); 8517 return Mod->Parent; 8518 } 8519 8520 CXString clang_Module_getName(CXModule CXMod) { 8521 if (!CXMod) 8522 return cxstring::createEmpty(); 8523 Module *Mod = static_cast<Module *>(CXMod); 8524 return cxstring::createDup(Mod->Name); 8525 } 8526 8527 CXString clang_Module_getFullName(CXModule CXMod) { 8528 if (!CXMod) 8529 return cxstring::createEmpty(); 8530 Module *Mod = static_cast<Module *>(CXMod); 8531 return cxstring::createDup(Mod->getFullModuleName()); 8532 } 8533 8534 int clang_Module_isSystem(CXModule CXMod) { 8535 if (!CXMod) 8536 return 0; 8537 Module *Mod = static_cast<Module *>(CXMod); 8538 return Mod->IsSystem; 8539 } 8540 8541 unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU, 8542 CXModule CXMod) { 8543 if (isNotUsableTU(TU)) { 8544 LOG_BAD_TU(TU); 8545 return 0; 8546 } 8547 if (!CXMod) 8548 return 0; 8549 Module *Mod = static_cast<Module *>(CXMod); 8550 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager(); 8551 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr); 8552 return TopHeaders.size(); 8553 } 8554 8555 CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU, CXModule CXMod, 8556 unsigned Index) { 8557 if (isNotUsableTU(TU)) { 8558 LOG_BAD_TU(TU); 8559 return nullptr; 8560 } 8561 if (!CXMod) 8562 return nullptr; 8563 Module *Mod = static_cast<Module *>(CXMod); 8564 FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager(); 8565 8566 ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr); 8567 if (Index < TopHeaders.size()) 8568 return const_cast<FileEntry *>(TopHeaders[Index]); 8569 8570 return nullptr; 8571 } 8572 8573 //===----------------------------------------------------------------------===// 8574 // C++ AST instrospection. 8575 //===----------------------------------------------------------------------===// 8576 8577 unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) { 8578 if (!clang_isDeclaration(C.kind)) 8579 return 0; 8580 8581 const Decl *D = cxcursor::getCursorDecl(C); 8582 const CXXConstructorDecl *Constructor = 8583 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr; 8584 return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0; 8585 } 8586 8587 unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) { 8588 if (!clang_isDeclaration(C.kind)) 8589 return 0; 8590 8591 const Decl *D = cxcursor::getCursorDecl(C); 8592 const CXXConstructorDecl *Constructor = 8593 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr; 8594 return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0; 8595 } 8596 8597 unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) { 8598 if (!clang_isDeclaration(C.kind)) 8599 return 0; 8600 8601 const Decl *D = cxcursor::getCursorDecl(C); 8602 const CXXConstructorDecl *Constructor = 8603 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr; 8604 return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0; 8605 } 8606 8607 unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) { 8608 if (!clang_isDeclaration(C.kind)) 8609 return 0; 8610 8611 const Decl *D = cxcursor::getCursorDecl(C); 8612 const CXXConstructorDecl *Constructor = 8613 D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr; 8614 // Passing 'false' excludes constructors marked 'explicit'. 8615 return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0; 8616 } 8617 8618 unsigned clang_CXXField_isMutable(CXCursor C) { 8619 if (!clang_isDeclaration(C.kind)) 8620 return 0; 8621 8622 if (const auto D = cxcursor::getCursorDecl(C)) 8623 if (const auto FD = dyn_cast_or_null<FieldDecl>(D)) 8624 return FD->isMutable() ? 1 : 0; 8625 return 0; 8626 } 8627 8628 unsigned clang_CXXMethod_isPureVirtual(CXCursor C) { 8629 if (!clang_isDeclaration(C.kind)) 8630 return 0; 8631 8632 const Decl *D = cxcursor::getCursorDecl(C); 8633 const CXXMethodDecl *Method = 8634 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr; 8635 return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0; 8636 } 8637 8638 unsigned clang_CXXMethod_isConst(CXCursor C) { 8639 if (!clang_isDeclaration(C.kind)) 8640 return 0; 8641 8642 const Decl *D = cxcursor::getCursorDecl(C); 8643 const CXXMethodDecl *Method = 8644 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr; 8645 return (Method && Method->getMethodQualifiers().hasConst()) ? 1 : 0; 8646 } 8647 8648 unsigned clang_CXXMethod_isDefaulted(CXCursor C) { 8649 if (!clang_isDeclaration(C.kind)) 8650 return 0; 8651 8652 const Decl *D = cxcursor::getCursorDecl(C); 8653 const CXXMethodDecl *Method = 8654 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr; 8655 return (Method && Method->isDefaulted()) ? 1 : 0; 8656 } 8657 8658 unsigned clang_CXXMethod_isStatic(CXCursor C) { 8659 if (!clang_isDeclaration(C.kind)) 8660 return 0; 8661 8662 const Decl *D = cxcursor::getCursorDecl(C); 8663 const CXXMethodDecl *Method = 8664 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr; 8665 return (Method && Method->isStatic()) ? 1 : 0; 8666 } 8667 8668 unsigned clang_CXXMethod_isVirtual(CXCursor C) { 8669 if (!clang_isDeclaration(C.kind)) 8670 return 0; 8671 8672 const Decl *D = cxcursor::getCursorDecl(C); 8673 const CXXMethodDecl *Method = 8674 D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr; 8675 return (Method && Method->isVirtual()) ? 1 : 0; 8676 } 8677 8678 unsigned clang_CXXRecord_isAbstract(CXCursor C) { 8679 if (!clang_isDeclaration(C.kind)) 8680 return 0; 8681 8682 const auto *D = cxcursor::getCursorDecl(C); 8683 const auto *RD = dyn_cast_or_null<CXXRecordDecl>(D); 8684 if (RD) 8685 RD = RD->getDefinition(); 8686 return (RD && RD->isAbstract()) ? 1 : 0; 8687 } 8688 8689 unsigned clang_EnumDecl_isScoped(CXCursor C) { 8690 if (!clang_isDeclaration(C.kind)) 8691 return 0; 8692 8693 const Decl *D = cxcursor::getCursorDecl(C); 8694 auto *Enum = dyn_cast_or_null<EnumDecl>(D); 8695 return (Enum && Enum->isScoped()) ? 1 : 0; 8696 } 8697 8698 //===----------------------------------------------------------------------===// 8699 // Attribute introspection. 8700 //===----------------------------------------------------------------------===// 8701 8702 CXType clang_getIBOutletCollectionType(CXCursor C) { 8703 if (C.kind != CXCursor_IBOutletCollectionAttr) 8704 return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C)); 8705 8706 const IBOutletCollectionAttr *A = 8707 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C)); 8708 8709 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C)); 8710 } 8711 8712 //===----------------------------------------------------------------------===// 8713 // Inspecting memory usage. 8714 //===----------------------------------------------------------------------===// 8715 8716 typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries; 8717 8718 static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries, 8719 enum CXTUResourceUsageKind k, 8720 unsigned long amount) { 8721 CXTUResourceUsageEntry entry = {k, amount}; 8722 entries.push_back(entry); 8723 } 8724 8725 const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) { 8726 const char *str = ""; 8727 switch (kind) { 8728 case CXTUResourceUsage_AST: 8729 str = "ASTContext: expressions, declarations, and types"; 8730 break; 8731 case CXTUResourceUsage_Identifiers: 8732 str = "ASTContext: identifiers"; 8733 break; 8734 case CXTUResourceUsage_Selectors: 8735 str = "ASTContext: selectors"; 8736 break; 8737 case CXTUResourceUsage_GlobalCompletionResults: 8738 str = "Code completion: cached global results"; 8739 break; 8740 case CXTUResourceUsage_SourceManagerContentCache: 8741 str = "SourceManager: content cache allocator"; 8742 break; 8743 case CXTUResourceUsage_AST_SideTables: 8744 str = "ASTContext: side tables"; 8745 break; 8746 case CXTUResourceUsage_SourceManager_Membuffer_Malloc: 8747 str = "SourceManager: malloc'ed memory buffers"; 8748 break; 8749 case CXTUResourceUsage_SourceManager_Membuffer_MMap: 8750 str = "SourceManager: mmap'ed memory buffers"; 8751 break; 8752 case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc: 8753 str = "ExternalASTSource: malloc'ed memory buffers"; 8754 break; 8755 case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap: 8756 str = "ExternalASTSource: mmap'ed memory buffers"; 8757 break; 8758 case CXTUResourceUsage_Preprocessor: 8759 str = "Preprocessor: malloc'ed memory"; 8760 break; 8761 case CXTUResourceUsage_PreprocessingRecord: 8762 str = "Preprocessor: PreprocessingRecord"; 8763 break; 8764 case CXTUResourceUsage_SourceManager_DataStructures: 8765 str = "SourceManager: data structures and tables"; 8766 break; 8767 case CXTUResourceUsage_Preprocessor_HeaderSearch: 8768 str = "Preprocessor: header search tables"; 8769 break; 8770 } 8771 return str; 8772 } 8773 8774 CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) { 8775 if (isNotUsableTU(TU)) { 8776 LOG_BAD_TU(TU); 8777 CXTUResourceUsage usage = {(void *)nullptr, 0, nullptr}; 8778 return usage; 8779 } 8780 8781 ASTUnit *astUnit = cxtu::getASTUnit(TU); 8782 std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries()); 8783 ASTContext &astContext = astUnit->getASTContext(); 8784 8785 // How much memory is used by AST nodes and types? 8786 createCXTUResourceUsageEntry( 8787 *entries, CXTUResourceUsage_AST, 8788 (unsigned long)astContext.getASTAllocatedMemory()); 8789 8790 // How much memory is used by identifiers? 8791 createCXTUResourceUsageEntry( 8792 *entries, CXTUResourceUsage_Identifiers, 8793 (unsigned long)astContext.Idents.getAllocator().getTotalMemory()); 8794 8795 // How much memory is used for selectors? 8796 createCXTUResourceUsageEntry( 8797 *entries, CXTUResourceUsage_Selectors, 8798 (unsigned long)astContext.Selectors.getTotalMemory()); 8799 8800 // How much memory is used by ASTContext's side tables? 8801 createCXTUResourceUsageEntry( 8802 *entries, CXTUResourceUsage_AST_SideTables, 8803 (unsigned long)astContext.getSideTableAllocatedMemory()); 8804 8805 // How much memory is used for caching global code completion results? 8806 unsigned long completionBytes = 0; 8807 if (GlobalCodeCompletionAllocator *completionAllocator = 8808 astUnit->getCachedCompletionAllocator().get()) { 8809 completionBytes = completionAllocator->getTotalMemory(); 8810 } 8811 createCXTUResourceUsageEntry( 8812 *entries, CXTUResourceUsage_GlobalCompletionResults, completionBytes); 8813 8814 // How much memory is being used by SourceManager's content cache? 8815 createCXTUResourceUsageEntry( 8816 *entries, CXTUResourceUsage_SourceManagerContentCache, 8817 (unsigned long)astContext.getSourceManager().getContentCacheSize()); 8818 8819 // How much memory is being used by the MemoryBuffer's in SourceManager? 8820 const SourceManager::MemoryBufferSizes &srcBufs = 8821 astUnit->getSourceManager().getMemoryBufferSizes(); 8822 8823 createCXTUResourceUsageEntry(*entries, 8824 CXTUResourceUsage_SourceManager_Membuffer_Malloc, 8825 (unsigned long)srcBufs.malloc_bytes); 8826 createCXTUResourceUsageEntry(*entries, 8827 CXTUResourceUsage_SourceManager_Membuffer_MMap, 8828 (unsigned long)srcBufs.mmap_bytes); 8829 createCXTUResourceUsageEntry( 8830 *entries, CXTUResourceUsage_SourceManager_DataStructures, 8831 (unsigned long)astContext.getSourceManager().getDataStructureSizes()); 8832 8833 // How much memory is being used by the ExternalASTSource? 8834 if (ExternalASTSource *esrc = astContext.getExternalSource()) { 8835 const ExternalASTSource::MemoryBufferSizes &sizes = 8836 esrc->getMemoryBufferSizes(); 8837 8838 createCXTUResourceUsageEntry( 8839 *entries, CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc, 8840 (unsigned long)sizes.malloc_bytes); 8841 createCXTUResourceUsageEntry( 8842 *entries, CXTUResourceUsage_ExternalASTSource_Membuffer_MMap, 8843 (unsigned long)sizes.mmap_bytes); 8844 } 8845 8846 // How much memory is being used by the Preprocessor? 8847 Preprocessor &pp = astUnit->getPreprocessor(); 8848 createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Preprocessor, 8849 pp.getTotalMemory()); 8850 8851 if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) { 8852 createCXTUResourceUsageEntry(*entries, 8853 CXTUResourceUsage_PreprocessingRecord, 8854 pRec->getTotalMemory()); 8855 } 8856 8857 createCXTUResourceUsageEntry(*entries, 8858 CXTUResourceUsage_Preprocessor_HeaderSearch, 8859 pp.getHeaderSearchInfo().getTotalMemory()); 8860 8861 CXTUResourceUsage usage = {(void *)entries.get(), (unsigned)entries->size(), 8862 !entries->empty() ? &(*entries)[0] : nullptr}; 8863 (void)entries.release(); 8864 return usage; 8865 } 8866 8867 void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) { 8868 if (usage.data) 8869 delete (MemUsageEntries *)usage.data; 8870 } 8871 8872 CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) { 8873 CXSourceRangeList *skipped = new CXSourceRangeList; 8874 skipped->count = 0; 8875 skipped->ranges = nullptr; 8876 8877 if (isNotUsableTU(TU)) { 8878 LOG_BAD_TU(TU); 8879 return skipped; 8880 } 8881 8882 if (!file) 8883 return skipped; 8884 8885 ASTUnit *astUnit = cxtu::getASTUnit(TU); 8886 PreprocessingRecord *ppRec = 8887 astUnit->getPreprocessor().getPreprocessingRecord(); 8888 if (!ppRec) 8889 return skipped; 8890 8891 ASTContext &Ctx = astUnit->getASTContext(); 8892 SourceManager &sm = Ctx.getSourceManager(); 8893 FileEntry *fileEntry = static_cast<FileEntry *>(file); 8894 FileID wantedFileID = sm.translateFile(fileEntry); 8895 bool isMainFile = wantedFileID == sm.getMainFileID(); 8896 8897 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges(); 8898 std::vector<SourceRange> wantedRanges; 8899 for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), 8900 ei = SkippedRanges.end(); 8901 i != ei; ++i) { 8902 if (sm.getFileID(i->getBegin()) == wantedFileID || 8903 sm.getFileID(i->getEnd()) == wantedFileID) 8904 wantedRanges.push_back(*i); 8905 else if (isMainFile && (astUnit->isInPreambleFileID(i->getBegin()) || 8906 astUnit->isInPreambleFileID(i->getEnd()))) 8907 wantedRanges.push_back(*i); 8908 } 8909 8910 skipped->count = wantedRanges.size(); 8911 skipped->ranges = new CXSourceRange[skipped->count]; 8912 for (unsigned i = 0, ei = skipped->count; i != ei; ++i) 8913 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]); 8914 8915 return skipped; 8916 } 8917 8918 CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) { 8919 CXSourceRangeList *skipped = new CXSourceRangeList; 8920 skipped->count = 0; 8921 skipped->ranges = nullptr; 8922 8923 if (isNotUsableTU(TU)) { 8924 LOG_BAD_TU(TU); 8925 return skipped; 8926 } 8927 8928 ASTUnit *astUnit = cxtu::getASTUnit(TU); 8929 PreprocessingRecord *ppRec = 8930 astUnit->getPreprocessor().getPreprocessingRecord(); 8931 if (!ppRec) 8932 return skipped; 8933 8934 ASTContext &Ctx = astUnit->getASTContext(); 8935 8936 const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges(); 8937 8938 skipped->count = SkippedRanges.size(); 8939 skipped->ranges = new CXSourceRange[skipped->count]; 8940 for (unsigned i = 0, ei = skipped->count; i != ei; ++i) 8941 skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]); 8942 8943 return skipped; 8944 } 8945 8946 void clang_disposeSourceRangeList(CXSourceRangeList *ranges) { 8947 if (ranges) { 8948 delete[] ranges->ranges; 8949 delete ranges; 8950 } 8951 } 8952 8953 void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) { 8954 CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU); 8955 for (unsigned I = 0; I != Usage.numEntries; ++I) 8956 fprintf(stderr, " %s: %lu\n", 8957 clang_getTUResourceUsageName(Usage.entries[I].kind), 8958 Usage.entries[I].amount); 8959 8960 clang_disposeCXTUResourceUsage(Usage); 8961 } 8962 8963 CXCursor clang_Cursor_getVarDeclInitializer(CXCursor cursor) { 8964 const Decl *const D = getCursorDecl(cursor); 8965 if (!D) 8966 return clang_getNullCursor(); 8967 const auto *const VD = dyn_cast<VarDecl>(D); 8968 if (!VD) 8969 return clang_getNullCursor(); 8970 const Expr *const Init = VD->getInit(); 8971 if (!Init) 8972 return clang_getNullCursor(); 8973 8974 return cxcursor::MakeCXCursor(Init, VD, cxcursor::getCursorTU(cursor)); 8975 } 8976 8977 int clang_Cursor_hasVarDeclGlobalStorage(CXCursor cursor) { 8978 const Decl *const D = getCursorDecl(cursor); 8979 if (!D) 8980 return -1; 8981 const auto *const VD = dyn_cast<VarDecl>(D); 8982 if (!VD) 8983 return -1; 8984 8985 return VD->hasGlobalStorage(); 8986 } 8987 8988 int clang_Cursor_hasVarDeclExternalStorage(CXCursor cursor) { 8989 const Decl *const D = getCursorDecl(cursor); 8990 if (!D) 8991 return -1; 8992 const auto *const VD = dyn_cast<VarDecl>(D); 8993 if (!VD) 8994 return -1; 8995 8996 return VD->hasExternalStorage(); 8997 } 8998 8999 //===----------------------------------------------------------------------===// 9000 // Misc. utility functions. 9001 //===----------------------------------------------------------------------===// 9002 9003 /// Default to using our desired 8 MB stack size on "safety" threads. 9004 static unsigned SafetyStackThreadSize = DesiredStackSize; 9005 9006 namespace clang { 9007 9008 bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn, 9009 unsigned Size) { 9010 if (!Size) 9011 Size = GetSafetyThreadStackSize(); 9012 if (Size && !getenv("LIBCLANG_NOTHREADS")) 9013 return CRC.RunSafelyOnThread(Fn, Size); 9014 return CRC.RunSafely(Fn); 9015 } 9016 9017 unsigned GetSafetyThreadStackSize() { return SafetyStackThreadSize; } 9018 9019 void SetSafetyThreadStackSize(unsigned Value) { SafetyStackThreadSize = Value; } 9020 9021 } // namespace clang 9022 9023 void clang::setThreadBackgroundPriority() { 9024 if (getenv("LIBCLANG_BGPRIO_DISABLE")) 9025 return; 9026 9027 #if LLVM_ENABLE_THREADS 9028 llvm::set_thread_priority(llvm::ThreadPriority::Background); 9029 #endif 9030 } 9031 9032 void cxindex::printDiagsToStderr(ASTUnit *Unit) { 9033 if (!Unit) 9034 return; 9035 9036 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(), 9037 DEnd = Unit->stored_diag_end(); 9038 D != DEnd; ++D) { 9039 CXStoredDiagnostic Diag(*D, Unit->getLangOpts()); 9040 CXString Msg = 9041 clang_formatDiagnostic(&Diag, clang_defaultDiagnosticDisplayOptions()); 9042 fprintf(stderr, "%s\n", clang_getCString(Msg)); 9043 clang_disposeString(Msg); 9044 } 9045 #ifdef _WIN32 9046 // On Windows, force a flush, since there may be multiple copies of 9047 // stderr and stdout in the file system, all with different buffers 9048 // but writing to the same device. 9049 fflush(stderr); 9050 #endif 9051 } 9052 9053 MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II, 9054 SourceLocation MacroDefLoc, 9055 CXTranslationUnit TU) { 9056 if (MacroDefLoc.isInvalid() || !TU) 9057 return nullptr; 9058 if (!II.hadMacroDefinition()) 9059 return nullptr; 9060 9061 ASTUnit *Unit = cxtu::getASTUnit(TU); 9062 Preprocessor &PP = Unit->getPreprocessor(); 9063 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II); 9064 if (MD) { 9065 for (MacroDirective::DefInfo Def = MD->getDefinition(); Def; 9066 Def = Def.getPreviousDefinition()) { 9067 if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc()) 9068 return Def.getMacroInfo(); 9069 } 9070 } 9071 9072 return nullptr; 9073 } 9074 9075 const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef, 9076 CXTranslationUnit TU) { 9077 if (!MacroDef || !TU) 9078 return nullptr; 9079 const IdentifierInfo *II = MacroDef->getName(); 9080 if (!II) 9081 return nullptr; 9082 9083 return getMacroInfo(*II, MacroDef->getLocation(), TU); 9084 } 9085 9086 MacroDefinitionRecord * 9087 cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok, 9088 CXTranslationUnit TU) { 9089 if (!MI || !TU) 9090 return nullptr; 9091 if (Tok.isNot(tok::raw_identifier)) 9092 return nullptr; 9093 9094 if (MI->getNumTokens() == 0) 9095 return nullptr; 9096 SourceRange DefRange(MI->getReplacementToken(0).getLocation(), 9097 MI->getDefinitionEndLoc()); 9098 ASTUnit *Unit = cxtu::getASTUnit(TU); 9099 9100 // Check that the token is inside the definition and not its argument list. 9101 SourceManager &SM = Unit->getSourceManager(); 9102 if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin())) 9103 return nullptr; 9104 if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation())) 9105 return nullptr; 9106 9107 Preprocessor &PP = Unit->getPreprocessor(); 9108 PreprocessingRecord *PPRec = PP.getPreprocessingRecord(); 9109 if (!PPRec) 9110 return nullptr; 9111 9112 IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier()); 9113 if (!II.hadMacroDefinition()) 9114 return nullptr; 9115 9116 // Check that the identifier is not one of the macro arguments. 9117 if (llvm::is_contained(MI->params(), &II)) 9118 return nullptr; 9119 9120 MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II); 9121 if (!InnerMD) 9122 return nullptr; 9123 9124 return PPRec->findMacroDefinition(InnerMD->getMacroInfo()); 9125 } 9126 9127 MacroDefinitionRecord * 9128 cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc, 9129 CXTranslationUnit TU) { 9130 if (Loc.isInvalid() || !MI || !TU) 9131 return nullptr; 9132 9133 if (MI->getNumTokens() == 0) 9134 return nullptr; 9135 ASTUnit *Unit = cxtu::getASTUnit(TU); 9136 Preprocessor &PP = Unit->getPreprocessor(); 9137 if (!PP.getPreprocessingRecord()) 9138 return nullptr; 9139 Loc = Unit->getSourceManager().getSpellingLoc(Loc); 9140 Token Tok; 9141 if (PP.getRawToken(Loc, Tok)) 9142 return nullptr; 9143 9144 return checkForMacroInMacroDefinition(MI, Tok, TU); 9145 } 9146 9147 CXString clang_getClangVersion() { 9148 return cxstring::createDup(getClangFullVersion()); 9149 } 9150 9151 Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) { 9152 if (TU) { 9153 if (ASTUnit *Unit = cxtu::getASTUnit(TU)) { 9154 LogOS << '<' << Unit->getMainFileName() << '>'; 9155 if (Unit->isMainFileAST()) 9156 LogOS << " (" << Unit->getASTFileName() << ')'; 9157 return *this; 9158 } 9159 } else { 9160 LogOS << "<NULL TU>"; 9161 } 9162 return *this; 9163 } 9164 9165 Logger &cxindex::Logger::operator<<(const FileEntry *FE) { 9166 *this << FE->getName(); 9167 return *this; 9168 } 9169 9170 Logger &cxindex::Logger::operator<<(CXCursor cursor) { 9171 CXString cursorName = clang_getCursorDisplayName(cursor); 9172 *this << cursorName << "@" << clang_getCursorLocation(cursor); 9173 clang_disposeString(cursorName); 9174 return *this; 9175 } 9176 9177 Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) { 9178 CXFile File; 9179 unsigned Line, Column; 9180 clang_getFileLocation(Loc, &File, &Line, &Column, nullptr); 9181 CXString FileName = clang_getFileName(File); 9182 *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column); 9183 clang_disposeString(FileName); 9184 return *this; 9185 } 9186 9187 Logger &cxindex::Logger::operator<<(CXSourceRange range) { 9188 CXSourceLocation BLoc = clang_getRangeStart(range); 9189 CXSourceLocation ELoc = clang_getRangeEnd(range); 9190 9191 CXFile BFile; 9192 unsigned BLine, BColumn; 9193 clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr); 9194 9195 CXFile EFile; 9196 unsigned ELine, EColumn; 9197 clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr); 9198 9199 CXString BFileName = clang_getFileName(BFile); 9200 if (BFile == EFile) { 9201 *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName), 9202 BLine, BColumn, ELine, EColumn); 9203 } else { 9204 CXString EFileName = clang_getFileName(EFile); 9205 *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName), BLine, 9206 BColumn) 9207 << llvm::format("%s:%d:%d]", clang_getCString(EFileName), ELine, 9208 EColumn); 9209 clang_disposeString(EFileName); 9210 } 9211 clang_disposeString(BFileName); 9212 return *this; 9213 } 9214 9215 Logger &cxindex::Logger::operator<<(CXString Str) { 9216 *this << clang_getCString(Str); 9217 return *this; 9218 } 9219 9220 Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) { 9221 LogOS << Fmt; 9222 return *this; 9223 } 9224 9225 static llvm::ManagedStatic<std::mutex> LoggingMutex; 9226 9227 cxindex::Logger::~Logger() { 9228 std::lock_guard<std::mutex> L(*LoggingMutex); 9229 9230 static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime(); 9231 9232 raw_ostream &OS = llvm::errs(); 9233 OS << "[libclang:" << Name << ':'; 9234 9235 #ifdef USE_DARWIN_THREADS 9236 // TODO: Portability. 9237 mach_port_t tid = pthread_mach_thread_np(pthread_self()); 9238 OS << tid << ':'; 9239 #endif 9240 9241 llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime(); 9242 OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime()); 9243 OS << Msg << '\n'; 9244 9245 if (Trace) { 9246 llvm::sys::PrintStackTrace(OS); 9247 OS << "--------------------------------------------------\n"; 9248 } 9249 } 9250