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