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