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