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