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