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