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