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