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