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