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