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