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