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