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