Clang Project

clang_source_code/tools/libclang/CIndex.cpp
1//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the main API hooks in the Clang-C Source Indexing
10// library.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CIndexDiagnostic.h"
15#include "CIndexer.h"
16#include "CLog.h"
17#include "CXCursor.h"
18#include "CXSourceLocation.h"
19#include "CXString.h"
20#include "CXTranslationUnit.h"
21#include "CXType.h"
22#include "CursorVisitor.h"
23#include "clang/AST/Attr.h"
24#include "clang/AST/StmtVisitor.h"
25#include "clang/Basic/Diagnostic.h"
26#include "clang/Basic/DiagnosticCategories.h"
27#include "clang/Basic/DiagnosticIDs.h"
28#include "clang/Basic/Stack.h"
29#include "clang/Basic/TargetInfo.h"
30#include "clang/Basic/Version.h"
31#include "clang/Frontend/ASTUnit.h"
32#include "clang/Frontend/CompilerInstance.h"
33#include "clang/Index/CodegenNameGenerator.h"
34#include "clang/Index/CommentToXML.h"
35#include "clang/Lex/HeaderSearch.h"
36#include "clang/Lex/Lexer.h"
37#include "clang/Lex/PreprocessingRecord.h"
38#include "clang/Lex/Preprocessor.h"
39#include "llvm/ADT/Optional.h"
40#include "llvm/ADT/STLExtras.h"
41#include "llvm/ADT/StringSwitch.h"
42#include "llvm/Config/llvm-config.h"
43#include "llvm/Support/Compiler.h"
44#include "llvm/Support/CrashRecoveryContext.h"
45#include "llvm/Support/Format.h"
46#include "llvm/Support/ManagedStatic.h"
47#include "llvm/Support/MemoryBuffer.h"
48#include "llvm/Support/Mutex.h"
49#include "llvm/Support/Program.h"
50#include "llvm/Support/SaveAndRestore.h"
51#include "llvm/Support/Signals.h"
52#include "llvm/Support/TargetSelect.h"
53#include "llvm/Support/Threading.h"
54#include "llvm/Support/Timer.h"
55#include "llvm/Support/raw_ostream.h"
56
57#if LLVM_ENABLE_THREADS != 0 && defined(__APPLE__)
58#define USE_DARWIN_THREADS
59#endif
60
61#ifdef USE_DARWIN_THREADS
62#include <pthread.h>
63#endif
64
65using namespace clang;
66using namespace clang::cxcursor;
67using namespace clang::cxtu;
68using namespace clang::cxindex;
69
70CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx,
71                                              std::unique_ptr<ASTUnitAU) {
72  if (!AU)
73    return nullptr;
74  assert(CIdx);
75  CXTranslationUnit D = new CXTranslationUnitImpl();
76  D->CIdx = CIdx;
77  D->TheASTUnit = AU.release();
78  D->StringPool = new cxstring::CXStringPool();
79  D->Diagnostics = nullptr;
80  D->OverridenCursorsPool = createOverridenCXCursorsPool();
81  D->CommentToXML = nullptr;
82  D->ParsingOptions = 0;
83  D->Arguments = {};
84  return D;
85}
86
87bool cxtu::isASTReadError(ASTUnit *AU) {
88  for (ASTUnit::stored_diag_iterator D = AU->stored_diag_begin(),
89                                     DEnd = AU->stored_diag_end();
90       D != DEnd; ++D) {
91    if (D->getLevel() >= DiagnosticsEngine::Error &&
92        DiagnosticIDs::getCategoryNumberForDiag(D->getID()) ==
93            diag::DiagCat_AST_Deserialization_Issue)
94      return true;
95  }
96  return false;
97}
98
99cxtu::CXTUOwner::~CXTUOwner() {
100  if (TU)
101    clang_disposeTranslationUnit(TU);
102}
103
104/// Compare two source ranges to determine their relative position in
105/// the translation unit.
106static RangeComparisonResult RangeCompare(SourceManager &SM,
107                                          SourceRange R1,
108                                          SourceRange R2) {
109   (0) . __assert_fail ("R1.isValid() && \"First range is invalid?\"", "/home/seafit/code_projects/clang_source/clang/tools/libclang/CIndex.cpp", 109, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(R1.isValid() && "First range is invalid?");
110   (0) . __assert_fail ("R2.isValid() && \"Second range is invalid?\"", "/home/seafit/code_projects/clang_source/clang/tools/libclang/CIndex.cpp", 110, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(R2.isValid() && "Second range is invalid?");
111  if (R1.getEnd() != R2.getBegin() &&
112      SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
113    return RangeBefore;
114  if (R2.getEnd() != R1.getBegin() &&
115      SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
116    return RangeAfter;
117  return RangeOverlap;
118}
119
120/// Determine if a source location falls within, before, or after a
121///   a given source range.
122static RangeComparisonResult LocationCompare(SourceManager &SM,
123                                             SourceLocation LSourceRange R) {
124   (0) . __assert_fail ("R.isValid() && \"First range is invalid?\"", "/home/seafit/code_projects/clang_source/clang/tools/libclang/CIndex.cpp", 124, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(R.isValid() && "First range is invalid?");
125   (0) . __assert_fail ("L.isValid() && \"Second range is invalid?\"", "/home/seafit/code_projects/clang_source/clang/tools/libclang/CIndex.cpp", 125, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(L.isValid() && "Second range is invalid?");
126  if (L == R.getBegin() || L == R.getEnd())
127    return RangeOverlap;
128  if (SM.isBeforeInTranslationUnit(LR.getBegin()))
129    return RangeBefore;
130  if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
131    return RangeAfter;
132  return RangeOverlap;
133}
134
135/// Translate a Clang source range into a CIndex source range.
136///
137/// Clang internally represents ranges where the end location points to the
138/// start of the token at the end. However, for external clients it is more
139/// useful to have a CXSourceRange be a proper half-open interval. This routine
140/// does the appropriate translation.
141CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
142                                          const LangOptions &LangOpts,
143                                          const CharSourceRange &R) {
144  // We want the last character in this location, so we will adjust the
145  // location accordingly.
146  SourceLocation EndLoc = R.getEnd();
147  bool IsTokenRange = R.isTokenRange();
148  if (EndLoc.isValid() && EndLoc.isMacroID() && !SM.isMacroArgExpansion(EndLoc)) {
149    CharSourceRange Expansion = SM.getExpansionRange(EndLoc);
150    EndLoc = Expansion.getEnd();
151    IsTokenRange = Expansion.isTokenRange();
152  }
153  if (IsTokenRange && EndLoc.isValid()) {
154    unsigned Length = Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc),
155                                                SMLangOpts);
156    EndLoc = EndLoc.getLocWithOffset(Length);
157  }
158
159  CXSourceRange Result = {
160    { &SM, &LangOpts },
161    R.getBegin().getRawEncoding(),
162    EndLoc.getRawEncoding()
163  };
164  return Result;
165}
166
167//===----------------------------------------------------------------------===//
168// Cursor visitor.
169//===----------------------------------------------------------------------===//
170
171static SourceRange getRawCursorExtent(CXCursor C);
172static SourceRange getFullCursorExtent(CXCursor CSourceManager &SrcMgr);
173
174
175RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
176  return RangeCompare(AU->getSourceManager()RRegionOfInterest);
177}
178
179/// Visit the given cursor and, if requested by the visitor,
180/// its children.
181///
182/// \param Cursor the cursor to visit.
183///
184/// \param CheckedRegionOfInterest if true, then the caller already checked
185/// that this cursor is within the region of interest.
186///
187/// \returns true if the visitation should be aborted, false if it
188/// should continue.
189bool CursorVisitor::Visit(CXCursor Cursorbool CheckedRegionOfInterest) {
190  if (clang_isInvalid(Cursor.kind))
191    return false;
192
193  if (clang_isDeclaration(Cursor.kind)) {
194    const Decl *D = getCursorDecl(Cursor);
195    if (!D) {
196       (0) . __assert_fail ("0 && \"Invalid declaration cursor\"", "/home/seafit/code_projects/clang_source/clang/tools/libclang/CIndex.cpp", 196, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(0 && "Invalid declaration cursor");
197      return true// abort.
198    }
199    
200    // Ignore implicit declarations, unless it's an objc method because
201    // currently we should report implicit methods for properties when indexing.
202    if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
203      return false;
204  }
205
206  // If we have a range of interest, and this cursor doesn't intersect with it,
207  // we're done.
208  if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
209    SourceRange Range = getRawCursorExtent(Cursor);
210    if (Range.isInvalid() || CompareRegionOfInterest(Range))
211      return false;
212  }
213
214  switch (Visitor(CursorParentClientData)) {
215  case CXChildVisit_Break:
216    return true;
217
218  case CXChildVisit_Continue:
219    return false;
220
221  case CXChildVisit_Recurse: {
222    bool ret = VisitChildren(Cursor);
223    if (PostChildrenVisitor)
224      if (PostChildrenVisitor(CursorClientData))
225        return true;
226    return ret;
227  }
228  }
229
230  llvm_unreachable("Invalid CXChildVisitResult!");
231}
232
233static bool visitPreprocessedEntitiesInRange(SourceRange R,
234                                             PreprocessingRecord &PPRec,
235                                             CursorVisitor &Visitor) {
236  SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
237  FileID FID;
238  
239  if (!Visitor.shouldVisitIncludedEntities()) {
240    // If the begin/end of the range lie in the same FileID, do the optimization
241    // where we skip preprocessed entities that do not come from the same FileID.
242    FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
243    if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
244      FID = FileID();
245  }
246
247  const auto &Entities = PPRec.getPreprocessedEntitiesInRange(R);
248  return Visitor.visitPreprocessedEntities(Entities.begin(), Entities.end(),
249                                           PPRec, FID);
250}
251
252bool CursorVisitor::visitFileRegion() {
253  if (RegionOfInterest.isInvalid())
254    return false;
255
256  ASTUnit *Unit = cxtu::getASTUnit(TU);
257  SourceManager &SM = Unit->getSourceManager();
258  
259  std::pair<FileIDunsigned>
260    Begin = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getBegin())), 
261    End = SM.getDecomposedLoc(SM.getFileLoc(RegionOfInterest.getEnd())); 
262
263  if (End.first != Begin.first) {
264    // If the end does not reside in the same file, try to recover by
265    // picking the end of the file of begin location.
266    End.first = Begin.first;
267    End.second = SM.getFileIDSize(Begin.first);
268  }
269
270  assert(Begin.first == End.first);
271  if (Begin.second > End.second)
272    return false;
273  
274  FileID File = Begin.first;
275  unsigned Offset = Begin.second;
276  unsigned Length = End.second - Begin.second;
277
278  if (!VisitDeclsOnly && !VisitPreprocessorLast)
279    if (visitPreprocessedEntitiesInRegion())
280      return true// visitation break.
281
282  if (visitDeclsFromFileRegion(FileOffsetLength))
283    return true// visitation break.
284
285  if (!VisitDeclsOnly && VisitPreprocessorLast)
286    return visitPreprocessedEntitiesInRegion();
287
288  return false;
289}
290
291static bool isInLexicalContext(Decl *DDeclContext *DC) {
292  if (!DC)
293    return false;
294
295  for (DeclContext *DeclDC = D->getLexicalDeclContext();
296         DeclDCDeclDC = DeclDC->getLexicalParent()) {
297    if (DeclDC == DC)
298      return true;
299  }
300  return false;
301}
302
303bool CursorVisitor::visitDeclsFromFileRegion(FileID File,
304                                             unsigned Offsetunsigned Length) {
305  ASTUnit *Unit = cxtu::getASTUnit(TU);
306  SourceManager &SM = Unit->getSourceManager();
307  SourceRange Range = RegionOfInterest;
308
309  SmallVector<Decl *, 16Decls;
310  Unit->findFileRegionDecls(File, Offset, Length, Decls);
311
312  // If we didn't find any file level decls for the file, try looking at the
313  // file that it was included from.
314  while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
315    bool Invalid = false;
316    const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
317    if (Invalid)
318      return false;
319
320    SourceLocation Outer;
321    if (SLEntry.isFile())
322      Outer = SLEntry.getFile().getIncludeLoc();
323    else
324      Outer = SLEntry.getExpansion().getExpansionLocStart();
325    if (Outer.isInvalid())
326      return false;
327
328    std::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
329    Length = 0;
330    Unit->findFileRegionDecls(File, Offset, Length, Decls);
331  }
332
333  assert(!Decls.empty());
334
335  bool VisitedAtLeastOnce = false;
336  DeclContext *CurDC = nullptr;
337  SmallVectorImpl<Decl *>::iterator DIt = Decls.begin();
338  for (SmallVectorImpl<Decl *>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
339    Decl *D = *DIt;
340    if (D->getSourceRange().isInvalid())
341      continue;
342
343    if (isInLexicalContext(D, CurDC))
344      continue;
345
346    CurDC = dyn_cast<DeclContext>(D);
347
348    if (TagDecl *TD = dyn_cast<TagDecl>(D))
349      if (!TD->isFreeStanding())
350        continue;
351
352    RangeComparisonResult CompRes = RangeCompare(SM, D->getSourceRange(),Range);
353    if (CompRes == RangeBefore)
354      continue;
355    if (CompRes == RangeAfter)
356      break;
357
358    assert(CompRes == RangeOverlap);
359    VisitedAtLeastOnce = true;
360
361    if (isa<ObjCContainerDecl>(D)) {
362      FileDI_current = &DIt;
363      FileDE_current = DE;
364    } else {
365      FileDI_current = nullptr;
366    }
367
368    if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
369      return true// visitation break.
370  }
371
372  if (VisitedAtLeastOnce)
373    return false;
374
375  // No Decls overlapped with the range. Move up the lexical context until there
376  // is a context that contains the range or we reach the translation unit
377  // level.
378  DeclContext *DC = DIt == Decls.begin() ? (*DIt)->getLexicalDeclContext()
379                                         : (*(DIt-1))->getLexicalDeclContext();
380
381  while (DC && !DC->isTranslationUnit()) {
382    Decl *D = cast<Decl>(DC);
383    SourceRange CurDeclRange = D->getSourceRange();
384    if (CurDeclRange.isInvalid())
385      break;
386
387    if (RangeCompare(SMCurDeclRangeRange) == RangeOverlap) {
388      if (Visit(MakeCXCursor(DTURange), /*CheckedRegionOfInterest=*/true))
389        return true// visitation break.
390    }
391
392    DC = D->getLexicalDeclContext();
393  }
394
395  return false;
396}
397
398bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
399  if (!AU->getPreprocessor().getPreprocessingRecord())
400    return false;
401
402  PreprocessingRecord &PPRec
403    = *AU->getPreprocessor().getPreprocessingRecord();
404  SourceManager &SM = AU->getSourceManager();
405  
406  if (RegionOfInterest.isValid()) {
407    SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
408    SourceLocation B = MappedRange.getBegin();
409    SourceLocation E = MappedRange.getEnd();
410
411    if (AU->isInPreambleFileID(B)) {
412      if (SM.isLoadedSourceLocation(E))
413        return visitPreprocessedEntitiesInRange(SourceRange(BE),
414                                                 PPRec*this);
415
416      // Beginning of range lies in the preamble but it also extends beyond
417      // it into the main file. Split the range into 2 parts, one covering
418      // the preamble and another covering the main file. This allows subsequent
419      // calls to visitPreprocessedEntitiesInRange to accept a source range that
420      // lies in the same FileID, allowing it to skip preprocessed entities that
421      // do not come from the same FileID.
422      bool breaked =
423        visitPreprocessedEntitiesInRange(
424                                   SourceRange(BAU->getEndOfPreambleFileID()),
425                                          PPRec*this);
426      if (breakedreturn true;
427      return visitPreprocessedEntitiesInRange(
428                                    SourceRange(AU->getStartOfMainFileID(), E),
429                                        PPRec*this);
430    }
431
432    return visitPreprocessedEntitiesInRange(SourceRange(BE), PPRec*this);
433  }
434
435  bool OnlyLocalDecls
436    = !AU->isMainFileAST() && AU->getOnlyLocalDecls(); 
437  
438  if (OnlyLocalDecls)
439    return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
440                                     PPRec);
441
442  return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
443}
444
445template<typename InputIterator>
446bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
447                                              InputIterator Last,
448                                              PreprocessingRecord &PPRec,
449                                              FileID FID) {
450  for (; First != Last; ++First) {
451    if (!FID.isInvalid() && !PPRec.isEntityInFileID(FirstFID))
452      continue;
453
454    PreprocessedEntity *PPE = *First;
455    if (!PPE)
456      continue;
457
458    if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
459      if (Visit(MakeMacroExpansionCursor(METU)))
460        return true;
461
462      continue;
463    }
464
465    if (MacroDefinitionRecord *MD = dyn_cast<MacroDefinitionRecord>(PPE)) {
466      if (Visit(MakeMacroDefinitionCursor(MDTU)))
467        return true;
468
469      continue;
470    }
471    
472    if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
473      if (Visit(MakeInclusionDirectiveCursor(IDTU)))
474        return true;
475      
476      continue;
477    }
478  }
479
480  return false;
481}
482
483/// Visit the children of the given cursor.
484/// 
485/// \returns true if the visitation should be aborted, false if it
486/// should continue.
487bool CursorVisitor::VisitChildren(CXCursor Cursor) {
488  if (clang_isReference(Cursor.kind) && 
489      Cursor.kind != CXCursor_CXXBaseSpecifier) {
490    // By definition, references have no children.
491    return false;
492  }
493
494  // Set the Parent field to Cursor, then back to its old value once we're
495  // done.
496  SetParentRAII SetParent(ParentStmtParentCursor);
497
498  if (clang_isDeclaration(Cursor.kind)) {
499    Decl *D = const_cast<Decl *>(getCursorDecl(Cursor));
500    if (!D)
501      return false;
502
503    return VisitAttributes(D) || Visit(D);
504  }
505
506  if (clang_isStatement(Cursor.kind)) {
507    if (const Stmt *S = getCursorStmt(Cursor))
508      return Visit(S);
509
510    return false;
511  }
512
513  if (clang_isExpression(Cursor.kind)) {
514    if (const Expr *E = getCursorExpr(Cursor))
515      return Visit(E);
516
517    return false;
518  }
519
520  if (clang_isTranslationUnit(Cursor.kind)) {
521    CXTranslationUnit TU = getCursorTU(Cursor);
522    ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
523    
524    int VisitOrder[2] = { VisitPreprocessorLast, !VisitPreprocessorLast };
525    for (unsigned I = 0I != 2; ++I) {
526      if (VisitOrder[I]) {
527        if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
528            RegionOfInterest.isInvalid()) {
529          for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
530                                        TLEnd = CXXUnit->top_level_end();
531               TL != TLEnd; ++TL) {
532            const Optional<boolV = handleDeclForVisitation(*TL);
533            if (!V.hasValue())
534              continue;
535            return V.getValue();
536          }
537        } else if (VisitDeclContext(
538                                CXXUnit->getASTContext().getTranslationUnitDecl()))
539          return true;
540        continue;
541      }
542
543      // Walk the preprocessing record.
544      if (CXXUnit->getPreprocessor().getPreprocessingRecord())
545        visitPreprocessedEntitiesInRegion();
546    }
547    
548    return false;
549  }
550
551  if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
552    if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
553      if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
554        return Visit(BaseTSInfo->getTypeLoc());
555      }
556    }
557  }
558
559  if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
560    const IBOutletCollectionAttr *A =
561      cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
562    if (const ObjCObjectType *ObjT = A->getInterface()->getAs<ObjCObjectType>())
563      return Visit(cxcursor::MakeCursorObjCClassRef(
564          ObjT->getInterface(),
565          A->getInterfaceLoc()->getTypeLoc().getBeginLoc(), TU));
566  }
567
568  // If pointing inside a macro definition, check if the token is an identifier
569  // that was ever defined as a macro. In such a case, create a "pseudo" macro
570  // expansion cursor for that token.
571  SourceLocation BeginLoc = RegionOfInterest.getBegin();
572  if (Cursor.kind == CXCursor_MacroDefinition &&
573      BeginLoc == RegionOfInterest.getEnd()) {
574    SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc);
575    const MacroInfo *MI =
576        getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU);
577    if (MacroDefinitionRecord *MacroDef =
578            checkForMacroInMacroDefinition(MILocTU))
579      return Visit(cxcursor::MakeMacroExpansionCursor(MacroDefBeginLocTU));
580  }
581
582  // Nothing to visit at the moment.
583  return false;
584}
585
586bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
587  if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
588    if (Visit(TSInfo->getTypeLoc()))
589        return true;
590
591  if (Stmt *Body = B->getBody())
592    return Visit(MakeCXCursor(BodyStmtParentTURegionOfInterest));
593
594  return false;
595}
596
597Optional<boolCursorVisitor::shouldVisitCursor(CXCursor Cursor) {
598  if (RegionOfInterest.isValid()) {
599    SourceRange Range = getFullCursorExtent(CursorAU->getSourceManager());
600    if (Range.isInvalid())
601      return None;
602    
603    switch (CompareRegionOfInterest(Range)) {
604    case RangeBefore:
605      // This declaration comes before the region of interest; skip it.
606      return None;
607
608    case RangeAfter:
609      // This declaration comes after the region of interest; we're done.
610      return false;
611
612    case RangeOverlap:
613      // This declaration overlaps the region of interest; visit it.
614      break;
615    }
616  }
617  return true;
618}
619
620bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
621  DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
622
623  // FIXME: Eventually remove.  This part of a hack to support proper
624  // iteration over all Decls contained lexically within an ObjC container.
625  SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
626  SaveAndRestore<DeclContext::decl_iteratorDE_saved(DE_current, E);
627
628  for ( ; I != E; ++I) {
629    Decl *D = *I;
630    if (D->getLexicalDeclContext() != DC)
631      continue;
632    const Optional<boolV = handleDeclForVisitation(D);
633    if (!V.hasValue())
634      continue;
635    return V.getValue();
636  }
637  return false;
638}
639
640Optional<boolCursorVisitor::handleDeclForVisitation(const Decl *D) {
641  CXCursor Cursor = MakeCXCursor(DTURegionOfInterest);
642
643  // Ignore synthesized ivars here, otherwise if we have something like:
644  //   @synthesize prop = _prop;
645  // and '_prop' is not declared, we will encounter a '_prop' ivar before
646  // encountering the 'prop' synthesize declaration and we will think that
647  // we passed the region-of-interest.
648  if (auto *ivarD = dyn_cast<ObjCIvarDecl>(D)) {
649    if (ivarD->getSynthesize())
650      return None;
651  }
652
653  // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
654  // declarations is a mismatch with the compiler semantics.
655  if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
656    auto *ID = cast<ObjCInterfaceDecl>(D);
657    if (!ID->isThisDeclarationADefinition())
658      Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
659
660  } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
661    auto *PD = cast<ObjCProtocolDecl>(D);
662    if (!PD->isThisDeclarationADefinition())
663      Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
664  }
665
666  const Optional<boolV = shouldVisitCursor(Cursor);
667  if (!V.hasValue())
668    return None;
669  if (!V.getValue())
670    return false;
671  if (Visit(Cursor, true))
672    return true;
673  return None;
674}
675
676bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
677  llvm_unreachable("Translation units are visited directly by Visit()");
678}
679
680bool CursorVisitor::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
681    if (VisitTemplateParameters(D->getTemplateParameters()))
682        return true;
683
684    return Visit(MakeCXCursor(D->getTemplatedDecl(), TURegionOfInterest));
685}
686
687bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
688  if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
689    return Visit(TSInfo->getTypeLoc());
690
691  return false;
692}
693
694bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
695  if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
696    return Visit(TSInfo->getTypeLoc());
697
698  return false;
699}
700
701bool CursorVisitor::VisitTagDecl(TagDecl *D) {
702  return VisitDeclContext(D);
703}
704
705bool CursorVisitor::VisitClassTemplateSpecializationDecl(
706                                          ClassTemplateSpecializationDecl *D) {
707  bool ShouldVisitBody = false;
708  switch (D->getSpecializationKind()) {
709  case TSK_Undeclared:
710  case TSK_ImplicitInstantiation:
711    // Nothing to visit
712    return false;
713      
714  case TSK_ExplicitInstantiationDeclaration:
715  case TSK_ExplicitInstantiationDefinition:
716    break;
717      
718  case TSK_ExplicitSpecialization:
719    ShouldVisitBody = true;
720    break;
721  }
722  
723  // Visit the template arguments used in the specialization.
724  if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
725    TypeLoc TL = SpecType->getTypeLoc();
726    if (TemplateSpecializationTypeLoc TSTLoc =
727            TL.getAs<TemplateSpecializationTypeLoc>()) {
728      for (unsigned I = 0N = TSTLoc.getNumArgs(); I != N; ++I)
729        if (VisitTemplateArgumentLoc(TSTLoc.getArgLoc(I)))
730          return true;
731    }
732  }
733
734  return ShouldVisitBody && VisitCXXRecordDecl(D);
735}
736
737bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
738                                   ClassTemplatePartialSpecializationDecl *D) {
739  // FIXME: Visit the "outer" template parameter lists on the TagDecl
740  // before visiting these template parameters.
741  if (VisitTemplateParameters(D->getTemplateParameters()))
742    return true;
743
744  // Visit the partial specialization arguments.
745  const ASTTemplateArgumentListInfo *Info = D->getTemplateArgsAsWritten();
746  const TemplateArgumentLoc *TemplateArgs = Info->getTemplateArgs();
747  for (unsigned I = 0N = Info->NumTemplateArgsI != N; ++I)
748    if (VisitTemplateArgumentLoc(TemplateArgs[I]))
749      return true;
750  
751  return VisitCXXRecordDecl(D);
752}
753
754bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
755  // Visit the default argument.
756  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
757    if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
758      if (Visit(DefArg->getTypeLoc()))
759        return true;
760  
761  return false;
762}
763
764bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
765  if (Expr *Init = D->getInitExpr())
766    return Visit(MakeCXCursor(InitStmtParentTURegionOfInterest));
767  return false;
768}
769
770bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
771  unsigned NumParamList = DD->getNumTemplateParameterLists();
772  for (unsigned i = 0i < NumParamListi++) {
773    TemplateParameterListParams = DD->getTemplateParameterList(i);
774    if (VisitTemplateParameters(Params))
775      return true;
776  }
777
778  if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
779    if (Visit(TSInfo->getTypeLoc()))
780      return true;
781
782  // Visit the nested-name-specifier, if present.
783  if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
784    if (VisitNestedNameSpecifierLoc(QualifierLoc))
785      return true;
786
787  return false;
788}
789
790static bool HasTrailingReturnType(FunctionDecl *ND) {
791  const QualType Ty = ND->getType();
792  if (const FunctionType *AFT = Ty->getAs<FunctionType>()) {
793    if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(AFT))
794      return FT->hasTrailingReturn();
795  }
796
797  return false;
798}
799
800/// Compare two base or member initializers based on their source order.
801static int CompareCXXCtorInitializers(CXXCtorInitializer *const *X,
802                                      CXXCtorInitializer *const *Y) {
803  return (*X)->getSourceOrder() - (*Y)->getSourceOrder();
804}
805
806bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
807  unsigned NumParamList = ND->getNumTemplateParameterLists();
808  for (unsigned i = 0i < NumParamListi++) {
809    TemplateParameterListParams = ND->getTemplateParameterList(i);
810    if (VisitTemplateParameters(Params))
811      return true;
812  }
813
814  if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
815    // Visit the function declaration's syntactic components in the order
816    // written. This requires a bit of work.
817    TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
818    FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>();
819    const bool HasTrailingRT = HasTrailingReturnType(ND);
820    
821    // If we have a function declared directly (without the use of a typedef),
822    // visit just the return type. Otherwise, just visit the function's type
823    // now.
824    if ((FTL && !isa<CXXConversionDecl>(ND) && !HasTrailingRT &&
825         Visit(FTL.getReturnLoc())) ||
826        (!FTL && Visit(TL)))
827      return true;
828
829    // Visit the nested-name-specifier, if present.
830    if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
831      if (VisitNestedNameSpecifierLoc(QualifierLoc))
832        return true;
833    
834    // Visit the declaration name.
835    if (!isa<CXXDestructorDecl>(ND))
836      if (VisitDeclarationNameInfo(ND->getNameInfo()))
837        return true;
838    
839    // FIXME: Visit explicitly-specified template arguments!
840    
841    // Visit the function parameters, if we have a function type.
842    if (FTL && VisitFunctionTypeLoc(FTLtrue))
843      return true;
844
845    // Visit the function's trailing return type.
846    if (FTL && HasTrailingRT && Visit(FTL.getReturnLoc()))
847      return true;
848
849    // FIXME: Attributes?
850  }
851  
852  if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
853    if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
854      // Find the initializers that were written in the source.
855      SmallVector<CXXCtorInitializer *, 4WrittenInits;
856      for (auto *I : Constructor->inits()) {
857        if (!I->isWritten())
858          continue;
859      
860        WrittenInits.push_back(I);
861      }
862      
863      // Sort the initializers in source order
864      llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
865                           &CompareCXXCtorInitializers);
866      
867      // Visit the initializers in source order
868      for (unsigned I = 0N = WrittenInits.size(); I != N; ++I) {
869        CXXCtorInitializer *Init = WrittenInits[I];
870        if (Init->isAnyMemberInitializer()) {
871          if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
872                                        Init->getMemberLocation(), TU)))
873            return true;
874        } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
875          if (Visit(TInfo->getTypeLoc()))
876            return true;
877        }
878        
879        // Visit the initializer value.
880        if (Expr *Initializer = Init->getInit())
881          if (Visit(MakeCXCursor(InitializerNDTURegionOfInterest)))
882            return true;
883      } 
884    }
885    
886    if (Visit(MakeCXCursor(ND->getBody(), StmtParentTURegionOfInterest)))
887      return true;
888  }
889
890  return false;
891}
892
893bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
894  if (VisitDeclaratorDecl(D))
895    return true;
896
897  if (Expr *BitWidth = D->getBitWidth())
898    return Visit(MakeCXCursor(BitWidthStmtParentTURegionOfInterest));
899
900  if (Expr *Init = D->getInClassInitializer())
901    return Visit(MakeCXCursor(InitStmtParentTURegionOfInterest));
902
903  return false;
904}
905
906bool CursorVisitor::VisitVarDecl(VarDecl *D) {
907  if (VisitDeclaratorDecl(D))
908    return true;
909
910  if (Expr *Init = D->getInit())
911    return Visit(MakeCXCursor(InitStmtParentTURegionOfInterest));
912
913  return false;
914}
915
916bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
917  if (VisitDeclaratorDecl(D))
918    return true;
919  
920  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
921    if (Expr *DefArg = D->getDefaultArgument())
922      return Visit(MakeCXCursor(DefArgStmtParentTURegionOfInterest));
923  
924  return false;  
925}
926
927bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
928  // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
929  // before visiting these template parameters.
930  if (VisitTemplateParameters(D->getTemplateParameters()))
931    return true;
932  
933  autoFD = D->getTemplatedDecl();
934  return VisitAttributes(FD) || VisitFunctionDecl(FD);
935}
936
937bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
938  // FIXME: Visit the "outer" template parameter lists on the TagDecl
939  // before visiting these template parameters.
940  if (VisitTemplateParameters(D->getTemplateParameters()))
941    return true;
942  
943  autoCD = D->getTemplatedDecl();
944  return VisitAttributes(CD) || VisitCXXRecordDecl(CD);
945}
946
947bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
948  if (VisitTemplateParameters(D->getTemplateParameters()))
949    return true;
950  
951  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
952      VisitTemplateArgumentLoc(D->getDefaultArgument()))
953    return true;
954  
955  return false;
956}
957
958bool CursorVisitor::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
959  // Visit the bound, if it's explicit.
960  if (D->hasExplicitBound()) {
961    if (auto TInfo = D->getTypeSourceInfo()) {
962      if (Visit(TInfo->getTypeLoc()))
963        return true;
964    }
965  }
966
967  return false;
968}
969
970bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
971  if (TypeSourceInfo *TSInfo = ND->getReturnTypeSourceInfo())
972    if (Visit(TSInfo->getTypeLoc()))
973      return true;
974
975  for (const auto *P : ND->parameters()) {
976    if (Visit(MakeCXCursor(P, TU, RegionOfInterest)))
977      return true;
978  }
979
980  return ND->isThisDeclarationADefinition() &&
981         Visit(MakeCXCursor(ND->getBody(), StmtParentTURegionOfInterest));
982}
983
984template <typename DeclIt>
985static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
986                                      SourceManager &SMSourceLocation EndLoc,
987                                      SmallVectorImpl<Decl *> &Decls) {
988  DeclIt next = *DI_current;
989  while (++next != DE_current) {
990    Decl *D_next = *next;
991    if (!D_next)
992      break;
993    SourceLocation L = D_next->getBeginLoc();
994    if (!L.isValid())
995      break;
996    if (SM.isBeforeInTranslationUnit(LEndLoc)) {
997      *DI_current = next;
998      Decls.push_back(D_next);
999      continue;
1000    }
1001    break;
1002  }
1003}
1004
1005bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
1006  // FIXME: Eventually convert back to just 'VisitDeclContext()'.  Essentially
1007  // an @implementation can lexically contain Decls that are not properly
1008  // nested in the AST.  When we identify such cases, we need to retrofit
1009  // this nesting here.
1010  if (!DI_current && !FileDI_current)
1011    return VisitDeclContext(D);
1012
1013  // Scan the Decls that immediately come after the container
1014  // in the current DeclContext.  If any fall within the
1015  // container's lexical region, stash them into a vector
1016  // for later processing.
1017  SmallVector<Decl *, 24DeclsInContainer;
1018  SourceLocation EndLoc = D->getSourceRange().getEnd();
1019  SourceManager &SM = AU->getSourceManager();
1020  if (EndLoc.isValid()) {
1021    if (DI_current) {
1022      addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
1023                                DeclsInContainer);
1024    } else {
1025      addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
1026                                DeclsInContainer);
1027    }
1028  }
1029
1030  // The common case.
1031  if (DeclsInContainer.empty())
1032    return VisitDeclContext(D);
1033
1034  // Get all the Decls in the DeclContext, and sort them with the
1035  // additional ones we've collected.  Then visit them.
1036  for (auto *SubDecl : D->decls()) {
1037    if (!SubDecl || SubDecl->getLexicalDeclContext() != D ||
1038        SubDecl->getBeginLoc().isInvalid())
1039      continue;
1040    DeclsInContainer.push_back(SubDecl);
1041  }
1042
1043  // Now sort the Decls so that they appear in lexical order.
1044  llvm::sort(DeclsInContainer,
1045             [&SM](Decl *A, Decl *B) {
1046               SourceLocation L_A = A->getBeginLoc();
1047               SourceLocation L_B = B->getBeginLoc();
1048               return L_A != L_B ? SM.isBeforeInTranslationUnit(L_A, L_B)
1049                                 : SM.isBeforeInTranslationUnit(A->getEndLoc(),
1050                                                                B->getEndLoc());
1051             });
1052
1053  // Now visit the decls.
1054  for (SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
1055         E = DeclsInContainer.end(); I != E; ++I) {
1056    CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
1057    const Optional<bool> &V = shouldVisitCursor(Cursor);
1058    if (!V.hasValue())
1059      continue;
1060    if (!V.getValue())
1061      return false;
1062    if (Visit(Cursor, true))
1063      return true;
1064  }
1065  return false;
1066}
1067
1068bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
1069  if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
1070                                   TU)))
1071    return true;
1072
1073  if (VisitObjCTypeParamList(ND->getTypeParamList()))
1074    return true;
1075
1076  ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
1077  for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
1078         E = ND->protocol_end(); I != E; ++I, ++PL)
1079    if (Visit(MakeCursorObjCProtocolRef(*I, *PLTU)))
1080      return true;
1081
1082  return VisitObjCContainerDecl(ND);
1083}
1084
1085bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1086  if (!PID->isThisDeclarationADefinition())
1087    return Visit(MakeCursorObjCProtocolRef(PIDPID->getLocation(), TU));
1088  
1089  ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1090  for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1091       E = PID->protocol_end(); I != E; ++I, ++PL)
1092    if (Visit(MakeCursorObjCProtocolRef(*I, *PLTU)))
1093      return true;
1094
1095  return VisitObjCContainerDecl(PID);
1096}
1097
1098bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
1099  if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
1100    return true;
1101
1102  // FIXME: This implements a workaround with @property declarations also being
1103  // installed in the DeclContext for the @interface.  Eventually this code
1104  // should be removed.
1105  ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1106  if (!CDecl || !CDecl->IsClassExtension())
1107    return false;
1108
1109  ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1110  if (!ID)
1111    return false;
1112
1113  IdentifierInfo *PropertyId = PD->getIdentifier();
1114  ObjCPropertyDecl *prevDecl =
1115    ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId,
1116                                       PD->getQueryKind());
1117
1118  if (!prevDecl)
1119    return false;
1120
1121  // Visit synthesized methods since they will be skipped when visiting
1122  // the @interface.
1123  if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
1124    if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1125      if (Visit(MakeCXCursor(MDTURegionOfInterest)))
1126        return true;
1127
1128  if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
1129    if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1130      if (Visit(MakeCXCursor(MDTURegionOfInterest)))
1131        return true;
1132
1133  return false;
1134}
1135
1136bool CursorVisitor::VisitObjCTypeParamList(ObjCTypeParamList *typeParamList) {
1137  if (!typeParamList)
1138    return false;
1139
1140  for (auto *typeParam : *typeParamList) {
1141    // Visit the type parameter.
1142    if (Visit(MakeCXCursor(typeParamTURegionOfInterest)))
1143      return true;
1144  }
1145
1146  return false;
1147}
1148
1149bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
1150  if (!D->isThisDeclarationADefinition()) {
1151    // Forward declaration is treated like a reference.
1152    return Visit(MakeCursorObjCClassRef(DD->getLocation(), TU));
1153  }
1154
1155  // Objective-C type parameters.
1156  if (VisitObjCTypeParamList(D->getTypeParamListAsWritten()))
1157    return true;
1158
1159  // Issue callbacks for super class.
1160  if (D->getSuperClass() &&
1161      Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1162                                        D->getSuperClassLoc(),
1163                                        TU)))
1164    return true;
1165
1166  if (TypeSourceInfo *SuperClassTInfo = D->getSuperClassTInfo())
1167    if (Visit(SuperClassTInfo->getTypeLoc()))
1168      return true;
1169
1170  ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1171  for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1172         E = D->protocol_end(); I != E; ++I, ++PL)
1173    if (Visit(MakeCursorObjCProtocolRef(*I, *PLTU)))
1174      return true;
1175
1176  return VisitObjCContainerDecl(D);
1177}
1178
1179bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1180  return VisitObjCContainerDecl(D);
1181}
1182
1183bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1184  // 'ID' could be null when dealing with invalid code.
1185  if (ObjCInterfaceDecl *ID = D->getClassInterface())
1186    if (Visit(MakeCursorObjCClassRef(IDD->getLocation(), TU)))
1187      return true;
1188
1189  return VisitObjCImplDecl(D);
1190}
1191
1192bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1193#if 0
1194  // Issue callbacks for super class.
1195  // FIXME: No source location information!
1196  if (D->getSuperClass() &&
1197      Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1198                                        D->getSuperClassLoc(),
1199                                        TU)))
1200    return true;
1201#endif
1202
1203  return VisitObjCImplDecl(D);
1204}
1205
1206bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1207  if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1208    if (PD->isIvarNameSpecified())
1209      return Visit(MakeCursorMemberRef(IvarPD->getPropertyIvarDeclLoc(), TU));
1210  
1211  return false;
1212}
1213
1214bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1215  return VisitDeclContext(D);
1216}
1217
1218bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1219  // Visit nested-name-specifier.
1220  if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1221    if (VisitNestedNameSpecifierLoc(QualifierLoc))
1222      return true;
1223  
1224  return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(), 
1225                                      D->getTargetNameLoc(), TU));
1226}
1227
1228bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1229  // Visit nested-name-specifier.
1230  if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1231    if (VisitNestedNameSpecifierLoc(QualifierLoc))
1232      return true;
1233  }
1234  
1235  if (Visit(MakeCursorOverloadedDeclRef(DD->getLocation(), TU)))
1236    return true;
1237    
1238  return VisitDeclarationNameInfo(D->getNameInfo());
1239}
1240
1241bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1242  // Visit nested-name-specifier.
1243  if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1244    if (VisitNestedNameSpecifierLoc(QualifierLoc))
1245      return true;
1246
1247  return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1248                                      D->getIdentLocation(), TU));
1249}
1250
1251bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1252  // Visit nested-name-specifier.
1253  if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1254    if (VisitNestedNameSpecifierLoc(QualifierLoc))
1255      return true;
1256  }
1257
1258  return VisitDeclarationNameInfo(D->getNameInfo());
1259}
1260
1261bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1262                                               UnresolvedUsingTypenameDecl *D) {
1263  // Visit nested-name-specifier.
1264  if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1265    if (VisitNestedNameSpecifierLoc(QualifierLoc))
1266      return true;
1267  
1268  return false;
1269}
1270
1271bool CursorVisitor::VisitStaticAssertDecl(StaticAssertDecl *D) {
1272  if (Visit(MakeCXCursor(D->getAssertExpr(), StmtParentTURegionOfInterest)))
1273    return true;
1274  if (StringLiteral *Message = D->getMessage())
1275    if (Visit(MakeCXCursor(MessageStmtParentTURegionOfInterest)))
1276      return true;
1277  return false;
1278}
1279
1280bool CursorVisitor::VisitFriendDecl(FriendDecl *D) {
1281  if (NamedDecl *FriendD = D->getFriendDecl()) {
1282    if (Visit(MakeCXCursor(FriendDTURegionOfInterest)))
1283      return true;
1284  } else if (TypeSourceInfo *TI = D->getFriendType()) {
1285    if (Visit(TI->getTypeLoc()))
1286      return true;
1287  }
1288  return false;
1289}
1290
1291bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1292  switch (Name.getName().getNameKind()) {
1293  case clang::DeclarationName::Identifier:
1294  case clang::DeclarationName::CXXLiteralOperatorName:
1295  case clang::DeclarationName::CXXDeductionGuideName:
1296  case clang::DeclarationName::CXXOperatorName:
1297  case clang::DeclarationName::CXXUsingDirective:
1298    return false;
1299
1300  case clang::DeclarationName::CXXConstructorName:
1301  case clang::DeclarationName::CXXDestructorName:
1302  case clang::DeclarationName::CXXConversionFunctionName:
1303    if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1304      return Visit(TSInfo->getTypeLoc());
1305    return false;
1306
1307  case clang::DeclarationName::ObjCZeroArgSelector:
1308  case clang::DeclarationName::ObjCOneArgSelector:
1309  case clang::DeclarationName::ObjCMultiArgSelector:
1310    // FIXME: Per-identifier location info?
1311    return false;
1312  }
1313
1314  llvm_unreachable("Invalid DeclarationName::Kind!");
1315}
1316
1317bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS
1318                                             SourceRange Range) {
1319  // FIXME: This whole routine is a hack to work around the lack of proper
1320  // source information in nested-name-specifiers (PR5791). Since we do have
1321  // a beginning source location, we can visit the first component of the
1322  // nested-name-specifier, if it's a single-token component.
1323  if (!NNS)
1324    return false;
1325  
1326  // Get the first component in the nested-name-specifier.
1327  while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1328    NNS = Prefix;
1329  
1330  switch (NNS->getKind()) {
1331  case NestedNameSpecifier::Namespace:
1332    return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1333                                        TU));
1334
1335  case NestedNameSpecifier::NamespaceAlias:
1336    return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(), 
1337                                        Range.getBegin(), TU));
1338
1339  case NestedNameSpecifier::TypeSpec: {
1340    // If the type has a form where we know that the beginning of the source
1341    // range matches up with a reference cursor. Visit the appropriate reference
1342    // cursor.
1343    const Type *T = NNS->getAsType();
1344    if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1345      return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1346    if (const TagType *Tag = dyn_cast<TagType>(T))
1347      return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1348    if (const TemplateSpecializationType *TST
1349                                      = dyn_cast<TemplateSpecializationType>(T))
1350      return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1351    break;
1352  }
1353      
1354  case NestedNameSpecifier::TypeSpecWithTemplate:
1355  case NestedNameSpecifier::Global:
1356  case NestedNameSpecifier::Identifier:
1357  case NestedNameSpecifier::Super:
1358    break;      
1359  }
1360  
1361  return false;
1362}
1363
1364bool 
1365CursorVisitor::VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
1366  SmallVector<NestedNameSpecifierLoc4Qualifiers;
1367  for (; Qualifier; Qualifier = Qualifier.getPrefix())
1368    Qualifiers.push_back(Qualifier);
1369  
1370  while (!Qualifiers.empty()) {
1371    NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1372    NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1373    switch (NNS->getKind()) {
1374    case NestedNameSpecifier::Namespace:
1375      if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), 
1376                                       Q.getLocalBeginLoc(),
1377                                       TU)))
1378        return true;
1379        
1380      break;
1381      
1382    case NestedNameSpecifier::NamespaceAlias:
1383      if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(), 
1384                                       Q.getLocalBeginLoc(),
1385                                       TU)))
1386        return true;
1387        
1388      break;
1389        
1390    case NestedNameSpecifier::TypeSpec:
1391    case NestedNameSpecifier::TypeSpecWithTemplate:
1392      if (Visit(Q.getTypeLoc()))
1393        return true;
1394        
1395      break;
1396        
1397    case NestedNameSpecifier::Global:
1398    case NestedNameSpecifier::Identifier:
1399    case NestedNameSpecifier::Super:
1400      break;              
1401    }
1402  }
1403  
1404  return false;
1405}
1406
1407bool CursorVisitor::VisitTemplateParameters(
1408                                          const TemplateParameterList *Params) {
1409  if (!Params)
1410    return false;
1411  
1412  for (TemplateParameterList::const_iterator P = Params->begin(),
1413                                          PEnd = Params->end();
1414       P != PEnd; ++P) {
1415    if (Visit(MakeCXCursor(*PTURegionOfInterest)))
1416      return true;
1417  }
1418  
1419  return false;
1420}
1421
1422bool CursorVisitor::VisitTemplateName(TemplateName NameSourceLocation Loc) {
1423  switch (Name.getKind()) {
1424  case TemplateName::Template:
1425    return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), LocTU));
1426
1427  case TemplateName::OverloadedTemplate:
1428    // Visit the overloaded template set.
1429    if (Visit(MakeCursorOverloadedDeclRef(NameLocTU)))
1430      return true;
1431
1432    return false;
1433
1434  case TemplateName::DependentTemplate:
1435    // FIXME: Visit nested-name-specifier.
1436    return false;
1437      
1438  case TemplateName::QualifiedTemplate:
1439    // FIXME: Visit nested-name-specifier.
1440    return Visit(MakeCursorTemplateRef(
1441                                  Name.getAsQualifiedTemplateName()->getDecl(), 
1442                                       LocTU));
1443
1444  case TemplateName::SubstTemplateTemplateParm:
1445    return Visit(MakeCursorTemplateRef(
1446                         Name.getAsSubstTemplateTemplateParm()->getParameter(),
1447                                       LocTU));
1448      
1449  case TemplateName::SubstTemplateTemplateParmPack:
1450    return Visit(MakeCursorTemplateRef(
1451                  Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(),
1452                                       LocTU));
1453  }
1454
1455  llvm_unreachable("Invalid TemplateName::Kind!");
1456}
1457
1458bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1459  switch (TAL.getArgument().getKind()) {
1460  case TemplateArgument::Null:
1461  case TemplateArgument::Integral:
1462  case TemplateArgument::Pack:
1463    return false;
1464      
1465  case TemplateArgument::Type:
1466    if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1467      return Visit(TSInfo->getTypeLoc());
1468    return false;
1469      
1470  case TemplateArgument::Declaration:
1471    if (Expr *E = TAL.getSourceDeclExpression())
1472      return Visit(MakeCXCursor(EStmtParentTURegionOfInterest));
1473    return false;
1474
1475  case TemplateArgument::NullPtr:
1476    if (Expr *E = TAL.getSourceNullPtrExpression())
1477      return Visit(MakeCXCursor(EStmtParentTURegionOfInterest));
1478    return false;
1479
1480  case TemplateArgument::Expression:
1481    if (Expr *E = TAL.getSourceExpression())
1482      return Visit(MakeCXCursor(EStmtParentTURegionOfInterest));
1483    return false;
1484  
1485  case TemplateArgument::Template:
1486  case TemplateArgument::TemplateExpansion:
1487    if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1488      return true;
1489      
1490    return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(), 
1491                             TAL.getTemplateNameLoc());
1492  }
1493
1494  llvm_unreachable("Invalid TemplateArgument::Kind!");
1495}
1496
1497bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1498  return VisitDeclContext(D);
1499}
1500
1501bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1502  return Visit(TL.getUnqualifiedLoc());
1503}
1504
1505bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1506  ASTContext &Context = AU->getASTContext();
1507
1508  // Some builtin types (such as Objective-C's "id", "sel", and
1509  // "Class") have associated declarations. Create cursors for those.
1510  QualType VisitType;
1511  switch (TL.getTypePtr()->getKind()) {
1512
1513  case BuiltinType::Void:
1514  case BuiltinType::NullPtr:
1515  case BuiltinType::Dependent:
1516#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1517  case BuiltinType::Id:
1518#include "clang/Basic/OpenCLImageTypes.def"
1519#define EXT_OPAQUE_TYPE(ExtTYpe, Id, Ext) \
1520  case BuiltinType::Id:
1521#include "clang/Basic/OpenCLExtensionTypes.def"
1522  case BuiltinType::OCLSampler:
1523  case BuiltinType::OCLEvent:
1524  case BuiltinType::OCLClkEvent:
1525  case BuiltinType::OCLQueue:
1526  case BuiltinType::OCLReserveID:
1527#define BUILTIN_TYPE(Id, SingletonId)
1528#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1529#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1530#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1531#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1532#include "clang/AST/BuiltinTypes.def"
1533    break;
1534
1535  case BuiltinType::ObjCId:
1536    VisitType = Context.getObjCIdType();
1537    break;
1538
1539  case BuiltinType::ObjCClass:
1540    VisitType = Context.getObjCClassType();
1541    break;
1542
1543  case BuiltinType::ObjCSel:
1544    VisitType = Context.getObjCSelType();
1545    break;
1546  }
1547
1548  if (!VisitType.isNull()) {
1549    if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1550      return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
1551                                     TU));
1552  }
1553
1554  return false;
1555}
1556
1557bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1558  return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1559}
1560
1561bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1562  return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1563}
1564
1565bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1566  if (TL.isDefinition())
1567    return Visit(MakeCXCursor(TL.getDecl(), TURegionOfInterest));
1568
1569  return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1570}
1571
1572bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1573  return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1574}
1575
1576bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1577  return Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU));
1578}
1579
1580bool CursorVisitor::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
1581  if (Visit(MakeCursorTypeRef(TL.getDecl(), TL.getBeginLoc(), TU)))
1582    return true;
1583  for (unsigned I = 0N = TL.getNumProtocols(); I != N; ++I) {
1584    if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1585                                        TU)))
1586      return true;
1587  }
1588
1589  return false;
1590}
1591
1592bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1593  if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1594    return true;
1595
1596  for (unsigned I = 0N = TL.getNumTypeArgs(); I != N; ++I) {
1597    if (Visit(TL.getTypeArgTInfo(I)->getTypeLoc()))
1598      return true;
1599  }
1600
1601  for (unsigned I = 0N = TL.getNumProtocols(); I != N; ++I) {
1602    if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1603                                        TU)))
1604      return true;
1605  }
1606
1607  return false;
1608}
1609
1610bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1611  return Visit(TL.getPointeeLoc());
1612}
1613
1614bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1615  return Visit(TL.getInnerLoc());
1616}
1617
1618bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1619  return Visit(TL.getPointeeLoc());
1620}
1621
1622bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1623  return Visit(TL.getPointeeLoc());
1624}
1625
1626bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1627  return Visit(TL.getPointeeLoc());
1628}
1629
1630bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1631  return Visit(TL.getPointeeLoc());
1632}
1633
1634bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1635  return Visit(TL.getPointeeLoc());
1636}
1637
1638bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1639  return Visit(TL.getModifiedLoc());
1640}
1641
1642bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL
1643                                         bool SkipResultType) {
1644  if (!SkipResultType && Visit(TL.getReturnLoc()))
1645    return true;
1646
1647  for (unsigned I = 0N = TL.getNumParams(); I != N; ++I)
1648    if (Decl *D = TL.getParam(I))
1649      if (Visit(MakeCXCursor(DTURegionOfInterest)))
1650        return true;
1651
1652  return false;
1653}
1654
1655bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1656  if (Visit(TL.getElementLoc()))
1657    return true;
1658
1659  if (Expr *Size = TL.getSizeExpr())
1660    return Visit(MakeCXCursor(SizeStmtParentTURegionOfInterest));
1661
1662  return false;
1663}
1664
1665bool CursorVisitor::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
1666  return Visit(TL.getOriginalLoc());
1667}
1668
1669bool CursorVisitor::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
1670  return Visit(TL.getOriginalLoc());
1671}
1672
1673bool CursorVisitor::VisitDeducedTemplateSpecializationTypeLoc(
1674    DeducedTemplateSpecializationTypeLoc TL) {
1675  if (VisitTemplateName(TL.getTypePtr()->getTemplateName(), 
1676                        TL.getTemplateNameLoc()))
1677    return true;
1678  
1679  return false;
1680}
1681
1682bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1683                                             TemplateSpecializationTypeLoc TL) {
1684  // Visit the template name.
1685  if (VisitTemplateName(TL.getTypePtr()->getTemplateName(), 
1686                        TL.getTemplateNameLoc()))
1687    return true;
1688  
1689  // Visit the template arguments.
1690  for (unsigned I = 0N = TL.getNumArgs(); I != N; ++I)
1691    if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1692      return true;
1693  
1694  return false;
1695}
1696
1697bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1698  return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParentTU));
1699}
1700
1701bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1702  if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1703    return Visit(TSInfo->getTypeLoc());
1704
1705  return false;
1706}
1707
1708bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1709  if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1710    return Visit(TSInfo->getTypeLoc());
1711
1712  return false;
1713}
1714
1715bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1716  return VisitNestedNameSpecifierLoc(TL.getQualifierLoc());
1717}
1718
1719bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1720                                    DependentTemplateSpecializationTypeLoc TL) {
1721  // Visit the nested-name-specifier, if there is one.
1722  if (TL.getQualifierLoc() &&
1723      VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1724    return true;
1725  
1726  // Visit the template arguments.
1727  for (unsigned I = 0N = TL.getNumArgs(); I != N; ++I)
1728    if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1729      return true;
1730
1731  return false;
1732}
1733
1734bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1735  if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1736    return true;
1737  
1738  return Visit(TL.getNamedTypeLoc());
1739}
1740
1741bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1742  return Visit(TL.getPatternLoc());
1743}
1744
1745bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1746  if (Expr *E = TL.getUnderlyingExpr())
1747    return Visit(MakeCXCursor(EStmtParentTU));
1748
1749  return false;
1750}
1751
1752bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1753  return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1754}
1755
1756bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1757  return Visit(TL.getValueLoc());
1758}
1759
1760bool CursorVisitor::VisitPipeTypeLoc(PipeTypeLoc TL) {
1761  return Visit(TL.getValueLoc());
1762}
1763
1764#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
1765bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1766  return Visit##PARENT##Loc(TL); \
1767}
1768
1769DEFAULT_TYPELOC_IMPL(Complex, Type)
1770DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1771DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1772DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1773DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1774DEFAULT_TYPELOC_IMPL(DependentAddressSpace, Type)
1775DEFAULT_TYPELOC_IMPL(DependentVector, Type)
1776DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1777DEFAULT_TYPELOC_IMPL(Vector, Type)
1778DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1779DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1780DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1781DEFAULT_TYPELOC_IMPL(Record, TagType)
1782DEFAULT_TYPELOC_IMPL(Enum, TagType)
1783DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1784DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1785DEFAULT_TYPELOC_IMPL(Auto, Type)
1786
1787bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1788  // Visit the nested-name-specifier, if present.
1789  if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1790    if (VisitNestedNameSpecifierLoc(QualifierLoc))
1791      return true;
1792
1793  if (D->isCompleteDefinition()) {
1794    for (const auto &I : D->bases()) {
1795      if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU)))
1796        return true;
1797    }
1798  }
1799
1800  return VisitTagDecl(D);
1801}
1802
1803bool CursorVisitor::VisitAttributes(Decl *D) {
1804  for (const auto *I : D->attrs())
1805    if ((TU->ParsingOptions & CXTranslationUnit_VisitImplicitAttributes ||
1806         !I->isImplicit()) &&
1807        Visit(MakeCXCursor(I, D, TU)))
1808        return true;
1809
1810  return false;
1811}
1812
1813//===----------------------------------------------------------------------===//
1814// Data-recursive visitor methods.
1815//===----------------------------------------------------------------------===//
1816
1817namespace {
1818#define DEF_JOB(NAME, DATA, KIND)\
1819class NAME : public VisitorJob {\
1820public:\
1821  NAME(const DATA *d, CXCursor parent) : \
1822      VisitorJob(parent, VisitorJob::KIND, d) {} \
1823  static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
1824  const DATA *get() const { return static_cast<const DATA*>(data[0]); }\
1825};
1826
1827DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1828DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1829DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1830DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
1831DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1832DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
1833DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
1834#undef DEF_JOB
1835
1836class ExplicitTemplateArgsVisit : public VisitorJob {
1837public:
1838  ExplicitTemplateArgsVisit(const TemplateArgumentLoc *Begin,
1839                            const TemplateArgumentLoc *EndCXCursor parent)
1840      : VisitorJob(parentVisitorJob::ExplicitTemplateArgsVisitKindBegin,
1841                   End) {}
1842  static bool classof(const VisitorJob *VJ) {
1843    return VJ->getKind() == ExplicitTemplateArgsVisitKind;
1844  }
1845  const TemplateArgumentLoc *begin() const {
1846    return static_cast<const TemplateArgumentLoc *>(data[0]);
1847  }
1848  const TemplateArgumentLoc *end() {
1849    return static_cast<const TemplateArgumentLoc *>(data[1]);
1850  }
1851};
1852class DeclVisit : public VisitorJob {
1853public:
1854  DeclVisit(const Decl *DCXCursor parentbool isFirst) :
1855    VisitorJob(parentVisitorJob::DeclVisitKind,
1856               DisFirst ? (void*) 1 : (void*) nullptr) {}
1857  static bool classof(const VisitorJob *VJ) {
1858    return VJ->getKind() == DeclVisitKind;
1859  }
1860  const Decl *get() const { return static_cast<const Decl *>(data[0]); }
1861  bool isFirst() const { return data[1] != nullptr; }
1862};
1863class TypeLocVisit : public VisitorJob {
1864public:
1865  TypeLocVisit(TypeLoc tlCXCursor parent) :
1866    VisitorJob(parentVisitorJob::TypeLocVisitKind,
1867               tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1868
1869  static bool classof(const VisitorJob *VJ) {
1870    return VJ->getKind() == TypeLocVisitKind;
1871  }
1872
1873  TypeLoc get() const { 
1874    QualType T = QualType::getFromOpaquePtr(data[0]);
1875    return TypeLoc(Tconst_cast<void *>(data[1]));
1876  }
1877};
1878
1879class LabelRefVisit : public VisitorJob {
1880public:
1881  LabelRefVisit(LabelDecl *LDSourceLocation labelLocCXCursor parent)
1882    : VisitorJob(parentVisitorJob::LabelRefVisitKindLD,
1883                 labelLoc.getPtrEncoding()) {}
1884  
1885  static bool classof(const VisitorJob *VJ) {
1886    return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1887  }
1888  const LabelDecl *get() const {
1889    return static_cast<const LabelDecl *>(data[0]);
1890  }
1891  SourceLocation getLoc() const { 
1892    return SourceLocation::getFromPtrEncoding(data[1]); }
1893};
1894  
1895class NestedNameSpecifierLocVisit : public VisitorJob {
1896public:
1897  NestedNameSpecifierLocVisit(NestedNameSpecifierLoc QualifierCXCursor parent)
1898    : VisitorJob(parentVisitorJob::NestedNameSpecifierLocVisitKind,
1899                 Qualifier.getNestedNameSpecifier(),
1900                 Qualifier.getOpaqueData()) { }
1901  
1902  static bool classof(const VisitorJob *VJ) {
1903    return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1904  }
1905  
1906  NestedNameSpecifierLoc get() const {
1907    return NestedNameSpecifierLoc(
1908            const_cast<NestedNameSpecifier *>(
1909              static_cast<const NestedNameSpecifier *>(data[0])),
1910            const_cast<void *>(data[1]));
1911  }
1912};
1913  
1914class DeclarationNameInfoVisit : public VisitorJob {
1915public:
1916  DeclarationNameInfoVisit(const Stmt *SCXCursor parent)
1917    : VisitorJob(parentVisitorJob::DeclarationNameInfoVisitKindS) {}
1918  static bool classof(const VisitorJob *VJ) {
1919    return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1920  }
1921  DeclarationNameInfo get() const {
1922    const Stmt *S = static_cast<const Stmt *>(data[0]);
1923    switch (S->getStmtClass()) {
1924    default:
1925      llvm_unreachable("Unhandled Stmt");
1926    case clang::Stmt::MSDependentExistsStmtClass:
1927      return cast<MSDependentExistsStmt>(S)->getNameInfo();
1928    case Stmt::CXXDependentScopeMemberExprClass:
1929      return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1930    case Stmt::DependentScopeDeclRefExprClass:
1931      return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1932    case Stmt::OMPCriticalDirectiveClass:
1933      return cast<OMPCriticalDirective>(S)->getDirectiveName();
1934    }
1935  }
1936};
1937class MemberRefVisit : public VisitorJob {
1938public:
1939  MemberRefVisit(const FieldDecl *DSourceLocation LCXCursor parent)
1940    : VisitorJob(parentVisitorJob::MemberRefVisitKindD,
1941                 L.getPtrEncoding()) {}
1942  static bool classof(const VisitorJob *VJ) {
1943    return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1944  }
1945  const FieldDecl *get() const {
1946    return static_cast<const FieldDecl *>(data[0]);
1947  }
1948  SourceLocation getLoc() const {
1949    return SourceLocation::getFromRawEncoding((unsigned)(uintptr_tdata[1]);
1950  }
1951};
1952class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitorvoid> {
1953  friend class OMPClauseEnqueue;
1954  VisitorWorkList &WL;
1955  CXCursor Parent;
1956public:
1957  EnqueueVisitor(VisitorWorkList &wlCXCursor parent)
1958    : WL(wl), Parent(parent) {}
1959
1960  void VisitAddrLabelExpr(const AddrLabelExpr *E);
1961  void VisitBlockExpr(const BlockExpr *B);
1962  void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1963  void VisitCompoundStmt(const CompoundStmt *S);
1964  void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */ }
1965  void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S);
1966  void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E);
1967  void VisitCXXNewExpr(const CXXNewExpr *E);
1968  void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
1969  void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E);
1970  void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
1971  void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E);
1972  void VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1973  void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E);
1974  void VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1975  void VisitCXXCatchStmt(const CXXCatchStmt *S);
1976  void VisitCXXForRangeStmt(const CXXForRangeStmt *S);
1977  void VisitDeclRefExpr(const DeclRefExpr *D);
1978  void VisitDeclStmt(const DeclStmt *S);
1979  void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E);
1980  void VisitDesignatedInitExpr(const DesignatedInitExpr *E);
1981  void VisitExplicitCastExpr(const ExplicitCastExpr *E);
1982  void VisitForStmt(const ForStmt *FS);
1983  void VisitGotoStmt(const GotoStmt *GS);
1984  void VisitIfStmt(const IfStmt *If);
1985  void VisitInitListExpr(const InitListExpr *IE);
1986  void VisitMemberExpr(const MemberExpr *M);
1987  void VisitOffsetOfExpr(const OffsetOfExpr *E);
1988  void VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
1989  void VisitObjCMessageExpr(const ObjCMessageExpr *M);
1990  void VisitOverloadExpr(const OverloadExpr *E);
1991  void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
1992  void VisitStmt(const Stmt *S);
1993  void VisitSwitchStmt(const SwitchStmt *S);
1994  void VisitWhileStmt(const WhileStmt *W);
1995  void VisitTypeTraitExpr(const TypeTraitExpr *E);
1996  void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E);
1997  void VisitExpressionTraitExpr(const ExpressionTraitExpr *E);
1998  void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U);
1999  void VisitVAArgExpr(const VAArgExpr *E);
2000  void VisitSizeOfPackExpr(const SizeOfPackExpr *E);
2001  void VisitPseudoObjectExpr(const PseudoObjectExpr *E);
2002  void VisitOpaqueValueExpr(const OpaqueValueExpr *E);
2003  void VisitLambdaExpr(const LambdaExpr *E);
2004  void VisitOMPExecutableDirective(const OMPExecutableDirective *D);
2005  void VisitOMPLoopDirective(const OMPLoopDirective *D);
2006  void VisitOMPParallelDirective(const OMPParallelDirective *D);
2007  void VisitOMPSimdDirective(const OMPSimdDirective *D);
2008  void VisitOMPForDirective(const OMPForDirective *D);
2009  void VisitOMPForSimdDirective(const OMPForSimdDirective *D);
2010  void VisitOMPSectionsDirective(const OMPSectionsDirective *D);
2011  void VisitOMPSectionDirective(const OMPSectionDirective *D);
2012  void VisitOMPSingleDirective(const OMPSingleDirective *D);
2013  void VisitOMPMasterDirective(const OMPMasterDirective *D);
2014  void VisitOMPCriticalDirective(const OMPCriticalDirective *D);
2015  void VisitOMPParallelForDirective(const OMPParallelForDirective *D);
2016  void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D);
2017  void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D);
2018  void VisitOMPTaskDirective(const OMPTaskDirective *D);
2019  void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D);
2020  void VisitOMPBarrierDirective(const OMPBarrierDirective *D);
2021  void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D);
2022  void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D);
2023  void
2024  VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D);
2025  void VisitOMPCancelDirective(const OMPCancelDirective *D);
2026  void VisitOMPFlushDirective(const OMPFlushDirective *D);
2027  void VisitOMPOrderedDirective(const OMPOrderedDirective *D);
2028  void VisitOMPAtomicDirective(const OMPAtomicDirective *D);
2029  void VisitOMPTargetDirective(const OMPTargetDirective *D);
2030  void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D);
2031  void VisitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective *D);
2032  void VisitOMPTargetExitDataDirective(const OMPTargetExitDataDirective *D);
2033  void VisitOMPTargetParallelDirective(const OMPTargetParallelDirective *D);
2034  void
2035  VisitOMPTargetParallelForDirective(const OMPTargetParallelForDirective *D);
2036  void VisitOMPTeamsDirective(const OMPTeamsDirective *D);
2037  void VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D);
2038  void VisitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective *D);
2039  void VisitOMPDistributeDirective(const OMPDistributeDirective *D);
2040  void VisitOMPDistributeParallelForDirective(
2041      const OMPDistributeParallelForDirective *D);
2042  void VisitOMPDistributeParallelForSimdDirective(
2043      const OMPDistributeParallelForSimdDirective *D);
2044  void VisitOMPDistributeSimdDirective(const OMPDistributeSimdDirective *D);
2045  void VisitOMPTargetParallelForSimdDirective(
2046      const OMPTargetParallelForSimdDirective *D);
2047  void VisitOMPTargetSimdDirective(const OMPTargetSimdDirective *D);
2048  void VisitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective *D);
2049  void VisitOMPTeamsDistributeSimdDirective(
2050      const OMPTeamsDistributeSimdDirective *D);
2051  void VisitOMPTeamsDistributeParallelForSimdDirective(
2052      const OMPTeamsDistributeParallelForSimdDirective *D);
2053  void VisitOMPTeamsDistributeParallelForDirective(
2054      const OMPTeamsDistributeParallelForDirective *D);
2055  void VisitOMPTargetTeamsDirective(const OMPTargetTeamsDirective *D);
2056  void VisitOMPTargetTeamsDistributeDirective(
2057      const OMPTargetTeamsDistributeDirective *D);
2058  void VisitOMPTargetTeamsDistributeParallelForDirective(
2059      const OMPTargetTeamsDistributeParallelForDirective *D);
2060  void VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2061      const OMPTargetTeamsDistributeParallelForSimdDirective *D);
2062  void VisitOMPTargetTeamsDistributeSimdDirective(
2063      const OMPTargetTeamsDistributeSimdDirective *D);
2064
2065private:
2066  void AddDeclarationNameInfo(const Stmt *S);
2067  void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
2068  void AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2069                               unsigned NumTemplateArgs);
2070  void AddMemberRef(const FieldDecl *DSourceLocation L);
2071  void AddStmt(const Stmt *S);
2072  void AddDecl(const Decl *Dbool isFirst = true);
2073  void AddTypeLoc(TypeSourceInfo *TI);
2074  void EnqueueChildren(const Stmt *S);
2075  void EnqueueChildren(const OMPClause *S);
2076};
2077// end anonyous namespace
2078
2079void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
2080  // 'S' should always be non-null, since it comes from the
2081  // statement we are visiting.
2082  WL.push_back(DeclarationNameInfoVisit(S, Parent));
2083}
2084
2085void 
2086EnqueueVisitor::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier) {
2087  if (Qualifier)
2088    WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
2089}
2090
2091void EnqueueVisitor::AddStmt(const Stmt *S) {
2092  if (S)
2093    WL.push_back(StmtVisit(S, Parent));
2094}
2095void EnqueueVisitor::AddDecl(const Decl *Dbool isFirst) {
2096  if (D)
2097    WL.push_back(DeclVisit(D, Parent, isFirst));
2098}
2099void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2100                                             unsigned NumTemplateArgs) {
2101  WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent));
2102}
2103void EnqueueVisitor::AddMemberRef(const FieldDecl *DSourceLocation L) {
2104  if (D)
2105    WL.push_back(MemberRefVisit(D, L, Parent));
2106}
2107void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
2108  if (TI)
2109    WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
2110 }
2111void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
2112  unsigned size = WL.size();
2113  for (const Stmt *SubStmt : S->children()) {
2114    AddStmt(SubStmt);
2115  }
2116  if (size == WL.size())
2117    return;
2118  // Now reverse the entries we just added.  This will match the DFS
2119  // ordering performed by the worklist.
2120  VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2121  std::reverse(I, E);
2122}
2123namespace {
2124class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
2125  EnqueueVisitor *Visitor;
2126  /// Process clauses with list of variables.
2127  template <typename T>
2128  void VisitOMPClauseList(T *Node);
2129public:
2130  OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) { }
2131#define OPENMP_CLAUSE(Name, Class)                                             \
2132  void Visit##Class(const Class *C);
2133#include "clang/Basic/OpenMPKinds.def"
2134  void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C);
2135  void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C);
2136};
2137
2138void OMPClauseEnqueue::VisitOMPClauseWithPreInit(
2139    const OMPClauseWithPreInit *C) {
2140  Visitor->AddStmt(C->getPreInitStmt());
2141}
2142
2143void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate(
2144    const OMPClauseWithPostUpdate *C) {
2145  VisitOMPClauseWithPreInit(C);
2146  Visitor->AddStmt(C->getPostUpdateExpr());
2147}
2148
2149void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
2150  VisitOMPClauseWithPreInit(C);
2151  Visitor->AddStmt(C->getCondition());
2152}
2153
2154void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
2155  Visitor->AddStmt(C->getCondition());
2156}
2157
2158void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
2159  VisitOMPClauseWithPreInit(C);
2160  Visitor->AddStmt(C->getNumThreads());
2161}
2162
2163void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2164  Visitor->AddStmt(C->getSafelen());
2165}
2166
2167void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2168  Visitor->AddStmt(C->getSimdlen());
2169}
2170
2171void OMPClauseEnqueue::VisitOMPAllocatorClause(const OMPAllocatorClause *C) {
2172  Visitor->AddStmt(C->getAllocator());
2173}
2174
2175void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2176  Visitor->AddStmt(C->getNumForLoops());
2177}
2178
2179void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { }
2180
2181void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { }
2182
2183void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
2184  VisitOMPClauseWithPreInit(C);
2185  Visitor->AddStmt(C->getChunkSize());
2186}
2187
2188void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2189  Visitor->AddStmt(C->getNumForLoops());
2190}
2191
2192void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2193
2194void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2195
2196void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2197
2198void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2199
2200void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2201
2202void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2203
2204void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2205
2206void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2207
2208void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2209
2210void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2211
2212void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
2213
2214void OMPClauseEnqueue::VisitOMPUnifiedAddressClause(
2215    const OMPUnifiedAddressClause *) {}
2216
2217void OMPClauseEnqueue::VisitOMPUnifiedSharedMemoryClause(
2218    const OMPUnifiedSharedMemoryClause *) {}
2219
2220void OMPClauseEnqueue::VisitOMPReverseOffloadClause(
2221    const OMPReverseOffloadClause *) {}
2222
2223void OMPClauseEnqueue::VisitOMPDynamicAllocatorsClause(
2224    const OMPDynamicAllocatorsClause *) {}
2225
2226void OMPClauseEnqueue::VisitOMPAtomicDefaultMemOrderClause(
2227    const OMPAtomicDefaultMemOrderClause *) {}
2228
2229void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2230  Visitor->AddStmt(C->getDevice());
2231}
2232
2233void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
2234  VisitOMPClauseWithPreInit(C);
2235  Visitor->AddStmt(C->getNumTeams());
2236}
2237
2238void OMPClauseEnqueue::VisitOMPThreadLimitClause(const OMPThreadLimitClause *C) {
2239  VisitOMPClauseWithPreInit(C);
2240  Visitor->AddStmt(C->getThreadLimit());
2241}
2242
2243void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2244  Visitor->AddStmt(C->getPriority());
2245}
2246
2247void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2248  Visitor->AddStmt(C->getGrainsize());
2249}
2250
2251void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2252  Visitor->AddStmt(C->getNumTasks());
2253}
2254
2255void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2256  Visitor->AddStmt(C->getHint());
2257}
2258
2259template<typename T>
2260void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
2261  for (const auto *I : Node->varlists()) {
2262    Visitor->AddStmt(I);
2263  }
2264}
2265
2266void OMPClauseEnqueue::VisitOMPAllocateClause(const OMPAllocateClause *C) {
2267  VisitOMPClauseList(C);
2268  Visitor->AddStmt(C->getAllocator());
2269}
2270void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
2271  VisitOMPClauseList(C);
2272  for (const auto *E : C->private_copies()) {
2273    Visitor->AddStmt(E);
2274  }
2275}
2276void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2277                                        const OMPFirstprivateClause *C) {
2278  VisitOMPClauseList(C);
2279  VisitOMPClauseWithPreInit(C);
2280  for (const auto *E : C->private_copies()) {
2281    Visitor->AddStmt(E);
2282  }
2283  for (const auto *E : C->inits()) {
2284    Visitor->AddStmt(E);
2285  }
2286}
2287void OMPClauseEnqueue::VisitOMPLastprivateClause(
2288                                        const OMPLastprivateClause *C) {
2289  VisitOMPClauseList(C);
2290  VisitOMPClauseWithPostUpdate(C);
2291  for (auto *E : C->private_copies()) {
2292    Visitor->AddStmt(E);
2293  }
2294  for (auto *E : C->source_exprs()) {
2295    Visitor->AddStmt(E);
2296  }
2297  for (auto *E : C->destination_exprs()) {
2298    Visitor->AddStmt(E);
2299  }
2300  for (auto *E : C->assignment_ops()) {
2301    Visitor->AddStmt(E);
2302  }
2303}
2304void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
2305  VisitOMPClauseList(C);
2306}
2307void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2308  VisitOMPClauseList(C);
2309  VisitOMPClauseWithPostUpdate(C);
2310  for (auto *E : C->privates()) {
2311    Visitor->AddStmt(E);
2312  }
2313  for (auto *E : C->lhs_exprs()) {
2314    Visitor->AddStmt(E);
2315  }
2316  for (auto *E : C->rhs_exprs()) {
2317    Visitor->AddStmt(E);
2318  }
2319  for (auto *E : C->reduction_ops()) {
2320    Visitor->AddStmt(E);
2321  }
2322}
2323void OMPClauseEnqueue::VisitOMPTaskReductionClause(
2324    const OMPTaskReductionClause *C) {
2325  VisitOMPClauseList(C);
2326  VisitOMPClauseWithPostUpdate(C);
2327  for (auto *E : C->privates()) {
2328    Visitor->AddStmt(E);
2329  }
2330  for (auto *E : C->lhs_exprs()) {
2331    Visitor->AddStmt(E);
2332  }
2333  for (auto *E : C->rhs_exprs()) {
2334    Visitor->AddStmt(E);
2335  }
2336  for (auto *E : C->reduction_ops()) {
2337    Visitor->AddStmt(E);
2338  }
2339}
2340void OMPClauseEnqueue::VisitOMPInReductionClause(
2341    const OMPInReductionClause *C) {
2342  VisitOMPClauseList(C);
2343  VisitOMPClauseWithPostUpdate(C);
2344  for (auto *E : C->privates()) {
2345    Visitor->AddStmt(E);
2346  }
2347  for (auto *E : C->lhs_exprs()) {
2348    Visitor->AddStmt(E);
2349  }
2350  for (auto *E : C->rhs_exprs()) {
2351    Visitor->AddStmt(E);
2352  }
2353  for (auto *E : C->reduction_ops()) {
2354    Visitor->AddStmt(E);
2355  }
2356  for (auto *E : C->taskgroup_descriptors())
2357    Visitor->AddStmt(E);
2358}
2359void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2360  VisitOMPClauseList(C);
2361  VisitOMPClauseWithPostUpdate(C);
2362  for (const auto *E : C->privates()) {
2363    Visitor->AddStmt(E);
2364  }
2365  for (const auto *E : C->inits()) {
2366    Visitor->AddStmt(E);
2367  }
2368  for (const auto *E : C->updates()) {
2369    Visitor->AddStmt(E);
2370  }
2371  for (const auto *E : C->finals()) {
2372    Visitor->AddStmt(E);
2373  }
2374  Visitor->AddStmt(C->getStep());
2375  Visitor->AddStmt(C->getCalcStep());
2376}
2377void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2378  VisitOMPClauseList(C);
2379  Visitor->AddStmt(C->getAlignment());
2380}
2381void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2382  VisitOMPClauseList(C);
2383  for (auto *E : C->source_exprs()) {
2384    Visitor->AddStmt(E);
2385  }
2386  for (auto *E : C->destination_exprs()) {
2387    Visitor->AddStmt(E);
2388  }
2389  for (auto *E : C->assignment_ops()) {
2390    Visitor->AddStmt(E);
2391  }
2392}
2393void
2394OMPClauseEnqueue::VisitOMPCopyprivateClause(const OMPCopyprivateClause *C) {
2395  VisitOMPClauseList(C);
2396  for (auto *E : C->source_exprs()) {
2397    Visitor->AddStmt(E);
2398  }
2399  for (auto *E : C->destination_exprs()) {
2400    Visitor->AddStmt(E);
2401  }
2402  for (auto *E : C->assignment_ops()) {
2403    Visitor->AddStmt(E);
2404  }
2405}
2406void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2407  VisitOMPClauseList(C);
2408}
2409void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2410  VisitOMPClauseList(C);
2411}
2412void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2413  VisitOMPClauseList(C);
2414}
2415void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2416    const OMPDistScheduleClause *C) {
2417  VisitOMPClauseWithPreInit(C);
2418  Visitor->AddStmt(C->getChunkSize());
2419}
2420void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2421    const OMPDefaultmapClause * /*C*/) {}
2422void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2423  VisitOMPClauseList(C);
2424}
2425void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2426  VisitOMPClauseList(C);
2427}
2428void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(const OMPUseDevicePtrClause *C) {
2429  VisitOMPClauseList(C);
2430}
2431void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(const OMPIsDevicePtrClause *C) {
2432  VisitOMPClauseList(C);
2433}
2434}
2435
2436void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2437  unsigned size = WL.size();
2438  OMPClauseEnqueue Visitor(this);
2439  Visitor.Visit(S);
2440  if (size == WL.size())
2441    return;
2442  // Now reverse the entries we just added.  This will match the DFS
2443  // ordering performed by the worklist.
2444  VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2445  std::reverse(I, E);
2446}
2447void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
2448  WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2449}
2450void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
2451  AddDecl(B->getBlockDecl());
2452}
2453void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2454  EnqueueChildren(E);
2455  AddTypeLoc(E->getTypeSourceInfo());
2456}
2457void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
2458  for (auto &I : llvm::reverse(S->body()))
2459    AddStmt(I);
2460}
2461void EnqueueVisitor::
2462VisitMSDependentExistsStmt(const MSDependentExistsStmt *S) {
2463  AddStmt(S->getSubStmt());
2464  AddDeclarationNameInfo(S);
2465  if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2466    AddNestedNameSpecifierLoc(QualifierLoc);
2467}
2468
2469void EnqueueVisitor::
2470VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
2471  if (E->hasExplicitTemplateArgs())
2472    AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
2473  AddDeclarationNameInfo(E);
2474  if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2475    AddNestedNameSpecifierLoc(QualifierLoc);
2476  if (!E->isImplicitAccess())
2477    AddStmt(E->getBase());
2478}
2479void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
2480  // Enqueue the initializer , if any.
2481  AddStmt(E->getInitializer());
2482  // Enqueue the array size, if any.
2483  AddStmt(E->getArraySize());
2484  // Enqueue the allocated type.
2485  AddTypeLoc(E->getAllocatedTypeSourceInfo());
2486  // Enqueue the placement arguments.
2487  for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2488    AddStmt(E->getPlacementArg(I-1));
2489}
2490void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
2491  for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2492    AddStmt(CE->getArg(I-1));
2493  AddStmt(CE->getCallee());
2494  AddStmt(CE->getArg(0));
2495}
2496void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2497                                        const CXXPseudoDestructorExpr *E) {
2498  // Visit the name of the type being destroyed.
2499  AddTypeLoc(E->getDestroyedTypeInfo());
2500  // Visit the scope type that looks disturbingly like the nested-name-specifier
2501  // but isn't.
2502  AddTypeLoc(E->getScopeTypeInfo());
2503  // Visit the nested-name-specifier.
2504  if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2505    AddNestedNameSpecifierLoc(QualifierLoc);
2506  // Visit base expression.
2507  AddStmt(E->getBase());
2508}
2509void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2510                                        const CXXScalarValueInitExpr *E) {
2511  AddTypeLoc(E->getTypeSourceInfo());
2512}
2513void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2514                                        const CXXTemporaryObjectExpr *E) {
2515  EnqueueChildren(E);
2516  AddTypeLoc(E->getTypeSourceInfo());
2517}
2518void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2519  EnqueueChildren(E);
2520  if (E->isTypeOperand())
2521    AddTypeLoc(E->getTypeOperandSourceInfo());
2522}
2523
2524void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2525                                        const CXXUnresolvedConstructExpr *E) {
2526  EnqueueChildren(E);
2527  AddTypeLoc(E->getTypeSourceInfo());
2528}
2529void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
2530  EnqueueChildren(E);
2531  if (E->isTypeOperand())
2532    AddTypeLoc(E->getTypeOperandSourceInfo());
2533}
2534
2535void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
2536  EnqueueChildren(S);
2537  AddDecl(S->getExceptionDecl());
2538}
2539
2540void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
2541  AddStmt(S->getBody());
2542  AddStmt(S->getRangeInit());
2543  AddDecl(S->getLoopVariable());
2544}
2545
2546void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
2547  if (DR->hasExplicitTemplateArgs())
2548    AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
2549  WL.push_back(DeclRefExprParts(DR, Parent));
2550}
2551void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2552                                        const DependentScopeDeclRefExpr *E) {
2553  if (E->hasExplicitTemplateArgs())
2554    AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
2555  AddDeclarationNameInfo(E);
2556  AddNestedNameSpecifierLoc(E->getQualifierLoc());
2557}
2558void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
2559  unsigned size = WL.size();
2560  bool isFirst = true;
2561  for (const auto *D : S->decls()) {
2562    AddDecl(D, isFirst);
2563    isFirst = false;
2564  }
2565  if (size == WL.size())
2566    return;
2567  // Now reverse the entries we just added.  This will match the DFS
2568  // ordering performed by the worklist.
2569  VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2570  std::reverse(I, E);
2571}
2572void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
2573  AddStmt(E->getInit());
2574  for (const DesignatedInitExpr::Designator &D :
2575       llvm::reverse(E->designators())) {
2576    if (D.isFieldDesignator()) {
2577      if (FieldDecl *Field = D.getField())
2578        AddMemberRef(Field, D.getFieldLoc());
2579      continue;
2580    }
2581    if (D.isArrayDesignator()) {
2582      AddStmt(E->getArrayIndex(D));
2583      continue;
2584    }
2585     (0) . __assert_fail ("D.isArrayRangeDesignator() && \"Unknown designator kind\"", "/home/seafit/code_projects/clang_source/clang/tools/libclang/CIndex.cpp", 2585, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(D.isArrayRangeDesignator() && "Unknown designator kind");
2586    AddStmt(E->getArrayRangeEnd(D));
2587    AddStmt(E->getArrayRangeStart(D));
2588  }
2589}
2590void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
2591  EnqueueChildren(E);
2592  AddTypeLoc(E->getTypeInfoAsWritten());
2593}
2594void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
2595  AddStmt(FS->getBody());
2596  AddStmt(FS->getInc());
2597  AddStmt(FS->getCond());
2598  AddDecl(FS->getConditionVariable());
2599  AddStmt(FS->getInit());
2600}
2601void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
2602  WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2603}
2604void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
2605  AddStmt(If->getElse());
2606  AddStmt(If->getThen());
2607  AddStmt(If->getCond());
2608  AddDecl(If->getConditionVariable());
2609}
2610void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
2611  // We care about the syntactic form of the initializer list, only.
2612  if (InitListExpr *Syntactic = IE->getSyntacticForm())
2613    IE = Syntactic;
2614  EnqueueChildren(IE);
2615}
2616void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
2617  WL.push_back(MemberExprParts(M, Parent));
2618  
2619  // If the base of the member access expression is an implicit 'this', don't
2620  // visit it.
2621  // FIXME: If we ever want to show these implicit accesses, this will be
2622  // unfortunate. However, clang_getCursor() relies on this behavior.
2623  if (M->isImplicitAccess())
2624    return;
2625
2626  // Ignore base anonymous struct/union fields, otherwise they will shadow the
2627  // real field that we are interested in.
2628  if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2629    if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2630      if (FD->isAnonymousStructOrUnion()) {
2631        AddStmt(SubME->getBase());
2632        return;
2633      }
2634    }
2635  }
2636
2637  AddStmt(M->getBase());
2638}
2639void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
2640  AddTypeLoc(E->getEncodedTypeSourceInfo());
2641}
2642void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
2643  EnqueueChildren(M);
2644  AddTypeLoc(M->getClassReceiverTypeInfo());
2645}
2646void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
2647  // Visit the components of the offsetof expression.
2648  for (unsigned N = E->getNumComponents(), I = NI > 0; --I) {
2649    const OffsetOfNode &Node = E->getComponent(I-1);
2650    switch (Node.getKind()) {
2651    case OffsetOfNode::Array:
2652      AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2653      break;
2654    case OffsetOfNode::Field:
2655      AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2656      break;
2657    case OffsetOfNode::Identifier:
2658    case OffsetOfNode::Base:
2659      continue;
2660    }
2661  }
2662  // Visit the type into which we're computing the offset.
2663  AddTypeLoc(E->getTypeSourceInfo());
2664}
2665void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
2666  if (E->hasExplicitTemplateArgs())
2667    AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
2668  WL.push_back(OverloadExprParts(E, Parent));
2669}
2670void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2671                                        const UnaryExprOrTypeTraitExpr *E) {
2672  EnqueueChildren(E);
2673  if (E->isArgumentType())
2674    AddTypeLoc(E->getArgumentTypeInfo());
2675}
2676void EnqueueVisitor::VisitStmt(const Stmt *S) {
2677  EnqueueChildren(S);
2678}
2679void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
2680  AddStmt(S->getBody());
2681  AddStmt(S->getCond());
2682  AddDecl(S->getConditionVariable());
2683}
2684
2685void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
2686  AddStmt(W->getBody());
2687  AddStmt(W->getCond());
2688  AddDecl(W->getConditionVariable());
2689}
2690
2691void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
2692  for (unsigned I = E->getNumArgs(); I > 0; --I)
2693    AddTypeLoc(E->getArg(I-1));
2694}
2695
2696void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
2697  AddTypeLoc(E->getQueriedTypeSourceInfo());
2698}
2699
2700void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
2701  EnqueueChildren(E);
2702}
2703
2704void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
2705  VisitOverloadExpr(U);
2706  if (!U->isImplicitAccess())
2707    AddStmt(U->getBase());
2708}
2709void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
2710  AddStmt(E->getSubExpr());
2711  AddTypeLoc(E->getWrittenTypeInfo());
2712}
2713void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
2714  WL.push_back(SizeOfPackExprParts(E, Parent));
2715}
2716void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
2717  // If the opaque value has a source expression, just transparently
2718  // visit that.  This is useful for (e.g.) pseudo-object expressions.
2719  if (Expr *SourceExpr = E->getSourceExpr())
2720    return Visit(SourceExpr);
2721}
2722void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
2723  AddStmt(E->getBody());
2724  WL.push_back(LambdaExprParts(E, Parent));
2725}
2726void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
2727  // Treat the expression like its syntactic form.
2728  Visit(E->getSyntacticForm());
2729}
2730
2731void EnqueueVisitor::VisitOMPExecutableDirective(
2732  const OMPExecutableDirective *D) {
2733  EnqueueChildren(D);
2734  for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2735                                       E = D->clauses().end();
2736       I != E; ++I)
2737    EnqueueChildren(*I);
2738}
2739
2740void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2741  VisitOMPExecutableDirective(D);
2742}
2743
2744void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2745  VisitOMPExecutableDirective(D);
2746}
2747
2748void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
2749  VisitOMPLoopDirective(D);
2750}
2751
2752void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
2753  VisitOMPLoopDirective(D);
2754}
2755
2756void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2757  VisitOMPLoopDirective(D);
2758}
2759
2760void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2761  VisitOMPExecutableDirective(D);
2762}
2763
2764void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2765  VisitOMPExecutableDirective(D);
2766}
2767
2768void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2769  VisitOMPExecutableDirective(D);
2770}
2771
2772void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2773  VisitOMPExecutableDirective(D);
2774}
2775
2776void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2777  VisitOMPExecutableDirective(D);
2778  AddDeclarationNameInfo(D);
2779}
2780
2781void
2782EnqueueVisitor::VisitOMPParallelForDirective(const OMPParallelForDirective *D) {
2783  VisitOMPLoopDirective(D);
2784}
2785
2786void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2787    const OMPParallelForSimdDirective *D) {
2788  VisitOMPLoopDirective(D);
2789}
2790
2791void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2792    const OMPParallelSectionsDirective *D) {
2793  VisitOMPExecutableDirective(D);
2794}
2795
2796void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2797  VisitOMPExecutableDirective(D);
2798}
2799
2800void
2801EnqueueVisitor::VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D) {
2802  VisitOMPExecutableDirective(D);
2803}
2804
2805void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2806  VisitOMPExecutableDirective(D);
2807}
2808
2809void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2810  VisitOMPExecutableDirective(D);
2811}
2812
2813void EnqueueVisitor::VisitOMPTaskgroupDirective(
2814    const OMPTaskgroupDirective *D) {
2815  VisitOMPExecutableDirective(D);
2816  if (const Expr *E = D->getReductionRef())
2817    VisitStmt(E);
2818}
2819
2820void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2821  VisitOMPExecutableDirective(D);
2822}
2823
2824void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2825  VisitOMPExecutableDirective(D);
2826}
2827
2828void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2829  VisitOMPExecutableDirective(D);
2830}
2831
2832void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2833  VisitOMPExecutableDirective(D);
2834}
2835
2836void EnqueueVisitor::VisitOMPTargetDataDirective(const 
2837                                                 OMPTargetDataDirective *D) {
2838  VisitOMPExecutableDirective(D);
2839}
2840
2841void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
2842    const OMPTargetEnterDataDirective *D) {
2843  VisitOMPExecutableDirective(D);
2844}
2845
2846void EnqueueVisitor::VisitOMPTargetExitDataDirective(
2847    const OMPTargetExitDataDirective *D) {
2848  VisitOMPExecutableDirective(D);
2849}
2850
2851void EnqueueVisitor::VisitOMPTargetParallelDirective(
2852    const OMPTargetParallelDirective *D) {
2853  VisitOMPExecutableDirective(D);
2854}
2855
2856void EnqueueVisitor::VisitOMPTargetParallelForDirective(
2857    const OMPTargetParallelForDirective *D) {
2858  VisitOMPLoopDirective(D);
2859}
2860
2861void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2862  VisitOMPExecutableDirective(D);
2863}
2864
2865void EnqueueVisitor::VisitOMPCancellationPointDirective(
2866    const OMPCancellationPointDirective *D) {
2867  VisitOMPExecutableDirective(D);
2868}
2869
2870void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2871  VisitOMPExecutableDirective(D);
2872}
2873
2874void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2875  VisitOMPLoopDirective(D);
2876}
2877
2878void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
2879    const OMPTaskLoopSimdDirective *D) {
2880  VisitOMPLoopDirective(D);
2881}
2882
2883void EnqueueVisitor::VisitOMPDistributeDirective(
2884    const OMPDistributeDirective *D) {
2885  VisitOMPLoopDirective(D);
2886}
2887
2888void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
2889    const OMPDistributeParallelForDirective *D) {
2890  VisitOMPLoopDirective(D);
2891}
2892
2893void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
2894    const OMPDistributeParallelForSimdDirective *D) {
2895  VisitOMPLoopDirective(D);
2896}
2897
2898void EnqueueVisitor::VisitOMPDistributeSimdDirective(
2899    const OMPDistributeSimdDirective *D) {
2900  VisitOMPLoopDirective(D);
2901}
2902
2903void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
2904    const OMPTargetParallelForSimdDirective *D) {
2905  VisitOMPLoopDirective(D);
2906}
2907
2908void EnqueueVisitor::VisitOMPTargetSimdDirective(
2909    const OMPTargetSimdDirective *D) {
2910  VisitOMPLoopDirective(D);
2911}
2912
2913void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
2914    const OMPTeamsDistributeDirective *D) {
2915  VisitOMPLoopDirective(D);
2916}
2917
2918void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
2919    const OMPTeamsDistributeSimdDirective *D) {
2920  VisitOMPLoopDirective(D);
2921}
2922
2923void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective(
2924    const OMPTeamsDistributeParallelForSimdDirective *D) {
2925  VisitOMPLoopDirective(D);
2926}
2927
2928void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective(
2929    const OMPTeamsDistributeParallelForDirective *D) {
2930  VisitOMPLoopDirective(D);
2931}
2932
2933void EnqueueVisitor::VisitOMPTargetTeamsDirective(
2934    const OMPTargetTeamsDirective *D) {
2935  VisitOMPExecutableDirective(D);
2936}
2937
2938void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective(
2939    const OMPTargetTeamsDistributeDirective *D) {
2940  VisitOMPLoopDirective(D);
2941}
2942
2943void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective(
2944    const OMPTargetTeamsDistributeParallelForDirective *D) {
2945  VisitOMPLoopDirective(D);
2946}
2947
2948void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2949    const OMPTargetTeamsDistributeParallelForSimdDirective *D) {
2950  VisitOMPLoopDirective(D);
2951}
2952
2953void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective(
2954    const OMPTargetTeamsDistributeSimdDirective *D) {
2955  VisitOMPLoopDirective(D);
2956}
2957
2958void CursorVisitor::EnqueueWorkList(VisitorWorkList &WLconst Stmt *S) {
2959  EnqueueVisitor(WLMakeCXCursor(SStmtParentTU,RegionOfInterest)).Visit(S);
2960}
2961
2962bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
2963  if (RegionOfInterest.isValid()) {
2964    SourceRange Range = getRawCursorExtent(C);
2965    if (Range.isInvalid() || CompareRegionOfInterest(Range))
2966      return false;
2967  }
2968  return true;
2969}
2970
2971bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2972  while (!WL.empty()) {
2973    // Dequeue the worklist item.
2974    VisitorJob LI = WL.pop_back_val();
2975
2976    // Set the Parent field, then back to its old value once we're done.
2977    SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2978  
2979    switch (LI.getKind()) {
2980      case VisitorJob::DeclVisitKind: {
2981        const Decl *D = cast<DeclVisit>(&LI)->get();
2982        if (!D)
2983          continue;
2984
2985        // For now, perform default visitation for Decls.
2986        if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
2987                               cast<DeclVisit>(&LI)->isFirst())))
2988            return true;
2989
2990        continue;
2991      }
2992      case VisitorJob::ExplicitTemplateArgsVisitKind: {
2993        for (const TemplateArgumentLoc &Arg :
2994             *cast<ExplicitTemplateArgsVisit>(&LI)) {
2995          if (VisitTemplateArgumentLoc(Arg))
2996            return true;
2997        }
2998        continue;
2999      }
3000      case VisitorJob::TypeLocVisitKind: {
3001        // Perform default visitation for TypeLocs.
3002        if (Visit(cast<TypeLocVisit>(&LI)->get()))
3003          return true;
3004        continue;
3005      }
3006      case VisitorJob::LabelRefVisitKind: {
3007        const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
3008        if (LabelStmt *stmt = LS->getStmt()) {
3009          if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
3010                                       TU))) {
3011            return true;
3012          }
3013        }
3014        continue;
3015      }
3016
3017      case VisitorJob::NestedNameSpecifierLocVisitKind: {
3018        NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
3019        if (VisitNestedNameSpecifierLoc(V->get()))
3020          return true;
3021        continue;
3022      }
3023        
3024      case VisitorJob::DeclarationNameInfoVisitKind: {
3025        if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)
3026                                     ->get()))
3027          return true;
3028        continue;
3029      }
3030      case VisitorJob::MemberRefVisitKind: {
3031        MemberRefVisit *V = cast<MemberRefVisit>(&LI);
3032        if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
3033          return true;
3034        continue;
3035      }
3036      case VisitorJob::StmtVisitKind: {
3037        const Stmt *S = cast<StmtVisit>(&LI)->get();
3038        if (!S)
3039          continue;
3040
3041        // Update the current cursor.
3042        CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
3043        if (!IsInRegionOfInterest(Cursor))
3044          continue;
3045        switch (Visitor(Cursor, Parent, ClientData)) {
3046          case CXChildVisit_Break: return true;
3047          case CXChildVisit_Continue: break;
3048          case CXChildVisit_Recurse:
3049            if (PostChildrenVisitor)
3050              WL.push_back(PostChildrenVisit(nullptr, Cursor));
3051            EnqueueWorkList(WL, S);
3052            break;
3053        }
3054        continue;
3055      }
3056      case VisitorJob::MemberExprPartsKind: {
3057        // Handle the other pieces in the MemberExpr besides the base.
3058        const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
3059        
3060        // Visit the nested-name-specifier
3061        if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
3062          if (VisitNestedNameSpecifierLoc(QualifierLoc))
3063            return true;
3064        
3065        // Visit the declaration name.
3066        if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
3067          return true;
3068        
3069        // Visit the explicitly-specified template arguments, if any.
3070        if (M->hasExplicitTemplateArgs()) {
3071          for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
3072               *ArgEnd = Arg + M->getNumTemplateArgs();
3073               Arg != ArgEnd; ++Arg) {
3074            if (VisitTemplateArgumentLoc(*Arg))
3075              return true;
3076          }
3077        }
3078        continue;
3079      }
3080      case VisitorJob::DeclRefExprPartsKind: {
3081        const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
3082        // Visit nested-name-specifier, if present.
3083        if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
3084          if (VisitNestedNameSpecifierLoc(QualifierLoc))
3085            return true;
3086        // Visit declaration name.
3087        if (VisitDeclarationNameInfo(DR->getNameInfo()))
3088          return true;
3089        continue;
3090      }
3091      case VisitorJob::OverloadExprPartsKind: {
3092        const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
3093        // Visit the nested-name-specifier.
3094        if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
3095          if (VisitNestedNameSpecifierLoc(QualifierLoc))
3096            return true;
3097        // Visit the declaration name.
3098        if (VisitDeclarationNameInfo(O->getNameInfo()))
3099          return true;
3100        // Visit the overloaded declaration reference.
3101        if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
3102          return true;
3103        continue;
3104      }
3105      case VisitorJob::SizeOfPackExprPartsKind: {
3106        const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
3107        NamedDecl *Pack = E->getPack();
3108        if (isa<TemplateTypeParmDecl>(Pack)) {
3109          if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
3110                                      E->getPackLoc(), TU)))
3111            return true;
3112          
3113          continue;
3114        }
3115          
3116        if (isa<TemplateTemplateParmDecl>(Pack)) {
3117          if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
3118                                          E->getPackLoc(), TU)))
3119            return true;
3120          
3121          continue;
3122        }
3123        
3124        // Non-type template parameter packs and function parameter packs are
3125        // treated like DeclRefExpr cursors.
3126        continue;
3127      }
3128        
3129      case VisitorJob::LambdaExprPartsKind: {
3130        // Visit captures.
3131        const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
3132        for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
3133                                       CEnd = E->explicit_capture_end();
3134             C != CEnd; ++C) {
3135          // FIXME: Lambda init-captures.
3136          if (!C->capturesVariable())
3137            continue;
3138
3139          if (Visit(MakeCursorVariableRef(C->getCapturedVar(),
3140                                          C->getLocation(),
3141                                          TU)))
3142            return true;
3143        }
3144        
3145        TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
3146        // Visit parameters and return type, if present.
3147        if (FunctionTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) {
3148          if (E->hasExplicitParameters()) {
3149            // Visit parameters.
3150            for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
3151              if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
3152                return true;
3153          }
3154          if (E->hasExplicitResultType()) {
3155            // Visit result type.
3156            if (Visit(Proto.getReturnLoc()))
3157              return true;
3158          }
3159        }
3160        break;
3161      }
3162
3163      case VisitorJob::PostChildrenVisitKind:
3164        if (PostChildrenVisitor(Parent, ClientData))
3165          return true;
3166        break;
3167    }
3168  }
3169  return false;
3170}
3171
3172bool CursorVisitor::Visit(const Stmt *S) {
3173  VisitorWorkList *WL = nullptr;
3174  if (!WorkListFreeList.empty()) {
3175    WL = WorkListFreeList.back();
3176    WL->clear();
3177    WorkListFreeList.pop_back();
3178  }
3179  else {
3180    WL = new VisitorWorkList();
3181    WorkListCache.push_back(WL);
3182  }
3183  EnqueueWorkList(*WLS);
3184  bool result = RunVisitorWorkList(*WL);
3185  WorkListFreeList.push_back(WL);
3186  return result;
3187}
3188
3189namespace {
3190typedef SmallVector<SourceRange4RefNamePieces;
3191RefNamePieces buildPieces(unsigned NameFlagsbool IsMemberRefExpr,
3192                          const DeclarationNameInfo &NISourceRange QLoc,
3193                          const SourceRange *TemplateArgsLoc = nullptr) {
3194  const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3195  const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3196  const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3197  
3198  const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3199  
3200  RefNamePieces Pieces;
3201
3202  if (WantQualifier && QLoc.isValid())
3203    Pieces.push_back(QLoc);
3204  
3205  if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
3206    Pieces.push_back(NI.getLoc());
3207
3208  if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
3209    Pieces.push_back(*TemplateArgsLoc);
3210
3211  if (Kind == DeclarationName::CXXOperatorName) {
3212    Pieces.push_back(SourceLocation::getFromRawEncoding(
3213                       NI.getInfo().CXXOperatorName.BeginOpNameLoc));
3214    Pieces.push_back(SourceLocation::getFromRawEncoding(
3215                       NI.getInfo().CXXOperatorName.EndOpNameLoc));
3216  }
3217  
3218  if (WantSinglePiece) {
3219    SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3220    Pieces.clear();
3221    Pieces.push_back(R);
3222  }  
3223
3224  return Pieces;  
3225}
3226}
3227
3228//===----------------------------------------------------------------------===//
3229// Misc. API hooks.
3230//===----------------------------------------------------------------------===//               
3231
3232static void fatal_error_handler(void *user_dataconst std::stringreason,
3233                                bool gen_crash_diag) {
3234  // Write the result out to stderr avoiding errs() because raw_ostreams can
3235  // call report_fatal_error.
3236  fprintf(stderr"LIBCLANG FATAL ERROR: %s\n"reason.c_str());
3237  ::abort();
3238}
3239
3240namespace {
3241struct RegisterFatalErrorHandler {
3242  RegisterFatalErrorHandler() {
3243    llvm::install_fatal_error_handler(fatal_error_handler, nullptr);
3244  }
3245};
3246}
3247
3248static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;
3249
3250CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3251                          int displayDiagnostics) {
3252  // We use crash recovery to make some of our APIs more reliable, implicitly
3253  // enable it.
3254  if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3255    llvm::CrashRecoveryContext::Enable();
3256
3257  // Look through the managed static to trigger construction of the managed
3258  // static which registers our fatal error handler. This ensures it is only
3259  // registered once.
3260  (void)*RegisterFatalErrorHandlerOnce;
3261
3262  // Initialize targets for clang module support.
3263  llvm::InitializeAllTargets();
3264  llvm::InitializeAllTargetMCs();
3265  llvm::InitializeAllAsmPrinters();
3266  llvm::InitializeAllAsmParsers();
3267
3268  CIndexer *CIdxr = new CIndexer();
3269
3270  if (excludeDeclarationsFromPCH)
3271    CIdxr->setOnlyLocalDecls();
3272  if (displayDiagnostics)
3273    CIdxr->setDisplayDiagnostics();
3274
3275  if (getenv("LIBCLANG_BGPRIO_INDEX"))
3276    CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3277                               CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3278  if (getenv("LIBCLANG_BGPRIO_EDIT"))
3279    CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3280                               CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3281
3282  return CIdxr;
3283}
3284
3285void clang_disposeIndex(CXIndex CIdx) {
3286  if (CIdx)
3287    delete static_cast<CIndexer *>(CIdx);
3288}
3289
3290void clang_CXIndex_setGlobalOptions(CXIndex CIdxunsigned options) {
3291  if (CIdx)
3292    static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3293}
3294
3295unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3296  if (CIdx)
3297    return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3298  return 0;
3299}
3300
3301void clang_CXIndex_setInvocationEmissionPathOption(CXIndex CIdx,
3302                                                   const char *Path) {
3303  if (CIdx)
3304    static_cast<CIndexer *>(CIdx)->setInvocationEmissionPath(Path ? Path : "");
3305}
3306
3307void clang_toggleCrashRecovery(unsigned isEnabled) {
3308  if (isEnabled)
3309    llvm::CrashRecoveryContext::Enable();
3310  else
3311    llvm::CrashRecoveryContext::Disable();
3312}
3313
3314CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3315                                              const char *ast_filename) {
3316  CXTranslationUnit TU;
3317  enum CXErrorCode Result =
3318      clang_createTranslationUnit2(CIdxast_filename, &TU);
3319  (void)Result;
3320  assert((TU && Result == CXError_Success) ||
3321         (!TU && Result != CXError_Success));
3322  return TU;
3323}
3324
3325enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3326                                              const char *ast_filename,
3327                                              CXTranslationUnit *out_TU) {
3328  if (out_TU)
3329    *out_TU = nullptr;
3330
3331  if (!CIdx || !ast_filename || !out_TU)
3332    return CXError_InvalidArguments;
3333
3334  LOG_FUNC_SECTION {
3335    *Log << ast_filename;
3336  }
3337
3338  CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3339  FileSystemOptions FileSystemOpts;
3340
3341  IntrusiveRefCntPtr<DiagnosticsEngineDiags =
3342      CompilerInstance::createDiagnostics(new DiagnosticOptions());
3343  std::unique_ptr<ASTUnitAU = ASTUnit::LoadFromASTFile(
3344      ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(),
3345      ASTUnit::LoadEverything, Diags,
3346      FileSystemOpts, /*UseDebugInfo=*/false,
3347      CXXIdx->getOnlyLocalDecls(), None,
3348      /*CaptureDiagnostics=*/true,
3349      /*AllowPCHWithCompilerErrors=*/true,
3350      /*UserFilesAreVolatile=*/true);
3351  *out_TU = MakeCXTranslationUnit(CXXIdxstd::move(AU));
3352  return *out_TU ? CXError_Success : CXError_Failure;
3353}
3354
3355unsigned clang_defaultEditingTranslationUnitOptions() {
3356  return CXTranslationUnit_PrecompiledPreamble | 
3357         CXTranslationUnit_CacheCompletionResults;
3358}
3359
3360CXTranslationUnit
3361clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
3362                                          const char *source_filename,
3363                                          int num_command_line_args,
3364                                          const char * const *command_line_args,
3365                                          unsigned num_unsaved_files,
3366                                          struct CXUnsavedFile *unsaved_files) {
3367  unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3368  return clang_parseTranslationUnit(CIdxsource_filename,
3369                                    command_line_argsnum_command_line_args,
3370                                    unsaved_filesnum_unsaved_files,
3371                                    Options);
3372}
3373
3374static CXErrorCode
3375clang_parseTranslationUnit_Impl(CXIndex CIdxconst char *source_filename,
3376                                const char *const *command_line_args,
3377                                int num_command_line_args,
3378                                ArrayRef<CXUnsavedFileunsaved_files,
3379                                unsigned optionsCXTranslationUnit *out_TU) {
3380  // Set up the initial return values.
3381  if (out_TU)
3382    *out_TU = nullptr;
3383
3384  // Check arguments.
3385  if (!CIdx || !out_TU)
3386    return CXError_InvalidArguments;
3387
3388  CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3389
3390  if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3391    setThreadBackgroundPriority();
3392
3393  bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
3394  bool CreatePreambleOnFirstParse =
3395      options & CXTranslationUnit_CreatePreambleOnFirstParse;
3396  // FIXME: Add a flag for modules.
3397  TranslationUnitKind TUKind
3398    = (options & (CXTranslationUnit_Incomplete |
3399                  CXTranslationUnit_SingleFileParse))? TU_Prefix : TU_Complete;
3400  bool CacheCodeCompletionResults
3401    = options & CXTranslationUnit_CacheCompletionResults;
3402  bool IncludeBriefCommentsInCodeCompletion
3403    = options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
3404  bool SingleFileParse = options & CXTranslationUnit_SingleFileParse;
3405  bool ForSerialization = options & CXTranslationUnit_ForSerialization;
3406  SkipFunctionBodiesScope SkipFunctionBodies = SkipFunctionBodiesScope::None;
3407  if (options & CXTranslationUnit_SkipFunctionBodies) {
3408    SkipFunctionBodies =
3409        (options & CXTranslationUnit_LimitSkipFunctionBodiesToPreamble)
3410            ? SkipFunctionBodiesScope::Preamble
3411            : SkipFunctionBodiesScope::PreambleAndMainFile;
3412  }
3413
3414  // Configure the diagnostics.
3415  IntrusiveRefCntPtr<DiagnosticsEngine>
3416    Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
3417
3418  if (options & CXTranslationUnit_KeepGoing)
3419    Diags->setFatalsAsError(true);
3420
3421  // Recover resources if we crash before exiting this function.
3422  llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
3423    llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
3424    DiagCleanup(Diags.get());
3425
3426  std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3427      new std::vector<ASTUnit::RemappedFile>());
3428
3429  // Recover resources if we crash before exiting this function.
3430  llvm::CrashRecoveryContextCleanupRegistrar<
3431    std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
3432
3433  for (auto &UF : unsaved_files) {
3434    std::unique_ptr<llvm::MemoryBuffer> MB =
3435        llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
3436    RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
3437  }
3438
3439  std::unique_ptr<std::vector<const char *>> Args(
3440      new std::vector<const char *>());
3441
3442  // Recover resources if we crash before exiting this method.
3443  llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char*> >
3444    ArgsCleanup(Args.get());
3445
3446  // Since the Clang C library is primarily used by batch tools dealing with
3447  // (often very broken) source code, where spell-checking can have a
3448  // significant negative impact on performance (particularly when 
3449  // precompiled headers are involved), we disable it by default.
3450  // Only do this if we haven't found a spell-checking-related argument.
3451  bool FoundSpellCheckingArgument = false;
3452  for (int I = 0I != num_command_line_args; ++I) {
3453    if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3454        strcmp(command_line_args[I], "-fspell-checking") == 0) {
3455      FoundSpellCheckingArgument = true;
3456      break;
3457    }
3458  }
3459  Args->insert(Args->end(), command_line_args,
3460               command_line_args + num_command_line_args);
3461
3462  if (!FoundSpellCheckingArgument)
3463    Args->insert(Args->begin() + 1"-fno-spell-checking");
3464
3465  // The 'source_filename' argument is optional.  If the caller does not
3466  // specify it then it is assumed that the source file is specified
3467  // in the actual argument list.
3468  // Put the source file after command_line_args otherwise if '-x' flag is
3469  // present it will be unused.
3470  if (source_filename)
3471    Args->push_back(source_filename);
3472
3473  // Do we need the detailed preprocessing record?
3474  if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3475    Args->push_back("-Xclang");
3476    Args->push_back("-detailed-preprocessing-record");
3477  }
3478
3479  // Suppress any editor placeholder diagnostics.
3480  Args->push_back("-fallow-editor-placeholders");
3481
3482  unsigned NumErrors = Diags->getClient()->getNumErrors();
3483  std::unique_ptr<ASTUnitErrUnit;
3484  // Unless the user specified that they want the preamble on the first parse
3485  // set it up to be created on the first reparse. This makes the first parse
3486  // faster, trading for a slower (first) reparse.
3487  unsigned PrecompilePreambleAfterNParses =
3488      !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
3489
3490  LibclangInvocationReporter InvocationReporter(
3491      *CXXIdx, LibclangInvocationReporter::OperationKind::ParseOperation,
3492      options, llvm::makeArrayRef(*Args), /*InvocationArgs=*/None,
3493      unsaved_files);
3494  std::unique_ptr<ASTUnitUnit(ASTUnit::LoadFromCommandLine(
3495      Args->data(), Args->data() + Args->size(),
3496      CXXIdx->getPCHContainerOperations(), Diags,
3497      CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
3498      /*CaptureDiagnostics=*/true, *RemappedFiles.get(),
3499      /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3500      TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
3501      /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, SingleFileParse,
3502      /*UserFilesAreVolatile=*/true, ForSerialization,
3503      CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3504      &ErrUnit));
3505
3506  // Early failures in LoadFromCommandLine may return with ErrUnit unset.
3507  if (!Unit && !ErrUnit)
3508    return CXError_ASTReadError;
3509
3510  if (NumErrors != Diags->getClient()->getNumErrors()) {
3511    // Make sure to check that 'Unit' is non-NULL.
3512    if (CXXIdx->getDisplayDiagnostics())
3513      printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3514  }
3515
3516  if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3517    return CXError_ASTReadError;
3518
3519  *out_TU = MakeCXTranslationUnit(CXXIdxstd::move(Unit));
3520  if (CXTranslationUnitImpl *TU = *out_TU) {
3521    TU->ParsingOptions = options;
3522    TU->Arguments.reserve(Args->size());
3523    for (const char *Arg : *Args)
3524      TU->Arguments.push_back(Arg);
3525    return CXError_Success;
3526  }
3527  return CXError_Failure;
3528}
3529
3530CXTranslationUnit
3531clang_parseTranslationUnit(CXIndex CIdx,
3532                           const char *source_filename,
3533                           const char *const *command_line_args,
3534                           int num_command_line_args,
3535                           struct CXUnsavedFile *unsaved_files,
3536                           unsigned num_unsaved_files,
3537                           unsigned options) {
3538  CXTranslationUnit TU;
3539  enum CXErrorCode Result = clang_parseTranslationUnit2(
3540      CIdxsource_filenamecommand_line_argsnum_command_line_args,
3541      unsaved_filesnum_unsaved_filesoptions, &TU);
3542  (void)Result;
3543  assert((TU && Result == CXError_Success) ||
3544         (!TU && Result != CXError_Success));
3545  return TU;
3546}
3547
3548enum CXErrorCode clang_parseTranslationUnit2(
3549    CXIndex CIdxconst char *source_filename,
3550    const char *const *command_line_argsint num_command_line_args,
3551    struct CXUnsavedFile *unsaved_filesunsigned num_unsaved_files,
3552    unsigned optionsCXTranslationUnit *out_TU) {
3553  SmallVector<const char *, 4Args;
3554  Args.push_back("clang");
3555  Args.append(command_line_args, command_line_args + num_command_line_args);
3556  return clang_parseTranslationUnit2FullArgv(
3557      CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3558      num_unsaved_files, options, out_TU);
3559}
3560
3561enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3562    CXIndex CIdxconst char *source_filename,
3563    const char *const *command_line_argsint num_command_line_args,
3564    struct CXUnsavedFile *unsaved_filesunsigned num_unsaved_files,
3565    unsigned optionsCXTranslationUnit *out_TU) {
3566  LOG_FUNC_SECTION {
3567    *Log << source_filename << ": ";
3568    for (int i = 0; i != num_command_line_args; ++i)
3569      *Log << command_line_args[i] << " ";
3570  }
3571
3572  if (num_unsaved_files && !unsaved_files)
3573    return CXError_InvalidArguments;
3574
3575  CXErrorCode result = CXError_Failure;
3576  auto ParseTranslationUnitImpl = [=, &result] {
3577    result = clang_parseTranslationUnit_Impl(
3578        CIdx, source_filename, command_line_args, num_command_line_args,
3579        llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3580  };
3581
3582  llvm::CrashRecoveryContext CRC;
3583
3584  if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
3585    fprintf(stderr"libclang: crash detected during parsing: {\n");
3586    fprintf(stderr"  'source_filename' : '%s'\n"source_filename);
3587    fprintf(stderr"  'command_line_args' : [");
3588    for (int i = 0i != num_command_line_args; ++i) {
3589      if (i)
3590        fprintf(stderr", ");
3591      fprintf(stderr"'%s'"command_line_args[i]);
3592    }
3593    fprintf(stderr"],\n");
3594    fprintf(stderr"  'unsaved_files' : [");
3595    for (unsigned i = 0i != num_unsaved_files; ++i) {
3596      if (i)
3597        fprintf(stderr", ");
3598      fprintf(stderr"('%s', '...', %ld)"unsaved_files[i].Filename,
3599              unsaved_files[i].Length);
3600    }
3601    fprintf(stderr"],\n");
3602    fprintf(stderr"  'options' : %d,\n"options);
3603    fprintf(stderr"}\n");
3604
3605    return CXError_Crashed;
3606  } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
3607    if (CXTranslationUnit *TU = out_TU)
3608      PrintLibclangResourceUsage(*TU);
3609  }
3610
3611  return result;
3612}
3613
3614CXString clang_Type_getObjCEncoding(CXType CT) {
3615  CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3616  ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3617  std::string encoding;
3618  Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]),
3619                             encoding);
3620
3621  return cxstring::createDup(encoding);
3622}
3623
3624static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3625  if (C.kind == CXCursor_MacroDefinition) {
3626    if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3627      return MDR->getName();
3628  } else if (C.kind == CXCursor_MacroExpansion) {
3629    MacroExpansionCursor ME = getCursorMacroExpansion(C);
3630    return ME.getName();
3631  }
3632  return nullptr;
3633}
3634
3635unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3636  const IdentifierInfo *II = getMacroIdentifier(C);
3637  if (!II) {
3638    return false;
3639  }
3640  ASTUnit *ASTU = getCursorASTUnit(C);
3641  Preprocessor &PP = ASTU->getPreprocessor();
3642  if (const MacroInfo *MI = PP.getMacroInfo(II))
3643    return MI->isFunctionLike();
3644  return false;
3645}
3646
3647unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3648  const IdentifierInfo *II = getMacroIdentifier(C);
3649  if (!II) {
3650    return false;
3651  }
3652  ASTUnit *ASTU = getCursorASTUnit(C);
3653  Preprocessor &PP = ASTU->getPreprocessor();
3654  if (const MacroInfo *MI = PP.getMacroInfo(II))
3655    return MI->isBuiltinMacro();
3656  return false;
3657}
3658
3659unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3660  const Decl *D = getCursorDecl(C);
3661  const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3662  if (!FD) {
3663    return false;
3664  }
3665  return FD->isInlined();
3666}
3667
3668static StringLiteralgetCFSTR_value(CallExpr *callExpr) {
3669  if (callExpr->getNumArgs() != 1) {
3670    return nullptr;
3671  }
3672
3673  StringLiteral *S = nullptr;
3674  auto *arg = callExpr->getArg(0);
3675  if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3676    ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3677    auto *subExpr = I->getSubExprAsWritten();
3678
3679    if(subExpr->getStmtClass() != Stmt::StringLiteralClass){
3680      return nullptr;
3681    }
3682
3683    S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3684  } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3685    S = static_cast<StringLiteral *>(callExpr->getArg(0));
3686  } else {
3687    return nullptr;
3688  }
3689  return S;
3690}
3691
3692struct ExprEvalResult {
3693  CXEvalResultKind EvalType;
3694  union {
3695    unsigned long long unsignedVal;
3696    long long intVal;
3697    double floatVal;
3698    char *stringVal;
3699  } EvalData;
3700  bool IsUnsignedInt;
3701  ~ExprEvalResult() {
3702    if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3703        EvalType != CXEval_Int) {
3704      delete[] EvalData.stringVal;
3705    }
3706  }
3707};
3708
3709void clang_EvalResult_dispose(CXEvalResult E) {
3710  delete static_cast<ExprEvalResult *>(E);
3711}
3712
3713CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3714  if (!E) {
3715    return CXEval_UnExposed;
3716  }
3717  return ((ExprEvalResult *)E)->EvalType;
3718}
3719
3720int clang_EvalResult_getAsInt(CXEvalResult E) {
3721  return clang_EvalResult_getAsLongLong(E);
3722}
3723
3724long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
3725  if (!E) {
3726    return 0;
3727  }
3728  ExprEvalResult *Result = (ExprEvalResult*)E;
3729  if (Result->IsUnsignedInt)
3730    return Result->EvalData.unsignedVal;
3731  return Result->EvalData.intVal;
3732}
3733
3734unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
3735  return ((ExprEvalResult *)E)->IsUnsignedInt;
3736}
3737
3738unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
3739  if (!E) {
3740    return 0;
3741  }
3742
3743  ExprEvalResult *Result = (ExprEvalResult*)E;
3744  if (Result->IsUnsignedInt)
3745    return Result->EvalData.unsignedVal;
3746  return Result->EvalData.intVal;
3747}
3748
3749double clang_EvalResult_getAsDouble(CXEvalResult E) {
3750  if (!E) {
3751    return 0;
3752  }
3753  return ((ExprEvalResult *)E)->EvalData.floatVal;
3754}
3755
3756const charclang_EvalResult_getAsStr(CXEvalResult E) {
3757  if (!E) {
3758    return nullptr;
3759  }
3760  return ((ExprEvalResult *)E)->EvalData.stringVal;
3761}
3762
3763static const ExprEvalResultevaluateExpr(Expr *exprCXCursor C) {
3764  Expr::EvalResult ER;
3765  ASTContext &ctx = getCursorContext(C);
3766  if (!expr)
3767    return nullptr;
3768
3769  expr = expr->IgnoreParens();
3770  if (!expr->EvaluateAsRValue(ERctx))
3771    return nullptr;
3772
3773  QualType rettype;
3774  CallExpr *callExpr;
3775  auto result = llvm::make_unique<ExprEvalResult>();
3776  result->EvalType = CXEval_UnExposed;
3777  result->IsUnsignedInt = false;
3778
3779  if (ER.Val.isInt()) {
3780    result->EvalType = CXEval_Int;
3781
3782    autoval = ER.Val.getInt();
3783    if (val.isUnsigned()) {
3784      result->IsUnsignedInt = true;
3785      result->EvalData.unsignedVal = val.getZExtValue();
3786    } else {
3787      result->EvalData.intVal = val.getExtValue();
3788    }
3789
3790    return result.release();
3791  }
3792
3793  if (ER.Val.isFloat()) {
3794    llvm::SmallVector<char100Buffer;
3795    ER.Val.getFloat().toString(Buffer);
3796    std::string floatStr(Buffer.data(), Buffer.size());
3797    result->EvalType = CXEval_Float;
3798    bool ignored;
3799    llvm::APFloat apFloat = ER.Val.getFloat();
3800    apFloat.convert(llvm::APFloat::IEEEdouble(),
3801                    llvm::APFloat::rmNearestTiesToEven, &ignored);
3802    result->EvalData.floatVal = apFloat.convertToDouble();
3803    return result.release();
3804  }
3805
3806  if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3807    const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3808    auto *subExpr = I->getSubExprAsWritten();
3809    if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3810        subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
3811      const StringLiteral *StrE = nullptr;
3812      const ObjCStringLiteral *ObjCExpr;
3813      ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
3814
3815      if (ObjCExpr) {
3816        StrE = ObjCExpr->getString();
3817        result->EvalType = CXEval_ObjCStrLiteral;
3818      } else {
3819        StrE = cast<StringLiteral>(I->getSubExprAsWritten());
3820        result->EvalType = CXEval_StrLiteral;
3821      }
3822
3823      std::string strRef(StrE->getString().str());
3824      result->EvalData.stringVal = new char[strRef.size() + 1];
3825      strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
3826              strRef.size());
3827      result->EvalData.stringVal[strRef.size()] = '\0';
3828      return result.release();
3829    }
3830  } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3831             expr->getStmtClass() == Stmt::StringLiteralClass) {
3832    const StringLiteral *StrE = nullptr;
3833    const ObjCStringLiteral *ObjCExpr;
3834    ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
3835
3836    if (ObjCExpr) {
3837      StrE = ObjCExpr->getString();
3838      result->EvalType = CXEval_ObjCStrLiteral;
3839    } else {
3840      StrE = cast<StringLiteral>(expr);
3841      result->EvalType = CXEval_StrLiteral;
3842    }
3843
3844    std::string strRef(StrE->getString().str());
3845    result->EvalData.stringVal = new char[strRef.size() + 1];
3846    strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
3847    result->EvalData.stringVal[strRef.size()] = '\0';
3848    return result.release();
3849  }
3850
3851  if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3852    CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
3853
3854    rettype = CC->getType();
3855    if (rettype.getAsString() == "CFStringRef" &&
3856        CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
3857
3858      callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3859      StringLiteral *S = getCFSTR_value(callExpr);
3860      if (S) {
3861        std::string strLiteral(S->getString().str());
3862        result->EvalType = CXEval_CFStr;
3863
3864        result->EvalData.stringVal = new char[strLiteral.size() + 1];
3865        strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3866                strLiteral.size());
3867        result->EvalData.stringVal[strLiteral.size()] = '\0';
3868        return result.release();
3869      }
3870    }
3871
3872  } else if (expr->getStmtClass() == Stmt::CallExprClass) {
3873    callExpr = static_cast<CallExpr *>(expr);
3874    rettype = callExpr->getCallReturnType(ctx);
3875
3876    if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
3877      return nullptr;
3878
3879    if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
3880      if (callExpr->getNumArgs() == 1 &&
3881          !callExpr->getArg(0)->getType()->isIntegralType(ctx))
3882        return nullptr;
3883    } else if (rettype.getAsString() == "CFStringRef") {
3884
3885      StringLiteral *S = getCFSTR_value(callExpr);
3886      if (S) {
3887        std::string strLiteral(S->getString().str());
3888        result->EvalType = CXEval_CFStr;
3889        result->EvalData.stringVal = new char[strLiteral.size() + 1];
3890        strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
3891                strLiteral.size());
3892        result->EvalData.stringVal[strLiteral.size()] = '\0';
3893        return result.release();
3894      }
3895    }
3896  } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
3897    DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
3898    ValueDecl *V = D->getDecl();
3899    if (V->getKind() == Decl::Function) {
3900      std::string strName = V->getNameAsString();
3901      result->EvalType = CXEval_Other;
3902      result->EvalData.stringVal = new char[strName.size() + 1];
3903      strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
3904      result->EvalData.stringVal[strName.size()] = '\0';
3905      return result.release();
3906    }
3907  }
3908
3909  return nullptr;
3910}
3911
3912static const Expr *evaluateDeclExpr(const Decl *D) {
3913  if (!D)
3914    return nullptr;
3915  if (auto *Var = dyn_cast<VarDecl>(D))
3916    return Var->getInit();
3917  else if (auto *Field = dyn_cast<FieldDecl>(D))
3918    return Field->getInClassInitializer();
3919  return nullptr;
3920}
3921
3922static const Expr *evaluateCompoundStmtExpr(const CompoundStmt *CS) {
3923   (0) . __assert_fail ("CS && \"invalid compound statement\"", "/home/seafit/code_projects/clang_source/clang/tools/libclang/CIndex.cpp", 3923, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(CS && "invalid compound statement");
3924  for (auto *bodyIterator : CS->body()) {
3925    if (const auto *E = dyn_cast<Expr>(bodyIterator))
3926      return E;
3927  }
3928  return nullptr;
3929}
3930
3931CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
3932  if (const Expr *E =
3933          clang_getCursorKind(C) == CXCursor_CompoundStmt
3934              ? evaluateCompoundStmtExpr(cast<CompoundStmt>(getCursorStmt(C)))
3935              : evaluateDeclExpr(getCursorDecl(C)))
3936    return const_cast<CXEvalResult>(
3937        reinterpret_cast<const void *>(evaluateExpr(const_cast<Expr *>(E), C)));
3938  return nullptr;
3939}
3940
3941unsigned clang_Cursor_hasAttrs(CXCursor C) {
3942  const Decl *D = getCursorDecl(C);
3943  if (!D) {
3944    return 0;
3945  }
3946
3947  if (D->hasAttrs()) {
3948    return 1;
3949  }
3950
3951  return 0;
3952}
3953unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
3954  return CXSaveTranslationUnit_None;
3955}  
3956
3957static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
3958                                                  const char *FileName,
3959                                                  unsigned options) {
3960  CIndexer *CXXIdx = TU->CIdx;
3961  if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3962    setThreadBackgroundPriority();
3963
3964  bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
3965  return hadError ? CXSaveError_Unknown : CXSaveError_None;
3966}
3967
3968int clang_saveTranslationUnit(CXTranslationUnit TUconst char *FileName,
3969                              unsigned options) {
3970  LOG_FUNC_SECTION {
3971    *Log << TU << ' ' << FileName;
3972  }
3973
3974  if (isNotUsableTU(TU)) {
3975    LOG_BAD_TU(TU);
3976    return CXSaveError_InvalidTU;
3977  }
3978
3979  ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
3980  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3981  if (!CXXUnit->hasSema())
3982    return CXSaveError_InvalidTU;
3983
3984  CXSaveError result;
3985  auto SaveTranslationUnitImpl = [=, &result]() {
3986    result = clang_saveTranslationUnit_Impl(TUFileNameoptions);
3987  };
3988
3989  if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred()) {
3990    SaveTranslationUnitImpl();
3991
3992    if (getenv("LIBCLANG_RESOURCE_USAGE"))
3993      PrintLibclangResourceUsage(TU);
3994
3995    return result;
3996  }
3997
3998  // We have an AST that has invalid nodes due to compiler errors.
3999  // Use a crash recovery thread for protection.
4000
4001  llvm::CrashRecoveryContext CRC;
4002
4003  if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
4004    fprintf(stderr"libclang: crash detected during AST saving: {\n");
4005    fprintf(stderr"  'filename' : '%s'\n"FileName);
4006    fprintf(stderr"  'options' : %d,\n"options);
4007    fprintf(stderr"}\n");
4008
4009    return CXSaveError_Unknown;
4010
4011  } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
4012    PrintLibclangResourceUsage(TU);
4013  }
4014
4015  return result;
4016}
4017
4018void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
4019  if (CTUnit) {
4020    // If the translation unit has been marked as unsafe to free, just discard
4021    // it.
4022    ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4023    if (Unit && Unit->isUnsafeToFree())
4024      return;
4025
4026    delete cxtu::getASTUnit(CTUnit);
4027    delete CTUnit->StringPool;
4028    delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
4029    disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
4030    delete CTUnit->CommentToXML;
4031    delete CTUnit;
4032  }
4033}
4034
4035unsigned clang_suspendTranslationUnit(CXTranslationUnit CTUnit) {
4036  if (CTUnit) {
4037    ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4038
4039    if (Unit && Unit->isUnsafeToFree())
4040      return false;
4041
4042    Unit->ResetForParse();
4043    return true;
4044  }
4045
4046  return false;
4047}
4048
4049unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
4050  return CXReparse_None;
4051}
4052
4053static CXErrorCode
4054clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
4055                                  ArrayRef<CXUnsavedFileunsaved_files,
4056                                  unsigned options) {
4057  // Check arguments.
4058  if (isNotUsableTU(TU)) {
4059    LOG_BAD_TU(TU);
4060    return CXError_InvalidArguments;
4061  }
4062
4063  // Reset the associated diagnostics.
4064  delete static_cast<CXDiagnosticSetImpl*>(TU->Diagnostics);
4065  TU->Diagnostics = nullptr;
4066
4067  CIndexer *CXXIdx = TU->CIdx;
4068  if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
4069    setThreadBackgroundPriority();
4070
4071  ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4072  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4073
4074  std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
4075      new std::vector<ASTUnit::RemappedFile>());
4076
4077  // Recover resources if we crash before exiting this function.
4078  llvm::CrashRecoveryContextCleanupRegistrar<
4079    std::vector<ASTUnit::RemappedFile> > RemappedCleanup(RemappedFiles.get());
4080
4081  for (auto &UF : unsaved_files) {
4082    std::unique_ptr<llvm::MemoryBuffer> MB =
4083        llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
4084    RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
4085  }
4086
4087  if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
4088                        *RemappedFiles.get()))
4089    return CXError_Success;
4090  if (isASTReadError(CXXUnit))
4091    return CXError_ASTReadError;
4092  return CXError_Failure;
4093}
4094
4095int clang_reparseTranslationUnit(CXTranslationUnit TU,
4096                                 unsigned num_unsaved_files,
4097                                 struct CXUnsavedFile *unsaved_files,
4098                                 unsigned options) {
4099  LOG_FUNC_SECTION {
4100    *Log << TU;
4101  }
4102
4103  if (num_unsaved_files && !unsaved_files)
4104    return CXError_InvalidArguments;
4105
4106  CXErrorCode result;
4107  auto ReparseTranslationUnitImpl = [=, &result]() {
4108    result = clang_reparseTranslationUnit_Impl(
4109        TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
4110  };
4111
4112  llvm::CrashRecoveryContext CRC;
4113
4114  if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
4115    fprintf(stderr"libclang: crash detected during reparsing\n");
4116    cxtu::getASTUnit(TU)->setUnsafeToFree(true);
4117    return CXError_Crashed;
4118  } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
4119    PrintLibclangResourceUsage(TU);
4120
4121  return result;
4122}
4123
4124
4125CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
4126  if (isNotUsableTU(CTUnit)) {
4127    LOG_BAD_TU(CTUnit);
4128    return cxstring::createEmpty();
4129  }
4130
4131  ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4132  return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
4133}
4134
4135CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
4136  if (isNotUsableTU(TU)) {
4137    LOG_BAD_TU(TU);
4138    return clang_getNullCursor();
4139  }
4140
4141  ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4142  return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
4143}
4144
4145CXTargetInfo clang_getTranslationUnitTargetInfo(CXTranslationUnit CTUnit) {
4146  if (isNotUsableTU(CTUnit)) {
4147    LOG_BAD_TU(CTUnit);
4148    return nullptr;
4149  }
4150
4151  CXTargetInfoImplimpl = new CXTargetInfoImpl();
4152  impl->TranslationUnit = CTUnit;
4153  return impl;
4154}
4155
4156CXString clang_TargetInfo_getTriple(CXTargetInfo TargetInfo) {
4157  if (!TargetInfo)
4158    return cxstring::createEmpty();
4159
4160  CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4161   (0) . __assert_fail ("!isNotUsableTU(CTUnit) && \"Unexpected unusable translation unit in TargetInfo\"", "/home/seafit/code_projects/clang_source/clang/tools/libclang/CIndex.cpp", 4162, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(!isNotUsableTU(CTUnit) &&
4162 (0) . __assert_fail ("!isNotUsableTU(CTUnit) && \"Unexpected unusable translation unit in TargetInfo\"", "/home/seafit/code_projects/clang_source/clang/tools/libclang/CIndex.cpp", 4162, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         "Unexpected unusable translation unit in TargetInfo");
4163
4164  ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4165  std::string Triple =
4166    CXXUnit->getASTContext().getTargetInfo().getTriple().normalize();
4167  return cxstring::createDup(Triple);
4168}
4169
4170int clang_TargetInfo_getPointerWidth(CXTargetInfo TargetInfo) {
4171  if (!TargetInfo)
4172    return -1;
4173
4174  CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4175   (0) . __assert_fail ("!isNotUsableTU(CTUnit) && \"Unexpected unusable translation unit in TargetInfo\"", "/home/seafit/code_projects/clang_source/clang/tools/libclang/CIndex.cpp", 4176, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(!isNotUsableTU(CTUnit) &&
4176 (0) . __assert_fail ("!isNotUsableTU(CTUnit) && \"Unexpected unusable translation unit in TargetInfo\"", "/home/seafit/code_projects/clang_source/clang/tools/libclang/CIndex.cpp", 4176, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         "Unexpected unusable translation unit in TargetInfo");
4177
4178  ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4179  return CXXUnit->getASTContext().getTargetInfo().getMaxPointerWidth();
4180}
4181
4182void clang_TargetInfo_dispose(CXTargetInfo TargetInfo) {
4183  if (!TargetInfo)
4184    return;
4185
4186  delete TargetInfo;
4187}
4188
4189//===----------------------------------------------------------------------===//
4190// CXFile Operations.
4191//===----------------------------------------------------------------------===//
4192
4193CXString clang_getFileName(CXFile SFile) {
4194  if (!SFile)
4195    return cxstring::createNull();
4196
4197  FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4198  return cxstring::createRef(FEnt->getName());
4199}
4200
4201time_t clang_getFileTime(CXFile SFile) {
4202  if (!SFile)
4203    return 0;
4204
4205  FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4206  return FEnt->getModificationTime();
4207}
4208
4209CXFile clang_getFile(CXTranslationUnit TUconst char *file_name) {
4210  if (isNotUsableTU(TU)) {
4211    LOG_BAD_TU(TU);
4212    return nullptr;
4213  }
4214
4215  ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4216
4217  FileManager &FMgr = CXXUnit->getFileManager();
4218  return const_cast<FileEntry *>(FMgr.getFile(file_name));
4219}
4220
4221const char *clang_getFileContents(CXTranslationUnit TUCXFile file,
4222                                  size_t *size) {
4223  if (isNotUsableTU(TU)) {
4224    LOG_BAD_TU(TU);
4225    return nullptr;
4226  }
4227
4228  const SourceManager &SM = cxtu::getASTUnit(TU)->getSourceManager();
4229  FileID fid = SM.translateFile(static_cast<FileEntry *>(file));
4230  bool Invalid = true;
4231  llvm::MemoryBuffer *buf = SM.getBuffer(fid, &Invalid);
4232  if (Invalid) {
4233    if (size)
4234      *size = 0;
4235    return nullptr;
4236  }
4237  if (size)
4238    *size = buf->getBufferSize();
4239  return buf->getBufferStart();
4240}
4241
4242unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU,
4243                                            CXFile file) {
4244  if (isNotUsableTU(TU)) {
4245    LOG_BAD_TU(TU);
4246    return 0;
4247  }
4248
4249  if (!file)
4250    return 0;
4251
4252  ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4253  FileEntry *FEnt = static_cast<FileEntry *>(file);
4254  return CXXUnit->getPreprocessor().getHeaderSearchInfo()
4255                                          .isFileMultipleIncludeGuarded(FEnt);
4256}
4257
4258int clang_getFileUniqueID(CXFile fileCXFileUniqueID *outID) {
4259  if (!file || !outID)
4260    return 1;
4261
4262  FileEntry *FEnt = static_cast<FileEntry *>(file);
4263  const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
4264  outID->data[0] = ID.getDevice();
4265  outID->data[1] = ID.getFile();
4266  outID->data[2] = FEnt->getModificationTime();
4267  return 0;
4268}
4269
4270int clang_File_isEqual(CXFile file1CXFile file2) {
4271  if (file1 == file2)
4272    return true;
4273
4274  if (!file1 || !file2)
4275    return false;
4276
4277  FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
4278  FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
4279  return FEnt1->getUniqueID() == FEnt2->getUniqueID();
4280}
4281
4282CXString clang_File_tryGetRealPathName(CXFile SFile) {
4283  if (!SFile)
4284    return cxstring::createNull();
4285
4286  FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4287  return cxstring::createRef(FEnt->tryGetRealPathName());
4288}
4289
4290//===----------------------------------------------------------------------===//
4291// CXCursor Operations.
4292//===----------------------------------------------------------------------===//
4293
4294static const Decl *getDeclFromExpr(const Stmt *E) {
4295  if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
4296    return getDeclFromExpr(CE->getSubExpr());
4297
4298  if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
4299    return RefExpr->getDecl();
4300  if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
4301    return ME->getMemberDecl();
4302  if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
4303    return RE->getDecl();
4304  if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
4305    if (PRE->isExplicitProperty())
4306      return PRE->getExplicitProperty();
4307    // It could be messaging both getter and setter as in:
4308    // ++myobj.myprop;
4309    // in which case prefer to associate the setter since it is less obvious
4310    // from inspecting the source that the setter is going to get called.
4311    if (PRE->isMessagingSetter())
4312      return PRE->getImplicitPropertySetter();
4313    return PRE->getImplicitPropertyGetter();
4314  }
4315  if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
4316    return getDeclFromExpr(POE->getSyntacticForm());
4317  if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
4318    if (Expr *Src = OVE->getSourceExpr())
4319      return getDeclFromExpr(Src);
4320      
4321  if (const CallExpr *CE = dyn_cast<CallExpr>(E))
4322    return getDeclFromExpr(CE->getCallee());
4323  if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
4324    if (!CE->isElidable())
4325    return CE->getConstructor();
4326  if (const CXXInheritedCtorInitExpr *CE =
4327          dyn_cast<CXXInheritedCtorInitExpr>(E))
4328    return CE->getConstructor();
4329  if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
4330    return OME->getMethodDecl();
4331
4332  if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
4333    return PE->getProtocol();
4334  if (const SubstNonTypeTemplateParmPackExpr *NTTP
4335                              = dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4336    return NTTP->getParameterPack();
4337  if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
4338    if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) || 
4339        isa<ParmVarDecl>(SizeOfPack->getPack()))
4340      return SizeOfPack->getPack();
4341
4342  return nullptr;
4343}
4344
4345static SourceLocation getLocationFromExpr(const Expr *E) {
4346  if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
4347    return getLocationFromExpr(CE->getSubExpr());
4348
4349  if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
4350    return /*FIXME:*/Msg->getLeftLoc();
4351  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
4352    return DRE->getLocation();
4353  if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
4354    return Member->getMemberLoc();
4355  if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
4356    return Ivar->getLocation();
4357  if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
4358    return SizeOfPack->getPackLoc();
4359  if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
4360    return PropRef->getLocation();
4361
4362  return E->getBeginLoc();
4363}
4364
4365extern "C" {
4366
4367unsigned clang_visitChildren(CXCursor parent,
4368                             CXCursorVisitor visitor,
4369                             CXClientData client_data) {
4370  CursorVisitor CursorVis(getCursorTU(parent), visitorclient_data,
4371                          /*VisitPreprocessorLast=*/false);
4372  return CursorVis.VisitChildren(parent);
4373}
4374
4375#ifndef __has_feature
4376#define __has_feature(x) 0
4377#endif
4378#if __has_feature(blocks)
4379typedef enum CXChildVisitResult 
4380     (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
4381
4382static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4383    CXClientData client_data) {
4384  CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4385  return block(cursor, parent);
4386}
4387#else
4388// If we are compiled with a compiler that doesn't have native blocks support,
4389// define and call the block manually, so the 
4390typedef struct _CXChildVisitResult
4391{
4392 void *isa;
4393 int flags;
4394 int reserved;
4395 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
4396                                         CXCursor);
4397} *CXCursorVisitorBlock;
4398
4399static enum CXChildVisitResult visitWithBlock(CXCursor cursorCXCursor parent,
4400    CXClientData client_data) {
4401  CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4402  return block->invoke(blockcursorparent);
4403}
4404#endif
4405
4406
4407unsigned clang_visitChildrenWithBlock(CXCursor parent,
4408                                      CXCursorVisitorBlock block) {
4409  return clang_visitChildren(parentvisitWithBlockblock);
4410}
4411
4412static CXString getDeclSpelling(const Decl *D) {
4413  if (!D)
4414    return cxstring::createEmpty();
4415
4416  const NamedDecl *ND = dyn_cast<NamedDecl>(D);
4417  if (!ND) {
4418    if (const ObjCPropertyImplDecl *PropImpl =
4419            dyn_cast<ObjCPropertyImplDecl>(D))
4420      if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
4421        return cxstring::createDup(Property->getIdentifier()->getName());
4422    
4423    if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
4424      if (Module *Mod = ImportD->getImportedModule())
4425        return cxstring::createDup(Mod->getFullModuleName());
4426
4427    return cxstring::createEmpty();
4428  }
4429  
4430  if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
4431    return cxstring::createDup(OMD->getSelector().getAsString());
4432
4433  if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
4434    // No, this isn't the same as the code below. getIdentifier() is non-virtual
4435    // and returns different names. NamedDecl returns the class name and
4436    // ObjCCategoryImplDecl returns the category name.
4437    return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
4438
4439  if (isa<UsingDirectiveDecl>(D))
4440    return cxstring::createEmpty();
4441  
4442  SmallString<1024S;
4443  llvm::raw_svector_ostream os(S);
4444  ND->printName(os);
4445  
4446  return cxstring::createDup(os.str());
4447}
4448
4449CXString clang_getCursorSpelling(CXCursor C) {
4450  if (clang_isTranslationUnit(C.kind))
4451    return clang_getTranslationUnitSpelling(getCursorTU(C));
4452
4453  if (clang_isReference(C.kind)) {
4454    switch (C.kind) {
4455    case CXCursor_ObjCSuperClassRef: {
4456      const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
4457      return cxstring::createRef(Super->getIdentifier()->getNameStart());
4458    }
4459    case CXCursor_ObjCClassRef: {
4460      const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
4461      return cxstring::createRef(Class->getIdentifier()->getNameStart());
4462    }
4463    case CXCursor_ObjCProtocolRef: {
4464      const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
4465       (0) . __assert_fail ("OID && \"getCursorSpelling(). Missing protocol decl\"", "/home/seafit/code_projects/clang_source/clang/tools/libclang/CIndex.cpp", 4465, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(OID && "getCursorSpelling(): Missing protocol decl");
4466      return cxstring::createRef(OID->getIdentifier()->getNameStart());
4467    }
4468    case CXCursor_CXXBaseSpecifier: {
4469      const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
4470      return cxstring::createDup(B->getType().getAsString());
4471    }
4472    case CXCursor_TypeRef: {
4473      const TypeDecl *Type = getCursorTypeRef(C).first;
4474       (0) . __assert_fail ("Type && \"Missing type decl\"", "/home/seafit/code_projects/clang_source/clang/tools/libclang/CIndex.cpp", 4474, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(Type && "Missing type decl");
4475
4476      return cxstring::createDup(getCursorContext(C).getTypeDeclType(Type).
4477                              getAsString());
4478    }
4479    case CXCursor_TemplateRef: {
4480      const TemplateDecl *Template = getCursorTemplateRef(C).first;
4481       (0) . __assert_fail ("Template && \"Missing template decl\"", "/home/seafit/code_projects/clang_source/clang/tools/libclang/CIndex.cpp", 4481, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(Template && "Missing template decl");
4482      
4483      return cxstring::createDup(Template->getNameAsString());
4484    }
4485        
4486    case CXCursor_NamespaceRef: {
4487      const NamedDecl *NS = getCursorNamespaceRef(C).first;
4488       (0) . __assert_fail ("NS && \"Missing namespace decl\"", "/home/seafit/code_projects/clang_source/clang/tools/libclang/CIndex.cpp", 4488, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(NS && "Missing namespace decl");
4489      
4490      return cxstring::createDup(NS->getNameAsString());
4491    }
4492
4493    case CXCursor_MemberRef: {
4494      const FieldDecl *Field = getCursorMemberRef(C).first;
4495       (0) . __assert_fail ("Field && \"Missing member decl\"", "/home/seafit/code_projects/clang_source/clang/tools/libclang/CIndex.cpp", 4495, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(Field && "Missing member decl");
4496      
4497      return cxstring::createDup(Field->getNameAsString());
4498    }
4499
4500    case CXCursor_LabelRef: {
4501      const LabelStmt *Label = getCursorLabelRef(C).first;
4502       (0) . __assert_fail ("Label && \"Missing label\"", "/home/seafit/code_projects/clang_source/clang/tools/libclang/CIndex.cpp", 4502, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(Label && "Missing label");
4503      
4504      return cxstring::createRef(Label->getName());
4505    }
4506
4507    case CXCursor_OverloadedDeclRef: {
4508      OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4509      if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4510        if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
4511          return cxstring::createDup(ND->getNameAsString());
4512        return cxstring::createEmpty();
4513      }
4514      if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
4515        return cxstring::createDup(E->getName().getAsString());
4516      OverloadedTemplateStorage *Ovl
4517        = Storage.get<OverloadedTemplateStorage*>();
4518      if (Ovl->size() == 0)
4519        return cxstring::createEmpty();
4520      return cxstring::createDup((*Ovl->begin())->getNameAsString());
4521    }
4522        
4523    case CXCursor_VariableRef: {
4524      const VarDecl *Var = getCursorVariableRef(C).first;
4525       (0) . __assert_fail ("Var && \"Missing variable decl\"", "/home/seafit/code_projects/clang_source/clang/tools/libclang/CIndex.cpp", 4525, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(Var && "Missing variable decl");
4526      
4527      return cxstring::createDup(Var->getNameAsString());
4528    }
4529        
4530    default:
4531      return cxstring::createRef("<not implemented>");
4532    }
4533  }
4534
4535  if (clang_isExpression(C.kind)) {
4536    const Expr *E = getCursorExpr(C);
4537
4538    if (C.kind == CXCursor_ObjCStringLiteral ||
4539        C.kind == CXCursor_StringLiteral) {
4540      const StringLiteral *SLit;
4541      if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4542        SLit = OSL->getString();
4543      } else {
4544        SLit = cast<StringLiteral>(E);
4545      }
4546      SmallString<256Buf;
4547      llvm::raw_svector_ostream OS(Buf);
4548      SLit->outputString(OS);
4549      return cxstring::createDup(OS.str());
4550    }
4551
4552    const Decl *D = getDeclFromExpr(getCursorExpr(C));
4553    if (D)
4554      return getDeclSpelling(D);
4555    return cxstring::createEmpty();
4556  }
4557
4558  if (clang_isStatement(C.kind)) {
4559    const Stmt *S = getCursorStmt(C);
4560    if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
4561      return cxstring::createRef(Label->getName());
4562
4563    return cxstring::createEmpty();
4564  }
4565  
4566  if (C.kind == CXCursor_MacroExpansion)
4567    return cxstring::createRef(getCursorMacroExpansion(C).getName()
4568                                                           ->getNameStart());
4569
4570  if (C.kind == CXCursor_MacroDefinition)
4571    return cxstring::createRef(getCursorMacroDefinition(C)->getName()
4572                                                           ->getNameStart());
4573
4574  if (C.kind == CXCursor_InclusionDirective)
4575    return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
4576      
4577  if (clang_isDeclaration(C.kind))
4578    return getDeclSpelling(getCursorDecl(C));
4579
4580  if (C.kind == CXCursor_AnnotateAttr) {
4581    const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
4582    return cxstring::createDup(AA->getAnnotation());
4583  }
4584
4585  if (C.kind == CXCursor_AsmLabelAttr) {
4586    const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
4587    return cxstring::createDup(AA->getLabel());
4588  }
4589
4590  if (C.kind == CXCursor_PackedAttr) {
4591    return cxstring::createRef("packed");
4592  }
4593
4594  if (C.kind == CXCursor_VisibilityAttr) {
4595    const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4596    switch (AA->getVisibility()) {
4597    case VisibilityAttr::VisibilityType::Default:
4598      return cxstring::createRef("default");
4599    case VisibilityAttr::VisibilityType::Hidden:
4600      return cxstring::createRef("hidden");
4601    case VisibilityAttr::VisibilityType::Protected:
4602      return cxstring::createRef("protected");
4603    }
4604    llvm_unreachable("unknown visibility type");
4605  }
4606
4607  return cxstring::createEmpty();
4608}
4609
4610CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C,
4611                                                unsigned pieceIndex,
4612                                                unsigned options) {
4613  if (clang_Cursor_isNull(C))
4614    return clang_getNullRange();
4615
4616  ASTContext &Ctx = getCursorContext(C);
4617
4618  if (clang_isStatement(C.kind)) {
4619    const Stmt *S = getCursorStmt(C);
4620    if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
4621      if (pieceIndex > 0)
4622        return clang_getNullRange();
4623      return cxloc::translateSourceRange(CtxLabel->getIdentLoc());
4624    }
4625
4626    return clang_getNullRange();
4627  }
4628
4629  if (C.kind == CXCursor_ObjCMessageExpr) {
4630    if (const ObjCMessageExpr *
4631          ME = dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4632      if (pieceIndex >= ME->getNumSelectorLocs())
4633        return clang_getNullRange();
4634      return cxloc::translateSourceRange(CtxME->getSelectorLoc(pieceIndex));
4635    }
4636  }
4637
4638  if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4639      C.kind == CXCursor_ObjCClassMethodDecl) {
4640    if (const ObjCMethodDecl *
4641          MD = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4642      if (pieceIndex >= MD->getNumSelectorLocs())
4643        return clang_getNullRange();
4644      return cxloc::translateSourceRange(CtxMD->getSelectorLoc(pieceIndex));
4645    }
4646  }
4647
4648  if (C.kind == CXCursor_ObjCCategoryDecl ||
4649      C.kind == CXCursor_ObjCCategoryImplDecl) {
4650    if (pieceIndex > 0)
4651      return clang_getNullRange();
4652    if (const ObjCCategoryDecl *
4653          CD = dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4654      return cxloc::translateSourceRange(CtxCD->getCategoryNameLoc());
4655    if (const ObjCCategoryImplDecl *
4656          CID = dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4657      return cxloc::translateSourceRange(CtxCID->getCategoryNameLoc());
4658  }
4659
4660  if (C.kind == CXCursor_ModuleImportDecl) {
4661    if (pieceIndex > 0)
4662      return clang_getNullRange();
4663    if (const ImportDecl *ImportD =
4664            dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
4665      ArrayRef<SourceLocationLocs = ImportD->getIdentifierLocs();
4666      if (!Locs.empty())
4667        return cxloc::translateSourceRange(Ctx,
4668                                         SourceRange(Locs.front(), Locs.back()));
4669    }
4670    return clang_getNullRange();
4671  }
4672
4673  if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
4674      C.kind == CXCursor_ConversionFunction ||
4675      C.kind == CXCursor_FunctionDecl) {
4676    if (pieceIndex > 0)
4677      return clang_getNullRange();
4678    if (const FunctionDecl *FD =
4679            dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4680      DeclarationNameInfo FunctionName = FD->getNameInfo();
4681      return cxloc::translateSourceRange(CtxFunctionName.getSourceRange());
4682    }
4683    return clang_getNullRange();
4684  }
4685
4686  // FIXME: A CXCursor_InclusionDirective should give the location of the
4687  // filename, but we don't keep track of this.
4688
4689  // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4690  // but we don't keep track of this.
4691
4692  // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4693  // but we don't keep track of this.
4694
4695  // Default handling, give the location of the cursor.
4696
4697  if (pieceIndex > 0)
4698    return clang_getNullRange();
4699
4700  CXSourceLocation CXLoc = clang_getCursorLocation(C);
4701  SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4702  return cxloc::translateSourceRange(CtxLoc);
4703}
4704
4705CXString clang_Cursor_getMangling(CXCursor C) {
4706  if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4707    return cxstring::createEmpty();
4708
4709  // Mangling only works for functions and variables.
4710  const Decl *D = getCursorDecl(C);
4711  if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4712    return cxstring::createEmpty();
4713
4714  ASTContext &Ctx = D->getASTContext();
4715  index::CodegenNameGenerator CGNameGen(Ctx);
4716  return cxstring::createDup(CGNameGen.getName(D));
4717}
4718
4719CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4720  if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4721    return nullptr;
4722
4723  const Decl *D = getCursorDecl(C);
4724  if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4725    return nullptr;
4726
4727  ASTContext &Ctx = D->getASTContext();
4728  index::CodegenNameGenerator CGNameGen(Ctx);
4729  std::vector<std::stringManglings = CGNameGen.getAllManglings(D);
4730  return cxstring::createSet(Manglings);
4731}
4732
4733CXStringSet *clang_Cursor_getObjCManglings(CXCursor C) {
4734  if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4735    return nullptr;
4736
4737  const Decl *D = getCursorDecl(C);
4738  if (!(isa<ObjCInterfaceDecl>(D) || isa<ObjCImplementationDecl>(D)))
4739    return nullptr;
4740
4741  ASTContext &Ctx = D->getASTContext();
4742  index::CodegenNameGenerator CGNameGen(Ctx);
4743  std::vector<std::stringManglings = CGNameGen.getAllManglings(D);
4744  return cxstring::createSet(Manglings);
4745}
4746
4747CXPrintingPolicy clang_getCursorPrintingPolicy(CXCursor C) {
4748  if (clang_Cursor_isNull(C))
4749    return 0;
4750  return new PrintingPolicy(getCursorContext(C).getPrintingPolicy());
4751}
4752
4753void clang_PrintingPolicy_dispose(CXPrintingPolicy Policy) {
4754  if (Policy)
4755    delete static_cast<PrintingPolicy *>(Policy);
4756}
4757
4758unsigned
4759clang_PrintingPolicy_getProperty(CXPrintingPolicy Policy,
4760                                 enum CXPrintingPolicyProperty Property) {
4761  if (!Policy)
4762    return 0;
4763
4764  PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4765  switch (Property) {
4766  case CXPrintingPolicy_Indentation:
4767    return P->Indentation;
4768  case CXPrintingPolicy_SuppressSpecifiers:
4769    return P->SuppressSpecifiers;
4770  case CXPrintingPolicy_SuppressTagKeyword:
4771    return P->SuppressTagKeyword;
4772  case CXPrintingPolicy_IncludeTagDefinition:
4773    return P->IncludeTagDefinition;
4774  case CXPrintingPolicy_SuppressScope:
4775    return P->SuppressScope;
4776  case CXPrintingPolicy_SuppressUnwrittenScope:
4777    return P->SuppressUnwrittenScope;
4778  case CXPrintingPolicy_SuppressInitializers:
4779    return P->SuppressInitializers;
4780  case CXPrintingPolicy_ConstantArraySizeAsWritten:
4781    return P->ConstantArraySizeAsWritten;
4782  case CXPrintingPolicy_AnonymousTagLocations:
4783    return P->AnonymousTagLocations;
4784  case CXPrintingPolicy_SuppressStrongLifetime:
4785    return P->SuppressStrongLifetime;
4786  case CXPrintingPolicy_SuppressLifetimeQualifiers:
4787    return P->SuppressLifetimeQualifiers;
4788  case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4789    return P->SuppressTemplateArgsInCXXConstructors;
4790  case CXPrintingPolicy_Bool:
4791    return P->Bool;
4792  case CXPrintingPolicy_Restrict:
4793    return P->Restrict;
4794  case CXPrintingPolicy_Alignof:
4795    return P->Alignof;
4796  case CXPrintingPolicy_UnderscoreAlignof:
4797    return P->UnderscoreAlignof;
4798  case CXPrintingPolicy_UseVoidForZeroParams:
4799    return P->UseVoidForZeroParams;
4800  case CXPrintingPolicy_TerseOutput:
4801    return P->TerseOutput;
4802  case CXPrintingPolicy_PolishForDeclaration:
4803    return P->PolishForDeclaration;
4804  case CXPrintingPolicy_Half:
4805    return P->Half;
4806  case CXPrintingPolicy_MSWChar:
4807    return P->MSWChar;
4808  case CXPrintingPolicy_IncludeNewlines:
4809    return P->IncludeNewlines;
4810  case CXPrintingPolicy_MSVCFormatting:
4811    return P->MSVCFormatting;
4812  case CXPrintingPolicy_ConstantsAsWritten:
4813    return P->ConstantsAsWritten;
4814  case CXPrintingPolicy_SuppressImplicitBase:
4815    return P->SuppressImplicitBase;
4816  case CXPrintingPolicy_FullyQualifiedName:
4817    return P->FullyQualifiedName;
4818  }
4819
4820   (0) . __assert_fail ("false && \"Invalid CXPrintingPolicyProperty\"", "/home/seafit/code_projects/clang_source/clang/tools/libclang/CIndex.cpp", 4820, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(false && "Invalid CXPrintingPolicyProperty");
4821  return 0;
4822}
4823
4824void clang_PrintingPolicy_setProperty(CXPrintingPolicy Policy,
4825                                      enum CXPrintingPolicyProperty Property,
4826                                      unsigned Value) {
4827  if (!Policy)
4828    return;
4829
4830  PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4831  switch (Property) {
4832  case CXPrintingPolicy_Indentation:
4833    P->Indentation = Value;
4834    return;
4835  case CXPrintingPolicy_SuppressSpecifiers:
4836    P->SuppressSpecifiers = Value;
4837    return;
4838  case CXPrintingPolicy_SuppressTagKeyword:
4839    P->SuppressTagKeyword = Value;
4840    return;
4841  case CXPrintingPolicy_IncludeTagDefinition:
4842    P->IncludeTagDefinition = Value;
4843    return;
4844  case CXPrintingPolicy_SuppressScope:
4845    P->SuppressScope = Value;
4846    return;
4847  case CXPrintingPolicy_SuppressUnwrittenScope:
4848    P->SuppressUnwrittenScope = Value;
4849    return;
4850  case CXPrintingPolicy_SuppressInitializers:
4851    P->SuppressInitializers = Value;
4852    return;
4853  case CXPrintingPolicy_ConstantArraySizeAsWritten:
4854    P->ConstantArraySizeAsWritten = Value;
4855    return;
4856  case CXPrintingPolicy_AnonymousTagLocations:
4857    P->AnonymousTagLocations = Value;
4858    return;
4859  case CXPrintingPolicy_SuppressStrongLifetime:
4860    P->SuppressStrongLifetime = Value;
4861    return;
4862  case CXPrintingPolicy_SuppressLifetimeQualifiers:
4863    P->SuppressLifetimeQualifiers = Value;
4864    return;
4865  case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4866    P->SuppressTemplateArgsInCXXConstructors = Value;
4867    return;
4868  case CXPrintingPolicy_Bool:
4869    P->Bool = Value;
4870    return;
4871  case CXPrintingPolicy_Restrict:
4872    P->Restrict = Value;
4873    return;
4874  case CXPrintingPolicy_Alignof:
4875    P->Alignof = Value;
4876    return;
4877  case CXPrintingPolicy_UnderscoreAlignof:
4878    P->UnderscoreAlignof = Value;
4879    return;
4880  case CXPrintingPolicy_UseVoidForZeroParams:
4881    P->UseVoidForZeroParams = Value;
4882    return;
4883  case CXPrintingPolicy_TerseOutput:
4884    P->TerseOutput = Value;
4885    return;
4886  case CXPrintingPolicy_PolishForDeclaration:
4887    P->PolishForDeclaration = Value;
4888    return;
4889  case CXPrintingPolicy_Half:
4890    P->Half = Value;
4891    return;
4892  case CXPrintingPolicy_MSWChar:
4893    P->MSWChar = Value;
4894    return;
4895  case CXPrintingPolicy_IncludeNewlines:
4896    P->IncludeNewlines = Value;
4897    return;
4898  case CXPrintingPolicy_MSVCFormatting:
4899    P->MSVCFormatting = Value;
4900    return;
4901  case CXPrintingPolicy_ConstantsAsWritten:
4902    P->ConstantsAsWritten = Value;
4903    return;
4904  case CXPrintingPolicy_SuppressImplicitBase:
4905    P->SuppressImplicitBase = Value;
4906    return;
4907  case CXPrintingPolicy_FullyQualifiedName:
4908    P->FullyQualifiedName = Value;
4909    return;
4910  }
4911
4912   (0) . __assert_fail ("false && \"Invalid CXPrintingPolicyProperty\"", "/home/seafit/code_projects/clang_source/clang/tools/libclang/CIndex.cpp", 4912, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(false && "Invalid CXPrintingPolicyProperty");
4913}
4914
4915CXString clang_getCursorPrettyPrinted(CXCursor CCXPrintingPolicy cxPolicy) {
4916  if (clang_Cursor_isNull(C))
4917    return cxstring::createEmpty();
4918
4919  if (clang_isDeclaration(C.kind)) {
4920    const Decl *D = getCursorDecl(C);
4921    if (!D)
4922      return cxstring::createEmpty();
4923
4924    SmallString<128Str;
4925    llvm::raw_svector_ostream OS(Str);
4926    PrintingPolicy *UserPolicy = static_cast<PrintingPolicy *>(cxPolicy);
4927    D->print(OS, UserPolicy ? *UserPolicy
4928                            : getCursorContext(C).getPrintingPolicy());
4929
4930    return cxstring::createDup(OS.str());
4931  }
4932
4933  return cxstring::createEmpty();
4934}
4935
4936CXString clang_getCursorDisplayName(CXCursor C) {
4937  if (!clang_isDeclaration(C.kind))
4938    return clang_getCursorSpelling(C);
4939  
4940  const Decl *D = getCursorDecl(C);
4941  if (!D)
4942    return cxstring::createEmpty();
4943
4944  PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
4945  if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
4946    D = FunTmpl->getTemplatedDecl();
4947  
4948  if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
4949    SmallString<64Str;
4950    llvm::raw_svector_ostream OS(Str);
4951    OS << *Function;
4952    if (Function->getPrimaryTemplate())
4953      OS << "<>";
4954    OS << "(";
4955    for (unsigned I = 0N = Function->getNumParams(); I != N; ++I) {
4956      if (I)
4957        OS << ", ";
4958      OS << Function->getParamDecl(I)->getType().getAsString(Policy);
4959    }
4960    
4961    if (Function->isVariadic()) {
4962      if (Function->getNumParams())
4963        OS << ", ";
4964      OS << "...";
4965    }
4966    OS << ")";
4967    return cxstring::createDup(OS.str());
4968  }
4969  
4970  if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
4971    SmallString<64Str;
4972    llvm::raw_svector_ostream OS(Str);
4973    OS << *ClassTemplate;
4974    OS << "<";
4975    TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
4976    for (unsigned I = 0N = Params->size(); I != N; ++I) {
4977      if (I)
4978        OS << ", ";
4979      
4980      NamedDecl *Param = Params->getParam(I);
4981      if (Param->getIdentifier()) {
4982        OS << Param->getIdentifier()->getName();
4983        continue;
4984      }
4985      
4986      // There is no parameter name, which makes this tricky. Try to come up
4987      // with something useful that isn't too long.
4988      if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4989        OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
4990      else if (NonTypeTemplateParmDecl *NTTP
4991                                    = dyn_cast<NonTypeTemplateParmDecl>(Param))
4992        OS << NTTP->getType().getAsString(Policy);
4993      else
4994        OS << "template<...> class";
4995    }
4996    
4997    OS << ">";
4998    return cxstring::createDup(OS.str());
4999  }
5000  
5001  if (const ClassTemplateSpecializationDecl *ClassSpec
5002                              = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
5003    // If the type was explicitly written, use that.
5004    if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
5005      return cxstring::createDup(TSInfo->getType().getAsString(Policy));
5006
5007    SmallString<128Str;
5008    llvm::raw_svector_ostream OS(Str);
5009    OS << *ClassSpec;
5010    printTemplateArgumentList(OS, ClassSpec->getTemplateArgs().asArray(),
5011                              Policy);
5012    return cxstring::createDup(OS.str());
5013  }
5014  
5015  return clang_getCursorSpelling(C);
5016}
5017  
5018CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
5019  switch (Kind) {
5020  case CXCursor_FunctionDecl:
5021      return cxstring::createRef("FunctionDecl");
5022  case CXCursor_TypedefDecl:
5023      return cxstring::createRef("TypedefDecl");
5024  case CXCursor_EnumDecl:
5025      return cxstring::createRef("EnumDecl");
5026  case CXCursor_EnumConstantDecl:
5027      return cxstring::createRef("EnumConstantDecl");
5028  case CXCursor_StructDecl:
5029      return cxstring::createRef("StructDecl");
5030  case CXCursor_UnionDecl:
5031      return cxstring::createRef("UnionDecl");
5032  case CXCursor_ClassDecl:
5033      return cxstring::createRef("ClassDecl");
5034  case CXCursor_FieldDecl:
5035      return cxstring::createRef("FieldDecl");
5036  case CXCursor_VarDecl:
5037      return cxstring::createRef("VarDecl");
5038  case CXCursor_ParmDecl:
5039      return cxstring::createRef("ParmDecl");
5040  case CXCursor_ObjCInterfaceDecl:
5041      return cxstring::createRef("ObjCInterfaceDecl");
5042  case CXCursor_ObjCCategoryDecl:
5043      return cxstring::createRef("ObjCCategoryDecl");
5044  case CXCursor_ObjCProtocolDecl:
5045      return cxstring::createRef("ObjCProtocolDecl");
5046  case CXCursor_ObjCPropertyDecl:
5047      return cxstring::createRef("ObjCPropertyDecl");
5048  case CXCursor_ObjCIvarDecl:
5049      return cxstring::createRef("ObjCIvarDecl");
5050  case CXCursor_ObjCInstanceMethodDecl:
5051      return cxstring::createRef("ObjCInstanceMethodDecl");
5052  case CXCursor_ObjCClassMethodDecl:
5053      return cxstring::createRef("ObjCClassMethodDecl");
5054  case CXCursor_ObjCImplementationDecl:
5055      return cxstring::createRef("ObjCImplementationDecl");
5056  case CXCursor_ObjCCategoryImplDecl:
5057      return cxstring::createRef("ObjCCategoryImplDecl");
5058  case CXCursor_CXXMethod:
5059      return cxstring::createRef("CXXMethod");
5060  case CXCursor_UnexposedDecl:
5061      return cxstring::createRef("UnexposedDecl");
5062  case CXCursor_ObjCSuperClassRef:
5063      return cxstring::createRef("ObjCSuperClassRef");
5064  case CXCursor_ObjCProtocolRef:
5065      return cxstring::createRef("ObjCProtocolRef");
5066  case CXCursor_ObjCClassRef:
5067      return cxstring::createRef("ObjCClassRef");
5068  case CXCursor_TypeRef:
5069      return cxstring::createRef("TypeRef");
5070  case CXCursor_TemplateRef:
5071      return cxstring::createRef("TemplateRef");
5072  case CXCursor_NamespaceRef:
5073    return cxstring::createRef("NamespaceRef");
5074  case CXCursor_MemberRef:
5075    return cxstring::createRef("MemberRef");
5076  case CXCursor_LabelRef:
5077    return cxstring::createRef("LabelRef");
5078  case CXCursor_OverloadedDeclRef:
5079    return cxstring::createRef("OverloadedDeclRef");
5080  case CXCursor_VariableRef:
5081    return cxstring::createRef("VariableRef");
5082  case CXCursor_IntegerLiteral:
5083      return cxstring::createRef("IntegerLiteral");
5084  case CXCursor_FixedPointLiteral:
5085      return cxstring::createRef("FixedPointLiteral");
5086  case CXCursor_FloatingLiteral:
5087      return cxstring::createRef("FloatingLiteral");
5088  case CXCursor_ImaginaryLiteral:
5089      return cxstring::createRef("ImaginaryLiteral");
5090  case CXCursor_StringLiteral:
5091      return cxstring::createRef("StringLiteral");
5092  case CXCursor_CharacterLiteral:
5093      return cxstring::createRef("CharacterLiteral");
5094  case CXCursor_ParenExpr:
5095      return cxstring::createRef("ParenExpr");
5096  case CXCursor_UnaryOperator:
5097      return cxstring::createRef("UnaryOperator");
5098  case CXCursor_ArraySubscriptExpr:
5099      return cxstring::createRef("ArraySubscriptExpr");
5100  case CXCursor_OMPArraySectionExpr:
5101      return cxstring::createRef("OMPArraySectionExpr");
5102  case CXCursor_BinaryOperator:
5103      return cxstring::createRef("BinaryOperator");
5104  case CXCursor_CompoundAssignOperator:
5105      return cxstring::createRef("CompoundAssignOperator");
5106  case CXCursor_ConditionalOperator:
5107      return cxstring::createRef("ConditionalOperator");
5108  case CXCursor_CStyleCastExpr:
5109      return cxstring::createRef("CStyleCastExpr");
5110  case CXCursor_CompoundLiteralExpr:
5111      return cxstring::createRef("CompoundLiteralExpr");
5112  case CXCursor_InitListExpr:
5113      return cxstring::createRef("InitListExpr");
5114  case CXCursor_AddrLabelExpr:
5115      return cxstring::createRef("AddrLabelExpr");
5116  case CXCursor_StmtExpr:
5117      return cxstring::createRef("StmtExpr");
5118  case CXCursor_GenericSelectionExpr:
5119      return cxstring::createRef("GenericSelectionExpr");
5120  case CXCursor_GNUNullExpr:
5121      return cxstring::createRef("GNUNullExpr");
5122  case CXCursor_CXXStaticCastExpr:
5123      return cxstring::createRef("CXXStaticCastExpr");
5124  case CXCursor_CXXDynamicCastExpr:
5125      return cxstring::createRef("CXXDynamicCastExpr");
5126  case CXCursor_CXXReinterpretCastExpr:
5127      return cxstring::createRef("CXXReinterpretCastExpr");
5128  case CXCursor_CXXConstCastExpr:
5129      return cxstring::createRef("CXXConstCastExpr");
5130  case CXCursor_CXXFunctionalCastExpr:
5131      return cxstring::createRef("CXXFunctionalCastExpr");
5132  case CXCursor_CXXTypeidExpr:
5133      return cxstring::createRef("CXXTypeidExpr");
5134  case CXCursor_CXXBoolLiteralExpr:
5135      return cxstring::createRef("CXXBoolLiteralExpr");
5136  case CXCursor_CXXNullPtrLiteralExpr:
5137      return cxstring::createRef("CXXNullPtrLiteralExpr");
5138  case CXCursor_CXXThisExpr:
5139      return cxstring::createRef("CXXThisExpr");
5140  case CXCursor_CXXThrowExpr:
5141      return cxstring::createRef("CXXThrowExpr");
5142  case CXCursor_CXXNewExpr:
5143      return cxstring::createRef("CXXNewExpr");
5144  case CXCursor_CXXDeleteExpr:
5145      return cxstring::createRef("CXXDeleteExpr");
5146  case CXCursor_UnaryExpr:
5147      return cxstring::createRef("UnaryExpr");
5148  case CXCursor_ObjCStringLiteral:
5149      return cxstring::createRef("ObjCStringLiteral");
5150  case CXCursor_ObjCBoolLiteralExpr:
5151      return cxstring::createRef("ObjCBoolLiteralExpr");
5152  case CXCursor_ObjCAvailabilityCheckExpr:
5153      return cxstring::createRef("ObjCAvailabilityCheckExpr");
5154  case CXCursor_ObjCSelfExpr:
5155      return cxstring::createRef("ObjCSelfExpr");
5156  case CXCursor_ObjCEncodeExpr:
5157      return cxstring::createRef("ObjCEncodeExpr");
5158  case CXCursor_ObjCSelectorExpr:
5159      return cxstring::createRef("ObjCSelectorExpr");
5160  case CXCursor_ObjCProtocolExpr:
5161      return cxstring::createRef("ObjCProtocolExpr");
5162  case CXCursor_ObjCBridgedCastExpr:
5163      return cxstring::createRef("ObjCBridgedCastExpr");
5164  case CXCursor_BlockExpr:
5165      return cxstring::createRef("BlockExpr");
5166  case CXCursor_PackExpansionExpr:
5167      return cxstring::createRef("PackExpansionExpr");
5168  case CXCursor_SizeOfPackExpr:
5169      return cxstring::createRef("SizeOfPackExpr");
5170  case CXCursor_LambdaExpr:
5171    return cxstring::createRef("LambdaExpr");
5172  case CXCursor_UnexposedExpr:
5173      return cxstring::createRef("UnexposedExpr");
5174  case CXCursor_DeclRefExpr:
5175      return cxstring::createRef("DeclRefExpr");
5176  case CXCursor_MemberRefExpr:
5177      return cxstring::createRef("MemberRefExpr");
5178  case CXCursor_CallExpr:
5179      return cxstring::createRef("CallExpr");
5180  case CXCursor_ObjCMessageExpr:
5181      return cxstring::createRef("ObjCMessageExpr");
5182  case CXCursor_UnexposedStmt:
5183      return cxstring::createRef("UnexposedStmt");
5184  case CXCursor_DeclStmt:
5185      return cxstring::createRef("DeclStmt");
5186  case CXCursor_LabelStmt:
5187      return cxstring::createRef("LabelStmt");
5188  case CXCursor_CompoundStmt:
5189      return cxstring::createRef("CompoundStmt");
5190  case CXCursor_CaseStmt:
5191      return cxstring::createRef("CaseStmt");
5192  case CXCursor_DefaultStmt:
5193      return cxstring::createRef("DefaultStmt");
5194  case CXCursor_IfStmt:
5195      return cxstring::createRef("IfStmt");
5196  case CXCursor_SwitchStmt:
5197      return cxstring::createRef("SwitchStmt");
5198  case CXCursor_WhileStmt:
5199      return cxstring::createRef("WhileStmt");
5200  case CXCursor_DoStmt:
5201      return cxstring::createRef("DoStmt");
5202  case CXCursor_ForStmt:
5203      return cxstring::createRef("ForStmt");
5204  case CXCursor_GotoStmt:
5205      return cxstring::createRef("GotoStmt");
5206  case CXCursor_IndirectGotoStmt:
5207      return cxstring::createRef("IndirectGotoStmt");
5208  case CXCursor_ContinueStmt:
5209      return cxstring::createRef("ContinueStmt");
5210  case CXCursor_BreakStmt:
5211      return cxstring::createRef("BreakStmt");
5212  case CXCursor_ReturnStmt:
5213      return cxstring::createRef("ReturnStmt");
5214  case CXCursor_GCCAsmStmt:
5215      return cxstring::createRef("GCCAsmStmt");
5216  case CXCursor_MSAsmStmt:
5217      return cxstring::createRef("MSAsmStmt");
5218  case CXCursor_ObjCAtTryStmt:
5219      return cxstring::createRef("ObjCAtTryStmt");
5220  case CXCursor_ObjCAtCatchStmt:
5221      return cxstring::createRef("ObjCAtCatchStmt");
5222  case CXCursor_ObjCAtFinallyStmt:
5223      return cxstring::createRef("ObjCAtFinallyStmt");
5224  case CXCursor_ObjCAtThrowStmt:
5225      return cxstring::createRef("ObjCAtThrowStmt");
5226  case CXCursor_ObjCAtSynchronizedStmt:
5227      return cxstring::createRef("ObjCAtSynchronizedStmt");
5228  case CXCursor_ObjCAutoreleasePoolStmt:
5229      return cxstring::createRef("ObjCAutoreleasePoolStmt");
5230  case CXCursor_ObjCForCollectionStmt:
5231      return cxstring::createRef("ObjCForCollectionStmt");
5232  case CXCursor_CXXCatchStmt:
5233      return cxstring::createRef("CXXCatchStmt");
5234  case CXCursor_CXXTryStmt:
5235      return cxstring::createRef("CXXTryStmt");
5236  case CXCursor_CXXForRangeStmt:
5237      return cxstring::createRef("CXXForRangeStmt");
5238  case CXCursor_SEHTryStmt:
5239      return cxstring::createRef("SEHTryStmt");
5240  case CXCursor_SEHExceptStmt:
5241      return cxstring::createRef("SEHExceptStmt");
5242  case CXCursor_SEHFinallyStmt:
5243      return cxstring::createRef("SEHFinallyStmt");
5244  case CXCursor_SEHLeaveStmt:
5245      return cxstring::createRef("SEHLeaveStmt");
5246  case CXCursor_NullStmt:
5247      return cxstring::createRef("NullStmt");
5248  case CXCursor_InvalidFile:
5249      return cxstring::createRef("InvalidFile");
5250  case CXCursor_InvalidCode:
5251    return cxstring::createRef("InvalidCode");
5252  case CXCursor_NoDeclFound:
5253      return cxstring::createRef("NoDeclFound");
5254  case CXCursor_NotImplemented:
5255      return cxstring::createRef("NotImplemented");
5256  case CXCursor_TranslationUnit:
5257      return cxstring::createRef("TranslationUnit");
5258  case CXCursor_UnexposedAttr:
5259      return cxstring::createRef("UnexposedAttr");
5260  case CXCursor_IBActionAttr:
5261      return cxstring::createRef("attribute(ibaction)");
5262  case CXCursor_IBOutletAttr:
5263     return cxstring::createRef("attribute(iboutlet)");
5264  case CXCursor_IBOutletCollectionAttr:
5265      return cxstring::createRef("attribute(iboutletcollection)");
5266  case CXCursor_CXXFinalAttr:
5267      return cxstring::createRef("attribute(final)");
5268  case CXCursor_CXXOverrideAttr:
5269      return cxstring::createRef("attribute(override)");
5270  case CXCursor_AnnotateAttr:
5271    return cxstring::createRef("attribute(annotate)");
5272  case CXCursor_AsmLabelAttr:
5273    return cxstring::createRef("asm label");
5274  case CXCursor_PackedAttr:
5275    return cxstring::createRef("attribute(packed)");
5276  case CXCursor_PureAttr:
5277    return cxstring::createRef("attribute(pure)");
5278  case CXCursor_ConstAttr:
5279    return cxstring::createRef("attribute(const)");
5280  case CXCursor_NoDuplicateAttr:
5281    return cxstring::createRef("attribute(noduplicate)");
5282  case CXCursor_CUDAConstantAttr:
5283    return cxstring::createRef("attribute(constant)");
5284  case CXCursor_CUDADeviceAttr:
5285    return cxstring::createRef("attribute(device)");
5286  case CXCursor_CUDAGlobalAttr:
5287    return cxstring::createRef("attribute(global)");
5288  case CXCursor_CUDAHostAttr:
5289    return cxstring::createRef("attribute(host)");
5290  case CXCursor_CUDASharedAttr:
5291    return cxstring::createRef("attribute(shared)");
5292  case CXCursor_VisibilityAttr:
5293    return cxstring::createRef("attribute(visibility)");
5294  case CXCursor_DLLExport:
5295    return cxstring::createRef("attribute(dllexport)");
5296  case CXCursor_DLLImport:
5297    return cxstring::createRef("attribute(dllimport)");
5298  case CXCursor_NSReturnsRetained:
5299    return cxstring::createRef("attribute(ns_returns_retained)");
5300  case CXCursor_NSReturnsNotRetained:
5301    return cxstring::createRef("attribute(ns_returns_not_retained)");
5302  case CXCursor_NSReturnsAutoreleased:
5303    return cxstring::createRef("attribute(ns_returns_autoreleased)");
5304  case CXCursor_NSConsumesSelf:
5305    return cxstring::createRef("attribute(ns_consumes_self)");
5306  case CXCursor_NSConsumed:
5307    return cxstring::createRef("attribute(ns_consumed)");
5308  case CXCursor_ObjCException:
5309    return cxstring::createRef("attribute(objc_exception)");
5310  case CXCursor_ObjCNSObject:
5311    return cxstring::createRef("attribute(NSObject)");
5312  case CXCursor_ObjCIndependentClass:
5313    return cxstring::createRef("attribute(objc_independent_class)");
5314  case CXCursor_ObjCPreciseLifetime:
5315    return cxstring::createRef("attribute(objc_precise_lifetime)");
5316  case CXCursor_ObjCReturnsInnerPointer:
5317    return cxstring::createRef("attribute(objc_returns_inner_pointer)");
5318  case CXCursor_ObjCRequiresSuper:
5319    return cxstring::createRef("attribute(objc_requires_super)");
5320  case CXCursor_ObjCRootClass:
5321    return cxstring::createRef("attribute(objc_root_class)");
5322  case CXCursor_ObjCSubclassingRestricted:
5323    return cxstring::createRef("attribute(objc_subclassing_restricted)");
5324  case CXCursor_ObjCExplicitProtocolImpl:
5325    return cxstring::createRef("attribute(objc_protocol_requires_explicit_implementation)");
5326  case CXCursor_ObjCDesignatedInitializer:
5327    return cxstring::createRef("attribute(objc_designated_initializer)");
5328  case CXCursor_ObjCRuntimeVisible:
5329    return cxstring::createRef("attribute(objc_runtime_visible)");
5330  case CXCursor_ObjCBoxable:
5331    return cxstring::createRef("attribute(objc_boxable)");
5332  case CXCursor_FlagEnum:
5333    return cxstring::createRef("attribute(flag_enum)");
5334  case CXCursor_PreprocessingDirective:
5335    return cxstring::createRef("preprocessing directive");
5336  case CXCursor_MacroDefinition:
5337    return cxstring::createRef("macro definition");
5338  case CXCursor_MacroExpansion:
5339    return cxstring::createRef("macro expansion");
5340  case CXCursor_InclusionDirective:
5341    return cxstring::createRef("inclusion directive");
5342  case CXCursor_Namespace:
5343    return cxstring::createRef("Namespace");
5344  case CXCursor_LinkageSpec:
5345    return cxstring::createRef("LinkageSpec");
5346  case CXCursor_CXXBaseSpecifier:
5347    return cxstring::createRef("C++ base class specifier");
5348  case CXCursor_Constructor:
5349    return cxstring::createRef("CXXConstructor");
5350  case CXCursor_Destructor:
5351    return cxstring::createRef("CXXDestructor");
5352  case CXCursor_ConversionFunction:
5353    return cxstring::createRef("CXXConversion");
5354  case CXCursor_TemplateTypeParameter:
5355    return cxstring::createRef("TemplateTypeParameter");
5356  case CXCursor_NonTypeTemplateParameter:
5357    return cxstring::createRef("NonTypeTemplateParameter");
5358  case CXCursor_TemplateTemplateParameter:
5359    return cxstring::createRef("TemplateTemplateParameter");
5360  case CXCursor_FunctionTemplate:
5361    return cxstring::createRef("FunctionTemplate");
5362  case CXCursor_ClassTemplate:
5363    return cxstring::createRef("ClassTemplate");
5364  case CXCursor_ClassTemplatePartialSpecialization:
5365    return cxstring::createRef("ClassTemplatePartialSpecialization");
5366  case CXCursor_NamespaceAlias:
5367    return cxstring::createRef("NamespaceAlias");
5368  case CXCursor_UsingDirective:
5369    return cxstring::createRef("UsingDirective");
5370  case CXCursor_UsingDeclaration:
5371    return cxstring::createRef("UsingDeclaration");
5372  case CXCursor_TypeAliasDecl:
5373    return cxstring::createRef("TypeAliasDecl");
5374  case CXCursor_ObjCSynthesizeDecl:
5375    return cxstring::createRef("ObjCSynthesizeDecl");
5376  case CXCursor_ObjCDynamicDecl:
5377    return cxstring::createRef("ObjCDynamicDecl");
5378  case CXCursor_CXXAccessSpecifier:
5379    return cxstring::createRef("CXXAccessSpecifier");
5380  case CXCursor_ModuleImportDecl:
5381    return cxstring::createRef("ModuleImport");
5382  case CXCursor_OMPParallelDirective:
5383    return cxstring::createRef("OMPParallelDirective");
5384  case CXCursor_OMPSimdDirective:
5385    return cxstring::createRef("OMPSimdDirective");
5386  case CXCursor_OMPForDirective:
5387    return cxstring::createRef("OMPForDirective");
5388  case CXCursor_OMPForSimdDirective:
5389    return cxstring::createRef("OMPForSimdDirective");
5390  case CXCursor_OMPSectionsDirective:
5391    return cxstring::createRef("OMPSectionsDirective");
5392  case CXCursor_OMPSectionDirective:
5393    return cxstring::createRef("OMPSectionDirective");
5394  case CXCursor_OMPSingleDirective:
5395    return cxstring::createRef("OMPSingleDirective");
5396  case CXCursor_OMPMasterDirective:
5397    return cxstring::createRef("OMPMasterDirective");
5398  case CXCursor_OMPCriticalDirective:
5399    return cxstring::createRef("OMPCriticalDirective");
5400  case CXCursor_OMPParallelForDirective:
5401    return cxstring::createRef("OMPParallelForDirective");
5402  case CXCursor_OMPParallelForSimdDirective:
5403    return cxstring::createRef("OMPParallelForSimdDirective");
5404  case CXCursor_OMPParallelSectionsDirective:
5405    return cxstring::createRef("OMPParallelSectionsDirective");
5406  case CXCursor_OMPTaskDirective:
5407    return cxstring::createRef("OMPTaskDirective");
5408  case CXCursor_OMPTaskyieldDirective:
5409    return cxstring::createRef("OMPTaskyieldDirective");
5410  case CXCursor_OMPBarrierDirective:
5411    return cxstring::createRef("OMPBarrierDirective");
5412  case CXCursor_OMPTaskwaitDirective:
5413    return cxstring::createRef("OMPTaskwaitDirective");
5414  case CXCursor_OMPTaskgroupDirective:
5415    return cxstring::createRef("OMPTaskgroupDirective");
5416  case CXCursor_OMPFlushDirective:
5417    return cxstring::createRef("OMPFlushDirective");
5418  case CXCursor_OMPOrderedDirective:
5419    return cxstring::createRef("OMPOrderedDirective");
5420  case CXCursor_OMPAtomicDirective:
5421    return cxstring::createRef("OMPAtomicDirective");
5422  case CXCursor_OMPTargetDirective:
5423    return cxstring::createRef("OMPTargetDirective");
5424  case CXCursor_OMPTargetDataDirective:
5425    return cxstring::createRef("OMPTargetDataDirective");
5426  case CXCursor_OMPTargetEnterDataDirective:
5427    return cxstring::createRef("OMPTargetEnterDataDirective");
5428  case CXCursor_OMPTargetExitDataDirective:
5429    return cxstring::createRef("OMPTargetExitDataDirective");
5430  case CXCursor_OMPTargetParallelDirective:
5431    return cxstring::createRef("OMPTargetParallelDirective");
5432  case CXCursor_OMPTargetParallelForDirective:
5433    return cxstring::createRef("OMPTargetParallelForDirective");
5434  case CXCursor_OMPTargetUpdateDirective:
5435    return cxstring::createRef("OMPTargetUpdateDirective");
5436  case CXCursor_OMPTeamsDirective:
5437    return cxstring::createRef("OMPTeamsDirective");
5438  case CXCursor_OMPCancellationPointDirective:
5439    return cxstring::createRef("OMPCancellationPointDirective");
5440  case CXCursor_OMPCancelDirective:
5441    return cxstring::createRef("OMPCancelDirective");
5442  case CXCursor_OMPTaskLoopDirective:
5443    return cxstring::createRef("OMPTaskLoopDirective");
5444  case CXCursor_OMPTaskLoopSimdDirective:
5445    return cxstring::createRef("OMPTaskLoopSimdDirective");
5446  case CXCursor_OMPDistributeDirective:
5447    return cxstring::createRef("OMPDistributeDirective");
5448  case CXCursor_OMPDistributeParallelForDirective:
5449    return cxstring::createRef("OMPDistributeParallelForDirective");
5450  case CXCursor_OMPDistributeParallelForSimdDirective:
5451    return cxstring::createRef("OMPDistributeParallelForSimdDirective");
5452  case CXCursor_OMPDistributeSimdDirective:
5453    return cxstring::createRef("OMPDistributeSimdDirective");
5454  case CXCursor_OMPTargetParallelForSimdDirective:
5455    return cxstring::createRef("OMPTargetParallelForSimdDirective");
5456  case CXCursor_OMPTargetSimdDirective:
5457    return cxstring::createRef("OMPTargetSimdDirective");
5458  case CXCursor_OMPTeamsDistributeDirective:
5459    return cxstring::createRef("OMPTeamsDistributeDirective");
5460  case CXCursor_OMPTeamsDistributeSimdDirective:
5461    return cxstring::createRef("OMPTeamsDistributeSimdDirective");
5462  case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
5463    return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
5464  case CXCursor_OMPTeamsDistributeParallelForDirective:
5465    return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
5466  case CXCursor_OMPTargetTeamsDirective:
5467    return cxstring::createRef("OMPTargetTeamsDirective");
5468  case CXCursor_OMPTargetTeamsDistributeDirective:
5469    return cxstring::createRef("OMPTargetTeamsDistributeDirective");
5470  case CXCursor_OMPTargetTeamsDistributeParallelForDirective:
5471    return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective");
5472  case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective:
5473    return cxstring::createRef(
5474        "OMPTargetTeamsDistributeParallelForSimdDirective");
5475  case CXCursor_OMPTargetTeamsDistributeSimdDirective:
5476    return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective");
5477  case CXCursor_OverloadCandidate:
5478      return cxstring::createRef("OverloadCandidate");
5479  case CXCursor_TypeAliasTemplateDecl:
5480      return cxstring::createRef("TypeAliasTemplateDecl");
5481  case CXCursor_StaticAssert:
5482      return cxstring::createRef("StaticAssert");
5483  case CXCursor_FriendDecl:
5484      return cxstring::createRef("FriendDecl");
5485  case CXCursor_ConvergentAttr:
5486      return cxstring::createRef("attribute(convergent)");
5487  case CXCursor_WarnUnusedAttr:
5488      return cxstring::createRef("attribute(warn_unused)");
5489  case CXCursor_WarnUnusedResultAttr:
5490      return cxstring::createRef("attribute(warn_unused_result)");
5491  case CXCursor_AlignedAttr:
5492      return cxstring::createRef("attribute(aligned)");
5493  }
5494
5495  llvm_unreachable("Unhandled CXCursorKind");
5496}
5497
5498struct GetCursorData {
5499  SourceLocation TokenBeginLoc;
5500  bool PointsAtMacroArgExpansion;
5501  bool VisitedObjCPropertyImplDecl;
5502  SourceLocation VisitedDeclaratorDeclStartLoc;
5503  CXCursor &BestCursor;
5504
5505  GetCursorData(SourceManager &SM,
5506                SourceLocation tokenBeginCXCursor &outputCursor)
5507    : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
5508    PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
5509    VisitedObjCPropertyImplDecl = false;
5510  }
5511};
5512
5513static enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
5514                                                CXCursor parent,
5515                                                CXClientData client_data) {
5516  GetCursorData *Data = static_cast<GetCursorData *>(client_data);
5517  CXCursor *BestCursor = &Data->BestCursor;
5518
5519  // If we point inside a macro argument we should provide info of what the
5520  // token is so use the actual cursor, don't replace it with a macro expansion
5521  // cursor.
5522  if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
5523    return CXChildVisit_Recurse;
5524  
5525  if (clang_isDeclaration(cursor.kind)) {
5526    // Avoid having the implicit methods override the property decls.
5527    if (const ObjCMethodDecl *MD
5528          = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5529      if (MD->isImplicit())
5530        return CXChildVisit_Break;
5531
5532    } else if (const ObjCInterfaceDecl *ID
5533                 = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
5534      // Check that when we have multiple @class references in the same line,
5535      // that later ones do not override the previous ones.
5536      // If we have:
5537      // @class Foo, Bar;
5538      // source ranges for both start at '@', so 'Bar' will end up overriding
5539      // 'Foo' even though the cursor location was at 'Foo'.
5540      if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
5541          BestCursor->kind == CXCursor_ObjCClassRef)
5542        if (const ObjCInterfaceDecl *PrevID
5543             = dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(*BestCursor))){
5544         if (PrevID != ID &&
5545             !PrevID->isThisDeclarationADefinition() &&
5546             !ID->isThisDeclarationADefinition())
5547           return CXChildVisit_Break;
5548        }
5549
5550    } else if (const DeclaratorDecl *DD
5551                    = dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
5552      SourceLocation StartLoc = DD->getSourceRange().getBegin();
5553      // Check that when we have multiple declarators in the same line,
5554      // that later ones do not override the previous ones.
5555      // If we have:
5556      // int Foo, Bar;
5557      // source ranges for both start at 'int', so 'Bar' will end up overriding
5558      // 'Foo' even though the cursor location was at 'Foo'.
5559      if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
5560        return CXChildVisit_Break;
5561      Data->VisitedDeclaratorDeclStartLoc = StartLoc;
5562
5563    } else if (const ObjCPropertyImplDecl *PropImp
5564              = dyn_cast_or_null<ObjCPropertyImplDecl>(getCursorDecl(cursor))) {
5565      (void)PropImp;
5566      // Check that when we have multiple @synthesize in the same line,
5567      // that later ones do not override the previous ones.
5568      // If we have:
5569      // @synthesize Foo, Bar;
5570      // source ranges for both start at '@', so 'Bar' will end up overriding
5571      // 'Foo' even though the cursor location was at 'Foo'.
5572      if (Data->VisitedObjCPropertyImplDecl)
5573        return CXChildVisit_Break;
5574      Data->VisitedObjCPropertyImplDecl = true;
5575    }
5576  }
5577
5578  if (clang_isExpression(cursor.kind) &&
5579      clang_isDeclaration(BestCursor->kind)) {
5580    if (const Decl *D = getCursorDecl(*BestCursor)) {
5581      // Avoid having the cursor of an expression replace the declaration cursor
5582      // when the expression source range overlaps the declaration range.
5583      // This can happen for C++ constructor expressions whose range generally
5584      // include the variable declaration, e.g.:
5585      //  MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl cursor.
5586      if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
5587          D->getLocation() == Data->TokenBeginLoc)
5588        return CXChildVisit_Break;
5589    }
5590  }
5591
5592  // If our current best cursor is the construction of a temporary object, 
5593  // don't replace that cursor with a type reference, because we want 
5594  // clang_getCursor() to point at the constructor.
5595  if (clang_isExpression(BestCursor->kind) &&
5596      isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
5597      cursor.kind == CXCursor_TypeRef) {
5598    // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
5599    // as having the actual point on the type reference.
5600    *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
5601    return CXChildVisit_Recurse;
5602  }
5603
5604  // If we already have an Objective-C superclass reference, don't
5605  // update it further.
5606  if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
5607    return CXChildVisit_Break;
5608
5609  *BestCursor = cursor;
5610  return CXChildVisit_Recurse;
5611}
5612
5613CXCursor clang_getCursor(CXTranslationUnit TUCXSourceLocation Loc) {
5614  if (isNotUsableTU(TU)) {
5615    LOG_BAD_TU(TU);
5616    return clang_getNullCursor();
5617  }
5618
5619  ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
5620  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5621
5622  SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
5623  CXCursor Result = cxcursor::getCursor(TUSLoc);
5624
5625  LOG_FUNC_SECTION {
5626    CXFile SearchFile;
5627    unsigned SearchLineSearchColumn;
5628    CXFile ResultFile;
5629    unsigned ResultLineResultColumn;
5630    CXString SearchFileNameResultFileNameKindSpellingUSR;
5631    const char *IsDef = clang_isCursorDefinition(Result)? " (Definition)" : "";
5632    CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
5633
5634    clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
5635                          nullptr);
5636    clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine,
5637                          &ResultColumnnullptr);
5638    SearchFileName = clang_getFileName(SearchFile);
5639    ResultFileName = clang_getFileName(ResultFile);
5640    KindSpelling = clang_getCursorKindSpelling(Result.kind);
5641    USR = clang_getCursorUSR(Result);
5642    *Log << llvm::format("(%s:%d:%d) = %s",
5643                   clang_getCString(SearchFileName), SearchLine, SearchColumn,
5644                   clang_getCString(KindSpelling))
5645        << llvm::format("(%s:%d:%d):%s%s",
5646                     clang_getCString(ResultFileName), ResultLine, ResultColumn,
5647                     clang_getCString(USR), IsDef);
5648    clang_disposeString(SearchFileName);
5649    clang_disposeString(ResultFileName);
5650    clang_disposeString(KindSpelling);
5651    clang_disposeString(USR);
5652    
5653    CXCursor Definition = clang_getCursorDefinition(Result);
5654    if (!clang_equalCursors(Definitionclang_getNullCursor())) {
5655      CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
5656      CXString DefinitionKindSpelling
5657                                = clang_getCursorKindSpelling(Definition.kind);
5658      CXFile DefinitionFile;
5659      unsigned DefinitionLineDefinitionColumn;
5660      clang_getFileLocation(DefinitionLoc, &DefinitionFile,
5661                            &DefinitionLine, &DefinitionColumnnullptr);
5662      CXString DefinitionFileName = clang_getFileName(DefinitionFile);
5663      *Log << llvm::format("  -> %s(%s:%d:%d)",
5664                     clang_getCString(DefinitionKindSpelling),
5665                     clang_getCString(DefinitionFileName),
5666                     DefinitionLine, DefinitionColumn);
5667      clang_disposeString(DefinitionFileName);
5668      clang_disposeString(DefinitionKindSpelling);
5669    }
5670  }
5671
5672  return Result;
5673}
5674
5675CXCursor clang_getNullCursor(void) {
5676  return MakeCXCursorInvalid(CXCursor_InvalidFile);
5677}
5678
5679unsigned clang_equalCursors(CXCursor XCXCursor Y) {
5680  // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5681  // can't set consistently. For example, when visiting a DeclStmt we will set
5682  // it but we don't set it on the result of clang_getCursorDefinition for
5683  // a reference of the same declaration.
5684  // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5685  // when visiting a DeclStmt currently, the AST should be enhanced to be able
5686  // to provide that kind of info.
5687  if (clang_isDeclaration(X.kind))
5688    X.data[1] = nullptr;
5689  if (clang_isDeclaration(Y.kind))
5690    Y.data[1] = nullptr;
5691
5692  return X == Y;
5693}
5694
5695unsigned clang_hashCursor(CXCursor C) {
5696  unsigned Index = 0;
5697  if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5698    Index = 1;
5699  
5700  return llvm::DenseMapInfo<std::pair<unsignedconst void*> >::getHashValue(
5701                                        std::make_pair(C.kind, C.data[Index]));
5702}
5703
5704unsigned clang_isInvalid(enum CXCursorKind K) {
5705  return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5706}
5707
5708unsigned clang_isDeclaration(enum CXCursorKind K) {
5709  return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
5710         (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5711}
5712
5713unsigned clang_isInvalidDeclaration(CXCursor C) {
5714  if (clang_isDeclaration(C.kind)) {
5715    if (const Decl *D = getCursorDecl(C))
5716      return D->isInvalidDecl();
5717  }
5718
5719  return 0;
5720}
5721
5722unsigned clang_isReference(enum CXCursorKind K) {
5723  return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5724}
5725
5726unsigned clang_isExpression(enum CXCursorKind K) {
5727  return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5728}
5729
5730unsigned clang_isStatement(enum CXCursorKind K) {
5731  return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5732}
5733
5734unsigned clang_isAttribute(enum CXCursorKind K) {
5735    return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
5736}
5737
5738unsigned clang_isTranslationUnit(enum CXCursorKind K) {
5739  return K == CXCursor_TranslationUnit;
5740}
5741
5742unsigned clang_isPreprocessing(enum CXCursorKind K) {
5743  return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
5744}
5745  
5746unsigned clang_isUnexposed(enum CXCursorKind K) {
5747  switch (K) {
5748    case CXCursor_UnexposedDecl:
5749    case CXCursor_UnexposedExpr:
5750    case CXCursor_UnexposedStmt:
5751    case CXCursor_UnexposedAttr:
5752      return true;
5753    default:
5754      return false;
5755  }
5756}
5757
5758CXCursorKind clang_getCursorKind(CXCursor C) {
5759  return C.kind;
5760}
5761
5762CXSourceLocation clang_getCursorLocation(CXCursor C) {
5763  if (clang_isReference(C.kind)) {
5764    switch (C.kind) {
5765    case CXCursor_ObjCSuperClassRef: {
5766      std::pair<const ObjCInterfaceDecl *, SourceLocationP
5767        = getCursorObjCSuperClassRef(C);
5768      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5769    }
5770
5771    case CXCursor_ObjCProtocolRef: {
5772      std::pair<const ObjCProtocolDecl *, SourceLocationP
5773        = getCursorObjCProtocolRef(C);
5774      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5775    }
5776
5777    case CXCursor_ObjCClassRef: {
5778      std::pair<const ObjCInterfaceDecl *, SourceLocationP
5779        = getCursorObjCClassRef(C);
5780      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5781    }
5782
5783    case CXCursor_TypeRef: {
5784      std::pair<const TypeDecl *, SourceLocationP = getCursorTypeRef(C);
5785      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5786    }
5787
5788    case CXCursor_TemplateRef: {
5789      std::pair<const TemplateDecl *, SourceLocationP =
5790          getCursorTemplateRef(C);
5791      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5792    }
5793
5794    case CXCursor_NamespaceRef: {
5795      std::pair<const NamedDecl *, SourceLocationP = getCursorNamespaceRef(C);
5796      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5797    }
5798
5799    case CXCursor_MemberRef: {
5800      std::pair<const FieldDecl *, SourceLocationP = getCursorMemberRef(C);
5801      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5802    }
5803
5804    case CXCursor_VariableRef: {
5805      std::pair<const VarDecl *, SourceLocationP = getCursorVariableRef(C);
5806      return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
5807    }
5808
5809    case CXCursor_CXXBaseSpecifier: {
5810      const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
5811      if (!BaseSpec)
5812        return clang_getNullLocation();
5813      
5814      if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
5815        return cxloc::translateSourceLocation(getCursorContext(C),
5816                                            TSInfo->getTypeLoc().getBeginLoc());
5817
5818      return cxloc::translateSourceLocation(getCursorContext(C),
5819                                            BaseSpec->getBeginLoc());
5820    }
5821
5822    case CXCursor_LabelRef: {
5823      std::pair<const LabelStmt *, SourceLocationP = getCursorLabelRef(C);
5824      return cxloc::translateSourceLocation(getCursorContext(C)P.second);
5825    }
5826
5827    case CXCursor_OverloadedDeclRef:
5828      return cxloc::translateSourceLocation(getCursorContext(C),
5829                                          getCursorOverloadedDeclRef(C).second);
5830
5831    default:
5832      // FIXME: Need a way to enumerate all non-reference cases.
5833      llvm_unreachable("Missed a reference kind");
5834    }
5835  }
5836
5837  if (clang_isExpression(C.kind))
5838    return cxloc::translateSourceLocation(getCursorContext(C),
5839                                   getLocationFromExpr(getCursorExpr(C)));
5840
5841  if (clang_isStatement(C.kind))
5842    return cxloc::translateSourceLocation(getCursorContext(C),
5843                                          getCursorStmt(C)->getBeginLoc());
5844
5845  if (C.kind == CXCursor_PreprocessingDirective) {
5846    SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
5847    return cxloc::translateSourceLocation(getCursorContext(C)L);
5848  }
5849
5850  if (C.kind == CXCursor_MacroExpansion) {
5851    SourceLocation L
5852      = cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
5853    return cxloc::translateSourceLocation(getCursorContext(C)L);
5854  }
5855
5856  if (C.kind == CXCursor_MacroDefinition) {
5857    SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
5858    return cxloc::translateSourceLocation(getCursorContext(C)L);
5859  }
5860
5861  if (C.kind == CXCursor_InclusionDirective) {
5862    SourceLocation L
5863      = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
5864    return cxloc::translateSourceLocation(getCursorContext(C)L);
5865  }
5866
5867  if (clang_isAttribute(C.kind)) {
5868    SourceLocation L
5869      = cxcursor::getCursorAttr(C)->getLocation();
5870    return cxloc::translateSourceLocation(getCursorContext(C)L);
5871  }
5872
5873  if (!clang_isDeclaration(C.kind))
5874    return clang_getNullLocation();
5875
5876  const Decl *D = getCursorDecl(C);
5877  if (!D)
5878    return clang_getNullLocation();
5879
5880  SourceLocation Loc = D->getLocation();
5881  // FIXME: Multiple variables declared in a single declaration
5882  // currently lack the information needed to correctly determine their
5883  // ranges when accounting for the type-specifier.  We use context
5884  // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
5885  // and if so, whether it is the first decl.
5886  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
5887    if (!cxcursor::isFirstInDeclGroup(C))
5888      Loc = VD->getLocation();
5889  }
5890
5891  // For ObjC methods, give the start location of the method name.
5892  if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
5893    Loc = MD->getSelectorStartLoc();
5894
5895  return cxloc::translateSourceLocation(getCursorContext(C)Loc);
5896}
5897
5898// end extern "C"
5899
5900CXCursor cxcursor::getCursor(CXTranslationUnit TUSourceLocation SLoc) {
5901  assert(TU);
5902
5903  // Guard against an invalid SourceLocation, or we may assert in one
5904  // of the following calls.
5905  if (SLoc.isInvalid())
5906    return clang_getNullCursor();
5907
5908  ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
5909
5910  // Translate the given source location to make it point at the beginning of
5911  // the token under the cursor.
5912  SLoc = Lexer::GetBeginningOfToken(SLocCXXUnit->getSourceManager(),
5913                                    CXXUnit->getASTContext().getLangOpts());
5914  
5915  CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
5916  if (SLoc.isValid()) {
5917    GetCursorData ResultData(CXXUnit->getSourceManager(), SLocResult);
5918    CursorVisitor CursorVis(TUGetCursorVisitor, &ResultData,
5919                            /*VisitPreprocessorLast=*/true
5920                            /*VisitIncludedEntities=*/false,
5921                            SourceLocation(SLoc));
5922    CursorVis.visitFileRegion();
5923  }
5924
5925  return Result;
5926}
5927
5928static SourceRange getRawCursorExtent(CXCursor C) {
5929  if (clang_isReference(C.kind)) {
5930    switch (C.kind) {
5931    case CXCursor_ObjCSuperClassRef:
5932      return  getCursorObjCSuperClassRef(C).second;
5933
5934    case CXCursor_ObjCProtocolRef:
5935      return getCursorObjCProtocolRef(C).second;
5936
5937    case CXCursor_ObjCClassRef:
5938      return getCursorObjCClassRef(C).second;
5939
5940    case CXCursor_TypeRef:
5941      return getCursorTypeRef(C).second;
5942
5943    case CXCursor_TemplateRef:
5944      return getCursorTemplateRef(C).second;
5945
5946    case CXCursor_NamespaceRef:
5947      return getCursorNamespaceRef(C).second;
5948
5949    case CXCursor_MemberRef:
5950      return getCursorMemberRef(C).second;
5951
5952    case CXCursor_CXXBaseSpecifier:
5953      return getCursorCXXBaseSpecifier(C)->getSourceRange();
5954
5955    case CXCursor_LabelRef:
5956      return getCursorLabelRef(C).second;
5957
5958    case CXCursor_OverloadedDeclRef:
5959      return getCursorOverloadedDeclRef(C).second;
5960
5961    case CXCursor_VariableRef:
5962      return getCursorVariableRef(C).second;
5963        
5964    default:
5965      // FIXME: Need a way to enumerate all non-reference cases.
5966      llvm_unreachable("Missed a reference kind");
5967    }
5968  }
5969
5970  if (clang_isExpression(C.kind))
5971    return getCursorExpr(C)->getSourceRange();
5972
5973  if (clang_isStatement(C.kind))
5974    return getCursorStmt(C)->getSourceRange();
5975
5976  if (clang_isAttribute(C.kind))
5977    return getCursorAttr(C)->getRange();
5978
5979  if (C.kind == CXCursor_PreprocessingDirective)
5980    return cxcursor::getCursorPreprocessingDirective(C);
5981
5982  if (C.kind == CXCursor_MacroExpansion) {
5983    ASTUnit *TU = getCursorASTUnit(C);
5984    SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
5985    return TU->mapRangeFromPreamble(Range);
5986  }
5987
5988  if (C.kind == CXCursor_MacroDefinition) {
5989    ASTUnit *TU = getCursorASTUnit(C);
5990    SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
5991    return TU->mapRangeFromPreamble(Range);
5992  }
5993
5994  if (C.kind == CXCursor_InclusionDirective) {
5995    ASTUnit *TU = getCursorASTUnit(C);
5996    SourceRange Range = cxcursor::getCursorInclusionDirective(C)->getSourceRange();
5997    return TU->mapRangeFromPreamble(Range);
5998  }
5999
6000  if (C.kind == CXCursor_TranslationUnit) {
6001    ASTUnit *TU = getCursorASTUnit(C);
6002    FileID MainID = TU->getSourceManager().getMainFileID();
6003    SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
6004    SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
6005    return SourceRange(StartEnd);
6006  }
6007
6008  if (clang_isDeclaration(C.kind)) {
6009    const Decl *D = cxcursor::getCursorDecl(C);
6010    if (!D)
6011      return SourceRange();
6012
6013    SourceRange R = D->getSourceRange();
6014    // FIXME: Multiple variables declared in a single declaration
6015    // currently lack the information needed to correctly determine their
6016    // ranges when accounting for the type-specifier.  We use context
6017    // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6018    // and if so, whether it is the first decl.
6019    if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6020      if (!cxcursor::isFirstInDeclGroup(C))
6021        R.setBegin(VD->getLocation());
6022    }
6023    return R;
6024  }
6025  return SourceRange();
6026}
6027
6028/// Retrieves the "raw" cursor extent, which is then extended to include
6029/// the decl-specifier-seq for declarations.
6030static SourceRange getFullCursorExtent(CXCursor CSourceManager &SrcMgr) {
6031  if (clang_isDeclaration(C.kind)) {
6032    const Decl *D = cxcursor::getCursorDecl(C);
6033    if (!D)
6034      return SourceRange();
6035
6036    SourceRange R = D->getSourceRange();
6037
6038    // Adjust the start of the location for declarations preceded by
6039    // declaration specifiers.
6040    SourceLocation StartLoc;
6041    if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6042      if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
6043        StartLoc = TI->getTypeLoc().getBeginLoc();
6044    } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
6045      if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
6046        StartLoc = TI->getTypeLoc().getBeginLoc();
6047    }
6048
6049    if (StartLoc.isValid() && R.getBegin().isValid() &&
6050        SrcMgr.isBeforeInTranslationUnit(StartLocR.getBegin()))
6051      R.setBegin(StartLoc);
6052
6053    // FIXME: Multiple variables declared in a single declaration
6054    // currently lack the information needed to correctly determine their
6055    // ranges when accounting for the type-specifier.  We use context
6056    // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
6057    // and if so, whether it is the first decl.
6058    if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6059      if (!cxcursor::isFirstInDeclGroup(C))
6060        R.setBegin(VD->getLocation());
6061    }
6062
6063    return R;    
6064  }
6065  
6066  return getRawCursorExtent(C);
6067}
6068
6069CXSourceRange clang_getCursorExtent(CXCursor C) {
6070  SourceRange R = getRawCursorExtent(C);
6071  if (R.isInvalid())
6072    return clang_getNullRange();
6073
6074  return cxloc::translateSourceRange(getCursorContext(C)R);
6075}
6076
6077CXCursor clang_getCursorReferenced(CXCursor C) {
6078  if (clang_isInvalid(C.kind))
6079    return clang_getNullCursor();
6080
6081  CXTranslationUnit tu = getCursorTU(C);
6082  if (clang_isDeclaration(C.kind)) {
6083    const Decl *D = getCursorDecl(C);
6084    if (!D)
6085      return clang_getNullCursor();
6086    if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
6087      return MakeCursorOverloadedDeclRef(UsingD->getLocation(), tu);
6088    if (const ObjCPropertyImplDecl *PropImpl =
6089            dyn_cast<ObjCPropertyImplDecl>(D))
6090      if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
6091        return MakeCXCursor(Propertytu);
6092    
6093    return C;
6094  }
6095  
6096  if (clang_isExpression(C.kind)) {
6097    const Expr *E = getCursorExpr(C);
6098    const Decl *D = getDeclFromExpr(E);
6099    if (D) {
6100      CXCursor declCursor = MakeCXCursor(Dtu);
6101      declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
6102                                               declCursor);
6103      return declCursor;
6104    }
6105    
6106    if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
6107      return MakeCursorOverloadedDeclRef(Ovltu);
6108        
6109    return clang_getNullCursor();
6110  }
6111
6112  if (clang_isStatement(C.kind)) {
6113    const Stmt *S = getCursorStmt(C);
6114    if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
6115      if (LabelDecl *label = Goto->getLabel())
6116        if (LabelStmt *labelS = label->getStmt())
6117        return MakeCXCursor(labelSgetCursorDecl(C), tu);
6118
6119    return clang_getNullCursor();
6120  }
6121
6122  if (C.kind == CXCursor_MacroExpansion) {
6123    if (const MacroDefinitionRecord *Def =
6124            getCursorMacroExpansion(C).getDefinition())
6125      return MakeMacroDefinitionCursor(Deftu);
6126  }
6127
6128  if (!clang_isReference(C.kind))
6129    return clang_getNullCursor();
6130
6131  switch (C.kind) {
6132    case CXCursor_ObjCSuperClassRef:
6133      return MakeCXCursor(getCursorObjCSuperClassRef(C).firsttu);
6134
6135    case CXCursor_ObjCProtocolRef: {
6136      const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
6137      if (const ObjCProtocolDecl *Def = Prot->getDefinition())
6138        return MakeCXCursor(Deftu);
6139
6140      return MakeCXCursor(Prottu);
6141    }
6142
6143    case CXCursor_ObjCClassRef: {
6144      const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
6145      if (const ObjCInterfaceDecl *Def = Class->getDefinition())
6146        return MakeCXCursor(Deftu);
6147
6148      return MakeCXCursor(Classtu);
6149    }
6150
6151    case CXCursor_TypeRef:
6152      return MakeCXCursor(getCursorTypeRef(C).firsttu );
6153
6154    case CXCursor_TemplateRef:
6155      return MakeCXCursor(getCursorTemplateRef(C).firsttu );
6156
6157    case CXCursor_NamespaceRef:
6158      return MakeCXCursor(getCursorNamespaceRef(C).firsttu );
6159
6160    case CXCursor_MemberRef:
6161      return MakeCXCursor(getCursorMemberRef(C).firsttu );
6162
6163    case CXCursor_CXXBaseSpecifier: {
6164      const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
6165      return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
6166                                                         tu ));
6167    }
6168
6169    case CXCursor_LabelRef:
6170      // FIXME: We end up faking the "parent" declaration here because we
6171      // don't want to make CXCursor larger.
6172      return MakeCXCursor(getCursorLabelRef(C).first,
6173                          cxtu::getASTUnit(tu)->getASTContext()
6174                              .getTranslationUnitDecl(),
6175                          tu);
6176
6177    case CXCursor_OverloadedDeclRef:
6178      return C;
6179      
6180    case CXCursor_VariableRef:
6181      return MakeCXCursor(getCursorVariableRef(C).firsttu);
6182
6183    default:
6184      // We would prefer to enumerate all non-reference cursor kinds here.
6185      llvm_unreachable("Unhandled reference cursor kind");
6186  }
6187}
6188
6189CXCursor clang_getCursorDefinition(CXCursor C) {
6190  if (clang_isInvalid(C.kind))
6191    return clang_getNullCursor();
6192
6193  CXTranslationUnit TU = getCursorTU(C);
6194
6195  bool WasReference = false;
6196  if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
6197    C = clang_getCursorReferenced(C);
6198    WasReference = true;
6199  }
6200
6201  if (C.kind == CXCursor_MacroExpansion)
6202    return clang_getCursorReferenced(C);
6203
6204  if (!clang_isDeclaration(C.kind))
6205    return clang_getNullCursor();
6206
6207  const Decl *D = getCursorDecl(C);
6208  if (!D)
6209    return clang_getNullCursor();
6210
6211  switch (D->getKind()) {
6212  // Declaration kinds that don't really separate the notions of
6213  // declaration and definition.
6214  case Decl::Namespace:
6215  case Decl::Typedef:
6216  case Decl::TypeAlias:
6217  case Decl::TypeAliasTemplate:
6218  case Decl::TemplateTypeParm:
6219  case Decl::EnumConstant:
6220  case Decl::Field:
6221  case Decl::Binding:
6222  case Decl::MSProperty:
6223  case Decl::IndirectField:
6224  case Decl::ObjCIvar:
6225  case Decl::ObjCAtDefsField:
6226  case Decl::ImplicitParam:
6227  case Decl::ParmVar:
6228  case Decl::NonTypeTemplateParm:
6229  case Decl::TemplateTemplateParm:
6230  case Decl::ObjCCategoryImpl:
6231  case Decl::ObjCImplementation:
6232  case Decl::AccessSpec:
6233  case Decl::LinkageSpec:
6234  case Decl::Export:
6235  case Decl::ObjCPropertyImpl:
6236  case Decl::FileScopeAsm:
6237  case Decl::StaticAssert:
6238  case Decl::Block:
6239  case Decl::Captured:
6240  case Decl::OMPCapturedExpr:
6241  case Decl::Label:  // FIXME: Is this right??
6242  case Decl::ClassScopeFunctionSpecialization:
6243  case Decl::CXXDeductionGuide:
6244  case Decl::Import:
6245  case Decl::OMPThreadPrivate:
6246  case Decl::OMPAllocate:
6247  case Decl::OMPDeclareReduction:
6248  case Decl::OMPDeclareMapper:
6249  case Decl::OMPRequires:
6250  case Decl::ObjCTypeParam:
6251  case Decl::BuiltinTemplate:
6252  case Decl::PragmaComment:
6253  case Decl::PragmaDetectMismatch:
6254  case Decl::UsingPack:
6255    return C;
6256
6257  // Declaration kinds that don't make any sense here, but are
6258  // nonetheless harmless.
6259  case Decl::Empty:
6260  case Decl::TranslationUnit:
6261  case Decl::ExternCContext:
6262    break;
6263
6264  // Declaration kinds for which the definition is not resolvable.
6265  case Decl::UnresolvedUsingTypename:
6266  case Decl::UnresolvedUsingValue:
6267    break;
6268
6269  case Decl::UsingDirective:
6270    return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
6271                        TU);
6272
6273  case Decl::NamespaceAlias:
6274    return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
6275
6276  case Decl::Enum:
6277  case Decl::Record:
6278  case Decl::CXXRecord:
6279  case Decl::ClassTemplateSpecialization:
6280  case Decl::ClassTemplatePartialSpecialization:
6281    if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
6282      return MakeCXCursor(DefTU);
6283    return clang_getNullCursor();
6284
6285  case Decl::Function:
6286  case Decl::CXXMethod:
6287  case Decl::CXXConstructor:
6288  case Decl::CXXDestructor:
6289  case Decl::CXXConversion: {
6290    const FunctionDecl *Def = nullptr;
6291    if (cast<FunctionDecl>(D)->getBody(Def))
6292      return MakeCXCursor(DefTU);
6293    return clang_getNullCursor();
6294  }
6295
6296  case Decl::Var:
6297  case Decl::VarTemplateSpecialization:
6298  case Decl::VarTemplatePartialSpecialization:
6299  case Decl::Decomposition: {
6300    // Ask the variable if it has a definition.
6301    if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
6302      return MakeCXCursor(DefTU);
6303    return clang_getNullCursor();
6304  }
6305
6306  case Decl::FunctionTemplate: {
6307    const FunctionDecl *Def = nullptr;
6308    if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
6309      return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
6310    return clang_getNullCursor();
6311  }
6312
6313  case Decl::ClassTemplate: {
6314    if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
6315                                                            ->getDefinition())
6316      return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
6317                          TU);
6318    return clang_getNullCursor();
6319  }
6320
6321  case Decl::VarTemplate: {
6322    if (VarDecl *Def =
6323            cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
6324      return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
6325    return clang_getNullCursor();
6326  }
6327
6328  case Decl::Using:
6329    return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D), 
6330                                       D->getLocation(), TU);
6331
6332  case Decl::UsingShadow:
6333  case Decl::ConstructorUsingShadow:
6334    return clang_getCursorDefinition(
6335                       MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
6336                                    TU));
6337
6338  case Decl::ObjCMethod: {
6339    const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
6340    if (Method->isThisDeclarationADefinition())
6341      return C;
6342
6343    // Dig out the method definition in the associated
6344    // @implementation, if we have it.
6345    // FIXME: The ASTs should make finding the definition easier.
6346    if (const ObjCInterfaceDecl *Class
6347                       = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
6348      if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
6349        if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
6350                                                  Method->isInstanceMethod()))
6351          if (Def->isThisDeclarationADefinition())
6352            return MakeCXCursor(DefTU);
6353
6354    return clang_getNullCursor();
6355  }
6356
6357  case Decl::ObjCCategory:
6358    if (ObjCCategoryImplDecl *Impl
6359                               = cast<ObjCCategoryDecl>(D)->getImplementation())
6360      return MakeCXCursor(ImplTU);
6361    return clang_getNullCursor();
6362
6363  case Decl::ObjCProtocol:
6364    if (const ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(D)->getDefinition())
6365      return MakeCXCursor(DefTU);
6366    return clang_getNullCursor();
6367
6368  case Decl::ObjCInterface: {
6369    // There are two notions of a "definition" for an Objective-C
6370    // class: the interface and its implementation. When we resolved a
6371    // reference to an Objective-C class, produce the @interface as
6372    // the definition; when we were provided with the interface,
6373    // produce the @implementation as the definition.
6374    const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
6375    if (WasReference) {
6376      if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
6377        return MakeCXCursor(DefTU);
6378    } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
6379      return MakeCXCursor(ImplTU);
6380    return clang_getNullCursor();
6381  }
6382
6383  case Decl::ObjCProperty:
6384    // FIXME: We don't really know where to find the
6385    // ObjCPropertyImplDecls that implement this property.
6386    return clang_getNullCursor();
6387
6388  case Decl::ObjCCompatibleAlias:
6389    if (const ObjCInterfaceDecl *Class
6390          = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
6391      if (const ObjCInterfaceDecl *Def = Class->getDefinition())
6392        return MakeCXCursor(DefTU);
6393
6394    return clang_getNullCursor();
6395
6396  case Decl::Friend:
6397    if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
6398      return clang_getCursorDefinition(MakeCXCursor(FriendTU));
6399    return clang_getNullCursor();
6400
6401  case Decl::FriendTemplate:
6402    if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
6403      return clang_getCursorDefinition(MakeCXCursor(FriendTU));
6404    return clang_getNullCursor();
6405  }
6406
6407  return clang_getNullCursor();
6408}
6409
6410unsigned clang_isCursorDefinition(CXCursor C) {
6411  if (!clang_isDeclaration(C.kind))
6412    return 0;
6413
6414  return clang_getCursorDefinition(C) == C;
6415}
6416
6417CXCursor clang_getCanonicalCursor(CXCursor C) {
6418  if (!clang_isDeclaration(C.kind))
6419    return C;
6420  
6421  if (const Decl *D = getCursorDecl(C)) {
6422    if (const ObjCCategoryImplDecl *CatImplD = dyn_cast<ObjCCategoryImplDecl>(D))
6423      if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
6424        return MakeCXCursor(CatDgetCursorTU(C));
6425
6426    if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6427      if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
6428        return MakeCXCursor(IFDgetCursorTU(C));
6429
6430    return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
6431  }
6432  
6433  return C;
6434}
6435
6436int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
6437  return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
6438}
6439  
6440unsigned clang_getNumOverloadedDecls(CXCursor C) {
6441  if (C.kind != CXCursor_OverloadedDeclRef)
6442    return 0;
6443  
6444  OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
6445  if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
6446    return E->getNumDecls();
6447  
6448  if (OverloadedTemplateStorage *S
6449                              = Storage.dyn_cast<OverloadedTemplateStorage*>())
6450    return S->size();
6451  
6452  const Decl *D = Storage.get<const Decl *>();
6453  if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
6454    return Using->shadow_size();
6455  
6456  return 0;
6457}
6458
6459CXCursor clang_getOverloadedDecl(CXCursor cursorunsigned index) {
6460  if (cursor.kind != CXCursor_OverloadedDeclRef)
6461    return clang_getNullCursor();
6462
6463  if (index >= clang_getNumOverloadedDecls(cursor))
6464    return clang_getNullCursor();
6465  
6466  CXTranslationUnit TU = getCursorTU(cursor);
6467  OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
6468  if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
6469    return MakeCXCursor(E->decls_begin()[index], TU);
6470  
6471  if (OverloadedTemplateStorage *S
6472                              = Storage.dyn_cast<OverloadedTemplateStorage*>())
6473    return MakeCXCursor(S->begin()[index], TU);
6474  
6475  const Decl *D = Storage.get<const Decl *>();
6476  if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
6477    // FIXME: This is, unfortunately, linear time.
6478    UsingDecl::shadow_iterator Pos = Using->shadow_begin();
6479    std::advance(Posindex);
6480    return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
6481  }
6482  
6483  return clang_getNullCursor();
6484}
6485  
6486void clang_getDefinitionSpellingAndExtent(CXCursor C,
6487                                          const char **startBuf,
6488                                          const char **endBuf,
6489                                          unsigned *startLine,
6490                                          unsigned *startColumn,
6491                                          unsigned *endLine,
6492                                          unsigned *endColumn) {
6493   (0) . __assert_fail ("getCursorDecl(C) && \"CXCursor has null decl\"", "/home/seafit/code_projects/clang_source/clang/tools/libclang/CIndex.cpp", 6493, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(getCursorDecl(C) && "CXCursor has null decl");
6494  const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
6495  CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
6496
6497  SourceManager &SM = FD->getASTContext().getSourceManager();
6498  *startBuf = SM.getCharacterData(Body->getLBracLoc());
6499  *endBuf = SM.getCharacterData(Body->getRBracLoc());
6500  *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
6501  *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
6502  *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
6503  *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
6504}
6505
6506
6507CXSourceRange clang_getCursorReferenceNameRange(CXCursor Cunsigned NameFlags,
6508                                                unsigned PieceIndex) {
6509  RefNamePieces Pieces;
6510  
6511  switch (C.kind) {
6512  case CXCursor_MemberRefExpr:
6513    if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
6514      Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
6515                           E->getQualifierLoc().getSourceRange());
6516    break;
6517  
6518  case CXCursor_DeclRefExpr:
6519    if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
6520      SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
6521      Pieces =
6522          buildPieces(NameFlags, false, E->getNameInfo(),
6523                      E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
6524    }
6525    break;
6526    
6527  case CXCursor_CallExpr:
6528    if (const CXXOperatorCallExpr *OCE = 
6529        dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
6530      const Expr *Callee = OCE->getCallee();
6531      if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
6532        Callee = ICE->getSubExpr();
6533
6534      if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
6535        Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
6536                             DRE->getQualifierLoc().getSourceRange());
6537    }
6538    break;
6539    
6540  default:
6541    break;
6542  }
6543
6544  if (Pieces.empty()) {
6545    if (PieceIndex == 0)
6546      return clang_getCursorExtent(C);
6547  } else if (PieceIndex < Pieces.size()) {
6548      SourceRange R = Pieces[PieceIndex];
6549      if (R.isValid())
6550        return cxloc::translateSourceRange(getCursorContext(C)R);
6551  }
6552  
6553  return clang_getNullRange();
6554}
6555
6556void clang_enableStackTraces(void) {
6557  // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
6558  llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
6559}
6560
6561void clang_executeOnThread(void (*fn)(void*), void *user_data,
6562                           unsigned stack_size) {
6563  llvm::llvm_execute_on_thread(fn, user_data, stack_size);
6564}
6565
6566//===----------------------------------------------------------------------===//
6567// Token-based Operations.
6568//===----------------------------------------------------------------------===//
6569
6570/* CXToken layout:
6571 *   int_data[0]: a CXTokenKind
6572 *   int_data[1]: starting token location
6573 *   int_data[2]: token length
6574 *   int_data[3]: reserved
6575 *   ptr_data: for identifiers and keywords, an IdentifierInfo*.
6576 *   otherwise unused.
6577 */
6578CXTokenKind clang_getTokenKind(CXToken CXTok) {
6579  return static_cast<CXTokenKind>(CXTok.int_data[0]);
6580}
6581
6582CXString clang_getTokenSpelling(CXTranslationUnit TUCXToken CXTok) {
6583  switch (clang_getTokenKind(CXTok)) {
6584  case CXToken_Identifier:
6585  case CXToken_Keyword:
6586    // We know we have an IdentifierInfo*, so use that.
6587    return cxstring::createRef(static_cast<IdentifierInfo *>(CXTok.ptr_data)
6588                            ->getNameStart());
6589
6590  case CXToken_Literal: {
6591    // We have stashed the starting pointer in the ptr_data field. Use it.
6592    const char *Text = static_cast<const char *>(CXTok.ptr_data);
6593    return cxstring::createDup(StringRef(TextCXTok.int_data[2]));
6594  }
6595
6596  case CXToken_Punctuation:
6597  case CXToken_Comment:
6598    break;
6599  }
6600
6601  if (isNotUsableTU(TU)) {
6602    LOG_BAD_TU(TU);
6603    return cxstring::createEmpty();
6604  }
6605
6606  // We have to find the starting buffer pointer the hard way, by
6607  // deconstructing the source location.
6608  ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6609  if (!CXXUnit)
6610    return cxstring::createEmpty();
6611
6612  SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
6613  std::pair<FileIDunsignedLocInfo
6614    = CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
6615  bool Invalid = false;
6616  StringRef Buffer
6617    = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
6618  if (Invalid)
6619    return cxstring::createEmpty();
6620
6621  return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
6622}
6623
6624CXSourceLocation clang_getTokenLocation(CXTranslationUnit TUCXToken CXTok) {
6625  if (isNotUsableTU(TU)) {
6626    LOG_BAD_TU(TU);
6627    return clang_getNullLocation();
6628  }
6629
6630  ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6631  if (!CXXUnit)
6632    return clang_getNullLocation();
6633
6634  return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
6635                        SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6636}
6637
6638CXSourceRange clang_getTokenExtent(CXTranslationUnit TUCXToken CXTok) {
6639  if (isNotUsableTU(TU)) {
6640    LOG_BAD_TU(TU);
6641    return clang_getNullRange();
6642  }
6643
6644  ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6645  if (!CXXUnit)
6646    return clang_getNullRange();
6647
6648  return cxloc::translateSourceRange(CXXUnit->getASTContext(),
6649                        SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
6650}
6651
6652static void getTokens(ASTUnit *CXXUnitSourceRange Range,
6653                      SmallVectorImpl<CXToken> &CXTokens) {
6654  SourceManager &SourceMgr = CXXUnit->getSourceManager();
6655  std::pair<FileIDunsignedBeginLocInfo
6656    = SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
6657  std::pair<FileIDunsignedEndLocInfo
6658    = SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
6659
6660  // Cannot tokenize across files.
6661  if (BeginLocInfo.first != EndLocInfo.first)
6662    return;
6663
6664  // Create a lexer
6665  bool Invalid = false;
6666  StringRef Buffer
6667    = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
6668  if (Invalid)
6669    return;
6670  
6671  Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
6672            CXXUnit->getASTContext().getLangOpts(),
6673            Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
6674  Lex.SetCommentRetentionState(true);
6675
6676  // Lex tokens until we hit the end of the range.
6677  const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
6678  Token Tok;
6679  bool previousWasAt = false;
6680  do {
6681    // Lex the next token
6682    Lex.LexFromRawLexer(Tok);
6683    if (Tok.is(tok::eof))
6684      break;
6685
6686    // Initialize the CXToken.
6687    CXToken CXTok;
6688
6689    //   - Common fields
6690    CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
6691    CXTok.int_data[2] = Tok.getLength();
6692    CXTok.int_data[3] = 0;
6693
6694    //   - Kind-specific fields
6695    if (Tok.isLiteral()) {
6696      CXTok.int_data[0] = CXToken_Literal;
6697      CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
6698    } else if (Tok.is(tok::raw_identifier)) {
6699      // Lookup the identifier to determine whether we have a keyword.
6700      IdentifierInfo *II
6701        = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
6702
6703      if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
6704        CXTok.int_data[0] = CXToken_Keyword;
6705      }
6706      else {
6707        CXTok.int_data[0] = Tok.is(tok::identifier)
6708          ? CXToken_Identifier
6709          : CXToken_Keyword;
6710      }
6711      CXTok.ptr_data = II;
6712    } else if (Tok.is(tok::comment)) {
6713      CXTok.int_data[0] = CXToken_Comment;
6714      CXTok.ptr_data = nullptr;
6715    } else {
6716      CXTok.int_data[0] = CXToken_Punctuation;
6717      CXTok.ptr_data = nullptr;
6718    }
6719    CXTokens.push_back(CXTok);
6720    previousWasAt = Tok.is(tok::at);
6721  } while (Lex.getBufferLocation() < EffectiveBufferEnd);
6722}
6723
6724CXToken *clang_getToken(CXTranslationUnit TUCXSourceLocation Location) {
6725  LOG_FUNC_SECTION {
6726    *Log << TU << ' ' << Location;
6727  }
6728
6729  if (isNotUsableTU(TU)) {
6730    LOG_BAD_TU(TU);
6731    return NULL;
6732  }
6733
6734  ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6735  if (!CXXUnit)
6736    return NULL;
6737
6738  SourceLocation Begin = cxloc::translateSourceLocation(Location);
6739  if (Begin.isInvalid())
6740    return NULL;
6741  SourceManager &SM = CXXUnit->getSourceManager();
6742  std::pair<FileIDunsignedDecomposedEnd = SM.getDecomposedLoc(Begin);
6743  DecomposedEnd.second += Lexer::MeasureTokenLength(BeginSMCXXUnit->getLangOpts());
6744
6745  SourceLocation End = SM.getComposedLoc(DecomposedEnd.firstDecomposedEnd.second);
6746
6747  SmallVector<CXToken32CXTokens;
6748  getTokens(CXXUnit, SourceRange(Begin, End), CXTokens);
6749
6750  if (CXTokens.empty())
6751    return NULL;
6752
6753  CXTokens.resize(1);
6754  CXToken *Token = static_cast<CXToken *>(llvm::safe_malloc(sizeof(CXToken)));
6755
6756  memmove(Token, CXTokens.data(), sizeof(CXToken));
6757  return Token;
6758}
6759
6760void clang_tokenize(CXTranslationUnit TUCXSourceRange Range,
6761                    CXToken **Tokensunsigned *NumTokens) {
6762  LOG_FUNC_SECTION {
6763    *Log << TU << ' ' << Range;
6764  }
6765
6766  if (Tokens)
6767    *Tokens = nullptr;
6768  if (NumTokens)
6769    *NumTokens = 0;
6770
6771  if (isNotUsableTU(TU)) {
6772    LOG_BAD_TU(TU);
6773    return;
6774  }
6775
6776  ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
6777  if (!CXXUnit || !Tokens || !NumTokens)
6778    return;
6779
6780  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
6781  
6782  SourceRange R = cxloc::translateCXSourceRange(Range);
6783  if (R.isInvalid())
6784    return;
6785
6786  SmallVector<CXToken32CXTokens;
6787  getTokens(CXXUnit, R, CXTokens);
6788
6789  if (CXTokens.empty())
6790    return;
6791
6792  *Tokens = static_cast<CXToken *>(
6793      llvm::safe_malloc(sizeof(CXToken) * CXTokens.size()));
6794  memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
6795  *NumTokens = CXTokens.size();
6796}
6797
6798void clang_disposeTokens(CXTranslationUnit TU,
6799                         CXToken *Tokensunsigned NumTokens) {
6800  free(Tokens);
6801}
6802
6803//===----------------------------------------------------------------------===//
6804// Token annotation APIs.
6805//===----------------------------------------------------------------------===//
6806
6807static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
6808                                                     CXCursor parent,
6809                                                     CXClientData client_data);
6810static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
6811                                              CXClientData client_data);
6812
6813namespace {
6814class AnnotateTokensWorker {
6815  CXToken *Tokens;
6816  CXCursor *Cursors;
6817  unsigned NumTokens;
6818  unsigned TokIdx;
6819  unsigned PreprocessingTokIdx;
6820  CursorVisitor AnnotateVis;
6821  SourceManager &SrcMgr;
6822  bool HasContextSensitiveKeywords;
6823
6824  struct PostChildrenAction {
6825    CXCursor cursor;
6826    enum Action { InvalidIgnorePostpone } action;
6827  };
6828  using PostChildrenActions = SmallVector<PostChildrenAction0>;
6829
6830  struct PostChildrenInfo {
6831    CXCursor Cursor;
6832    SourceRange CursorRange;
6833    unsigned BeforeReachingCursorIdx;
6834    unsigned BeforeChildrenTokenIdx;
6835    PostChildrenActions ChildActions;
6836  };
6837  SmallVector<PostChildrenInfo8PostChildrenInfos;
6838
6839  CXToken &getTok(unsigned Idx) {
6840    assert(Idx < NumTokens);
6841    return Tokens[Idx];
6842  }
6843  const CXToken &getTok(unsigned Idxconst {
6844    assert(Idx < NumTokens);
6845    return Tokens[Idx];
6846  }
6847  bool MoreTokens() const { return TokIdx < NumTokens; }
6848  unsigned NextToken() const { return TokIdx; }
6849  void AdvanceToken() { ++TokIdx; }
6850  SourceLocation GetTokenLoc(unsigned tokI) {
6851    return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
6852  }
6853  bool isFunctionMacroToken(unsigned tokIconst {
6854    return getTok(tokI).int_data[3] != 0;
6855  }
6856  SourceLocation getFunctionMacroTokenLoc(unsigned tokIconst {
6857    return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
6858  }
6859
6860  void annotateAndAdvanceTokens(CXCursorRangeComparisonResultSourceRange);
6861  bool annotateAndAdvanceFunctionMacroTokens(CXCursorRangeComparisonResult,
6862                                             SourceRange);
6863
6864public:
6865  AnnotateTokensWorker(CXToken *tokensCXCursor *cursorsunsigned numTokens,
6866                       CXTranslationUnit TUSourceRange RegionOfInterest)
6867    : Tokens(tokens), Cursors(cursors),
6868      NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
6869      AnnotateVis(TU,
6870                  AnnotateTokensVisitor, this,
6871                  /*VisitPreprocessorLast=*/true,
6872                  /*VisitIncludedEntities=*/false,
6873                  RegionOfInterest,
6874                  /*VisitDeclsOnly=*/false,
6875                  AnnotateTokensPostChildrenVisitor),
6876      SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
6877      HasContextSensitiveKeywords(false) { }
6878
6879  void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
6880  enum CXChildVisitResult Visit(CXCursor cursorCXCursor parent);
6881  bool IsIgnoredChildCursor(CXCursor cursorconst;
6882  PostChildrenActions DetermineChildActions(CXCursor Cursorconst;
6883
6884  bool postVisitChildren(CXCursor cursor);
6885  void HandlePostPonedChildCursors(const PostChildrenInfo &Info);
6886  void HandlePostPonedChildCursor(CXCursor Cursorunsigned StartTokenIndex);
6887
6888  void AnnotateTokens();
6889  
6890  /// Determine whether the annotator saw any cursors that have 
6891  /// context-sensitive keywords.
6892  bool hasContextSensitiveKeywords() const {
6893    return HasContextSensitiveKeywords;
6894  }
6895
6896  ~AnnotateTokensWorker() {
6897    assert(PostChildrenInfos.empty());
6898  }
6899};
6900}
6901
6902void AnnotateTokensWorker::AnnotateTokens() {
6903  // Walk the AST within the region of interest, annotating tokens
6904  // along the way.
6905  AnnotateVis.visitFileRegion();
6906}
6907
6908bool AnnotateTokensWorker::IsIgnoredChildCursor(CXCursor cursorconst {
6909  if (PostChildrenInfos.empty())
6910    return false;
6911
6912  for (const auto &ChildAction : PostChildrenInfos.back().ChildActions) {
6913    if (ChildAction.cursor == cursor &&
6914        ChildAction.action == PostChildrenAction::Ignore) {
6915      return true;
6916    }
6917  }
6918
6919  return false;
6920}
6921
6922const CXXOperatorCallExpr *GetSubscriptOrCallOperator(CXCursor Cursor) {
6923  if (!clang_isExpression(Cursor.kind))
6924    return nullptr;
6925
6926  const Expr *E = getCursorExpr(Cursor);
6927  if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
6928    const OverloadedOperatorKind Kind = OCE->getOperator();
6929    if (Kind == OO_Call || Kind == OO_Subscript)
6930      return OCE;
6931  }
6932
6933  return nullptr;
6934}
6935
6936AnnotateTokensWorker::PostChildrenActions
6937AnnotateTokensWorker::DetermineChildActions(CXCursor Cursorconst {
6938  PostChildrenActions actions;
6939
6940  // The DeclRefExpr of CXXOperatorCallExpr refering to the custom operator is
6941  // visited before the arguments to the operator call. For the Call and
6942  // Subscript operator the range of this DeclRefExpr includes the whole call
6943  // expression, so that all tokens in that range would be mapped to the
6944  // operator function, including the tokens of the arguments. To avoid that,
6945  // ensure to visit this DeclRefExpr as last node.
6946  if (const auto *OCE = GetSubscriptOrCallOperator(Cursor)) {
6947    const Expr *Callee = OCE->getCallee();
6948    if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee)) {
6949      const Expr *SubExpr = ICE->getSubExpr();
6950      if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr)) {
6951        const Decl *parentDecl = getCursorDecl(Cursor);
6952        CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
6953
6954        // Visit the DeclRefExpr as last.
6955        CXCursor cxChild = MakeCXCursor(DREparentDeclTU);
6956        actions.push_back({cxChild, PostChildrenAction::Postpone});
6957
6958        // The parent of the DeclRefExpr, an ImplicitCastExpr, has an equally
6959        // wide range as the DeclRefExpr. We can skip visiting this entirely.
6960        cxChild = MakeCXCursor(ICEparentDeclTU);
6961        actions.push_back({cxChild, PostChildrenAction::Ignore});
6962      }
6963    }
6964  }
6965
6966  return actions;
6967}
6968
6969static inline void updateCursorAnnotation(CXCursor &Cursor,
6970                                          const CXCursor &updateC) {
6971  if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
6972    return;
6973  Cursor = updateC;
6974}
6975
6976/// It annotates and advances tokens with a cursor until the comparison
6977//// between the cursor location and the source range is the same as
6978/// \arg compResult.
6979///
6980/// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
6981/// Pass RangeOverlap to annotate tokens inside a range.
6982void AnnotateTokensWorker::annotateAndAdvanceTokens(CXCursor updateC,
6983                                               RangeComparisonResult compResult,
6984                                               SourceRange range) {
6985  while (MoreTokens()) {
6986    const unsigned I = NextToken();
6987    if (isFunctionMacroToken(I))
6988      if (!annotateAndAdvanceFunctionMacroTokens(updateCcompResultrange))
6989        return;
6990
6991    SourceLocation TokLoc = GetTokenLoc(I);
6992    if (LocationCompare(SrcMgrTokLocrange) == compResult) {
6993      updateCursorAnnotation(Cursors[I]updateC);
6994      AdvanceToken();
6995      continue;
6996    }
6997    break;
6998  }
6999}
7000
7001/// Special annotation handling for macro argument tokens.
7002/// \returns true if it advanced beyond all macro tokens, false otherwise.
7003bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
7004                                               CXCursor updateC,
7005                                               RangeComparisonResult compResult,
7006                                               SourceRange range) {
7007  assert(MoreTokens());
7008   (0) . __assert_fail ("isFunctionMacroToken(NextToken()) && \"Should be called only for macro arg tokens\"", "/home/seafit/code_projects/clang_source/clang/tools/libclang/CIndex.cpp", 7009, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(isFunctionMacroToken(NextToken()) &&
7009 (0) . __assert_fail ("isFunctionMacroToken(NextToken()) && \"Should be called only for macro arg tokens\"", "/home/seafit/code_projects/clang_source/clang/tools/libclang/CIndex.cpp", 7009, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         "Should be called only for macro arg tokens");
7010
7011  // This works differently than annotateAndAdvanceTokens; because expanded
7012  // macro arguments can have arbitrary translation-unit source order, we do not
7013  // advance the token index one by one until a token fails the range test.
7014  // We only advance once past all of the macro arg tokens if all of them
7015  // pass the range test. If one of them fails we keep the token index pointing
7016  // at the start of the macro arg tokens so that the failing token will be
7017  // annotated by a subsequent annotation try.
7018
7019  bool atLeastOneCompFail = false;
7020  
7021  unsigned I = NextToken();
7022  for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
7023    SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
7024    if (TokLoc.isFileID())
7025      continue// not macro arg token, it's parens or comma.
7026    if (LocationCompare(SrcMgrTokLocrange) == compResult) {
7027      if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
7028        Cursors[I] = updateC;
7029    } else
7030      atLeastOneCompFail = true;
7031  }
7032
7033  if (atLeastOneCompFail)
7034    return false;
7035
7036  TokIdx = I// All of the tokens were handled, advance beyond all of them.
7037  return true;
7038}
7039
7040enum CXChildVisitResult
7041AnnotateTokensWorker::Visit(CXCursor cursorCXCursor parent) {  
7042  SourceRange cursorRange = getRawCursorExtent(cursor);
7043  if (cursorRange.isInvalid())
7044    return CXChildVisit_Recurse;
7045
7046  if (IsIgnoredChildCursor(cursor))
7047    return CXChildVisit_Continue;
7048
7049  if (!HasContextSensitiveKeywords) {
7050    // Objective-C properties can have context-sensitive keywords.
7051    if (cursor.kind == CXCursor_ObjCPropertyDecl) {
7052      if (const ObjCPropertyDecl *Property
7053                  = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
7054        HasContextSensitiveKeywords = Property->getPropertyAttributesAsWritten() != 0;
7055    }
7056    // Objective-C methods can have context-sensitive keywords.
7057    else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
7058             cursor.kind == CXCursor_ObjCClassMethodDecl) {
7059      if (const ObjCMethodDecl *Method
7060            = dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
7061        if (Method->getObjCDeclQualifier())
7062          HasContextSensitiveKeywords = true;
7063        else {
7064          for (const auto *P : Method->parameters()) {
7065            if (P->getObjCDeclQualifier()) {
7066              HasContextSensitiveKeywords = true;
7067              break;
7068            }
7069          }
7070        }
7071      }
7072    }    
7073    // C++ methods can have context-sensitive keywords.
7074    else if (cursor.kind == CXCursor_CXXMethod) {
7075      if (const CXXMethodDecl *Method
7076                  = dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
7077        if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
7078          HasContextSensitiveKeywords = true;
7079      }
7080    }
7081    // C++ classes can have context-sensitive keywords.
7082    else if (cursor.kind == CXCursor_StructDecl ||
7083             cursor.kind == CXCursor_ClassDecl ||
7084             cursor.kind == CXCursor_ClassTemplate ||
7085             cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
7086      if (const Decl *D = getCursorDecl(cursor))
7087        if (D->hasAttr<FinalAttr>())
7088          HasContextSensitiveKeywords = true;
7089    }
7090  }
7091
7092  // Don't override a property annotation with its getter/setter method.
7093  if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
7094      parent.kind == CXCursor_ObjCPropertyDecl)
7095    return CXChildVisit_Continue;
7096  
7097  if (clang_isPreprocessing(cursor.kind)) {    
7098    // Items in the preprocessing record are kept separate from items in
7099    // declarations, so we keep a separate token index.
7100    unsigned SavedTokIdx = TokIdx;
7101    TokIdx = PreprocessingTokIdx;
7102
7103    // Skip tokens up until we catch up to the beginning of the preprocessing
7104    // entry.
7105    while (MoreTokens()) {
7106      const unsigned I = NextToken();
7107      SourceLocation TokLoc = GetTokenLoc(I);
7108      switch (LocationCompare(SrcMgrTokLoccursorRange)) {
7109      case RangeBefore:
7110        AdvanceToken();
7111        continue;
7112      case RangeAfter:
7113      case RangeOverlap:
7114        break;
7115      }
7116      break;
7117    }
7118    
7119    // Look at all of the tokens within this range.
7120    while (MoreTokens()) {
7121      const unsigned I = NextToken();
7122      SourceLocation TokLoc = GetTokenLoc(I);
7123      switch (LocationCompare(SrcMgrTokLoccursorRange)) {
7124      case RangeBefore:
7125        llvm_unreachable("Infeasible");
7126      case RangeAfter:
7127        break;
7128      case RangeOverlap:
7129        // For macro expansions, just note where the beginning of the macro
7130        // expansion occurs.
7131        if (cursor.kind == CXCursor_MacroExpansion) {
7132          if (TokLoc == cursorRange.getBegin())
7133            Cursors[I] = cursor;
7134          AdvanceToken();
7135          break;
7136        }
7137        // We may have already annotated macro names inside macro definitions.
7138        if (Cursors[I].kind != CXCursor_MacroExpansion)
7139          Cursors[I] = cursor;
7140        AdvanceToken();
7141        continue;
7142      }
7143      break;
7144    }
7145
7146    // Save the preprocessing token index; restore the non-preprocessing
7147    // token index.
7148    PreprocessingTokIdx = TokIdx;
7149    TokIdx = SavedTokIdx;
7150    return CXChildVisit_Recurse;
7151  }
7152
7153  if (cursorRange.isInvalid())
7154    return CXChildVisit_Continue;
7155
7156  unsigned BeforeReachingCursorIdx = NextToken();
7157  const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
7158  const enum CXCursorKind K = clang_getCursorKind(parent);
7159  const CXCursor updateC =
7160    (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
7161     // Attributes are annotated out-of-order, skip tokens until we reach it.
7162     clang_isAttribute(cursor.kind))
7163     ? clang_getNullCursor() : parent;
7164
7165  annotateAndAdvanceTokens(updateCRangeBeforecursorRange);
7166
7167  // Avoid having the cursor of an expression "overwrite" the annotation of the
7168  // variable declaration that it belongs to.
7169  // This can happen for C++ constructor expressions whose range generally
7170  // include the variable declaration, e.g.:
7171  //  MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
7172  if (clang_isExpression(cursorK) && MoreTokens()) {
7173    const Expr *E = getCursorExpr(cursor);
7174    if (const Decl *D = getCursorDecl(cursor)) {
7175      const unsigned I = NextToken();
7176      if (E->getBeginLoc().isValid() && D->getLocation().isValid() &&
7177          E->getBeginLoc() == D->getLocation() &&
7178          E->getBeginLoc() == GetTokenLoc(I)) {
7179        updateCursorAnnotation(Cursors[I]updateC);
7180        AdvanceToken();
7181      }
7182    }
7183  }
7184
7185  // Before recursing into the children keep some state that we are going
7186  // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
7187  // extra work after the child nodes are visited.
7188  // Note that we don't call VisitChildren here to avoid traversing statements
7189  // code-recursively which can blow the stack.
7190
7191  PostChildrenInfo Info;
7192  Info.Cursor = cursor;
7193  Info.CursorRange = cursorRange;
7194  Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
7195  Info.BeforeChildrenTokenIdx = NextToken();
7196  Info.ChildActions = DetermineChildActions(cursor);
7197  PostChildrenInfos.push_back(Info);
7198
7199  return CXChildVisit_Recurse;
7200}
7201
7202bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
7203  if (PostChildrenInfos.empty())
7204    return false;
7205  const PostChildrenInfo &Info = PostChildrenInfos.back();
7206  if (!clang_equalCursors(Info.Cursorcursor))
7207    return false;
7208
7209  HandlePostPonedChildCursors(Info);
7210
7211  const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
7212  const unsigned AfterChildren = NextToken();
7213  SourceRange cursorRange = Info.CursorRange;
7214
7215  // Scan the tokens that are at the end of the cursor, but are not captured
7216  // but the child cursors.
7217  annotateAndAdvanceTokens(cursorRangeOverlapcursorRange);
7218
7219  // Scan the tokens that are at the beginning of the cursor, but are not
7220  // capture by the child cursors.
7221  for (unsigned I = BeforeChildrenI != AfterChildren; ++I) {
7222    if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
7223      break;
7224
7225    Cursors[I] = cursor;
7226  }
7227
7228  // Attributes are annotated out-of-order, rewind TokIdx to when we first
7229  // encountered the attribute cursor.
7230  if (clang_isAttribute(cursor.kind))
7231    TokIdx = Info.BeforeReachingCursorIdx;
7232
7233  PostChildrenInfos.pop_back();
7234  return false;
7235}
7236
7237void AnnotateTokensWorker::HandlePostPonedChildCursors(
7238    const PostChildrenInfo &Info) {
7239  for (const auto &ChildAction : Info.ChildActions) {
7240    if (ChildAction.action == PostChildrenAction::Postpone) {
7241      HandlePostPonedChildCursor(ChildAction.cursor,
7242                                 Info.BeforeChildrenTokenIdx);
7243    }
7244  }
7245}
7246
7247void AnnotateTokensWorker::HandlePostPonedChildCursor(
7248    CXCursor Cursorunsigned StartTokenIndex) {
7249  const auto flags = CXNameRange_WantQualifier | CXNameRange_WantQualifier;
7250  unsigned I = StartTokenIndex;
7251
7252  // The bracket tokens of a Call or Subscript operator are mapped to
7253  // CallExpr/CXXOperatorCallExpr because we skipped visiting the corresponding
7254  // DeclRefExpr. Remap these tokens to the DeclRefExpr cursors.
7255  for (unsigned RefNameRangeNr = 0I < NumTokensRefNameRangeNr++) {
7256    const CXSourceRange CXRefNameRange =
7257        clang_getCursorReferenceNameRange(CursorflagsRefNameRangeNr);
7258    if (clang_Range_isNull(CXRefNameRange))
7259      break// All ranges handled.
7260
7261    SourceRange RefNameRange = cxloc::translateCXSourceRange(CXRefNameRange);
7262    while (I < NumTokens) {
7263      const SourceLocation TokenLocation = GetTokenLoc(I);
7264      if (!TokenLocation.isValid())
7265        break;
7266
7267      // Adapt the end range, because LocationCompare() reports
7268      // RangeOverlap even for the not-inclusive end location.
7269      const SourceLocation fixedEnd =
7270          RefNameRange.getEnd().getLocWithOffset(-1);
7271      RefNameRange = SourceRange(RefNameRange.getBegin(), fixedEnd);
7272
7273      const RangeComparisonResult ComparisonResult =
7274          LocationCompare(SrcMgrTokenLocationRefNameRange);
7275
7276      if (ComparisonResult == RangeOverlap) {
7277        Cursors[I++] = Cursor;
7278      } else if (ComparisonResult == RangeBefore) {
7279        ++I// Not relevant token, check next one.
7280      } else if (ComparisonResult == RangeAfter) {
7281        break// All tokens updated for current range, check next.
7282      }
7283    }
7284  }
7285}
7286
7287static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
7288                                                     CXCursor parent,
7289                                                     CXClientData client_data) {
7290  return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursorparent);
7291}
7292
7293static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
7294                                              CXClientData client_data) {
7295  return static_cast<AnnotateTokensWorker*>(client_data)->
7296                                                      postVisitChildren(cursor);
7297}
7298
7299namespace {
7300
7301/// Uses the macro expansions in the preprocessing record to find
7302/// and mark tokens that are macro arguments. This info is used by the
7303/// AnnotateTokensWorker.
7304class MarkMacroArgTokensVisitor {
7305  SourceManager &SM;
7306  CXToken *Tokens;
7307  unsigned NumTokens;
7308  unsigned CurIdx;
7309  
7310public:
7311  MarkMacroArgTokensVisitor(SourceManager &SM,
7312                            CXToken *tokensunsigned numTokens)
7313    : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) { }
7314
7315  CXChildVisitResult visit(CXCursor cursorCXCursor parent) {
7316    if (cursor.kind != CXCursor_MacroExpansion)
7317      return CXChildVisit_Continue;
7318
7319    SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
7320    if (macroRange.getBegin() == macroRange.getEnd())
7321      return CXChildVisit_Continue// it's not a function macro.
7322
7323    for (; CurIdx < NumTokens; ++CurIdx) {
7324      if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
7325                                        macroRange.getBegin()))
7326        break;
7327    }
7328    
7329    if (CurIdx == NumTokens)
7330      return CXChildVisit_Break;
7331
7332    for (; CurIdx < NumTokens; ++CurIdx) {
7333      SourceLocation tokLoc = getTokenLoc(CurIdx);
7334      if (!SM.isBeforeInTranslationUnit(tokLocmacroRange.getEnd()))
7335        break;
7336
7337      setFunctionMacroTokenLoc(CurIdxSM.getMacroArgExpandedLocation(tokLoc));
7338    }
7339
7340    if (CurIdx == NumTokens)
7341      return CXChildVisit_Break;
7342
7343    return CXChildVisit_Continue;
7344  }
7345
7346private:
7347  CXToken &getTok(unsigned Idx) {
7348    assert(Idx < NumTokens);
7349    return Tokens[Idx];
7350  }
7351  const CXToken &getTok(unsigned Idxconst {
7352    assert(Idx < NumTokens);
7353    return Tokens[Idx];
7354  }
7355
7356  SourceLocation getTokenLoc(unsigned tokI) {
7357    return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
7358  }
7359
7360  void setFunctionMacroTokenLoc(unsigned tokISourceLocation loc) {
7361    // The third field is reserved and currently not used. Use it here
7362    // to mark macro arg expanded tokens with their expanded locations.
7363    getTok(tokI).int_data[3] = loc.getRawEncoding();
7364  }
7365};
7366
7367// end anonymous namespace
7368
7369static CXChildVisitResult
7370MarkMacroArgTokensVisitorDelegate(CXCursor cursorCXCursor parent,
7371                                  CXClientData client_data) {
7372  return static_cast<MarkMacroArgTokensVisitor*>(client_data)->visit(cursor,
7373                                                                     parent);
7374}
7375
7376/// Used by \c annotatePreprocessorTokens.
7377/// \returns true if lexing was finished, false otherwise.
7378static bool lexNext(Lexer &LexToken &Tok,
7379                   unsigned &NextIdxunsigned NumTokens) {
7380  if (NextIdx >= NumTokens)
7381    return true;
7382
7383  ++NextIdx;
7384  Lex.LexFromRawLexer(Tok);
7385  return Tok.is(tok::eof);
7386}
7387
7388static void annotatePreprocessorTokens(CXTranslationUnit TU,
7389                                       SourceRange RegionOfInterest,
7390                                       CXCursor *Cursors,
7391                                       CXToken *Tokens,
7392                                       unsigned NumTokens) {
7393  ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
7394
7395  Preprocessor &PP = CXXUnit->getPreprocessor();
7396  SourceManager &SourceMgr = CXXUnit->getSourceManager();
7397  std::pair<FileIDunsignedBeginLocInfo
7398    = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
7399  std::pair<FileIDunsignedEndLocInfo
7400    = SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
7401
7402  if (BeginLocInfo.first != EndLocInfo.first)
7403    return;
7404
7405  StringRef Buffer;
7406  bool Invalid = false;
7407  Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
7408  if (Buffer.empty() || Invalid)
7409    return;
7410
7411  Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
7412            CXXUnit->getASTContext().getLangOpts(),
7413            Buffer.begin(), Buffer.data() + BeginLocInfo.second,
7414            Buffer.end());
7415  Lex.SetCommentRetentionState(true);
7416  
7417  unsigned NextIdx = 0;
7418  // Lex tokens in raw mode until we hit the end of the range, to avoid
7419  // entering #includes or expanding macros.
7420  while (true) {
7421    Token Tok;
7422    if (lexNext(LexTokNextIdxNumTokens))
7423      break;
7424    unsigned TokIdx = NextIdx-1;
7425    assert(Tok.getLocation() ==
7426             SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
7427    
7428  reprocess:
7429    if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
7430      // We have found a preprocessing directive. Annotate the tokens
7431      // appropriately.
7432      //
7433      // FIXME: Some simple tests here could identify macro definitions and
7434      // #undefs, to provide specific cursor kinds for those.
7435
7436      SourceLocation BeginLoc = Tok.getLocation();
7437      if (lexNext(LexTokNextIdxNumTokens))
7438        break;
7439
7440      MacroInfo *MI = nullptr;
7441      if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
7442        if (lexNext(LexTokNextIdxNumTokens))
7443          break;
7444
7445        if (Tok.is(tok::raw_identifier)) {
7446          IdentifierInfo &II =
7447              PP.getIdentifierTable().get(Tok.getRawIdentifier());
7448          SourceLocation MappedTokLoc =
7449              CXXUnit->mapLocationToPreamble(Tok.getLocation());
7450          MI = getMacroInfo(IIMappedTokLocTU);
7451        }
7452      }
7453
7454      bool finished = false;
7455      do {
7456        if (lexNext(LexTokNextIdxNumTokens)) {
7457          finished = true;
7458          break;
7459        }
7460        // If we are in a macro definition, check if the token was ever a
7461        // macro name and annotate it if that's the case.
7462        if (MI) {
7463          SourceLocation SaveLoc = Tok.getLocation();
7464          Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
7465          MacroDefinitionRecord *MacroDef =
7466              checkForMacroInMacroDefinition(MITokTU);
7467          Tok.setLocation(SaveLoc);
7468          if (MacroDef)
7469            Cursors[NextIdx - 1] =
7470                MakeMacroExpansionCursor(MacroDefTok.getLocation(), TU);
7471        }
7472      } while (!Tok.isAtStartOfLine());
7473
7474      unsigned LastIdx = finished ? NextIdx-1 : NextIdx-2;
7475      assert(TokIdx <= LastIdx);
7476      SourceLocation EndLoc =
7477          SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
7478      CXCursor Cursor =
7479          MakePreprocessingDirectiveCursor(SourceRange(BeginLocEndLoc), TU);
7480
7481      for (; TokIdx <= LastIdx; ++TokIdx)
7482        updateCursorAnnotation(Cursors[TokIdx]Cursor);
7483      
7484      if (finished)
7485        break;
7486      goto reprocess;
7487    }
7488  }
7489}
7490
7491// This gets run a separate thread to avoid stack blowout.
7492static void clang_annotateTokensImpl(CXTranslationUnit TUASTUnit *CXXUnit,
7493                                     CXToken *Tokensunsigned NumTokens,
7494                                     CXCursor *Cursors) {
7495  CIndexer *CXXIdx = TU->CIdx;
7496  if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
7497    setThreadBackgroundPriority();
7498
7499  // Determine the region of interest, which contains all of the tokens.
7500  SourceRange RegionOfInterest;
7501  RegionOfInterest.setBegin(
7502    cxloc::translateSourceLocation(clang_getTokenLocation(TUTokens[0])));
7503  RegionOfInterest.setEnd(
7504    cxloc::translateSourceLocation(clang_getTokenLocation(TU,
7505                                                         Tokens[NumTokens-1])));
7506
7507  // Relex the tokens within the source range to look for preprocessing
7508  // directives.
7509  annotatePreprocessorTokens(TURegionOfInterestCursorsTokensNumTokens);
7510
7511  // If begin location points inside a macro argument, set it to the expansion
7512  // location so we can have the full context when annotating semantically.
7513  {
7514    SourceManager &SM = CXXUnit->getSourceManager();
7515    SourceLocation Loc =
7516        SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
7517    if (Loc.isMacroID())
7518      RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
7519  }
7520
7521  if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
7522    // Search and mark tokens that are macro argument expansions.
7523    MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(),
7524                                      TokensNumTokens);
7525    CursorVisitor MacroArgMarker(TU,
7526                                 MarkMacroArgTokensVisitorDelegate, &Visitor,
7527                                 /*VisitPreprocessorLast=*/true,
7528                                 /*VisitIncludedEntities=*/false,
7529                                 RegionOfInterest);
7530    MacroArgMarker.visitPreprocessedEntitiesInRegion();
7531  }
7532  
7533  // Annotate all of the source locations in the region of interest that map to
7534  // a specific cursor.
7535  AnnotateTokensWorker W(TokensCursorsNumTokensTURegionOfInterest);
7536  
7537  // FIXME: We use a ridiculous stack size here because the data-recursion
7538  // algorithm uses a large stack frame than the non-data recursive version,
7539  // and AnnotationTokensWorker currently transforms the data-recursion
7540  // algorithm back into a traditional recursion by explicitly calling
7541  // VisitChildren().  We will need to remove this explicit recursive call.
7542  W.AnnotateTokens();
7543
7544  // If we ran into any entities that involve context-sensitive keywords,
7545  // take another pass through the tokens to mark them as such.
7546  if (W.hasContextSensitiveKeywords()) {
7547    for (unsigned I = 0I != NumTokens; ++I) {
7548      if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
7549        continue;
7550      
7551      if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
7552        IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
7553        if (const ObjCPropertyDecl *Property
7554            = dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
7555          if (Property->getPropertyAttributesAsWritten() != 0 &&
7556              llvm::StringSwitch<bool>(II->getName())
7557              .Case("readonly"true)
7558              .Case("assign"true)
7559              .Case("unsafe_unretained"true)
7560              .Case("readwrite"true)
7561              .Case("retain"true)
7562              .Case("copy"true)
7563              .Case("nonatomic"true)
7564              .Case("atomic"true)
7565              .Case("getter"true)
7566              .Case("setter"true)
7567              .Case("strong"true)
7568              .Case("weak"true)
7569              .Case("class"true)
7570              .Default(false))
7571            Tokens[I].int_data[0] = CXToken_Keyword;
7572        }
7573        continue;
7574      }
7575      
7576      if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
7577          Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
7578        IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
7579        if (llvm::StringSwitch<bool>(II->getName())
7580            .Case("in"true)
7581            .Case("out"true)
7582            .Case("inout"true)
7583            .Case("oneway"true)
7584            .Case("bycopy"true)
7585            .Case("byref"true)
7586            .Default(false))
7587          Tokens[I].int_data[0] = CXToken_Keyword;
7588        continue;
7589      }
7590
7591      if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
7592          Cursors[I].kind == CXCursor_CXXOverrideAttr) {
7593        Tokens[I].int_data[0] = CXToken_Keyword;
7594        continue;
7595      }
7596    }
7597  }
7598}
7599
7600void clang_annotateTokens(CXTranslationUnit TU,
7601                          CXToken *Tokensunsigned NumTokens,
7602                          CXCursor *Cursors) {
7603  if (isNotUsableTU(TU)) {
7604    LOG_BAD_TU(TU);
7605    return;
7606  }
7607  if (NumTokens == 0 || !Tokens || !Cursors) {
7608    LOG_FUNC_SECTION { *Log << "<null input>"; }
7609    return;
7610  }
7611
7612  LOG_FUNC_SECTION {
7613    *Log << TU << ' ';
7614    CXSourceLocation bloc = clang_getTokenLocation(TUTokens[0]);
7615    CXSourceLocation eloc = clang_getTokenLocation(TUTokens[NumTokens-1]);
7616    *Log << clang_getRange(bloc, eloc);
7617  }
7618
7619  // Any token we don't specifically annotate will have a NULL cursor.
7620  CXCursor C = clang_getNullCursor();
7621  for (unsigned I = 0I != NumTokens; ++I)
7622    Cursors[I] = C;
7623
7624  ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
7625  if (!CXXUnit)
7626    return;
7627
7628  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
7629
7630  auto AnnotateTokensImpl = [=]() {
7631    clang_annotateTokensImpl(TUCXXUnitTokensNumTokensCursors);
7632  };
7633  llvm::CrashRecoveryContext CRC;
7634  if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
7635    fprintf(stderr"libclang: crash detected while annotating tokens\n");
7636  }
7637}
7638
7639//===----------------------------------------------------------------------===//
7640// Operations for querying linkage of a cursor.
7641//===----------------------------------------------------------------------===//
7642
7643CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
7644  if (!clang_isDeclaration(cursor.kind))
7645    return CXLinkage_Invalid;
7646
7647  const Decl *D = cxcursor::getCursorDecl(cursor);
7648  if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
7649    switch (ND->getLinkageInternal()) {
7650      case NoLinkage:
7651      case VisibleNoLinkagereturn CXLinkage_NoLinkage;
7652      case ModuleInternalLinkage:
7653      case InternalLinkagereturn CXLinkage_Internal;
7654      case UniqueExternalLinkagereturn CXLinkage_UniqueExternal;
7655      case ModuleLinkage:
7656      case ExternalLinkagereturn CXLinkage_External;
7657    };
7658
7659  return CXLinkage_Invalid;
7660}
7661
7662//===----------------------------------------------------------------------===//
7663// Operations for querying visibility of a cursor.
7664//===----------------------------------------------------------------------===//
7665
7666CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
7667  if (!clang_isDeclaration(cursor.kind))
7668    return CXVisibility_Invalid;
7669
7670  const Decl *D = cxcursor::getCursorDecl(cursor);
7671  if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
7672    switch (ND->getVisibility()) {
7673      case HiddenVisibilityreturn CXVisibility_Hidden;
7674      case ProtectedVisibilityreturn CXVisibility_Protected;
7675      case DefaultVisibilityreturn CXVisibility_Default;
7676    };
7677
7678  return CXVisibility_Invalid;
7679}
7680
7681//===----------------------------------------------------------------------===//
7682// Operations for querying language of a cursor.
7683//===----------------------------------------------------------------------===//
7684
7685static CXLanguageKind getDeclLanguage(const Decl *D) {
7686  if (!D)
7687    return CXLanguage_C;
7688
7689  switch (D->getKind()) {
7690    default:
7691      break;
7692    case Decl::ImplicitParam:
7693    case Decl::ObjCAtDefsField:
7694    case Decl::ObjCCategory:
7695    case Decl::ObjCCategoryImpl:
7696    case Decl::ObjCCompatibleAlias:
7697    case Decl::ObjCImplementation:
7698    case Decl::ObjCInterface:
7699    case Decl::ObjCIvar:
7700    case Decl::ObjCMethod:
7701    case Decl::ObjCProperty:
7702    case Decl::ObjCPropertyImpl:
7703    case Decl::ObjCProtocol:
7704    case Decl::ObjCTypeParam:
7705      return CXLanguage_ObjC;
7706    case Decl::CXXConstructor:
7707    case Decl::CXXConversion:
7708    case Decl::CXXDestructor:
7709    case Decl::CXXMethod:
7710    case Decl::CXXRecord:
7711    case Decl::ClassTemplate:
7712    case Decl::ClassTemplatePartialSpecialization:
7713    case Decl::ClassTemplateSpecialization:
7714    case Decl::Friend:
7715    case Decl::FriendTemplate:
7716    case Decl::FunctionTemplate:
7717    case Decl::LinkageSpec:
7718    case Decl::Namespace:
7719    case Decl::NamespaceAlias:
7720    case Decl::NonTypeTemplateParm:
7721    case Decl::StaticAssert:
7722    case Decl::TemplateTemplateParm:
7723    case Decl::TemplateTypeParm:
7724    case Decl::UnresolvedUsingTypename:
7725    case Decl::UnresolvedUsingValue:
7726    case Decl::Using:
7727    case Decl::UsingDirective:
7728    case Decl::UsingShadow:
7729      return CXLanguage_CPlusPlus;
7730  }
7731
7732  return CXLanguage_C;
7733}
7734
7735static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
7736  if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
7737    return CXAvailability_NotAvailable;
7738  
7739  switch (D->getAvailability()) {
7740  case AR_Available:
7741  case AR_NotYetIntroduced:
7742    if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7743      return getCursorAvailabilityForDecl(
7744          cast<Decl>(EnumConst->getDeclContext()));
7745    return CXAvailability_Available;
7746
7747  case AR_Deprecated:
7748    return CXAvailability_Deprecated;
7749
7750  case AR_Unavailable:
7751    return CXAvailability_NotAvailable;
7752  }
7753
7754  llvm_unreachable("Unknown availability kind!");
7755}
7756
7757enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
7758  if (clang_isDeclaration(cursor.kind))
7759    if (const Decl *D = cxcursor::getCursorDecl(cursor))
7760      return getCursorAvailabilityForDecl(D);
7761
7762  return CXAvailability_Available;
7763}
7764
7765static CXVersion convertVersion(VersionTuple In) {
7766  CXVersion Out = { -1, -1, -1 };
7767  if (In.empty())
7768    return Out;
7769
7770  Out.Major = In.getMajor();
7771  
7772  Optional<unsignedMinor = In.getMinor();
7773  if (Minor.hasValue())
7774    Out.Minor = *Minor;
7775  else
7776    return Out;
7777
7778  Optional<unsignedSubminor = In.getSubminor();
7779  if (Subminor.hasValue())
7780    Out.Subminor = *Subminor;
7781  
7782  return Out;
7783}
7784
7785static void getCursorPlatformAvailabilityForDecl(
7786    const Decl *Dint *always_deprecatedCXString *deprecated_message,
7787    int *always_unavailableCXString *unavailable_message,
7788    SmallVectorImpl<AvailabilityAttr *> &AvailabilityAttrs) {
7789  bool HadAvailAttr = false;
7790  for (auto A : D->attrs()) {
7791    if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
7792      HadAvailAttr = true;
7793      if (always_deprecated)
7794        *always_deprecated = 1;
7795      if (deprecated_message) {
7796        clang_disposeString(*deprecated_message);
7797        *deprecated_message = cxstring::createDup(Deprecated->getMessage());
7798      }
7799      continue;
7800    }
7801
7802    if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
7803      HadAvailAttr = true;
7804      if (always_unavailable)
7805        *always_unavailable = 1;
7806      if (unavailable_message) {
7807        clang_disposeString(*unavailable_message);
7808        *unavailable_message = cxstring::createDup(Unavailable->getMessage());
7809      }
7810      continue;
7811    }
7812
7813    if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
7814      AvailabilityAttrs.push_back(Avail);
7815      HadAvailAttr = true;
7816    }
7817  }
7818
7819  if (!HadAvailAttr)
7820    if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
7821      return getCursorPlatformAvailabilityForDecl(
7822          cast<Decl>(EnumConst->getDeclContext()), always_deprecated,
7823          deprecated_message, always_unavailable, unavailable_message,
7824          AvailabilityAttrs);
7825
7826  if (AvailabilityAttrs.empty())
7827    return;
7828
7829  llvm::sort(AvailabilityAttrs,
7830             [](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7831               return LHS->getPlatform()->getName() <
7832                      RHS->getPlatform()->getName();
7833             });
7834  ASTContext &Ctx = D->getASTContext();
7835  auto It = std::unique(
7836      AvailabilityAttrs.begin(), AvailabilityAttrs.end(),
7837      [&Ctx](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
7838        if (LHS->getPlatform() != RHS->getPlatform())
7839          return false;
7840
7841        if (LHS->getIntroduced() == RHS->getIntroduced() &&
7842            LHS->getDeprecated() == RHS->getDeprecated() &&
7843            LHS->getObsoleted() == RHS->getObsoleted() &&
7844            LHS->getMessage() == RHS->getMessage() &&
7845            LHS->getReplacement() == RHS->getReplacement())
7846          return true;
7847
7848        if ((!LHS->getIntroduced().empty() && !RHS->getIntroduced().empty()) ||
7849            (!LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) ||
7850            (!LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()))
7851          return false;
7852
7853        if (LHS->getIntroduced().empty() && !RHS->getIntroduced().empty())
7854          LHS->setIntroduced(Ctx, RHS->getIntroduced());
7855
7856        if (LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) {
7857          LHS->setDeprecated(Ctx, RHS->getDeprecated());
7858          if (LHS->getMessage().empty())
7859            LHS->setMessage(Ctx, RHS->getMessage());
7860          if (LHS->getReplacement().empty())
7861            LHS->setReplacement(Ctx, RHS->getReplacement());
7862        }
7863
7864        if (LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()) {
7865          LHS->setObsoleted(Ctx, RHS->getObsoleted());
7866          if (LHS->getMessage().empty())
7867            LHS->setMessage(Ctx, RHS->getMessage());
7868          if (LHS->getReplacement().empty())
7869            LHS->setReplacement(Ctx, RHS->getReplacement());
7870        }
7871
7872        return true;
7873      });
7874  AvailabilityAttrs.erase(It, AvailabilityAttrs.end());
7875}
7876
7877int clang_getCursorPlatformAvailability(CXCursor cursorint *always_deprecated,
7878                                        CXString *deprecated_message,
7879                                        int *always_unavailable,
7880                                        CXString *unavailable_message,
7881                                        CXPlatformAvailability *availability,
7882                                        int availability_size) {
7883  if (always_deprecated)
7884    *always_deprecated = 0;
7885  if (deprecated_message)
7886    *deprecated_message = cxstring::createEmpty();
7887  if (always_unavailable)
7888    *always_unavailable = 0;
7889  if (unavailable_message)
7890    *unavailable_message = cxstring::createEmpty();
7891
7892  if (!clang_isDeclaration(cursor.kind))
7893    return 0;
7894
7895  const Decl *D = cxcursor::getCursorDecl(cursor);
7896  if (!D)
7897    return 0;
7898
7899  SmallVector<AvailabilityAttr *, 8AvailabilityAttrs;
7900  getCursorPlatformAvailabilityForDecl(D, always_deprecated, deprecated_message,
7901                                       always_unavailable, unavailable_message,
7902                                       AvailabilityAttrs);
7903  for (const auto &Avail :
7904       llvm::enumerate(llvm::makeArrayRef(AvailabilityAttrs)
7905                           .take_front(availability_size))) {
7906    availability[Avail.index()].Platform =
7907        cxstring::createDup(Avail.value()->getPlatform()->getName());
7908    availability[Avail.index()].Introduced =
7909        convertVersion(Avail.value()->getIntroduced());
7910    availability[Avail.index()].Deprecated =
7911        convertVersion(Avail.value()->getDeprecated());
7912    availability[Avail.index()].Obsoleted =
7913        convertVersion(Avail.value()->getObsoleted());
7914    availability[Avail.index()].Unavailable = Avail.value()->getUnavailable();
7915    availability[Avail.index()].Message =
7916        cxstring::createDup(Avail.value()->getMessage());
7917  }
7918
7919  return AvailabilityAttrs.size();
7920}
7921
7922void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
7923  clang_disposeString(availability->Platform);
7924  clang_disposeString(availability->Message);
7925}
7926
7927CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
7928  if (clang_isDeclaration(cursor.kind))
7929    return getDeclLanguage(cxcursor::getCursorDecl(cursor));
7930
7931  return CXLanguage_Invalid;
7932}
7933
7934CXTLSKind clang_getCursorTLSKind(CXCursor cursor) {
7935  const Decl *D = cxcursor::getCursorDecl(cursor);
7936  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7937    switch (VD->getTLSKind()) {
7938    case VarDecl::TLS_None:
7939      return CXTLS_None;
7940    case VarDecl::TLS_Dynamic:
7941      return CXTLS_Dynamic;
7942    case VarDecl::TLS_Static:
7943      return CXTLS_Static;
7944    }
7945  }
7946
7947  return CXTLS_None;
7948}
7949
7950 /// If the given cursor is the "templated" declaration
7951 /// describing a class or function template, return the class or
7952 /// function template.
7953static const Decl *maybeGetTemplateCursor(const Decl *D) {
7954  if (!D)
7955    return nullptr;
7956
7957  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
7958    if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
7959      return FunTmpl;
7960
7961  if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
7962    if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
7963      return ClassTmpl;
7964
7965  return D;
7966}
7967
7968
7969enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
7970  StorageClass sc = SC_None;
7971  const Decl *D = getCursorDecl(C);
7972  if (D) {
7973    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7974      sc = FD->getStorageClass();
7975    } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7976      sc = VD->getStorageClass();
7977    } else {
7978      return CX_SC_Invalid;
7979    }
7980  } else {
7981    return CX_SC_Invalid;
7982  }
7983  switch (sc) {
7984  case SC_None:
7985    return CX_SC_None;
7986  case SC_Extern:
7987    return CX_SC_Extern;
7988  case SC_Static:
7989    return CX_SC_Static;
7990  case SC_PrivateExtern:
7991    return CX_SC_PrivateExtern;
7992  case SC_Auto:
7993    return CX_SC_Auto;
7994  case SC_Register:
7995    return CX_SC_Register;
7996  }
7997  llvm_unreachable("Unhandled storage class!");
7998}
7999
8000CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
8001  if (clang_isDeclaration(cursor.kind)) {
8002    if (const Decl *D = getCursorDecl(cursor)) {
8003      const DeclContext *DC = D->getDeclContext();
8004      if (!DC)
8005        return clang_getNullCursor();
8006
8007      return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)), 
8008                          getCursorTU(cursor));
8009    }
8010  }
8011  
8012  if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
8013    if (const Decl *D = getCursorDecl(cursor))
8014      return MakeCXCursor(DgetCursorTU(cursor));
8015  }
8016  
8017  return clang_getNullCursor();
8018}
8019
8020CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
8021  if (clang_isDeclaration(cursor.kind)) {
8022    if (const Decl *D = getCursorDecl(cursor)) {
8023      const DeclContext *DC = D->getLexicalDeclContext();
8024      if (!DC)
8025        return clang_getNullCursor();
8026
8027      return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)), 
8028                          getCursorTU(cursor));
8029    }
8030  }
8031
8032  // FIXME: Note that we can't easily compute the lexical context of a 
8033  // statement or expression, so we return nothing.
8034  return clang_getNullCursor();
8035}
8036
8037CXFile clang_getIncludedFile(CXCursor cursor) {
8038  if (cursor.kind != CXCursor_InclusionDirective)
8039    return nullptr;
8040
8041  const InclusionDirective *ID = getCursorInclusionDirective(cursor);
8042  return const_cast<FileEntry *>(ID->getFile());
8043}
8044
8045unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor Cunsigned reserved) {
8046  if (C.kind != CXCursor_ObjCPropertyDecl)
8047    return CXObjCPropertyAttr_noattr;
8048
8049  unsigned Result = CXObjCPropertyAttr_noattr;
8050  const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8051  ObjCPropertyDecl::PropertyAttributeKind Attr =
8052      PD->getPropertyAttributesAsWritten();
8053
8054#define SET_CXOBJCPROP_ATTR(A) \
8055  if (Attr & ObjCPropertyDecl::OBJC_PR_##A) \
8056    Result |= CXObjCPropertyAttr_##A
8057  SET_CXOBJCPROP_ATTR(readonly);
8058  SET_CXOBJCPROP_ATTR(getter);
8059  SET_CXOBJCPROP_ATTR(assign);
8060  SET_CXOBJCPROP_ATTR(readwrite);
8061  SET_CXOBJCPROP_ATTR(retain);
8062  SET_CXOBJCPROP_ATTR(copy);
8063  SET_CXOBJCPROP_ATTR(nonatomic);
8064  SET_CXOBJCPROP_ATTR(setter);
8065  SET_CXOBJCPROP_ATTR(atomic);
8066  SET_CXOBJCPROP_ATTR(weak);
8067  SET_CXOBJCPROP_ATTR(strong);
8068  SET_CXOBJCPROP_ATTR(unsafe_unretained);
8069  SET_CXOBJCPROP_ATTR(class);
8070#undef SET_CXOBJCPROP_ATTR
8071
8072  return Result;
8073}
8074
8075CXString clang_Cursor_getObjCPropertyGetterName(CXCursor C) {
8076  if (C.kind != CXCursor_ObjCPropertyDecl)
8077    return cxstring::createNull();
8078
8079  const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8080  Selector sel = PD->getGetterName();
8081  if (sel.isNull())
8082    return cxstring::createNull();
8083
8084  return cxstring::createDup(sel.getAsString());
8085}
8086
8087CXString clang_Cursor_getObjCPropertySetterName(CXCursor C) {
8088  if (C.kind != CXCursor_ObjCPropertyDecl)
8089    return cxstring::createNull();
8090
8091  const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
8092  Selector sel = PD->getSetterName();
8093  if (sel.isNull())
8094    return cxstring::createNull();
8095
8096  return cxstring::createDup(sel.getAsString());
8097}
8098
8099unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
8100  if (!clang_isDeclaration(C.kind))
8101    return CXObjCDeclQualifier_None;
8102
8103  Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
8104  const Decl *D = getCursorDecl(C);
8105  if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8106    QT = MD->getObjCDeclQualifier();
8107  else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
8108    QT = PD->getObjCDeclQualifier();
8109  if (QT == Decl::OBJC_TQ_None)
8110    return CXObjCDeclQualifier_None;
8111
8112  unsigned Result = CXObjCDeclQualifier_None;
8113  if (QT & Decl::OBJC_TQ_InResult |= CXObjCDeclQualifier_In;
8114  if (QT & Decl::OBJC_TQ_InoutResult |= CXObjCDeclQualifier_Inout;
8115  if (QT & Decl::OBJC_TQ_OutResult |= CXObjCDeclQualifier_Out;
8116  if (QT & Decl::OBJC_TQ_BycopyResult |= CXObjCDeclQualifier_Bycopy;
8117  if (QT & Decl::OBJC_TQ_ByrefResult |= CXObjCDeclQualifier_Byref;
8118  if (QT & Decl::OBJC_TQ_OnewayResult |= CXObjCDeclQualifier_Oneway;
8119
8120  return Result;
8121}
8122
8123unsigned clang_Cursor_isObjCOptional(CXCursor C) {
8124  if (!clang_isDeclaration(C.kind))
8125    return 0;
8126
8127  const Decl *D = getCursorDecl(C);
8128  if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
8129    return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
8130  if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8131    return MD->getImplementationControl() == ObjCMethodDecl::Optional;
8132
8133  return 0;
8134}
8135
8136unsigned clang_Cursor_isVariadic(CXCursor C) {
8137  if (!clang_isDeclaration(C.kind))
8138    return 0;
8139
8140  const Decl *D = getCursorDecl(C);
8141  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
8142    return FD->isVariadic();
8143  if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
8144    return MD->isVariadic();
8145
8146  return 0;
8147}
8148
8149unsigned clang_Cursor_isExternalSymbol(CXCursor C,
8150                                     CXString *languageCXString *definedIn,
8151                                     unsigned *isGenerated) {
8152  if (!clang_isDeclaration(C.kind))
8153    return 0;
8154
8155  const Decl *D = getCursorDecl(C);
8156
8157  if (auto *attr = D->getExternalSourceSymbolAttr()) {
8158    if (language)
8159      *language = cxstring::createDup(attr->getLanguage());
8160    if (definedIn)
8161      *definedIn = cxstring::createDup(attr->getDefinedIn());
8162    if (isGenerated)
8163      *isGenerated = attr->getGeneratedDeclaration();
8164    return 1;
8165  }
8166  return 0;
8167}
8168
8169CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
8170  if (!clang_isDeclaration(C.kind))
8171    return clang_getNullRange();
8172
8173  const Decl *D = getCursorDecl(C);
8174  ASTContext &Context = getCursorContext(C);
8175  const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8176  if (!RC)
8177    return clang_getNullRange();
8178
8179  return cxloc::translateSourceRange(ContextRC->getSourceRange());
8180}
8181
8182CXString clang_Cursor_getRawCommentText(CXCursor C) {
8183  if (!clang_isDeclaration(C.kind))
8184    return cxstring::createNull();
8185
8186  const Decl *D = getCursorDecl(C);
8187  ASTContext &Context = getCursorContext(C);
8188  const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8189  StringRef RawText = RC ? RC->getRawText(Context.getSourceManager()) :
8190                           StringRef();
8191
8192  // Don't duplicate the string because RawText points directly into source
8193  // code.
8194  return cxstring::createRef(RawText);
8195}
8196
8197CXString clang_Cursor_getBriefCommentText(CXCursor C) {
8198  if (!clang_isDeclaration(C.kind))
8199    return cxstring::createNull();
8200
8201  const Decl *D = getCursorDecl(C);
8202  const ASTContext &Context = getCursorContext(C);
8203  const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
8204
8205  if (RC) {
8206    StringRef BriefText = RC->getBriefText(Context);
8207
8208    // Don't duplicate the string because RawComment ensures that this memory
8209    // will not go away.
8210    return cxstring::createRef(BriefText);
8211  }
8212
8213  return cxstring::createNull();
8214}
8215
8216CXModule clang_Cursor_getModule(CXCursor C) {
8217  if (C.kind == CXCursor_ModuleImportDecl) {
8218    if (const ImportDecl *ImportD =
8219            dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
8220      return ImportD->getImportedModule();
8221  }
8222
8223  return nullptr;
8224}
8225
8226CXModule clang_getModuleForFile(CXTranslationUnit TUCXFile File) {
8227  if (isNotUsableTU(TU)) {
8228    LOG_BAD_TU(TU);
8229    return nullptr;
8230  }
8231  if (!File)
8232    return nullptr;
8233  FileEntry *FE = static_cast<FileEntry *>(File);
8234  
8235  ASTUnit &Unit = *cxtu::getASTUnit(TU);
8236  HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
8237  ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
8238  
8239  return Header.getModule();
8240}
8241
8242CXFile clang_Module_getASTFile(CXModule CXMod) {
8243  if (!CXMod)
8244    return nullptr;
8245  Module *Mod = static_cast<Module*>(CXMod);
8246  return const_cast<FileEntry *>(Mod->getASTFile());
8247}
8248
8249CXModule clang_Module_getParent(CXModule CXMod) {
8250  if (!CXMod)
8251    return nullptr;
8252  Module *Mod = static_cast<Module*>(CXMod);
8253  return Mod->Parent;
8254}
8255
8256CXString clang_Module_getName(CXModule CXMod) {
8257  if (!CXMod)
8258    return cxstring::createEmpty();
8259  Module *Mod = static_cast<Module*>(CXMod);
8260  return cxstring::createDup(Mod->Name);
8261}
8262
8263CXString clang_Module_getFullName(CXModule CXMod) {
8264  if (!CXMod)
8265    return cxstring::createEmpty();
8266  Module *Mod = static_cast<Module*>(CXMod);
8267  return cxstring::createDup(Mod->getFullModuleName());
8268}
8269
8270int clang_Module_isSystem(CXModule CXMod) {
8271  if (!CXMod)
8272    return 0;
8273  Module *Mod = static_cast<Module*>(CXMod);
8274  return Mod->IsSystem;
8275}
8276
8277unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
8278                                            CXModule CXMod) {
8279  if (isNotUsableTU(TU)) {
8280    LOG_BAD_TU(TU);
8281    return 0;
8282  }
8283  if (!CXMod)
8284    return 0;
8285  Module *Mod = static_cast<Module*>(CXMod);
8286  FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
8287  ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8288  return TopHeaders.size();
8289}
8290
8291CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU,
8292                                      CXModule CXModunsigned Index) {
8293  if (isNotUsableTU(TU)) {
8294    LOG_BAD_TU(TU);
8295    return nullptr;
8296  }
8297  if (!CXMod)
8298    return nullptr;
8299  Module *Mod = static_cast<Module*>(CXMod);
8300  FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
8301
8302  ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
8303  if (Index < TopHeaders.size())
8304    return const_cast<FileEntry *>(TopHeaders[Index]);
8305
8306  return nullptr;
8307}
8308
8309//===----------------------------------------------------------------------===//
8310// C++ AST instrospection.
8311//===----------------------------------------------------------------------===//
8312
8313unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) {
8314  if (!clang_isDeclaration(C.kind))
8315    return 0;
8316
8317  const Decl *D = cxcursor::getCursorDecl(C);
8318  const CXXConstructorDecl *Constructor =
8319      D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8320  return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0;
8321}
8322
8323unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) {
8324  if (!clang_isDeclaration(C.kind))
8325    return 0;
8326
8327  const Decl *D = cxcursor::getCursorDecl(C);
8328  const CXXConstructorDecl *Constructor =
8329      D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8330  return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0;
8331}
8332
8333unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) {
8334  if (!clang_isDeclaration(C.kind))
8335    return 0;
8336
8337  const Decl *D = cxcursor::getCursorDecl(C);
8338  const CXXConstructorDecl *Constructor =
8339      D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8340  return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
8341}
8342
8343unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) {
8344  if (!clang_isDeclaration(C.kind))
8345    return 0;
8346
8347  const Decl *D = cxcursor::getCursorDecl(C);
8348  const CXXConstructorDecl *Constructor =
8349      D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
8350  // Passing 'false' excludes constructors marked 'explicit'.
8351  return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
8352}
8353
8354unsigned clang_CXXField_isMutable(CXCursor C) {
8355  if (!clang_isDeclaration(C.kind))
8356    return 0;
8357
8358  if (const auto D = cxcursor::getCursorDecl(C))
8359    if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
8360      return FD->isMutable() ? 1 : 0;
8361  return 0;
8362}
8363
8364unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
8365  if (!clang_isDeclaration(C.kind))
8366    return 0;
8367
8368  const Decl *D = cxcursor::getCursorDecl(C);
8369  const CXXMethodDecl *Method =
8370      D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
8371  return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
8372}
8373
8374unsigned clang_CXXMethod_isConst(CXCursor C) {
8375  if (!clang_isDeclaration(C.kind))
8376    return 0;
8377
8378  const Decl *D = cxcursor::getCursorDecl(C);
8379  const CXXMethodDecl *Method =
8380      D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
8381  return (Method && Method->getMethodQualifiers().hasConst()) ? 1 : 0;
8382}
8383
8384unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
8385  if (!clang_isDeclaration(C.kind))
8386    return 0;
8387
8388  const Decl *D = cxcursor::getCursorDecl(C);
8389  const CXXMethodDecl *Method =
8390      D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
8391  return (Method && Method->isDefaulted()) ? 1 : 0;
8392}
8393
8394unsigned clang_CXXMethod_isStatic(CXCursor C) {
8395  if (!clang_isDeclaration(C.kind))
8396    return 0;
8397  
8398  const Decl *D = cxcursor::getCursorDecl(C);
8399  const CXXMethodDecl *Method =
8400      D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
8401  return (Method && Method->isStatic()) ? 1 : 0;
8402}
8403
8404unsigned clang_CXXMethod_isVirtual(CXCursor C) {
8405  if (!clang_isDeclaration(C.kind))
8406    return 0;
8407  
8408  const Decl *D = cxcursor::getCursorDecl(C);
8409  const CXXMethodDecl *Method =
8410      D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
8411  return (Method && Method->isVirtual()) ? 1 : 0;
8412}
8413
8414unsigned clang_CXXRecord_isAbstract(CXCursor C) {
8415  if (!clang_isDeclaration(C.kind))
8416    return 0;
8417
8418  const auto *D = cxcursor::getCursorDecl(C);
8419  const auto *RD = dyn_cast_or_null<CXXRecordDecl>(D);
8420  if (RD)
8421    RD = RD->getDefinition();
8422  return (RD && RD->isAbstract()) ? 1 : 0;
8423}
8424
8425unsigned clang_EnumDecl_isScoped(CXCursor C) {
8426  if (!clang_isDeclaration(C.kind))
8427    return 0;
8428
8429  const Decl *D = cxcursor::getCursorDecl(C);
8430  auto *Enum = dyn_cast_or_null<EnumDecl>(D);
8431  return (Enum && Enum->isScoped()) ? 1 : 0;
8432}
8433
8434//===----------------------------------------------------------------------===//
8435// Attribute introspection.
8436//===----------------------------------------------------------------------===//
8437
8438CXType clang_getIBOutletCollectionType(CXCursor C) {
8439  if (C.kind != CXCursor_IBOutletCollectionAttr)
8440    return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
8441  
8442  const IBOutletCollectionAttr *A =
8443    cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
8444  
8445  return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));  
8446}
8447
8448//===----------------------------------------------------------------------===//
8449// Inspecting memory usage.
8450//===----------------------------------------------------------------------===//
8451
8452typedef std::vector<CXTUResourceUsageEntryMemUsageEntries;
8453
8454static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
8455                                              enum CXTUResourceUsageKind k,
8456                                              unsigned long amount) {
8457  CXTUResourceUsageEntry entry = { kamount };
8458  entries.push_back(entry);
8459}
8460
8461const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
8462  const char *str = "";
8463  switch (kind) {
8464    case CXTUResourceUsage_AST:
8465      str = "ASTContext: expressions, declarations, and types"
8466      break;
8467    case CXTUResourceUsage_Identifiers:
8468      str = "ASTContext: identifiers";
8469      break;
8470    case CXTUResourceUsage_Selectors:
8471      str = "ASTContext: selectors";
8472      break;
8473    case CXTUResourceUsage_GlobalCompletionResults:
8474      str = "Code completion: cached global results";
8475      break;
8476    case CXTUResourceUsage_SourceManagerContentCache:
8477      str = "SourceManager: content cache allocator";
8478      break;
8479    case CXTUResourceUsage_AST_SideTables:
8480      str = "ASTContext: side tables";
8481      break;
8482    case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
8483      str = "SourceManager: malloc'ed memory buffers";
8484      break;
8485    case CXTUResourceUsage_SourceManager_Membuffer_MMap:
8486      str = "SourceManager: mmap'ed memory buffers";
8487      break;
8488    case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
8489      str = "ExternalASTSource: malloc'ed memory buffers";
8490      break;
8491    case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
8492      str = "ExternalASTSource: mmap'ed memory buffers";
8493      break;
8494    case CXTUResourceUsage_Preprocessor:
8495      str = "Preprocessor: malloc'ed memory";
8496      break;
8497    case CXTUResourceUsage_PreprocessingRecord:
8498      str = "Preprocessor: PreprocessingRecord";
8499      break;
8500    case CXTUResourceUsage_SourceManager_DataStructures:
8501      str = "SourceManager: data structures and tables";
8502      break;
8503    case CXTUResourceUsage_Preprocessor_HeaderSearch:
8504      str = "Preprocessor: header search tables";
8505      break;
8506  }
8507  return str;
8508}
8509
8510CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
8511  if (isNotUsableTU(TU)) {
8512    LOG_BAD_TU(TU);
8513    CXTUResourceUsage usage = { (void*) nullptr0nullptr };
8514    return usage;
8515  }
8516  
8517  ASTUnit *astUnit = cxtu::getASTUnit(TU);
8518  std::unique_ptr<MemUsageEntriesentries(new MemUsageEntries());
8519  ASTContext &astContext = astUnit->getASTContext();
8520  
8521  // How much memory is used by AST nodes and types?
8522  createCXTUResourceUsageEntry(*entriesCXTUResourceUsage_AST,
8523    (unsigned longastContext.getASTAllocatedMemory());
8524
8525  // How much memory is used by identifiers?
8526  createCXTUResourceUsageEntry(*entriesCXTUResourceUsage_Identifiers,
8527    (unsigned longastContext.Idents.getAllocator().getTotalMemory());
8528
8529  // How much memory is used for selectors?
8530  createCXTUResourceUsageEntry(*entriesCXTUResourceUsage_Selectors,
8531    (unsigned longastContext.Selectors.getTotalMemory());
8532  
8533  // How much memory is used by ASTContext's side tables?
8534  createCXTUResourceUsageEntry(*entriesCXTUResourceUsage_AST_SideTables,
8535    (unsigned longastContext.getSideTableAllocatedMemory());
8536  
8537  // How much memory is used for caching global code completion results?
8538  unsigned long completionBytes = 0;
8539  if (GlobalCodeCompletionAllocator *completionAllocator =
8540      astUnit->getCachedCompletionAllocator().get()) {
8541    completionBytes = completionAllocator->getTotalMemory();
8542  }
8543  createCXTUResourceUsageEntry(*entries,
8544                               CXTUResourceUsage_GlobalCompletionResults,
8545                               completionBytes);
8546  
8547  // How much memory is being used by SourceManager's content cache?
8548  createCXTUResourceUsageEntry(*entries,
8549          CXTUResourceUsage_SourceManagerContentCache,
8550          (unsigned longastContext.getSourceManager().getContentCacheSize());
8551  
8552  // How much memory is being used by the MemoryBuffer's in SourceManager?
8553  const SourceManager::MemoryBufferSizes &srcBufs =
8554    astUnit->getSourceManager().getMemoryBufferSizes();
8555  
8556  createCXTUResourceUsageEntry(*entries,
8557                               CXTUResourceUsage_SourceManager_Membuffer_Malloc,
8558                               (unsigned longsrcBufs.malloc_bytes);
8559  createCXTUResourceUsageEntry(*entries,
8560                               CXTUResourceUsage_SourceManager_Membuffer_MMap,
8561                               (unsigned longsrcBufs.mmap_bytes);
8562  createCXTUResourceUsageEntry(*entries,
8563                               CXTUResourceUsage_SourceManager_DataStructures,
8564                               (unsigned longastContext.getSourceManager()
8565                                .getDataStructureSizes());
8566  
8567  // How much memory is being used by the ExternalASTSource?
8568  if (ExternalASTSource *esrc = astContext.getExternalSource()) {
8569    const ExternalASTSource::MemoryBufferSizes &sizes =
8570      esrc->getMemoryBufferSizes();
8571    
8572    createCXTUResourceUsageEntry(*entries,
8573      CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
8574                                 (unsigned longsizes.malloc_bytes);
8575    createCXTUResourceUsageEntry(*entries,
8576      CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
8577                                 (unsigned longsizes.mmap_bytes);
8578  }
8579  
8580  // How much memory is being used by the Preprocessor?
8581  Preprocessor &pp = astUnit->getPreprocessor();
8582  createCXTUResourceUsageEntry(*entries,
8583                               CXTUResourceUsage_Preprocessor,
8584                               pp.getTotalMemory());
8585  
8586  if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
8587    createCXTUResourceUsageEntry(*entries,
8588                                 CXTUResourceUsage_PreprocessingRecord,
8589                                 pRec->getTotalMemory());    
8590  }
8591  
8592  createCXTUResourceUsageEntry(*entries,
8593                               CXTUResourceUsage_Preprocessor_HeaderSearch,
8594                               pp.getHeaderSearchInfo().getTotalMemory());
8595
8596  CXTUResourceUsage usage = { (void*) entries.get(),
8597                            (unsignedentries->size(),
8598                            !entries->empty() ? &(*entries)[0] : nullptr };
8599  (void)entries.release();
8600  return usage;
8601}
8602
8603void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
8604  if (usage.data)
8605    delete (MemUsageEntries*) usage.data;
8606}
8607
8608CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TUCXFile file) {
8609  CXSourceRangeList *skipped = new CXSourceRangeList;
8610  skipped->count = 0;
8611  skipped->ranges = nullptr;
8612
8613  if (isNotUsableTU(TU)) {
8614    LOG_BAD_TU(TU);
8615    return skipped;
8616  }
8617
8618  if (!file)
8619    return skipped;
8620
8621  ASTUnit *astUnit = cxtu::getASTUnit(TU);
8622  PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8623  if (!ppRec)
8624    return skipped;
8625
8626  ASTContext &Ctx = astUnit->getASTContext();
8627  SourceManager &sm = Ctx.getSourceManager();
8628  FileEntry *fileEntry = static_cast<FileEntry *>(file);
8629  FileID wantedFileID = sm.translateFile(fileEntry);
8630  bool isMainFile = wantedFileID == sm.getMainFileID();
8631
8632  const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8633  std::vector<SourceRangewantedRanges;
8634  for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(), ei = SkippedRanges.end();
8635       i != ei; ++i) {
8636    if (sm.getFileID(i->getBegin()) == wantedFileID || sm.getFileID(i->getEnd()) == wantedFileID)
8637      wantedRanges.push_back(*i);
8638    else if (isMainFile && (astUnit->isInPreambleFileID(i->getBegin()) || astUnit->isInPreambleFileID(i->getEnd())))
8639      wantedRanges.push_back(*i);
8640  }
8641
8642  skipped->count = wantedRanges.size();
8643  skipped->ranges = new CXSourceRange[skipped->count];
8644  for (unsigned i = 0ei = skipped->counti != ei; ++i)
8645    skipped->ranges[i] = cxloc::translateSourceRange(CtxwantedRanges[i]);
8646
8647  return skipped;
8648}
8649
8650CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) {
8651  CXSourceRangeList *skipped = new CXSourceRangeList;
8652  skipped->count = 0;
8653  skipped->ranges = nullptr;
8654
8655  if (isNotUsableTU(TU)) {
8656    LOG_BAD_TU(TU);
8657    return skipped;
8658  }
8659    
8660  ASTUnit *astUnit = cxtu::getASTUnit(TU);
8661  PreprocessingRecord *ppRec = astUnit->getPreprocessor().getPreprocessingRecord();
8662  if (!ppRec)
8663    return skipped;
8664
8665  ASTContext &Ctx = astUnit->getASTContext();
8666
8667  const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
8668
8669  skipped->count = SkippedRanges.size();
8670  skipped->ranges = new CXSourceRange[skipped->count];
8671  for (unsigned i = 0ei = skipped->counti != ei; ++i)
8672    skipped->ranges[i] = cxloc::translateSourceRange(CtxSkippedRanges[i]);
8673
8674  return skipped;
8675}
8676
8677void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
8678  if (ranges) {
8679    delete[] ranges->ranges;
8680    delete ranges;
8681  }
8682}
8683
8684void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
8685  CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
8686  for (unsigned I = 0I != Usage.numEntries; ++I)
8687    fprintf(stderr"  %s: %lu\n"
8688            clang_getTUResourceUsageName(Usage.entries[I].kind),
8689            Usage.entries[I].amount);
8690  
8691  clang_disposeCXTUResourceUsage(Usage);
8692}
8693
8694//===----------------------------------------------------------------------===//
8695// Misc. utility functions.
8696//===----------------------------------------------------------------------===//
8697
8698/// Default to using our desired 8 MB stack size on "safety" threads.
8699static unsigned SafetyStackThreadSize = DesiredStackSize;
8700
8701namespace clang {
8702
8703bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
8704               unsigned Size) {
8705  if (!Size)
8706    Size = GetSafetyThreadStackSize();
8707  if (Size && !getenv("LIBCLANG_NOTHREADS"))
8708    return CRC.RunSafelyOnThread(Fn, Size);
8709  return CRC.RunSafely(Fn);
8710}
8711
8712unsigned GetSafetyThreadStackSize() {
8713  return SafetyStackThreadSize;
8714}
8715
8716void SetSafetyThreadStackSize(unsigned Value) {
8717  SafetyStackThreadSize = Value;
8718}
8719
8720}
8721
8722void clang::setThreadBackgroundPriority() {
8723  if (getenv("LIBCLANG_BGPRIO_DISABLE"))
8724    return;
8725
8726#ifdef USE_DARWIN_THREADS
8727  setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
8728#endif
8729}
8730
8731void cxindex::printDiagsToStderr(ASTUnit *Unit) {
8732  if (!Unit)
8733    return;
8734
8735  for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(), 
8736                                  DEnd = Unit->stored_diag_end();
8737       D != DEnd; ++D) {
8738    CXStoredDiagnostic Diag(*DUnit->getLangOpts());
8739    CXString Msg = clang_formatDiagnostic(&Diag,
8740                                clang_defaultDiagnosticDisplayOptions());
8741    fprintf(stderr"%s\n"clang_getCString(Msg));
8742    clang_disposeString(Msg);
8743  }
8744#ifdef _WIN32
8745  // On Windows, force a flush, since there may be multiple copies of
8746  // stderr and stdout in the file system, all with different buffers
8747  // but writing to the same device.
8748  fflush(stderr);
8749#endif
8750}
8751
8752MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
8753                                 SourceLocation MacroDefLoc,
8754                                 CXTranslationUnit TU){
8755  if (MacroDefLoc.isInvalid() || !TU)
8756    return nullptr;
8757  if (!II.hadMacroDefinition())
8758    return nullptr;
8759
8760  ASTUnit *Unit = cxtu::getASTUnit(TU);
8761  Preprocessor &PP = Unit->getPreprocessor();
8762  MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
8763  if (MD) {
8764    for (MacroDirective::DefInfo
8765           Def = MD->getDefinition(); DefDef = Def.getPreviousDefinition()) {
8766      if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
8767        return Def.getMacroInfo();
8768    }
8769  }
8770
8771  return nullptr;
8772}
8773
8774const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
8775                                       CXTranslationUnit TU) {
8776  if (!MacroDef || !TU)
8777    return nullptr;
8778  const IdentifierInfo *II = MacroDef->getName();
8779  if (!II)
8780    return nullptr;
8781
8782  return getMacroInfo(*IIMacroDef->getLocation(), TU);
8783}
8784
8785MacroDefinitionRecord *
8786cxindex::checkForMacroInMacroDefinition(const MacroInfo *MIconst Token &Tok,
8787                                        CXTranslationUnit TU) {
8788  if (!MI || !TU)
8789    return nullptr;
8790  if (Tok.isNot(tok::raw_identifier))
8791    return nullptr;
8792
8793  if (MI->getNumTokens() == 0)
8794    return nullptr;
8795  SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
8796                       MI->getDefinitionEndLoc());
8797  ASTUnit *Unit = cxtu::getASTUnit(TU);
8798
8799  // Check that the token is inside the definition and not its argument list.
8800  SourceManager &SM = Unit->getSourceManager();
8801  if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
8802    return nullptr;
8803  if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
8804    return nullptr;
8805
8806  Preprocessor &PP = Unit->getPreprocessor();
8807  PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
8808  if (!PPRec)
8809    return nullptr;
8810
8811  IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
8812  if (!II.hadMacroDefinition())
8813    return nullptr;
8814
8815  // Check that the identifier is not one of the macro arguments.
8816  if (std::find(MI->param_begin(), MI->param_end(), &II) != MI->param_end())
8817    return nullptr;
8818
8819  MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
8820  if (!InnerMD)
8821    return nullptr;
8822
8823  return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
8824}
8825
8826MacroDefinitionRecord *
8827cxindex::checkForMacroInMacroDefinition(const MacroInfo *MISourceLocation Loc,
8828                                        CXTranslationUnit TU) {
8829  if (Loc.isInvalid() || !MI || !TU)
8830    return nullptr;
8831
8832  if (MI->getNumTokens() == 0)
8833    return nullptr;
8834  ASTUnit *Unit = cxtu::getASTUnit(TU);
8835  Preprocessor &PP = Unit->getPreprocessor();
8836  if (!PP.getPreprocessingRecord())
8837    return nullptr;
8838  Loc = Unit->getSourceManager().getSpellingLoc(Loc);
8839  Token Tok;
8840  if (PP.getRawToken(LocTok))
8841    return nullptr;
8842
8843  return checkForMacroInMacroDefinition(MITokTU);
8844}
8845
8846CXString clang_getClangVersion() {
8847  return cxstring::createDup(getClangFullVersion());
8848}
8849
8850Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
8851  if (TU) {
8852    if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
8853      LogOS << '<' << Unit->getMainFileName() << '>';
8854      if (Unit->isMainFileAST())
8855        LogOS << " (" << Unit->getASTFileName() << ')';
8856      return *this;
8857    }
8858  } else {
8859    LogOS << "<NULL TU>";
8860  }
8861  return *this;
8862}
8863
8864Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
8865  *this << FE->getName();
8866  return *this;
8867}
8868
8869Logger &cxindex::Logger::operator<<(CXCursor cursor) {
8870  CXString cursorName = clang_getCursorDisplayName(cursor);
8871  *this << cursorName << "@" << clang_getCursorLocation(cursor);
8872  clang_disposeString(cursorName);
8873  return *this;
8874}
8875
8876Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
8877  CXFile File;
8878  unsigned LineColumn;
8879  clang_getFileLocation(Loc, &File, &Line, &Columnnullptr);
8880  CXString FileName = clang_getFileName(File);
8881  *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
8882  clang_disposeString(FileName);
8883  return *this;
8884}
8885
8886Logger &cxindex::Logger::operator<<(CXSourceRange range) {
8887  CXSourceLocation BLoc = clang_getRangeStart(range);
8888  CXSourceLocation ELoc = clang_getRangeEnd(range);
8889
8890  CXFile BFile;
8891  unsigned BLineBColumn;
8892  clang_getFileLocation(BLoc, &BFile, &BLine, &BColumnnullptr);
8893
8894  CXFile EFile;
8895  unsigned ELineEColumn;
8896  clang_getFileLocation(ELoc, &EFile, &ELine, &EColumnnullptr);
8897
8898  CXString BFileName = clang_getFileName(BFile);
8899  if (BFile == EFile) {
8900    *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
8901                         BLine, BColumn, ELine, EColumn);
8902  } else {
8903    CXString EFileName = clang_getFileName(EFile);
8904    *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName),
8905                          BLine, BColumn)
8906          << llvm::format("%s:%d:%d]", clang_getCString(EFileName),
8907                          ELine, EColumn);
8908    clang_disposeString(EFileName);
8909  }
8910  clang_disposeString(BFileName);
8911  return *this;
8912}
8913
8914Logger &cxindex::Logger::operator<<(CXString Str) {
8915  *this << clang_getCString(Str);
8916  return *this;
8917}
8918
8919Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
8920  LogOS << Fmt;
8921  return *this;
8922}
8923
8924static llvm::ManagedStatic<llvm::sys::Mutex> LoggingMutex;
8925
8926cxindex::Logger::~Logger() {
8927  llvm::sys::ScopedLock L(*LoggingMutex);
8928
8929  static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
8930
8931  raw_ostream &OS = llvm::errs();
8932  OS << "[libclang:" << Name << ':';
8933
8934#ifdef USE_DARWIN_THREADS
8935  // TODO: Portability.
8936  mach_port_t tid = pthread_mach_thread_np(pthread_self());
8937  OS << tid << ':';
8938#endif
8939
8940  llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
8941  OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
8942  OS << Msg << '\n';
8943
8944  if (Trace) {
8945    llvm::sys::PrintStackTrace(OS);
8946    OS << "--------------------------------------------------\n";
8947  }
8948}
8949
8950#ifdef CLANG_TOOL_EXTRA_BUILD
8951// This anchor is used to force the linker to link the clang-tidy plugin.
8952extern volatile int ClangTidyPluginAnchorSource;
8953static int LLVM_ATTRIBUTE_UNUSED ClangTidyPluginAnchorDestination =
8954    ClangTidyPluginAnchorSource;
8955
8956// This anchor is used to force the linker to link the clang-include-fixer
8957// plugin.
8958extern volatile int ClangIncludeFixerPluginAnchorSource;
8959static int LLVM_ATTRIBUTE_UNUSED ClangIncludeFixerPluginAnchorDestination =
8960    ClangIncludeFixerPluginAnchorSource;
8961#endif
8962
clang::cxcursor::CursorVisitor::CompareRegionOfInterest
clang::cxcursor::CursorVisitor::Visit
clang::cxcursor::CursorVisitor::visitFileRegion
clang::cxcursor::CursorVisitor::visitDeclsFromFileRegion
clang::cxcursor::CursorVisitor::visitPreprocessedEntitiesInRegion
clang::cxcursor::CursorVisitor::visitPreprocessedEntities
clang::cxcursor::CursorVisitor::VisitChildren
clang::cxcursor::CursorVisitor::VisitBlockDecl
clang::cxcursor::CursorVisitor::shouldVisitCursor
clang::cxcursor::CursorVisitor::VisitDeclContext
clang::cxcursor::CursorVisitor::handleDeclForVisitation
clang::cxcursor::CursorVisitor::VisitTranslationUnitDecl
clang::cxcursor::CursorVisitor::VisitTypeAliasTemplateDecl
clang::cxcursor::CursorVisitor::VisitTypeAliasDecl
clang::cxcursor::CursorVisitor::VisitTypedefDecl
clang::cxcursor::CursorVisitor::VisitTagDecl
clang::cxcursor::CursorVisitor::VisitClassTemplateSpecializationDecl
clang::cxcursor::CursorVisitor::VisitClassTemplatePartialSpecializationDecl
clang::cxcursor::CursorVisitor::VisitTemplateTypeParmDecl
clang::cxcursor::CursorVisitor::VisitEnumConstantDecl
clang::cxcursor::CursorVisitor::VisitDeclaratorDecl
clang::cxcursor::CursorVisitor::VisitFunctionDecl
clang::cxcursor::CursorVisitor::VisitFieldDecl
clang::cxcursor::CursorVisitor::VisitVarDecl
clang::cxcursor::CursorVisitor::VisitNonTypeTemplateParmDecl
clang::cxcursor::CursorVisitor::VisitFunctionTemplateDecl
clang::cxcursor::CursorVisitor::VisitClassTemplateDecl
clang::cxcursor::CursorVisitor::VisitTemplateTemplateParmDecl
clang::cxcursor::CursorVisitor::VisitObjCTypeParamDecl
clang::cxcursor::CursorVisitor::VisitObjCMethodDecl
clang::cxcursor::CursorVisitor::VisitObjCContainerDecl
clang::cxcursor::CursorVisitor::VisitObjCCategoryDecl
clang::cxcursor::CursorVisitor::VisitObjCProtocolDecl
clang::cxcursor::CursorVisitor::VisitObjCPropertyDecl
clang::cxcursor::CursorVisitor::VisitObjCTypeParamList
clang::cxcursor::CursorVisitor::VisitObjCInterfaceDecl
clang::cxcursor::CursorVisitor::VisitObjCImplDecl
clang::cxcursor::CursorVisitor::VisitObjCCategoryImplDecl
clang::cxcursor::CursorVisitor::VisitObjCImplementationDecl
clang::cxcursor::CursorVisitor::VisitObjCPropertyImplDecl
clang::cxcursor::CursorVisitor::VisitNamespaceDecl
clang::cxcursor::CursorVisitor::VisitNamespaceAliasDecl
clang::cxcursor::CursorVisitor::VisitUsingDecl
clang::cxcursor::CursorVisitor::VisitUsingDirectiveDecl
clang::cxcursor::CursorVisitor::VisitUnresolvedUsingValueDecl
clang::cxcursor::CursorVisitor::VisitUnresolvedUsingTypenameDecl
clang::cxcursor::CursorVisitor::VisitStaticAssertDecl
clang::cxcursor::CursorVisitor::VisitFriendDecl
clang::cxcursor::CursorVisitor::VisitDeclarationNameInfo
clang::cxcursor::CursorVisitor::VisitNestedNameSpecifier
clang::cxcursor::CursorVisitor::VisitNestedNameSpecifierLoc
clang::cxcursor::CursorVisitor::VisitTemplateParameters
clang::cxcursor::CursorVisitor::VisitTemplateName
clang::cxcursor::CursorVisitor::VisitTemplateArgumentLoc
clang::cxcursor::CursorVisitor::VisitLinkageSpecDecl
clang::cxcursor::CursorVisitor::VisitQualifiedTypeLoc
clang::cxcursor::CursorVisitor::VisitBuiltinTypeLoc
clang::cxcursor::CursorVisitor::VisitTypedefTypeLoc
clang::cxcursor::CursorVisitor::VisitUnresolvedUsingTypeLoc
clang::cxcursor::CursorVisitor::VisitTagTypeLoc
clang::cxcursor::CursorVisitor::VisitTemplateTypeParmTypeLoc
clang::cxcursor::CursorVisitor::VisitObjCInterfaceTypeLoc
clang::cxcursor::CursorVisitor::VisitObjCTypeParamTypeLoc
clang::cxcursor::CursorVisitor::VisitObjCObjectTypeLoc
clang::cxcursor::CursorVisitor::VisitObjCObjectPointerTypeLoc
clang::cxcursor::CursorVisitor::VisitParenTypeLoc
clang::cxcursor::CursorVisitor::VisitPointerTypeLoc
clang::cxcursor::CursorVisitor::VisitBlockPointerTypeLoc
clang::cxcursor::CursorVisitor::VisitMemberPointerTypeLoc
clang::cxcursor::CursorVisitor::VisitLValueReferenceTypeLoc
clang::cxcursor::CursorVisitor::VisitRValueReferenceTypeLoc
clang::cxcursor::CursorVisitor::VisitAttributedTypeLoc
clang::cxcursor::CursorVisitor::VisitFunctionTypeLoc
clang::cxcursor::CursorVisitor::VisitArrayTypeLoc
clang::cxcursor::CursorVisitor::VisitDecayedTypeLoc
clang::cxcursor::CursorVisitor::VisitAdjustedTypeLoc
clang::cxcursor::CursorVisitor::VisitDeducedTemplateSpecializationTypeLoc
clang::cxcursor::CursorVisitor::VisitTemplateSpecializationTypeLoc
clang::cxcursor::CursorVisitor::VisitTypeOfExprTypeLoc
clang::cxcursor::CursorVisitor::VisitTypeOfTypeLoc
clang::cxcursor::CursorVisitor::VisitUnaryTransformTypeLoc
clang::cxcursor::CursorVisitor::VisitDependentNameTypeLoc
clang::cxcursor::CursorVisitor::VisitDependentTemplateSpecializationTypeLoc
clang::cxcursor::CursorVisitor::VisitElaboratedTypeLoc
clang::cxcursor::CursorVisitor::VisitPackExpansionTypeLoc
clang::cxcursor::CursorVisitor::VisitDecltypeTypeLoc
clang::cxcursor::CursorVisitor::VisitInjectedClassNameTypeLoc
clang::cxcursor::CursorVisitor::VisitAtomicTypeLoc
clang::cxcursor::CursorVisitor::VisitPipeTypeLoc
clang::cxcursor::CursorVisitor::VisitCXXRecordDecl
clang::cxcursor::CursorVisitor::VisitAttributes
clang::cxcursor::CursorVisitor::EnqueueWorkList
clang::cxcursor::CursorVisitor::IsInRegionOfInterest
clang::cxcursor::CursorVisitor::RunVisitorWorkList
clang::cxcursor::CursorVisitor::Visit