CIndex.cpp revision b619e7877f09f2984d06629fd8653f3f333d8ea2
1//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the main API hooks in the Clang-C Source Indexing
11// library.
12//
13//===----------------------------------------------------------------------===//
14
15#include "CIndexer.h"
16#include "CXCursor.h"
17#include "CXTranslationUnit.h"
18#include "CXString.h"
19#include "CXType.h"
20#include "CXSourceLocation.h"
21#include "CIndexDiagnostic.h"
22#include "CursorVisitor.h"
23
24#include "clang/Basic/Version.h"
25
26#include "clang/AST/StmtVisitor.h"
27#include "clang/Basic/Diagnostic.h"
28#include "clang/Frontend/ASTUnit.h"
29#include "clang/Frontend/CompilerInstance.h"
30#include "clang/Frontend/FrontendDiagnostic.h"
31#include "clang/Lex/Lexer.h"
32#include "clang/Lex/HeaderSearch.h"
33#include "clang/Lex/PreprocessingRecord.h"
34#include "clang/Lex/Preprocessor.h"
35#include "llvm/ADT/STLExtras.h"
36#include "llvm/ADT/Optional.h"
37#include "llvm/ADT/StringSwitch.h"
38#include "llvm/Support/SaveAndRestore.h"
39#include "llvm/Support/CrashRecoveryContext.h"
40#include "llvm/Support/PrettyStackTrace.h"
41#include "llvm/Support/MemoryBuffer.h"
42#include "llvm/Support/raw_ostream.h"
43#include "llvm/Support/Timer.h"
44#include "llvm/Support/Mutex.h"
45#include "llvm/Support/Program.h"
46#include "llvm/Support/Signals.h"
47#include "llvm/Support/Threading.h"
48#include "llvm/Support/Compiler.h"
49
50using namespace clang;
51using namespace clang::cxcursor;
52using namespace clang::cxstring;
53using namespace clang::cxtu;
54using namespace clang::cxindex;
55
56CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx, ASTUnit *TU) {
57  if (!TU)
58    return 0;
59  CXTranslationUnit D = new CXTranslationUnitImpl();
60  D->CIdx = CIdx;
61  D->TUData = TU;
62  D->StringPool = createCXStringPool();
63  D->Diagnostics = 0;
64  D->OverridenCursorsPool = createOverridenCXCursorsPool();
65  return D;
66}
67
68cxtu::CXTUOwner::~CXTUOwner() {
69  if (TU)
70    clang_disposeTranslationUnit(TU);
71}
72
73/// \brief Compare two source ranges to determine their relative position in
74/// the translation unit.
75static RangeComparisonResult RangeCompare(SourceManager &SM,
76                                          SourceRange R1,
77                                          SourceRange R2) {
78  assert(R1.isValid() && "First range is invalid?");
79  assert(R2.isValid() && "Second range is invalid?");
80  if (R1.getEnd() != R2.getBegin() &&
81      SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
82    return RangeBefore;
83  if (R2.getEnd() != R1.getBegin() &&
84      SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
85    return RangeAfter;
86  return RangeOverlap;
87}
88
89/// \brief Determine if a source location falls within, before, or after a
90///   a given source range.
91static RangeComparisonResult LocationCompare(SourceManager &SM,
92                                             SourceLocation L, SourceRange R) {
93  assert(R.isValid() && "First range is invalid?");
94  assert(L.isValid() && "Second range is invalid?");
95  if (L == R.getBegin() || L == R.getEnd())
96    return RangeOverlap;
97  if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
98    return RangeBefore;
99  if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
100    return RangeAfter;
101  return RangeOverlap;
102}
103
104/// \brief Translate a Clang source range into a CIndex source range.
105///
106/// Clang internally represents ranges where the end location points to the
107/// start of the token at the end. However, for external clients it is more
108/// useful to have a CXSourceRange be a proper half-open interval. This routine
109/// does the appropriate translation.
110CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
111                                          const LangOptions &LangOpts,
112                                          const CharSourceRange &R) {
113  // We want the last character in this location, so we will adjust the
114  // location accordingly.
115  SourceLocation EndLoc = R.getEnd();
116  if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc))
117    EndLoc = SM.getExpansionRange(EndLoc).second;
118  if (R.isTokenRange() && !EndLoc.isInvalid()) {
119    unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc),
120                                                SM, LangOpts);
121    EndLoc = EndLoc.getLocWithOffset(Length);
122  }
123
124  CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
125                           R.getBegin().getRawEncoding(),
126                           EndLoc.getRawEncoding() };
127  return Result;
128}
129
130//===----------------------------------------------------------------------===//
131// Cursor visitor.
132//===----------------------------------------------------------------------===//
133
134static SourceRange getRawCursorExtent(CXCursor C);
135static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
136
137
138RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
139  return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
140}
141
142/// \brief Visit the given cursor and, if requested by the visitor,
143/// its children.
144///
145/// \param Cursor the cursor to visit.
146///
147/// \param CheckRegionOfInterest if true, then the caller already checked that
148/// this cursor is within the region of interest.
149///
150/// \returns true if the visitation should be aborted, false if it
151/// should continue.
152bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
153  if (clang_isInvalid(Cursor.kind))
154    return false;
155
156  if (clang_isDeclaration(Cursor.kind)) {
157    Decl *D = getCursorDecl(Cursor);
158    if (!D) {
159      assert(0 && "Invalid declaration cursor");
160      return true; // abort.
161    }
162
163    // Ignore implicit declarations, unless it's an objc method because
164    // currently we should report implicit methods for properties when indexing.
165    if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
166      return false;
167  }
168
169  // If we have a range of interest, and this cursor doesn't intersect with it,
170  // we're done.
171  if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
172    SourceRange Range = getRawCursorExtent(Cursor);
173    if (Range.isInvalid() || CompareRegionOfInterest(Range))
174      return false;
175  }
176
177  switch (Visitor(Cursor, Parent, ClientData)) {
178  case CXChildVisit_Break:
179    return true;
180
181  case CXChildVisit_Continue:
182    return false;
183
184  case CXChildVisit_Recurse:
185    return VisitChildren(Cursor);
186  }
187
188  llvm_unreachable("Invalid CXChildVisitResult!");
189}
190
191static bool visitPreprocessedEntitiesInRange(SourceRange R,
192                                             PreprocessingRecord &PPRec,
193                                             CursorVisitor &Visitor) {
194  SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
195  FileID FID;
196
197  if (!Visitor.shouldVisitIncludedEntities()) {
198    // If the begin/end of the range lie in the same FileID, do the optimization
199    // where we skip preprocessed entities that do not come from the same FileID.
200    FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
201    if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
202      FID = FileID();
203  }
204
205  std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
206    Entities = PPRec.getPreprocessedEntitiesInRange(R);
207  return Visitor.visitPreprocessedEntities(Entities.first, Entities.second,
208                                           PPRec, FID);
209}
210
211void CursorVisitor::visitFileRegion() {
212  if (RegionOfInterest.isInvalid())
213    return;
214
215  ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
216  SourceManager &SM = Unit->getSourceManager();
217
218  std::pair<FileID, unsigned>
219    Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())),
220    End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd()));
221
222  if (End.first != Begin.first) {
223    // If the end does not reside in the same file, try to recover by
224    // picking the end of the file of begin location.
225    End.first = Begin.first;
226    End.second = SM.getFileIDSize(Begin.first);
227  }
228
229  assert(Begin.first == End.first);
230  if (Begin.second > End.second)
231    return;
232
233  FileID File = Begin.first;
234  unsigned Offset = Begin.second;
235  unsigned Length = End.second - Begin.second;
236
237  if (!VisitDeclsOnly && !VisitPreprocessorLast)
238    if (visitPreprocessedEntitiesInRegion())
239      return; // visitation break.
240
241  visitDeclsFromFileRegion(File, Offset, Length);
242
243  if (!VisitDeclsOnly && VisitPreprocessorLast)
244    visitPreprocessedEntitiesInRegion();
245}
246
247static bool isInLexicalContext(Decl *D, DeclContext *DC) {
248  if (!DC)
249    return false;
250
251  for (DeclContext *DeclDC = D->getLexicalDeclContext();
252         DeclDC; DeclDC = DeclDC->getLexicalParent()) {
253    if (DeclDC == DC)
254      return true;
255  }
256  return false;
257}
258
259void CursorVisitor::visitDeclsFromFileRegion(FileID File,
260                                             unsigned Offset, unsigned Length) {
261  ASTUnit *Unit = static_cast<ASTUnit *>(TU->TUData);
262  SourceManager &SM = Unit->getSourceManager();
263  SourceRange Range = RegionOfInterest;
264
265  SmallVector<Decl *, 16> Decls;
266  Unit->findFileRegionDecls(File, Offset, Length, Decls);
267
268  // If we didn't find any file level decls for the file, try looking at the
269  // file that it was included from.
270  while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
271    bool Invalid = false;
272    const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
273    if (Invalid)
274      return;
275
276    SourceLocation Outer;
277    if (SLEntry.isFile())
278      Outer = SLEntry.getFile().getIncludeLoc();
279    else
280      Outer = SLEntry.getExpansion().getExpansionLocStart();
281    if (Outer.isInvalid())
282      return;
283
284    llvm::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
285    Length = 0;
286    Unit->findFileRegionDecls(File, Offset, Length, Decls);
287  }
288
289  assert(!Decls.empty());
290
291  bool VisitedAtLeastOnce = false;
292  DeclContext *CurDC = 0;
293  SmallVector<Decl *, 16>::iterator DIt = Decls.begin();
294  for (SmallVector<Decl *, 16>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
295    Decl *D = *DIt;
296    if (D->getSourceRange().isInvalid())
297      continue;
298
299    if (isInLexicalContext(D, CurDC))
300      continue;
301
302    CurDC = dyn_cast<DeclContext>(D);
303
304    if (TagDecl *TD = dyn_cast<TagDecl>(D))
305      if (!TD->isFreeStanding())
306        continue;
307
308    RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
309    if (CompRes == RangeBefore)
310      continue;
311    if (CompRes == RangeAfter)
312      break;
313
314    assert(CompRes == RangeOverlap);
315    VisitedAtLeastOnce = true;
316
317    if (isa<ObjCContainerDecl>(D)) {
318      FileDI_current = &DIt;
319      FileDE_current = DE;
320    } else {
321      FileDI_current = 0;
322    }
323
324    if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
325      break;
326  }
327
328  if (VisitedAtLeastOnce)
329    return;
330
331  // No Decls overlapped with the range. Move up the lexical context until there
332  // is a context that contains the range or we reach the translation unit
333  // level.
334  DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
335                                         : (*(DIt-1))->getLexicalDeclContext();
336
337  while (DC && !DC->isTranslationUnit()) {
338    Decl *D = cast<Decl>(DC);
339    SourceRange CurDeclRange = D->getSourceRange();
340    if (CurDeclRange.isInvalid())
341      break;
342
343    if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
344      Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true);
345      break;
346    }
347
348    DC = D->getLexicalDeclContext();
349  }
350}
351
352bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
353  if (!AU->getPreprocessor().getPreprocessingRecord())
354    return false;
355
356  PreprocessingRecord &PPRec
357    = *AU->getPreprocessor().getPreprocessingRecord();
358  SourceManager &SM = AU->getSourceManager();
359
360  if (RegionOfInterest.isValid()) {
361    SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
362    SourceLocation B = MappedRange.getBegin();
363    SourceLocation E = MappedRange.getEnd();
364
365    if (AU->isInPreambleFileID(B)) {
366      if (SM.isLoadedSourceLocation(E))
367        return visitPreprocessedEntitiesInRange(SourceRange(B, E),
368                                                 PPRec, *this);
369
370      // Beginning of range lies in the preamble but it also extends beyond
371      // it into the main file. Split the range into 2 parts, one covering
372      // the preamble and another covering the main file. This allows subsequent
373      // calls to visitPreprocessedEntitiesInRange to accept a source range that
374      // lies in the same FileID, allowing it to skip preprocessed entities that
375      // do not come from the same FileID.
376      bool breaked =
377        visitPreprocessedEntitiesInRange(
378                                   SourceRange(B, AU->getEndOfPreambleFileID()),
379                                          PPRec, *this);
380      if (breaked) return true;
381      return visitPreprocessedEntitiesInRange(
382                                    SourceRange(AU->getStartOfMainFileID(), E),
383                                        PPRec, *this);
384    }
385
386    return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
387  }
388
389  bool OnlyLocalDecls
390    = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
391
392  if (OnlyLocalDecls)
393    return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
394                                     PPRec);
395
396  return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
397}
398
399template<typename InputIterator>
400bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
401                                              InputIterator Last,
402                                              PreprocessingRecord &PPRec,
403                                              FileID FID) {
404  for (; First != Last; ++First) {
405    if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
406      continue;
407
408    PreprocessedEntity *PPE = *First;
409    if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
410      if (Visit(MakeMacroExpansionCursor(ME, TU)))
411        return true;
412
413      continue;
414    }
415
416    if (MacroDefinition *MD = dyn_cast<MacroDefinition>(PPE)) {
417      if (Visit(MakeMacroDefinitionCursor(MD, TU)))
418        return true;
419
420      continue;
421    }
422
423    if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
424      if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
425        return true;
426
427      continue;
428    }
429  }
430
431  return false;
432}
433
434/// \brief Visit the children of the given cursor.
435///
436/// \returns true if the visitation should be aborted, false if it
437/// should continue.
438bool CursorVisitor::VisitChildren(CXCursor Cursor) {
439  if (clang_isReference(Cursor.kind) &&
440      Cursor.kind != CXCursor_CXXBaseSpecifier) {
441    // By definition, references have no children.
442    return false;
443  }
444
445  // Set the Parent field to Cursor, then back to its old value once we're
446  // done.
447  SetParentRAII SetParent(Parent, StmtParent, Cursor);
448
449  if (clang_isDeclaration(Cursor.kind)) {
450    Decl *D = getCursorDecl(Cursor);
451    if (!D)
452      return false;
453
454    return VisitAttributes(D) || Visit(D);
455  }
456
457  if (clang_isStatement(Cursor.kind)) {
458    if (Stmt *S = getCursorStmt(Cursor))
459      return Visit(S);
460
461    return false;
462  }
463
464  if (clang_isExpression(Cursor.kind)) {
465    if (Expr *E = getCursorExpr(Cursor))
466      return Visit(E);
467
468    return false;
469  }
470
471  if (clang_isTranslationUnit(Cursor.kind)) {
472    CXTranslationUnit tu = getCursorTU(Cursor);
473    ASTUnit *CXXUnit = static_cast<ASTUnit*>(tu->TUData);
474
475    int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
476    for (unsigned I = 0; I != 2; ++I) {
477      if (VisitOrder[I]) {
478        if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
479            RegionOfInterest.isInvalid()) {
480          for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
481                                        TLEnd = CXXUnit->top_level_end();
482               TL != TLEnd; ++TL) {
483            if (Visit(MakeCXCursor(*TL, tu, RegionOfInterest), true))
484              return true;
485          }
486        } else if (VisitDeclContext(
487                                CXXUnit->getASTContext().getTranslationUnitDecl()))
488          return true;
489        continue;
490      }
491
492      // Walk the preprocessing record.
493      if (CXXUnit->getPreprocessor().getPreprocessingRecord())
494        visitPreprocessedEntitiesInRegion();
495    }
496
497    return false;
498  }
499
500  if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
501    if (CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
502      if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
503        return Visit(BaseTSInfo->getTypeLoc());
504      }
505    }
506  }
507
508  if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
509    IBOutletCollectionAttr *A =
510      cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
511    if (const ObjCInterfaceType *InterT = A->getInterface()->getAs<ObjCInterfaceType>())
512      return Visit(cxcursor::MakeCursorObjCClassRef(InterT->getInterface(),
513                                                    A->getInterfaceLoc(), TU));
514  }
515
516  // Nothing to visit at the moment.
517  return false;
518}
519
520bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
521  if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
522    if (Visit(TSInfo->getTypeLoc()))
523        return true;
524
525  if (Stmt *Body = B->getBody())
526    return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
527
528  return false;
529}
530
531llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
532  if (RegionOfInterest.isValid()) {
533    SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
534    if (Range.isInvalid())
535      return llvm::Optional<bool>();
536
537    switch (CompareRegionOfInterest(Range)) {
538    case RangeBefore:
539      // This declaration comes before the region of interest; skip it.
540      return llvm::Optional<bool>();
541
542    case RangeAfter:
543      // This declaration comes after the region of interest; we're done.
544      return false;
545
546    case RangeOverlap:
547      // This declaration overlaps the region of interest; visit it.
548      break;
549    }
550  }
551  return true;
552}
553
554bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
555  DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
556
557  // FIXME: Eventually remove.  This part of a hack to support proper
558  // iteration over all Decls contained lexically within an ObjC container.
559  SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
560  SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
561
562  for ( ; I != E; ++I) {
563    Decl *D = *I;
564    if (D->getLexicalDeclContext() != DC)
565      continue;
566    CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
567
568    // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
569    // declarations is a mismatch with the compiler semantics.
570    if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
571      ObjCInterfaceDecl *ID = cast<ObjCInterfaceDecl>(D);
572      if (!ID->isThisDeclarationADefinition())
573        Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
574
575    } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
576      ObjCProtocolDecl *PD = cast<ObjCProtocolDecl>(D);
577      if (!PD->isThisDeclarationADefinition())
578        Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
579    }
580
581    const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
582    if (!V.hasValue())
583      continue;
584    if (!V.getValue())
585      return false;
586    if (Visit(Cursor, true))
587      return true;
588  }
589  return false;
590}
591
592bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
593  llvm_unreachable("Translation units are visited directly by Visit()");
594}
595
596bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
597  if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
598    return Visit(TSInfo->getTypeLoc());
599
600  return false;
601}
602
603bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
604  if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
605    return Visit(TSInfo->getTypeLoc());
606
607  return false;
608}
609
610bool CursorVisitor::VisitTagDecl(TagDecl *D) {
611  return VisitDeclContext(D);
612}
613
614bool CursorVisitor::VisitClassTemplateSpecializationDecl(
615                                          ClassTemplateSpecializationDecl *D) {
616  bool ShouldVisitBody = false;
617  switch (D->getSpecializationKind()) {
618  case TSK_Undeclared:
619  case TSK_ImplicitInstantiation:
620    // Nothing to visit
621    return false;
622
623  case TSK_ExplicitInstantiationDeclaration:
624  case TSK_ExplicitInstantiationDefinition:
625    break;
626
627  case TSK_ExplicitSpecialization:
628    ShouldVisitBody = true;
629    break;
630  }
631
632  // Visit the template arguments used in the specialization.
633  if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
634    TypeLoc TL = SpecType->getTypeLoc();
635    if (TemplateSpecializationTypeLoc *TSTLoc
636          = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
637      for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
638        if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
639          return true;
640    }
641  }
642
643  if (ShouldVisitBody && VisitCXXRecordDecl(D))
644    return true;
645
646  return false;
647}
648
649bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
650                                   ClassTemplatePartialSpecializationDecl *D) {
651  // FIXME: Visit the "outer" template parameter lists on the TagDecl
652  // before visiting these template parameters.
653  if (VisitTemplateParameters(D->getTemplateParameters()))
654    return true;
655
656  // Visit the partial specialization arguments.
657  const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
658  for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
659    if (VisitTemplateArgumentLoc(TemplateArgs[I]))
660      return true;
661
662  return VisitCXXRecordDecl(D);
663}
664
665bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
666  // Visit the default argument.
667  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
668    if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
669      if (Visit(DefArg->getTypeLoc()))
670        return true;
671
672  return false;
673}
674
675bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
676  if (Expr *Init = D->getInitExpr())
677    return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
678  return false;
679}
680
681bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
682  if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
683    if (Visit(TSInfo->getTypeLoc()))
684      return true;
685
686  // Visit the nested-name-specifier, if present.
687  if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
688    if (VisitNestedNameSpecifierLoc(QualifierLoc))
689      return true;
690
691  return false;
692}
693
694/// \brief Compare two base or member initializers based on their source order.
695static int CompareCXXCtorInitializers(const void* Xp, const void *Yp) {
696  CXXCtorInitializer const * const *X
697    = static_cast<CXXCtorInitializer const * const *>(Xp);
698  CXXCtorInitializer const * const *Y
699    = static_cast<CXXCtorInitializer const * const *>(Yp);
700
701  if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
702    return -1;
703  else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
704    return 1;
705  else
706    return 0;
707}
708
709bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
710  if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
711    // Visit the function declaration's syntactic components in the order
712    // written. This requires a bit of work.
713    TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
714    FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
715
716    // If we have a function declared directly (without the use of a typedef),
717    // visit just the return type. Otherwise, just visit the function's type
718    // now.
719    if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
720        (!FTL && Visit(TL)))
721      return true;
722
723    // Visit the nested-name-specifier, if present.
724    if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
725      if (VisitNestedNameSpecifierLoc(QualifierLoc))
726        return true;
727
728    // Visit the declaration name.
729    if (VisitDeclarationNameInfo(ND->getNameInfo()))
730      return true;
731
732    // FIXME: Visit explicitly-specified template arguments!
733
734    // Visit the function parameters, if we have a function type.
735    if (FTL && VisitFunctionTypeLoc(*FTL, true))
736      return true;
737
738    // FIXME: Attributes?
739  }
740
741  if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
742    if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
743      // Find the initializers that were written in the source.
744      SmallVector<CXXCtorInitializer *, 4> WrittenInits;
745      for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
746                                          IEnd = Constructor->init_end();
747           I != IEnd; ++I) {
748        if (!(*I)->isWritten())
749          continue;
750
751        WrittenInits.push_back(*I);
752      }
753
754      // Sort the initializers in source order
755      llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
756                           &CompareCXXCtorInitializers);
757
758      // Visit the initializers in source order
759      for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
760        CXXCtorInitializer *Init = WrittenInits[I];
761        if (Init->isAnyMemberInitializer()) {
762          if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
763                                        Init->getMemberLocation(), TU)))
764            return true;
765        } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
766          if (Visit(TInfo->getTypeLoc()))
767            return true;
768        }
769
770        // Visit the initializer value.
771        if (Expr *Initializer = Init->getInit())
772          if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
773            return true;
774      }
775    }
776
777    if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
778      return true;
779  }
780
781  return false;
782}
783
784bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
785  if (VisitDeclaratorDecl(D))
786    return true;
787
788  if (Expr *BitWidth = D->getBitWidth())
789    return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
790
791  return false;
792}
793
794bool CursorVisitor::VisitVarDecl(VarDecl *D) {
795  if (VisitDeclaratorDecl(D))
796    return true;
797
798  if (Expr *Init = D->getInit())
799    return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
800
801  return false;
802}
803
804bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
805  if (VisitDeclaratorDecl(D))
806    return true;
807
808  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
809    if (Expr *DefArg = D->getDefaultArgument())
810      return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
811
812  return false;
813}
814
815bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
816  // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
817  // before visiting these template parameters.
818  if (VisitTemplateParameters(D->getTemplateParameters()))
819    return true;
820
821  return VisitFunctionDecl(D->getTemplatedDecl());
822}
823
824bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
825  // FIXME: Visit the "outer" template parameter lists on the TagDecl
826  // before visiting these template parameters.
827  if (VisitTemplateParameters(D->getTemplateParameters()))
828    return true;
829
830  return VisitCXXRecordDecl(D->getTemplatedDecl());
831}
832
833bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
834  if (VisitTemplateParameters(D->getTemplateParameters()))
835    return true;
836
837  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
838      VisitTemplateArgumentLoc(D->getDefaultArgument()))
839    return true;
840
841  return false;
842}
843
844bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
845  if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
846    if (Visit(TSInfo->getTypeLoc()))
847      return true;
848
849  for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
850       PEnd = ND->param_end();
851       P != PEnd; ++P) {
852    if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
853      return true;
854  }
855
856  if (ND->isThisDeclarationADefinition() &&
857      Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
858    return true;
859
860  return false;
861}
862
863template <typename DeclIt>
864static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
865                                      SourceManager &SM, SourceLocation EndLoc,
866                                      SmallVectorImpl<Decl *> &Decls) {
867  DeclIt next = *DI_current;
868  while (++next != DE_current) {
869    Decl *D_next = *next;
870    if (!D_next)
871      break;
872    SourceLocation L = D_next->getLocStart();
873    if (!L.isValid())
874      break;
875    if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
876      *DI_current = next;
877      Decls.push_back(D_next);
878      continue;
879    }
880    break;
881  }
882}
883
884namespace {
885  struct ContainerDeclsSort {
886    SourceManager &SM;
887    ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
888    bool operator()(Decl *A, Decl *B) {
889      SourceLocation L_A = A->getLocStart();
890      SourceLocation L_B = B->getLocStart();
891      assert(L_A.isValid() && L_B.isValid());
892      return SM.isBeforeInTranslationUnit(L_A, L_B);
893    }
894  };
895}
896
897bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
898  // FIXME: Eventually convert back to just 'VisitDeclContext()'.  Essentially
899  // an @implementation can lexically contain Decls that are not properly
900  // nested in the AST.  When we identify such cases, we need to retrofit
901  // this nesting here.
902  if (!DI_current && !FileDI_current)
903    return VisitDeclContext(D);
904
905  // Scan the Decls that immediately come after the container
906  // in the current DeclContext.  If any fall within the
907  // container's lexical region, stash them into a vector
908  // for later processing.
909  SmallVector<Decl *, 24> DeclsInContainer;
910  SourceLocation EndLoc = D->getSourceRange().getEnd();
911  SourceManager &SM = AU->getSourceManager();
912  if (EndLoc.isValid()) {
913    if (DI_current) {
914      addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
915                                DeclsInContainer);
916    } else {
917      addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
918                                DeclsInContainer);
919    }
920  }
921
922  // The common case.
923  if (DeclsInContainer.empty())
924    return VisitDeclContext(D);
925
926  // Get all the Decls in the DeclContext, and sort them with the
927  // additional ones we've collected.  Then visit them.
928  for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
929       I!=E; ++I) {
930    Decl *subDecl = *I;
931    if (!subDecl || subDecl->getLexicalDeclContext() != D ||
932        subDecl->getLocStart().isInvalid())
933      continue;
934    DeclsInContainer.push_back(subDecl);
935  }
936
937  // Now sort the Decls so that they appear in lexical order.
938  std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
939            ContainerDeclsSort(SM));
940
941  // Now visit the decls.
942  for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
943         E = DeclsInContainer.end(); I != E; ++I) {
944    CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
945    const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
946    if (!V.hasValue())
947      continue;
948    if (!V.getValue())
949      return false;
950    if (Visit(Cursor, true))
951      return true;
952  }
953  return false;
954}
955
956bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
957  if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
958                                   TU)))
959    return true;
960
961  ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
962  for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
963         E = ND->protocol_end(); I != E; ++I, ++PL)
964    if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
965      return true;
966
967  return VisitObjCContainerDecl(ND);
968}
969
970bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
971  if (!PID->isThisDeclarationADefinition())
972    return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
973
974  ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
975  for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
976       E = PID->protocol_end(); I != E; ++I, ++PL)
977    if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
978      return true;
979
980  return VisitObjCContainerDecl(PID);
981}
982
983bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
984  if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
985    return true;
986
987  // FIXME: This implements a workaround with @property declarations also being
988  // installed in the DeclContext for the @interface.  Eventually this code
989  // should be removed.
990  ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
991  if (!CDecl || !CDecl->IsClassExtension())
992    return false;
993
994  ObjCInterfaceDecl *ID = CDecl->getClassInterface();
995  if (!ID)
996    return false;
997
998  IdentifierInfo *PropertyId = PD->getIdentifier();
999  ObjCPropertyDecl *prevDecl =
1000    ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
1001
1002  if (!prevDecl)
1003    return false;
1004
1005  // Visit synthesized methods since they will be skipped when visiting
1006  // the @interface.
1007  if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
1008    if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
1009      if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1010        return true;
1011
1012  if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
1013    if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
1014      if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1015        return true;
1016
1017  return false;
1018}
1019
1020bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
1021  if (!D->isThisDeclarationADefinition()) {
1022    // Forward declaration is treated like a reference.
1023    return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1024  }
1025
1026  // Issue callbacks for super class.
1027  if (D->getSuperClass() &&
1028      Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1029                                        D->getSuperClassLoc(),
1030                                        TU)))
1031    return true;
1032
1033  ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1034  for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1035         E = D->protocol_end(); I != E; ++I, ++PL)
1036    if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1037      return true;
1038
1039  return VisitObjCContainerDecl(D);
1040}
1041
1042bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1043  return VisitObjCContainerDecl(D);
1044}
1045
1046bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1047  // 'ID' could be null when dealing with invalid code.
1048  if (ObjCInterfaceDecl *ID = D->getClassInterface())
1049    if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1050      return true;
1051
1052  return VisitObjCImplDecl(D);
1053}
1054
1055bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1056#if 0
1057  // Issue callbacks for super class.
1058  // FIXME: No source location information!
1059  if (D->getSuperClass() &&
1060      Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1061                                        D->getSuperClassLoc(),
1062                                        TU)))
1063    return true;
1064#endif
1065
1066  return VisitObjCImplDecl(D);
1067}
1068
1069bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1070  if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1071    if (PD->isIvarNameSpecified())
1072      return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1073
1074  return false;
1075}
1076
1077bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1078  return VisitDeclContext(D);
1079}
1080
1081bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1082  // Visit nested-name-specifier.
1083  if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1084    if (VisitNestedNameSpecifierLoc(QualifierLoc))
1085      return true;
1086
1087  return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1088                                      D->getTargetNameLoc(), TU));
1089}
1090
1091bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1092  // Visit nested-name-specifier.
1093  if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1094    if (VisitNestedNameSpecifierLoc(QualifierLoc))
1095      return true;
1096  }
1097
1098  if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1099    return true;
1100
1101  return VisitDeclarationNameInfo(D->getNameInfo());
1102}
1103
1104bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1105  // Visit nested-name-specifier.
1106  if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1107    if (VisitNestedNameSpecifierLoc(QualifierLoc))
1108      return true;
1109
1110  return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1111                                      D->getIdentLocation(), TU));
1112}
1113
1114bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1115  // Visit nested-name-specifier.
1116  if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1117    if (VisitNestedNameSpecifierLoc(QualifierLoc))
1118      return true;
1119  }
1120
1121  return VisitDeclarationNameInfo(D->getNameInfo());
1122}
1123
1124bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1125                                               UnresolvedUsingTypenameDecl *D) {
1126  // Visit nested-name-specifier.
1127  if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1128    if (VisitNestedNameSpecifierLoc(QualifierLoc))
1129      return true;
1130
1131  return false;
1132}
1133
1134bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1135  switch (Name.getName().getNameKind()) {
1136  case clang::DeclarationName::Identifier:
1137  case clang::DeclarationName::CXXLiteralOperatorName:
1138  case clang::DeclarationName::CXXOperatorName:
1139  case clang::DeclarationName::CXXUsingDirective:
1140    return false;
1141
1142  case clang::DeclarationName::CXXConstructorName:
1143  case clang::DeclarationName::CXXDestructorName:
1144  case clang::DeclarationName::CXXConversionFunctionName:
1145    if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1146      return Visit(TSInfo->getTypeLoc());
1147    return false;
1148
1149  case clang::DeclarationName::ObjCZeroArgSelector:
1150  case clang::DeclarationName::ObjCOneArgSelector:
1151  case clang::DeclarationName::ObjCMultiArgSelector:
1152    // FIXME: Per-identifier location info?
1153    return false;
1154  }
1155
1156  llvm_unreachable("Invalid DeclarationName::Kind!");
1157}
1158
1159bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1160                                             SourceRange Range) {
1161  // FIXME: This whole routine is a hack to work around the lack of proper
1162  // source information in nested-name-specifiers (PR5791). Since we do have
1163  // a beginning source location, we can visit the first component of the
1164  // nested-name-specifier, if it's a single-token component.
1165  if (!NNS)
1166    return false;
1167
1168  // Get the first component in the nested-name-specifier.
1169  while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1170    NNS = Prefix;
1171
1172  switch (NNS->getKind()) {
1173  case NestedNameSpecifier::Namespace:
1174    return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1175                                        TU));
1176
1177  case NestedNameSpecifier::NamespaceAlias:
1178    return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1179                                        Range.getBegin(), TU));
1180
1181  case NestedNameSpecifier::TypeSpec: {
1182    // If the type has a form where we know that the beginning of the source
1183    // range matches up with a reference cursor. Visit the appropriate reference
1184    // cursor.
1185    const Type *T = NNS->getAsType();
1186    if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1187      return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1188    if (const TagType *Tag = dyn_cast<TagType>(T))
1189      return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1190    if (const TemplateSpecializationType *TST
1191                                      = dyn_cast<TemplateSpecializationType>(T))
1192      return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1193    break;
1194  }
1195
1196  case NestedNameSpecifier::TypeSpecWithTemplate:
1197  case NestedNameSpecifier::Global:
1198  case NestedNameSpecifier::Identifier:
1199    break;
1200  }
1201
1202  return false;
1203}
1204
1205bool
1206CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1207  SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1208  for (; Qualifier; Qualifier = Qualifier.getPrefix())
1209    Qualifiers.push_back(Qualifier);
1210
1211  while (!Qualifiers.empty()) {
1212    NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1213    NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1214    switch (NNS->getKind()) {
1215    case NestedNameSpecifier::Namespace:
1216      if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
1217                                       Q.getLocalBeginLoc(),
1218                                       TU)))
1219        return true;
1220
1221      break;
1222
1223    case NestedNameSpecifier::NamespaceAlias:
1224      if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1225                                       Q.getLocalBeginLoc(),
1226                                       TU)))
1227        return true;
1228
1229      break;
1230
1231    case NestedNameSpecifier::TypeSpec:
1232    case NestedNameSpecifier::TypeSpecWithTemplate:
1233      if (Visit(Q.getTypeLoc()))
1234        return true;
1235
1236      break;
1237
1238    case NestedNameSpecifier::Global:
1239    case NestedNameSpecifier::Identifier:
1240      break;
1241    }
1242  }
1243
1244  return false;
1245}
1246
1247bool CursorVisitor::VisitTemplateParameters(
1248                                          const TemplateParameterList *Params) {
1249  if (!Params)
1250    return false;
1251
1252  for (TemplateParameterList::const_iterator P = Params->begin(),
1253                                          PEnd = Params->end();
1254       P != PEnd; ++P) {
1255    if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
1256      return true;
1257  }
1258
1259  return false;
1260}
1261
1262bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1263  switch (Name.getKind()) {
1264  case TemplateName::Template:
1265    return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1266
1267  case TemplateName::OverloadedTemplate:
1268    // Visit the overloaded template set.
1269    if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1270      return true;
1271
1272    return false;
1273
1274  case TemplateName::DependentTemplate:
1275    // FIXME: Visit nested-name-specifier.
1276    return false;
1277
1278  case TemplateName::QualifiedTemplate:
1279    // FIXME: Visit nested-name-specifier.
1280    return Visit(MakeCursorTemplateRef(
1281                                  Name.getAsQualifiedTemplateName()->getDecl(),
1282                                       Loc, TU));
1283
1284  case TemplateName::SubstTemplateTemplateParm:
1285    return Visit(MakeCursorTemplateRef(
1286                         Name.getAsSubstTemplateTemplateParm()->getParameter(),
1287                                       Loc, TU));
1288
1289  case TemplateName::SubstTemplateTemplateParmPack:
1290    return Visit(MakeCursorTemplateRef(
1291                  Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1292                                       Loc, TU));
1293  }
1294
1295  llvm_unreachable("Invalid TemplateName::Kind!");
1296}
1297
1298bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1299  switch (TAL.getArgument().getKind()) {
1300  case TemplateArgument::Null:
1301  case TemplateArgument::Integral:
1302  case TemplateArgument::Pack:
1303    return false;
1304
1305  case TemplateArgument::Type:
1306    if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1307      return Visit(TSInfo->getTypeLoc());
1308    return false;
1309
1310  case TemplateArgument::Declaration:
1311    if (Expr *E = TAL.getSourceDeclExpression())
1312      return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1313    return false;
1314
1315  case TemplateArgument::Expression:
1316    if (Expr *E = TAL.getSourceExpression())
1317      return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1318    return false;
1319
1320  case TemplateArgument::Template:
1321  case TemplateArgument::TemplateExpansion:
1322    if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1323      return true;
1324
1325    return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
1326                             TAL.getTemplateNameLoc());
1327  }
1328
1329  llvm_unreachable("Invalid TemplateArgument::Kind!");
1330}
1331
1332bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1333  return VisitDeclContext(D);
1334}
1335
1336bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1337  return Visit(TL.getUnqualifiedLoc());
1338}
1339
1340bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1341  ASTContext &Context = AU->getASTContext();
1342
1343  // Some builtin types (such as Objective-C's "id", "sel", and
1344  // "Class") have associated declarations. Create cursors for those.
1345  QualType VisitType;
1346  switch (TL.getTypePtr()->getKind()) {
1347
1348  case BuiltinType::Void:
1349  case BuiltinType::NullPtr:
1350  case BuiltinType::Dependent:
1351#define BUILTIN_TYPE(Id, SingletonId)
1352#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1353#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1354#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1355#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1356#include "clang/AST/BuiltinTypes.def"
1357    break;
1358
1359  case BuiltinType::ObjCId:
1360    VisitType = Context.getObjCIdType();
1361    break;
1362
1363  case BuiltinType::ObjCClass:
1364    VisitType = Context.getObjCClassType();
1365    break;
1366
1367  case BuiltinType::ObjCSel:
1368    VisitType = Context.getObjCSelType();
1369    break;
1370  }
1371
1372  if (!VisitType.isNull()) {
1373    if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1374      return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1375                                     TU));
1376  }
1377
1378  return false;
1379}
1380
1381bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1382  return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1383}
1384
1385bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1386  return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1387}
1388
1389bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1390  if (TL.isDefinition())
1391    return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
1392
1393  return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1394}
1395
1396bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1397  return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1398}
1399
1400bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1401  if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1402    return true;
1403
1404  return false;
1405}
1406
1407bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1408  if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1409    return true;
1410
1411  for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1412    if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1413                                        TU)))
1414      return true;
1415  }
1416
1417  return false;
1418}
1419
1420bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1421  return Visit(TL.getPointeeLoc());
1422}
1423
1424bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1425  return Visit(TL.getInnerLoc());
1426}
1427
1428bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1429  return Visit(TL.getPointeeLoc());
1430}
1431
1432bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1433  return Visit(TL.getPointeeLoc());
1434}
1435
1436bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1437  return Visit(TL.getPointeeLoc());
1438}
1439
1440bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1441  return Visit(TL.getPointeeLoc());
1442}
1443
1444bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1445  return Visit(TL.getPointeeLoc());
1446}
1447
1448bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1449  return Visit(TL.getModifiedLoc());
1450}
1451
1452bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1453                                         bool SkipResultType) {
1454  if (!SkipResultType && Visit(TL.getResultLoc()))
1455    return true;
1456
1457  for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1458    if (Decl *D = TL.getArg(I))
1459      if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
1460        return true;
1461
1462  return false;
1463}
1464
1465bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1466  if (Visit(TL.getElementLoc()))
1467    return true;
1468
1469  if (Expr *Size = TL.getSizeExpr())
1470    return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
1471
1472  return false;
1473}
1474
1475bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1476                                             TemplateSpecializationTypeLoc TL) {
1477  // Visit the template name.
1478  if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1479                        TL.getTemplateNameLoc()))
1480    return true;
1481
1482  // Visit the template arguments.
1483  for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1484    if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1485      return true;
1486
1487  return false;
1488}
1489
1490bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1491  return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1492}
1493
1494bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1495  if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1496    return Visit(TSInfo->getTypeLoc());
1497
1498  return false;
1499}
1500
1501bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1502  if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1503    return Visit(TSInfo->getTypeLoc());
1504
1505  return false;
1506}
1507
1508bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1509  if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1510    return true;
1511
1512  return false;
1513}
1514
1515bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1516                                    DependentTemplateSpecializationTypeLoc TL) {
1517  // Visit the nested-name-specifier, if there is one.
1518  if (TL.getQualifierLoc() &&
1519      VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1520    return true;
1521
1522  // Visit the template arguments.
1523  for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1524    if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1525      return true;
1526
1527  return false;
1528}
1529
1530bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1531  if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1532    return true;
1533
1534  return Visit(TL.getNamedTypeLoc());
1535}
1536
1537bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1538  return Visit(TL.getPatternLoc());
1539}
1540
1541bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1542  if (Expr *E = TL.getUnderlyingExpr())
1543    return Visit(MakeCXCursor(E, StmtParent, TU));
1544
1545  return false;
1546}
1547
1548bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1549  return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1550}
1551
1552bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1553  return Visit(TL.getValueLoc());
1554}
1555
1556#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1557bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1558  return Visit##PARENT##Loc(TL); \
1559}
1560
1561DEFAULT_TYPELOC_IMPL(Complex, Type)
1562DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1563DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1564DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1565DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1566DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1567DEFAULT_TYPELOC_IMPL(Vector, Type)
1568DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1569DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1570DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1571DEFAULT_TYPELOC_IMPL(Record, TagType)
1572DEFAULT_TYPELOC_IMPL(Enum, TagType)
1573DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1574DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1575DEFAULT_TYPELOC_IMPL(Auto, Type)
1576
1577bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1578  // Visit the nested-name-specifier, if present.
1579  if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1580    if (VisitNestedNameSpecifierLoc(QualifierLoc))
1581      return true;
1582
1583  if (D->isCompleteDefinition()) {
1584    for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1585         E = D->bases_end(); I != E; ++I) {
1586      if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1587        return true;
1588    }
1589  }
1590
1591  return VisitTagDecl(D);
1592}
1593
1594bool CursorVisitor::VisitAttributes(Decl *D) {
1595  for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1596       i != e; ++i)
1597    if (Visit(MakeCXCursor(*i, D, TU)))
1598        return true;
1599
1600  return false;
1601}
1602
1603//===----------------------------------------------------------------------===//
1604// Data-recursive visitor methods.
1605//===----------------------------------------------------------------------===//
1606
1607namespace {
1608#define DEF_JOB(NAME, DATA, KIND)\
1609class NAME : public VisitorJob {\
1610public:\
1611  NAME(DATA *d, CXCursor parent) : VisitorJob(parent, VisitorJob::KIND, d) {} \
1612  static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
1613  DATA *get() const { return static_cast<DATA*>(data[0]); }\
1614};
1615
1616DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1617DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1618DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1619DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
1620DEF_JOB(ExplicitTemplateArgsVisit, ASTTemplateArgumentListInfo,
1621        ExplicitTemplateArgsVisitKind)
1622DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1623DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
1624#undef DEF_JOB
1625
1626class DeclVisit : public VisitorJob {
1627public:
1628  DeclVisit(Decl *d, CXCursor parent, bool isFirst) :
1629    VisitorJob(parent, VisitorJob::DeclVisitKind,
1630               d, isFirst ? (void*) 1 : (void*) 0) {}
1631  static bool classof(const VisitorJob *VJ) {
1632    return VJ->getKind() == DeclVisitKind;
1633  }
1634  Decl *get() const { return static_cast<Decl*>(data[0]); }
1635  bool isFirst() const { return data[1] ? true : false; }
1636};
1637class TypeLocVisit : public VisitorJob {
1638public:
1639  TypeLocVisit(TypeLoc tl, CXCursor parent) :
1640    VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1641               tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1642
1643  static bool classof(const VisitorJob *VJ) {
1644    return VJ->getKind() == TypeLocVisitKind;
1645  }
1646
1647  TypeLoc get() const {
1648    QualType T = QualType::getFromOpaquePtr(data[0]);
1649    return TypeLoc(T, data[1]);
1650  }
1651};
1652
1653class LabelRefVisit : public VisitorJob {
1654public:
1655  LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1656    : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1657                 labelLoc.getPtrEncoding()) {}
1658
1659  static bool classof(const VisitorJob *VJ) {
1660    return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1661  }
1662  LabelDecl *get() const { return static_cast<LabelDecl*>(data[0]); }
1663  SourceLocation getLoc() const {
1664    return SourceLocation::getFromPtrEncoding(data[1]); }
1665};
1666
1667class NestedNameSpecifierLocVisit : public VisitorJob {
1668public:
1669  NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1670    : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1671                 Qualifier.getNestedNameSpecifier(),
1672                 Qualifier.getOpaqueData()) { }
1673
1674  static bool classof(const VisitorJob *VJ) {
1675    return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1676  }
1677
1678  NestedNameSpecifierLoc get() const {
1679    return NestedNameSpecifierLoc(static_cast<NestedNameSpecifier*>(data[0]),
1680                                  data[1]);
1681  }
1682};
1683
1684class DeclarationNameInfoVisit : public VisitorJob {
1685public:
1686  DeclarationNameInfoVisit(Stmt *S, CXCursor parent)
1687    : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1688  static bool classof(const VisitorJob *VJ) {
1689    return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1690  }
1691  DeclarationNameInfo get() const {
1692    Stmt *S = static_cast<Stmt*>(data[0]);
1693    switch (S->getStmtClass()) {
1694    default:
1695      llvm_unreachable("Unhandled Stmt");
1696    case clang::Stmt::MSDependentExistsStmtClass:
1697      return cast<MSDependentExistsStmt>(S)->getNameInfo();
1698    case Stmt::CXXDependentScopeMemberExprClass:
1699      return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1700    case Stmt::DependentScopeDeclRefExprClass:
1701      return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1702    }
1703  }
1704};
1705class MemberRefVisit : public VisitorJob {
1706public:
1707  MemberRefVisit(FieldDecl *D, SourceLocation L, CXCursor parent)
1708    : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1709                 L.getPtrEncoding()) {}
1710  static bool classof(const VisitorJob *VJ) {
1711    return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1712  }
1713  FieldDecl *get() const {
1714    return static_cast<FieldDecl*>(data[0]);
1715  }
1716  SourceLocation getLoc() const {
1717    return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t) data[1]);
1718  }
1719};
1720class EnqueueVisitor : public StmtVisitor<EnqueueVisitor, void> {
1721  VisitorWorkList &WL;
1722  CXCursor Parent;
1723public:
1724  EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1725    : WL(wl), Parent(parent) {}
1726
1727  void VisitAddrLabelExpr(AddrLabelExpr *E);
1728  void VisitBlockExpr(BlockExpr *B);
1729  void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
1730  void VisitCompoundStmt(CompoundStmt *S);
1731  void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { /* Do nothing. */ }
1732  void VisitMSDependentExistsStmt(MSDependentExistsStmt *S);
1733  void VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
1734  void VisitCXXNewExpr(CXXNewExpr *E);
1735  void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
1736  void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
1737  void VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
1738  void VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
1739  void VisitCXXTypeidExpr(CXXTypeidExpr *E);
1740  void VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
1741  void VisitCXXUuidofExpr(CXXUuidofExpr *E);
1742  void VisitCXXCatchStmt(CXXCatchStmt *S);
1743  void VisitDeclRefExpr(DeclRefExpr *D);
1744  void VisitDeclStmt(DeclStmt *S);
1745  void VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
1746  void VisitDesignatedInitExpr(DesignatedInitExpr *E);
1747  void VisitExplicitCastExpr(ExplicitCastExpr *E);
1748  void VisitForStmt(ForStmt *FS);
1749  void VisitGotoStmt(GotoStmt *GS);
1750  void VisitIfStmt(IfStmt *If);
1751  void VisitInitListExpr(InitListExpr *IE);
1752  void VisitMemberExpr(MemberExpr *M);
1753  void VisitOffsetOfExpr(OffsetOfExpr *E);
1754  void VisitObjCEncodeExpr(ObjCEncodeExpr *E);
1755  void VisitObjCMessageExpr(ObjCMessageExpr *M);
1756  void VisitOverloadExpr(OverloadExpr *E);
1757  void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
1758  void VisitStmt(Stmt *S);
1759  void VisitSwitchStmt(SwitchStmt *S);
1760  void VisitWhileStmt(WhileStmt *W);
1761  void VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
1762  void VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E);
1763  void VisitTypeTraitExpr(TypeTraitExpr *E);
1764  void VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
1765  void VisitExpressionTraitExpr(ExpressionTraitExpr *E);
1766  void VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U);
1767  void VisitVAArgExpr(VAArgExpr *E);
1768  void VisitSizeOfPackExpr(SizeOfPackExpr *E);
1769  void VisitPseudoObjectExpr(PseudoObjectExpr *E);
1770  void VisitOpaqueValueExpr(OpaqueValueExpr *E);
1771  void VisitLambdaExpr(LambdaExpr *E);
1772
1773private:
1774  void AddDeclarationNameInfo(Stmt *S);
1775  void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
1776  void AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A);
1777  void AddMemberRef(FieldDecl *D, SourceLocation L);
1778  void AddStmt(Stmt *S);
1779  void AddDecl(Decl *D, bool isFirst = true);
1780  void AddTypeLoc(TypeSourceInfo *TI);
1781  void EnqueueChildren(Stmt *S);
1782};
1783} // end anonyous namespace
1784
1785void EnqueueVisitor::AddDeclarationNameInfo(Stmt *S) {
1786  // 'S' should always be non-null, since it comes from the
1787  // statement we are visiting.
1788  WL.push_back(DeclarationNameInfoVisit(S, Parent));
1789}
1790
1791void
1792EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1793  if (Qualifier)
1794    WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
1795}
1796
1797void EnqueueVisitor::AddStmt(Stmt *S) {
1798  if (S)
1799    WL.push_back(StmtVisit(S, Parent));
1800}
1801void EnqueueVisitor::AddDecl(Decl *D, bool isFirst) {
1802  if (D)
1803    WL.push_back(DeclVisit(D, Parent, isFirst));
1804}
1805void EnqueueVisitor::
1806  AddExplicitTemplateArgs(const ASTTemplateArgumentListInfo *A) {
1807  if (A)
1808    WL.push_back(ExplicitTemplateArgsVisit(
1809                        const_cast<ASTTemplateArgumentListInfo*>(A), Parent));
1810}
1811void EnqueueVisitor::AddMemberRef(FieldDecl *D, SourceLocation L) {
1812  if (D)
1813    WL.push_back(MemberRefVisit(D, L, Parent));
1814}
1815void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
1816  if (TI)
1817    WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
1818 }
1819void EnqueueVisitor::EnqueueChildren(Stmt *S) {
1820  unsigned size = WL.size();
1821  for (Stmt::child_range Child = S->children(); Child; ++Child) {
1822    AddStmt(*Child);
1823  }
1824  if (size == WL.size())
1825    return;
1826  // Now reverse the entries we just added.  This will match the DFS
1827  // ordering performed by the worklist.
1828  VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1829  std::reverse(I, E);
1830}
1831void EnqueueVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1832  WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
1833}
1834void EnqueueVisitor::VisitBlockExpr(BlockExpr *B) {
1835  AddDecl(B->getBlockDecl());
1836}
1837void EnqueueVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1838  EnqueueChildren(E);
1839  AddTypeLoc(E->getTypeSourceInfo());
1840}
1841void EnqueueVisitor::VisitCompoundStmt(CompoundStmt *S) {
1842  for (CompoundStmt::reverse_body_iterator I = S->body_rbegin(),
1843        E = S->body_rend(); I != E; ++I) {
1844    AddStmt(*I);
1845  }
1846}
1847void EnqueueVisitor::
1848VisitMSDependentExistsStmt(MSDependentExistsStmt *S) {
1849  AddStmt(S->getSubStmt());
1850  AddDeclarationNameInfo(S);
1851  if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
1852    AddNestedNameSpecifierLoc(QualifierLoc);
1853}
1854
1855void EnqueueVisitor::
1856VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
1857  AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1858  AddDeclarationNameInfo(E);
1859  if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1860    AddNestedNameSpecifierLoc(QualifierLoc);
1861  if (!E->isImplicitAccess())
1862    AddStmt(E->getBase());
1863}
1864void EnqueueVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1865  // Enqueue the initializer , if any.
1866  AddStmt(E->getInitializer());
1867  // Enqueue the array size, if any.
1868  AddStmt(E->getArraySize());
1869  // Enqueue the allocated type.
1870  AddTypeLoc(E->getAllocatedTypeSourceInfo());
1871  // Enqueue the placement arguments.
1872  for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
1873    AddStmt(E->getPlacementArg(I-1));
1874}
1875void EnqueueVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *CE) {
1876  for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
1877    AddStmt(CE->getArg(I-1));
1878  AddStmt(CE->getCallee());
1879  AddStmt(CE->getArg(0));
1880}
1881void EnqueueVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1882  // Visit the name of the type being destroyed.
1883  AddTypeLoc(E->getDestroyedTypeInfo());
1884  // Visit the scope type that looks disturbingly like the nested-name-specifier
1885  // but isn't.
1886  AddTypeLoc(E->getScopeTypeInfo());
1887  // Visit the nested-name-specifier.
1888  if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
1889    AddNestedNameSpecifierLoc(QualifierLoc);
1890  // Visit base expression.
1891  AddStmt(E->getBase());
1892}
1893void EnqueueVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1894  AddTypeLoc(E->getTypeSourceInfo());
1895}
1896void EnqueueVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1897  EnqueueChildren(E);
1898  AddTypeLoc(E->getTypeSourceInfo());
1899}
1900void EnqueueVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1901  EnqueueChildren(E);
1902  if (E->isTypeOperand())
1903    AddTypeLoc(E->getTypeOperandSourceInfo());
1904}
1905
1906void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr
1907                                                     *E) {
1908  EnqueueChildren(E);
1909  AddTypeLoc(E->getTypeSourceInfo());
1910}
1911void EnqueueVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1912  EnqueueChildren(E);
1913  if (E->isTypeOperand())
1914    AddTypeLoc(E->getTypeOperandSourceInfo());
1915}
1916
1917void EnqueueVisitor::VisitCXXCatchStmt(CXXCatchStmt *S) {
1918  EnqueueChildren(S);
1919  AddDecl(S->getExceptionDecl());
1920}
1921
1922void EnqueueVisitor::VisitDeclRefExpr(DeclRefExpr *DR) {
1923  if (DR->hasExplicitTemplateArgs()) {
1924    AddExplicitTemplateArgs(&DR->getExplicitTemplateArgs());
1925  }
1926  WL.push_back(DeclRefExprParts(DR, Parent));
1927}
1928void EnqueueVisitor::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
1929  AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
1930  AddDeclarationNameInfo(E);
1931  AddNestedNameSpecifierLoc(E->getQualifierLoc());
1932}
1933void EnqueueVisitor::VisitDeclStmt(DeclStmt *S) {
1934  unsigned size = WL.size();
1935  bool isFirst = true;
1936  for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1937       D != DEnd; ++D) {
1938    AddDecl(*D, isFirst);
1939    isFirst = false;
1940  }
1941  if (size == WL.size())
1942    return;
1943  // Now reverse the entries we just added.  This will match the DFS
1944  // ordering performed by the worklist.
1945  VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1946  std::reverse(I, E);
1947}
1948void EnqueueVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1949  AddStmt(E->getInit());
1950  typedef DesignatedInitExpr::Designator Designator;
1951  for (DesignatedInitExpr::reverse_designators_iterator
1952         D = E->designators_rbegin(), DEnd = E->designators_rend();
1953         D != DEnd; ++D) {
1954    if (D->isFieldDesignator()) {
1955      if (FieldDecl *Field = D->getField())
1956        AddMemberRef(Field, D->getFieldLoc());
1957      continue;
1958    }
1959    if (D->isArrayDesignator()) {
1960      AddStmt(E->getArrayIndex(*D));
1961      continue;
1962    }
1963    assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1964    AddStmt(E->getArrayRangeEnd(*D));
1965    AddStmt(E->getArrayRangeStart(*D));
1966  }
1967}
1968void EnqueueVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1969  EnqueueChildren(E);
1970  AddTypeLoc(E->getTypeInfoAsWritten());
1971}
1972void EnqueueVisitor::VisitForStmt(ForStmt *FS) {
1973  AddStmt(FS->getBody());
1974  AddStmt(FS->getInc());
1975  AddStmt(FS->getCond());
1976  AddDecl(FS->getConditionVariable());
1977  AddStmt(FS->getInit());
1978}
1979void EnqueueVisitor::VisitGotoStmt(GotoStmt *GS) {
1980  WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
1981}
1982void EnqueueVisitor::VisitIfStmt(IfStmt *If) {
1983  AddStmt(If->getElse());
1984  AddStmt(If->getThen());
1985  AddStmt(If->getCond());
1986  AddDecl(If->getConditionVariable());
1987}
1988void EnqueueVisitor::VisitInitListExpr(InitListExpr *IE) {
1989  // We care about the syntactic form of the initializer list, only.
1990  if (InitListExpr *Syntactic = IE->getSyntacticForm())
1991    IE = Syntactic;
1992  EnqueueChildren(IE);
1993}
1994void EnqueueVisitor::VisitMemberExpr(MemberExpr *M) {
1995  WL.push_back(MemberExprParts(M, Parent));
1996
1997  // If the base of the member access expression is an implicit 'this', don't
1998  // visit it.
1999  // FIXME: If we ever want to show these implicit accesses, this will be
2000  // unfortunate. However, clang_getCursor() relies on this behavior.
2001  if (!M->isImplicitAccess())
2002    AddStmt(M->getBase());
2003}
2004void EnqueueVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
2005  AddTypeLoc(E->getEncodedTypeSourceInfo());
2006}
2007void EnqueueVisitor::VisitObjCMessageExpr(ObjCMessageExpr *M) {
2008  EnqueueChildren(M);
2009  AddTypeLoc(M->getClassReceiverTypeInfo());
2010}
2011void EnqueueVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
2012  // Visit the components of the offsetof expression.
2013  for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2014    typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
2015    const OffsetOfNode &Node = E->getComponent(I-1);
2016    switch (Node.getKind()) {
2017    case OffsetOfNode::Array:
2018      AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2019      break;
2020    case OffsetOfNode::Field:
2021      AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2022      break;
2023    case OffsetOfNode::Identifier:
2024    case OffsetOfNode::Base:
2025      continue;
2026    }
2027  }
2028  // Visit the type into which we're computing the offset.
2029  AddTypeLoc(E->getTypeSourceInfo());
2030}
2031void EnqueueVisitor::VisitOverloadExpr(OverloadExpr *E) {
2032  AddExplicitTemplateArgs(E->getOptionalExplicitTemplateArgs());
2033  WL.push_back(OverloadExprParts(E, Parent));
2034}
2035void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2036                                              UnaryExprOrTypeTraitExpr *E) {
2037  EnqueueChildren(E);
2038  if (E->isArgumentType())
2039    AddTypeLoc(E->getArgumentTypeInfo());
2040}
2041void EnqueueVisitor::VisitStmt(Stmt *S) {
2042  EnqueueChildren(S);
2043}
2044void EnqueueVisitor::VisitSwitchStmt(SwitchStmt *S) {
2045  AddStmt(S->getBody());
2046  AddStmt(S->getCond());
2047  AddDecl(S->getConditionVariable());
2048}
2049
2050void EnqueueVisitor::VisitWhileStmt(WhileStmt *W) {
2051  AddStmt(W->getBody());
2052  AddStmt(W->getCond());
2053  AddDecl(W->getConditionVariable());
2054}
2055
2056void EnqueueVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
2057  AddTypeLoc(E->getQueriedTypeSourceInfo());
2058}
2059
2060void EnqueueVisitor::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
2061  AddTypeLoc(E->getRhsTypeSourceInfo());
2062  AddTypeLoc(E->getLhsTypeSourceInfo());
2063}
2064
2065void EnqueueVisitor::VisitTypeTraitExpr(TypeTraitExpr *E) {
2066  for (unsigned I = E->getNumArgs(); I > 0; --I)
2067    AddTypeLoc(E->getArg(I-1));
2068}
2069
2070void EnqueueVisitor::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2071  AddTypeLoc(E->getQueriedTypeSourceInfo());
2072}
2073
2074void EnqueueVisitor::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2075  EnqueueChildren(E);
2076}
2077
2078void EnqueueVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *U) {
2079  VisitOverloadExpr(U);
2080  if (!U->isImplicitAccess())
2081    AddStmt(U->getBase());
2082}
2083void EnqueueVisitor::VisitVAArgExpr(VAArgExpr *E) {
2084  AddStmt(E->getSubExpr());
2085  AddTypeLoc(E->getWrittenTypeInfo());
2086}
2087void EnqueueVisitor::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2088  WL.push_back(SizeOfPackExprParts(E, Parent));
2089}
2090void EnqueueVisitor::VisitOpaqueValueExpr(OpaqueValueExpr *E) {
2091  // If the opaque value has a source expression, just transparently
2092  // visit that.  This is useful for (e.g.) pseudo-object expressions.
2093  if (Expr *SourceExpr = E->getSourceExpr())
2094    return Visit(SourceExpr);
2095}
2096void EnqueueVisitor::VisitLambdaExpr(LambdaExpr *E) {
2097  AddStmt(E->getBody());
2098  WL.push_back(LambdaExprParts(E, Parent));
2099}
2100void EnqueueVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
2101  // Treat the expression like its syntactic form.
2102  Visit(E->getSyntacticForm());
2103}
2104
2105void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
2106  EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU,RegionOfInterest)).Visit(S);
2107}
2108
2109bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2110  if (RegionOfInterest.isValid()) {
2111    SourceRange Range = getRawCursorExtent(C);
2112    if (Range.isInvalid() || CompareRegionOfInterest(Range))
2113      return false;
2114  }
2115  return true;
2116}
2117
2118bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2119  while (!WL.empty()) {
2120    // Dequeue the worklist item.
2121    VisitorJob LI = WL.back();
2122    WL.pop_back();
2123
2124    // Set the Parent field, then back to its old value once we're done.
2125    SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2126
2127    switch (LI.getKind()) {
2128      case VisitorJob::DeclVisitKind: {
2129        Decl *D = cast<DeclVisit>(&LI)->get();
2130        if (!D)
2131          continue;
2132
2133        // For now, perform default visitation for Decls.
2134        if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2135                               cast<DeclVisit>(&LI)->isFirst())))
2136            return true;
2137
2138        continue;
2139      }
2140      case VisitorJob::ExplicitTemplateArgsVisitKind: {
2141        const ASTTemplateArgumentListInfo *ArgList =
2142          cast<ExplicitTemplateArgsVisit>(&LI)->get();
2143        for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
2144               *ArgEnd = Arg + ArgList->NumTemplateArgs;
2145               Arg != ArgEnd; ++Arg) {
2146          if (VisitTemplateArgumentLoc(*Arg))
2147            return true;
2148        }
2149        continue;
2150      }
2151      case VisitorJob::TypeLocVisitKind: {
2152        // Perform default visitation for TypeLocs.
2153        if (Visit(cast<TypeLocVisit>(&LI)->get()))
2154          return true;
2155        continue;
2156      }
2157      case VisitorJob::LabelRefVisitKind: {
2158        LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
2159        if (LabelStmt *stmt = LS->getStmt()) {
2160          if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
2161                                       TU))) {
2162            return true;
2163          }
2164        }
2165        continue;
2166      }
2167
2168      case VisitorJob::NestedNameSpecifierLocVisitKind: {
2169        NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
2170        if (VisitNestedNameSpecifierLoc(V->get()))
2171          return true;
2172        continue;
2173      }
2174
2175      case VisitorJob::DeclarationNameInfoVisitKind: {
2176        if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
2177                                     ->get()))
2178          return true;
2179        continue;
2180      }
2181      case VisitorJob::MemberRefVisitKind: {
2182        MemberRefVisit *V = cast<MemberRefVisit>(&LI);
2183        if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
2184          return true;
2185        continue;
2186      }
2187      case VisitorJob::StmtVisitKind: {
2188        Stmt *S = cast<StmtVisit>(&LI)->get();
2189        if (!S)
2190          continue;
2191
2192        // Update the current cursor.
2193        CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
2194        if (!IsInRegionOfInterest(Cursor))
2195          continue;
2196        switch (Visitor(Cursor, Parent, ClientData)) {
2197          case CXChildVisit_Break: return true;
2198          case CXChildVisit_Continue: break;
2199          case CXChildVisit_Recurse:
2200            EnqueueWorkList(WL, S);
2201            break;
2202        }
2203        continue;
2204      }
2205      case VisitorJob::MemberExprPartsKind: {
2206        // Handle the other pieces in the MemberExpr besides the base.
2207        MemberExpr *M = cast<MemberExprParts>(&LI)->get();
2208
2209        // Visit the nested-name-specifier
2210        if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
2211          if (VisitNestedNameSpecifierLoc(QualifierLoc))
2212            return true;
2213
2214        // Visit the declaration name.
2215        if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2216          return true;
2217
2218        // Visit the explicitly-specified template arguments, if any.
2219        if (M->hasExplicitTemplateArgs()) {
2220          for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2221               *ArgEnd = Arg + M->getNumTemplateArgs();
2222               Arg != ArgEnd; ++Arg) {
2223            if (VisitTemplateArgumentLoc(*Arg))
2224              return true;
2225          }
2226        }
2227        continue;
2228      }
2229      case VisitorJob::DeclRefExprPartsKind: {
2230        DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
2231        // Visit nested-name-specifier, if present.
2232        if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
2233          if (VisitNestedNameSpecifierLoc(QualifierLoc))
2234            return true;
2235        // Visit declaration name.
2236        if (VisitDeclarationNameInfo(DR->getNameInfo()))
2237          return true;
2238        continue;
2239      }
2240      case VisitorJob::OverloadExprPartsKind: {
2241        OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
2242        // Visit the nested-name-specifier.
2243        if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
2244          if (VisitNestedNameSpecifierLoc(QualifierLoc))
2245            return true;
2246        // Visit the declaration name.
2247        if (VisitDeclarationNameInfo(O->getNameInfo()))
2248          return true;
2249        // Visit the overloaded declaration reference.
2250        if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
2251          return true;
2252        continue;
2253      }
2254      case VisitorJob::SizeOfPackExprPartsKind: {
2255        SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
2256        NamedDecl *Pack = E->getPack();
2257        if (isa<TemplateTypeParmDecl>(Pack)) {
2258          if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
2259                                      E->getPackLoc(), TU)))
2260            return true;
2261
2262          continue;
2263        }
2264
2265        if (isa<TemplateTemplateParmDecl>(Pack)) {
2266          if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
2267                                          E->getPackLoc(), TU)))
2268            return true;
2269
2270          continue;
2271        }
2272
2273        // Non-type template parameter packs and function parameter packs are
2274        // treated like DeclRefExpr cursors.
2275        continue;
2276      }
2277
2278      case VisitorJob::LambdaExprPartsKind: {
2279        // Visit captures.
2280        LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
2281        for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
2282                                       CEnd = E->explicit_capture_end();
2283             C != CEnd; ++C) {
2284          if (C->capturesThis())
2285            continue;
2286
2287          if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
2288                                          C->getLocation(),
2289                                          TU)))
2290            return true;
2291        }
2292
2293        // Visit parameters and return type, if present.
2294        if (E->hasExplicitParameters() || E->hasExplicitResultType()) {
2295          TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
2296          if (E->hasExplicitParameters() && E->hasExplicitResultType()) {
2297            // Visit the whole type.
2298            if (Visit(TL))
2299              return true;
2300          } else if (isa<FunctionProtoTypeLoc>(TL)) {
2301            FunctionProtoTypeLoc Proto = cast<FunctionProtoTypeLoc>(TL);
2302            if (E->hasExplicitParameters()) {
2303              // Visit parameters.
2304              for (unsigned I = 0, N = Proto.getNumArgs(); I != N; ++I)
2305                if (Visit(MakeCXCursor(Proto.getArg(I), TU)))
2306                  return true;
2307            } else {
2308              // Visit result type.
2309              if (Visit(Proto.getResultLoc()))
2310                return true;
2311            }
2312          }
2313        }
2314        break;
2315      }
2316    }
2317  }
2318  return false;
2319}
2320
2321bool CursorVisitor::Visit(Stmt *S) {
2322  VisitorWorkList *WL = 0;
2323  if (!WorkListFreeList.empty()) {
2324    WL = WorkListFreeList.back();
2325    WL->clear();
2326    WorkListFreeList.pop_back();
2327  }
2328  else {
2329    WL = new VisitorWorkList();
2330    WorkListCache.push_back(WL);
2331  }
2332  EnqueueWorkList(*WL, S);
2333  bool result = RunVisitorWorkList(*WL);
2334  WorkListFreeList.push_back(WL);
2335  return result;
2336}
2337
2338namespace {
2339typedef llvm::SmallVector<SourceRange, 4> RefNamePieces;
2340RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
2341                          const DeclarationNameInfo &NI,
2342                          const SourceRange &QLoc,
2343                          const ASTTemplateArgumentListInfo *TemplateArgs = 0){
2344  const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
2345  const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
2346  const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
2347
2348  const DeclarationName::NameKind Kind = NI.getName().getNameKind();
2349
2350  RefNamePieces Pieces;
2351
2352  if (WantQualifier && QLoc.isValid())
2353    Pieces.push_back(QLoc);
2354
2355  if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
2356    Pieces.push_back(NI.getLoc());
2357
2358  if (WantTemplateArgs && TemplateArgs)
2359    Pieces.push_back(SourceRange(TemplateArgs->LAngleLoc,
2360                                 TemplateArgs->RAngleLoc));
2361
2362  if (Kind == DeclarationName::CXXOperatorName) {
2363    Pieces.push_back(SourceLocation::getFromRawEncoding(
2364                       NI.getInfo().CXXOperatorName.BeginOpNameLoc));
2365    Pieces.push_back(SourceLocation::getFromRawEncoding(
2366                       NI.getInfo().CXXOperatorName.EndOpNameLoc));
2367  }
2368
2369  if (WantSinglePiece) {
2370    SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
2371    Pieces.clear();
2372    Pieces.push_back(R);
2373  }
2374
2375  return Pieces;
2376}
2377}
2378
2379//===----------------------------------------------------------------------===//
2380// Misc. API hooks.
2381//===----------------------------------------------------------------------===//
2382
2383static llvm::sys::Mutex EnableMultithreadingMutex;
2384static bool EnabledMultithreading;
2385
2386static void fatal_error_handler(void *user_data, const std::string& reason) {
2387  // Write the result out to stderr avoiding errs() because raw_ostreams can
2388  // call report_fatal_error.
2389  fprintf(stderr, "LIBCLANG FATAL ERROR: %s\n", reason.c_str());
2390  ::abort();
2391}
2392
2393extern "C" {
2394CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2395                          int displayDiagnostics) {
2396  // Disable pretty stack trace functionality, which will otherwise be a very
2397  // poor citizen of the world and set up all sorts of signal handlers.
2398  llvm::DisablePrettyStackTrace = true;
2399
2400  // We use crash recovery to make some of our APIs more reliable, implicitly
2401  // enable it.
2402  llvm::CrashRecoveryContext::Enable();
2403
2404  // Enable support for multithreading in LLVM.
2405  {
2406    llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2407    if (!EnabledMultithreading) {
2408      llvm::install_fatal_error_handler(fatal_error_handler, 0);
2409      llvm::llvm_start_multithreaded();
2410      EnabledMultithreading = true;
2411    }
2412  }
2413
2414  CIndexer *CIdxr = new CIndexer();
2415  if (excludeDeclarationsFromPCH)
2416    CIdxr->setOnlyLocalDecls();
2417  if (displayDiagnostics)
2418    CIdxr->setDisplayDiagnostics();
2419
2420  if (getenv("LIBCLANG_BGPRIO_INDEX"))
2421    CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
2422                               CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
2423  if (getenv("LIBCLANG_BGPRIO_EDIT"))
2424    CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
2425                               CXGlobalOpt_ThreadBackgroundPriorityForEditing);
2426
2427  return CIdxr;
2428}
2429
2430void clang_disposeIndex(CXIndex CIdx) {
2431  if (CIdx)
2432    delete static_cast<CIndexer *>(CIdx);
2433}
2434
2435void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
2436  if (CIdx)
2437    static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
2438}
2439
2440unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
2441  if (CIdx)
2442    return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
2443  return 0;
2444}
2445
2446void clang_toggleCrashRecovery(unsigned isEnabled) {
2447  if (isEnabled)
2448    llvm::CrashRecoveryContext::Enable();
2449  else
2450    llvm::CrashRecoveryContext::Disable();
2451}
2452
2453CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
2454                                              const char *ast_filename) {
2455  if (!CIdx)
2456    return 0;
2457
2458  CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2459  FileSystemOptions FileSystemOpts;
2460  FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
2461
2462  IntrusiveRefCntPtr<DiagnosticsEngine> Diags;
2463  ASTUnit *TU = ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
2464                                  CXXIdx->getOnlyLocalDecls(),
2465                                  0, 0,
2466                                  /*CaptureDiagnostics=*/true,
2467                                  /*AllowPCHWithCompilerErrors=*/true,
2468                                  /*UserFilesAreVolatile=*/true);
2469  return MakeCXTranslationUnit(CXXIdx, TU);
2470}
2471
2472unsigned clang_defaultEditingTranslationUnitOptions() {
2473  return CXTranslationUnit_PrecompiledPreamble |
2474         CXTranslationUnit_CacheCompletionResults;
2475}
2476
2477CXTranslationUnit
2478clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2479                                          const char *source_filename,
2480                                          int num_command_line_args,
2481                                          const char * const *command_line_args,
2482                                          unsigned num_unsaved_files,
2483                                          struct CXUnsavedFile *unsaved_files) {
2484  unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
2485  return clang_parseTranslationUnit(CIdx, source_filename,
2486                                    command_line_args, num_command_line_args,
2487                                    unsaved_files, num_unsaved_files,
2488                                    Options);
2489}
2490
2491struct ParseTranslationUnitInfo {
2492  CXIndex CIdx;
2493  const char *source_filename;
2494  const char *const *command_line_args;
2495  int num_command_line_args;
2496  struct CXUnsavedFile *unsaved_files;
2497  unsigned num_unsaved_files;
2498  unsigned options;
2499  CXTranslationUnit result;
2500};
2501static void clang_parseTranslationUnit_Impl(void *UserData) {
2502  ParseTranslationUnitInfo *PTUI =
2503    static_cast<ParseTranslationUnitInfo*>(UserData);
2504  CXIndex CIdx = PTUI->CIdx;
2505  const char *source_filename = PTUI->source_filename;
2506  const char * const *command_line_args = PTUI->command_line_args;
2507  int num_command_line_args = PTUI->num_command_line_args;
2508  struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2509  unsigned num_unsaved_files = PTUI->num_unsaved_files;
2510  unsigned options = PTUI->options;
2511  PTUI->result = 0;
2512
2513  if (!CIdx)
2514    return;
2515
2516  CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2517
2518  if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
2519    setThreadBackgroundPriority();
2520
2521  bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
2522  // FIXME: Add a flag for modules.
2523  TranslationUnitKind TUKind
2524    = (options & CXTranslationUnit_Incomplete)? TU_Prefix : TU_Complete;
2525  bool CacheCodeCompetionResults
2526    = options & CXTranslationUnit_CacheCompletionResults;
2527  bool IncludeBriefCommentsInCodeCompletion
2528    = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
2529  bool SkipFunctionBodies = options & CXTranslationUnit_SkipFunctionBodies;
2530
2531  // Configure the diagnostics.
2532  DiagnosticOptions DiagOpts;
2533  IntrusiveRefCntPtr<DiagnosticsEngine>
2534    Diags(CompilerInstance::createDiagnostics(DiagOpts, num_command_line_args,
2535                                                command_line_args));
2536
2537  // Recover resources if we crash before exiting this function.
2538  llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
2539    llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
2540    DiagCleanup(Diags.getPtr());
2541
2542  OwningPtr<std::vector<ASTUnit::RemappedFile> >
2543    RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2544
2545  // Recover resources if we crash before exiting this function.
2546  llvm::CrashRecoveryContextCleanupRegistrar<
2547    std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2548
2549  for (unsigned I = 0; I != num_unsaved_files; ++I) {
2550    StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2551    const llvm::MemoryBuffer *Buffer
2552      = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
2553    RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2554                                            Buffer));
2555  }
2556
2557  OwningPtr<std::vector<const char *> >
2558    Args(new std::vector<const char*>());
2559
2560  // Recover resources if we crash before exiting this method.
2561  llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
2562    ArgsCleanup(Args.get());
2563
2564  // Since the Clang C library is primarily used by batch tools dealing with
2565  // (often very broken) source code, where spell-checking can have a
2566  // significant negative impact on performance (particularly when
2567  // precompiled headers are involved), we disable it by default.
2568  // Only do this if we haven't found a spell-checking-related argument.
2569  bool FoundSpellCheckingArgument = false;
2570  for (int I = 0; I != num_command_line_args; ++I) {
2571    if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2572        strcmp(command_line_args[I], "-fspell-checking") == 0) {
2573      FoundSpellCheckingArgument = true;
2574      break;
2575    }
2576  }
2577  if (!FoundSpellCheckingArgument)
2578    Args->push_back("-fno-spell-checking");
2579
2580  Args->insert(Args->end(), command_line_args,
2581               command_line_args + num_command_line_args);
2582
2583  // The 'source_filename' argument is optional.  If the caller does not
2584  // specify it then it is assumed that the source file is specified
2585  // in the actual argument list.
2586  // Put the source file after command_line_args otherwise if '-x' flag is
2587  // present it will be unused.
2588  if (source_filename)
2589    Args->push_back(source_filename);
2590
2591  // Do we need the detailed preprocessing record?
2592  if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
2593    Args->push_back("-Xclang");
2594    Args->push_back("-detailed-preprocessing-record");
2595  }
2596
2597  unsigned NumErrors = Diags->getClient()->getNumErrors();
2598  OwningPtr<ASTUnit> ErrUnit;
2599  OwningPtr<ASTUnit> Unit(
2600    ASTUnit::LoadFromCommandLine(Args->size() ? &(*Args)[0] : 0
2601                                 /* vector::data() not portable */,
2602                                 Args->size() ? (&(*Args)[0] + Args->size()) :0,
2603                                 Diags,
2604                                 CXXIdx->getClangResourcesPath(),
2605                                 CXXIdx->getOnlyLocalDecls(),
2606                                 /*CaptureDiagnostics=*/true,
2607                                 RemappedFiles->size() ? &(*RemappedFiles)[0]:0,
2608                                 RemappedFiles->size(),
2609                                 /*RemappedFilesKeepOriginalName=*/true,
2610                                 PrecompilePreamble,
2611                                 TUKind,
2612                                 CacheCodeCompetionResults,
2613                                 IncludeBriefCommentsInCodeCompletion,
2614                                 /*AllowPCHWithCompilerErrors=*/true,
2615                                 SkipFunctionBodies,
2616                                 /*UserFilesAreVolatile=*/true,
2617                                 &ErrUnit));
2618
2619  if (NumErrors != Diags->getClient()->getNumErrors()) {
2620    // Make sure to check that 'Unit' is non-NULL.
2621    if (CXXIdx->getDisplayDiagnostics())
2622      printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
2623  }
2624
2625  PTUI->result = MakeCXTranslationUnit(CXXIdx, Unit.take());
2626}
2627CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2628                                             const char *source_filename,
2629                                         const char * const *command_line_args,
2630                                             int num_command_line_args,
2631                                            struct CXUnsavedFile *unsaved_files,
2632                                             unsigned num_unsaved_files,
2633                                             unsigned options) {
2634  ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
2635                                    num_command_line_args, unsaved_files,
2636                                    num_unsaved_files, options, 0 };
2637  llvm::CrashRecoveryContext CRC;
2638
2639  if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
2640    fprintf(stderr, "libclang: crash detected during parsing: {\n");
2641    fprintf(stderr, "  'source_filename' : '%s'\n", source_filename);
2642    fprintf(stderr, "  'command_line_args' : [");
2643    for (int i = 0; i != num_command_line_args; ++i) {
2644      if (i)
2645        fprintf(stderr, ", ");
2646      fprintf(stderr, "'%s'", command_line_args[i]);
2647    }
2648    fprintf(stderr, "],\n");
2649    fprintf(stderr, "  'unsaved_files' : [");
2650    for (unsigned i = 0; i != num_unsaved_files; ++i) {
2651      if (i)
2652        fprintf(stderr, ", ");
2653      fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2654              unsaved_files[i].Length);
2655    }
2656    fprintf(stderr, "],\n");
2657    fprintf(stderr, "  'options' : %d,\n", options);
2658    fprintf(stderr, "}\n");
2659
2660    return 0;
2661  } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2662    PrintLibclangResourceUsage(PTUI.result);
2663  }
2664
2665  return PTUI.result;
2666}
2667
2668unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2669  return CXSaveTranslationUnit_None;
2670}
2671
2672namespace {
2673
2674struct SaveTranslationUnitInfo {
2675  CXTranslationUnit TU;
2676  const char *FileName;
2677  unsigned options;
2678  CXSaveError result;
2679};
2680
2681}
2682
2683static void clang_saveTranslationUnit_Impl(void *UserData) {
2684  SaveTranslationUnitInfo *STUI =
2685    static_cast<SaveTranslationUnitInfo*>(UserData);
2686
2687  CIndexer *CXXIdx = (CIndexer*)STUI->TU->CIdx;
2688  if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
2689    setThreadBackgroundPriority();
2690
2691  STUI->result = static_cast<ASTUnit *>(STUI->TU->TUData)->Save(STUI->FileName);
2692}
2693
2694int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2695                              unsigned options) {
2696  if (!TU)
2697    return CXSaveError_InvalidTU;
2698
2699  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
2700  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2701  if (!CXXUnit->hasSema())
2702    return CXSaveError_InvalidTU;
2703
2704  SaveTranslationUnitInfo STUI = { TU, FileName, options, CXSaveError_None };
2705
2706  if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred() ||
2707      getenv("LIBCLANG_NOTHREADS")) {
2708    clang_saveTranslationUnit_Impl(&STUI);
2709
2710    if (getenv("LIBCLANG_RESOURCE_USAGE"))
2711      PrintLibclangResourceUsage(TU);
2712
2713    return STUI.result;
2714  }
2715
2716  // We have an AST that has invalid nodes due to compiler errors.
2717  // Use a crash recovery thread for protection.
2718
2719  llvm::CrashRecoveryContext CRC;
2720
2721  if (!RunSafely(CRC, clang_saveTranslationUnit_Impl, &STUI)) {
2722    fprintf(stderr, "libclang: crash detected during AST saving: {\n");
2723    fprintf(stderr, "  'filename' : '%s'\n", FileName);
2724    fprintf(stderr, "  'options' : %d,\n", options);
2725    fprintf(stderr, "}\n");
2726
2727    return CXSaveError_Unknown;
2728
2729  } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
2730    PrintLibclangResourceUsage(TU);
2731  }
2732
2733  return STUI.result;
2734}
2735
2736void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
2737  if (CTUnit) {
2738    // If the translation unit has been marked as unsafe to free, just discard
2739    // it.
2740    if (static_cast<ASTUnit *>(CTUnit->TUData)->isUnsafeToFree())
2741      return;
2742
2743    delete static_cast<ASTUnit *>(CTUnit->TUData);
2744    disposeCXStringPool(CTUnit->StringPool);
2745    delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
2746    disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
2747    delete CTUnit;
2748  }
2749}
2750
2751unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2752  return CXReparse_None;
2753}
2754
2755struct ReparseTranslationUnitInfo {
2756  CXTranslationUnit TU;
2757  unsigned num_unsaved_files;
2758  struct CXUnsavedFile *unsaved_files;
2759  unsigned options;
2760  int result;
2761};
2762
2763static void clang_reparseTranslationUnit_Impl(void *UserData) {
2764  ReparseTranslationUnitInfo *RTUI =
2765    static_cast<ReparseTranslationUnitInfo*>(UserData);
2766  CXTranslationUnit TU = RTUI->TU;
2767
2768  // Reset the associated diagnostics.
2769  delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
2770  TU->Diagnostics = 0;
2771
2772  unsigned num_unsaved_files = RTUI->num_unsaved_files;
2773  struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2774  unsigned options = RTUI->options;
2775  (void) options;
2776  RTUI->result = 1;
2777
2778  if (!TU)
2779    return;
2780
2781  CIndexer *CXXIdx = (CIndexer*)TU->CIdx;
2782  if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
2783    setThreadBackgroundPriority();
2784
2785  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
2786  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2787
2788  OwningPtr<std::vector<ASTUnit::RemappedFile> >
2789    RemappedFiles(new std::vector<ASTUnit::RemappedFile>());
2790
2791  // Recover resources if we crash before exiting this function.
2792  llvm::CrashRecoveryContextCleanupRegistrar<
2793    std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
2794
2795  for (unsigned I = 0; I != num_unsaved_files; ++I) {
2796    StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2797    const llvm::MemoryBuffer *Buffer
2798      = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
2799    RemappedFiles->push_back(std::make_pair(unsaved_files[I].Filename,
2800                                            Buffer));
2801  }
2802
2803  if (!CXXUnit->Reparse(RemappedFiles->size() ? &(*RemappedFiles)[0] : 0,
2804                        RemappedFiles->size()))
2805    RTUI->result = 0;
2806}
2807
2808int clang_reparseTranslationUnit(CXTranslationUnit TU,
2809                                 unsigned num_unsaved_files,
2810                                 struct CXUnsavedFile *unsaved_files,
2811                                 unsigned options) {
2812  ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2813                                      options, 0 };
2814
2815  if (getenv("LIBCLANG_NOTHREADS")) {
2816    clang_reparseTranslationUnit_Impl(&RTUI);
2817    return RTUI.result;
2818  }
2819
2820  llvm::CrashRecoveryContext CRC;
2821
2822  if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
2823    fprintf(stderr, "libclang: crash detected during reparsing\n");
2824    static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
2825    return 1;
2826  } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
2827    PrintLibclangResourceUsage(TU);
2828
2829  return RTUI.result;
2830}
2831
2832
2833CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
2834  if (!CTUnit)
2835    return createCXString("");
2836
2837  ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit->TUData);
2838  return createCXString(CXXUnit->getOriginalSourceFileName(), true);
2839}
2840
2841CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
2842  ASTUnit *CXXUnit = static_cast<ASTUnit*>(TU->TUData);
2843  return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
2844}
2845
2846} // end: extern "C"
2847
2848//===----------------------------------------------------------------------===//
2849// CXFile Operations.
2850//===----------------------------------------------------------------------===//
2851
2852extern "C" {
2853CXString clang_getFileName(CXFile SFile) {
2854  if (!SFile)
2855    return createCXString((const char*)NULL);
2856
2857  FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2858  return createCXString(FEnt->getName());
2859}
2860
2861time_t clang_getFileTime(CXFile SFile) {
2862  if (!SFile)
2863    return 0;
2864
2865  FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2866  return FEnt->getModificationTime();
2867}
2868
2869CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2870  if (!tu)
2871    return 0;
2872
2873  ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2874
2875  FileManager &FMgr = CXXUnit->getFileManager();
2876  return const_cast<FileEntry *>(FMgr.getFile(file_name));
2877}
2878
2879unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file) {
2880  if (!tu || !file)
2881    return 0;
2882
2883  ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu->TUData);
2884  FileEntry *FEnt = static_cast<FileEntry *>(file);
2885  return CXXUnit->getPreprocessor().getHeaderSearchInfo()
2886                                          .isFileMultipleIncludeGuarded(FEnt);
2887}
2888
2889} // end: extern "C"
2890
2891//===----------------------------------------------------------------------===//
2892// CXCursor Operations.
2893//===----------------------------------------------------------------------===//
2894
2895static Decl *getDeclFromExpr(Stmt *E) {
2896  if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
2897    return getDeclFromExpr(CE->getSubExpr());
2898
2899  if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2900    return RefExpr->getDecl();
2901  if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2902    return ME->getMemberDecl();
2903  if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2904    return RE->getDecl();
2905  if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
2906    if (PRE->isExplicitProperty())
2907      return PRE->getExplicitProperty();
2908    // It could be messaging both getter and setter as in:
2909    // ++myobj.myprop;
2910    // in which case prefer to associate the setter since it is less obvious
2911    // from inspecting the source that the setter is going to get called.
2912    if (PRE->isMessagingSetter())
2913      return PRE->getImplicitPropertySetter();
2914    return PRE->getImplicitPropertyGetter();
2915  }
2916  if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
2917    return getDeclFromExpr(POE->getSyntacticForm());
2918  if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
2919    if (Expr *Src = OVE->getSourceExpr())
2920      return getDeclFromExpr(Src);
2921
2922  if (CallExpr *CE = dyn_cast<CallExpr>(E))
2923    return getDeclFromExpr(CE->getCallee());
2924  if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
2925    if (!CE->isElidable())
2926    return CE->getConstructor();
2927  if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2928    return OME->getMethodDecl();
2929
2930  if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2931    return PE->getProtocol();
2932  if (SubstNonTypeTemplateParmPackExpr *NTTP
2933                              = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
2934    return NTTP->getParameterPack();
2935  if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2936    if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
2937        isa<ParmVarDecl>(SizeOfPack->getPack()))
2938      return SizeOfPack->getPack();
2939
2940  return 0;
2941}
2942
2943static SourceLocation getLocationFromExpr(Expr *E) {
2944  if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
2945    return getLocationFromExpr(CE->getSubExpr());
2946
2947  if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2948    return /*FIXME:*/Msg->getLeftLoc();
2949  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2950    return DRE->getLocation();
2951  if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2952    return Member->getMemberLoc();
2953  if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2954    return Ivar->getLocation();
2955  if (SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
2956    return SizeOfPack->getPackLoc();
2957  if (ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
2958    return PropRef->getLocation();
2959
2960  return E->getLocStart();
2961}
2962
2963extern "C" {
2964
2965unsigned clang_visitChildren(CXCursor parent,
2966                             CXCursorVisitor visitor,
2967                             CXClientData client_data) {
2968  CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
2969                          /*VisitPreprocessorLast=*/false);
2970  return CursorVis.VisitChildren(parent);
2971}
2972
2973#ifndef __has_feature
2974#define __has_feature(x) 0
2975#endif
2976#if __has_feature(blocks)
2977typedef enum CXChildVisitResult
2978     (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2979
2980static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2981    CXClientData client_data) {
2982  CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2983  return block(cursor, parent);
2984}
2985#else
2986// If we are compiled with a compiler that doesn't have native blocks support,
2987// define and call the block manually, so the
2988typedef struct _CXChildVisitResult
2989{
2990	void *isa;
2991	int flags;
2992	int reserved;
2993	enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2994                                         CXCursor);
2995} *CXCursorVisitorBlock;
2996
2997static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2998    CXClientData client_data) {
2999  CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
3000  return block->invoke(block, cursor, parent);
3001}
3002#endif
3003
3004
3005unsigned clang_visitChildrenWithBlock(CXCursor parent,
3006                                      CXCursorVisitorBlock block) {
3007  return clang_visitChildren(parent, visitWithBlock, block);
3008}
3009
3010static CXString getDeclSpelling(Decl *D) {
3011  if (!D)
3012    return createCXString("");
3013
3014  NamedDecl *ND = dyn_cast<NamedDecl>(D);
3015  if (!ND) {
3016    if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
3017      if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
3018        return createCXString(Property->getIdentifier()->getName());
3019
3020    return createCXString("");
3021  }
3022
3023  if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
3024    return createCXString(OMD->getSelector().getAsString());
3025
3026  if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
3027    // No, this isn't the same as the code below. getIdentifier() is non-virtual
3028    // and returns different names. NamedDecl returns the class name and
3029    // ObjCCategoryImplDecl returns the category name.
3030    return createCXString(CIMP->getIdentifier()->getNameStart());
3031
3032  if (isa<UsingDirectiveDecl>(D))
3033    return createCXString("");
3034
3035  SmallString<1024> S;
3036  llvm::raw_svector_ostream os(S);
3037  ND->printName(os);
3038
3039  return createCXString(os.str());
3040}
3041
3042CXString clang_getCursorSpelling(CXCursor C) {
3043  if (clang_isTranslationUnit(C.kind))
3044    return clang_getTranslationUnitSpelling(
3045                            static_cast<CXTranslationUnit>(C.data[2]));
3046
3047  if (clang_isReference(C.kind)) {
3048    switch (C.kind) {
3049    case CXCursor_ObjCSuperClassRef: {
3050      ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
3051      return createCXString(Super->getIdentifier()->getNameStart());
3052    }
3053    case CXCursor_ObjCClassRef: {
3054      ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
3055      return createCXString(Class->getIdentifier()->getNameStart());
3056    }
3057    case CXCursor_ObjCProtocolRef: {
3058      ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
3059      assert(OID && "getCursorSpelling(): Missing protocol decl");
3060      return createCXString(OID->getIdentifier()->getNameStart());
3061    }
3062    case CXCursor_CXXBaseSpecifier: {
3063      CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
3064      return createCXString(B->getType().getAsString());
3065    }
3066    case CXCursor_TypeRef: {
3067      TypeDecl *Type = getCursorTypeRef(C).first;
3068      assert(Type && "Missing type decl");
3069
3070      return createCXString(getCursorContext(C).getTypeDeclType(Type).
3071                              getAsString());
3072    }
3073    case CXCursor_TemplateRef: {
3074      TemplateDecl *Template = getCursorTemplateRef(C).first;
3075      assert(Template && "Missing template decl");
3076
3077      return createCXString(Template->getNameAsString());
3078    }
3079
3080    case CXCursor_NamespaceRef: {
3081      NamedDecl *NS = getCursorNamespaceRef(C).first;
3082      assert(NS && "Missing namespace decl");
3083
3084      return createCXString(NS->getNameAsString());
3085    }
3086
3087    case CXCursor_MemberRef: {
3088      FieldDecl *Field = getCursorMemberRef(C).first;
3089      assert(Field && "Missing member decl");
3090
3091      return createCXString(Field->getNameAsString());
3092    }
3093
3094    case CXCursor_LabelRef: {
3095      LabelStmt *Label = getCursorLabelRef(C).first;
3096      assert(Label && "Missing label");
3097
3098      return createCXString(Label->getName());
3099    }
3100
3101    case CXCursor_OverloadedDeclRef: {
3102      OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3103      if (Decl *D = Storage.dyn_cast<Decl *>()) {
3104        if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
3105          return createCXString(ND->getNameAsString());
3106        return createCXString("");
3107      }
3108      if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3109        return createCXString(E->getName().getAsString());
3110      OverloadedTemplateStorage *Ovl
3111        = Storage.get<OverloadedTemplateStorage*>();
3112      if (Ovl->size() == 0)
3113        return createCXString("");
3114      return createCXString((*Ovl->begin())->getNameAsString());
3115    }
3116
3117    case CXCursor_VariableRef: {
3118      VarDecl *Var = getCursorVariableRef(C).first;
3119      assert(Var && "Missing variable decl");
3120
3121      return createCXString(Var->getNameAsString());
3122    }
3123
3124    default:
3125      return createCXString("<not implemented>");
3126    }
3127  }
3128
3129  if (clang_isExpression(C.kind)) {
3130    Decl *D = getDeclFromExpr(getCursorExpr(C));
3131    if (D)
3132      return getDeclSpelling(D);
3133    return createCXString("");
3134  }
3135
3136  if (clang_isStatement(C.kind)) {
3137    Stmt *S = getCursorStmt(C);
3138    if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
3139      return createCXString(Label->getName());
3140
3141    return createCXString("");
3142  }
3143
3144  if (C.kind == CXCursor_MacroExpansion)
3145    return createCXString(getCursorMacroExpansion(C)->getName()
3146                                                           ->getNameStart());
3147
3148  if (C.kind == CXCursor_MacroDefinition)
3149    return createCXString(getCursorMacroDefinition(C)->getName()
3150                                                           ->getNameStart());
3151
3152  if (C.kind == CXCursor_InclusionDirective)
3153    return createCXString(getCursorInclusionDirective(C)->getFileName());
3154
3155  if (clang_isDeclaration(C.kind))
3156    return getDeclSpelling(getCursorDecl(C));
3157
3158  if (C.kind == CXCursor_AnnotateAttr) {
3159    AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
3160    return createCXString(AA->getAnnotation());
3161  }
3162
3163  if (C.kind == CXCursor_AsmLabelAttr) {
3164    AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
3165    return createCXString(AA->getLabel());
3166  }
3167
3168  return createCXString("");
3169}
3170
3171CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
3172                                                unsigned pieceIndex,
3173                                                unsigned options) {
3174  if (clang_Cursor_isNull(C))
3175    return clang_getNullRange();
3176
3177  ASTContext &Ctx = getCursorContext(C);
3178
3179  if (clang_isStatement(C.kind)) {
3180    Stmt *S = getCursorStmt(C);
3181    if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
3182      if (pieceIndex > 0)
3183        return clang_getNullRange();
3184      return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
3185    }
3186
3187    return clang_getNullRange();
3188  }
3189
3190  if (C.kind == CXCursor_ObjCMessageExpr) {
3191    if (ObjCMessageExpr *
3192          ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
3193      if (pieceIndex >= ME->getNumSelectorLocs())
3194        return clang_getNullRange();
3195      return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
3196    }
3197  }
3198
3199  if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
3200      C.kind == CXCursor_ObjCClassMethodDecl) {
3201    if (ObjCMethodDecl *
3202          MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
3203      if (pieceIndex >= MD->getNumSelectorLocs())
3204        return clang_getNullRange();
3205      return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
3206    }
3207  }
3208
3209  if (C.kind == CXCursor_ObjCCategoryDecl ||
3210      C.kind == CXCursor_ObjCCategoryImplDecl) {
3211    if (pieceIndex > 0)
3212      return clang_getNullRange();
3213    if (ObjCCategoryDecl *
3214          CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
3215      return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
3216    if (ObjCCategoryImplDecl *
3217          CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
3218      return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
3219  }
3220
3221  // FIXME: A CXCursor_InclusionDirective should give the location of the
3222  // filename, but we don't keep track of this.
3223
3224  // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
3225  // but we don't keep track of this.
3226
3227  // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
3228  // but we don't keep track of this.
3229
3230  // Default handling, give the location of the cursor.
3231
3232  if (pieceIndex > 0)
3233    return clang_getNullRange();
3234
3235  CXSourceLocation CXLoc = clang_getCursorLocation(C);
3236  SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
3237  return cxloc::translateSourceRange(Ctx, Loc);
3238}
3239
3240CXString clang_getCursorDisplayName(CXCursor C) {
3241  if (!clang_isDeclaration(C.kind))
3242    return clang_getCursorSpelling(C);
3243
3244  Decl *D = getCursorDecl(C);
3245  if (!D)
3246    return createCXString("");
3247
3248  PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
3249  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
3250    D = FunTmpl->getTemplatedDecl();
3251
3252  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
3253    SmallString<64> Str;
3254    llvm::raw_svector_ostream OS(Str);
3255    OS << *Function;
3256    if (Function->getPrimaryTemplate())
3257      OS << "<>";
3258    OS << "(";
3259    for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
3260      if (I)
3261        OS << ", ";
3262      OS << Function->getParamDecl(I)->getType().getAsString(Policy);
3263    }
3264
3265    if (Function->isVariadic()) {
3266      if (Function->getNumParams())
3267        OS << ", ";
3268      OS << "...";
3269    }
3270    OS << ")";
3271    return createCXString(OS.str());
3272  }
3273
3274  if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
3275    SmallString<64> Str;
3276    llvm::raw_svector_ostream OS(Str);
3277    OS << *ClassTemplate;
3278    OS << "<";
3279    TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
3280    for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3281      if (I)
3282        OS << ", ";
3283
3284      NamedDecl *Param = Params->getParam(I);
3285      if (Param->getIdentifier()) {
3286        OS << Param->getIdentifier()->getName();
3287        continue;
3288      }
3289
3290      // There is no parameter name, which makes this tricky. Try to come up
3291      // with something useful that isn't too long.
3292      if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3293        OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
3294      else if (NonTypeTemplateParmDecl *NTTP
3295                                    = dyn_cast<NonTypeTemplateParmDecl>(Param))
3296        OS << NTTP->getType().getAsString(Policy);
3297      else
3298        OS << "template<...> class";
3299    }
3300
3301    OS << ">";
3302    return createCXString(OS.str());
3303  }
3304
3305  if (ClassTemplateSpecializationDecl *ClassSpec
3306                              = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
3307    // If the type was explicitly written, use that.
3308    if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
3309      return createCXString(TSInfo->getType().getAsString(Policy));
3310
3311    SmallString<64> Str;
3312    llvm::raw_svector_ostream OS(Str);
3313    OS << *ClassSpec;
3314    OS << TemplateSpecializationType::PrintTemplateArgumentList(
3315                                      ClassSpec->getTemplateArgs().data(),
3316                                      ClassSpec->getTemplateArgs().size(),
3317                                                                Policy);
3318    return createCXString(OS.str());
3319  }
3320
3321  return clang_getCursorSpelling(C);
3322}
3323
3324CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
3325  switch (Kind) {
3326  case CXCursor_FunctionDecl:
3327      return createCXString("FunctionDecl");
3328  case CXCursor_TypedefDecl:
3329      return createCXString("TypedefDecl");
3330  case CXCursor_EnumDecl:
3331      return createCXString("EnumDecl");
3332  case CXCursor_EnumConstantDecl:
3333      return createCXString("EnumConstantDecl");
3334  case CXCursor_StructDecl:
3335      return createCXString("StructDecl");
3336  case CXCursor_UnionDecl:
3337      return createCXString("UnionDecl");
3338  case CXCursor_ClassDecl:
3339      return createCXString("ClassDecl");
3340  case CXCursor_FieldDecl:
3341      return createCXString("FieldDecl");
3342  case CXCursor_VarDecl:
3343      return createCXString("VarDecl");
3344  case CXCursor_ParmDecl:
3345      return createCXString("ParmDecl");
3346  case CXCursor_ObjCInterfaceDecl:
3347      return createCXString("ObjCInterfaceDecl");
3348  case CXCursor_ObjCCategoryDecl:
3349      return createCXString("ObjCCategoryDecl");
3350  case CXCursor_ObjCProtocolDecl:
3351      return createCXString("ObjCProtocolDecl");
3352  case CXCursor_ObjCPropertyDecl:
3353      return createCXString("ObjCPropertyDecl");
3354  case CXCursor_ObjCIvarDecl:
3355      return createCXString("ObjCIvarDecl");
3356  case CXCursor_ObjCInstanceMethodDecl:
3357      return createCXString("ObjCInstanceMethodDecl");
3358  case CXCursor_ObjCClassMethodDecl:
3359      return createCXString("ObjCClassMethodDecl");
3360  case CXCursor_ObjCImplementationDecl:
3361      return createCXString("ObjCImplementationDecl");
3362  case CXCursor_ObjCCategoryImplDecl:
3363      return createCXString("ObjCCategoryImplDecl");
3364  case CXCursor_CXXMethod:
3365      return createCXString("CXXMethod");
3366  case CXCursor_UnexposedDecl:
3367      return createCXString("UnexposedDecl");
3368  case CXCursor_ObjCSuperClassRef:
3369      return createCXString("ObjCSuperClassRef");
3370  case CXCursor_ObjCProtocolRef:
3371      return createCXString("ObjCProtocolRef");
3372  case CXCursor_ObjCClassRef:
3373      return createCXString("ObjCClassRef");
3374  case CXCursor_TypeRef:
3375      return createCXString("TypeRef");
3376  case CXCursor_TemplateRef:
3377      return createCXString("TemplateRef");
3378  case CXCursor_NamespaceRef:
3379    return createCXString("NamespaceRef");
3380  case CXCursor_MemberRef:
3381    return createCXString("MemberRef");
3382  case CXCursor_LabelRef:
3383    return createCXString("LabelRef");
3384  case CXCursor_OverloadedDeclRef:
3385    return createCXString("OverloadedDeclRef");
3386  case CXCursor_VariableRef:
3387    return createCXString("VariableRef");
3388  case CXCursor_IntegerLiteral:
3389      return createCXString("IntegerLiteral");
3390  case CXCursor_FloatingLiteral:
3391      return createCXString("FloatingLiteral");
3392  case CXCursor_ImaginaryLiteral:
3393      return createCXString("ImaginaryLiteral");
3394  case CXCursor_StringLiteral:
3395      return createCXString("StringLiteral");
3396  case CXCursor_CharacterLiteral:
3397      return createCXString("CharacterLiteral");
3398  case CXCursor_ParenExpr:
3399      return createCXString("ParenExpr");
3400  case CXCursor_UnaryOperator:
3401      return createCXString("UnaryOperator");
3402  case CXCursor_ArraySubscriptExpr:
3403      return createCXString("ArraySubscriptExpr");
3404  case CXCursor_BinaryOperator:
3405      return createCXString("BinaryOperator");
3406  case CXCursor_CompoundAssignOperator:
3407      return createCXString("CompoundAssignOperator");
3408  case CXCursor_ConditionalOperator:
3409      return createCXString("ConditionalOperator");
3410  case CXCursor_CStyleCastExpr:
3411      return createCXString("CStyleCastExpr");
3412  case CXCursor_CompoundLiteralExpr:
3413      return createCXString("CompoundLiteralExpr");
3414  case CXCursor_InitListExpr:
3415      return createCXString("InitListExpr");
3416  case CXCursor_AddrLabelExpr:
3417      return createCXString("AddrLabelExpr");
3418  case CXCursor_StmtExpr:
3419      return createCXString("StmtExpr");
3420  case CXCursor_GenericSelectionExpr:
3421      return createCXString("GenericSelectionExpr");
3422  case CXCursor_GNUNullExpr:
3423      return createCXString("GNUNullExpr");
3424  case CXCursor_CXXStaticCastExpr:
3425      return createCXString("CXXStaticCastExpr");
3426  case CXCursor_CXXDynamicCastExpr:
3427      return createCXString("CXXDynamicCastExpr");
3428  case CXCursor_CXXReinterpretCastExpr:
3429      return createCXString("CXXReinterpretCastExpr");
3430  case CXCursor_CXXConstCastExpr:
3431      return createCXString("CXXConstCastExpr");
3432  case CXCursor_CXXFunctionalCastExpr:
3433      return createCXString("CXXFunctionalCastExpr");
3434  case CXCursor_CXXTypeidExpr:
3435      return createCXString("CXXTypeidExpr");
3436  case CXCursor_CXXBoolLiteralExpr:
3437      return createCXString("CXXBoolLiteralExpr");
3438  case CXCursor_CXXNullPtrLiteralExpr:
3439      return createCXString("CXXNullPtrLiteralExpr");
3440  case CXCursor_CXXThisExpr:
3441      return createCXString("CXXThisExpr");
3442  case CXCursor_CXXThrowExpr:
3443      return createCXString("CXXThrowExpr");
3444  case CXCursor_CXXNewExpr:
3445      return createCXString("CXXNewExpr");
3446  case CXCursor_CXXDeleteExpr:
3447      return createCXString("CXXDeleteExpr");
3448  case CXCursor_UnaryExpr:
3449      return createCXString("UnaryExpr");
3450  case CXCursor_ObjCStringLiteral:
3451      return createCXString("ObjCStringLiteral");
3452  case CXCursor_ObjCBoolLiteralExpr:
3453      return createCXString("ObjCBoolLiteralExpr");
3454  case CXCursor_ObjCEncodeExpr:
3455      return createCXString("ObjCEncodeExpr");
3456  case CXCursor_ObjCSelectorExpr:
3457      return createCXString("ObjCSelectorExpr");
3458  case CXCursor_ObjCProtocolExpr:
3459      return createCXString("ObjCProtocolExpr");
3460  case CXCursor_ObjCBridgedCastExpr:
3461      return createCXString("ObjCBridgedCastExpr");
3462  case CXCursor_BlockExpr:
3463      return createCXString("BlockExpr");
3464  case CXCursor_PackExpansionExpr:
3465      return createCXString("PackExpansionExpr");
3466  case CXCursor_SizeOfPackExpr:
3467      return createCXString("SizeOfPackExpr");
3468  case CXCursor_LambdaExpr:
3469    return createCXString("LambdaExpr");
3470  case CXCursor_UnexposedExpr:
3471      return createCXString("UnexposedExpr");
3472  case CXCursor_DeclRefExpr:
3473      return createCXString("DeclRefExpr");
3474  case CXCursor_MemberRefExpr:
3475      return createCXString("MemberRefExpr");
3476  case CXCursor_CallExpr:
3477      return createCXString("CallExpr");
3478  case CXCursor_ObjCMessageExpr:
3479      return createCXString("ObjCMessageExpr");
3480  case CXCursor_UnexposedStmt:
3481      return createCXString("UnexposedStmt");
3482  case CXCursor_DeclStmt:
3483      return createCXString("DeclStmt");
3484  case CXCursor_LabelStmt:
3485      return createCXString("LabelStmt");
3486  case CXCursor_CompoundStmt:
3487      return createCXString("CompoundStmt");
3488  case CXCursor_CaseStmt:
3489      return createCXString("CaseStmt");
3490  case CXCursor_DefaultStmt:
3491      return createCXString("DefaultStmt");
3492  case CXCursor_IfStmt:
3493      return createCXString("IfStmt");
3494  case CXCursor_SwitchStmt:
3495      return createCXString("SwitchStmt");
3496  case CXCursor_WhileStmt:
3497      return createCXString("WhileStmt");
3498  case CXCursor_DoStmt:
3499      return createCXString("DoStmt");
3500  case CXCursor_ForStmt:
3501      return createCXString("ForStmt");
3502  case CXCursor_GotoStmt:
3503      return createCXString("GotoStmt");
3504  case CXCursor_IndirectGotoStmt:
3505      return createCXString("IndirectGotoStmt");
3506  case CXCursor_ContinueStmt:
3507      return createCXString("ContinueStmt");
3508  case CXCursor_BreakStmt:
3509      return createCXString("BreakStmt");
3510  case CXCursor_ReturnStmt:
3511      return createCXString("ReturnStmt");
3512  case CXCursor_AsmStmt:
3513      return createCXString("AsmStmt");
3514  case CXCursor_MSAsmStmt:
3515      return createCXString("MSAsmStmt");
3516  case CXCursor_ObjCAtTryStmt:
3517      return createCXString("ObjCAtTryStmt");
3518  case CXCursor_ObjCAtCatchStmt:
3519      return createCXString("ObjCAtCatchStmt");
3520  case CXCursor_ObjCAtFinallyStmt:
3521      return createCXString("ObjCAtFinallyStmt");
3522  case CXCursor_ObjCAtThrowStmt:
3523      return createCXString("ObjCAtThrowStmt");
3524  case CXCursor_ObjCAtSynchronizedStmt:
3525      return createCXString("ObjCAtSynchronizedStmt");
3526  case CXCursor_ObjCAutoreleasePoolStmt:
3527      return createCXString("ObjCAutoreleasePoolStmt");
3528  case CXCursor_ObjCForCollectionStmt:
3529      return createCXString("ObjCForCollectionStmt");
3530  case CXCursor_CXXCatchStmt:
3531      return createCXString("CXXCatchStmt");
3532  case CXCursor_CXXTryStmt:
3533      return createCXString("CXXTryStmt");
3534  case CXCursor_CXXForRangeStmt:
3535      return createCXString("CXXForRangeStmt");
3536  case CXCursor_SEHTryStmt:
3537      return createCXString("SEHTryStmt");
3538  case CXCursor_SEHExceptStmt:
3539      return createCXString("SEHExceptStmt");
3540  case CXCursor_SEHFinallyStmt:
3541      return createCXString("SEHFinallyStmt");
3542  case CXCursor_NullStmt:
3543      return createCXString("NullStmt");
3544  case CXCursor_InvalidFile:
3545      return createCXString("InvalidFile");
3546  case CXCursor_InvalidCode:
3547    return createCXString("InvalidCode");
3548  case CXCursor_NoDeclFound:
3549      return createCXString("NoDeclFound");
3550  case CXCursor_NotImplemented:
3551      return createCXString("NotImplemented");
3552  case CXCursor_TranslationUnit:
3553      return createCXString("TranslationUnit");
3554  case CXCursor_UnexposedAttr:
3555      return createCXString("UnexposedAttr");
3556  case CXCursor_IBActionAttr:
3557      return createCXString("attribute(ibaction)");
3558  case CXCursor_IBOutletAttr:
3559     return createCXString("attribute(iboutlet)");
3560  case CXCursor_IBOutletCollectionAttr:
3561      return createCXString("attribute(iboutletcollection)");
3562  case CXCursor_CXXFinalAttr:
3563      return createCXString("attribute(final)");
3564  case CXCursor_CXXOverrideAttr:
3565      return createCXString("attribute(override)");
3566  case CXCursor_AnnotateAttr:
3567    return createCXString("attribute(annotate)");
3568  case CXCursor_AsmLabelAttr:
3569    return createCXString("asm label");
3570  case CXCursor_PreprocessingDirective:
3571    return createCXString("preprocessing directive");
3572  case CXCursor_MacroDefinition:
3573    return createCXString("macro definition");
3574  case CXCursor_MacroExpansion:
3575    return createCXString("macro expansion");
3576  case CXCursor_InclusionDirective:
3577    return createCXString("inclusion directive");
3578  case CXCursor_Namespace:
3579    return createCXString("Namespace");
3580  case CXCursor_LinkageSpec:
3581    return createCXString("LinkageSpec");
3582  case CXCursor_CXXBaseSpecifier:
3583    return createCXString("C++ base class specifier");
3584  case CXCursor_Constructor:
3585    return createCXString("CXXConstructor");
3586  case CXCursor_Destructor:
3587    return createCXString("CXXDestructor");
3588  case CXCursor_ConversionFunction:
3589    return createCXString("CXXConversion");
3590  case CXCursor_TemplateTypeParameter:
3591    return createCXString("TemplateTypeParameter");
3592  case CXCursor_NonTypeTemplateParameter:
3593    return createCXString("NonTypeTemplateParameter");
3594  case CXCursor_TemplateTemplateParameter:
3595    return createCXString("TemplateTemplateParameter");
3596  case CXCursor_FunctionTemplate:
3597    return createCXString("FunctionTemplate");
3598  case CXCursor_ClassTemplate:
3599    return createCXString("ClassTemplate");
3600  case CXCursor_ClassTemplatePartialSpecialization:
3601    return createCXString("ClassTemplatePartialSpecialization");
3602  case CXCursor_NamespaceAlias:
3603    return createCXString("NamespaceAlias");
3604  case CXCursor_UsingDirective:
3605    return createCXString("UsingDirective");
3606  case CXCursor_UsingDeclaration:
3607    return createCXString("UsingDeclaration");
3608  case CXCursor_TypeAliasDecl:
3609    return createCXString("TypeAliasDecl");
3610  case CXCursor_ObjCSynthesizeDecl:
3611    return createCXString("ObjCSynthesizeDecl");
3612  case CXCursor_ObjCDynamicDecl:
3613    return createCXString("ObjCDynamicDecl");
3614  case CXCursor_CXXAccessSpecifier:
3615    return createCXString("CXXAccessSpecifier");
3616  }
3617
3618  llvm_unreachable("Unhandled CXCursorKind");
3619}
3620
3621struct GetCursorData {
3622  SourceLocation TokenBeginLoc;
3623  bool PointsAtMacroArgExpansion;
3624  bool VisitedObjCPropertyImplDecl;
3625  SourceLocation VisitedDeclaratorDeclStartLoc;
3626  CXCursor &BestCursor;
3627
3628  GetCursorData(SourceManager &SM,
3629                SourceLocation tokenBegin, CXCursor &outputCursor)
3630    : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
3631    PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
3632    VisitedObjCPropertyImplDecl = false;
3633  }
3634};
3635
3636static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3637                                                CXCursor parent,
3638                                                CXClientData client_data) {
3639  GetCursorData *Data = static_cast<GetCursorData *>(client_data);
3640  CXCursor *BestCursor = &Data->BestCursor;
3641
3642  // If we point inside a macro argument we should provide info of what the
3643  // token is so use the actual cursor, don't replace it with a macro expansion
3644  // cursor.
3645  if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
3646    return CXChildVisit_Recurse;
3647
3648  if (clang_isDeclaration(cursor.kind)) {
3649    // Avoid having the implicit methods override the property decls.
3650    if (ObjCMethodDecl *MD
3651          = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
3652      if (MD->isImplicit())
3653        return CXChildVisit_Break;
3654
3655    } else if (ObjCInterfaceDecl *ID
3656                 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
3657      // Check that when we have multiple @class references in the same line,
3658      // that later ones do not override the previous ones.
3659      // If we have:
3660      // @class Foo, Bar;
3661      // source ranges for both start at '@', so 'Bar' will end up overriding
3662      // 'Foo' even though the cursor location was at 'Foo'.
3663      if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
3664          BestCursor->kind == CXCursor_ObjCClassRef)
3665        if (ObjCInterfaceDecl *PrevID
3666             = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
3667         if (PrevID != ID &&
3668             !PrevID->isThisDeclarationADefinition() &&
3669             !ID->isThisDeclarationADefinition())
3670           return CXChildVisit_Break;
3671        }
3672
3673    } else if (DeclaratorDecl *DD
3674                    = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
3675      SourceLocation StartLoc = DD->getSourceRange().getBegin();
3676      // Check that when we have multiple declarators in the same line,
3677      // that later ones do not override the previous ones.
3678      // If we have:
3679      // int Foo, Bar;
3680      // source ranges for both start at 'int', so 'Bar' will end up overriding
3681      // 'Foo' even though the cursor location was at 'Foo'.
3682      if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
3683        return CXChildVisit_Break;
3684      Data->VisitedDeclaratorDeclStartLoc = StartLoc;
3685
3686    } else if (ObjCPropertyImplDecl *PropImp
3687              = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
3688      (void)PropImp;
3689      // Check that when we have multiple @synthesize in the same line,
3690      // that later ones do not override the previous ones.
3691      // If we have:
3692      // @synthesize Foo, Bar;
3693      // source ranges for both start at '@', so 'Bar' will end up overriding
3694      // 'Foo' even though the cursor location was at 'Foo'.
3695      if (Data->VisitedObjCPropertyImplDecl)
3696        return CXChildVisit_Break;
3697      Data->VisitedObjCPropertyImplDecl = true;
3698    }
3699  }
3700
3701  if (clang_isExpression(cursor.kind) &&
3702      clang_isDeclaration(BestCursor->kind)) {
3703    if (Decl *D = getCursorDecl(*BestCursor)) {
3704      // Avoid having the cursor of an expression replace the declaration cursor
3705      // when the expression source range overlaps the declaration range.
3706      // This can happen for C++ constructor expressions whose range generally
3707      // include the variable declaration, e.g.:
3708      //  MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
3709      if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
3710          D->getLocation() == Data->TokenBeginLoc)
3711        return CXChildVisit_Break;
3712    }
3713  }
3714
3715  // If our current best cursor is the construction of a temporary object,
3716  // don't replace that cursor with a type reference, because we want
3717  // clang_getCursor() to point at the constructor.
3718  if (clang_isExpression(BestCursor->kind) &&
3719      isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3720      cursor.kind == CXCursor_TypeRef) {
3721    // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
3722    // as having the actual point on the type reference.
3723    *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
3724    return CXChildVisit_Recurse;
3725  }
3726
3727  *BestCursor = cursor;
3728  return CXChildVisit_Recurse;
3729}
3730
3731CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3732  if (!TU)
3733    return clang_getNullCursor();
3734
3735  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3736  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3737
3738  SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
3739  CXCursor Result = cxcursor::getCursor(TU, SLoc);
3740
3741  bool Logging = getenv("LIBCLANG_LOGGING");
3742  if (Logging) {
3743    CXFile SearchFile;
3744    unsigned SearchLine, SearchColumn;
3745    CXFile ResultFile;
3746    unsigned ResultLine, ResultColumn;
3747    CXString SearchFileName, ResultFileName, KindSpelling, USR;
3748    const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
3749    CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3750
3751    clang_getExpansionLocation(Loc, &SearchFile, &SearchLine, &SearchColumn, 0);
3752    clang_getExpansionLocation(ResultLoc, &ResultFile, &ResultLine,
3753                               &ResultColumn, 0);
3754    SearchFileName = clang_getFileName(SearchFile);
3755    ResultFileName = clang_getFileName(ResultFile);
3756    KindSpelling = clang_getCursorKindSpelling(Result.kind);
3757    USR = clang_getCursorUSR(Result);
3758    fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d):%s%s\n",
3759            clang_getCString(SearchFileName), SearchLine, SearchColumn,
3760            clang_getCString(KindSpelling),
3761            clang_getCString(ResultFileName), ResultLine, ResultColumn,
3762            clang_getCString(USR), IsDef);
3763    clang_disposeString(SearchFileName);
3764    clang_disposeString(ResultFileName);
3765    clang_disposeString(KindSpelling);
3766    clang_disposeString(USR);
3767
3768    CXCursor Definition = clang_getCursorDefinition(Result);
3769    if (!clang_equalCursors(Definition, clang_getNullCursor())) {
3770      CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
3771      CXString DefinitionKindSpelling
3772                                = clang_getCursorKindSpelling(Definition.kind);
3773      CXFile DefinitionFile;
3774      unsigned DefinitionLine, DefinitionColumn;
3775      clang_getExpansionLocation(DefinitionLoc, &DefinitionFile,
3776                                 &DefinitionLine, &DefinitionColumn, 0);
3777      CXString DefinitionFileName = clang_getFileName(DefinitionFile);
3778      fprintf(stderr, "  -> %s(%s:%d:%d)\n",
3779              clang_getCString(DefinitionKindSpelling),
3780              clang_getCString(DefinitionFileName),
3781              DefinitionLine, DefinitionColumn);
3782      clang_disposeString(DefinitionFileName);
3783      clang_disposeString(DefinitionKindSpelling);
3784    }
3785  }
3786
3787  return Result;
3788}
3789
3790CXCursor clang_getNullCursor(void) {
3791  return MakeCXCursorInvalid(CXCursor_InvalidFile);
3792}
3793
3794unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
3795  return X == Y;
3796}
3797
3798unsigned clang_hashCursor(CXCursor C) {
3799  unsigned Index = 0;
3800  if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
3801    Index = 1;
3802
3803  return llvm::DenseMapInfo<std::pair<unsigned, void*> >::getHashValue(
3804                                        std::make_pair(C.kind, C.data[Index]));
3805}
3806
3807unsigned clang_isInvalid(enum CXCursorKind K) {
3808  return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3809}
3810
3811unsigned clang_isDeclaration(enum CXCursorKind K) {
3812  return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3813}
3814
3815unsigned clang_isReference(enum CXCursorKind K) {
3816  return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3817}
3818
3819unsigned clang_isExpression(enum CXCursorKind K) {
3820  return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3821}
3822
3823unsigned clang_isStatement(enum CXCursorKind K) {
3824  return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3825}
3826
3827unsigned clang_isAttribute(enum CXCursorKind K) {
3828    return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
3829}
3830
3831unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3832  return K == CXCursor_TranslationUnit;
3833}
3834
3835unsigned clang_isPreprocessing(enum CXCursorKind K) {
3836  return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3837}
3838
3839unsigned clang_isUnexposed(enum CXCursorKind K) {
3840  switch (K) {
3841    case CXCursor_UnexposedDecl:
3842    case CXCursor_UnexposedExpr:
3843    case CXCursor_UnexposedStmt:
3844    case CXCursor_UnexposedAttr:
3845      return true;
3846    default:
3847      return false;
3848  }
3849}
3850
3851CXCursorKind clang_getCursorKind(CXCursor C) {
3852  return C.kind;
3853}
3854
3855CXSourceLocation clang_getCursorLocation(CXCursor C) {
3856  if (clang_isReference(C.kind)) {
3857    switch (C.kind) {
3858    case CXCursor_ObjCSuperClassRef: {
3859      std::pair<ObjCInterfaceDecl *, SourceLocation> P
3860        = getCursorObjCSuperClassRef(C);
3861      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3862    }
3863
3864    case CXCursor_ObjCProtocolRef: {
3865      std::pair<ObjCProtocolDecl *, SourceLocation> P
3866        = getCursorObjCProtocolRef(C);
3867      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3868    }
3869
3870    case CXCursor_ObjCClassRef: {
3871      std::pair<ObjCInterfaceDecl *, SourceLocation> P
3872        = getCursorObjCClassRef(C);
3873      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3874    }
3875
3876    case CXCursor_TypeRef: {
3877      std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
3878      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3879    }
3880
3881    case CXCursor_TemplateRef: {
3882      std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3883      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3884    }
3885
3886    case CXCursor_NamespaceRef: {
3887      std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3888      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3889    }
3890
3891    case CXCursor_MemberRef: {
3892      std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3893      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3894    }
3895
3896    case CXCursor_VariableRef: {
3897      std::pair<VarDecl *, SourceLocation> P = getCursorVariableRef(C);
3898      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3899    }
3900
3901    case CXCursor_CXXBaseSpecifier: {
3902      CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3903      if (!BaseSpec)
3904        return clang_getNullLocation();
3905
3906      if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3907        return cxloc::translateSourceLocation(getCursorContext(C),
3908                                            TSInfo->getTypeLoc().getBeginLoc());
3909
3910      return cxloc::translateSourceLocation(getCursorContext(C),
3911                                        BaseSpec->getLocStart());
3912    }
3913
3914    case CXCursor_LabelRef: {
3915      std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3916      return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3917    }
3918
3919    case CXCursor_OverloadedDeclRef:
3920      return cxloc::translateSourceLocation(getCursorContext(C),
3921                                          getCursorOverloadedDeclRef(C).second);
3922
3923    default:
3924      // FIXME: Need a way to enumerate all non-reference cases.
3925      llvm_unreachable("Missed a reference kind");
3926    }
3927  }
3928
3929  if (clang_isExpression(C.kind))
3930    return cxloc::translateSourceLocation(getCursorContext(C),
3931                                   getLocationFromExpr(getCursorExpr(C)));
3932
3933  if (clang_isStatement(C.kind))
3934    return cxloc::translateSourceLocation(getCursorContext(C),
3935                                          getCursorStmt(C)->getLocStart());
3936
3937  if (C.kind == CXCursor_PreprocessingDirective) {
3938    SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3939    return cxloc::translateSourceLocation(getCursorContext(C), L);
3940  }
3941
3942  if (C.kind == CXCursor_MacroExpansion) {
3943    SourceLocation L
3944      = cxcursor::getCursorMacroExpansion(C)->getSourceRange().getBegin();
3945    return cxloc::translateSourceLocation(getCursorContext(C), L);
3946  }
3947
3948  if (C.kind == CXCursor_MacroDefinition) {
3949    SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3950    return cxloc::translateSourceLocation(getCursorContext(C), L);
3951  }
3952
3953  if (C.kind == CXCursor_InclusionDirective) {
3954    SourceLocation L
3955      = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3956    return cxloc::translateSourceLocation(getCursorContext(C), L);
3957  }
3958
3959  if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
3960    return clang_getNullLocation();
3961
3962  Decl *D = getCursorDecl(C);
3963  if (!D)
3964    return clang_getNullLocation();
3965
3966  SourceLocation Loc = D->getLocation();
3967  // FIXME: Multiple variables declared in a single declaration
3968  // currently lack the information needed to correctly determine their
3969  // ranges when accounting for the type-specifier.  We use context
3970  // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3971  // and if so, whether it is the first decl.
3972  if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3973    if (!cxcursor::isFirstInDeclGroup(C))
3974      Loc = VD->getLocation();
3975  }
3976
3977  // For ObjC methods, give the start location of the method name.
3978  if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
3979    Loc = MD->getSelectorStartLoc();
3980
3981  return cxloc::translateSourceLocation(getCursorContext(C), Loc);
3982}
3983
3984} // end extern "C"
3985
3986CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
3987  assert(TU);
3988
3989  // Guard against an invalid SourceLocation, or we may assert in one
3990  // of the following calls.
3991  if (SLoc.isInvalid())
3992    return clang_getNullCursor();
3993
3994  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
3995
3996  // Translate the given source location to make it point at the beginning of
3997  // the token under the cursor.
3998  SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3999                                    CXXUnit->getASTContext().getLangOpts());
4000
4001  CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
4002  if (SLoc.isValid()) {
4003    GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
4004    CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
4005                            /*VisitPreprocessorLast=*/true,
4006                            /*VisitIncludedEntities=*/false,
4007                            SourceLocation(SLoc));
4008    CursorVis.visitFileRegion();
4009  }
4010
4011  return Result;
4012}
4013
4014static SourceRange getRawCursorExtent(CXCursor C) {
4015  if (clang_isReference(C.kind)) {
4016    switch (C.kind) {
4017    case CXCursor_ObjCSuperClassRef:
4018      return  getCursorObjCSuperClassRef(C).second;
4019
4020    case CXCursor_ObjCProtocolRef:
4021      return getCursorObjCProtocolRef(C).second;
4022
4023    case CXCursor_ObjCClassRef:
4024      return getCursorObjCClassRef(C).second;
4025
4026    case CXCursor_TypeRef:
4027      return getCursorTypeRef(C).second;
4028
4029    case CXCursor_TemplateRef:
4030      return getCursorTemplateRef(C).second;
4031
4032    case CXCursor_NamespaceRef:
4033      return getCursorNamespaceRef(C).second;
4034
4035    case CXCursor_MemberRef:
4036      return getCursorMemberRef(C).second;
4037
4038    case CXCursor_CXXBaseSpecifier:
4039      return getCursorCXXBaseSpecifier(C)->getSourceRange();
4040
4041    case CXCursor_LabelRef:
4042      return getCursorLabelRef(C).second;
4043
4044    case CXCursor_OverloadedDeclRef:
4045      return getCursorOverloadedDeclRef(C).second;
4046
4047    case CXCursor_VariableRef:
4048      return getCursorVariableRef(C).second;
4049
4050    default:
4051      // FIXME: Need a way to enumerate all non-reference cases.
4052      llvm_unreachable("Missed a reference kind");
4053    }
4054  }
4055
4056  if (clang_isExpression(C.kind))
4057    return getCursorExpr(C)->getSourceRange();
4058
4059  if (clang_isStatement(C.kind))
4060    return getCursorStmt(C)->getSourceRange();
4061
4062  if (clang_isAttribute(C.kind))
4063    return getCursorAttr(C)->getRange();
4064
4065  if (C.kind == CXCursor_PreprocessingDirective)
4066    return cxcursor::getCursorPreprocessingDirective(C);
4067
4068  if (C.kind == CXCursor_MacroExpansion) {
4069    ASTUnit *TU = getCursorASTUnit(C);
4070    SourceRange Range = cxcursor::getCursorMacroExpansion(C)->getSourceRange();
4071    return TU->mapRangeFromPreamble(Range);
4072  }
4073
4074  if (C.kind == CXCursor_MacroDefinition) {
4075    ASTUnit *TU = getCursorASTUnit(C);
4076    SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
4077    return TU->mapRangeFromPreamble(Range);
4078  }
4079
4080  if (C.kind == CXCursor_InclusionDirective) {
4081    ASTUnit *TU = getCursorASTUnit(C);
4082    SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
4083    return TU->mapRangeFromPreamble(Range);
4084  }
4085
4086  if (C.kind == CXCursor_TranslationUnit) {
4087    ASTUnit *TU = getCursorASTUnit(C);
4088    FileID MainID = TU->getSourceManager().getMainFileID();
4089    SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
4090    SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
4091    return SourceRange(Start, End);
4092  }
4093
4094  if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
4095    Decl *D = cxcursor::getCursorDecl(C);
4096    if (!D)
4097      return SourceRange();
4098
4099    SourceRange R = D->getSourceRange();
4100    // FIXME: Multiple variables declared in a single declaration
4101    // currently lack the information needed to correctly determine their
4102    // ranges when accounting for the type-specifier.  We use context
4103    // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4104    // and if so, whether it is the first decl.
4105    if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4106      if (!cxcursor::isFirstInDeclGroup(C))
4107        R.setBegin(VD->getLocation());
4108    }
4109    return R;
4110  }
4111  return SourceRange();
4112}
4113
4114/// \brief Retrieves the "raw" cursor extent, which is then extended to include
4115/// the decl-specifier-seq for declarations.
4116static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
4117  if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
4118    Decl *D = cxcursor::getCursorDecl(C);
4119    if (!D)
4120      return SourceRange();
4121
4122    SourceRange R = D->getSourceRange();
4123
4124    // Adjust the start of the location for declarations preceded by
4125    // declaration specifiers.
4126    SourceLocation StartLoc;
4127    if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
4128      if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
4129        StartLoc = TI->getTypeLoc().getLocStart();
4130    } else if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
4131      if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
4132        StartLoc = TI->getTypeLoc().getLocStart();
4133    }
4134
4135    if (StartLoc.isValid() && R.getBegin().isValid() &&
4136        SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
4137      R.setBegin(StartLoc);
4138
4139    // FIXME: Multiple variables declared in a single declaration
4140    // currently lack the information needed to correctly determine their
4141    // ranges when accounting for the type-specifier.  We use context
4142    // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
4143    // and if so, whether it is the first decl.
4144    if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4145      if (!cxcursor::isFirstInDeclGroup(C))
4146        R.setBegin(VD->getLocation());
4147    }
4148
4149    return R;
4150  }
4151
4152  return getRawCursorExtent(C);
4153}
4154
4155extern "C" {
4156
4157CXSourceRange clang_getCursorExtent(CXCursor C) {
4158  SourceRange R = getRawCursorExtent(C);
4159  if (R.isInvalid())
4160    return clang_getNullRange();
4161
4162  return cxloc::translateSourceRange(getCursorContext(C), R);
4163}
4164
4165CXCursor clang_getCursorReferenced(CXCursor C) {
4166  if (clang_isInvalid(C.kind))
4167    return clang_getNullCursor();
4168
4169  CXTranslationUnit tu = getCursorTU(C);
4170  if (clang_isDeclaration(C.kind)) {
4171    Decl *D = getCursorDecl(C);
4172    if (!D)
4173      return clang_getNullCursor();
4174    if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
4175      return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
4176    if (ObjCPropertyImplDecl *PropImpl =dyn_cast<ObjCPropertyImplDecl>(D))
4177      if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
4178        return MakeCXCursor(Property, tu);
4179
4180    return C;
4181  }
4182
4183  if (clang_isExpression(C.kind)) {
4184    Expr *E = getCursorExpr(C);
4185    Decl *D = getDeclFromExpr(E);
4186    if (D) {
4187      CXCursor declCursor = MakeCXCursor(D, tu);
4188      declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
4189                                               declCursor);
4190      return declCursor;
4191    }
4192
4193    if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
4194      return MakeCursorOverloadedDeclRef(Ovl, tu);
4195
4196    return clang_getNullCursor();
4197  }
4198
4199  if (clang_isStatement(C.kind)) {
4200    Stmt *S = getCursorStmt(C);
4201    if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
4202      if (LabelDecl *label = Goto->getLabel())
4203        if (LabelStmt *labelS = label->getStmt())
4204        return MakeCXCursor(labelS, getCursorDecl(C), tu);
4205
4206    return clang_getNullCursor();
4207  }
4208
4209  if (C.kind == CXCursor_MacroExpansion) {
4210    if (MacroDefinition *Def = getCursorMacroExpansion(C)->getDefinition())
4211      return MakeMacroDefinitionCursor(Def, tu);
4212  }
4213
4214  if (!clang_isReference(C.kind))
4215    return clang_getNullCursor();
4216
4217  switch (C.kind) {
4218    case CXCursor_ObjCSuperClassRef:
4219      return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
4220
4221    case CXCursor_ObjCProtocolRef: {
4222      ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
4223      if (ObjCProtocolDecl *Def = Prot->getDefinition())
4224        return MakeCXCursor(Def, tu);
4225
4226      return MakeCXCursor(Prot, tu);
4227    }
4228
4229    case CXCursor_ObjCClassRef: {
4230      ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
4231      if (ObjCInterfaceDecl *Def = Class->getDefinition())
4232        return MakeCXCursor(Def, tu);
4233
4234      return MakeCXCursor(Class, tu);
4235    }
4236
4237    case CXCursor_TypeRef:
4238      return MakeCXCursor(getCursorTypeRef(C).first, tu );
4239
4240    case CXCursor_TemplateRef:
4241      return MakeCXCursor(getCursorTemplateRef(C).first, tu );
4242
4243    case CXCursor_NamespaceRef:
4244      return MakeCXCursor(getCursorNamespaceRef(C).first, tu );
4245
4246    case CXCursor_MemberRef:
4247      return MakeCXCursor(getCursorMemberRef(C).first, tu );
4248
4249    case CXCursor_CXXBaseSpecifier: {
4250      CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
4251      return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
4252                                                         tu ));
4253    }
4254
4255    case CXCursor_LabelRef:
4256      // FIXME: We end up faking the "parent" declaration here because we
4257      // don't want to make CXCursor larger.
4258      return MakeCXCursor(getCursorLabelRef(C).first,
4259               static_cast<ASTUnit*>(tu->TUData)->getASTContext()
4260                          .getTranslationUnitDecl(),
4261                          tu);
4262
4263    case CXCursor_OverloadedDeclRef:
4264      return C;
4265
4266    case CXCursor_VariableRef:
4267      return MakeCXCursor(getCursorVariableRef(C).first, tu);
4268
4269    default:
4270      // We would prefer to enumerate all non-reference cursor kinds here.
4271      llvm_unreachable("Unhandled reference cursor kind");
4272  }
4273}
4274
4275CXCursor clang_getCursorDefinition(CXCursor C) {
4276  if (clang_isInvalid(C.kind))
4277    return clang_getNullCursor();
4278
4279  CXTranslationUnit TU = getCursorTU(C);
4280
4281  bool WasReference = false;
4282  if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
4283    C = clang_getCursorReferenced(C);
4284    WasReference = true;
4285  }
4286
4287  if (C.kind == CXCursor_MacroExpansion)
4288    return clang_getCursorReferenced(C);
4289
4290  if (!clang_isDeclaration(C.kind))
4291    return clang_getNullCursor();
4292
4293  Decl *D = getCursorDecl(C);
4294  if (!D)
4295    return clang_getNullCursor();
4296
4297  switch (D->getKind()) {
4298  // Declaration kinds that don't really separate the notions of
4299  // declaration and definition.
4300  case Decl::Namespace:
4301  case Decl::Typedef:
4302  case Decl::TypeAlias:
4303  case Decl::TypeAliasTemplate:
4304  case Decl::TemplateTypeParm:
4305  case Decl::EnumConstant:
4306  case Decl::Field:
4307  case Decl::IndirectField:
4308  case Decl::ObjCIvar:
4309  case Decl::ObjCAtDefsField:
4310  case Decl::ImplicitParam:
4311  case Decl::ParmVar:
4312  case Decl::NonTypeTemplateParm:
4313  case Decl::TemplateTemplateParm:
4314  case Decl::ObjCCategoryImpl:
4315  case Decl::ObjCImplementation:
4316  case Decl::AccessSpec:
4317  case Decl::LinkageSpec:
4318  case Decl::ObjCPropertyImpl:
4319  case Decl::FileScopeAsm:
4320  case Decl::StaticAssert:
4321  case Decl::Block:
4322  case Decl::Label:  // FIXME: Is this right??
4323  case Decl::ClassScopeFunctionSpecialization:
4324  case Decl::Import:
4325    return C;
4326
4327  // Declaration kinds that don't make any sense here, but are
4328  // nonetheless harmless.
4329  case Decl::TranslationUnit:
4330    break;
4331
4332  // Declaration kinds for which the definition is not resolvable.
4333  case Decl::UnresolvedUsingTypename:
4334  case Decl::UnresolvedUsingValue:
4335    break;
4336
4337  case Decl::UsingDirective:
4338    return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
4339                        TU);
4340
4341  case Decl::NamespaceAlias:
4342    return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
4343
4344  case Decl::Enum:
4345  case Decl::Record:
4346  case Decl::CXXRecord:
4347  case Decl::ClassTemplateSpecialization:
4348  case Decl::ClassTemplatePartialSpecialization:
4349    if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
4350      return MakeCXCursor(Def, TU);
4351    return clang_getNullCursor();
4352
4353  case Decl::Function:
4354  case Decl::CXXMethod:
4355  case Decl::CXXConstructor:
4356  case Decl::CXXDestructor:
4357  case Decl::CXXConversion: {
4358    const FunctionDecl *Def = 0;
4359    if (cast<FunctionDecl>(D)->getBody(Def))
4360      return MakeCXCursor(const_cast<FunctionDecl *>(Def), TU);
4361    return clang_getNullCursor();
4362  }
4363
4364  case Decl::Var: {
4365    // Ask the variable if it has a definition.
4366    if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
4367      return MakeCXCursor(Def, TU);
4368    return clang_getNullCursor();
4369  }
4370
4371  case Decl::FunctionTemplate: {
4372    const FunctionDecl *Def = 0;
4373    if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
4374      return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
4375    return clang_getNullCursor();
4376  }
4377
4378  case Decl::ClassTemplate: {
4379    if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
4380                                                            ->getDefinition())
4381      return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
4382                          TU);
4383    return clang_getNullCursor();
4384  }
4385
4386  case Decl::Using:
4387    return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
4388                                       D->getLocation(), TU);
4389
4390  case Decl::UsingShadow:
4391    return clang_getCursorDefinition(
4392                       MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
4393                                    TU));
4394
4395  case Decl::ObjCMethod: {
4396    ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
4397    if (Method->isThisDeclarationADefinition())
4398      return C;
4399
4400    // Dig out the method definition in the associated
4401    // @implementation, if we have it.
4402    // FIXME: The ASTs should make finding the definition easier.
4403    if (ObjCInterfaceDecl *Class
4404                       = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
4405      if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
4406        if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
4407                                                  Method->isInstanceMethod()))
4408          if (Def->isThisDeclarationADefinition())
4409            return MakeCXCursor(Def, TU);
4410
4411    return clang_getNullCursor();
4412  }
4413
4414  case Decl::ObjCCategory:
4415    if (ObjCCategoryImplDecl *Impl
4416                               = cast<ObjCCategoryDecl>(D)->getImplementation())
4417      return MakeCXCursor(Impl, TU);
4418    return clang_getNullCursor();
4419
4420  case Decl::ObjCProtocol:
4421    if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
4422      return MakeCXCursor(Def, TU);
4423    return clang_getNullCursor();
4424
4425  case Decl::ObjCInterface: {
4426    // There are two notions of a "definition" for an Objective-C
4427    // class: the interface and its implementation. When we resolved a
4428    // reference to an Objective-C class, produce the @interface as
4429    // the definition; when we were provided with the interface,
4430    // produce the @implementation as the definition.
4431    ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
4432    if (WasReference) {
4433      if (ObjCInterfaceDecl *Def = IFace->getDefinition())
4434        return MakeCXCursor(Def, TU);
4435    } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
4436      return MakeCXCursor(Impl, TU);
4437    return clang_getNullCursor();
4438  }
4439
4440  case Decl::ObjCProperty:
4441    // FIXME: We don't really know where to find the
4442    // ObjCPropertyImplDecls that implement this property.
4443    return clang_getNullCursor();
4444
4445  case Decl::ObjCCompatibleAlias:
4446    if (ObjCInterfaceDecl *Class
4447          = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
4448      if (ObjCInterfaceDecl *Def = Class->getDefinition())
4449        return MakeCXCursor(Def, TU);
4450
4451    return clang_getNullCursor();
4452
4453  case Decl::Friend:
4454    if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
4455      return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
4456    return clang_getNullCursor();
4457
4458  case Decl::FriendTemplate:
4459    if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
4460      return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
4461    return clang_getNullCursor();
4462  }
4463
4464  return clang_getNullCursor();
4465}
4466
4467unsigned clang_isCursorDefinition(CXCursor C) {
4468  if (!clang_isDeclaration(C.kind))
4469    return 0;
4470
4471  return clang_getCursorDefinition(C) == C;
4472}
4473
4474CXCursor clang_getCanonicalCursor(CXCursor C) {
4475  if (!clang_isDeclaration(C.kind))
4476    return C;
4477
4478  if (Decl *D = getCursorDecl(C)) {
4479    if (ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
4480      if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
4481        return MakeCXCursor(CatD, getCursorTU(C));
4482
4483    if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4484      if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
4485        return MakeCXCursor(IFD, getCursorTU(C));
4486
4487    return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
4488  }
4489
4490  return C;
4491}
4492
4493int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
4494  return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
4495}
4496
4497unsigned clang_getNumOverloadedDecls(CXCursor C) {
4498  if (C.kind != CXCursor_OverloadedDeclRef)
4499    return 0;
4500
4501  OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4502  if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4503    return E->getNumDecls();
4504
4505  if (OverloadedTemplateStorage *S
4506                              = Storage.dyn_cast<OverloadedTemplateStorage*>())
4507    return S->size();
4508
4509  Decl *D = Storage.get<Decl*>();
4510  if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
4511    return Using->shadow_size();
4512
4513  return 0;
4514}
4515
4516CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
4517  if (cursor.kind != CXCursor_OverloadedDeclRef)
4518    return clang_getNullCursor();
4519
4520  if (index >= clang_getNumOverloadedDecls(cursor))
4521    return clang_getNullCursor();
4522
4523  CXTranslationUnit TU = getCursorTU(cursor);
4524  OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
4525  if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
4526    return MakeCXCursor(E->decls_begin()[index], TU);
4527
4528  if (OverloadedTemplateStorage *S
4529                              = Storage.dyn_cast<OverloadedTemplateStorage*>())
4530    return MakeCXCursor(S->begin()[index], TU);
4531
4532  Decl *D = Storage.get<Decl*>();
4533  if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
4534    // FIXME: This is, unfortunately, linear time.
4535    UsingDecl::shadow_iterator Pos = Using->shadow_begin();
4536    std::advance(Pos, index);
4537    return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
4538  }
4539
4540  return clang_getNullCursor();
4541}
4542
4543void clang_getDefinitionSpellingAndExtent(CXCursor C,
4544                                          const char **startBuf,
4545                                          const char **endBuf,
4546                                          unsigned *startLine,
4547                                          unsigned *startColumn,
4548                                          unsigned *endLine,
4549                                          unsigned *endColumn) {
4550  assert(getCursorDecl(C) && "CXCursor has null decl");
4551  NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
4552  FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
4553  CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
4554
4555  SourceManager &SM = FD->getASTContext().getSourceManager();
4556  *startBuf = SM.getCharacterData(Body->getLBracLoc());
4557  *endBuf = SM.getCharacterData(Body->getRBracLoc());
4558  *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
4559  *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
4560  *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
4561  *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
4562}
4563
4564
4565CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
4566                                                unsigned PieceIndex) {
4567  RefNamePieces Pieces;
4568
4569  switch (C.kind) {
4570  case CXCursor_MemberRefExpr:
4571    if (MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
4572      Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
4573                           E->getQualifierLoc().getSourceRange());
4574    break;
4575
4576  case CXCursor_DeclRefExpr:
4577    if (DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C)))
4578      Pieces = buildPieces(NameFlags, false, E->getNameInfo(),
4579                           E->getQualifierLoc().getSourceRange(),
4580                           E->getOptionalExplicitTemplateArgs());
4581    break;
4582
4583  case CXCursor_CallExpr:
4584    if (CXXOperatorCallExpr *OCE =
4585        dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
4586      Expr *Callee = OCE->getCallee();
4587      if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
4588        Callee = ICE->getSubExpr();
4589
4590      if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
4591        Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
4592                             DRE->getQualifierLoc().getSourceRange());
4593    }
4594    break;
4595
4596  default:
4597    break;
4598  }
4599
4600  if (Pieces.empty()) {
4601    if (PieceIndex == 0)
4602      return clang_getCursorExtent(C);
4603  } else if (PieceIndex < Pieces.size()) {
4604      SourceRange R = Pieces[PieceIndex];
4605      if (R.isValid())
4606        return cxloc::translateSourceRange(getCursorContext(C), R);
4607  }
4608
4609  return clang_getNullRange();
4610}
4611
4612void clang_enableStackTraces(void) {
4613  llvm::sys::PrintStackTraceOnErrorSignal();
4614}
4615
4616void clang_executeOnThread(void (*fn)(void*), void *user_data,
4617                           unsigned stack_size) {
4618  llvm::llvm_execute_on_thread(fn, user_data, stack_size);
4619}
4620
4621} // end: extern "C"
4622
4623//===----------------------------------------------------------------------===//
4624// Token-based Operations.
4625//===----------------------------------------------------------------------===//
4626
4627/* CXToken layout:
4628 *   int_data[0]: a CXTokenKind
4629 *   int_data[1]: starting token location
4630 *   int_data[2]: token length
4631 *   int_data[3]: reserved
4632 *   ptr_data: for identifiers and keywords, an IdentifierInfo*.
4633 *   otherwise unused.
4634 */
4635extern "C" {
4636
4637CXTokenKind clang_getTokenKind(CXToken CXTok) {
4638  return static_cast<CXTokenKind>(CXTok.int_data[0]);
4639}
4640
4641CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
4642  switch (clang_getTokenKind(CXTok)) {
4643  case CXToken_Identifier:
4644  case CXToken_Keyword:
4645    // We know we have an IdentifierInfo*, so use that.
4646    return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
4647                            ->getNameStart());
4648
4649  case CXToken_Literal: {
4650    // We have stashed the starting pointer in the ptr_data field. Use it.
4651    const char *Text = static_cast<const char *>(CXTok.ptr_data);
4652    return createCXString(StringRef(Text, CXTok.int_data[2]));
4653  }
4654
4655  case CXToken_Punctuation:
4656  case CXToken_Comment:
4657    break;
4658  }
4659
4660  // We have to find the starting buffer pointer the hard way, by
4661  // deconstructing the source location.
4662  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4663  if (!CXXUnit)
4664    return createCXString("");
4665
4666  SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
4667  std::pair<FileID, unsigned> LocInfo
4668    = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
4669  bool Invalid = false;
4670  StringRef Buffer
4671    = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
4672  if (Invalid)
4673    return createCXString("");
4674
4675  return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
4676}
4677
4678CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
4679  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4680  if (!CXXUnit)
4681    return clang_getNullLocation();
4682
4683  return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
4684                        SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4685}
4686
4687CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
4688  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4689  if (!CXXUnit)
4690    return clang_getNullRange();
4691
4692  return cxloc::translateSourceRange(CXXUnit->getASTContext(),
4693                        SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
4694}
4695
4696static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
4697                      SmallVectorImpl<CXToken> &CXTokens) {
4698  SourceManager &SourceMgr = CXXUnit->getSourceManager();
4699  std::pair<FileID, unsigned> BeginLocInfo
4700    = SourceMgr.getDecomposedLoc(Range.getBegin());
4701  std::pair<FileID, unsigned> EndLocInfo
4702    = SourceMgr.getDecomposedLoc(Range.getEnd());
4703
4704  // Cannot tokenize across files.
4705  if (BeginLocInfo.first != EndLocInfo.first)
4706    return;
4707
4708  // Create a lexer
4709  bool Invalid = false;
4710  StringRef Buffer
4711    = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
4712  if (Invalid)
4713    return;
4714
4715  Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4716            CXXUnit->getASTContext().getLangOpts(),
4717            Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
4718  Lex.SetCommentRetentionState(true);
4719
4720  // Lex tokens until we hit the end of the range.
4721  const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
4722  Token Tok;
4723  bool previousWasAt = false;
4724  do {
4725    // Lex the next token
4726    Lex.LexFromRawLexer(Tok);
4727    if (Tok.is(tok::eof))
4728      break;
4729
4730    // Initialize the CXToken.
4731    CXToken CXTok;
4732
4733    //   - Common fields
4734    CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
4735    CXTok.int_data[2] = Tok.getLength();
4736    CXTok.int_data[3] = 0;
4737
4738    //   - Kind-specific fields
4739    if (Tok.isLiteral()) {
4740      CXTok.int_data[0] = CXToken_Literal;
4741      CXTok.ptr_data = (void *)Tok.getLiteralData();
4742    } else if (Tok.is(tok::raw_identifier)) {
4743      // Lookup the identifier to determine whether we have a keyword.
4744      IdentifierInfo *II
4745        = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
4746
4747      if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
4748        CXTok.int_data[0] = CXToken_Keyword;
4749      }
4750      else {
4751        CXTok.int_data[0] = Tok.is(tok::identifier)
4752          ? CXToken_Identifier
4753          : CXToken_Keyword;
4754      }
4755      CXTok.ptr_data = II;
4756    } else if (Tok.is(tok::comment)) {
4757      CXTok.int_data[0] = CXToken_Comment;
4758      CXTok.ptr_data = 0;
4759    } else {
4760      CXTok.int_data[0] = CXToken_Punctuation;
4761      CXTok.ptr_data = 0;
4762    }
4763    CXTokens.push_back(CXTok);
4764    previousWasAt = Tok.is(tok::at);
4765  } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
4766}
4767
4768void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
4769                    CXToken **Tokens, unsigned *NumTokens) {
4770  if (Tokens)
4771    *Tokens = 0;
4772  if (NumTokens)
4773    *NumTokens = 0;
4774
4775  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
4776  if (!CXXUnit || !Tokens || !NumTokens)
4777    return;
4778
4779  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4780
4781  SourceRange R = cxloc::translateCXSourceRange(Range);
4782  if (R.isInvalid())
4783    return;
4784
4785  SmallVector<CXToken, 32> CXTokens;
4786  getTokens(CXXUnit, R, CXTokens);
4787
4788  if (CXTokens.empty())
4789    return;
4790
4791  *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
4792  memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
4793  *NumTokens = CXTokens.size();
4794}
4795
4796void clang_disposeTokens(CXTranslationUnit TU,
4797                         CXToken *Tokens, unsigned NumTokens) {
4798  free(Tokens);
4799}
4800
4801} // end: extern "C"
4802
4803//===----------------------------------------------------------------------===//
4804// Token annotation APIs.
4805//===----------------------------------------------------------------------===//
4806
4807typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
4808static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4809                                                     CXCursor parent,
4810                                                     CXClientData client_data);
4811namespace {
4812class AnnotateTokensWorker {
4813  AnnotateTokensData &Annotated;
4814  CXToken *Tokens;
4815  CXCursor *Cursors;
4816  unsigned NumTokens;
4817  unsigned TokIdx;
4818  unsigned PreprocessingTokIdx;
4819  CursorVisitor AnnotateVis;
4820  SourceManager &SrcMgr;
4821  bool HasContextSensitiveKeywords;
4822
4823  bool MoreTokens() const { return TokIdx < NumTokens; }
4824  unsigned NextToken() const { return TokIdx; }
4825  void AdvanceToken() { ++TokIdx; }
4826  SourceLocation GetTokenLoc(unsigned tokI) {
4827    return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
4828  }
4829  bool isFunctionMacroToken(unsigned tokI) const {
4830    return Tokens[tokI].int_data[3] != 0;
4831  }
4832  SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
4833    return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[3]);
4834  }
4835
4836  void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
4837  void annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
4838                                             SourceRange);
4839
4840public:
4841  AnnotateTokensWorker(AnnotateTokensData &annotated,
4842                       CXToken *tokens, CXCursor *cursors, unsigned numTokens,
4843                       CXTranslationUnit tu, SourceRange RegionOfInterest)
4844    : Annotated(annotated), Tokens(tokens), Cursors(cursors),
4845      NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
4846      AnnotateVis(tu,
4847                  AnnotateTokensVisitor, this,
4848                  /*VisitPreprocessorLast=*/true,
4849                  /*VisitIncludedEntities=*/false,
4850                  RegionOfInterest),
4851      SrcMgr(static_cast<ASTUnit*>(tu->TUData)->getSourceManager()),
4852      HasContextSensitiveKeywords(false) { }
4853
4854  void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
4855  enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
4856  void AnnotateTokens();
4857
4858  /// \brief Determine whether the annotator saw any cursors that have
4859  /// context-sensitive keywords.
4860  bool hasContextSensitiveKeywords() const {
4861    return HasContextSensitiveKeywords;
4862  }
4863};
4864}
4865
4866void AnnotateTokensWorker::AnnotateTokens() {
4867  // Walk the AST within the region of interest, annotating tokens
4868  // along the way.
4869  AnnotateVis.visitFileRegion();
4870
4871  for (unsigned I = 0 ; I < TokIdx ; ++I) {
4872    AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4873    if (Pos != Annotated.end() &&
4874        (clang_isInvalid(Cursors[I].kind) ||
4875         Pos->second.kind != CXCursor_PreprocessingDirective))
4876      Cursors[I] = Pos->second;
4877  }
4878
4879  // Finish up annotating any tokens left.
4880  if (!MoreTokens())
4881    return;
4882
4883  const CXCursor &C = clang_getNullCursor();
4884  for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4885    if (I < PreprocessingTokIdx && clang_isPreprocessing(Cursors[I].kind))
4886      continue;
4887
4888    AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4889    Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
4890  }
4891}
4892
4893/// \brief It annotates and advances tokens with a cursor until the comparison
4894//// between the cursor location and the source range is the same as
4895/// \arg compResult.
4896///
4897/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
4898/// Pass RangeOverlap to annotate tokens inside a range.
4899void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
4900                                               RangeComparisonResult compResult,
4901                                               SourceRange range) {
4902  while (MoreTokens()) {
4903    const unsigned I = NextToken();
4904    if (isFunctionMacroToken(I))
4905      return annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range);
4906
4907    SourceLocation TokLoc = GetTokenLoc(I);
4908    if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4909      Cursors[I] = updateC;
4910      AdvanceToken();
4911      continue;
4912    }
4913    break;
4914  }
4915}
4916
4917/// \brief Special annotation handling for macro argument tokens.
4918void AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
4919                                               CXCursor updateC,
4920                                               RangeComparisonResult compResult,
4921                                               SourceRange range) {
4922  assert(MoreTokens());
4923  assert(isFunctionMacroToken(NextToken()) &&
4924         "Should be called only for macro arg tokens");
4925
4926  // This works differently than annotateAndAdvanceTokens; because expanded
4927  // macro arguments can have arbitrary translation-unit source order, we do not
4928  // advance the token index one by one until a token fails the range test.
4929  // We only advance once past all of the macro arg tokens if all of them
4930  // pass the range test. If one of them fails we keep the token index pointing
4931  // at the start of the macro arg tokens so that the failing token will be
4932  // annotated by a subsequent annotation try.
4933
4934  bool atLeastOneCompFail = false;
4935
4936  unsigned I = NextToken();
4937  for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
4938    SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
4939    if (TokLoc.isFileID())
4940      continue; // not macro arg token, it's parens or comma.
4941    if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
4942      if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
4943        Cursors[I] = updateC;
4944    } else
4945      atLeastOneCompFail = true;
4946  }
4947
4948  if (!atLeastOneCompFail)
4949    TokIdx = I; // All of the tokens were handled, advance beyond all of them.
4950}
4951
4952enum CXChildVisitResult
4953AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
4954  CXSourceLocation Loc = clang_getCursorLocation(cursor);
4955  SourceRange cursorRange = getRawCursorExtent(cursor);
4956  if (cursorRange.isInvalid())
4957    return CXChildVisit_Recurse;
4958
4959  if (!HasContextSensitiveKeywords) {
4960    // Objective-C properties can have context-sensitive keywords.
4961    if (cursor.kind == CXCursor_ObjCPropertyDecl) {
4962      if (ObjCPropertyDecl *Property
4963                  = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
4964        HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
4965    }
4966    // Objective-C methods can have context-sensitive keywords.
4967    else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
4968             cursor.kind == CXCursor_ObjCClassMethodDecl) {
4969      if (ObjCMethodDecl *Method
4970            = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
4971        if (Method->getObjCDeclQualifier())
4972          HasContextSensitiveKeywords = true;
4973        else {
4974          for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
4975                                           PEnd = Method->param_end();
4976               P != PEnd; ++P) {
4977            if ((*P)->getObjCDeclQualifier()) {
4978              HasContextSensitiveKeywords = true;
4979              break;
4980            }
4981          }
4982        }
4983      }
4984    }
4985    // C++ methods can have context-sensitive keywords.
4986    else if (cursor.kind == CXCursor_CXXMethod) {
4987      if (CXXMethodDecl *Method
4988                  = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
4989        if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
4990          HasContextSensitiveKeywords = true;
4991      }
4992    }
4993    // C++ classes can have context-sensitive keywords.
4994    else if (cursor.kind == CXCursor_StructDecl ||
4995             cursor.kind == CXCursor_ClassDecl ||
4996             cursor.kind == CXCursor_ClassTemplate ||
4997             cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
4998      if (Decl *D = getCursorDecl(cursor))
4999        if (D->hasAttr<FinalAttr>())
5000          HasContextSensitiveKeywords = true;
5001    }
5002  }
5003
5004  if (clang_isPreprocessing(cursor.kind)) {
5005    // For macro expansions, just note where the beginning of the macro
5006    // expansion occurs.
5007    if (cursor.kind == CXCursor_MacroExpansion) {
5008      Annotated[Loc.int_data] = cursor;
5009      return CXChildVisit_Recurse;
5010    }
5011
5012    // Items in the preprocessing record are kept separate from items in
5013    // declarations, so we keep a separate token index.
5014    unsigned SavedTokIdx = TokIdx;
5015    TokIdx = PreprocessingTokIdx;
5016
5017    // Skip tokens up until we catch up to the beginning of the preprocessing
5018    // entry.
5019    while (MoreTokens()) {
5020      const unsigned I = NextToken();
5021      SourceLocation TokLoc = GetTokenLoc(I);
5022      switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
5023      case RangeBefore:
5024        AdvanceToken();
5025        continue;
5026      case RangeAfter:
5027      case RangeOverlap:
5028        break;
5029      }
5030      break;
5031    }
5032
5033    // Look at all of the tokens within this range.
5034    while (MoreTokens()) {
5035      const unsigned I = NextToken();
5036      SourceLocation TokLoc = GetTokenLoc(I);
5037      switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
5038      case RangeBefore:
5039        llvm_unreachable("Infeasible");
5040      case RangeAfter:
5041        break;
5042      case RangeOverlap:
5043        Cursors[I] = cursor;
5044        AdvanceToken();
5045        continue;
5046      }
5047      break;
5048    }
5049
5050    // Save the preprocessing token index; restore the non-preprocessing
5051    // token index.
5052    PreprocessingTokIdx = TokIdx;
5053    TokIdx = SavedTokIdx;
5054    return CXChildVisit_Recurse;
5055  }
5056
5057  if (cursorRange.isInvalid())
5058    return CXChildVisit_Continue;
5059
5060  SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
5061
5062  // Adjust the annotated range based specific declarations.
5063  const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
5064  if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
5065    Decl *D = cxcursor::getCursorDecl(cursor);
5066
5067    SourceLocation StartLoc;
5068    if (const DeclaratorDecl *DD = dyn_cast_or_null<DeclaratorDecl>(D)) {
5069      if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
5070        StartLoc = TI->getTypeLoc().getLocStart();
5071    } else if (TypedefDecl *Typedef = dyn_cast_or_null<TypedefDecl>(D)) {
5072      if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
5073        StartLoc = TI->getTypeLoc().getLocStart();
5074    }
5075
5076    if (StartLoc.isValid() && L.isValid() &&
5077        SrcMgr.isBeforeInTranslationUnit(StartLoc, L))
5078      cursorRange.setBegin(StartLoc);
5079  }
5080
5081  // If the location of the cursor occurs within a macro instantiation, record
5082  // the spelling location of the cursor in our annotation map.  We can then
5083  // paper over the token labelings during a post-processing step to try and
5084  // get cursor mappings for tokens that are the *arguments* of a macro
5085  // instantiation.
5086  if (L.isMacroID()) {
5087    unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
5088    // Only invalidate the old annotation if it isn't part of a preprocessing
5089    // directive.  Here we assume that the default construction of CXCursor
5090    // results in CXCursor.kind being an initialized value (i.e., 0).  If
5091    // this isn't the case, we can fix by doing lookup + insertion.
5092
5093    CXCursor &oldC = Annotated[rawEncoding];
5094    if (!clang_isPreprocessing(oldC.kind))
5095      oldC = cursor;
5096  }
5097
5098  const enum CXCursorKind K = clang_getCursorKind(parent);
5099  const CXCursor updateC =
5100    (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
5101     ? clang_getNullCursor() : parent;
5102
5103  annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
5104
5105  // Avoid having the cursor of an expression "overwrite" the annotation of the
5106  // variable declaration that it belongs to.
5107  // This can happen for C++ constructor expressions whose range generally
5108  // include the variable declaration, e.g.:
5109  //  MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
5110  if (clang_isExpression(cursorK)) {
5111    Expr *E = getCursorExpr(cursor);
5112    if (Decl *D = getCursorParentDecl(cursor)) {
5113      const unsigned I = NextToken();
5114      if (E->getLocStart().isValid() && D->getLocation().isValid() &&
5115          E->getLocStart() == D->getLocation() &&
5116          E->getLocStart() == GetTokenLoc(I)) {
5117        Cursors[I] = updateC;
5118        AdvanceToken();
5119      }
5120    }
5121  }
5122
5123  // Visit children to get their cursor information.
5124  const unsigned BeforeChildren = NextToken();
5125  VisitChildren(cursor);
5126  const unsigned AfterChildren = NextToken();
5127
5128  // Scan the tokens that are at the end of the cursor, but are not captured
5129  // but the child cursors.
5130  annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
5131
5132  // Scan the tokens that are at the beginning of the cursor, but are not
5133  // capture by the child cursors.
5134  for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
5135    if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
5136      break;
5137
5138    Cursors[I] = cursor;
5139  }
5140
5141  return CXChildVisit_Continue;
5142}
5143
5144static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
5145                                                     CXCursor parent,
5146                                                     CXClientData client_data) {
5147  return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
5148}
5149
5150namespace {
5151
5152/// \brief Uses the macro expansions in the preprocessing record to find
5153/// and mark tokens that are macro arguments. This info is used by the
5154/// AnnotateTokensWorker.
5155class MarkMacroArgTokensVisitor {
5156  SourceManager &SM;
5157  CXToken *Tokens;
5158  unsigned NumTokens;
5159  unsigned CurIdx;
5160
5161public:
5162  MarkMacroArgTokensVisitor(SourceManager &SM,
5163                            CXToken *tokens, unsigned numTokens)
5164    : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
5165
5166  CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
5167    if (cursor.kind != CXCursor_MacroExpansion)
5168      return CXChildVisit_Continue;
5169
5170    SourceRange macroRange = getCursorMacroExpansion(cursor)->getSourceRange();
5171    if (macroRange.getBegin() == macroRange.getEnd())
5172      return CXChildVisit_Continue; // it's not a function macro.
5173
5174    for (; CurIdx < NumTokens; ++CurIdx) {
5175      if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
5176                                        macroRange.getBegin()))
5177        break;
5178    }
5179
5180    if (CurIdx == NumTokens)
5181      return CXChildVisit_Break;
5182
5183    for (; CurIdx < NumTokens; ++CurIdx) {
5184      SourceLocation tokLoc = getTokenLoc(CurIdx);
5185      if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
5186        break;
5187
5188      setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
5189    }
5190
5191    if (CurIdx == NumTokens)
5192      return CXChildVisit_Break;
5193
5194    return CXChildVisit_Continue;
5195  }
5196
5197private:
5198  SourceLocation getTokenLoc(unsigned tokI) {
5199    return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
5200  }
5201
5202  void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
5203    // The third field is reserved and currently not used. Use it here
5204    // to mark macro arg expanded tokens with their expanded locations.
5205    Tokens[tokI].int_data[3] = loc.getRawEncoding();
5206  }
5207};
5208
5209} // end anonymous namespace
5210
5211static CXChildVisitResult
5212MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
5213                                  CXClientData client_data) {
5214  return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
5215                                                                     parent);
5216}
5217
5218namespace {
5219  struct clang_annotateTokens_Data {
5220    CXTranslationUnit TU;
5221    ASTUnit *CXXUnit;
5222    CXToken *Tokens;
5223    unsigned NumTokens;
5224    CXCursor *Cursors;
5225  };
5226}
5227
5228static void annotatePreprocessorTokens(CXTranslationUnit TU,
5229                                       SourceRange RegionOfInterest,
5230                                       AnnotateTokensData &Annotated) {
5231  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
5232
5233  SourceManager &SourceMgr = CXXUnit->getSourceManager();
5234  std::pair<FileID, unsigned> BeginLocInfo
5235    = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
5236  std::pair<FileID, unsigned> EndLocInfo
5237    = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
5238
5239  if (BeginLocInfo.first != EndLocInfo.first)
5240    return;
5241
5242  StringRef Buffer;
5243  bool Invalid = false;
5244  Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
5245  if (Buffer.empty() || Invalid)
5246    return;
5247
5248  Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
5249            CXXUnit->getASTContext().getLangOpts(),
5250            Buffer.begin(), Buffer.data() + BeginLocInfo.second,
5251            Buffer.end());
5252  Lex.SetCommentRetentionState(true);
5253
5254  // Lex tokens in raw mode until we hit the end of the range, to avoid
5255  // entering #includes or expanding macros.
5256  while (true) {
5257    Token Tok;
5258    Lex.LexFromRawLexer(Tok);
5259
5260  reprocess:
5261    if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
5262      // We have found a preprocessing directive. Gobble it up so that we
5263      // don't see it while preprocessing these tokens later, but keep track
5264      // of all of the token locations inside this preprocessing directive so
5265      // that we can annotate them appropriately.
5266      //
5267      // FIXME: Some simple tests here could identify macro definitions and
5268      // #undefs, to provide specific cursor kinds for those.
5269      SmallVector<SourceLocation, 32> Locations;
5270      do {
5271        Locations.push_back(Tok.getLocation());
5272        Lex.LexFromRawLexer(Tok);
5273      } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
5274
5275      using namespace cxcursor;
5276      CXCursor Cursor
5277      = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
5278                                                     Locations.back()),
5279                                         TU);
5280      for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
5281        Annotated[Locations[I].getRawEncoding()] = Cursor;
5282      }
5283
5284      if (Tok.isAtStartOfLine())
5285        goto reprocess;
5286
5287      continue;
5288    }
5289
5290    if (Tok.is(tok::eof))
5291      break;
5292  }
5293}
5294
5295// This gets run a separate thread to avoid stack blowout.
5296static void clang_annotateTokensImpl(void *UserData) {
5297  CXTranslationUnit TU = ((clang_annotateTokens_Data*)UserData)->TU;
5298  ASTUnit *CXXUnit = ((clang_annotateTokens_Data*)UserData)->CXXUnit;
5299  CXToken *Tokens = ((clang_annotateTokens_Data*)UserData)->Tokens;
5300  const unsigned NumTokens = ((clang_annotateTokens_Data*)UserData)->NumTokens;
5301  CXCursor *Cursors = ((clang_annotateTokens_Data*)UserData)->Cursors;
5302
5303  CIndexer *CXXIdx = (CIndexer*)TU->CIdx;
5304  if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
5305    setThreadBackgroundPriority();
5306
5307  // Determine the region of interest, which contains all of the tokens.
5308  SourceRange RegionOfInterest;
5309  RegionOfInterest.setBegin(
5310    cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
5311  RegionOfInterest.setEnd(
5312    cxloc::translateSourceLocation(clang_getTokenLocation(TU,
5313                                                         Tokens[NumTokens-1])));
5314
5315  // A mapping from the source locations found when re-lexing or traversing the
5316  // region of interest to the corresponding cursors.
5317  AnnotateTokensData Annotated;
5318
5319  // Relex the tokens within the source range to look for preprocessing
5320  // directives.
5321  annotatePreprocessorTokens(TU, RegionOfInterest, Annotated);
5322
5323  if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
5324    // Search and mark tokens that are macro argument expansions.
5325    MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
5326                                      Tokens, NumTokens);
5327    CursorVisitor MacroArgMarker(TU,
5328                                 MarkMacroArgTokensVisitorDelegate, &Visitor,
5329                                 /*VisitPreprocessorLast=*/true,
5330                                 /*VisitIncludedEntities=*/false,
5331                                 RegionOfInterest);
5332    MacroArgMarker.visitPreprocessedEntitiesInRegion();
5333  }
5334
5335  // Annotate all of the source locations in the region of interest that map to
5336  // a specific cursor.
5337  AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
5338                         TU, RegionOfInterest);
5339
5340  // FIXME: We use a ridiculous stack size here because the data-recursion
5341  // algorithm uses a large stack frame than the non-data recursive version,
5342  // and AnnotationTokensWorker currently transforms the data-recursion
5343  // algorithm back into a traditional recursion by explicitly calling
5344  // VisitChildren().  We will need to remove this explicit recursive call.
5345  W.AnnotateTokens();
5346
5347  // If we ran into any entities that involve context-sensitive keywords,
5348  // take another pass through the tokens to mark them as such.
5349  if (W.hasContextSensitiveKeywords()) {
5350    for (unsigned I = 0; I != NumTokens; ++I) {
5351      if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
5352        continue;
5353
5354      if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
5355        IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5356        if (ObjCPropertyDecl *Property
5357            = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
5358          if (Property->getPropertyAttributesAsWritten() != 0 &&
5359              llvm::StringSwitch<bool>(II->getName())
5360              .Case("readonly", true)
5361              .Case("assign", true)
5362              .Case("unsafe_unretained", true)
5363              .Case("readwrite", true)
5364              .Case("retain", true)
5365              .Case("copy", true)
5366              .Case("nonatomic", true)
5367              .Case("atomic", true)
5368              .Case("getter", true)
5369              .Case("setter", true)
5370              .Case("strong", true)
5371              .Case("weak", true)
5372              .Default(false))
5373            Tokens[I].int_data[0] = CXToken_Keyword;
5374        }
5375        continue;
5376      }
5377
5378      if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
5379          Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
5380        IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
5381        if (llvm::StringSwitch<bool>(II->getName())
5382            .Case("in", true)
5383            .Case("out", true)
5384            .Case("inout", true)
5385            .Case("oneway", true)
5386            .Case("bycopy", true)
5387            .Case("byref", true)
5388            .Default(false))
5389          Tokens[I].int_data[0] = CXToken_Keyword;
5390        continue;
5391      }
5392
5393      if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
5394          Cursors[I].kind == CXCursor_CXXOverrideAttr) {
5395        Tokens[I].int_data[0] = CXToken_Keyword;
5396        continue;
5397      }
5398    }
5399  }
5400}
5401
5402extern "C" {
5403
5404void clang_annotateTokens(CXTranslationUnit TU,
5405                          CXToken *Tokens, unsigned NumTokens,
5406                          CXCursor *Cursors) {
5407
5408  if (NumTokens == 0 || !Tokens || !Cursors)
5409    return;
5410
5411  // Any token we don't specifically annotate will have a NULL cursor.
5412  CXCursor C = clang_getNullCursor();
5413  for (unsigned I = 0; I != NumTokens; ++I)
5414    Cursors[I] = C;
5415
5416  ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU->TUData);
5417  if (!CXXUnit)
5418    return;
5419
5420  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5421
5422  clang_annotateTokens_Data data = { TU, CXXUnit, Tokens, NumTokens, Cursors };
5423  llvm::CrashRecoveryContext CRC;
5424  if (!RunSafely(CRC, clang_annotateTokensImpl, &data,
5425                 GetSafetyThreadStackSize() * 2)) {
5426    fprintf(stderr, "libclang: crash detected while annotating tokens\n");
5427  }
5428}
5429
5430} // end: extern "C"
5431
5432//===----------------------------------------------------------------------===//
5433// Operations for querying linkage of a cursor.
5434//===----------------------------------------------------------------------===//
5435
5436extern "C" {
5437CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
5438  if (!clang_isDeclaration(cursor.kind))
5439    return CXLinkage_Invalid;
5440
5441  Decl *D = cxcursor::getCursorDecl(cursor);
5442  if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
5443    switch (ND->getLinkage()) {
5444      case NoLinkage: return CXLinkage_NoLinkage;
5445      case InternalLinkage: return CXLinkage_Internal;
5446      case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
5447      case ExternalLinkage: return CXLinkage_External;
5448    };
5449
5450  return CXLinkage_Invalid;
5451}
5452} // end: extern "C"
5453
5454//===----------------------------------------------------------------------===//
5455// Operations for querying language of a cursor.
5456//===----------------------------------------------------------------------===//
5457
5458static CXLanguageKind getDeclLanguage(const Decl *D) {
5459  if (!D)
5460    return CXLanguage_C;
5461
5462  switch (D->getKind()) {
5463    default:
5464      break;
5465    case Decl::ImplicitParam:
5466    case Decl::ObjCAtDefsField:
5467    case Decl::ObjCCategory:
5468    case Decl::ObjCCategoryImpl:
5469    case Decl::ObjCCompatibleAlias:
5470    case Decl::ObjCImplementation:
5471    case Decl::ObjCInterface:
5472    case Decl::ObjCIvar:
5473    case Decl::ObjCMethod:
5474    case Decl::ObjCProperty:
5475    case Decl::ObjCPropertyImpl:
5476    case Decl::ObjCProtocol:
5477      return CXLanguage_ObjC;
5478    case Decl::CXXConstructor:
5479    case Decl::CXXConversion:
5480    case Decl::CXXDestructor:
5481    case Decl::CXXMethod:
5482    case Decl::CXXRecord:
5483    case Decl::ClassTemplate:
5484    case Decl::ClassTemplatePartialSpecialization:
5485    case Decl::ClassTemplateSpecialization:
5486    case Decl::Friend:
5487    case Decl::FriendTemplate:
5488    case Decl::FunctionTemplate:
5489    case Decl::LinkageSpec:
5490    case Decl::Namespace:
5491    case Decl::NamespaceAlias:
5492    case Decl::NonTypeTemplateParm:
5493    case Decl::StaticAssert:
5494    case Decl::TemplateTemplateParm:
5495    case Decl::TemplateTypeParm:
5496    case Decl::UnresolvedUsingTypename:
5497    case Decl::UnresolvedUsingValue:
5498    case Decl::Using:
5499    case Decl::UsingDirective:
5500    case Decl::UsingShadow:
5501      return CXLanguage_CPlusPlus;
5502  }
5503
5504  return CXLanguage_C;
5505}
5506
5507extern "C" {
5508
5509enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
5510  if (clang_isDeclaration(cursor.kind))
5511    if (Decl *D = cxcursor::getCursorDecl(cursor)) {
5512      if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
5513        return CXAvailability_Available;
5514
5515      switch (D->getAvailability()) {
5516      case AR_Available:
5517      case AR_NotYetIntroduced:
5518        return CXAvailability_Available;
5519
5520      case AR_Deprecated:
5521        return CXAvailability_Deprecated;
5522
5523      case AR_Unavailable:
5524        return CXAvailability_NotAvailable;
5525      }
5526    }
5527
5528  return CXAvailability_Available;
5529}
5530
5531static CXVersion convertVersion(VersionTuple In) {
5532  CXVersion Out = { -1, -1, -1 };
5533  if (In.empty())
5534    return Out;
5535
5536  Out.Major = In.getMajor();
5537
5538  if (llvm::Optional<unsigned> Minor = In.getMinor())
5539    Out.Minor = *Minor;
5540  else
5541    return Out;
5542
5543  if (llvm::Optional<unsigned> Subminor = In.getSubminor())
5544    Out.Subminor = *Subminor;
5545
5546  return Out;
5547}
5548
5549int clang_getCursorPlatformAvailability(CXCursor cursor,
5550                                        int *always_deprecated,
5551                                        CXString *deprecated_message,
5552                                        int *always_unavailable,
5553                                        CXString *unavailable_message,
5554                                        CXPlatformAvailability *availability,
5555                                        int availability_size) {
5556  if (always_deprecated)
5557    *always_deprecated = 0;
5558  if (deprecated_message)
5559    *deprecated_message = cxstring::createCXString("", /*DupString=*/false);
5560  if (always_unavailable)
5561    *always_unavailable = 0;
5562  if (unavailable_message)
5563    *unavailable_message = cxstring::createCXString("", /*DupString=*/false);
5564
5565  if (!clang_isDeclaration(cursor.kind))
5566    return 0;
5567
5568  Decl *D = cxcursor::getCursorDecl(cursor);
5569  if (!D)
5570    return 0;
5571
5572  int N = 0;
5573  for (Decl::attr_iterator A = D->attr_begin(), AEnd = D->attr_end(); A != AEnd;
5574       ++A) {
5575    if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(*A)) {
5576      if (always_deprecated)
5577        *always_deprecated = 1;
5578      if (deprecated_message)
5579        *deprecated_message = cxstring::createCXString(Deprecated->getMessage());
5580      continue;
5581    }
5582
5583    if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(*A)) {
5584      if (always_unavailable)
5585        *always_unavailable = 1;
5586      if (unavailable_message) {
5587        *unavailable_message
5588          = cxstring::createCXString(Unavailable->getMessage());
5589      }
5590      continue;
5591    }
5592
5593    if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(*A)) {
5594      if (N < availability_size) {
5595        availability[N].Platform
5596          = cxstring::createCXString(Avail->getPlatform()->getName());
5597        availability[N].Introduced = convertVersion(Avail->getIntroduced());
5598        availability[N].Deprecated = convertVersion(Avail->getDeprecated());
5599        availability[N].Obsoleted = convertVersion(Avail->getObsoleted());
5600        availability[N].Unavailable = Avail->getUnavailable();
5601        availability[N].Message = cxstring::createCXString(Avail->getMessage());
5602      }
5603      ++N;
5604    }
5605  }
5606
5607  return N;
5608}
5609
5610void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
5611  clang_disposeString(availability->Platform);
5612  clang_disposeString(availability->Message);
5613}
5614
5615CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
5616  if (clang_isDeclaration(cursor.kind))
5617    return getDeclLanguage(cxcursor::getCursorDecl(cursor));
5618
5619  return CXLanguage_Invalid;
5620}
5621
5622 /// \brief If the given cursor is the "templated" declaration
5623 /// descibing a class or function template, return the class or
5624 /// function template.
5625static Decl *maybeGetTemplateCursor(Decl *D) {
5626  if (!D)
5627    return 0;
5628
5629  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5630    if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
5631      return FunTmpl;
5632
5633  if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5634    if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
5635      return ClassTmpl;
5636
5637  return D;
5638}
5639
5640CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
5641  if (clang_isDeclaration(cursor.kind)) {
5642    if (Decl *D = getCursorDecl(cursor)) {
5643      DeclContext *DC = D->getDeclContext();
5644      if (!DC)
5645        return clang_getNullCursor();
5646
5647      return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5648                          getCursorTU(cursor));
5649    }
5650  }
5651
5652  if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
5653    if (Decl *D = getCursorDecl(cursor))
5654      return MakeCXCursor(D, getCursorTU(cursor));
5655  }
5656
5657  return clang_getNullCursor();
5658}
5659
5660CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
5661  if (clang_isDeclaration(cursor.kind)) {
5662    if (Decl *D = getCursorDecl(cursor)) {
5663      DeclContext *DC = D->getLexicalDeclContext();
5664      if (!DC)
5665        return clang_getNullCursor();
5666
5667      return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
5668                          getCursorTU(cursor));
5669    }
5670  }
5671
5672  // FIXME: Note that we can't easily compute the lexical context of a
5673  // statement or expression, so we return nothing.
5674  return clang_getNullCursor();
5675}
5676
5677CXFile clang_getIncludedFile(CXCursor cursor) {
5678  if (cursor.kind != CXCursor_InclusionDirective)
5679    return 0;
5680
5681  InclusionDirective *ID = getCursorInclusionDirective(cursor);
5682  return (void *)ID->getFile();
5683}
5684
5685CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
5686  if (!clang_isDeclaration(C.kind))
5687    return clang_getNullRange();
5688
5689  const Decl *D = getCursorDecl(C);
5690  ASTContext &Context = getCursorContext(C);
5691  const RawComment *RC = Context.getRawCommentForDecl(D);
5692  if (!RC)
5693    return clang_getNullRange();
5694
5695  return cxloc::translateSourceRange(Context, RC->getSourceRange());
5696}
5697
5698CXString clang_Cursor_getRawCommentText(CXCursor C) {
5699  if (!clang_isDeclaration(C.kind))
5700    return createCXString((const char *) NULL);
5701
5702  const Decl *D = getCursorDecl(C);
5703  ASTContext &Context = getCursorContext(C);
5704  const RawComment *RC = Context.getRawCommentForDecl(D);
5705  StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
5706                           StringRef();
5707
5708  // Don't duplicate the string because RawText points directly into source
5709  // code.
5710  return createCXString(RawText, false);
5711}
5712
5713CXString clang_Cursor_getBriefCommentText(CXCursor C) {
5714  if (!clang_isDeclaration(C.kind))
5715    return createCXString((const char *) NULL);
5716
5717  const Decl *D = getCursorDecl(C);
5718  const ASTContext &Context = getCursorContext(C);
5719  const RawComment *RC = Context.getRawCommentForDecl(D);
5720
5721  if (RC) {
5722    StringRef BriefText = RC->getBriefText(Context);
5723
5724    // Don't duplicate the string because RawComment ensures that this memory
5725    // will not go away.
5726    return createCXString(BriefText, false);
5727  }
5728
5729  return createCXString((const char *) NULL);
5730}
5731
5732} // end: extern "C"
5733
5734//===----------------------------------------------------------------------===//
5735// C++ AST instrospection.
5736//===----------------------------------------------------------------------===//
5737
5738extern "C" {
5739unsigned clang_CXXMethod_isStatic(CXCursor C) {
5740  if (!clang_isDeclaration(C.kind))
5741    return 0;
5742
5743  CXXMethodDecl *Method = 0;
5744  Decl *D = cxcursor::getCursorDecl(C);
5745  if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5746    Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5747  else
5748    Method = dyn_cast_or_null<CXXMethodDecl>(D);
5749  return (Method && Method->isStatic()) ? 1 : 0;
5750}
5751
5752unsigned clang_CXXMethod_isVirtual(CXCursor C) {
5753  if (!clang_isDeclaration(C.kind))
5754    return 0;
5755
5756  CXXMethodDecl *Method = 0;
5757  Decl *D = cxcursor::getCursorDecl(C);
5758  if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
5759    Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
5760  else
5761    Method = dyn_cast_or_null<CXXMethodDecl>(D);
5762  return (Method && Method->isVirtual()) ? 1 : 0;
5763}
5764} // end: extern "C"
5765
5766//===----------------------------------------------------------------------===//
5767// Attribute introspection.
5768//===----------------------------------------------------------------------===//
5769
5770extern "C" {
5771CXType clang_getIBOutletCollectionType(CXCursor C) {
5772  if (C.kind != CXCursor_IBOutletCollectionAttr)
5773    return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
5774
5775  IBOutletCollectionAttr *A =
5776    cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
5777
5778  return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
5779}
5780} // end: extern "C"
5781
5782//===----------------------------------------------------------------------===//
5783// Inspecting memory usage.
5784//===----------------------------------------------------------------------===//
5785
5786typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
5787
5788static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
5789                                              enum CXTUResourceUsageKind k,
5790                                              unsigned long amount) {
5791  CXTUResourceUsageEntry entry = { k, amount };
5792  entries.push_back(entry);
5793}
5794
5795extern "C" {
5796
5797const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
5798  const char *str = "";
5799  switch (kind) {
5800    case CXTUResourceUsage_AST:
5801      str = "ASTContext: expressions, declarations, and types";
5802      break;
5803    case CXTUResourceUsage_Identifiers:
5804      str = "ASTContext: identifiers";
5805      break;
5806    case CXTUResourceUsage_Selectors:
5807      str = "ASTContext: selectors";
5808      break;
5809    case CXTUResourceUsage_GlobalCompletionResults:
5810      str = "Code completion: cached global results";
5811      break;
5812    case CXTUResourceUsage_SourceManagerContentCache:
5813      str = "SourceManager: content cache allocator";
5814      break;
5815    case CXTUResourceUsage_AST_SideTables:
5816      str = "ASTContext: side tables";
5817      break;
5818    case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
5819      str = "SourceManager: malloc'ed memory buffers";
5820      break;
5821    case CXTUResourceUsage_SourceManager_Membuffer_MMap:
5822      str = "SourceManager: mmap'ed memory buffers";
5823      break;
5824    case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
5825      str = "ExternalASTSource: malloc'ed memory buffers";
5826      break;
5827    case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
5828      str = "ExternalASTSource: mmap'ed memory buffers";
5829      break;
5830    case CXTUResourceUsage_Preprocessor:
5831      str = "Preprocessor: malloc'ed memory";
5832      break;
5833    case CXTUResourceUsage_PreprocessingRecord:
5834      str = "Preprocessor: PreprocessingRecord";
5835      break;
5836    case CXTUResourceUsage_SourceManager_DataStructures:
5837      str = "SourceManager: data structures and tables";
5838      break;
5839    case CXTUResourceUsage_Preprocessor_HeaderSearch:
5840      str = "Preprocessor: header search tables";
5841      break;
5842  }
5843  return str;
5844}
5845
5846CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
5847  if (!TU) {
5848    CXTUResourceUsage usage = { (void*) 0, 0, 0 };
5849    return usage;
5850  }
5851
5852  ASTUnit *astUnit = static_cast<ASTUnit*>(TU->TUData);
5853  OwningPtr<MemUsageEntries> entries(new MemUsageEntries());
5854  ASTContext &astContext = astUnit->getASTContext();
5855
5856  // How much memory is used by AST nodes and types?
5857  createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST,
5858    (unsigned long) astContext.getASTAllocatedMemory());
5859
5860  // How much memory is used by identifiers?
5861  createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Identifiers,
5862    (unsigned long) astContext.Idents.getAllocator().getTotalMemory());
5863
5864  // How much memory is used for selectors?
5865  createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Selectors,
5866    (unsigned long) astContext.Selectors.getTotalMemory());
5867
5868  // How much memory is used by ASTContext's side tables?
5869  createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_AST_SideTables,
5870    (unsigned long) astContext.getSideTableAllocatedMemory());
5871
5872  // How much memory is used for caching global code completion results?
5873  unsigned long completionBytes = 0;
5874  if (GlobalCodeCompletionAllocator *completionAllocator =
5875      astUnit->getCachedCompletionAllocator().getPtr()) {
5876    completionBytes = completionAllocator->getTotalMemory();
5877  }
5878  createCXTUResourceUsageEntry(*entries,
5879                               CXTUResourceUsage_GlobalCompletionResults,
5880                               completionBytes);
5881
5882  // How much memory is being used by SourceManager's content cache?
5883  createCXTUResourceUsageEntry(*entries,
5884          CXTUResourceUsage_SourceManagerContentCache,
5885          (unsigned long) astContext.getSourceManager().getContentCacheSize());
5886
5887  // How much memory is being used by the MemoryBuffer's in SourceManager?
5888  const SourceManager::MemoryBufferSizes &srcBufs =
5889    astUnit->getSourceManager().getMemoryBufferSizes();
5890
5891  createCXTUResourceUsageEntry(*entries,
5892                               CXTUResourceUsage_SourceManager_Membuffer_Malloc,
5893                               (unsigned long) srcBufs.malloc_bytes);
5894  createCXTUResourceUsageEntry(*entries,
5895                               CXTUResourceUsage_SourceManager_Membuffer_MMap,
5896                               (unsigned long) srcBufs.mmap_bytes);
5897  createCXTUResourceUsageEntry(*entries,
5898                               CXTUResourceUsage_SourceManager_DataStructures,
5899                               (unsigned long) astContext.getSourceManager()
5900                                .getDataStructureSizes());
5901
5902  // How much memory is being used by the ExternalASTSource?
5903  if (ExternalASTSource *esrc = astContext.getExternalSource()) {
5904    const ExternalASTSource::MemoryBufferSizes &sizes =
5905      esrc->getMemoryBufferSizes();
5906
5907    createCXTUResourceUsageEntry(*entries,
5908      CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
5909                                 (unsigned long) sizes.malloc_bytes);
5910    createCXTUResourceUsageEntry(*entries,
5911      CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
5912                                 (unsigned long) sizes.mmap_bytes);
5913  }
5914
5915  // How much memory is being used by the Preprocessor?
5916  Preprocessor &pp = astUnit->getPreprocessor();
5917  createCXTUResourceUsageEntry(*entries,
5918                               CXTUResourceUsage_Preprocessor,
5919                               pp.getTotalMemory());
5920
5921  if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
5922    createCXTUResourceUsageEntry(*entries,
5923                                 CXTUResourceUsage_PreprocessingRecord,
5924                                 pRec->getTotalMemory());
5925  }
5926
5927  createCXTUResourceUsageEntry(*entries,
5928                               CXTUResourceUsage_Preprocessor_HeaderSearch,
5929                               pp.getHeaderSearchInfo().getTotalMemory());
5930
5931  CXTUResourceUsage usage = { (void*) entries.get(),
5932                            (unsigned) entries->size(),
5933                            entries->size() ? &(*entries)[0] : 0 };
5934  entries.take();
5935  return usage;
5936}
5937
5938void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
5939  if (usage.data)
5940    delete (MemUsageEntries*) usage.data;
5941}
5942
5943} // end extern "C"
5944
5945void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
5946  CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
5947  for (unsigned I = 0; I != Usage.numEntries; ++I)
5948    fprintf(stderr, "  %s: %lu\n",
5949            clang_getTUResourceUsageName(Usage.entries[I].kind),
5950            Usage.entries[I].amount);
5951
5952  clang_disposeCXTUResourceUsage(Usage);
5953}
5954
5955//===----------------------------------------------------------------------===//
5956// Misc. utility functions.
5957//===----------------------------------------------------------------------===//
5958
5959/// Default to using an 8 MB stack size on "safety" threads.
5960static unsigned SafetyStackThreadSize = 8 << 20;
5961
5962namespace clang {
5963
5964bool RunSafely(llvm::CrashRecoveryContext &CRC,
5965               void (*Fn)(void*), void *UserData,
5966               unsigned Size) {
5967  if (!Size)
5968    Size = GetSafetyThreadStackSize();
5969  if (Size)
5970    return CRC.RunSafelyOnThread(Fn, UserData, Size);
5971  return CRC.RunSafely(Fn, UserData);
5972}
5973
5974unsigned GetSafetyThreadStackSize() {
5975  return SafetyStackThreadSize;
5976}
5977
5978void SetSafetyThreadStackSize(unsigned Value) {
5979  SafetyStackThreadSize = Value;
5980}
5981
5982}
5983
5984void clang::setThreadBackgroundPriority() {
5985  // FIXME: Move to llvm/Support and make it cross-platform.
5986#ifdef __APPLE__
5987  setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
5988#endif
5989}
5990
5991void cxindex::printDiagsToStderr(ASTUnit *Unit) {
5992  if (!Unit)
5993    return;
5994
5995  for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
5996                                  DEnd = Unit->stored_diag_end();
5997       D != DEnd; ++D) {
5998    CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOpts());
5999    CXString Msg = clang_formatDiagnostic(&Diag,
6000                                clang_defaultDiagnosticDisplayOptions());
6001    fprintf(stderr, "%s\n", clang_getCString(Msg));
6002    clang_disposeString(Msg);
6003  }
6004#ifdef LLVM_ON_WIN32
6005  // On Windows, force a flush, since there may be multiple copies of
6006  // stderr and stdout in the file system, all with different buffers
6007  // but writing to the same device.
6008  fflush(stderr);
6009#endif
6010}
6011
6012extern "C" {
6013
6014CXString clang_getClangVersion() {
6015  return createCXString(getClangFullVersion());
6016}
6017
6018} // end: extern "C"
6019
6020