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