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