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