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