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