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