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