Bug Summary

File:build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/tools/libclang/CIndex.cpp
Warning:line 4259, column 5
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name CIndex.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm/tools/clang/stage2-bins -resource-dir /usr/lib/llvm-15/lib/clang/15.0.0 -D _CINDEX_LIB_ -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/tools/libclang -I /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/tools/libclang -I /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-15/lib/clang/15.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fmacro-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-04-20-140412-16051-1 -x c++ /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/tools/libclang/CIndex.cpp

/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/tools/libclang/CIndex.cpp

1//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the main API hooks in the Clang-C Source Indexing
10// library.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CIndexDiagnostic.h"
15#include "CIndexer.h"
16#include "CLog.h"
17#include "CXCursor.h"
18#include "CXSourceLocation.h"
19#include "CXString.h"
20#include "CXTranslationUnit.h"
21#include "CXType.h"
22#include "CursorVisitor.h"
23#include "clang-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 "llvm/Support/thread.h"
59#include <mutex>
60
61#if LLVM_ENABLE_THREADS1 != 0 && defined(__APPLE__)
62#define USE_DARWIN_THREADS
63#endif
64
65#ifdef USE_DARWIN_THREADS
66#include <pthread.h>
67#endif
68
69using namespace clang;
70using namespace clang::cxcursor;
71using namespace clang::cxtu;
72using namespace clang::cxindex;
73
74CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx,
75 std::unique_ptr<ASTUnit> AU) {
76 if (!AU)
77 return nullptr;
78 assert(CIdx)(static_cast <bool> (CIdx) ? void (0) : __assert_fail (
"CIdx", "clang/tools/libclang/CIndex.cpp", 78, __extension__ __PRETTY_FUNCTION__
))
;
79 CXTranslationUnit D = new CXTranslationUnitImpl();
80 D->CIdx = CIdx;
81 D->TheASTUnit = AU.release();
82 D->StringPool = new cxstring::CXStringPool();
83 D->Diagnostics = nullptr;
84 D->OverridenCursorsPool = createOverridenCXCursorsPool();
85 D->CommentToXML = nullptr;
86 D->ParsingOptions = 0;
87 D->Arguments = {};
88 return D;
89}
90
91bool cxtu::isASTReadError(ASTUnit *AU) {
92 for (ASTUnit::stored_diag_iterator D = AU->stored_diag_begin(),
93 DEnd = AU->stored_diag_end();
94 D != DEnd; ++D) {
95 if (D->getLevel() >= DiagnosticsEngine::Error &&
96 DiagnosticIDs::getCategoryNumberForDiag(D->getID()) ==
97 diag::DiagCat_AST_Deserialization_Issue)
98 return true;
99 }
100 return false;
101}
102
103cxtu::CXTUOwner::~CXTUOwner() {
104 if (TU)
105 clang_disposeTranslationUnit(TU);
106}
107
108/// Compare two source ranges to determine their relative position in
109/// the translation unit.
110static RangeComparisonResult RangeCompare(SourceManager &SM, SourceRange R1,
111 SourceRange R2) {
112 assert(R1.isValid() && "First range is invalid?")(static_cast <bool> (R1.isValid() && "First range is invalid?"
) ? void (0) : __assert_fail ("R1.isValid() && \"First range is invalid?\""
, "clang/tools/libclang/CIndex.cpp", 112, __extension__ __PRETTY_FUNCTION__
))
;
113 assert(R2.isValid() && "Second range is invalid?")(static_cast <bool> (R2.isValid() && "Second range is invalid?"
) ? void (0) : __assert_fail ("R2.isValid() && \"Second range is invalid?\""
, "clang/tools/libclang/CIndex.cpp", 113, __extension__ __PRETTY_FUNCTION__
))
;
114 if (R1.getEnd() != R2.getBegin() &&
115 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
116 return RangeBefore;
117 if (R2.getEnd() != R1.getBegin() &&
118 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
119 return RangeAfter;
120 return RangeOverlap;
121}
122
123/// Determine if a source location falls within, before, or after a
124/// a given source range.
125static RangeComparisonResult LocationCompare(SourceManager &SM,
126 SourceLocation L, SourceRange R) {
127 assert(R.isValid() && "First range is invalid?")(static_cast <bool> (R.isValid() && "First range is invalid?"
) ? void (0) : __assert_fail ("R.isValid() && \"First range is invalid?\""
, "clang/tools/libclang/CIndex.cpp", 127, __extension__ __PRETTY_FUNCTION__
))
;
128 assert(L.isValid() && "Second range is invalid?")(static_cast <bool> (L.isValid() && "Second range is invalid?"
) ? void (0) : __assert_fail ("L.isValid() && \"Second range is invalid?\""
, "clang/tools/libclang/CIndex.cpp", 128, __extension__ __PRETTY_FUNCTION__
))
;
129 if (L == R.getBegin() || L == R.getEnd())
130 return RangeOverlap;
131 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
132 return RangeBefore;
133 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
134 return RangeAfter;
135 return RangeOverlap;
136}
137
138/// Translate a Clang source range into a CIndex source range.
139///
140/// Clang internally represents ranges where the end location points to the
141/// start of the token at the end. However, for external clients it is more
142/// useful to have a CXSourceRange be a proper half-open interval. This routine
143/// does the appropriate translation.
144CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
145 const LangOptions &LangOpts,
146 const CharSourceRange &R) {
147 // We want the last character in this location, so we will adjust the
148 // location accordingly.
149 SourceLocation EndLoc = R.getEnd();
150 bool IsTokenRange = R.isTokenRange();
151 if (EndLoc.isValid() && EndLoc.isMacroID() &&
152 !SM.isMacroArgExpansion(EndLoc)) {
153 CharSourceRange Expansion = SM.getExpansionRange(EndLoc);
154 EndLoc = Expansion.getEnd();
155 IsTokenRange = Expansion.isTokenRange();
156 }
157 if (IsTokenRange && EndLoc.isValid()) {
158 unsigned Length =
159 Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc), SM, LangOpts);
160 EndLoc = EndLoc.getLocWithOffset(Length);
161 }
162
163 CXSourceRange Result = {
164 {&SM, &LangOpts}, R.getBegin().getRawEncoding(), EndLoc.getRawEncoding()};
165 return Result;
166}
167
168CharSourceRange cxloc::translateCXRangeToCharRange(CXSourceRange R) {
169 return CharSourceRange::getCharRange(
170 SourceLocation::getFromRawEncoding(R.begin_int_data),
171 SourceLocation::getFromRawEncoding(R.end_int_data));
172}
173
174//===----------------------------------------------------------------------===//
175// Cursor visitor.
176//===----------------------------------------------------------------------===//
177
178static SourceRange getRawCursorExtent(CXCursor C);
179static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
180
181RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
182 return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
183}
184
185/// Visit the given cursor and, if requested by the visitor,
186/// its children.
187///
188/// \param Cursor the cursor to visit.
189///
190/// \param CheckedRegionOfInterest if true, then the caller already checked
191/// that this cursor is within the region of interest.
192///
193/// \returns true if the visitation should be aborted, false if it
194/// should continue.
195bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
196 if (clang_isInvalid(Cursor.kind))
197 return false;
198
199 if (clang_isDeclaration(Cursor.kind)) {
200 const Decl *D = getCursorDecl(Cursor);
201 if (!D) {
202 assert(0 && "Invalid declaration cursor")(static_cast <bool> (0 && "Invalid declaration cursor"
) ? void (0) : __assert_fail ("0 && \"Invalid declaration cursor\""
, "clang/tools/libclang/CIndex.cpp", 202, __extension__ __PRETTY_FUNCTION__
))
;
203 return true; // abort.
204 }
205
206 // Ignore implicit declarations, unless it's an objc method because
207 // currently we should report implicit methods for properties when indexing.
208 if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
209 return false;
210 }
211
212 // If we have a range of interest, and this cursor doesn't intersect with it,
213 // we're done.
214 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
215 SourceRange Range = getRawCursorExtent(Cursor);
216 if (Range.isInvalid() || CompareRegionOfInterest(Range))
217 return false;
218 }
219
220 switch (Visitor(Cursor, Parent, ClientData)) {
221 case CXChildVisit_Break:
222 return true;
223
224 case CXChildVisit_Continue:
225 return false;
226
227 case CXChildVisit_Recurse: {
228 bool ret = VisitChildren(Cursor);
229 if (PostChildrenVisitor)
230 if (PostChildrenVisitor(Cursor, ClientData))
231 return true;
232 return ret;
233 }
234 }
235
236 llvm_unreachable("Invalid CXChildVisitResult!")::llvm::llvm_unreachable_internal("Invalid CXChildVisitResult!"
, "clang/tools/libclang/CIndex.cpp", 236)
;
237}
238
239static bool visitPreprocessedEntitiesInRange(SourceRange R,
240 PreprocessingRecord &PPRec,
241 CursorVisitor &Visitor) {
242 SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
243 FileID FID;
244
245 if (!Visitor.shouldVisitIncludedEntities()) {
246 // If the begin/end of the range lie in the same FileID, do the optimization
247 // where we skip preprocessed entities that do not come from the same
248 // FileID.
249 FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
250 if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
251 FID = FileID();
252 }
253
254 const auto &Entities = PPRec.getPreprocessedEntitiesInRange(R);
255 return Visitor.visitPreprocessedEntities(Entities.begin(), Entities.end(),
256 PPRec, FID);
257}
258
259bool CursorVisitor::visitFileRegion() {
260 if (RegionOfInterest.isInvalid())
261 return false;
262
263 ASTUnit *Unit = cxtu::getASTUnit(TU);
264 SourceManager &SM = Unit->getSourceManager();
265
266 std::pair<FileID, unsigned> Begin = SM.getDecomposedLoc(
267 SM.getFileLoc(RegionOfInterest.getBegin())),
268 End = SM.getDecomposedLoc(
269 SM.getFileLoc(RegionOfInterest.getEnd()));
270
271 if (End.first != Begin.first) {
272 // If the end does not reside in the same file, try to recover by
273 // picking the end of the file of begin location.
274 End.first = Begin.first;
275 End.second = SM.getFileIDSize(Begin.first);
276 }
277
278 assert(Begin.first == End.first)(static_cast <bool> (Begin.first == End.first) ? void (
0) : __assert_fail ("Begin.first == End.first", "clang/tools/libclang/CIndex.cpp"
, 278, __extension__ __PRETTY_FUNCTION__))
;
279 if (Begin.second > End.second)
280 return false;
281
282 FileID File = Begin.first;
283 unsigned Offset = Begin.second;
284 unsigned Length = End.second - Begin.second;
285
286 if (!VisitDeclsOnly && !VisitPreprocessorLast)
287 if (visitPreprocessedEntitiesInRegion())
288 return true; // visitation break.
289
290 if (visitDeclsFromFileRegion(File, Offset, Length))
291 return true; // visitation break.
292
293 if (!VisitDeclsOnly && VisitPreprocessorLast)
294 return visitPreprocessedEntitiesInRegion();
295
296 return false;
297}
298
299static bool isInLexicalContext(Decl *D, DeclContext *DC) {
300 if (!DC)
301 return false;
302
303 for (DeclContext *DeclDC = D->getLexicalDeclContext(); DeclDC;
304 DeclDC = DeclDC->getLexicalParent()) {
305 if (DeclDC == DC)
306 return true;
307 }
308 return false;
309}
310
311bool CursorVisitor::visitDeclsFromFileRegion(FileID File, unsigned Offset,
312 unsigned Length) {
313 ASTUnit *Unit = cxtu::getASTUnit(TU);
314 SourceManager &SM = Unit->getSourceManager();
315 SourceRange Range = RegionOfInterest;
316
317 SmallVector<Decl *, 16> Decls;
318 Unit->findFileRegionDecls(File, Offset, Length, Decls);
319
320 // If we didn't find any file level decls for the file, try looking at the
321 // file that it was included from.
322 while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
323 bool Invalid = false;
324 const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
325 if (Invalid)
326 return false;
327
328 SourceLocation Outer;
329 if (SLEntry.isFile())
330 Outer = SLEntry.getFile().getIncludeLoc();
331 else
332 Outer = SLEntry.getExpansion().getExpansionLocStart();
333 if (Outer.isInvalid())
334 return false;
335
336 std::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
337 Length = 0;
338 Unit->findFileRegionDecls(File, Offset, Length, Decls);
339 }
340
341 assert(!Decls.empty())(static_cast <bool> (!Decls.empty()) ? void (0) : __assert_fail
("!Decls.empty()", "clang/tools/libclang/CIndex.cpp", 341, __extension__
__PRETTY_FUNCTION__))
;
342
343 bool VisitedAtLeastOnce = false;
344 DeclContext *CurDC = nullptr;
345 SmallVectorImpl<Decl *>::iterator DIt = Decls.begin();
346 for (SmallVectorImpl<Decl *>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
347 Decl *D = *DIt;
348 if (D->getSourceRange().isInvalid())
349 continue;
350
351 if (isInLexicalContext(D, CurDC))
352 continue;
353
354 CurDC = dyn_cast<DeclContext>(D);
355
356 if (TagDecl *TD = dyn_cast<TagDecl>(D))
357 if (!TD->isFreeStanding())
358 continue;
359
360 RangeComparisonResult CompRes =
361 RangeCompare(SM, D->getSourceRange(), Range);
362 if (CompRes == RangeBefore)
363 continue;
364 if (CompRes == RangeAfter)
365 break;
366
367 assert(CompRes == RangeOverlap)(static_cast <bool> (CompRes == RangeOverlap) ? void (0
) : __assert_fail ("CompRes == RangeOverlap", "clang/tools/libclang/CIndex.cpp"
, 367, __extension__ __PRETTY_FUNCTION__))
;
368 VisitedAtLeastOnce = true;
369
370 if (isa<ObjCContainerDecl>(D)) {
371 FileDI_current = &DIt;
372 FileDE_current = DE;
373 } else {
374 FileDI_current = nullptr;
375 }
376
377 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
378 return true; // visitation break.
379 }
380
381 if (VisitedAtLeastOnce)
382 return false;
383
384 // No Decls overlapped with the range. Move up the lexical context until there
385 // is a context that contains the range or we reach the translation unit
386 // level.
387 DeclContext *DC = DIt == Decls.begin()
388 ? (*DIt)->getLexicalDeclContext()
389 : (*(DIt - 1))->getLexicalDeclContext();
390
391 while (DC && !DC->isTranslationUnit()) {
392 Decl *D = cast<Decl>(DC);
393 SourceRange CurDeclRange = D->getSourceRange();
394 if (CurDeclRange.isInvalid())
395 break;
396
397 if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
398 if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
399 return true; // visitation break.
400 }
401
402 DC = D->getLexicalDeclContext();
403 }
404
405 return false;
406}
407
408bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
409 if (!AU->getPreprocessor().getPreprocessingRecord())
410 return false;
411
412 PreprocessingRecord &PPRec = *AU->getPreprocessor().getPreprocessingRecord();
413 SourceManager &SM = AU->getSourceManager();
414
415 if (RegionOfInterest.isValid()) {
416 SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
417 SourceLocation B = MappedRange.getBegin();
418 SourceLocation E = MappedRange.getEnd();
419
420 if (AU->isInPreambleFileID(B)) {
421 if (SM.isLoadedSourceLocation(E))
422 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec,
423 *this);
424
425 // Beginning of range lies in the preamble but it also extends beyond
426 // it into the main file. Split the range into 2 parts, one covering
427 // the preamble and another covering the main file. This allows subsequent
428 // calls to visitPreprocessedEntitiesInRange to accept a source range that
429 // lies in the same FileID, allowing it to skip preprocessed entities that
430 // do not come from the same FileID.
431 bool breaked = visitPreprocessedEntitiesInRange(
432 SourceRange(B, AU->getEndOfPreambleFileID()), PPRec, *this);
433 if (breaked)
434 return true;
435 return visitPreprocessedEntitiesInRange(
436 SourceRange(AU->getStartOfMainFileID(), E), PPRec, *this);
437 }
438
439 return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
440 }
441
442 bool OnlyLocalDecls = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
443
444 if (OnlyLocalDecls)
445 return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
446 PPRec);
447
448 return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
449}
450
451template <typename InputIterator>
452bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
453 InputIterator Last,
454 PreprocessingRecord &PPRec,
455 FileID FID) {
456 for (; First != Last; ++First) {
457 if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
458 continue;
459
460 PreprocessedEntity *PPE = *First;
461 if (!PPE)
462 continue;
463
464 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
465 if (Visit(MakeMacroExpansionCursor(ME, TU)))
466 return true;
467
468 continue;
469 }
470
471 if (MacroDefinitionRecord *MD = dyn_cast<MacroDefinitionRecord>(PPE)) {
472 if (Visit(MakeMacroDefinitionCursor(MD, TU)))
473 return true;
474
475 continue;
476 }
477
478 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
479 if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
480 return true;
481
482 continue;
483 }
484 }
485
486 return false;
487}
488
489/// Visit the children of the given cursor.
490///
491/// \returns true if the visitation should be aborted, false if it
492/// should continue.
493bool CursorVisitor::VisitChildren(CXCursor Cursor) {
494 if (clang_isReference(Cursor.kind) &&
495 Cursor.kind != CXCursor_CXXBaseSpecifier) {
496 // By definition, references have no children.
497 return false;
498 }
499
500 // Set the Parent field to Cursor, then back to its old value once we're
501 // done.
502 SetParentRAII SetParent(Parent, StmtParent, Cursor);
503
504 if (clang_isDeclaration(Cursor.kind)) {
505 Decl *D = const_cast<Decl *>(getCursorDecl(Cursor));
506 if (!D)
507 return false;
508
509 return VisitAttributes(D) || Visit(D);
510 }
511
512 if (clang_isStatement(Cursor.kind)) {
513 if (const Stmt *S = getCursorStmt(Cursor))
514 return Visit(S);
515
516 return false;
517 }
518
519 if (clang_isExpression(Cursor.kind)) {
520 if (const Expr *E = getCursorExpr(Cursor))
521 return Visit(E);
522
523 return false;
524 }
525
526 if (clang_isTranslationUnit(Cursor.kind)) {
527 CXTranslationUnit TU = getCursorTU(Cursor);
528 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
529
530 int VisitOrder[2] = {VisitPreprocessorLast, !VisitPreprocessorLast};
531 for (unsigned I = 0; I != 2; ++I) {
532 if (VisitOrder[I]) {
533 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
534 RegionOfInterest.isInvalid()) {
535 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
536 TLEnd = CXXUnit->top_level_end();
537 TL != TLEnd; ++TL) {
538 const Optional<bool> V = handleDeclForVisitation(*TL);
539 if (!V.hasValue())
540 continue;
541 return V.getValue();
542 }
543 } else if (VisitDeclContext(
544 CXXUnit->getASTContext().getTranslationUnitDecl()))
545 return true;
546 continue;
547 }
548
549 // Walk the preprocessing record.
550 if (CXXUnit->getPreprocessor().getPreprocessingRecord())
551 visitPreprocessedEntitiesInRegion();
552 }
553
554 return false;
555 }
556
557 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
558 if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
559 if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
560 return Visit(BaseTSInfo->getTypeLoc());
561 }
562 }
563 }
564
565 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
566 const IBOutletCollectionAttr *A =
567 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
568 if (const ObjCObjectType *ObjT = A->getInterface()->getAs<ObjCObjectType>())
569 return Visit(cxcursor::MakeCursorObjCClassRef(
570 ObjT->getInterface(),
571 A->getInterfaceLoc()->getTypeLoc().getBeginLoc(), TU));
572 }
573
574 // If pointing inside a macro definition, check if the token is an identifier
575 // that was ever defined as a macro. In such a case, create a "pseudo" macro
576 // expansion cursor for that token.
577 SourceLocation BeginLoc = RegionOfInterest.getBegin();
578 if (Cursor.kind == CXCursor_MacroDefinition &&
579 BeginLoc == RegionOfInterest.getEnd()) {
580 SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc);
581 const MacroInfo *MI =
582 getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU);
583 if (MacroDefinitionRecord *MacroDef =
584 checkForMacroInMacroDefinition(MI, Loc, TU))
585 return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU));
586 }
587
588 // Nothing to visit at the moment.
589 return false;
590}
591
592bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
593 if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
594 if (Visit(TSInfo->getTypeLoc()))
595 return true;
596
597 if (Stmt *Body = B->getBody())
598 return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
599
600 return false;
601}
602
603Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
604 if (RegionOfInterest.isValid()) {
605 SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
606 if (Range.isInvalid())
607 return None;
608
609 switch (CompareRegionOfInterest(Range)) {
610 case RangeBefore:
611 // This declaration comes before the region of interest; skip it.
612 return None;
613
614 case RangeAfter:
615 // This declaration comes after the region of interest; we're done.
616 return false;
617
618 case RangeOverlap:
619 // This declaration overlaps the region of interest; visit it.
620 break;
621 }
622 }
623 return true;
624}
625
626bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
627 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
628
629 // FIXME: Eventually remove. This part of a hack to support proper
630 // iteration over all Decls contained lexically within an ObjC container.
631 SaveAndRestore<DeclContext::decl_iterator *> DI_saved(DI_current, &I);
632 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
633
634 for (; I != E; ++I) {
635 Decl *D = *I;
636 if (D->getLexicalDeclContext() != DC)
637 continue;
638 // Filter out synthesized property accessor redeclarations.
639 if (isa<ObjCImplDecl>(DC))
640 if (auto *OMD = dyn_cast<ObjCMethodDecl>(D))
641 if (OMD->isSynthesizedAccessorStub())
642 continue;
643 const Optional<bool> V = handleDeclForVisitation(D);
644 if (!V.hasValue())
645 continue;
646 return V.getValue();
647 }
648 return false;
649}
650
651Optional<bool> CursorVisitor::handleDeclForVisitation(const Decl *D) {
652 CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
653
654 // Ignore synthesized ivars here, otherwise if we have something like:
655 // @synthesize prop = _prop;
656 // and '_prop' is not declared, we will encounter a '_prop' ivar before
657 // encountering the 'prop' synthesize declaration and we will think that
658 // we passed the region-of-interest.
659 if (auto *ivarD = dyn_cast<ObjCIvarDecl>(D)) {
660 if (ivarD->getSynthesize())
661 return None;
662 }
663
664 // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
665 // declarations is a mismatch with the compiler semantics.
666 if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
667 auto *ID = cast<ObjCInterfaceDecl>(D);
668 if (!ID->isThisDeclarationADefinition())
669 Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
670
671 } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
672 auto *PD = cast<ObjCProtocolDecl>(D);
673 if (!PD->isThisDeclarationADefinition())
674 Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
675 }
676
677 const Optional<bool> V = shouldVisitCursor(Cursor);
678 if (!V.hasValue())
679 return None;
680 if (!V.getValue())
681 return false;
682 if (Visit(Cursor, true))
683 return true;
684 return None;
685}
686
687bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
688 llvm_unreachable("Translation units are visited directly by Visit()")::llvm::llvm_unreachable_internal("Translation units are visited directly by Visit()"
, "clang/tools/libclang/CIndex.cpp", 688)
;
689}
690
691bool CursorVisitor::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
692 if (VisitTemplateParameters(D->getTemplateParameters()))
693 return true;
694
695 return Visit(MakeCXCursor(D->getTemplatedDecl(), TU, RegionOfInterest));
696}
697
698bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
699 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
700 return Visit(TSInfo->getTypeLoc());
701
702 return false;
703}
704
705bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
706 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
707 return Visit(TSInfo->getTypeLoc());
708
709 return false;
710}
711
712bool CursorVisitor::VisitTagDecl(TagDecl *D) { return VisitDeclContext(D); }
713
714bool CursorVisitor::VisitClassTemplateSpecializationDecl(
715 ClassTemplateSpecializationDecl *D) {
716 bool ShouldVisitBody = false;
717 switch (D->getSpecializationKind()) {
718 case TSK_Undeclared:
719 case TSK_ImplicitInstantiation:
720 // Nothing to visit
721 return false;
722
723 case TSK_ExplicitInstantiationDeclaration:
724 case TSK_ExplicitInstantiationDefinition:
725 break;
726
727 case TSK_ExplicitSpecialization:
728 ShouldVisitBody = true;
729 break;
730 }
731
732 // Visit the template arguments used in the specialization.
733 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
734 TypeLoc TL = SpecType->getTypeLoc();
735 if (TemplateSpecializationTypeLoc TSTLoc =
736 TL.getAs<TemplateSpecializationTypeLoc>()) {
737 for (unsigned I = 0, N = TSTLoc.getNumArgs(); I != N; ++I)
738 if (VisitTemplateArgumentLoc(TSTLoc.getArgLoc(I)))
739 return true;
740 }
741 }
742
743 return ShouldVisitBody && VisitCXXRecordDecl(D);
744}
745
746bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
747 ClassTemplatePartialSpecializationDecl *D) {
748 // FIXME: Visit the "outer" template parameter lists on the TagDecl
749 // before visiting these template parameters.
750 if (VisitTemplateParameters(D->getTemplateParameters()))
751 return true;
752
753 // Visit the partial specialization arguments.
754 const ASTTemplateArgumentListInfo *Info = D->getTemplateArgsAsWritten();
755 const TemplateArgumentLoc *TemplateArgs = Info->getTemplateArgs();
756 for (unsigned I = 0, N = Info->NumTemplateArgs; I != N; ++I)
757 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
758 return true;
759
760 return VisitCXXRecordDecl(D);
761}
762
763bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
764 if (const auto *TC = D->getTypeConstraint())
765 if (Visit(MakeCXCursor(TC->getImmediatelyDeclaredConstraint(), StmtParent,
766 TU, RegionOfInterest)))
767 return true;
768
769 // Visit the default argument.
770 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
771 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
772 if (Visit(DefArg->getTypeLoc()))
773 return true;
774
775 return false;
776}
777
778bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
779 if (Expr *Init = D->getInitExpr())
780 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
781 return false;
782}
783
784bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
785 unsigned NumParamList = DD->getNumTemplateParameterLists();
786 for (unsigned i = 0; i < NumParamList; i++) {
787 TemplateParameterList *Params = DD->getTemplateParameterList(i);
788 if (VisitTemplateParameters(Params))
789 return true;
790 }
791
792 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
793 if (Visit(TSInfo->getTypeLoc()))
794 return true;
795
796 // Visit the nested-name-specifier, if present.
797 if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
798 if (VisitNestedNameSpecifierLoc(QualifierLoc))
799 return true;
800
801 return false;
802}
803
804static bool HasTrailingReturnType(FunctionDecl *ND) {
805 const QualType Ty = ND->getType();
806 if (const FunctionType *AFT = Ty->getAs<FunctionType>()) {
807 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(AFT))
808 return FT->hasTrailingReturn();
809 }
810
811 return false;
812}
813
814/// Compare two base or member initializers based on their source order.
815static int CompareCXXCtorInitializers(CXXCtorInitializer *const *X,
816 CXXCtorInitializer *const *Y) {
817 return (*X)->getSourceOrder() - (*Y)->getSourceOrder();
818}
819
820bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
821 unsigned NumParamList = ND->getNumTemplateParameterLists();
822 for (unsigned i = 0; i < NumParamList; i++) {
823 TemplateParameterList *Params = ND->getTemplateParameterList(i);
824 if (VisitTemplateParameters(Params))
825 return true;
826 }
827
828 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
829 // Visit the function declaration's syntactic components in the order
830 // written. This requires a bit of work.
831 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
832 FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>();
833 const bool HasTrailingRT = HasTrailingReturnType(ND);
834
835 // If we have a function declared directly (without the use of a typedef),
836 // visit just the return type. Otherwise, just visit the function's type
837 // now.
838 if ((FTL && !isa<CXXConversionDecl>(ND) && !HasTrailingRT &&
839 Visit(FTL.getReturnLoc())) ||
840 (!FTL && Visit(TL)))
841 return true;
842
843 // Visit the nested-name-specifier, if present.
844 if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
845 if (VisitNestedNameSpecifierLoc(QualifierLoc))
846 return true;
847
848 // Visit the declaration name.
849 if (!isa<CXXDestructorDecl>(ND))
850 if (VisitDeclarationNameInfo(ND->getNameInfo()))
851 return true;
852
853 // FIXME: Visit explicitly-specified template arguments!
854
855 // Visit the function parameters, if we have a function type.
856 if (FTL && VisitFunctionTypeLoc(FTL, true))
857 return true;
858
859 // Visit the function's trailing return type.
860 if (FTL && HasTrailingRT && Visit(FTL.getReturnLoc()))
861 return true;
862
863 // FIXME: Attributes?
864 }
865
866 if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
867 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
868 // Find the initializers that were written in the source.
869 SmallVector<CXXCtorInitializer *, 4> WrittenInits;
870 for (auto *I : Constructor->inits()) {
871 if (!I->isWritten())
872 continue;
873
874 WrittenInits.push_back(I);
875 }
876
877 // Sort the initializers in source order
878 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
879 &CompareCXXCtorInitializers);
880
881 // Visit the initializers in source order
882 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
883 CXXCtorInitializer *Init = WrittenInits[I];
884 if (Init->isAnyMemberInitializer()) {
885 if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
886 Init->getMemberLocation(), TU)))
887 return true;
888 } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
889 if (Visit(TInfo->getTypeLoc()))
890 return true;
891 }
892
893 // Visit the initializer value.
894 if (Expr *Initializer = Init->getInit())
895 if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
896 return true;
897 }
898 }
899
900 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
901 return true;
902 }
903
904 return false;
905}
906
907bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
908 if (VisitDeclaratorDecl(D))
909 return true;
910
911 if (Expr *BitWidth = D->getBitWidth())
912 return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
913
914 if (Expr *Init = D->getInClassInitializer())
915 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
916
917 return false;
918}
919
920bool CursorVisitor::VisitVarDecl(VarDecl *D) {
921 if (VisitDeclaratorDecl(D))
922 return true;
923
924 if (Expr *Init = D->getInit())
925 return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
926
927 return false;
928}
929
930bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
931 if (VisitDeclaratorDecl(D))
932 return true;
933
934 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
935 if (Expr *DefArg = D->getDefaultArgument())
936 return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
937
938 return false;
939}
940
941bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
942 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
943 // before visiting these template parameters.
944 if (VisitTemplateParameters(D->getTemplateParameters()))
945 return true;
946
947 auto *FD = D->getTemplatedDecl();
948 return VisitAttributes(FD) || VisitFunctionDecl(FD);
949}
950
951bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
952 // FIXME: Visit the "outer" template parameter lists on the TagDecl
953 // before visiting these template parameters.
954 if (VisitTemplateParameters(D->getTemplateParameters()))
955 return true;
956
957 auto *CD = D->getTemplatedDecl();
958 return VisitAttributes(CD) || VisitCXXRecordDecl(CD);
959}
960
961bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
962 if (VisitTemplateParameters(D->getTemplateParameters()))
963 return true;
964
965 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
966 VisitTemplateArgumentLoc(D->getDefaultArgument()))
967 return true;
968
969 return false;
970}
971
972bool CursorVisitor::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
973 // Visit the bound, if it's explicit.
974 if (D->hasExplicitBound()) {
975 if (auto TInfo = D->getTypeSourceInfo()) {
976 if (Visit(TInfo->getTypeLoc()))
977 return true;
978 }
979 }
980
981 return false;
982}
983
984bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
985 if (TypeSourceInfo *TSInfo = ND->getReturnTypeSourceInfo())
986 if (Visit(TSInfo->getTypeLoc()))
987 return true;
988
989 for (const auto *P : ND->parameters()) {
990 if (Visit(MakeCXCursor(P, TU, RegionOfInterest)))
991 return true;
992 }
993
994 return ND->isThisDeclarationADefinition() &&
995 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest));
996}
997
998template <typename DeclIt>
999static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
1000 SourceManager &SM, SourceLocation EndLoc,
1001 SmallVectorImpl<Decl *> &Decls) {
1002 DeclIt next = *DI_current;
1003 while (++next != DE_current) {
1004 Decl *D_next = *next;
1005 if (!D_next)
1006 break;
1007 SourceLocation L = D_next->getBeginLoc();
1008 if (!L.isValid())
1009 break;
1010 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
1011 *DI_current = next;
1012 Decls.push_back(D_next);
1013 continue;
1014 }
1015 break;
1016 }
1017}
1018
1019bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
1020 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
1021 // an @implementation can lexically contain Decls that are not properly
1022 // nested in the AST. When we identify such cases, we need to retrofit
1023 // this nesting here.
1024 if (!DI_current && !FileDI_current)
1025 return VisitDeclContext(D);
1026
1027 // Scan the Decls that immediately come after the container
1028 // in the current DeclContext. If any fall within the
1029 // container's lexical region, stash them into a vector
1030 // for later processing.
1031 SmallVector<Decl *, 24> DeclsInContainer;
1032 SourceLocation EndLoc = D->getSourceRange().getEnd();
1033 SourceManager &SM = AU->getSourceManager();
1034 if (EndLoc.isValid()) {
1035 if (DI_current) {
1036 addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
1037 DeclsInContainer);
1038 } else {
1039 addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
1040 DeclsInContainer);
1041 }
1042 }
1043
1044 // The common case.
1045 if (DeclsInContainer.empty())
1046 return VisitDeclContext(D);
1047
1048 // Get all the Decls in the DeclContext, and sort them with the
1049 // additional ones we've collected. Then visit them.
1050 for (auto *SubDecl : D->decls()) {
1051 if (!SubDecl || SubDecl->getLexicalDeclContext() != D ||
1052 SubDecl->getBeginLoc().isInvalid())
1053 continue;
1054 DeclsInContainer.push_back(SubDecl);
1055 }
1056
1057 // Now sort the Decls so that they appear in lexical order.
1058 llvm::sort(DeclsInContainer, [&SM](Decl *A, Decl *B) {
1059 SourceLocation L_A = A->getBeginLoc();
1060 SourceLocation L_B = B->getBeginLoc();
1061 return L_A != L_B
1062 ? SM.isBeforeInTranslationUnit(L_A, L_B)
1063 : SM.isBeforeInTranslationUnit(A->getEndLoc(), B->getEndLoc());
1064 });
1065
1066 // Now visit the decls.
1067 for (SmallVectorImpl<Decl *>::iterator I = DeclsInContainer.begin(),
1068 E = DeclsInContainer.end();
1069 I != E; ++I) {
1070 CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
1071 const Optional<bool> &V = shouldVisitCursor(Cursor);
1072 if (!V.hasValue())
1073 continue;
1074 if (!V.getValue())
1075 return false;
1076 if (Visit(Cursor, true))
1077 return true;
1078 }
1079 return false;
1080}
1081
1082bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
1083 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
1084 TU)))
1085 return true;
1086
1087 if (VisitObjCTypeParamList(ND->getTypeParamList()))
1088 return true;
1089
1090 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
1091 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
1092 E = ND->protocol_end();
1093 I != E; ++I, ++PL)
1094 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1095 return true;
1096
1097 return VisitObjCContainerDecl(ND);
1098}
1099
1100bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1101 if (!PID->isThisDeclarationADefinition())
1102 return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
1103
1104 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1105 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1106 E = PID->protocol_end();
1107 I != E; ++I, ++PL)
1108 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1109 return true;
1110
1111 return VisitObjCContainerDecl(PID);
1112}
1113
1114bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
1115 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
1116 return true;
1117
1118 // FIXME: This implements a workaround with @property declarations also being
1119 // installed in the DeclContext for the @interface. Eventually this code
1120 // should be removed.
1121 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1122 if (!CDecl || !CDecl->IsClassExtension())
1123 return false;
1124
1125 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1126 if (!ID)
1127 return false;
1128
1129 IdentifierInfo *PropertyId = PD->getIdentifier();
1130 ObjCPropertyDecl *prevDecl = ObjCPropertyDecl::findPropertyDecl(
1131 cast<DeclContext>(ID), PropertyId, PD->getQueryKind());
1132
1133 if (!prevDecl)
1134 return false;
1135
1136 // Visit synthesized methods since they will be skipped when visiting
1137 // the @interface.
1138 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
1139 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1140 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1141 return true;
1142
1143 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
1144 if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1145 if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1146 return true;
1147
1148 return false;
1149}
1150
1151bool CursorVisitor::VisitObjCTypeParamList(ObjCTypeParamList *typeParamList) {
1152 if (!typeParamList)
1153 return false;
1154
1155 for (auto *typeParam : *typeParamList) {
1156 // Visit the type parameter.
1157 if (Visit(MakeCXCursor(typeParam, TU, RegionOfInterest)))
1158 return true;
1159 }
1160
1161 return false;
1162}
1163
1164bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
1165 if (!D->isThisDeclarationADefinition()) {
1166 // Forward declaration is treated like a reference.
1167 return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1168 }
1169
1170 // Objective-C type parameters.
1171 if (VisitObjCTypeParamList(D->getTypeParamListAsWritten()))
1172 return true;
1173
1174 // Issue callbacks for super class.
1175 if (D->getSuperClass() && Visit(MakeCursorObjCSuperClassRef(
1176 D->getSuperClass(), D->getSuperClassLoc(), TU)))
1177 return true;
1178
1179 if (TypeSourceInfo *SuperClassTInfo = D->getSuperClassTInfo())
1180 if (Visit(SuperClassTInfo->getTypeLoc()))
1181 return true;
1182
1183 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1184 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1185 E = D->protocol_end();
1186 I != E; ++I, ++PL)
1187 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1188 return true;
1189
1190 return VisitObjCContainerDecl(D);
1191}
1192
1193bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1194 return VisitObjCContainerDecl(D);
1195}
1196
1197bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1198 // 'ID' could be null when dealing with invalid code.
1199 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1200 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1201 return true;
1202
1203 return VisitObjCImplDecl(D);
1204}
1205
1206bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1207#if 0
1208 // Issue callbacks for super class.
1209 // FIXME: No source location information!
1210 if (D->getSuperClass() &&
1211 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1212 D->getSuperClassLoc(),
1213 TU)))
1214 return true;
1215#endif
1216
1217 return VisitObjCImplDecl(D);
1218}
1219
1220bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1221 if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1222 if (PD->isIvarNameSpecified())
1223 return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1224
1225 return false;
1226}
1227
1228bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1229 return VisitDeclContext(D);
1230}
1231
1232bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1233 // Visit nested-name-specifier.
1234 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1235 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1236 return true;
1237
1238 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1239 D->getTargetNameLoc(), TU));
1240}
1241
1242bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1243 // Visit nested-name-specifier.
1244 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1245 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1246 return true;
1247 }
1248
1249 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1250 return true;
1251
1252 return VisitDeclarationNameInfo(D->getNameInfo());
1253}
1254
1255bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1256 // Visit nested-name-specifier.
1257 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1258 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1259 return true;
1260
1261 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1262 D->getIdentLocation(), TU));
1263}
1264
1265bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1266 // Visit nested-name-specifier.
1267 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1268 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1269 return true;
1270 }
1271
1272 return VisitDeclarationNameInfo(D->getNameInfo());
1273}
1274
1275bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1276 UnresolvedUsingTypenameDecl *D) {
1277 // Visit nested-name-specifier.
1278 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1279 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1280 return true;
1281
1282 return false;
1283}
1284
1285bool CursorVisitor::VisitStaticAssertDecl(StaticAssertDecl *D) {
1286 if (Visit(MakeCXCursor(D->getAssertExpr(), StmtParent, TU, RegionOfInterest)))
1287 return true;
1288 if (StringLiteral *Message = D->getMessage())
1289 if (Visit(MakeCXCursor(Message, StmtParent, TU, RegionOfInterest)))
1290 return true;
1291 return false;
1292}
1293
1294bool CursorVisitor::VisitFriendDecl(FriendDecl *D) {
1295 if (NamedDecl *FriendD = D->getFriendDecl()) {
1296 if (Visit(MakeCXCursor(FriendD, TU, RegionOfInterest)))
1297 return true;
1298 } else if (TypeSourceInfo *TI = D->getFriendType()) {
1299 if (Visit(TI->getTypeLoc()))
1300 return true;
1301 }
1302 return false;
1303}
1304
1305bool CursorVisitor::VisitDecompositionDecl(DecompositionDecl *D) {
1306 for (auto *B : D->bindings()) {
1307 if (Visit(MakeCXCursor(B, TU, RegionOfInterest)))
1308 return true;
1309 }
1310 return VisitVarDecl(D);
1311}
1312
1313bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1314 switch (Name.getName().getNameKind()) {
1315 case clang::DeclarationName::Identifier:
1316 case clang::DeclarationName::CXXLiteralOperatorName:
1317 case clang::DeclarationName::CXXDeductionGuideName:
1318 case clang::DeclarationName::CXXOperatorName:
1319 case clang::DeclarationName::CXXUsingDirective:
1320 return false;
1321
1322 case clang::DeclarationName::CXXConstructorName:
1323 case clang::DeclarationName::CXXDestructorName:
1324 case clang::DeclarationName::CXXConversionFunctionName:
1325 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1326 return Visit(TSInfo->getTypeLoc());
1327 return false;
1328
1329 case clang::DeclarationName::ObjCZeroArgSelector:
1330 case clang::DeclarationName::ObjCOneArgSelector:
1331 case clang::DeclarationName::ObjCMultiArgSelector:
1332 // FIXME: Per-identifier location info?
1333 return false;
1334 }
1335
1336 llvm_unreachable("Invalid DeclarationName::Kind!")::llvm::llvm_unreachable_internal("Invalid DeclarationName::Kind!"
, "clang/tools/libclang/CIndex.cpp", 1336)
;
1337}
1338
1339bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1340 SourceRange Range) {
1341 // FIXME: This whole routine is a hack to work around the lack of proper
1342 // source information in nested-name-specifiers (PR5791). Since we do have
1343 // a beginning source location, we can visit the first component of the
1344 // nested-name-specifier, if it's a single-token component.
1345 if (!NNS)
1346 return false;
1347
1348 // Get the first component in the nested-name-specifier.
1349 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1350 NNS = Prefix;
1351
1352 switch (NNS->getKind()) {
1353 case NestedNameSpecifier::Namespace:
1354 return Visit(
1355 MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(), TU));
1356
1357 case NestedNameSpecifier::NamespaceAlias:
1358 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1359 Range.getBegin(), TU));
1360
1361 case NestedNameSpecifier::TypeSpec: {
1362 // If the type has a form where we know that the beginning of the source
1363 // range matches up with a reference cursor. Visit the appropriate reference
1364 // cursor.
1365 const Type *T = NNS->getAsType();
1366 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1367 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1368 if (const TagType *Tag = dyn_cast<TagType>(T))
1369 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1370 if (const TemplateSpecializationType *TST =
1371 dyn_cast<TemplateSpecializationType>(T))
1372 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1373 break;
1374 }
1375
1376 case NestedNameSpecifier::TypeSpecWithTemplate:
1377 case NestedNameSpecifier::Global:
1378 case NestedNameSpecifier::Identifier:
1379 case NestedNameSpecifier::Super:
1380 break;
1381 }
1382
1383 return false;
1384}
1385
1386bool CursorVisitor::VisitNestedNameSpecifierLoc(
1387 NestedNameSpecifierLoc Qualifier) {
1388 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1389 for (; Qualifier; Qualifier = Qualifier.getPrefix())
1390 Qualifiers.push_back(Qualifier);
1391
1392 while (!Qualifiers.empty()) {
1393 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1394 NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1395 switch (NNS->getKind()) {
1396 case NestedNameSpecifier::Namespace:
1397 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
1398 Q.getLocalBeginLoc(), TU)))
1399 return true;
1400
1401 break;
1402
1403 case NestedNameSpecifier::NamespaceAlias:
1404 if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1405 Q.getLocalBeginLoc(), TU)))
1406 return true;
1407
1408 break;
1409
1410 case NestedNameSpecifier::TypeSpec:
1411 case NestedNameSpecifier::TypeSpecWithTemplate:
1412 if (Visit(Q.getTypeLoc()))
1413 return true;
1414
1415 break;
1416
1417 case NestedNameSpecifier::Global:
1418 case NestedNameSpecifier::Identifier:
1419 case NestedNameSpecifier::Super:
1420 break;
1421 }
1422 }
1423
1424 return false;
1425}
1426
1427bool CursorVisitor::VisitTemplateParameters(
1428 const TemplateParameterList *Params) {
1429 if (!Params)
1430 return false;
1431
1432 for (TemplateParameterList::const_iterator P = Params->begin(),
1433 PEnd = Params->end();
1434 P != PEnd; ++P) {
1435 if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
1436 return true;
1437 }
1438
1439 return false;
1440}
1441
1442bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1443 switch (Name.getKind()) {
1444 case TemplateName::Template:
1445 case TemplateName::UsingTemplate:
1446 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1447
1448 case TemplateName::OverloadedTemplate:
1449 // Visit the overloaded template set.
1450 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1451 return true;
1452
1453 return false;
1454
1455 case TemplateName::AssumedTemplate:
1456 // FIXME: Visit DeclarationName?
1457 return false;
1458
1459 case TemplateName::DependentTemplate:
1460 // FIXME: Visit nested-name-specifier.
1461 return false;
1462
1463 case TemplateName::QualifiedTemplate:
1464 // FIXME: Visit nested-name-specifier.
1465 return Visit(MakeCursorTemplateRef(
1466 Name.getAsQualifiedTemplateName()->getTemplateDecl(), Loc, TU));
1467
1468 case TemplateName::SubstTemplateTemplateParm:
1469 return Visit(MakeCursorTemplateRef(
1470 Name.getAsSubstTemplateTemplateParm()->getParameter(), Loc, TU));
1471
1472 case TemplateName::SubstTemplateTemplateParmPack:
1473 return Visit(MakeCursorTemplateRef(
1474 Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(), Loc,
1475 TU));
1476 }
1477
1478 llvm_unreachable("Invalid TemplateName::Kind!")::llvm::llvm_unreachable_internal("Invalid TemplateName::Kind!"
, "clang/tools/libclang/CIndex.cpp", 1478)
;
1479}
1480
1481bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1482 switch (TAL.getArgument().getKind()) {
1483 case TemplateArgument::Null:
1484 case TemplateArgument::Integral:
1485 case TemplateArgument::Pack:
1486 return false;
1487
1488 case TemplateArgument::Type:
1489 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1490 return Visit(TSInfo->getTypeLoc());
1491 return false;
1492
1493 case TemplateArgument::Declaration:
1494 if (Expr *E = TAL.getSourceDeclExpression())
1495 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1496 return false;
1497
1498 case TemplateArgument::NullPtr:
1499 if (Expr *E = TAL.getSourceNullPtrExpression())
1500 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1501 return false;
1502
1503 case TemplateArgument::Expression:
1504 if (Expr *E = TAL.getSourceExpression())
1505 return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1506 return false;
1507
1508 case TemplateArgument::Template:
1509 case TemplateArgument::TemplateExpansion:
1510 if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1511 return true;
1512
1513 return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
1514 TAL.getTemplateNameLoc());
1515 }
1516
1517 llvm_unreachable("Invalid TemplateArgument::Kind!")::llvm::llvm_unreachable_internal("Invalid TemplateArgument::Kind!"
, "clang/tools/libclang/CIndex.cpp", 1517)
;
1518}
1519
1520bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1521 return VisitDeclContext(D);
1522}
1523
1524bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1525 return Visit(TL.getUnqualifiedLoc());
1526}
1527
1528bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1529 ASTContext &Context = AU->getASTContext();
1530
1531 // Some builtin types (such as Objective-C's "id", "sel", and
1532 // "Class") have associated declarations. Create cursors for those.
1533 QualType VisitType;
1534 switch (TL.getTypePtr()->getKind()) {
1535
1536 case BuiltinType::Void:
1537 case BuiltinType::NullPtr:
1538 case BuiltinType::Dependent:
1539#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1540 case BuiltinType::Id:
1541#include "clang/Basic/OpenCLImageTypes.def"
1542#define EXT_OPAQUE_TYPE(ExtTYpe, Id, Ext) case BuiltinType::Id:
1543#include "clang/Basic/OpenCLExtensionTypes.def"
1544 case BuiltinType::OCLSampler:
1545 case BuiltinType::OCLEvent:
1546 case BuiltinType::OCLClkEvent:
1547 case BuiltinType::OCLQueue:
1548 case BuiltinType::OCLReserveID:
1549#define SVE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
1550#include "clang/Basic/AArch64SVEACLETypes.def"
1551#define PPC_VECTOR_TYPE(Name, Id, Size) case BuiltinType::Id:
1552#include "clang/Basic/PPCTypes.def"
1553#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
1554#include "clang/Basic/RISCVVTypes.def"
1555#define BUILTIN_TYPE(Id, SingletonId)
1556#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1557#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1558#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1559#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1560#include "clang/AST/BuiltinTypes.def"
1561 break;
1562
1563 case BuiltinType::ObjCId:
1564 VisitType = Context.getObjCIdType();
1565 break;
1566
1567 case BuiltinType::ObjCClass:
1568 VisitType = Context.getObjCClassType();
1569 break;
1570
1571 case BuiltinType::ObjCSel:
1572 VisitType = Context.getObjCSelType();
1573 break;
1574 }
1575
1576 if (!VisitType.isNull()) {
1577 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1578 return Visit(
1579 MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(), TU));
1580 }
1581
1582 return false;
1583}
1584
1585bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1586 return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1587}
1588
1589bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1590 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1591}
1592
1593bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1594 if (TL.isDefinition())
1595 return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
1596
1597 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1598}
1599
1600bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1601 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1602}
1603
1604bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1605 return Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU));
1606}
1607
1608bool CursorVisitor::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
1609 if (Visit(MakeCursorTypeRef(TL.getDecl(), TL.getBeginLoc(), TU)))
1610 return true;
1611 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1612 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1613 TU)))
1614 return true;
1615 }
1616
1617 return false;
1618}
1619
1620bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1621 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1622 return true;
1623
1624 for (unsigned I = 0, N = TL.getNumTypeArgs(); I != N; ++I) {
1625 if (Visit(TL.getTypeArgTInfo(I)->getTypeLoc()))
1626 return true;
1627 }
1628
1629 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1630 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1631 TU)))
1632 return true;
1633 }
1634
1635 return false;
1636}
1637
1638bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1639 return Visit(TL.getPointeeLoc());
1640}
1641
1642bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1643 return Visit(TL.getInnerLoc());
1644}
1645
1646bool CursorVisitor::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
1647 return Visit(TL.getInnerLoc());
1648}
1649
1650bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1651 return Visit(TL.getPointeeLoc());
1652}
1653
1654bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1655 return Visit(TL.getPointeeLoc());
1656}
1657
1658bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1659 return Visit(TL.getPointeeLoc());
1660}
1661
1662bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1663 return Visit(TL.getPointeeLoc());
1664}
1665
1666bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1667 return Visit(TL.getPointeeLoc());
1668}
1669
1670bool CursorVisitor::VisitUsingTypeLoc(UsingTypeLoc TL) { return false; }
1671
1672bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1673 return Visit(TL.getModifiedLoc());
1674}
1675
1676bool CursorVisitor::VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
1677 return Visit(TL.getWrappedLoc());
1678}
1679
1680bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1681 bool SkipResultType) {
1682 if (!SkipResultType && Visit(TL.getReturnLoc()))
1683 return true;
1684
1685 for (unsigned I = 0, N = TL.getNumParams(); I != N; ++I)
1686 if (Decl *D = TL.getParam(I))
1687 if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
1688 return true;
1689
1690 return false;
1691}
1692
1693bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1694 if (Visit(TL.getElementLoc()))
1695 return true;
1696
1697 if (Expr *Size = TL.getSizeExpr())
1698 return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
1699
1700 return false;
1701}
1702
1703bool CursorVisitor::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
1704 return Visit(TL.getOriginalLoc());
1705}
1706
1707bool CursorVisitor::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
1708 return Visit(TL.getOriginalLoc());
1709}
1710
1711bool CursorVisitor::VisitDeducedTemplateSpecializationTypeLoc(
1712 DeducedTemplateSpecializationTypeLoc TL) {
1713 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1714 TL.getTemplateNameLoc()))
1715 return true;
1716
1717 return false;
1718}
1719
1720bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1721 TemplateSpecializationTypeLoc TL) {
1722 // Visit the template name.
1723 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1724 TL.getTemplateNameLoc()))
1725 return true;
1726
1727 // Visit the template arguments.
1728 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1729 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1730 return true;
1731
1732 return false;
1733}
1734
1735bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1736 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1737}
1738
1739bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1740 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1741 return Visit(TSInfo->getTypeLoc());
1742
1743 return false;
1744}
1745
1746bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1747 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1748 return Visit(TSInfo->getTypeLoc());
1749
1750 return false;
1751}
1752
1753bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1754 return VisitNestedNameSpecifierLoc(TL.getQualifierLoc());
1755}
1756
1757bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1758 DependentTemplateSpecializationTypeLoc TL) {
1759 // Visit the nested-name-specifier, if there is one.
1760 if (TL.getQualifierLoc() && VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1761 return true;
1762
1763 // Visit the template arguments.
1764 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1765 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1766 return true;
1767
1768 return false;
1769}
1770
1771bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1772 if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1773 return true;
1774
1775 return Visit(TL.getNamedTypeLoc());
1776}
1777
1778bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1779 return Visit(TL.getPatternLoc());
1780}
1781
1782bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1783 if (Expr *E = TL.getUnderlyingExpr())
1784 return Visit(MakeCXCursor(E, StmtParent, TU));
1785
1786 return false;
1787}
1788
1789bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1790 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1791}
1792
1793bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1794 return Visit(TL.getValueLoc());
1795}
1796
1797bool CursorVisitor::VisitPipeTypeLoc(PipeTypeLoc TL) {
1798 return Visit(TL.getValueLoc());
1799}
1800
1801#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT)bool CursorVisitor::VisitCLASSTypeLoc(CLASSTypeLoc TL) { return
VisitPARENTLoc(TL); }
\
1802 bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
1803 return Visit##PARENT##Loc(TL); \
1804 }
1805
1806DEFAULT_TYPELOC_IMPL(Complex, Type)bool CursorVisitor::VisitComplexTypeLoc(ComplexTypeLoc TL) { return
VisitTypeLoc(TL); }
1807DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)bool CursorVisitor::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc
TL) { return VisitArrayTypeLoc(TL); }
1808DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)bool CursorVisitor::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc
TL) { return VisitArrayTypeLoc(TL); }
1809DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)bool CursorVisitor::VisitVariableArrayTypeLoc(VariableArrayTypeLoc
TL) { return VisitArrayTypeLoc(TL); }
1810DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)bool CursorVisitor::VisitDependentSizedArrayTypeLoc(DependentSizedArrayTypeLoc
TL) { return VisitArrayTypeLoc(TL); }
1811DEFAULT_TYPELOC_IMPL(DependentAddressSpace, Type)bool CursorVisitor::VisitDependentAddressSpaceTypeLoc(DependentAddressSpaceTypeLoc
TL) { return VisitTypeLoc(TL); }
1812DEFAULT_TYPELOC_IMPL(DependentVector, Type)bool CursorVisitor::VisitDependentVectorTypeLoc(DependentVectorTypeLoc
TL) { return VisitTypeLoc(TL); }
1813DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)bool CursorVisitor::VisitDependentSizedExtVectorTypeLoc(DependentSizedExtVectorTypeLoc
TL) { return VisitTypeLoc(TL); }
1814DEFAULT_TYPELOC_IMPL(Vector, Type)bool CursorVisitor::VisitVectorTypeLoc(VectorTypeLoc TL) { return
VisitTypeLoc(TL); }
1815DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)bool CursorVisitor::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL
) { return VisitVectorTypeLoc(TL); }
1816DEFAULT_TYPELOC_IMPL(ConstantMatrix, MatrixType)bool CursorVisitor::VisitConstantMatrixTypeLoc(ConstantMatrixTypeLoc
TL) { return VisitMatrixTypeLoc(TL); }
1817DEFAULT_TYPELOC_IMPL(DependentSizedMatrix, MatrixType)bool CursorVisitor::VisitDependentSizedMatrixTypeLoc(DependentSizedMatrixTypeLoc
TL) { return VisitMatrixTypeLoc(TL); }
1818DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)bool CursorVisitor::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc
TL) { return VisitFunctionTypeLoc(TL); }
1819DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)bool CursorVisitor::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc
TL) { return VisitFunctionTypeLoc(TL); }
1820DEFAULT_TYPELOC_IMPL(Record, TagType)bool CursorVisitor::VisitRecordTypeLoc(RecordTypeLoc TL) { return
VisitTagTypeLoc(TL); }
1821DEFAULT_TYPELOC_IMPL(Enum, TagType)bool CursorVisitor::VisitEnumTypeLoc(EnumTypeLoc TL) { return
VisitTagTypeLoc(TL); }
1822DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)bool CursorVisitor::VisitSubstTemplateTypeParmTypeLoc(SubstTemplateTypeParmTypeLoc
TL) { return VisitTypeLoc(TL); }
1823DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)bool CursorVisitor::VisitSubstTemplateTypeParmPackTypeLoc(SubstTemplateTypeParmPackTypeLoc
TL) { return VisitTypeLoc(TL); }
1824DEFAULT_TYPELOC_IMPL(Auto, Type)bool CursorVisitor::VisitAutoTypeLoc(AutoTypeLoc TL) { return
VisitTypeLoc(TL); }
1825DEFAULT_TYPELOC_IMPL(BitInt, Type)bool CursorVisitor::VisitBitIntTypeLoc(BitIntTypeLoc TL) { return
VisitTypeLoc(TL); }
1826DEFAULT_TYPELOC_IMPL(DependentBitInt, Type)bool CursorVisitor::VisitDependentBitIntTypeLoc(DependentBitIntTypeLoc
TL) { return VisitTypeLoc(TL); }
1827
1828bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1829 // Visit the nested-name-specifier, if present.
1830 if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1831 if (VisitNestedNameSpecifierLoc(QualifierLoc))
1832 return true;
1833
1834 if (D->isCompleteDefinition()) {
1835 for (const auto &I : D->bases()) {
1836 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU)))
1837 return true;
1838 }
1839 }
1840
1841 return VisitTagDecl(D);
1842}
1843
1844bool CursorVisitor::VisitAttributes(Decl *D) {
1845 for (const auto *I : D->attrs())
1846 if ((TU->ParsingOptions & CXTranslationUnit_VisitImplicitAttributes ||
1847 !I->isImplicit()) &&
1848 Visit(MakeCXCursor(I, D, TU)))
1849 return true;
1850
1851 return false;
1852}
1853
1854//===----------------------------------------------------------------------===//
1855// Data-recursive visitor methods.
1856//===----------------------------------------------------------------------===//
1857
1858namespace {
1859#define DEF_JOB(NAME, DATA, KIND) \
1860 class NAME : public VisitorJob { \
1861 public: \
1862 NAME(const DATA *d, CXCursor parent) \
1863 : VisitorJob(parent, VisitorJob::KIND, d) {} \
1864 static bool classof(const VisitorJob *VJ) { \
1865 return VJ->getKind() == KIND; \
1866 } \
1867 const DATA *get() const { return static_cast<const DATA *>(data[0]); } \
1868 };
1869
1870DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1871DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1872DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1873DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
1874DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1875DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
1876DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
1877#undef DEF_JOB
1878
1879class ExplicitTemplateArgsVisit : public VisitorJob {
1880public:
1881 ExplicitTemplateArgsVisit(const TemplateArgumentLoc *Begin,
1882 const TemplateArgumentLoc *End, CXCursor parent)
1883 : VisitorJob(parent, VisitorJob::ExplicitTemplateArgsVisitKind, Begin,
1884 End) {}
1885 static bool classof(const VisitorJob *VJ) {
1886 return VJ->getKind() == ExplicitTemplateArgsVisitKind;
1887 }
1888 const TemplateArgumentLoc *begin() const {
1889 return static_cast<const TemplateArgumentLoc *>(data[0]);
1890 }
1891 const TemplateArgumentLoc *end() {
1892 return static_cast<const TemplateArgumentLoc *>(data[1]);
1893 }
1894};
1895class DeclVisit : public VisitorJob {
1896public:
1897 DeclVisit(const Decl *D, CXCursor parent, bool isFirst)
1898 : VisitorJob(parent, VisitorJob::DeclVisitKind, D,
1899 isFirst ? (void *)1 : (void *)nullptr) {}
1900 static bool classof(const VisitorJob *VJ) {
1901 return VJ->getKind() == DeclVisitKind;
1902 }
1903 const Decl *get() const { return static_cast<const Decl *>(data[0]); }
1904 bool isFirst() const { return data[1] != nullptr; }
1905};
1906class TypeLocVisit : public VisitorJob {
1907public:
1908 TypeLocVisit(TypeLoc tl, CXCursor parent)
1909 : VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1910 tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1911
1912 static bool classof(const VisitorJob *VJ) {
1913 return VJ->getKind() == TypeLocVisitKind;
1914 }
1915
1916 TypeLoc get() const {
1917 QualType T = QualType::getFromOpaquePtr(data[0]);
1918 return TypeLoc(T, const_cast<void *>(data[1]));
1919 }
1920};
1921
1922class LabelRefVisit : public VisitorJob {
1923public:
1924 LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1925 : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1926 labelLoc.getPtrEncoding()) {}
1927
1928 static bool classof(const VisitorJob *VJ) {
1929 return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1930 }
1931 const LabelDecl *get() const {
1932 return static_cast<const LabelDecl *>(data[0]);
1933 }
1934 SourceLocation getLoc() const {
1935 return SourceLocation::getFromPtrEncoding(data[1]);
1936 }
1937};
1938
1939class NestedNameSpecifierLocVisit : public VisitorJob {
1940public:
1941 NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1942 : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1943 Qualifier.getNestedNameSpecifier(),
1944 Qualifier.getOpaqueData()) {}
1945
1946 static bool classof(const VisitorJob *VJ) {
1947 return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1948 }
1949
1950 NestedNameSpecifierLoc get() const {
1951 return NestedNameSpecifierLoc(
1952 const_cast<NestedNameSpecifier *>(
1953 static_cast<const NestedNameSpecifier *>(data[0])),
1954 const_cast<void *>(data[1]));
1955 }
1956};
1957
1958class DeclarationNameInfoVisit : public VisitorJob {
1959public:
1960 DeclarationNameInfoVisit(const Stmt *S, CXCursor parent)
1961 : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1962 static bool classof(const VisitorJob *VJ) {
1963 return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1964 }
1965 DeclarationNameInfo get() const {
1966 const Stmt *S = static_cast<const Stmt *>(data[0]);
1967 switch (S->getStmtClass()) {
1968 default:
1969 llvm_unreachable("Unhandled Stmt")::llvm::llvm_unreachable_internal("Unhandled Stmt", "clang/tools/libclang/CIndex.cpp"
, 1969)
;
1970 case clang::Stmt::MSDependentExistsStmtClass:
1971 return cast<MSDependentExistsStmt>(S)->getNameInfo();
1972 case Stmt::CXXDependentScopeMemberExprClass:
1973 return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1974 case Stmt::DependentScopeDeclRefExprClass:
1975 return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1976 case Stmt::OMPCriticalDirectiveClass:
1977 return cast<OMPCriticalDirective>(S)->getDirectiveName();
1978 }
1979 }
1980};
1981class MemberRefVisit : public VisitorJob {
1982public:
1983 MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent)
1984 : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1985 L.getPtrEncoding()) {}
1986 static bool classof(const VisitorJob *VJ) {
1987 return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1988 }
1989 const FieldDecl *get() const {
1990 return static_cast<const FieldDecl *>(data[0]);
1991 }
1992 SourceLocation getLoc() const {
1993 return SourceLocation::getFromRawEncoding(
1994 (SourceLocation::UIntTy)(uintptr_t)data[1]);
1995 }
1996};
1997class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitor, void> {
1998 friend class OMPClauseEnqueue;
1999 VisitorWorkList &WL;
2000 CXCursor Parent;
2001
2002public:
2003 EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
2004 : WL(wl), Parent(parent) {}
2005
2006 void VisitAddrLabelExpr(const AddrLabelExpr *E);
2007 void VisitBlockExpr(const BlockExpr *B);
2008 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2009 void VisitCompoundStmt(const CompoundStmt *S);
2010 void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */
2011 }
2012 void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S);
2013 void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E);
2014 void VisitCXXNewExpr(const CXXNewExpr *E);
2015 void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
2016 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E);
2017 void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
2018 void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E);
2019 void VisitCXXTypeidExpr(const CXXTypeidExpr *E);
2020 void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E);
2021 void VisitCXXUuidofExpr(const CXXUuidofExpr *E);
2022 void VisitCXXCatchStmt(const CXXCatchStmt *S);
2023 void VisitCXXForRangeStmt(const CXXForRangeStmt *S);
2024 void VisitDeclRefExpr(const DeclRefExpr *D);
2025 void VisitDeclStmt(const DeclStmt *S);
2026 void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E);
2027 void VisitDesignatedInitExpr(const DesignatedInitExpr *E);
2028 void VisitExplicitCastExpr(const ExplicitCastExpr *E);
2029 void VisitForStmt(const ForStmt *FS);
2030 void VisitGotoStmt(const GotoStmt *GS);
2031 void VisitIfStmt(const IfStmt *If);
2032 void VisitInitListExpr(const InitListExpr *IE);
2033 void VisitMemberExpr(const MemberExpr *M);
2034 void VisitOffsetOfExpr(const OffsetOfExpr *E);
2035 void VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
2036 void VisitObjCMessageExpr(const ObjCMessageExpr *M);
2037 void VisitOverloadExpr(const OverloadExpr *E);
2038 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
2039 void VisitStmt(const Stmt *S);
2040 void VisitSwitchStmt(const SwitchStmt *S);
2041 void VisitWhileStmt(const WhileStmt *W);
2042 void VisitTypeTraitExpr(const TypeTraitExpr *E);
2043 void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E);
2044 void VisitExpressionTraitExpr(const ExpressionTraitExpr *E);
2045 void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U);
2046 void VisitVAArgExpr(const VAArgExpr *E);
2047 void VisitSizeOfPackExpr(const SizeOfPackExpr *E);
2048 void VisitPseudoObjectExpr(const PseudoObjectExpr *E);
2049 void VisitOpaqueValueExpr(const OpaqueValueExpr *E);
2050 void VisitLambdaExpr(const LambdaExpr *E);
2051 void VisitOMPExecutableDirective(const OMPExecutableDirective *D);
2052 void VisitOMPLoopBasedDirective(const OMPLoopBasedDirective *D);
2053 void VisitOMPLoopDirective(const OMPLoopDirective *D);
2054 void VisitOMPParallelDirective(const OMPParallelDirective *D);
2055 void VisitOMPSimdDirective(const OMPSimdDirective *D);
2056 void
2057 VisitOMPLoopTransformationDirective(const OMPLoopTransformationDirective *D);
2058 void VisitOMPTileDirective(const OMPTileDirective *D);
2059 void VisitOMPUnrollDirective(const OMPUnrollDirective *D);
2060 void VisitOMPForDirective(const OMPForDirective *D);
2061 void VisitOMPForSimdDirective(const OMPForSimdDirective *D);
2062 void VisitOMPSectionsDirective(const OMPSectionsDirective *D);
2063 void VisitOMPSectionDirective(const OMPSectionDirective *D);
2064 void VisitOMPSingleDirective(const OMPSingleDirective *D);
2065 void VisitOMPMasterDirective(const OMPMasterDirective *D);
2066 void VisitOMPCriticalDirective(const OMPCriticalDirective *D);
2067 void VisitOMPParallelForDirective(const OMPParallelForDirective *D);
2068 void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D);
2069 void VisitOMPParallelMasterDirective(const OMPParallelMasterDirective *D);
2070 void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D);
2071 void VisitOMPTaskDirective(const OMPTaskDirective *D);
2072 void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D);
2073 void VisitOMPBarrierDirective(const OMPBarrierDirective *D);
2074 void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D);
2075 void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D);
2076 void
2077 VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D);
2078 void VisitOMPCancelDirective(const OMPCancelDirective *D);
2079 void VisitOMPFlushDirective(const OMPFlushDirective *D);
2080 void VisitOMPDepobjDirective(const OMPDepobjDirective *D);
2081 void VisitOMPScanDirective(const OMPScanDirective *D);
2082 void VisitOMPOrderedDirective(const OMPOrderedDirective *D);
2083 void VisitOMPAtomicDirective(const OMPAtomicDirective *D);
2084 void VisitOMPTargetDirective(const OMPTargetDirective *D);
2085 void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D);
2086 void VisitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective *D);
2087 void VisitOMPTargetExitDataDirective(const OMPTargetExitDataDirective *D);
2088 void VisitOMPTargetParallelDirective(const OMPTargetParallelDirective *D);
2089 void
2090 VisitOMPTargetParallelForDirective(const OMPTargetParallelForDirective *D);
2091 void VisitOMPTeamsDirective(const OMPTeamsDirective *D);
2092 void VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D);
2093 void VisitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective *D);
2094 void VisitOMPMasterTaskLoopDirective(const OMPMasterTaskLoopDirective *D);
2095 void
2096 VisitOMPMasterTaskLoopSimdDirective(const OMPMasterTaskLoopSimdDirective *D);
2097 void VisitOMPParallelMasterTaskLoopDirective(
2098 const OMPParallelMasterTaskLoopDirective *D);
2099 void VisitOMPParallelMasterTaskLoopSimdDirective(
2100 const OMPParallelMasterTaskLoopSimdDirective *D);
2101 void VisitOMPDistributeDirective(const OMPDistributeDirective *D);
2102 void VisitOMPDistributeParallelForDirective(
2103 const OMPDistributeParallelForDirective *D);
2104 void VisitOMPDistributeParallelForSimdDirective(
2105 const OMPDistributeParallelForSimdDirective *D);
2106 void VisitOMPDistributeSimdDirective(const OMPDistributeSimdDirective *D);
2107 void VisitOMPTargetParallelForSimdDirective(
2108 const OMPTargetParallelForSimdDirective *D);
2109 void VisitOMPTargetSimdDirective(const OMPTargetSimdDirective *D);
2110 void VisitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective *D);
2111 void VisitOMPTeamsDistributeSimdDirective(
2112 const OMPTeamsDistributeSimdDirective *D);
2113 void VisitOMPTeamsDistributeParallelForSimdDirective(
2114 const OMPTeamsDistributeParallelForSimdDirective *D);
2115 void VisitOMPTeamsDistributeParallelForDirective(
2116 const OMPTeamsDistributeParallelForDirective *D);
2117 void VisitOMPTargetTeamsDirective(const OMPTargetTeamsDirective *D);
2118 void VisitOMPTargetTeamsDistributeDirective(
2119 const OMPTargetTeamsDistributeDirective *D);
2120 void VisitOMPTargetTeamsDistributeParallelForDirective(
2121 const OMPTargetTeamsDistributeParallelForDirective *D);
2122 void VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2123 const OMPTargetTeamsDistributeParallelForSimdDirective *D);
2124 void VisitOMPTargetTeamsDistributeSimdDirective(
2125 const OMPTargetTeamsDistributeSimdDirective *D);
2126
2127private:
2128 void AddDeclarationNameInfo(const Stmt *S);
2129 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
2130 void AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2131 unsigned NumTemplateArgs);
2132 void AddMemberRef(const FieldDecl *D, SourceLocation L);
2133 void AddStmt(const Stmt *S);
2134 void AddDecl(const Decl *D, bool isFirst = true);
2135 void AddTypeLoc(TypeSourceInfo *TI);
2136 void EnqueueChildren(const Stmt *S);
2137 void EnqueueChildren(const OMPClause *S);
2138};
2139} // namespace
2140
2141void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
2142 // 'S' should always be non-null, since it comes from the
2143 // statement we are visiting.
2144 WL.push_back(DeclarationNameInfoVisit(S, Parent));
2145}
2146
2147void EnqueueVisitor::AddNestedNameSpecifierLoc(
2148 NestedNameSpecifierLoc Qualifier) {
2149 if (Qualifier)
2150 WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
2151}
2152
2153void EnqueueVisitor::AddStmt(const Stmt *S) {
2154 if (S)
2155 WL.push_back(StmtVisit(S, Parent));
2156}
2157void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
2158 if (D)
2159 WL.push_back(DeclVisit(D, Parent, isFirst));
2160}
2161void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2162 unsigned NumTemplateArgs) {
2163 WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent));
2164}
2165void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
2166 if (D)
2167 WL.push_back(MemberRefVisit(D, L, Parent));
2168}
2169void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
2170 if (TI)
2171 WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
2172}
2173void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
2174 unsigned size = WL.size();
2175 for (const Stmt *SubStmt : S->children()) {
2176 AddStmt(SubStmt);
2177 }
2178 if (size == WL.size())
2179 return;
2180 // Now reverse the entries we just added. This will match the DFS
2181 // ordering performed by the worklist.
2182 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2183 std::reverse(I, E);
2184}
2185namespace {
2186class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
2187 EnqueueVisitor *Visitor;
2188 /// Process clauses with list of variables.
2189 template <typename T> void VisitOMPClauseList(T *Node);
2190
2191public:
2192 OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) {}
2193#define GEN_CLANG_CLAUSE_CLASS
2194#define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(const Class *C);
2195#include "llvm/Frontend/OpenMP/OMP.inc"
2196 void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C);
2197 void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C);
2198};
2199
2200void OMPClauseEnqueue::VisitOMPClauseWithPreInit(
2201 const OMPClauseWithPreInit *C) {
2202 Visitor->AddStmt(C->getPreInitStmt());
2203}
2204
2205void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate(
2206 const OMPClauseWithPostUpdate *C) {
2207 VisitOMPClauseWithPreInit(C);
2208 Visitor->AddStmt(C->getPostUpdateExpr());
2209}
2210
2211void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
2212 VisitOMPClauseWithPreInit(C);
2213 Visitor->AddStmt(C->getCondition());
2214}
2215
2216void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
2217 Visitor->AddStmt(C->getCondition());
2218}
2219
2220void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
2221 VisitOMPClauseWithPreInit(C);
2222 Visitor->AddStmt(C->getNumThreads());
2223}
2224
2225void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2226 Visitor->AddStmt(C->getSafelen());
2227}
2228
2229void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2230 Visitor->AddStmt(C->getSimdlen());
2231}
2232
2233void OMPClauseEnqueue::VisitOMPSizesClause(const OMPSizesClause *C) {
2234 for (auto E : C->getSizesRefs())
2235 Visitor->AddStmt(E);
2236}
2237
2238void OMPClauseEnqueue::VisitOMPFullClause(const OMPFullClause *C) {}
2239
2240void OMPClauseEnqueue::VisitOMPPartialClause(const OMPPartialClause *C) {
2241 Visitor->AddStmt(C->getFactor());
2242}
2243
2244void OMPClauseEnqueue::VisitOMPAllocatorClause(const OMPAllocatorClause *C) {
2245 Visitor->AddStmt(C->getAllocator());
2246}
2247
2248void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2249 Visitor->AddStmt(C->getNumForLoops());
2250}
2251
2252void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) {}
2253
2254void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) {}
2255
2256void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
2257 VisitOMPClauseWithPreInit(C);
2258 Visitor->AddStmt(C->getChunkSize());
2259}
2260
2261void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2262 Visitor->AddStmt(C->getNumForLoops());
2263}
2264
2265void OMPClauseEnqueue::VisitOMPDetachClause(const OMPDetachClause *C) {
2266 Visitor->AddStmt(C->getEventHandler());
2267}
2268
2269void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2270
2271void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2272
2273void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2274
2275void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2276
2277void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2278
2279void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2280
2281void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2282
2283void OMPClauseEnqueue::VisitOMPCompareClause(const OMPCompareClause *) {}
2284
2285void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2286
2287void OMPClauseEnqueue::VisitOMPAcqRelClause(const OMPAcqRelClause *) {}
2288
2289void OMPClauseEnqueue::VisitOMPAcquireClause(const OMPAcquireClause *) {}
2290
2291void OMPClauseEnqueue::VisitOMPReleaseClause(const OMPReleaseClause *) {}
2292
2293void OMPClauseEnqueue::VisitOMPRelaxedClause(const OMPRelaxedClause *) {}
2294
2295void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2296
2297void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2298
2299void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
2300
2301void OMPClauseEnqueue::VisitOMPInitClause(const OMPInitClause *C) {
2302 VisitOMPClauseList(C);
2303}
2304
2305void OMPClauseEnqueue::VisitOMPUseClause(const OMPUseClause *C) {
2306 Visitor->AddStmt(C->getInteropVar());
2307}
2308
2309void OMPClauseEnqueue::VisitOMPDestroyClause(const OMPDestroyClause *C) {
2310 if (C->getInteropVar())
2311 Visitor->AddStmt(C->getInteropVar());
2312}
2313
2314void OMPClauseEnqueue::VisitOMPNovariantsClause(const OMPNovariantsClause *C) {
2315 Visitor->AddStmt(C->getCondition());
2316}
2317
2318void OMPClauseEnqueue::VisitOMPNocontextClause(const OMPNocontextClause *C) {
2319 Visitor->AddStmt(C->getCondition());
2320}
2321
2322void OMPClauseEnqueue::VisitOMPFilterClause(const OMPFilterClause *C) {
2323 VisitOMPClauseWithPreInit(C);
2324 Visitor->AddStmt(C->getThreadID());
2325}
2326
2327void OMPClauseEnqueue::VisitOMPAlignClause(const OMPAlignClause *C) {
2328 Visitor->AddStmt(C->getAlignment());
2329}
2330
2331void OMPClauseEnqueue::VisitOMPUnifiedAddressClause(
2332 const OMPUnifiedAddressClause *) {}
2333
2334void OMPClauseEnqueue::VisitOMPUnifiedSharedMemoryClause(
2335 const OMPUnifiedSharedMemoryClause *) {}
2336
2337void OMPClauseEnqueue::VisitOMPReverseOffloadClause(
2338 const OMPReverseOffloadClause *) {}
2339
2340void OMPClauseEnqueue::VisitOMPDynamicAllocatorsClause(
2341 const OMPDynamicAllocatorsClause *) {}
2342
2343void OMPClauseEnqueue::VisitOMPAtomicDefaultMemOrderClause(
2344 const OMPAtomicDefaultMemOrderClause *) {}
2345
2346void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2347 Visitor->AddStmt(C->getDevice());
2348}
2349
2350void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
2351 VisitOMPClauseWithPreInit(C);
2352 Visitor->AddStmt(C->getNumTeams());
2353}
2354
2355void OMPClauseEnqueue::VisitOMPThreadLimitClause(
2356 const OMPThreadLimitClause *C) {
2357 VisitOMPClauseWithPreInit(C);
2358 Visitor->AddStmt(C->getThreadLimit());
2359}
2360
2361void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2362 Visitor->AddStmt(C->getPriority());
2363}
2364
2365void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2366 Visitor->AddStmt(C->getGrainsize());
2367}
2368
2369void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2370 Visitor->AddStmt(C->getNumTasks());
2371}
2372
2373void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2374 Visitor->AddStmt(C->getHint());
2375}
2376
2377template <typename T> void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
2378 for (const auto *I : Node->varlists()) {
2379 Visitor->AddStmt(I);
2380 }
2381}
2382
2383void OMPClauseEnqueue::VisitOMPInclusiveClause(const OMPInclusiveClause *C) {
2384 VisitOMPClauseList(C);
2385}
2386void OMPClauseEnqueue::VisitOMPExclusiveClause(const OMPExclusiveClause *C) {
2387 VisitOMPClauseList(C);
2388}
2389void OMPClauseEnqueue::VisitOMPAllocateClause(const OMPAllocateClause *C) {
2390 VisitOMPClauseList(C);
2391 Visitor->AddStmt(C->getAllocator());
2392}
2393void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
2394 VisitOMPClauseList(C);
2395 for (const auto *E : C->private_copies()) {
2396 Visitor->AddStmt(E);
2397 }
2398}
2399void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2400 const OMPFirstprivateClause *C) {
2401 VisitOMPClauseList(C);
2402 VisitOMPClauseWithPreInit(C);
2403 for (const auto *E : C->private_copies()) {
2404 Visitor->AddStmt(E);
2405 }
2406 for (const auto *E : C->inits()) {
2407 Visitor->AddStmt(E);
2408 }
2409}
2410void OMPClauseEnqueue::VisitOMPLastprivateClause(
2411 const OMPLastprivateClause *C) {
2412 VisitOMPClauseList(C);
2413 VisitOMPClauseWithPostUpdate(C);
2414 for (auto *E : C->private_copies()) {
2415 Visitor->AddStmt(E);
2416 }
2417 for (auto *E : C->source_exprs()) {
2418 Visitor->AddStmt(E);
2419 }
2420 for (auto *E : C->destination_exprs()) {
2421 Visitor->AddStmt(E);
2422 }
2423 for (auto *E : C->assignment_ops()) {
2424 Visitor->AddStmt(E);
2425 }
2426}
2427void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
2428 VisitOMPClauseList(C);
2429}
2430void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2431 VisitOMPClauseList(C);
2432 VisitOMPClauseWithPostUpdate(C);
2433 for (auto *E : C->privates()) {
2434 Visitor->AddStmt(E);
2435 }
2436 for (auto *E : C->lhs_exprs()) {
2437 Visitor->AddStmt(E);
2438 }
2439 for (auto *E : C->rhs_exprs()) {
2440 Visitor->AddStmt(E);
2441 }
2442 for (auto *E : C->reduction_ops()) {
2443 Visitor->AddStmt(E);
2444 }
2445 if (C->getModifier() == clang::OMPC_REDUCTION_inscan) {
2446 for (auto *E : C->copy_ops()) {
2447 Visitor->AddStmt(E);
2448 }
2449 for (auto *E : C->copy_array_temps()) {
2450 Visitor->AddStmt(E);
2451 }
2452 for (auto *E : C->copy_array_elems()) {
2453 Visitor->AddStmt(E);
2454 }
2455 }
2456}
2457void OMPClauseEnqueue::VisitOMPTaskReductionClause(
2458 const OMPTaskReductionClause *C) {
2459 VisitOMPClauseList(C);
2460 VisitOMPClauseWithPostUpdate(C);
2461 for (auto *E : C->privates()) {
2462 Visitor->AddStmt(E);
2463 }
2464 for (auto *E : C->lhs_exprs()) {
2465 Visitor->AddStmt(E);
2466 }
2467 for (auto *E : C->rhs_exprs()) {
2468 Visitor->AddStmt(E);
2469 }
2470 for (auto *E : C->reduction_ops()) {
2471 Visitor->AddStmt(E);
2472 }
2473}
2474void OMPClauseEnqueue::VisitOMPInReductionClause(
2475 const OMPInReductionClause *C) {
2476 VisitOMPClauseList(C);
2477 VisitOMPClauseWithPostUpdate(C);
2478 for (auto *E : C->privates()) {
2479 Visitor->AddStmt(E);
2480 }
2481 for (auto *E : C->lhs_exprs()) {
2482 Visitor->AddStmt(E);
2483 }
2484 for (auto *E : C->rhs_exprs()) {
2485 Visitor->AddStmt(E);
2486 }
2487 for (auto *E : C->reduction_ops()) {
2488 Visitor->AddStmt(E);
2489 }
2490 for (auto *E : C->taskgroup_descriptors())
2491 Visitor->AddStmt(E);
2492}
2493void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2494 VisitOMPClauseList(C);
2495 VisitOMPClauseWithPostUpdate(C);
2496 for (const auto *E : C->privates()) {
2497 Visitor->AddStmt(E);
2498 }
2499 for (const auto *E : C->inits()) {
2500 Visitor->AddStmt(E);
2501 }
2502 for (const auto *E : C->updates()) {
2503 Visitor->AddStmt(E);
2504 }
2505 for (const auto *E : C->finals()) {
2506 Visitor->AddStmt(E);
2507 }
2508 Visitor->AddStmt(C->getStep());
2509 Visitor->AddStmt(C->getCalcStep());
2510}
2511void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2512 VisitOMPClauseList(C);
2513 Visitor->AddStmt(C->getAlignment());
2514}
2515void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2516 VisitOMPClauseList(C);
2517 for (auto *E : C->source_exprs()) {
2518 Visitor->AddStmt(E);
2519 }
2520 for (auto *E : C->destination_exprs()) {
2521 Visitor->AddStmt(E);
2522 }
2523 for (auto *E : C->assignment_ops()) {
2524 Visitor->AddStmt(E);
2525 }
2526}
2527void OMPClauseEnqueue::VisitOMPCopyprivateClause(
2528 const OMPCopyprivateClause *C) {
2529 VisitOMPClauseList(C);
2530 for (auto *E : C->source_exprs()) {
2531 Visitor->AddStmt(E);
2532 }
2533 for (auto *E : C->destination_exprs()) {
2534 Visitor->AddStmt(E);
2535 }
2536 for (auto *E : C->assignment_ops()) {
2537 Visitor->AddStmt(E);
2538 }
2539}
2540void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2541 VisitOMPClauseList(C);
2542}
2543void OMPClauseEnqueue::VisitOMPDepobjClause(const OMPDepobjClause *C) {
2544 Visitor->AddStmt(C->getDepobj());
2545}
2546void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2547 VisitOMPClauseList(C);
2548}
2549void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2550 VisitOMPClauseList(C);
2551}
2552void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2553 const OMPDistScheduleClause *C) {
2554 VisitOMPClauseWithPreInit(C);
2555 Visitor->AddStmt(C->getChunkSize());
2556}
2557void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2558 const OMPDefaultmapClause * /*C*/) {}
2559void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2560 VisitOMPClauseList(C);
2561}
2562void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2563 VisitOMPClauseList(C);
2564}
2565void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(
2566 const OMPUseDevicePtrClause *C) {
2567 VisitOMPClauseList(C);
2568}
2569void OMPClauseEnqueue::VisitOMPUseDeviceAddrClause(
2570 const OMPUseDeviceAddrClause *C) {
2571 VisitOMPClauseList(C);
2572}
2573void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(
2574 const OMPIsDevicePtrClause *C) {
2575 VisitOMPClauseList(C);
2576}
2577void OMPClauseEnqueue::VisitOMPHasDeviceAddrClause(
2578 const OMPHasDeviceAddrClause *C) {
2579 VisitOMPClauseList(C);
2580}
2581void OMPClauseEnqueue::VisitOMPNontemporalClause(
2582 const OMPNontemporalClause *C) {
2583 VisitOMPClauseList(C);
2584 for (const auto *E : C->private_refs())
2585 Visitor->AddStmt(E);
2586}
2587void OMPClauseEnqueue::VisitOMPOrderClause(const OMPOrderClause *C) {}
2588void OMPClauseEnqueue::VisitOMPUsesAllocatorsClause(
2589 const OMPUsesAllocatorsClause *C) {
2590 for (unsigned I = 0, E = C->getNumberOfAllocators(); I < E; ++I) {
2591 const OMPUsesAllocatorsClause::Data &D = C->getAllocatorData(I);
2592 Visitor->AddStmt(D.Allocator);
2593 Visitor->AddStmt(D.AllocatorTraits);
2594 }
2595}
2596void OMPClauseEnqueue::VisitOMPAffinityClause(const OMPAffinityClause *C) {
2597 Visitor->AddStmt(C->getModifier());
2598 for (const Expr *E : C->varlists())
2599 Visitor->AddStmt(E);
2600}
2601void OMPClauseEnqueue::VisitOMPBindClause(const OMPBindClause *C) {}
2602
2603} // namespace
2604
2605void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2606 unsigned size = WL.size();
2607 OMPClauseEnqueue Visitor(this);
2608 Visitor.Visit(S);
2609 if (size == WL.size())
2610 return;
2611 // Now reverse the entries we just added. This will match the DFS
2612 // ordering performed by the worklist.
2613 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2614 std::reverse(I, E);
2615}
2616void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
2617 WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2618}
2619void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
2620 AddDecl(B->getBlockDecl());
2621}
2622void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2623 EnqueueChildren(E);
2624 AddTypeLoc(E->getTypeSourceInfo());
2625}
2626void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
2627 for (auto &I : llvm::reverse(S->body()))
2628 AddStmt(I);
2629}
2630void EnqueueVisitor::VisitMSDependentExistsStmt(
2631 const MSDependentExistsStmt *S) {
2632 AddStmt(S->getSubStmt());
2633 AddDeclarationNameInfo(S);
2634 if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2635 AddNestedNameSpecifierLoc(QualifierLoc);
2636}
2637
2638void EnqueueVisitor::VisitCXXDependentScopeMemberExpr(
2639 const CXXDependentScopeMemberExpr *E) {
2640 if (E->hasExplicitTemplateArgs())
2641 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
2642 AddDeclarationNameInfo(E);
2643 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2644 AddNestedNameSpecifierLoc(QualifierLoc);
2645 if (!E->isImplicitAccess())
2646 AddStmt(E->getBase());
2647}
2648void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
2649 // Enqueue the initializer , if any.
2650 AddStmt(E->getInitializer());
2651 // Enqueue the array size, if any.
2652 AddStmt(E->getArraySize().getValueOr(nullptr));
2653 // Enqueue the allocated type.
2654 AddTypeLoc(E->getAllocatedTypeSourceInfo());
2655 // Enqueue the placement arguments.
2656 for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
2657 AddStmt(E->getPlacementArg(I - 1));
2658}
2659void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
2660 for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
2661 AddStmt(CE->getArg(I - 1));
2662 AddStmt(CE->getCallee());
2663 AddStmt(CE->getArg(0));
2664}
2665void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2666 const CXXPseudoDestructorExpr *E) {
2667 // Visit the name of the type being destroyed.
2668 AddTypeLoc(E->getDestroyedTypeInfo());
2669 // Visit the scope type that looks disturbingly like the nested-name-specifier
2670 // but isn't.
2671 AddTypeLoc(E->getScopeTypeInfo());
2672 // Visit the nested-name-specifier.
2673 if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2674 AddNestedNameSpecifierLoc(QualifierLoc);
2675 // Visit base expression.
2676 AddStmt(E->getBase());
2677}
2678void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2679 const CXXScalarValueInitExpr *E) {
2680 AddTypeLoc(E->getTypeSourceInfo());
2681}
2682void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2683 const CXXTemporaryObjectExpr *E) {
2684 EnqueueChildren(E);
2685 AddTypeLoc(E->getTypeSourceInfo());
2686}
2687void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2688 EnqueueChildren(E);
2689 if (E->isTypeOperand())
2690 AddTypeLoc(E->getTypeOperandSourceInfo());
2691}
2692
2693void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2694 const CXXUnresolvedConstructExpr *E) {
2695 EnqueueChildren(E);
2696 AddTypeLoc(E->getTypeSourceInfo());
2697}
2698void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
2699 EnqueueChildren(E);
2700 if (E->isTypeOperand())
2701 AddTypeLoc(E->getTypeOperandSourceInfo());
2702}
2703
2704void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
2705 EnqueueChildren(S);
2706 AddDecl(S->getExceptionDecl());
2707}
2708
2709void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
2710 AddStmt(S->getBody());
2711 AddStmt(S->getRangeInit());
2712 AddDecl(S->getLoopVariable());
2713}
2714
2715void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
2716 if (DR->hasExplicitTemplateArgs())
2717 AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
2718 WL.push_back(DeclRefExprParts(DR, Parent));
2719}
2720void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2721 const DependentScopeDeclRefExpr *E) {
2722 if (E->hasExplicitTemplateArgs())
2723 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
2724 AddDeclarationNameInfo(E);
2725 AddNestedNameSpecifierLoc(E->getQualifierLoc());
2726}
2727void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
2728 unsigned size = WL.size();
2729 bool isFirst = true;
2730 for (const auto *D : S->decls()) {
2731 AddDecl(D, isFirst);
2732 isFirst = false;
2733 }
2734 if (size == WL.size())
2735 return;
2736 // Now reverse the entries we just added. This will match the DFS
2737 // ordering performed by the worklist.
2738 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2739 std::reverse(I, E);
2740}
2741void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
2742 AddStmt(E->getInit());
2743 for (const DesignatedInitExpr::Designator &D :
2744 llvm::reverse(E->designators())) {
2745 if (D.isFieldDesignator()) {
2746 if (FieldDecl *Field = D.getField())
2747 AddMemberRef(Field, D.getFieldLoc());
2748 continue;
2749 }
2750 if (D.isArrayDesignator()) {
2751 AddStmt(E->getArrayIndex(D));
2752 continue;
2753 }
2754 assert(D.isArrayRangeDesignator() && "Unknown designator kind")(static_cast <bool> (D.isArrayRangeDesignator() &&
"Unknown designator kind") ? void (0) : __assert_fail ("D.isArrayRangeDesignator() && \"Unknown designator kind\""
, "clang/tools/libclang/CIndex.cpp", 2754, __extension__ __PRETTY_FUNCTION__
))
;
2755 AddStmt(E->getArrayRangeEnd(D));
2756 AddStmt(E->getArrayRangeStart(D));
2757 }
2758}
2759void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
2760 EnqueueChildren(E);
2761 AddTypeLoc(E->getTypeInfoAsWritten());
2762}
2763void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
2764 AddStmt(FS->getBody());
2765 AddStmt(FS->getInc());
2766 AddStmt(FS->getCond());
2767 AddDecl(FS->getConditionVariable());
2768 AddStmt(FS->getInit());
2769}
2770void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
2771 WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2772}
2773void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
2774 AddStmt(If->getElse());
2775 AddStmt(If->getThen());
2776 AddStmt(If->getCond());
2777 AddStmt(If->getInit());
2778 AddDecl(If->getConditionVariable());
2779}
2780void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
2781 // We care about the syntactic form of the initializer list, only.
2782 if (InitListExpr *Syntactic = IE->getSyntacticForm())
2783 IE = Syntactic;
2784 EnqueueChildren(IE);
2785}
2786void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
2787 WL.push_back(MemberExprParts(M, Parent));
2788
2789 // If the base of the member access expression is an implicit 'this', don't
2790 // visit it.
2791 // FIXME: If we ever want to show these implicit accesses, this will be
2792 // unfortunate. However, clang_getCursor() relies on this behavior.
2793 if (M->isImplicitAccess())
2794 return;
2795
2796 // Ignore base anonymous struct/union fields, otherwise they will shadow the
2797 // real field that we are interested in.
2798 if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2799 if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2800 if (FD->isAnonymousStructOrUnion()) {
2801 AddStmt(SubME->getBase());
2802 return;
2803 }
2804 }
2805 }
2806
2807 AddStmt(M->getBase());
2808}
2809void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
2810 AddTypeLoc(E->getEncodedTypeSourceInfo());
2811}
2812void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
2813 EnqueueChildren(M);
2814 AddTypeLoc(M->getClassReceiverTypeInfo());
2815}
2816void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
2817 // Visit the components of the offsetof expression.
2818 for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
2819 const OffsetOfNode &Node = E->getComponent(I - 1);
2820 switch (Node.getKind()) {
2821 case OffsetOfNode::Array:
2822 AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2823 break;
2824 case OffsetOfNode::Field:
2825 AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2826 break;
2827 case OffsetOfNode::Identifier:
2828 case OffsetOfNode::Base:
2829 continue;
2830 }
2831 }
2832 // Visit the type into which we're computing the offset.
2833 AddTypeLoc(E->getTypeSourceInfo());
2834}
2835void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
2836 if (E->hasExplicitTemplateArgs())
2837 AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
2838 WL.push_back(OverloadExprParts(E, Parent));
2839}
2840void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2841 const UnaryExprOrTypeTraitExpr *E) {
2842 EnqueueChildren(E);
2843 if (E->isArgumentType())
2844 AddTypeLoc(E->getArgumentTypeInfo());
2845}
2846void EnqueueVisitor::VisitStmt(const Stmt *S) { EnqueueChildren(S); }
2847void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
2848 AddStmt(S->getBody());
2849 AddStmt(S->getCond());
2850 AddDecl(S->getConditionVariable());
2851}
2852
2853void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
2854 AddStmt(W->getBody());
2855 AddStmt(W->getCond());
2856 AddDecl(W->getConditionVariable());
2857}
2858
2859void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
2860 for (unsigned I = E->getNumArgs(); I > 0; --I)
2861 AddTypeLoc(E->getArg(I - 1));
2862}
2863
2864void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
2865 AddTypeLoc(E->getQueriedTypeSourceInfo());
2866}
2867
2868void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
2869 EnqueueChildren(E);
2870}
2871
2872void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
2873 VisitOverloadExpr(U);
2874 if (!U->isImplicitAccess())
2875 AddStmt(U->getBase());
2876}
2877void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
2878 AddStmt(E->getSubExpr());
2879 AddTypeLoc(E->getWrittenTypeInfo());
2880}
2881void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
2882 WL.push_back(SizeOfPackExprParts(E, Parent));
2883}
2884void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
2885 // If the opaque value has a source expression, just transparently
2886 // visit that. This is useful for (e.g.) pseudo-object expressions.
2887 if (Expr *SourceExpr = E->getSourceExpr())
2888 return Visit(SourceExpr);
2889}
2890void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
2891 AddStmt(E->getBody());
2892 WL.push_back(LambdaExprParts(E, Parent));
2893}
2894void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
2895 // Treat the expression like its syntactic form.
2896 Visit(E->getSyntacticForm());
2897}
2898
2899void EnqueueVisitor::VisitOMPExecutableDirective(
2900 const OMPExecutableDirective *D) {
2901 EnqueueChildren(D);
2902 for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2903 E = D->clauses().end();
2904 I != E; ++I)
2905 EnqueueChildren(*I);
2906}
2907
2908void EnqueueVisitor::VisitOMPLoopBasedDirective(
2909 const OMPLoopBasedDirective *D) {
2910 VisitOMPExecutableDirective(D);
2911}
2912
2913void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2914 VisitOMPLoopBasedDirective(D);
2915}
2916
2917void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2918 VisitOMPExecutableDirective(D);
2919}
2920
2921void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
2922 VisitOMPLoopDirective(D);
2923}
2924
2925void EnqueueVisitor::VisitOMPLoopTransformationDirective(
2926 const OMPLoopTransformationDirective *D) {
2927 VisitOMPLoopBasedDirective(D);
2928}
2929
2930void EnqueueVisitor::VisitOMPTileDirective(const OMPTileDirective *D) {
2931 VisitOMPLoopTransformationDirective(D);
2932}
2933
2934void EnqueueVisitor::VisitOMPUnrollDirective(const OMPUnrollDirective *D) {
2935 VisitOMPLoopTransformationDirective(D);
2936}
2937
2938void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
2939 VisitOMPLoopDirective(D);
2940}
2941
2942void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2943 VisitOMPLoopDirective(D);
2944}
2945
2946void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2947 VisitOMPExecutableDirective(D);
2948}
2949
2950void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2951 VisitOMPExecutableDirective(D);
2952}
2953
2954void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2955 VisitOMPExecutableDirective(D);
2956}
2957
2958void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2959 VisitOMPExecutableDirective(D);
2960}
2961
2962void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2963 VisitOMPExecutableDirective(D);
2964 AddDeclarationNameInfo(D);
2965}
2966
2967void EnqueueVisitor::VisitOMPParallelForDirective(
2968 const OMPParallelForDirective *D) {
2969 VisitOMPLoopDirective(D);
2970}
2971
2972void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2973 const OMPParallelForSimdDirective *D) {
2974 VisitOMPLoopDirective(D);
2975}
2976
2977void EnqueueVisitor::VisitOMPParallelMasterDirective(
2978 const OMPParallelMasterDirective *D) {
2979 VisitOMPExecutableDirective(D);
2980}
2981
2982void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2983 const OMPParallelSectionsDirective *D) {
2984 VisitOMPExecutableDirective(D);
2985}
2986
2987void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2988 VisitOMPExecutableDirective(D);
2989}
2990
2991void EnqueueVisitor::VisitOMPTaskyieldDirective(
2992 const OMPTaskyieldDirective *D) {
2993 VisitOMPExecutableDirective(D);
2994}
2995
2996void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2997 VisitOMPExecutableDirective(D);
2998}
2999
3000void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
3001 VisitOMPExecutableDirective(D);
3002}
3003
3004void EnqueueVisitor::VisitOMPTaskgroupDirective(
3005 const OMPTaskgroupDirective *D) {
3006 VisitOMPExecutableDirective(D);
3007 if (const Expr *E = D->getReductionRef())
3008 VisitStmt(E);
3009}
3010
3011void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
3012 VisitOMPExecutableDirective(D);
3013}
3014
3015void EnqueueVisitor::VisitOMPDepobjDirective(const OMPDepobjDirective *D) {
3016 VisitOMPExecutableDirective(D);
3017}
3018
3019void EnqueueVisitor::VisitOMPScanDirective(const OMPScanDirective *D) {
3020 VisitOMPExecutableDirective(D);
3021}
3022
3023void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
3024 VisitOMPExecutableDirective(D);
3025}
3026
3027void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
3028 VisitOMPExecutableDirective(D);
3029}
3030
3031void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
3032 VisitOMPExecutableDirective(D);
3033}
3034
3035void EnqueueVisitor::VisitOMPTargetDataDirective(
3036 const OMPTargetDataDirective *D) {
3037 VisitOMPExecutableDirective(D);
3038}
3039
3040void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
3041 const OMPTargetEnterDataDirective *D) {
3042 VisitOMPExecutableDirective(D);
3043}
3044
3045void EnqueueVisitor::VisitOMPTargetExitDataDirective(
3046 const OMPTargetExitDataDirective *D) {
3047 VisitOMPExecutableDirective(D);
3048}
3049
3050void EnqueueVisitor::VisitOMPTargetParallelDirective(
3051 const OMPTargetParallelDirective *D) {
3052 VisitOMPExecutableDirective(D);
3053}
3054
3055void EnqueueVisitor::VisitOMPTargetParallelForDirective(
3056 const OMPTargetParallelForDirective *D) {
3057 VisitOMPLoopDirective(D);
3058}
3059
3060void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
3061 VisitOMPExecutableDirective(D);
3062}
3063
3064void EnqueueVisitor::VisitOMPCancellationPointDirective(
3065 const OMPCancellationPointDirective *D) {
3066 VisitOMPExecutableDirective(D);
3067}
3068
3069void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
3070 VisitOMPExecutableDirective(D);
3071}
3072
3073void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
3074 VisitOMPLoopDirective(D);
3075}
3076
3077void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
3078 const OMPTaskLoopSimdDirective *D) {
3079 VisitOMPLoopDirective(D);
3080}
3081
3082void EnqueueVisitor::VisitOMPMasterTaskLoopDirective(
3083 const OMPMasterTaskLoopDirective *D) {
3084 VisitOMPLoopDirective(D);
3085}
3086
3087void EnqueueVisitor::VisitOMPMasterTaskLoopSimdDirective(
3088 const OMPMasterTaskLoopSimdDirective *D) {
3089 VisitOMPLoopDirective(D);
3090}
3091
3092void EnqueueVisitor::VisitOMPParallelMasterTaskLoopDirective(
3093 const OMPParallelMasterTaskLoopDirective *D) {
3094 VisitOMPLoopDirective(D);
3095}
3096
3097void EnqueueVisitor::VisitOMPParallelMasterTaskLoopSimdDirective(
3098 const OMPParallelMasterTaskLoopSimdDirective *D) {
3099 VisitOMPLoopDirective(D);
3100}
3101
3102void EnqueueVisitor::VisitOMPDistributeDirective(
3103 const OMPDistributeDirective *D) {
3104 VisitOMPLoopDirective(D);
3105}
3106
3107void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
3108 const OMPDistributeParallelForDirective *D) {
3109 VisitOMPLoopDirective(D);
3110}
3111
3112void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
3113 const OMPDistributeParallelForSimdDirective *D) {
3114 VisitOMPLoopDirective(D);
3115}
3116
3117void EnqueueVisitor::VisitOMPDistributeSimdDirective(
3118 const OMPDistributeSimdDirective *D) {
3119 VisitOMPLoopDirective(D);
3120}
3121
3122void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
3123 const OMPTargetParallelForSimdDirective *D) {
3124 VisitOMPLoopDirective(D);
3125}
3126
3127void EnqueueVisitor::VisitOMPTargetSimdDirective(
3128 const OMPTargetSimdDirective *D) {
3129 VisitOMPLoopDirective(D);
3130}
3131
3132void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
3133 const OMPTeamsDistributeDirective *D) {
3134 VisitOMPLoopDirective(D);
3135}
3136
3137void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
3138 const OMPTeamsDistributeSimdDirective *D) {
3139 VisitOMPLoopDirective(D);
3140}
3141
3142void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective(
3143 const OMPTeamsDistributeParallelForSimdDirective *D) {
3144 VisitOMPLoopDirective(D);
3145}
3146
3147void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective(
3148 const OMPTeamsDistributeParallelForDirective *D) {
3149 VisitOMPLoopDirective(D);
3150}
3151
3152void EnqueueVisitor::VisitOMPTargetTeamsDirective(
3153 const OMPTargetTeamsDirective *D) {
3154 VisitOMPExecutableDirective(D);
3155}
3156
3157void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective(
3158 const OMPTargetTeamsDistributeDirective *D) {
3159 VisitOMPLoopDirective(D);
3160}
3161
3162void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective(
3163 const OMPTargetTeamsDistributeParallelForDirective *D) {
3164 VisitOMPLoopDirective(D);
3165}
3166
3167void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
3168 const OMPTargetTeamsDistributeParallelForSimdDirective *D) {
3169 VisitOMPLoopDirective(D);
3170}
3171
3172void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective(
3173 const OMPTargetTeamsDistributeSimdDirective *D) {
3174 VisitOMPLoopDirective(D);
3175}
3176
3177void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
3178 EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU, RegionOfInterest))
3179 .Visit(S);
3180}
3181
3182bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
3183 if (RegionOfInterest.isValid()) {
3184 SourceRange Range = getRawCursorExtent(C);
3185 if (Range.isInvalid() || CompareRegionOfInterest(Range))
3186 return false;
3187 }
3188 return true;
3189}
3190
3191bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
3192 while (!WL.empty()) {
3193 // Dequeue the worklist item.
3194 VisitorJob LI = WL.pop_back_val();
3195
3196 // Set the Parent field, then back to its old value once we're done.
3197 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
3198
3199 switch (LI.getKind()) {
3200 case VisitorJob::DeclVisitKind: {
3201 const Decl *D = cast<DeclVisit>(&LI)->get();
3202 if (!D)
3203 continue;
3204
3205 // For now, perform default visitation for Decls.
3206 if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
3207 cast<DeclVisit>(&LI)->isFirst())))
3208 return true;
3209
3210 continue;
3211 }
3212 case VisitorJob::ExplicitTemplateArgsVisitKind: {
3213 for (const TemplateArgumentLoc &Arg :
3214 *cast<ExplicitTemplateArgsVisit>(&LI)) {
3215 if (VisitTemplateArgumentLoc(Arg))
3216 return true;
3217 }
3218 continue;
3219 }
3220 case VisitorJob::TypeLocVisitKind: {
3221 // Perform default visitation for TypeLocs.
3222 if (Visit(cast<TypeLocVisit>(&LI)->get()))
3223 return true;
3224 continue;
3225 }
3226 case VisitorJob::LabelRefVisitKind: {
3227 const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
3228 if (LabelStmt *stmt = LS->getStmt()) {
3229 if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
3230 TU))) {
3231 return true;
3232 }
3233 }
3234 continue;
3235 }
3236
3237 case VisitorJob::NestedNameSpecifierLocVisitKind: {
3238 NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
3239 if (VisitNestedNameSpecifierLoc(V->get()))
3240 return true;
3241 continue;
3242 }
3243
3244 case VisitorJob::DeclarationNameInfoVisitKind: {
3245 if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)->get()))
3246 return true;
3247 continue;
3248 }
3249 case VisitorJob::MemberRefVisitKind: {
3250 MemberRefVisit *V = cast<MemberRefVisit>(&LI);
3251 if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
3252 return true;
3253 continue;
3254 }
3255 case VisitorJob::StmtVisitKind: {
3256 const Stmt *S = cast<StmtVisit>(&LI)->get();
3257 if (!S)
3258 continue;
3259
3260 // Update the current cursor.
3261 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
3262 if (!IsInRegionOfInterest(Cursor))
3263 continue;
3264 switch (Visitor(Cursor, Parent, ClientData)) {
3265 case CXChildVisit_Break:
3266 return true;
3267 case CXChildVisit_Continue:
3268 break;
3269 case CXChildVisit_Recurse:
3270 if (PostChildrenVisitor)
3271 WL.push_back(PostChildrenVisit(nullptr, Cursor));
3272 EnqueueWorkList(WL, S);
3273 break;
3274 }
3275 continue;
3276 }
3277 case VisitorJob::MemberExprPartsKind: {
3278 // Handle the other pieces in the MemberExpr besides the base.
3279 const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
3280
3281 // Visit the nested-name-specifier
3282 if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
3283 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3284 return true;
3285
3286 // Visit the declaration name.
3287 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
3288 return true;
3289
3290 // Visit the explicitly-specified template arguments, if any.
3291 if (M->hasExplicitTemplateArgs()) {
3292 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
3293 *ArgEnd = Arg + M->getNumTemplateArgs();
3294 Arg != ArgEnd; ++Arg) {
3295 if (VisitTemplateArgumentLoc(*Arg))
3296 return true;
3297 }
3298 }
3299 continue;
3300 }
3301 case VisitorJob::DeclRefExprPartsKind: {
3302 const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
3303 // Visit nested-name-specifier, if present.
3304 if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
3305 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3306 return true;
3307 // Visit declaration name.
3308 if (VisitDeclarationNameInfo(DR->getNameInfo()))
3309 return true;
3310 continue;
3311 }
3312 case VisitorJob::OverloadExprPartsKind: {
3313 const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
3314 // Visit the nested-name-specifier.
3315 if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
3316 if (VisitNestedNameSpecifierLoc(QualifierLoc))
3317 return true;
3318 // Visit the declaration name.
3319 if (VisitDeclarationNameInfo(O->getNameInfo()))
3320 return true;
3321 // Visit the overloaded declaration reference.
3322 if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
3323 return true;
3324 continue;
3325 }
3326 case VisitorJob::SizeOfPackExprPartsKind: {
3327 const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
3328 NamedDecl *Pack = E->getPack();
3329 if (isa<TemplateTypeParmDecl>(Pack)) {
3330 if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
3331 E->getPackLoc(), TU)))
3332 return true;
3333
3334 continue;
3335 }
3336
3337 if (isa<TemplateTemplateParmDecl>(Pack)) {
3338 if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
3339 E->getPackLoc(), TU)))
3340 return true;
3341
3342 continue;
3343 }
3344
3345 // Non-type template parameter packs and function parameter packs are
3346 // treated like DeclRefExpr cursors.
3347 continue;
3348 }
3349
3350 case VisitorJob::LambdaExprPartsKind: {
3351 // Visit non-init captures.
3352 const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
3353 for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
3354 CEnd = E->explicit_capture_end();
3355 C != CEnd; ++C) {
3356 if (!C->capturesVariable())
3357 continue;
3358
3359 if (Visit(MakeCursorVariableRef(C->getCapturedVar(), C->getLocation(),
3360 TU)))
3361 return true;
3362 }
3363 // Visit init captures
3364 for (auto InitExpr : E->capture_inits()) {
3365 if (InitExpr && Visit(InitExpr))
3366 return true;
3367 }
3368
3369 TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
3370 // Visit parameters and return type, if present.
3371 if (FunctionTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) {
3372 if (E->hasExplicitParameters()) {
3373 // Visit parameters.
3374 for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
3375 if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
3376 return true;
3377 }
3378 if (E->hasExplicitResultType()) {
3379 // Visit result type.
3380 if (Visit(Proto.getReturnLoc()))
3381 return true;
3382 }
3383 }
3384 break;
3385 }
3386
3387 case VisitorJob::PostChildrenVisitKind:
3388 if (PostChildrenVisitor(Parent, ClientData))
3389 return true;
3390 break;
3391 }
3392 }
3393 return false;
3394}
3395
3396bool CursorVisitor::Visit(const Stmt *S) {
3397 VisitorWorkList *WL = nullptr;
3398 if (!WorkListFreeList.empty()) {
3399 WL = WorkListFreeList.back();
3400 WL->clear();
3401 WorkListFreeList.pop_back();
3402 } else {
3403 WL = new VisitorWorkList();
3404 WorkListCache.push_back(WL);
3405 }
3406 EnqueueWorkList(*WL, S);
3407 bool result = RunVisitorWorkList(*WL);
3408 WorkListFreeList.push_back(WL);
3409 return result;
3410}
3411
3412namespace {
3413typedef SmallVector<SourceRange, 4> RefNamePieces;
3414RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
3415 const DeclarationNameInfo &NI, SourceRange QLoc,
3416 const SourceRange *TemplateArgsLoc = nullptr) {
3417 const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3418 const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3419 const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3420
3421 const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3422
3423 RefNamePieces Pieces;
3424
3425 if (WantQualifier && QLoc.isValid())
3426 Pieces.push_back(QLoc);
3427
3428 if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
3429 Pieces.push_back(NI.getLoc());
3430
3431 if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
3432 Pieces.push_back(*TemplateArgsLoc);
3433
3434 if (Kind == DeclarationName::CXXOperatorName) {
3435 Pieces.push_back(NI.getInfo().getCXXOperatorNameBeginLoc());
3436 Pieces.push_back(NI.getInfo().getCXXOperatorNameEndLoc());
3437 }
3438
3439 if (WantSinglePiece) {
3440 SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3441 Pieces.clear();
3442 Pieces.push_back(R);
3443 }
3444
3445 return Pieces;
3446}
3447} // namespace
3448
3449//===----------------------------------------------------------------------===//
3450// Misc. API hooks.
3451//===----------------------------------------------------------------------===//
3452
3453namespace {
3454struct RegisterFatalErrorHandler {
3455 RegisterFatalErrorHandler() {
3456 clang_install_aborting_llvm_fatal_error_handler();
3457 }
3458};
3459} // namespace
3460
3461static llvm::ManagedStatic<RegisterFatalErrorHandler>
3462 RegisterFatalErrorHandlerOnce;
3463
3464CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3465 int displayDiagnostics) {
3466 // We use crash recovery to make some of our APIs more reliable, implicitly
3467 // enable it.
3468 if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3469 llvm::CrashRecoveryContext::Enable();
3470
3471 // Look through the managed static to trigger construction of the managed
3472 // static which registers our fatal error handler. This ensures it is only
3473 // registered once.
3474 (void)*RegisterFatalErrorHandlerOnce;
3475
3476 // Initialize targets for clang module support.
3477 llvm::InitializeAllTargets();
3478 llvm::InitializeAllTargetMCs();
3479 llvm::InitializeAllAsmPrinters();
3480 llvm::InitializeAllAsmParsers();
3481
3482 CIndexer *CIdxr = new CIndexer();
3483
3484 if (excludeDeclarationsFromPCH)
3485 CIdxr->setOnlyLocalDecls();
3486 if (displayDiagnostics)
3487 CIdxr->setDisplayDiagnostics();
3488
3489 if (getenv("LIBCLANG_BGPRIO_INDEX"))
3490 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3491 CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3492 if (getenv("LIBCLANG_BGPRIO_EDIT"))
3493 CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3494 CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3495
3496 return CIdxr;
3497}
3498
3499void clang_disposeIndex(CXIndex CIdx) {
3500 if (CIdx)
3501 delete static_cast<CIndexer *>(CIdx);
3502}
3503
3504void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3505 if (CIdx)
3506 static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3507}
3508
3509unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3510 if (CIdx)
3511 return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3512 return 0;
3513}
3514
3515void clang_CXIndex_setInvocationEmissionPathOption(CXIndex CIdx,
3516 const char *Path) {
3517 if (CIdx)
3518 static_cast<CIndexer *>(CIdx)->setInvocationEmissionPath(Path ? Path : "");
3519}
3520
3521void clang_toggleCrashRecovery(unsigned isEnabled) {
3522 if (isEnabled)
3523 llvm::CrashRecoveryContext::Enable();
3524 else
3525 llvm::CrashRecoveryContext::Disable();
3526}
3527
3528CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3529 const char *ast_filename) {
3530 CXTranslationUnit TU;
3531 enum CXErrorCode Result =
3532 clang_createTranslationUnit2(CIdx, ast_filename, &TU);
3533 (void)Result;
3534 assert((TU && Result == CXError_Success) ||(static_cast <bool> ((TU && Result == CXError_Success
) || (!TU && Result != CXError_Success)) ? void (0) :
__assert_fail ("(TU && Result == CXError_Success) || (!TU && Result != CXError_Success)"
, "clang/tools/libclang/CIndex.cpp", 3535, __extension__ __PRETTY_FUNCTION__
))
3535 (!TU && Result != CXError_Success))(static_cast <bool> ((TU && Result == CXError_Success
) || (!TU && Result != CXError_Success)) ? void (0) :
__assert_fail ("(TU && Result == CXError_Success) || (!TU && Result != CXError_Success)"
, "clang/tools/libclang/CIndex.cpp", 3535, __extension__ __PRETTY_FUNCTION__
))
;
3536 return TU;
3537}
3538
3539enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3540 const char *ast_filename,
3541 CXTranslationUnit *out_TU) {
3542 if (out_TU)
3543 *out_TU = nullptr;
3544
3545 if (!CIdx || !ast_filename || !out_TU)
3546 return CXError_InvalidArguments;
3547
3548 LOG_FUNC_SECTIONif (clang::cxindex::LogRef Log = clang::cxindex::Logger::make
(__func__))
{ *Log << ast_filename; }
3549
3550 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3551 FileSystemOptions FileSystemOpts;
3552
3553 IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3554 CompilerInstance::createDiagnostics(new DiagnosticOptions());
3555 std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
3556 ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(),
3557 ASTUnit::LoadEverything, Diags, FileSystemOpts, /*UseDebugInfo=*/false,
3558 CXXIdx->getOnlyLocalDecls(), CaptureDiagsKind::All,
3559 /*AllowASTWithCompilerErrors=*/true,
3560 /*UserFilesAreVolatile=*/true);
3561 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU));
3562 return *out_TU ? CXError_Success : CXError_Failure;
3563}
3564
3565unsigned clang_defaultEditingTranslationUnitOptions() {
3566 return CXTranslationUnit_PrecompiledPreamble |
3567 CXTranslationUnit_CacheCompletionResults;
3568}
3569
3570CXTranslationUnit clang_createTranslationUnitFromSourceFile(
3571 CXIndex CIdx, const char *source_filename, int num_command_line_args,
3572 const char *const *command_line_args, unsigned num_unsaved_files,
3573 struct CXUnsavedFile *unsaved_files) {
3574 unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3575 return clang_parseTranslationUnit(CIdx, source_filename, command_line_args,
3576 num_command_line_args, unsaved_files,
3577 num_unsaved_files, Options);
3578}
3579
3580static CXErrorCode
3581clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3582 const char *const *command_line_args,
3583 int num_command_line_args,
3584 ArrayRef<CXUnsavedFile> unsaved_files,
3585 unsigned options, CXTranslationUnit *out_TU) {
3586 // Set up the initial return values.
3587 if (out_TU)
3588 *out_TU = nullptr;
3589
3590 // Check arguments.
3591 if (!CIdx || !out_TU)
3592 return CXError_InvalidArguments;
3593
3594 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3595
3596 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3597 setThreadBackgroundPriority();
3598
3599 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
3600 bool CreatePreambleOnFirstParse =
3601 options & CXTranslationUnit_CreatePreambleOnFirstParse;
3602 // FIXME: Add a flag for modules.
3603 TranslationUnitKind TUKind = (options & (CXTranslationUnit_Incomplete |
3604 CXTranslationUnit_SingleFileParse))
3605 ? TU_Prefix
3606 : TU_Complete;
3607 bool CacheCodeCompletionResults =
3608 options & CXTranslationUnit_CacheCompletionResults;
3609 bool IncludeBriefCommentsInCodeCompletion =
3610 options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
3611 bool SingleFileParse = options & CXTranslationUnit_SingleFileParse;
3612 bool ForSerialization = options & CXTranslationUnit_ForSerialization;
3613 bool RetainExcludedCB =
3614 options & CXTranslationUnit_RetainExcludedConditionalBlocks;
3615 SkipFunctionBodiesScope SkipFunctionBodies = SkipFunctionBodiesScope::None;
3616 if (options & CXTranslationUnit_SkipFunctionBodies) {
3617 SkipFunctionBodies =
3618 (options & CXTranslationUnit_LimitSkipFunctionBodiesToPreamble)
3619 ? SkipFunctionBodiesScope::Preamble
3620 : SkipFunctionBodiesScope::PreambleAndMainFile;
3621 }
3622
3623 // Configure the diagnostics.
3624 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
3625 CompilerInstance::createDiagnostics(new DiagnosticOptions));
3626
3627 if (options & CXTranslationUnit_KeepGoing)
3628 Diags->setFatalsAsError(true);
3629
3630 CaptureDiagsKind CaptureDiagnostics = CaptureDiagsKind::All;
3631 if (options & CXTranslationUnit_IgnoreNonErrorsFromIncludedFiles)
3632 CaptureDiagnostics = CaptureDiagsKind::AllWithoutNonErrorsFromIncludes;
3633
3634 // Recover resources if we crash before exiting this function.
3635 llvm::CrashRecoveryContextCleanupRegistrar<
3636 DiagnosticsEngine,
3637 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
3638 DiagCleanup(Diags.get());
3639
3640 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3641 new std::vector<ASTUnit::RemappedFile>());
3642
3643 // Recover resources if we crash before exiting this function.
3644 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<ASTUnit::RemappedFile>>
3645 RemappedCleanup(RemappedFiles.get());
3646
3647 for (auto &UF : unsaved_files) {
3648 std::unique_ptr<llvm::MemoryBuffer> MB =
3649 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
3650 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
3651 }
3652
3653 std::unique_ptr<std::vector<const char *>> Args(
3654 new std::vector<const char *>());
3655
3656 // Recover resources if we crash before exiting this method.
3657 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char *>>
3658 ArgsCleanup(Args.get());
3659
3660 // Since the Clang C library is primarily used by batch tools dealing with
3661 // (often very broken) source code, where spell-checking can have a
3662 // significant negative impact on performance (particularly when
3663 // precompiled headers are involved), we disable it by default.
3664 // Only do this if we haven't found a spell-checking-related argument.
3665 bool FoundSpellCheckingArgument = false;
3666 for (int I = 0; I != num_command_line_args; ++I) {
3667 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3668 strcmp(command_line_args[I], "-fspell-checking") == 0) {
3669 FoundSpellCheckingArgument = true;
3670 break;
3671 }
3672 }
3673 Args->insert(Args->end(), command_line_args,
3674 command_line_args + num_command_line_args);
3675
3676 if (!FoundSpellCheckingArgument)
3677 Args->insert(Args->begin() + 1, "-fno-spell-checking");
3678
3679 // The 'source_filename' argument is optional. If the caller does not
3680 // specify it then it is assumed that the source file is specified
3681 // in the actual argument list.
3682 // Put the source file after command_line_args otherwise if '-x' flag is
3683 // present it will be unused.
3684 if (source_filename)
3685 Args->push_back(source_filename);
3686
3687 // Do we need the detailed preprocessing record?
3688 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3689 Args->push_back("-Xclang");
3690 Args->push_back("-detailed-preprocessing-record");
3691 }
3692
3693 // Suppress any editor placeholder diagnostics.
3694 Args->push_back("-fallow-editor-placeholders");
3695
3696 unsigned NumErrors = Diags->getClient()->getNumErrors();
3697 std::unique_ptr<ASTUnit> ErrUnit;
3698 // Unless the user specified that they want the preamble on the first parse
3699 // set it up to be created on the first reparse. This makes the first parse
3700 // faster, trading for a slower (first) reparse.
3701 unsigned PrecompilePreambleAfterNParses =
3702 !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
3703
3704 LibclangInvocationReporter InvocationReporter(
3705 *CXXIdx, LibclangInvocationReporter::OperationKind::ParseOperation,
3706 options, llvm::makeArrayRef(*Args), /*InvocationArgs=*/None,
3707 unsaved_files);
3708 std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
3709 Args->data(), Args->data() + Args->size(),
3710 CXXIdx->getPCHContainerOperations(), Diags,
3711 CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
3712 CaptureDiagnostics, *RemappedFiles.get(),
3713 /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3714 TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
3715 /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, SingleFileParse,
3716 /*UserFilesAreVolatile=*/true, ForSerialization, RetainExcludedCB,
3717 CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3718 &ErrUnit));
3719
3720 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
3721 if (!Unit && !ErrUnit)
3722 return CXError_ASTReadError;
3723
3724 if (NumErrors != Diags->getClient()->getNumErrors()) {
3725 // Make sure to check that 'Unit' is non-NULL.
3726 if (CXXIdx->getDisplayDiagnostics())
3727 printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
3728 }
3729
3730 if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
3731 return CXError_ASTReadError;
3732
3733 *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit));
3734 if (CXTranslationUnitImpl *TU = *out_TU) {
3735 TU->ParsingOptions = options;
3736 TU->Arguments.reserve(Args->size());
3737 for (const char *Arg : *Args)
3738 TU->Arguments.push_back(Arg);
3739 return CXError_Success;
3740 }
3741 return CXError_Failure;
3742}
3743
3744CXTranslationUnit
3745clang_parseTranslationUnit(CXIndex CIdx, const char *source_filename,
3746 const char *const *command_line_args,
3747 int num_command_line_args,
3748 struct CXUnsavedFile *unsaved_files,
3749 unsigned num_unsaved_files, unsigned options) {
3750 CXTranslationUnit TU;
3751 enum CXErrorCode Result = clang_parseTranslationUnit2(
3752 CIdx, source_filename, command_line_args, num_command_line_args,
3753 unsaved_files, num_unsaved_files, options, &TU);
3754 (void)Result;
3755 assert((TU && Result == CXError_Success) ||(static_cast <bool> ((TU && Result == CXError_Success
) || (!TU && Result != CXError_Success)) ? void (0) :
__assert_fail ("(TU && Result == CXError_Success) || (!TU && Result != CXError_Success)"
, "clang/tools/libclang/CIndex.cpp", 3756, __extension__ __PRETTY_FUNCTION__
))
3756 (!TU && Result != CXError_Success))(static_cast <bool> ((TU && Result == CXError_Success
) || (!TU && Result != CXError_Success)) ? void (0) :
__assert_fail ("(TU && Result == CXError_Success) || (!TU && Result != CXError_Success)"
, "clang/tools/libclang/CIndex.cpp", 3756, __extension__ __PRETTY_FUNCTION__
))
;
3757 return TU;
3758}
3759
3760enum CXErrorCode clang_parseTranslationUnit2(
3761 CXIndex CIdx, const char *source_filename,
3762 const char *const *command_line_args, int num_command_line_args,
3763 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3764 unsigned options, CXTranslationUnit *out_TU) {
3765 noteBottomOfStack();
3766 SmallVector<const char *, 4> Args;
3767 Args.push_back("clang");
3768 Args.append(command_line_args, command_line_args + num_command_line_args);
3769 return clang_parseTranslationUnit2FullArgv(
3770 CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3771 num_unsaved_files, options, out_TU);
3772}
3773
3774enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3775 CXIndex CIdx, const char *source_filename,
3776 const char *const *command_line_args, int num_command_line_args,
3777 struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3778 unsigned options, CXTranslationUnit *out_TU) {
3779 LOG_FUNC_SECTIONif (clang::cxindex::LogRef Log = clang::cxindex::Logger::make
(__func__))
{
3780 *Log << source_filename << ": ";
3781 for (int i = 0; i != num_command_line_args; ++i)
3782 *Log << command_line_args[i] << " ";
3783 }
3784
3785 if (num_unsaved_files && !unsaved_files)
3786 return CXError_InvalidArguments;
3787
3788 CXErrorCode result = CXError_Failure;
3789 auto ParseTranslationUnitImpl = [=, &result] {
3790 noteBottomOfStack();
3791 result = clang_parseTranslationUnit_Impl(
3792 CIdx, source_filename, command_line_args, num_command_line_args,
3793 llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3794 };
3795
3796 llvm::CrashRecoveryContext CRC;
3797
3798 if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
3799 fprintf(stderrstderr, "libclang: crash detected during parsing: {\n");
3800 fprintf(stderrstderr, " 'source_filename' : '%s'\n", source_filename);
3801 fprintf(stderrstderr, " 'command_line_args' : [");
3802 for (int i = 0; i != num_command_line_args; ++i) {
3803 if (i)
3804 fprintf(stderrstderr, ", ");
3805 fprintf(stderrstderr, "'%s'", command_line_args[i]);
3806 }
3807 fprintf(stderrstderr, "],\n");
3808 fprintf(stderrstderr, " 'unsaved_files' : [");
3809 for (unsigned i = 0; i != num_unsaved_files; ++i) {
3810 if (i)
3811 fprintf(stderrstderr, ", ");
3812 fprintf(stderrstderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3813 unsaved_files[i].Length);
3814 }
3815 fprintf(stderrstderr, "],\n");
3816 fprintf(stderrstderr, " 'options' : %d,\n", options);
3817 fprintf(stderrstderr, "}\n");
3818
3819 return CXError_Crashed;
3820 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
3821 if (CXTranslationUnit *TU = out_TU)
3822 PrintLibclangResourceUsage(*TU);
3823 }
3824
3825 return result;
3826}
3827
3828CXString clang_Type_getObjCEncoding(CXType CT) {
3829 CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3830 ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3831 std::string encoding;
3832 Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]), encoding);
3833
3834 return cxstring::createDup(encoding);
3835}
3836
3837static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3838 if (C.kind == CXCursor_MacroDefinition) {
3839 if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3840 return MDR->getName();
3841 } else if (C.kind == CXCursor_MacroExpansion) {
3842 MacroExpansionCursor ME = getCursorMacroExpansion(C);
3843 return ME.getName();
3844 }
3845 return nullptr;
3846}
3847
3848unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3849 const IdentifierInfo *II = getMacroIdentifier(C);
3850 if (!II) {
3851 return false;
3852 }
3853 ASTUnit *ASTU = getCursorASTUnit(C);
3854 Preprocessor &PP = ASTU->getPreprocessor();
3855 if (const MacroInfo *MI = PP.getMacroInfo(II))
3856 return MI->isFunctionLike();
3857 return false;
3858}
3859
3860unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3861 const IdentifierInfo *II = getMacroIdentifier(C);
3862 if (!II) {
3863 return false;
3864 }
3865 ASTUnit *ASTU = getCursorASTUnit(C);
3866 Preprocessor &PP = ASTU->getPreprocessor();
3867 if (const MacroInfo *MI = PP.getMacroInfo(II))
3868 return MI->isBuiltinMacro();
3869 return false;
3870}
3871
3872unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3873 const Decl *D = getCursorDecl(C);
3874 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3875 if (!FD) {
3876 return false;
3877 }
3878 return FD->isInlined();
3879}
3880
3881static StringLiteral *getCFSTR_value(CallExpr *callExpr) {
3882 if (callExpr->getNumArgs() != 1) {
3883 return nullptr;
3884 }
3885
3886 StringLiteral *S = nullptr;
3887 auto *arg = callExpr->getArg(0);
3888 if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3889 ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3890 auto *subExpr = I->getSubExprAsWritten();
3891
3892 if (subExpr->getStmtClass() != Stmt::StringLiteralClass) {
3893 return nullptr;
3894 }
3895
3896 S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3897 } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3898 S = static_cast<StringLiteral *>(callExpr->getArg(0));
3899 } else {
3900 return nullptr;
3901 }
3902 return S;
3903}
3904
3905struct ExprEvalResult {
3906 CXEvalResultKind EvalType;
3907 union {
3908 unsigned long long unsignedVal;
3909 long long intVal;
3910 double floatVal;
3911 char *stringVal;
3912 } EvalData;
3913 bool IsUnsignedInt;
3914 ~ExprEvalResult() {
3915 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3916 EvalType != CXEval_Int) {
3917 delete[] EvalData.stringVal;
3918 }
3919 }
3920};
3921
3922void clang_EvalResult_dispose(CXEvalResult E) {
3923 delete static_cast<ExprEvalResult *>(E);
3924}
3925
3926CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3927 if (!E) {
3928 return CXEval_UnExposed;
3929 }
3930 return ((ExprEvalResult *)E)->EvalType;
3931}
3932
3933int clang_EvalResult_getAsInt(CXEvalResult E) {
3934 return clang_EvalResult_getAsLongLong(E);
3935}
3936
3937long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
3938 if (!E) {
3939 return 0;
3940 }
3941 ExprEvalResult *Result = (ExprEvalResult *)E;
3942 if (Result->IsUnsignedInt)
3943 return Result->EvalData.unsignedVal;
3944 return Result->EvalData.intVal;
3945}
3946
3947unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
3948 return ((ExprEvalResult *)E)->IsUnsignedInt;
3949}
3950
3951unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
3952 if (!E) {
3953 return 0;
3954 }
3955
3956 ExprEvalResult *Result = (ExprEvalResult *)E;
3957 if (Result->IsUnsignedInt)
3958 return Result->EvalData.unsignedVal;
3959 return Result->EvalData.intVal;
3960}
3961
3962double clang_EvalResult_getAsDouble(CXEvalResult E) {
3963 if (!E) {
3964 return 0;
3965 }
3966 return ((ExprEvalResult *)E)->EvalData.floatVal;
3967}
3968
3969const char *clang_EvalResult_getAsStr(CXEvalResult E) {
3970 if (!E) {
3971 return nullptr;
3972 }
3973 return ((ExprEvalResult *)E)->EvalData.stringVal;
3974}
3975
3976static const ExprEvalResult *evaluateExpr(Expr *expr, CXCursor C) {
3977 Expr::EvalResult ER;
3978 ASTContext &ctx = getCursorContext(C);
3979 if (!expr)
3980 return nullptr;
3981
3982 expr = expr->IgnoreParens();
3983 if (expr->isValueDependent())
3984 return nullptr;
3985 if (!expr->EvaluateAsRValue(ER, ctx))
3986 return nullptr;
3987
3988 QualType rettype;
3989 CallExpr *callExpr;
3990 auto result = std::make_unique<ExprEvalResult>();
3991 result->EvalType = CXEval_UnExposed;
3992 result->IsUnsignedInt = false;
3993
3994 if (ER.Val.isInt()) {
3995 result->EvalType = CXEval_Int;
3996
3997 auto &val = ER.Val.getInt();
3998 if (val.isUnsigned()) {
3999 result->IsUnsignedInt = true;
4000 result->EvalData.unsignedVal = val.getZExtValue();
4001 } else {
4002 result->EvalData.intVal = val.getExtValue();
4003 }
4004
4005 return result.release();
4006 }
4007
4008 if (ER.Val.isFloat()) {
4009 llvm::SmallVector<char, 100> Buffer;
4010 ER.Val.getFloat().toString(Buffer);
4011 std::string floatStr(Buffer.data(), Buffer.size());
4012 result->EvalType = CXEval_Float;
4013 bool ignored;
4014 llvm::APFloat apFloat = ER.Val.getFloat();
4015 apFloat.convert(llvm::APFloat::IEEEdouble(),
4016 llvm::APFloat::rmNearestTiesToEven, &ignored);
4017 result->EvalData.floatVal = apFloat.convertToDouble();
4018 return result.release();
4019 }
4020
4021 if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
4022 const auto *I = cast<ImplicitCastExpr>(expr);
4023 auto *subExpr = I->getSubExprAsWritten();
4024 if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
4025 subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
4026 const StringLiteral *StrE = nullptr;
4027 const ObjCStringLiteral *ObjCExpr;
4028 ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
4029
4030 if (ObjCExpr) {
4031 StrE = ObjCExpr->getString();
4032 result->EvalType = CXEval_ObjCStrLiteral;
4033 } else {
4034 StrE = cast<StringLiteral>(I->getSubExprAsWritten());
4035 result->EvalType = CXEval_StrLiteral;
4036 }
4037
4038 std::string strRef(StrE->getString().str());
4039 result->EvalData.stringVal = new char[strRef.size() + 1];
4040 strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
4041 strRef.size());
4042 result->EvalData.stringVal[strRef.size()] = '\0';
4043 return result.release();
4044 }
4045 } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
4046 expr->getStmtClass() == Stmt::StringLiteralClass) {
4047 const StringLiteral *StrE = nullptr;
4048 const ObjCStringLiteral *ObjCExpr;
4049 ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
4050
4051 if (ObjCExpr) {
4052 StrE = ObjCExpr->getString();
4053 result->EvalType = CXEval_ObjCStrLiteral;
4054 } else {
4055 StrE = cast<StringLiteral>(expr);
4056 result->EvalType = CXEval_StrLiteral;
4057 }
4058
4059 std::string strRef(StrE->getString().str());
4060 result->EvalData.stringVal = new char[strRef.size() + 1];
4061 strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
4062 result->EvalData.stringVal[strRef.size()] = '\0';
4063 return result.release();
4064 }
4065
4066 if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
4067 CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
4068
4069 rettype = CC->getType();
4070 if (rettype.getAsString() == "CFStringRef" &&
4071 CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
4072
4073 callExpr = static_cast<CallExpr *>(CC->getSubExpr());
4074 StringLiteral *S = getCFSTR_value(callExpr);
4075 if (S) {
4076 std::string strLiteral(S->getString().str());
4077 result->EvalType = CXEval_CFStr;
4078
4079 result->EvalData.stringVal = new char[strLiteral.size() + 1];
4080 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
4081 strLiteral.size());
4082 result->EvalData.stringVal[strLiteral.size()] = '\0';
4083 return result.release();
4084 }
4085 }
4086
4087 } else if (expr->getStmtClass() == Stmt::CallExprClass) {
4088 callExpr = static_cast<CallExpr *>(expr);
4089 rettype = callExpr->getCallReturnType(ctx);
4090
4091 if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
4092 return nullptr;
4093
4094 if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
4095 if (callExpr->getNumArgs() == 1 &&
4096 !callExpr->getArg(0)->getType()->isIntegralType(ctx))
4097 return nullptr;
4098 } else if (rettype.getAsString() == "CFStringRef") {
4099
4100 StringLiteral *S = getCFSTR_value(callExpr);
4101 if (S) {
4102 std::string strLiteral(S->getString().str());
4103 result->EvalType = CXEval_CFStr;
4104 result->EvalData.stringVal = new char[strLiteral.size() + 1];
4105 strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
4106 strLiteral.size());
4107 result->EvalData.stringVal[strLiteral.size()] = '\0';
4108 return result.release();
4109 }
4110 }
4111 } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
4112 DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
4113 ValueDecl *V = D->getDecl();
4114 if (V->getKind() == Decl::Function) {
4115 std::string strName = V->getNameAsString();
4116 result->EvalType = CXEval_Other;
4117 result->EvalData.stringVal = new char[strName.size() + 1];
4118 strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
4119 result->EvalData.stringVal[strName.size()] = '\0';
4120 return result.release();
4121 }
4122 }
4123
4124 return nullptr;
4125}
4126
4127static const Expr *evaluateDeclExpr(const Decl *D) {
4128 if (!D)
4129 return nullptr;
4130 if (auto *Var = dyn_cast<VarDecl>(D))
4131 return Var->getInit();
4132 else if (auto *Field = dyn_cast<FieldDecl>(D))
4133 return Field->getInClassInitializer();
4134 return nullptr;
4135}
4136
4137static const Expr *evaluateCompoundStmtExpr(const CompoundStmt *CS) {
4138 assert(CS && "invalid compound statement")(static_cast <bool> (CS && "invalid compound statement"
) ? void (0) : __assert_fail ("CS && \"invalid compound statement\""
, "clang/tools/libclang/CIndex.cpp", 4138, __extension__ __PRETTY_FUNCTION__
))
;
4139 for (auto *bodyIterator : CS->body()) {
4140 if (const auto *E = dyn_cast<Expr>(bodyIterator))
4141 return E;
4142 }
4143 return nullptr;
4144}
4145
4146CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
4147 const Expr *E = nullptr;
4148 if (clang_getCursorKind(C) == CXCursor_CompoundStmt)
4149 E = evaluateCompoundStmtExpr(cast<CompoundStmt>(getCursorStmt(C)));
4150 else if (clang_isDeclaration(C.kind))
4151 E = evaluateDeclExpr(getCursorDecl(C));
4152 else if (clang_isExpression(C.kind))
4153 E = getCursorExpr(C);
4154 if (E)
4155 return const_cast<CXEvalResult>(
4156 reinterpret_cast<const void *>(evaluateExpr(const_cast<Expr *>(E), C)));
4157 return nullptr;
4158}
4159
4160unsigned clang_Cursor_hasAttrs(CXCursor C) {
4161 const Decl *D = getCursorDecl(C);
4162 if (!D) {
4163 return 0;
4164 }
4165
4166 if (D->hasAttrs()) {
4167 return 1;
4168 }
4169
4170 return 0;
4171}
4172unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
4173 return CXSaveTranslationUnit_None;
4174}
4175
4176static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
4177 const char *FileName,
4178 unsigned options) {
4179 CIndexer *CXXIdx = TU->CIdx;
4180 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
4181 setThreadBackgroundPriority();
4182
4183 bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
4184 return hadError ? CXSaveError_Unknown : CXSaveError_None;
4185}
4186
4187int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
4188 unsigned options) {
4189 LOG_FUNC_SECTIONif (clang::cxindex::LogRef Log = clang::cxindex::Logger::make
(__func__))
{ *Log << TU << ' ' << FileName; }
4190
4191 if (isNotUsableTU(TU)) {
4192 LOG_BAD_TU(TU)do { if (clang::cxindex::LogRef Log = clang::cxindex::Logger::
make(__func__)) { *Log << "called with a bad TU: " <<
TU; } } while(false)
;
4193 return CXSaveError_InvalidTU;
4194 }
4195
4196 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4197 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4198 if (!CXXUnit->hasSema())
4199 return CXSaveError_InvalidTU;
4200
4201 CXSaveError result;
4202 auto SaveTranslationUnitImpl = [=, &result]() {
4203 result = clang_saveTranslationUnit_Impl(TU, FileName, options);
4204 };
4205
4206 if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred()) {
4207 SaveTranslationUnitImpl();
4208
4209 if (getenv("LIBCLANG_RESOURCE_USAGE"))
4210 PrintLibclangResourceUsage(TU);
4211
4212 return result;
4213 }
4214
4215 // We have an AST that has invalid nodes due to compiler errors.
4216 // Use a crash recovery thread for protection.
4217
4218 llvm::CrashRecoveryContext CRC;
4219
4220 if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
4221 fprintf(stderrstderr, "libclang: crash detected during AST saving: {\n");
4222 fprintf(stderrstderr, " 'filename' : '%s'\n", FileName);
4223 fprintf(stderrstderr, " 'options' : %d,\n", options);
4224 fprintf(stderrstderr, "}\n");
4225
4226 return CXSaveError_Unknown;
4227
4228 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
4229 PrintLibclangResourceUsage(TU);
4230 }
4231
4232 return result;
4233}
4234
4235void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
4236 if (CTUnit) {
4237 // If the translation unit has been marked as unsafe to free, just discard
4238 // it.
4239 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4240 if (Unit && Unit->isUnsafeToFree())
4241 return;
4242
4243 delete cxtu::getASTUnit(CTUnit);
4244 delete CTUnit->StringPool;
4245 delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
4246 disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
4247 delete CTUnit->CommentToXML;
4248 delete CTUnit;
4249 }
4250}
4251
4252unsigned clang_suspendTranslationUnit(CXTranslationUnit CTUnit) {
4253 if (CTUnit) {
1
Assuming 'CTUnit' is non-null
2
Taking true branch
4254 ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
3
Calling 'getASTUnit'
9
Returning from 'getASTUnit'
10
'Unit' initialized here
4255
4256 if (Unit && Unit->isUnsafeToFree())
11
Assuming 'Unit' is null
4257 return false;
4258
4259 Unit->ResetForParse();
12
Called C++ object pointer is null
4260 return true;
4261 }
4262
4263 return false;
4264}
4265
4266unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
4267 return CXReparse_None;
4268}
4269
4270static CXErrorCode
4271clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
4272 ArrayRef<CXUnsavedFile> unsaved_files,
4273 unsigned options) {
4274 // Check arguments.
4275 if (isNotUsableTU(TU)) {
4276 LOG_BAD_TU(TU)do { if (clang::cxindex::LogRef Log = clang::cxindex::Logger::
make(__func__)) { *Log << "called with a bad TU: " <<
TU; } } while(false)
;
4277 return CXError_InvalidArguments;
4278 }
4279
4280 // Reset the associated diagnostics.
4281 delete static_cast<CXDiagnosticSetImpl *>(TU->Diagnostics);
4282 TU->Diagnostics = nullptr;
4283
4284 CIndexer *CXXIdx = TU->CIdx;
4285 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
4286 setThreadBackgroundPriority();
4287
4288 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4289 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4290
4291 std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
4292 new std::vector<ASTUnit::RemappedFile>());
4293
4294 // Recover resources if we crash before exiting this function.
4295 llvm::CrashRecoveryContextCleanupRegistrar<std::vector<ASTUnit::RemappedFile>>
4296 RemappedCleanup(RemappedFiles.get());
4297
4298 for (auto &UF : unsaved_files) {
4299 std::unique_ptr<llvm::MemoryBuffer> MB =
4300 llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
4301 RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
4302 }
4303
4304 if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
4305 *RemappedFiles.get()))
4306 return CXError_Success;
4307 if (isASTReadError(CXXUnit))
4308 return CXError_ASTReadError;
4309 return CXError_Failure;
4310}
4311
4312int clang_reparseTranslationUnit(CXTranslationUnit TU,
4313 unsigned num_unsaved_files,
4314 struct CXUnsavedFile *unsaved_files,
4315 unsigned options) {
4316 LOG_FUNC_SECTIONif (clang::cxindex::LogRef Log = clang::cxindex::Logger::make
(__func__))
{ *Log << TU; }
4317
4318 if (num_unsaved_files && !unsaved_files)
4319 return CXError_InvalidArguments;
4320
4321 CXErrorCode result;
4322 auto ReparseTranslationUnitImpl = [=, &result]() {
4323 result = clang_reparseTranslationUnit_Impl(
4324 TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
4325 };
4326
4327 llvm::CrashRecoveryContext CRC;
4328
4329 if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
4330 fprintf(stderrstderr, "libclang: crash detected during reparsing\n");
4331 cxtu::getASTUnit(TU)->setUnsafeToFree(true);
4332 return CXError_Crashed;
4333 } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
4334 PrintLibclangResourceUsage(TU);
4335
4336 return result;
4337}
4338
4339CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
4340 if (isNotUsableTU(CTUnit)) {
4341 LOG_BAD_TU(CTUnit)do { if (clang::cxindex::LogRef Log = clang::cxindex::Logger::
make(__func__)) { *Log << "called with a bad TU: " <<
CTUnit; } } while(false)
;
4342 return cxstring::createEmpty();
4343 }
4344
4345 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4346 return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
4347}
4348
4349CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
4350 if (isNotUsableTU(TU)) {
4351 LOG_BAD_TU(TU)do { if (clang::cxindex::LogRef Log = clang::cxindex::Logger::
make(__func__)) { *Log << "called with a bad TU: " <<
TU; } } while(false)
;
4352 return clang_getNullCursor();
4353 }
4354
4355 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4356 return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
4357}
4358
4359CXTargetInfo clang_getTranslationUnitTargetInfo(CXTranslationUnit CTUnit) {
4360 if (isNotUsableTU(CTUnit)) {
4361 LOG_BAD_TU(CTUnit)do { if (clang::cxindex::LogRef Log = clang::cxindex::Logger::
make(__func__)) { *Log << "called with a bad TU: " <<
CTUnit; } } while(false)
;
4362 return nullptr;
4363 }
4364
4365 CXTargetInfoImpl *impl = new CXTargetInfoImpl();
4366 impl->TranslationUnit = CTUnit;
4367 return impl;
4368}
4369
4370CXString clang_TargetInfo_getTriple(CXTargetInfo TargetInfo) {
4371 if (!TargetInfo)
4372 return cxstring::createEmpty();
4373
4374 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4375 assert(!isNotUsableTU(CTUnit) &&(static_cast <bool> (!isNotUsableTU(CTUnit) && "Unexpected unusable translation unit in TargetInfo"
) ? void (0) : __assert_fail ("!isNotUsableTU(CTUnit) && \"Unexpected unusable translation unit in TargetInfo\""
, "clang/tools/libclang/CIndex.cpp", 4376, __extension__ __PRETTY_FUNCTION__
))
4376 "Unexpected unusable translation unit in TargetInfo")(static_cast <bool> (!isNotUsableTU(CTUnit) && "Unexpected unusable translation unit in TargetInfo"
) ? void (0) : __assert_fail ("!isNotUsableTU(CTUnit) && \"Unexpected unusable translation unit in TargetInfo\""
, "clang/tools/libclang/CIndex.cpp", 4376, __extension__ __PRETTY_FUNCTION__
))
;
4377
4378 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4379 std::string Triple =
4380 CXXUnit->getASTContext().getTargetInfo().getTriple().normalize();
4381 return cxstring::createDup(Triple);
4382}
4383
4384int clang_TargetInfo_getPointerWidth(CXTargetInfo TargetInfo) {
4385 if (!TargetInfo)
4386 return -1;
4387
4388 CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4389 assert(!isNotUsableTU(CTUnit) &&(static_cast <bool> (!isNotUsableTU(CTUnit) && "Unexpected unusable translation unit in TargetInfo"
) ? void (0) : __assert_fail ("!isNotUsableTU(CTUnit) && \"Unexpected unusable translation unit in TargetInfo\""
, "clang/tools/libclang/CIndex.cpp", 4390, __extension__ __PRETTY_FUNCTION__
))
4390 "Unexpected unusable translation unit in TargetInfo")(static_cast <bool> (!isNotUsableTU(CTUnit) && "Unexpected unusable translation unit in TargetInfo"
) ? void (0) : __assert_fail ("!isNotUsableTU(CTUnit) && \"Unexpected unusable translation unit in TargetInfo\""
, "clang/tools/libclang/CIndex.cpp", 4390, __extension__ __PRETTY_FUNCTION__
))
;
4391
4392 ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4393 return CXXUnit->getASTContext().getTargetInfo().getMaxPointerWidth();
4394}
4395
4396void clang_TargetInfo_dispose(CXTargetInfo TargetInfo) {
4397 if (!TargetInfo)
4398 return;
4399
4400 delete TargetInfo;
4401}
4402
4403//===----------------------------------------------------------------------===//
4404// CXFile Operations.
4405//===----------------------------------------------------------------------===//
4406
4407CXString clang_getFileName(CXFile SFile) {
4408 if (!SFile)
4409 return cxstring::createNull();
4410
4411 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4412 return cxstring::createRef(FEnt->getName());
4413}
4414
4415time_t clang_getFileTime(CXFile SFile) {
4416 if (!SFile)
4417 return 0;
4418
4419 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4420 return FEnt->getModificationTime();
4421}
4422
4423CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
4424 if (isNotUsableTU(TU)) {
4425 LOG_BAD_TU(TU)do { if (clang::cxindex::LogRef Log = clang::cxindex::Logger::
make(__func__)) { *Log << "called with a bad TU: " <<
TU; } } while(false)
;
4426 return nullptr;
4427 }
4428
4429 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4430
4431 FileManager &FMgr = CXXUnit->getFileManager();
4432 auto File = FMgr.getFile(file_name);
4433 if (!File)
4434 return nullptr;
4435 return const_cast<FileEntry *>(*File);
4436}
4437
4438const char *clang_getFileContents(CXTranslationUnit TU, CXFile file,
4439 size_t *size) {
4440 if (isNotUsableTU(TU)) {
4441 LOG_BAD_TU(TU)do { if (clang::cxindex::LogRef Log = clang::cxindex::Logger::
make(__func__)) { *Log << "called with a bad TU: " <<
TU; } } while(false)
;
4442 return nullptr;
4443 }
4444
4445 const SourceManager &SM = cxtu::getASTUnit(TU)->getSourceManager();
4446 FileID fid = SM.translateFile(static_cast<FileEntry *>(file));
4447 llvm::Optional<llvm::MemoryBufferRef> buf = SM.getBufferOrNone(fid);
4448 if (!buf) {
4449 if (size)
4450 *size = 0;
4451 return nullptr;
4452 }
4453 if (size)
4454 *size = buf->getBufferSize();
4455 return buf->getBufferStart();
4456}
4457
4458unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU, CXFile file) {
4459 if (isNotUsableTU(TU)) {
4460 LOG_BAD_TU(TU)do { if (clang::cxindex::LogRef Log = clang::cxindex::Logger::
make(__func__)) { *Log << "called with a bad TU: " <<
TU; } } while(false)
;
4461 return 0;
4462 }
4463
4464 if (!file)
4465 return 0;
4466
4467 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4468 FileEntry *FEnt = static_cast<FileEntry *>(file);
4469 return CXXUnit->getPreprocessor()
4470 .getHeaderSearchInfo()
4471 .isFileMultipleIncludeGuarded(FEnt);
4472}
4473
4474int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
4475 if (!file || !outID)
4476 return 1;
4477
4478 FileEntry *FEnt = static_cast<FileEntry *>(file);
4479 const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
4480 outID->data[0] = ID.getDevice();
4481 outID->data[1] = ID.getFile();
4482 outID->data[2] = FEnt->getModificationTime();
4483 return 0;
4484}
4485
4486int clang_File_isEqual(CXFile file1, CXFile file2) {
4487 if (file1 == file2)
4488 return true;
4489
4490 if (!file1 || !file2)
4491 return false;
4492
4493 FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
4494 FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
4495 return FEnt1->getUniqueID() == FEnt2->getUniqueID();
4496}
4497
4498CXString clang_File_tryGetRealPathName(CXFile SFile) {
4499 if (!SFile)
4500 return cxstring::createNull();
4501
4502 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4503 return cxstring::createRef(FEnt->tryGetRealPathName());
4504}
4505
4506//===----------------------------------------------------------------------===//
4507// CXCursor Operations.
4508//===----------------------------------------------------------------------===//
4509
4510static const Decl *getDeclFromExpr(const Stmt *E) {
4511 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
4512 return getDeclFromExpr(CE->getSubExpr());
4513
4514 if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
4515 return RefExpr->getDecl();
4516 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
4517 return ME->getMemberDecl();
4518 if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
4519 return RE->getDecl();
4520 if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
4521 if (PRE->isExplicitProperty())
4522 return PRE->getExplicitProperty();
4523 // It could be messaging both getter and setter as in:
4524 // ++myobj.myprop;
4525 // in which case prefer to associate the setter since it is less obvious
4526 // from inspecting the source that the setter is going to get called.
4527 if (PRE->isMessagingSetter())
4528 return PRE->getImplicitPropertySetter();
4529 return PRE->getImplicitPropertyGetter();
4530 }
4531 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
4532 return getDeclFromExpr(POE->getSyntacticForm());
4533 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
4534 if (Expr *Src = OVE->getSourceExpr())
4535 return getDeclFromExpr(Src);
4536
4537 if (const CallExpr *CE = dyn_cast<CallExpr>(E))
4538 return getDeclFromExpr(CE->getCallee());
4539 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
4540 if (!CE->isElidable())
4541 return CE->getConstructor();
4542 if (const CXXInheritedCtorInitExpr *CE =
4543 dyn_cast<CXXInheritedCtorInitExpr>(E))
4544 return CE->getConstructor();
4545 if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
4546 return OME->getMethodDecl();
4547
4548 if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
4549 return PE->getProtocol();
4550 if (const SubstNonTypeTemplateParmPackExpr *NTTP =
4551 dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4552 return NTTP->getParameterPack();
4553 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
4554 if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
4555 isa<ParmVarDecl>(SizeOfPack->getPack()))
4556 return SizeOfPack->getPack();
4557
4558 return nullptr;
4559}
4560
4561static SourceLocation getLocationFromExpr(const Expr *E) {
4562 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
4563 return getLocationFromExpr(CE->getSubExpr());
4564
4565 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
4566 return /*FIXME:*/ Msg->getLeftLoc();
4567 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
4568 return DRE->getLocation();
4569 if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
4570 return Member->getMemberLoc();
4571 if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
4572 return Ivar->getLocation();
4573 if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
4574 return SizeOfPack->getPackLoc();
4575 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
4576 return PropRef->getLocation();
4577
4578 return E->getBeginLoc();
4579}
4580
4581extern "C" {
4582
4583unsigned clang_visitChildren(CXCursor parent, CXCursorVisitor visitor,
4584 CXClientData client_data) {
4585 CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4586 /*VisitPreprocessorLast=*/false);
4587 return CursorVis.VisitChildren(parent);
4588}
4589
4590#ifndef __has_feature
4591#define0 __has_feature(x)0 0
4592#endif
4593#if __has_feature(blocks)0
4594typedef enum CXChildVisitResult (^CXCursorVisitorBlock)(CXCursor cursor,
4595 CXCursor parent);
4596
4597static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4598 CXClientData client_data) {
4599 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4600 return block(cursor, parent);
4601}
4602#else
4603// If we are compiled with a compiler that doesn't have native blocks support,
4604// define and call the block manually, so the
4605typedef struct _CXChildVisitResult {
4606 void *isa;
4607 int flags;
4608 int reserved;
4609 enum CXChildVisitResult (*invoke)(struct _CXChildVisitResult *, CXCursor,
4610 CXCursor);
4611} * CXCursorVisitorBlock;
4612
4613static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4614 CXClientData client_data) {
4615 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4616 return block->invoke(block, cursor, parent);
4617}
4618#endif
4619
4620unsigned clang_visitChildrenWithBlock(CXCursor parent,
4621 CXCursorVisitorBlock block) {
4622 return clang_visitChildren(parent, visitWithBlock, block);
4623}
4624
4625static CXString getDeclSpelling(const Decl *D) {
4626 if (!D)
4627 return cxstring::createEmpty();
4628
4629 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
4630 if (!ND) {
4631 if (const ObjCPropertyImplDecl *PropImpl =
4632 dyn_cast<ObjCPropertyImplDecl>(D))
4633 if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
4634 return cxstring::createDup(Property->getIdentifier()->getName());
4635
4636 if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
4637 if (Module *Mod = ImportD->getImportedModule())
4638 return cxstring::createDup(Mod->getFullModuleName());
4639
4640 return cxstring::createEmpty();
4641 }
4642
4643 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
4644 return cxstring::createDup(OMD->getSelector().getAsString());
4645
4646 if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
4647 // No, this isn't the same as the code below. getIdentifier() is non-virtual
4648 // and returns different names. NamedDecl returns the class name and
4649 // ObjCCategoryImplDecl returns the category name.
4650 return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
4651
4652 if (isa<UsingDirectiveDecl>(D))
4653 return cxstring::createEmpty();
4654
4655 SmallString<1024> S;
4656 llvm::raw_svector_ostream os(S);
4657 ND->printName(os);
4658
4659 return cxstring::createDup(os.str());
4660}
4661
4662CXString clang_getCursorSpelling(CXCursor C) {
4663 if (clang_isTranslationUnit(C.kind))
4664 return clang_getTranslationUnitSpelling(getCursorTU(C));
4665
4666 if (clang_isReference(C.kind)) {
4667 switch (C.kind) {
4668 case CXCursor_ObjCSuperClassRef: {
4669 const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
4670 return cxstring::createRef(Super->getIdentifier()->getNameStart());
4671 }
4672 case CXCursor_ObjCClassRef: {
4673 const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
4674 return cxstring::createRef(Class->getIdentifier()->getNameStart());
4675 }
4676 case CXCursor_ObjCProtocolRef: {
4677 const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
4678 assert(OID && "getCursorSpelling(): Missing protocol decl")(static_cast <bool> (OID && "getCursorSpelling(): Missing protocol decl"
) ? void (0) : __assert_fail ("OID && \"getCursorSpelling(): Missing protocol decl\""
, "clang/tools/libclang/CIndex.cpp", 4678, __extension__ __PRETTY_FUNCTION__
))
;
4679 return cxstring::createRef(OID->getIdentifier()->getNameStart());
4680 }
4681 case CXCursor_CXXBaseSpecifier: {
4682 const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
4683 return cxstring::createDup(B->getType().getAsString());
4684 }
4685 case CXCursor_TypeRef: {
4686 const TypeDecl *Type = getCursorTypeRef(C).first;
4687 assert(Type && "Missing type decl")(static_cast <bool> (Type && "Missing type decl"
) ? void (0) : __assert_fail ("Type && \"Missing type decl\""
, "clang/tools/libclang/CIndex.cpp", 4687, __extension__ __PRETTY_FUNCTION__
))
;
4688
4689 return cxstring::createDup(
4690 getCursorContext(C).getTypeDeclType(Type).getAsString());
4691 }
4692 case CXCursor_TemplateRef: {
4693 const TemplateDecl *Template = getCursorTemplateRef(C).first;
4694 assert(Template && "Missing template decl")(static_cast <bool> (Template && "Missing template decl"
) ? void (0) : __assert_fail ("Template && \"Missing template decl\""
, "clang/tools/libclang/CIndex.cpp", 4694, __extension__ __PRETTY_FUNCTION__
))
;
4695
4696 return cxstring::createDup(Template->getNameAsString());
4697 }
4698
4699 case CXCursor_NamespaceRef: {
4700 const NamedDecl *NS = getCursorNamespaceRef(C).first;
4701 assert(NS && "Missing namespace decl")(static_cast <bool> (NS && "Missing namespace decl"
) ? void (0) : __assert_fail ("NS && \"Missing namespace decl\""
, "clang/tools/libclang/CIndex.cpp", 4701, __extension__ __PRETTY_FUNCTION__
))
;
4702
4703 return cxstring::createDup(NS->getNameAsString());
4704 }
4705
4706 case CXCursor_MemberRef: {
4707 const FieldDecl *Field = getCursorMemberRef(C).first;
4708 assert(Field && "Missing member decl")(static_cast <bool> (Field && "Missing member decl"
) ? void (0) : __assert_fail ("Field && \"Missing member decl\""
, "clang/tools/libclang/CIndex.cpp", 4708, __extension__ __PRETTY_FUNCTION__
))
;
4709
4710 return cxstring::createDup(Field->getNameAsString());
4711 }
4712
4713 case CXCursor_LabelRef: {
4714 const LabelStmt *Label = getCursorLabelRef(C).first;
4715 assert(Label && "Missing label")(static_cast <bool> (Label && "Missing label") ?
void (0) : __assert_fail ("Label && \"Missing label\""
, "clang/tools/libclang/CIndex.cpp", 4715, __extension__ __PRETTY_FUNCTION__
))
;
4716
4717 return cxstring::createRef(Label->getName());
4718 }
4719
4720 case CXCursor_OverloadedDeclRef: {
4721 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4722 if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4723 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
4724 return cxstring::createDup(ND->getNameAsString());
4725 return cxstring::createEmpty();
4726 }
4727 if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
4728 return cxstring::createDup(E->getName().getAsString());
4729 OverloadedTemplateStorage *Ovl =
4730 Storage.get<OverloadedTemplateStorage *>();
4731 if (Ovl->size() == 0)
4732 return cxstring::createEmpty();
4733 return cxstring::createDup((*Ovl->begin())->getNameAsString());
4734 }
4735
4736 case CXCursor_VariableRef: {
4737 const VarDecl *Var = getCursorVariableRef(C).first;
4738 assert(Var && "Missing variable decl")(static_cast <bool> (Var && "Missing variable decl"
) ? void (0) : __assert_fail ("Var && \"Missing variable decl\""
, "clang/tools/libclang/CIndex.cpp", 4738, __extension__ __PRETTY_FUNCTION__
))
;
4739
4740 return cxstring::createDup(Var->getNameAsString());
4741 }
4742
4743 default:
4744 return cxstring::createRef("<not implemented>");
4745 }
4746 }
4747
4748 if (clang_isExpression(C.kind)) {
4749 const Expr *E = getCursorExpr(C);
4750
4751 if (C.kind == CXCursor_ObjCStringLiteral ||
4752 C.kind == CXCursor_StringLiteral) {
4753 const StringLiteral *SLit;
4754 if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4755 SLit = OSL->getString();
4756 } else {
4757 SLit = cast<StringLiteral>(E);
4758 }
4759 SmallString<256> Buf;
4760 llvm::raw_svector_ostream OS(Buf);
4761 SLit->outputString(OS);
4762 return cxstring::createDup(OS.str());
4763 }
4764
4765 const Decl *D = getDeclFromExpr(getCursorExpr(C));
4766 if (D)
4767 return getDeclSpelling(D);
4768 return cxstring::createEmpty();
4769 }
4770
4771 if (clang_isStatement(C.kind)) {
4772 const Stmt *S = getCursorStmt(C);
4773 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
4774 return cxstring::createRef(Label->getName());
4775
4776 return cxstring::createEmpty();
4777 }
4778
4779 if (C.kind == CXCursor_MacroExpansion)
4780 return cxstring::createRef(
4781 getCursorMacroExpansion(C).getName()->getNameStart());
4782
4783 if (C.kind == CXCursor_MacroDefinition)
4784 return cxstring::createRef(
4785 getCursorMacroDefinition(C)->getName()->getNameStart());
4786
4787 if (C.kind == CXCursor_InclusionDirective)
4788 return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
4789
4790 if (clang_isDeclaration(C.kind))
4791 return getDeclSpelling(getCursorDecl(C));
4792
4793 if (C.kind == CXCursor_AnnotateAttr) {
4794 const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
4795 return cxstring::createDup(AA->getAnnotation());
4796 }
4797
4798 if (C.kind == CXCursor_AsmLabelAttr) {
4799 const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
4800 return cxstring::createDup(AA->getLabel());
4801 }
4802
4803 if (C.kind == CXCursor_PackedAttr) {
4804 return cxstring::createRef("packed");
4805 }
4806
4807 if (C.kind == CXCursor_VisibilityAttr) {
4808 const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4809 switch (AA->getVisibility()) {
4810 case VisibilityAttr::VisibilityType::Default:
4811 return cxstring::createRef("default");
4812 case VisibilityAttr::VisibilityType::Hidden:
4813 return cxstring::createRef("hidden");
4814 case VisibilityAttr::VisibilityType::Protected:
4815 return cxstring::createRef("protected");
4816 }
4817 llvm_unreachable("unknown visibility type")::llvm::llvm_unreachable_internal("unknown visibility type", "clang/tools/libclang/CIndex.cpp"
, 4817)
;
4818 }
4819
4820 return cxstring::createEmpty();
4821}
4822
4823CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C, unsigned pieceIndex,
4824 unsigned options) {
4825 if (clang_Cursor_isNull(C))
4826 return clang_getNullRange();
4827
4828 ASTContext &Ctx = getCursorContext(C);
4829
4830 if (clang_isStatement(C.kind)) {
4831 const Stmt *S = getCursorStmt(C);
4832 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
4833 if (pieceIndex > 0)
4834 return clang_getNullRange();
4835 return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4836 }
4837
4838 return clang_getNullRange();
4839 }
4840
4841 if (C.kind == CXCursor_ObjCMessageExpr) {
4842 if (const ObjCMessageExpr *ME =
4843 dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4844 if (pieceIndex >= ME->getNumSelectorLocs())
4845 return clang_getNullRange();
4846 return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4847 }
4848 }
4849
4850 if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4851 C.kind == CXCursor_ObjCClassMethodDecl) {
4852 if (const ObjCMethodDecl *MD =
4853 dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4854 if (pieceIndex >= MD->getNumSelectorLocs())
4855 return clang_getNullRange();
4856 return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4857 }
4858 }
4859
4860 if (C.kind == CXCursor_ObjCCategoryDecl ||
4861 C.kind == CXCursor_ObjCCategoryImplDecl) {
4862 if (pieceIndex > 0)
4863 return clang_getNullRange();
4864 if (const ObjCCategoryDecl *CD =
4865 dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4866 return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
4867 if (const ObjCCategoryImplDecl *CID =
4868 dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4869 return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4870 }
4871
4872 if (C.kind == CXCursor_ModuleImportDecl) {
4873 if (pieceIndex > 0)
4874 return clang_getNullRange();
4875 if (const ImportDecl *ImportD =
4876 dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
4877 ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4878 if (!Locs.empty())
4879 return cxloc::translateSourceRange(
4880 Ctx, SourceRange(Locs.front(), Locs.back()));
4881 }
4882 return clang_getNullRange();
4883 }
4884
4885 if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
4886 C.kind == CXCursor_ConversionFunction ||
4887 C.kind == CXCursor_FunctionDecl) {
4888 if (pieceIndex > 0)
4889 return clang_getNullRange();
4890 if (const FunctionDecl *FD =
4891 dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4892 DeclarationNameInfo FunctionName = FD->getNameInfo();
4893 return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4894 }
4895 return clang_getNullRange();
4896 }
4897
4898 // FIXME: A CXCursor_InclusionDirective should give the location of the
4899 // filename, but we don't keep track of this.
4900
4901 // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4902 // but we don't keep track of this.
4903
4904 // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4905 // but we don't keep track of this.
4906
4907 // Default handling, give the location of the cursor.
4908
4909 if (pieceIndex > 0)
4910 return clang_getNullRange();
4911
4912 CXSourceLocation CXLoc = clang_getCursorLocation(C);
4913 SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4914 return cxloc::translateSourceRange(Ctx, Loc);
4915}
4916
4917CXString clang_Cursor_getMangling(CXCursor C) {
4918 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4919 return cxstring::createEmpty();
4920
4921 // Mangling only works for functions and variables.
4922 const Decl *D = getCursorDecl(C);
4923 if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
4924 return cxstring::createEmpty();
4925
4926 ASTContext &Ctx = D->getASTContext();
4927 ASTNameGenerator ASTNameGen(Ctx);
4928 return cxstring::createDup(ASTNameGen.getName(D));
4929}
4930
4931CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4932 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4933 return nullptr;
4934
4935 const Decl *D = getCursorDecl(C);
4936 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
4937 return nullptr;
4938
4939 ASTContext &Ctx = D->getASTContext();
4940 ASTNameGenerator ASTNameGen(Ctx);
4941 std::vector<std::string> Manglings = ASTNameGen.getAllManglings(D);
4942 return cxstring::createSet(Manglings);
4943}
4944
4945CXStringSet *clang_Cursor_getObjCManglings(CXCursor C) {
4946 if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4947 return nullptr;
4948
4949 const Decl *D = getCursorDecl(C);
4950 if (!(isa<ObjCInterfaceDecl>(D) || isa<ObjCImplementationDecl>(D)))
4951 return nullptr;
4952
4953 ASTContext &Ctx = D->getASTContext();
4954 ASTNameGenerator ASTNameGen(Ctx);
4955 std::vector<std::string> Manglings = ASTNameGen.getAllManglings(D);
4956 return cxstring::createSet(Manglings);
4957}
4958
4959CXPrintingPolicy clang_getCursorPrintingPolicy(CXCursor C) {
4960 if (clang_Cursor_isNull(C))
4961 return nullptr;
4962 return new PrintingPolicy(getCursorContext(C).getPrintingPolicy());
4963}
4964
4965void clang_PrintingPolicy_dispose(CXPrintingPolicy Policy) {
4966 if (Policy)
4967 delete static_cast<PrintingPolicy *>(Policy);
4968}
4969
4970unsigned
4971clang_PrintingPolicy_getProperty(CXPrintingPolicy Policy,
4972 enum CXPrintingPolicyProperty Property) {
4973 if (!Policy)
4974 return 0;
4975
4976 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4977 switch (Property) {
4978 case CXPrintingPolicy_Indentation:
4979 return P->Indentation;
4980 case CXPrintingPolicy_SuppressSpecifiers:
4981 return P->SuppressSpecifiers;
4982 case CXPrintingPolicy_SuppressTagKeyword:
4983 return P->SuppressTagKeyword;
4984 case CXPrintingPolicy_IncludeTagDefinition:
4985 return P->IncludeTagDefinition;
4986 case CXPrintingPolicy_SuppressScope:
4987 return P->SuppressScope;
4988 case CXPrintingPolicy_SuppressUnwrittenScope:
4989 return P->SuppressUnwrittenScope;
4990 case CXPrintingPolicy_SuppressInitializers:
4991 return P->SuppressInitializers;
4992 case CXPrintingPolicy_ConstantArraySizeAsWritten:
4993 return P->ConstantArraySizeAsWritten;
4994 case CXPrintingPolicy_AnonymousTagLocations:
4995 return P->AnonymousTagLocations;
4996 case CXPrintingPolicy_SuppressStrongLifetime:
4997 return P->SuppressStrongLifetime;
4998 case CXPrintingPolicy_SuppressLifetimeQualifiers:
4999 return P->SuppressLifetimeQualifiers;
5000 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
5001 return P->SuppressTemplateArgsInCXXConstructors;
5002 case CXPrintingPolicy_Bool:
5003 return P->Bool;
5004 case CXPrintingPolicy_Restrict:
5005 return P->Restrict;
5006 case CXPrintingPolicy_Alignof:
5007 return P->Alignof;
5008 case CXPrintingPolicy_UnderscoreAlignof:
5009 return P->UnderscoreAlignof;
5010 case CXPrintingPolicy_UseVoidForZeroParams:
5011 return P->UseVoidForZeroParams;
5012 case CXPrintingPolicy_TerseOutput:
5013 return P->TerseOutput;
5014 case CXPrintingPolicy_PolishForDeclaration:
5015 return P->PolishForDeclaration;
5016 case CXPrintingPolicy_Half:
5017 return P->Half;
5018 case CXPrintingPolicy_MSWChar:
5019 return P->MSWChar;
5020 case CXPrintingPolicy_IncludeNewlines:
5021 return P->IncludeNewlines;
5022 case CXPrintingPolicy_MSVCFormatting:
5023 return P->MSVCFormatting;
5024 case CXPrintingPolicy_ConstantsAsWritten:
5025 return P->ConstantsAsWritten;
5026 case CXPrintingPolicy_SuppressImplicitBase:
5027 return P->SuppressImplicitBase;
5028 case CXPrintingPolicy_FullyQualifiedName:
5029 return P->FullyQualifiedName;
5030 }
5031
5032 assert(false && "Invalid CXPrintingPolicyProperty")(static_cast <bool> (false && "Invalid CXPrintingPolicyProperty"
) ? void (0) : __assert_fail ("false && \"Invalid CXPrintingPolicyProperty\""
, "clang/tools/libclang/CIndex.cpp", 5032, __extension__ __PRETTY_FUNCTION__
))
;
5033 return 0;
5034}
5035
5036void clang_PrintingPolicy_setProperty(CXPrintingPolicy Policy,
5037 enum CXPrintingPolicyProperty Property,
5038 unsigned Value) {
5039 if (!Policy)
5040 return;
5041
5042 PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
5043 switch (Property) {
5044 case CXPrintingPolicy_Indentation:
5045 P->Indentation = Value;
5046 return;
5047 case CXPrintingPolicy_SuppressSpecifiers:
5048 P->SuppressSpecifiers = Value;
5049 return;
5050 case CXPrintingPolicy_SuppressTagKeyword:
5051 P->SuppressTagKeyword = Value;
5052 return;
5053 case CXPrintingPolicy_IncludeTagDefinition:
5054 P->IncludeTagDefinition = Value;
5055 return;
5056 case CXPrintingPolicy_SuppressScope:
5057 P->SuppressScope = Value;
5058 return;
5059 case CXPrintingPolicy_SuppressUnwrittenScope:
5060 P->SuppressUnwrittenScope = Value;
5061 return;
5062 case CXPrintingPolicy_SuppressInitializers:
5063 P->SuppressInitializers = Value;
5064 return;
5065 case CXPrintingPolicy_ConstantArraySizeAsWritten:
5066 P->ConstantArraySizeAsWritten = Value;
5067 return;
5068 case CXPrintingPolicy_AnonymousTagLocations:
5069 P->AnonymousTagLocations = Value;
5070 return;
5071 case CXPrintingPolicy_SuppressStrongLifetime:
5072 P->SuppressStrongLifetime = Value;
5073 return;
5074 case CXPrintingPolicy_SuppressLifetimeQualifiers:
5075 P->SuppressLifetimeQualifiers = Value;
5076 return;
5077 case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
5078 P->SuppressTemplateArgsInCXXConstructors = Value;
5079 return;
5080 case CXPrintingPolicy_Bool:
5081 P->Bool = Value;
5082 return;
5083 case CXPrintingPolicy_Restrict:
5084 P->Restrict = Value;
5085 return;
5086 case CXPrintingPolicy_Alignof:
5087 P->Alignof = Value;
5088 return;
5089 case CXPrintingPolicy_UnderscoreAlignof:
5090 P->UnderscoreAlignof = Value;
5091 return;
5092 case CXPrintingPolicy_UseVoidForZeroParams:
5093 P->UseVoidForZeroParams = Value;
5094 return;
5095 case CXPrintingPolicy_TerseOutput:
5096 P->TerseOutput = Value;
5097 return;
5098 case CXPrintingPolicy_PolishForDeclaration:
5099 P->PolishForDeclaration = Value;
5100 return;
5101 case CXPrintingPolicy_Half:
5102 P->Half = Value;
5103 return;
5104 case CXPrintingPolicy_MSWChar:
5105 P->MSWChar = Value;
5106 return;
5107 case CXPrintingPolicy_IncludeNewlines:
5108 P->IncludeNewlines = Value;
5109 return;
5110 case CXPrintingPolicy_MSVCFormatting:
5111 P->MSVCFormatting = Value;
5112 return;
5113 case CXPrintingPolicy_ConstantsAsWritten:
5114 P->ConstantsAsWritten = Value;
5115 return;
5116 case CXPrintingPolicy_SuppressImplicitBase:
5117 P->SuppressImplicitBase = Value;
5118 return;
5119 case CXPrintingPolicy_FullyQualifiedName:
5120 P->FullyQualifiedName = Value;
5121 return;
5122 }
5123
5124 assert(false && "Invalid CXPrintingPolicyProperty")(static_cast <bool> (false && "Invalid CXPrintingPolicyProperty"
) ? void (0) : __assert_fail ("false && \"Invalid CXPrintingPolicyProperty\""
, "clang/tools/libclang/CIndex.cpp", 5124, __extension__ __PRETTY_FUNCTION__
))
;
5125}
5126
5127CXString clang_getCursorPrettyPrinted(CXCursor C, CXPrintingPolicy cxPolicy) {
5128 if (clang_Cursor_isNull(C))
5129 return cxstring::createEmpty();
5130
5131 if (clang_isDeclaration(C.kind)) {
5132 const Decl *D = getCursorDecl(C);
5133 if (!D)
5134 return cxstring::createEmpty();
5135
5136 SmallString<128> Str;
5137 llvm::raw_svector_ostream OS(Str);
5138 PrintingPolicy *UserPolicy = static_cast<PrintingPolicy *>(cxPolicy);
5139 D->print(OS, UserPolicy ? *UserPolicy
5140 : getCursorContext(C).getPrintingPolicy());
5141
5142 return cxstring::createDup(OS.str());
5143 }
5144
5145 return cxstring::createEmpty();
5146}
5147
5148CXString clang_getCursorDisplayName(CXCursor C) {
5149 if (!clang_isDeclaration(C.kind))
5150 return clang_getCursorSpelling(C);
5151
5152 const Decl *D = getCursorDecl(C);
5153 if (!D)
5154 return cxstring::createEmpty();
5155
5156 PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
5157 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
5158 D = FunTmpl->getTemplatedDecl();
5159
5160 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
5161 SmallString<64> Str;
5162 llvm::raw_svector_ostream OS(Str);
5163 OS << *Function;
5164 if (Function->getPrimaryTemplate())
5165 OS << "<>";
5166 OS << "(";
5167 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
5168 if (I)
5169 OS << ", ";
5170 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
5171 }
5172
5173 if (Function->isVariadic()) {
5174 if (Function->getNumParams())
5175 OS << ", ";
5176 OS << "...";
5177 }
5178 OS << ")";
5179 return cxstring::createDup(OS.str());
5180 }
5181
5182 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
5183 SmallString<64> Str;
5184 llvm::raw_svector_ostream OS(Str);
5185 OS << *ClassTemplate;
5186 OS << "<";
5187 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
5188 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
5189 if (I)
5190 OS << ", ";
5191
5192 NamedDecl *Param = Params->getParam(I);
5193 if (Param->getIdentifier()) {
5194 OS << Param->getIdentifier()->getName();
5195 continue;
5196 }
5197
5198 // There is no parameter name, which makes this tricky. Try to come up
5199 // with something useful that isn't too long.
5200 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5201 if (const auto *TC = TTP->getTypeConstraint()) {
5202 TC->getConceptNameInfo().printName(OS, Policy);
5203 if (TC->hasExplicitTemplateArgs())
5204 OS << "<...>";
5205 } else
5206 OS << (TTP->wasDeclaredWithTypename() ? "typename" : "class");
5207 else if (NonTypeTemplateParmDecl *NTTP =
5208 dyn_cast<NonTypeTemplateParmDecl>(Param))
5209 OS << NTTP->getType().getAsString(Policy);
5210 else
5211 OS << "template<...> class";
5212 }
5213
5214 OS << ">";
5215 return cxstring::createDup(OS.str());
5216 }
5217
5218 if (const ClassTemplateSpecializationDecl *ClassSpec =
5219 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
5220 // If the type was explicitly written, use that.
5221 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
5222 return cxstring::createDup(TSInfo->getType().getAsString(Policy));
5223
5224 SmallString<128> Str;
5225 llvm::raw_svector_ostream OS(Str);
5226 OS << *ClassSpec;
5227 printTemplateArgumentList(
5228 OS, ClassSpec->getTemplateArgs().asArray(), Policy,
5229 ClassSpec->getSpecializedTemplate()->getTemplateParameters());
5230 return cxstring::createDup(OS.str());
5231 }
5232
5233 return clang_getCursorSpelling(C);
5234}
5235
5236CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
5237 switch (Kind) {
5238 case CXCursor_FunctionDecl:
5239 return cxstring::createRef("FunctionDecl");
5240 case CXCursor_TypedefDecl:
5241 return cxstring::createRef("TypedefDecl");
5242 case CXCursor_EnumDecl:
5243 return cxstring::createRef("EnumDecl");
5244 case CXCursor_EnumConstantDecl:
5245 return cxstring::createRef("EnumConstantDecl");
5246 case CXCursor_StructDecl:
5247 return cxstring::createRef("StructDecl");
5248 case CXCursor_UnionDecl:
5249 return cxstring::createRef("UnionDecl");
5250 case CXCursor_ClassDecl:
5251 return cxstring::createRef("ClassDecl");
5252 case CXCursor_FieldDecl:
5253 return cxstring::createRef("FieldDecl");
5254 case CXCursor_VarDecl:
5255 return cxstring::createRef("VarDecl");
5256 case CXCursor_ParmDecl:
5257 return cxstring::createRef("ParmDecl");
5258 case CXCursor_ObjCInterfaceDecl:
5259 return cxstring::createRef("ObjCInterfaceDecl");
5260 case CXCursor_ObjCCategoryDecl:
5261 return cxstring::createRef("ObjCCategoryDecl");
5262 case CXCursor_ObjCProtocolDecl:
5263 return cxstring::createRef("ObjCProtocolDecl");
5264 case CXCursor_ObjCPropertyDecl:
5265 return cxstring::createRef("ObjCPropertyDecl");
5266 case CXCursor_ObjCIvarDecl:
5267 return cxstring::createRef("ObjCIvarDecl");
5268 case CXCursor_ObjCInstanceMethodDecl:
5269 return cxstring::createRef("ObjCInstanceMethodDecl");
5270 case CXCursor_ObjCClassMethodDecl:
5271 return cxstring::createRef("ObjCClassMethodDecl");
5272 case CXCursor_ObjCImplementationDecl:
5273 return cxstring::createRef("ObjCImplementationDecl");
5274 case CXCursor_ObjCCategoryImplDecl:
5275 return cxstring::createRef("ObjCCategoryImplDecl");
5276 case CXCursor_CXXMethod:
5277 return cxstring::createRef("CXXMethod");
5278 case CXCursor_UnexposedDecl:
5279 return cxstring::createRef("UnexposedDecl");
5280 case CXCursor_ObjCSuperClassRef:
5281 return cxstring::createRef("ObjCSuperClassRef");
5282 case CXCursor_ObjCProtocolRef:
5283 return cxstring::createRef("ObjCProtocolRef");
5284 case CXCursor_ObjCClassRef:
5285 return cxstring::createRef("ObjCClassRef");
5286 case CXCursor_TypeRef:
5287 return cxstring::createRef("TypeRef");
5288 case CXCursor_TemplateRef:
5289 return cxstring::createRef("TemplateRef");
5290 case CXCursor_NamespaceRef:
5291 return cxstring::createRef("NamespaceRef");
5292 case CXCursor_MemberRef:
5293 return cxstring::createRef("MemberRef");
5294 case CXCursor_LabelRef:
5295 return cxstring::createRef("LabelRef");
5296 case CXCursor_OverloadedDeclRef:
5297 return cxstring::createRef("OverloadedDeclRef");
5298 case CXCursor_VariableRef:
5299 return cxstring::createRef("VariableRef");
5300 case CXCursor_IntegerLiteral:
5301 return cxstring::createRef("IntegerLiteral");
5302 case CXCursor_FixedPointLiteral:
5303 return cxstring::createRef("FixedPointLiteral");
5304 case CXCursor_FloatingLiteral:
5305 return cxstring::createRef("FloatingLiteral");
5306 case CXCursor_ImaginaryLiteral:
5307 return cxstring::createRef("ImaginaryLiteral");
5308 case CXCursor_StringLiteral:
5309 return cxstring::createRef("StringLiteral");
5310 case CXCursor_CharacterLiteral:
5311 return cxstring::createRef("CharacterLiteral");
5312 case CXCursor_ParenExpr:
5313 return cxstring::createRef("ParenExpr");
5314 case CXCursor_UnaryOperator:
5315 return cxstring::createRef("UnaryOperator");
5316 case CXCursor_ArraySubscriptExpr:
5317 return cxstring::createRef("ArraySubscriptExpr");
5318 case CXCursor_OMPArraySectionExpr:
5319 return cxstring::createRef("OMPArraySectionExpr");
5320 case CXCursor_OMPArrayShapingExpr:
5321 return cxstring::createRef("OMPArrayShapingExpr");
5322 case CXCursor_OMPIteratorExpr:
5323 return cxstring::createRef("OMPIteratorExpr");
5324 case CXCursor_BinaryOperator:
5325 return cxstring::createRef("BinaryOperator");
5326 case CXCursor_CompoundAssignOperator:
5327 return cxstring::createRef("CompoundAssignOperator");
5328 case CXCursor_ConditionalOperator:
5329 return cxstring::createRef("ConditionalOperator");
5330 case CXCursor_CStyleCastExpr:
5331 return cxstring::createRef("CStyleCastExpr");
5332 case CXCursor_CompoundLiteralExpr:
5333 return cxstring::createRef("CompoundLiteralExpr");
5334 case CXCursor_InitListExpr:
5335 return cxstring::createRef("InitListExpr");
5336 case CXCursor_AddrLabelExpr:
5337 return cxstring::createRef("AddrLabelExpr");
5338 case CXCursor_StmtExpr:
5339 return cxstring::createRef("StmtExpr");
5340 case CXCursor_GenericSelectionExpr:
5341 return cxstring::createRef("GenericSelectionExpr");
5342 case CXCursor_GNUNullExpr:
5343 return cxstring::createRef("GNUNullExpr");
5344 case CXCursor_CXXStaticCastExpr:
5345 return cxstring::createRef("CXXStaticCastExpr");
5346 case CXCursor_CXXDynamicCastExpr:
5347 return cxstring::createRef("CXXDynamicCastExpr");
5348 case CXCursor_CXXReinterpretCastExpr:
5349 return cxstring::createRef("CXXReinterpretCastExpr");
5350 case CXCursor_CXXConstCastExpr:
5351 return cxstring::createRef("CXXConstCastExpr");
5352 case CXCursor_CXXFunctionalCastExpr:
5353 return cxstring::createRef("CXXFunctionalCastExpr");
5354 case CXCursor_CXXAddrspaceCastExpr:
5355 return cxstring::createRef("CXXAddrspaceCastExpr");
5356 case CXCursor_CXXTypeidExpr:
5357 return cxstring::createRef("CXXTypeidExpr");
5358 case CXCursor_CXXBoolLiteralExpr:
5359 return cxstring::createRef("CXXBoolLiteralExpr");
5360 case CXCursor_CXXNullPtrLiteralExpr:
5361 return cxstring::createRef("CXXNullPtrLiteralExpr");
5362 case CXCursor_CXXThisExpr:
5363 return cxstring::createRef("CXXThisExpr");
5364 case CXCursor_CXXThrowExpr:
5365 return cxstring::createRef("CXXThrowExpr");
5366 case CXCursor_CXXNewExpr:
5367 return cxstring::createRef("CXXNewExpr");
5368 case CXCursor_CXXDeleteExpr:
5369 return cxstring::createRef("CXXDeleteExpr");
5370 case CXCursor_UnaryExpr:
5371 return cxstring::createRef("UnaryExpr");
5372 case CXCursor_ObjCStringLiteral:
5373 return cxstring::createRef("ObjCStringLiteral");
5374 case CXCursor_ObjCBoolLiteralExpr:
5375 return cxstring::createRef("ObjCBoolLiteralExpr");
5376 case CXCursor_ObjCAvailabilityCheckExpr:
5377 return cxstring::createRef("ObjCAvailabilityCheckExpr");
5378 case CXCursor_ObjCSelfExpr:
5379 return cxstring::createRef("ObjCSelfExpr");
5380 case CXCursor_ObjCEncodeExpr:
5381 return cxstring::createRef("ObjCEncodeExpr");
5382 case CXCursor_ObjCSelectorExpr:
5383 return cxstring::createRef("ObjCSelectorExpr");
5384 case CXCursor_ObjCProtocolExpr:
5385 return cxstring::createRef("ObjCProtocolExpr");
5386 case CXCursor_ObjCBridgedCastExpr:
5387 return cxstring::createRef("ObjCBridgedCastExpr");
5388 case CXCursor_BlockExpr:
5389 return cxstring::createRef("BlockExpr");
5390 case CXCursor_PackExpansionExpr:
5391 return cxstring::createRef("PackExpansionExpr");
5392 case CXCursor_SizeOfPackExpr:
5393 return cxstring::createRef("SizeOfPackExpr");
5394 case CXCursor_LambdaExpr:
5395 return cxstring::createRef("LambdaExpr");
5396 case CXCursor_UnexposedExpr:
5397 return cxstring::createRef("UnexposedExpr");
5398 case CXCursor_DeclRefExpr:
5399 return cxstring::createRef("DeclRefExpr");
5400 case CXCursor_MemberRefExpr:
5401 return cxstring::createRef("MemberRefExpr");
5402 case CXCursor_CallExpr:
5403 return cxstring::createRef("CallExpr");
5404 case CXCursor_ObjCMessageExpr:
5405 return cxstring::createRef("ObjCMessageExpr");
5406 case CXCursor_BuiltinBitCastExpr:
5407 return cxstring::createRef("BuiltinBitCastExpr");
5408 case CXCursor_UnexposedStmt:
5409 return cxstring::createRef("UnexposedStmt");
5410 case CXCursor_DeclStmt:
5411 return cxstring::createRef("DeclStmt");
5412 case CXCursor_LabelStmt:
5413 return cxstring::createRef("LabelStmt");
5414 case CXCursor_CompoundStmt:
5415 return cxstring::createRef("CompoundStmt");
5416 case CXCursor_CaseStmt:
5417 return cxstring::createRef("CaseStmt");
5418 case CXCursor_DefaultStmt:
5419 return cxstring::createRef("DefaultStmt");
5420 case CXCursor_IfStmt:
5421 return cxstring::createRef("IfStmt");
5422 case CXCursor_SwitchStmt:
5423 return cxstring::createRef("SwitchStmt");
5424 case CXCursor_WhileStmt:
5425 return cxstring::createRef("WhileStmt");
5426 case CXCursor_DoStmt:
5427 return cxstring::createRef("DoStmt");
5428 case CXCursor_ForStmt:
5429 return cxstring::createRef("ForStmt");
5430 case CXCursor_GotoStmt:
5431 return cxstring::createRef("GotoStmt");
5432 case CXCursor_IndirectGotoStmt:
5433 return cxstring::createRef("IndirectGotoStmt");
5434 case CXCursor_ContinueStmt:
5435 return cxstring::createRef("ContinueStmt");
5436 case CXCursor_BreakStmt:
5437 return cxstring::createRef("BreakStmt");
5438 case CXCursor_ReturnStmt:
5439 return cxstring::createRef("ReturnStmt");
5440 case CXCursor_GCCAsmStmt:
5441 return cxstring::createRef("GCCAsmStmt");
5442 case CXCursor_MSAsmStmt:
5443 return cxstring::createRef("MSAsmStmt");
5444 case CXCursor_ObjCAtTryStmt:
5445 return cxstring::createRef("ObjCAtTryStmt");
5446 case CXCursor_ObjCAtCatchStmt:
5447 return cxstring::createRef("ObjCAtCatchStmt");
5448 case CXCursor_ObjCAtFinallyStmt:
5449 return cxstring::createRef("ObjCAtFinallyStmt");
5450 case CXCursor_ObjCAtThrowStmt:
5451 return cxstring::createRef("ObjCAtThrowStmt");
5452 case CXCursor_ObjCAtSynchronizedStmt:
5453 return cxstring::createRef("ObjCAtSynchronizedStmt");
5454 case CXCursor_ObjCAutoreleasePoolStmt:
5455 return cxstring::createRef("ObjCAutoreleasePoolStmt");
5456 case CXCursor_ObjCForCollectionStmt:
5457 return cxstring::createRef("ObjCForCollectionStmt");
5458 case CXCursor_CXXCatchStmt:
5459 return cxstring::createRef("CXXCatchStmt");
5460 case CXCursor_CXXTryStmt:
5461 return cxstring::createRef("CXXTryStmt");
5462 case CXCursor_CXXForRangeStmt:
5463 return cxstring::createRef("CXXForRangeStmt");
5464 case CXCursor_SEHTryStmt:
5465 return cxstring::createRef("SEHTryStmt");
5466 case CXCursor_SEHExceptStmt:
5467 return cxstring::createRef("SEHExceptStmt");
5468 case CXCursor_SEHFinallyStmt:
5469 return cxstring::createRef("SEHFinallyStmt");
5470 case CXCursor_SEHLeaveStmt:
5471 return cxstring::createRef("SEHLeaveStmt");
5472 case CXCursor_NullStmt:
5473 return cxstring::createRef("NullStmt");
5474 case CXCursor_InvalidFile:
5475 return cxstring::createRef("InvalidFile");
5476 case CXCursor_InvalidCode:
5477 return cxstring::createRef("InvalidCode");
5478 case CXCursor_NoDeclFound:
5479 return cxstring::createRef("NoDeclFound");
5480 case CXCursor_NotImplemented:
5481 return cxstring::createRef("NotImplemented");
5482 case CXCursor_TranslationUnit:
5483 return cxstring::createRef("TranslationUnit");
5484 case CXCursor_UnexposedAttr:
5485 return cxstring::createRef("UnexposedAttr");
5486 case CXCursor_IBActionAttr:
5487 return cxstring::createRef("attribute(ibaction)");
5488 case CXCursor_IBOutletAttr:
5489 return cxstring::createRef("attribute(iboutlet)");
5490 case CXCursor_IBOutletCollectionAttr:
5491 return cxstring::createRef("attribute(iboutletcollection)");
5492 case CXCursor_CXXFinalAttr:
5493 return cxstring::createRef("attribute(final)");
5494 case CXCursor_CXXOverrideAttr:
5495 return cxstring::createRef("attribute(override)");
5496 case CXCursor_AnnotateAttr:
5497 return cxstring::createRef("attribute(annotate)");
5498 case CXCursor_AsmLabelAttr:
5499 return cxstring::createRef("asm label");
5500 case CXCursor_PackedAttr:
5501 return cxstring::createRef("attribute(packed)");
5502 case CXCursor_PureAttr:
5503 return cxstring::createRef("attribute(pure)");
5504 case CXCursor_ConstAttr:
5505 return cxstring::createRef("attribute(const)");
5506 case CXCursor_NoDuplicateAttr:
5507 return cxstring::createRef("attribute(noduplicate)");
5508 case CXCursor_CUDAConstantAttr:
5509 return cxstring::createRef("attribute(constant)");
5510 case CXCursor_CUDADeviceAttr:
5511 return cxstring::createRef("attribute(device)");
5512 case CXCursor_CUDAGlobalAttr:
5513 return cxstring::createRef("attribute(global)");
5514 case CXCursor_CUDAHostAttr:
5515 return cxstring::createRef("attribute(host)");
5516 case CXCursor_CUDASharedAttr:
5517 return cxstring::createRef("attribute(shared)");
5518 case CXCursor_VisibilityAttr:
5519 return cxstring::createRef("attribute(visibility)");
5520 case CXCursor_DLLExport:
5521 return cxstring::createRef("attribute(dllexport)");
5522 case CXCursor_DLLImport:
5523 return cxstring::createRef("attribute(dllimport)");
5524 case CXCursor_NSReturnsRetained:
5525 return cxstring::createRef("attribute(ns_returns_retained)");
5526 case CXCursor_NSReturnsNotRetained:
5527 return cxstring::createRef("attribute(ns_returns_not_retained)");
5528 case CXCursor_NSReturnsAutoreleased:
5529 return cxstring::createRef("attribute(ns_returns_autoreleased)");
5530 case CXCursor_NSConsumesSelf:
5531 return cxstring::createRef("attribute(ns_consumes_self)");
5532 case CXCursor_NSConsumed:
5533 return cxstring::createRef("attribute(ns_consumed)");
5534 case CXCursor_ObjCException:
5535 return cxstring::createRef("attribute(objc_exception)");
5536 case CXCursor_ObjCNSObject:
5537 return cxstring::createRef("attribute(NSObject)");
5538 case CXCursor_ObjCIndependentClass:
5539 return cxstring::createRef("attribute(objc_independent_class)");
5540 case CXCursor_ObjCPreciseLifetime:
5541 return cxstring::createRef("attribute(objc_precise_lifetime)");
5542 case CXCursor_ObjCReturnsInnerPointer:
5543 return cxstring::createRef("attribute(objc_returns_inner_pointer)");
5544 case CXCursor_ObjCRequiresSuper:
5545 return cxstring::createRef("attribute(objc_requires_super)");
5546 case CXCursor_ObjCRootClass:
5547 return cxstring::createRef("attribute(objc_root_class)");
5548 case CXCursor_ObjCSubclassingRestricted:
5549 return cxstring::createRef("attribute(objc_subclassing_restricted)");
5550 case CXCursor_ObjCExplicitProtocolImpl:
5551 return cxstring::createRef(
5552 "attribute(objc_protocol_requires_explicit_implementation)");
5553 case CXCursor_ObjCDesignatedInitializer:
5554 return cxstring::createRef("attribute(objc_designated_initializer)");
5555 case CXCursor_ObjCRuntimeVisible:
5556 return cxstring::createRef("attribute(objc_runtime_visible)");
5557 case CXCursor_ObjCBoxable:
5558 return cxstring::createRef("attribute(objc_boxable)");
5559 case CXCursor_FlagEnum:
5560 return cxstring::createRef("attribute(flag_enum)");
5561 case CXCursor_PreprocessingDirective:
5562 return cxstring::createRef("preprocessing directive");
5563 case CXCursor_MacroDefinition:
5564 return cxstring::createRef("macro definition");
5565 case CXCursor_MacroExpansion:
5566 return cxstring::createRef("macro expansion");
5567 case CXCursor_InclusionDirective:
5568 return cxstring::createRef("inclusion directive");
5569 case CXCursor_Namespace:
5570 return cxstring::createRef("Namespace");
5571 case CXCursor_LinkageSpec:
5572 return cxstring::createRef("LinkageSpec");
5573 case CXCursor_CXXBaseSpecifier:
5574 return cxstring::createRef("C++ base class specifier");
5575 case CXCursor_Constructor:
5576 return cxstring::createRef("CXXConstructor");
5577 case CXCursor_Destructor:
5578 return cxstring::createRef("CXXDestructor");
5579 case CXCursor_ConversionFunction:
5580 return cxstring::createRef("CXXConversion");
5581 case CXCursor_TemplateTypeParameter:
5582 return cxstring::createRef("TemplateTypeParameter");
5583 case CXCursor_NonTypeTemplateParameter:
5584 return cxstring::createRef("NonTypeTemplateParameter");
5585 case CXCursor_TemplateTemplateParameter:
5586 return cxstring::createRef("TemplateTemplateParameter");
5587 case CXCursor_FunctionTemplate:
5588 return cxstring::createRef("FunctionTemplate");
5589 case CXCursor_ClassTemplate:
5590 return cxstring::createRef("ClassTemplate");
5591 case CXCursor_ClassTemplatePartialSpecialization:
5592 return cxstring::createRef("ClassTemplatePartialSpecialization");
5593 case CXCursor_NamespaceAlias:
5594 return cxstring::createRef("NamespaceAlias");
5595 case CXCursor_UsingDirective:
5596 return cxstring::createRef("UsingDirective");
5597 case CXCursor_UsingDeclaration:
5598 return cxstring::createRef("UsingDeclaration");
5599 case CXCursor_TypeAliasDecl:
5600 return cxstring::createRef("TypeAliasDecl");
5601 case CXCursor_ObjCSynthesizeDecl:
5602 return cxstring::createRef("ObjCSynthesizeDecl");
5603 case CXCursor_ObjCDynamicDecl:
5604 return cxstring::createRef("ObjCDynamicDecl");
5605 case CXCursor_CXXAccessSpecifier:
5606 return cxstring::createRef("CXXAccessSpecifier");
5607 case CXCursor_ModuleImportDecl:
5608 return cxstring::createRef("ModuleImport");
5609 case CXCursor_OMPCanonicalLoop:
5610 return cxstring::createRef("OMPCanonicalLoop");
5611 case CXCursor_OMPMetaDirective:
5612 return cxstring::createRef("OMPMetaDirective");
5613 case CXCursor_OMPParallelDirective:
5614 return cxstring::createRef("OMPParallelDirective");
5615 case CXCursor_OMPSimdDirective:
5616 return cxstring::createRef("OMPSimdDirective");
5617 case CXCursor_OMPTileDirective:
5618 return cxstring::createRef("OMPTileDirective");
5619 case CXCursor_OMPUnrollDirective:
5620 return cxstring::createRef("OMPUnrollDirective");
5621 case CXCursor_OMPForDirective:
5622 return cxstring::createRef("OMPForDirective");
5623 case CXCursor_OMPForSimdDirective:
5624 return cxstring::createRef("OMPForSimdDirective");
5625 case CXCursor_OMPSectionsDirective:
5626 return cxstring::createRef("OMPSectionsDirective");
5627 case CXCursor_OMPSectionDirective:
5628 return cxstring::createRef("OMPSectionDirective");
5629 case CXCursor_OMPSingleDirective:
5630 return cxstring::createRef("OMPSingleDirective");
5631 case CXCursor_OMPMasterDirective:
5632 return cxstring::createRef("OMPMasterDirective");
5633 case CXCursor_OMPCriticalDirective:
5634 return cxstring::createRef("OMPCriticalDirective");
5635 case CXCursor_OMPParallelForDirective:
5636 return cxstring::createRef("OMPParallelForDirective");
5637 case CXCursor_OMPParallelForSimdDirective:
5638 return cxstring::createRef("OMPParallelForSimdDirective");
5639 case CXCursor_OMPParallelMasterDirective:
5640 return cxstring::createRef("OMPParallelMasterDirective");
5641 case CXCursor_OMPParallelSectionsDirective:
5642 return cxstring::createRef("OMPParallelSectionsDirective");
5643 case CXCursor_OMPTaskDirective:
5644 return cxstring::createRef("OMPTaskDirective");
5645 case CXCursor_OMPTaskyieldDirective:
5646 return cxstring::createRef("OMPTaskyieldDirective");
5647 case CXCursor_OMPBarrierDirective:
5648 return cxstring::createRef("OMPBarrierDirective");
5649 case CXCursor_OMPTaskwaitDirective:
5650 return cxstring::createRef("OMPTaskwaitDirective");
5651 case CXCursor_OMPTaskgroupDirective:
5652 return cxstring::createRef("OMPTaskgroupDirective");
5653 case CXCursor_OMPFlushDirective:
5654 return cxstring::createRef("OMPFlushDirective");
5655 case CXCursor_OMPDepobjDirective:
5656 return cxstring::createRef("OMPDepobjDirective");
5657 case CXCursor_OMPScanDirective:
5658 return cxstring::createRef("OMPScanDirective");
5659 case CXCursor_OMPOrderedDirective:
5660 return cxstring::createRef("OMPOrderedDirective");
5661 case CXCursor_OMPAtomicDirective:
5662 return cxstring::createRef("OMPAtomicDirective");
5663 case CXCursor_OMPTargetDirective:
5664 return cxstring::createRef("OMPTargetDirective");
5665 case CXCursor_OMPTargetDataDirective:
5666 return cxstring::createRef("OMPTargetDataDirective");
5667 case CXCursor_OMPTargetEnterDataDirective:
5668 return cxstring::createRef("OMPTargetEnterDataDirective");
5669 case CXCursor_OMPTargetExitDataDirective:
5670 return cxstring::createRef("OMPTargetExitDataDirective");
5671 case CXCursor_OMPTargetParallelDirective:
5672 return cxstring::createRef("OMPTargetParallelDirective");
5673 case CXCursor_OMPTargetParallelForDirective:
5674 return cxstring::createRef("OMPTargetParallelForDirective");
5675 case CXCursor_OMPTargetUpdateDirective:
5676 return cxstring::createRef("OMPTargetUpdateDirective");
5677 case CXCursor_OMPTeamsDirective:
5678 return cxstring::createRef("OMPTeamsDirective");
5679 case CXCursor_OMPCancellationPointDirective:
5680 return cxstring::createRef("OMPCancellationPointDirective");
5681 case CXCursor_OMPCancelDirective:
5682 return cxstring::createRef("OMPCancelDirective");
5683 case CXCursor_OMPTaskLoopDirective:
5684 return cxstring::createRef("OMPTaskLoopDirective");
5685 case CXCursor_OMPTaskLoopSimdDirective:
5686 return cxstring::createRef("OMPTaskLoopSimdDirective");
5687 case CXCursor_OMPMasterTaskLoopDirective:
5688 return cxstring::createRef("OMPMasterTaskLoopDirective");
5689 case CXCursor_OMPMasterTaskLoopSimdDirective:
5690 return cxstring::createRef("OMPMasterTaskLoopSimdDirective");
5691 case CXCursor_OMPParallelMasterTaskLoopDirective:
5692 return cxstring::createRef("OMPParallelMasterTaskLoopDirective");
5693 case CXCursor_OMPParallelMasterTaskLoopSimdDirective:
5694 return cxstring::createRef("OMPParallelMasterTaskLoopSimdDirective");
5695 case CXCursor_OMPDistributeDirective:
5696 return cxstring::createRef("OMPDistributeDirective");
5697 case CXCursor_OMPDistributeParallelForDirective:
5698 return cxstring::createRef("OMPDistributeParallelForDirective");
5699 case CXCursor_OMPDistributeParallelForSimdDirective:
5700 return cxstring::createRef("OMPDistributeParallelForSimdDirective");
5701 case CXCursor_OMPDistributeSimdDirective:
5702 return cxstring::createRef("OMPDistributeSimdDirective");
5703 case CXCursor_OMPTargetParallelForSimdDirective:
5704 return cxstring::createRef("OMPTargetParallelForSimdDirective");
5705 case CXCursor_OMPTargetSimdDirective:
5706 return cxstring::createRef("OMPTargetSimdDirective");
5707 case CXCursor_OMPTeamsDistributeDirective:
5708 return cxstring::createRef("OMPTeamsDistributeDirective");
5709 case CXCursor_OMPTeamsDistributeSimdDirective:
5710 return cxstring::createRef("OMPTeamsDistributeSimdDirective");
5711 case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
5712 return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
5713 case CXCursor_OMPTeamsDistributeParallelForDirective:
5714 return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
5715 case CXCursor_OMPTargetTeamsDirective:
5716 return cxstring::createRef("OMPTargetTeamsDirective");
5717 case CXCursor_OMPTargetTeamsDistributeDirective:
5718 return cxstring::createRef("OMPTargetTeamsDistributeDirective");
5719 case CXCursor_OMPTargetTeamsDistributeParallelForDirective:
5720 return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective");
5721 case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective:
5722 return cxstring::createRef(
5723 "OMPTargetTeamsDistributeParallelForSimdDirective");
5724 case CXCursor_OMPTargetTeamsDistributeSimdDirective:
5725 return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective");
5726 case CXCursor_OMPInteropDirective:
5727 return cxstring::createRef("OMPInteropDirective");
5728 case CXCursor_OMPDispatchDirective:
5729 return cxstring::createRef("OMPDispatchDirective");
5730 case CXCursor_OMPMaskedDirective:
5731 return cxstring::createRef("OMPMaskedDirective");
5732 case CXCursor_OMPGenericLoopDirective:
5733 return cxstring::createRef("OMPGenericLoopDirective");
5734 case CXCursor_OMPTeamsGenericLoopDirective:
5735 return cxstring::createRef("OMPTeamsGenericLoopDirective");
5736 case CXCursor_OMPTargetTeamsGenericLoopDirective:
5737 return cxstring::createRef("OMPTargetTeamsGenericLoopDirective");
5738 case CXCursor_OMPParallelGenericLoopDirective:
5739 return cxstring::createRef("OMPParallelGenericLoopDirective");
5740 case CXCursor_OMPTargetParallelGenericLoopDirective:
5741 return cxstring::createRef("OMPTargetParallelGenericLoopDirective");
5742 case CXCursor_OverloadCandidate:
5743 return cxstring::createRef("OverloadCandidate");
5744 case CXCursor_TypeAliasTemplateDecl:
5745 return cxstring::createRef("TypeAliasTemplateDecl");
5746 case CXCursor_StaticAssert:
5747 return cxstring::createRef("StaticAssert");
5748 case CXCursor_FriendDecl:
5749 return cxstring::createRef("FriendDecl");
5750 case CXCursor_ConvergentAttr:
5751 return cxstring::createRef("attribute(convergent)");
5752 case CXCursor_WarnUnusedAttr:
5753 return cxstring::createRef("attribute(warn_unused)");
5754 case CXCursor_WarnUnusedResultAttr:
5755 return cxstring::createRef("attribute(warn_unused_result)");
5756 case CXCursor_AlignedAttr:
5757 return cxstring::createRef("attribute(aligned)");
5758 }
5759
5760 llvm_unreachable("Unhandled CXCursorKind")::llvm::llvm_unreachable_internal("Unhandled CXCursorKind", "clang/tools/libclang/CIndex.cpp"
, 5760)
;
5761}
5762
5763struct GetCursorData {
5764 SourceLocation TokenBeginLoc;
5765 bool PointsAtMacroArgExpansion;
5766 bool VisitedObjCPropertyImplDecl;
5767 SourceLocation VisitedDeclaratorDeclStartLoc;
5768 CXCursor &BestCursor;
5769
5770 GetCursorData(SourceManager &SM, SourceLocation tokenBegin,
5771 CXCursor &outputCursor)
5772 : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
5773 PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
5774 VisitedObjCPropertyImplDecl = false;
5775 }
5776};
5777
5778static enum CXChildVisitResult
5779GetCursorVisitor(CXCursor cursor, CXCursor parent, CXClientData client_data) {
5780 GetCursorData *Data = static_cast<GetCursorData *>(client_data);
5781 CXCursor *BestCursor = &Data->BestCursor;
5782
5783 // If we point inside a macro argument we should provide info of what the
5784 // token is so use the actual cursor, don't replace it with a macro expansion
5785 // cursor.
5786 if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
5787 return CXChildVisit_Recurse;
5788
5789 if (clang_isDeclaration(cursor.kind)) {
5790 // Avoid having the implicit methods override the property decls.
5791 if (const ObjCMethodDecl *MD =
5792 dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
5793 if (MD->isImplicit())
5794 return CXChildVisit_Break;
5795
5796 } else if (const ObjCInterfaceDecl *ID =
5797 dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
5798 // Check that when we have multiple @class references in the same line,
5799 // that later ones do not override the previous ones.
5800 // If we have:
5801 // @class Foo, Bar;
5802 // source ranges for both start at '@', so 'Bar' will end up overriding
5803 // 'Foo' even though the cursor location was at 'Foo'.
5804 if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
5805 BestCursor->kind == CXCursor_ObjCClassRef)
5806 if (const ObjCInterfaceDecl *PrevID =
5807 dyn_cast_or_null<ObjCInterfaceDecl>(
5808 getCursorDecl(*BestCursor))) {
5809 if (PrevID != ID && !PrevID->isThisDeclarationADefinition() &&
5810 !ID->isThisDeclarationADefinition())
5811 return CXChildVisit_Break;
5812 }
5813
5814 } else if (const DeclaratorDecl *DD =
5815 dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
5816 SourceLocation StartLoc = DD->getSourceRange().getBegin();
5817 // Check that when we have multiple declarators in the same line,
5818 // that later ones do not override the previous ones.
5819 // If we have:
5820 // int Foo, Bar;
5821 // source ranges for both start at 'int', so 'Bar' will end up overriding
5822 // 'Foo' even though the cursor location was at 'Foo'.
5823 if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
5824 return CXChildVisit_Break;
5825 Data->VisitedDeclaratorDeclStartLoc = StartLoc;
5826
5827 } else if (const ObjCPropertyImplDecl *PropImp =
5828 dyn_cast_or_null<ObjCPropertyImplDecl>(
5829 getCursorDecl(cursor))) {
5830 (void)PropImp;
5831 // Check that when we have multiple @synthesize in the same line,
5832 // that later ones do not override the previous ones.
5833 // If we have:
5834 // @synthesize Foo, Bar;
5835 // source ranges for both start at '@', so 'Bar' will end up overriding
5836 // 'Foo' even though the cursor location was at 'Foo'.
5837 if (Data->VisitedObjCPropertyImplDecl)
5838 return CXChildVisit_Break;
5839 Data->VisitedObjCPropertyImplDecl = true;
5840 }
5841 }
5842
5843 if (clang_isExpression(cursor.kind) &&
5844 clang_isDeclaration(BestCursor->kind)) {
5845 if (const Decl *D = getCursorDecl(*BestCursor)) {
5846 // Avoid having the cursor of an expression replace the declaration cursor
5847 // when the expression source range overlaps the declaration range.
5848 // This can happen for C++ constructor expressions whose range generally
5849 // include the variable declaration, e.g.:
5850 // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl
5851 // cursor.
5852 if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
5853 D->getLocation() == Data->TokenBeginLoc)
5854 return CXChildVisit_Break;
5855 }
5856 }
5857
5858 // If our current best cursor is the construction of a temporary object,
5859 // don't replace that cursor with a type reference, because we want
5860 // clang_getCursor() to point at the constructor.
5861 if (clang_isExpression(BestCursor->kind) &&
5862 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
5863 cursor.kind == CXCursor_TypeRef) {
5864 // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
5865 // as having the actual point on the type reference.
5866 *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
5867 return CXChildVisit_Recurse;
5868 }
5869
5870 // If we already have an Objective-C superclass reference, don't
5871 // update it further.
5872 if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
5873 return CXChildVisit_Break;
5874
5875 *BestCursor = cursor;
5876 return CXChildVisit_Recurse;
5877}
5878
5879CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
5880 if (isNotUsableTU(TU)) {
5881 LOG_BAD_TU(TU)do { if (clang::cxindex::LogRef Log = clang::cxindex::Logger::
make(__func__)) { *Log << "called with a bad TU: " <<
TU; } } while(false)
;
5882 return clang_getNullCursor();
5883 }
5884
5885 ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
5886 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
5887
5888 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
5889 CXCursor Result = cxcursor::getCursor(TU, SLoc);
5890
5891 LOG_FUNC_SECTIONif (clang::cxindex::LogRef Log = clang::cxindex::Logger::make
(__func__))
{
5892 CXFile SearchFile;
5893 unsigned SearchLine, SearchColumn;
5894 CXFile ResultFile;
5895 unsigned ResultLine, ResultColumn;
5896 CXString SearchFileName, ResultFileName, KindSpelling, USR;
5897 const char *IsDef = clang_isCursorDefinition(Result) ? " (Definition)" : "";
5898 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
5899
5900 clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
5901 nullptr);
5902 clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine, &ResultColumn,
5903 nullptr);
5904 SearchFileName = clang_getFileName(SearchFile);
5905 ResultFileName = clang_getFileName(ResultFile);
5906 KindSpelling = clang_getCursorKindSpelling(Result.kind);
5907 USR = clang_getCursorUSR(Result);
5908 *Log << llvm::format("(%s:%d:%d) = %s", clang_getCString(SearchFileName),
5909 SearchLine, SearchColumn,
5910 clang_getCString(KindSpelling))
5911 << llvm::format("(%s:%d:%d):%s%s", clang_getCString(ResultFileName),
5912 ResultLine, ResultColumn, clang_getCString(USR),
5913 IsDef);
5914 clang_disposeString(SearchFileName);
5915 clang_disposeString(ResultFileName);
5916 clang_disposeString(KindSpelling);
5917 clang_disposeString(USR);
5918
5919 CXCursor Definition = clang_getCursorDefinition(Result);
5920 if (!clang_equalCursors(Definition, clang_getNullCursor())) {
5921 CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
5922 CXString DefinitionKindSpelling =
5923 clang_getCursorKindSpelling(Definition.kind);
5924 CXFile DefinitionFile;
5925 unsigned DefinitionLine, DefinitionColumn;
5926 clang_getFileLocation(DefinitionLoc, &DefinitionFile, &DefinitionLine,
5927 &DefinitionColumn, nullptr);
5928 CXString DefinitionFileName = clang_getFileName(DefinitionFile);
5929 *Log << llvm::format(" -> %s(%s:%d:%d)",
5930 clang_getCString(DefinitionKindSpelling),
5931 clang_getCString(DefinitionFileName), DefinitionLine,
5932 DefinitionColumn);
5933 clang_disposeString(DefinitionFileName);
5934 clang_disposeString(DefinitionKindSpelling);
5935 }
5936 }
5937
5938 return Result;
5939}
5940
5941CXCursor clang_getNullCursor(void) {
5942 return MakeCXCursorInvalid(CXCursor_InvalidFile);
5943}
5944
5945unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
5946 // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
5947 // can't set consistently. For example, when visiting a DeclStmt we will set
5948 // it but we don't set it on the result of clang_getCursorDefinition for
5949 // a reference of the same declaration.
5950 // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
5951 // when visiting a DeclStmt currently, the AST should be enhanced to be able
5952 // to provide that kind of info.
5953 if (clang_isDeclaration(X.kind))
5954 X.data[1] = nullptr;
5955 if (clang_isDeclaration(Y.kind))
5956 Y.data[1] = nullptr;
5957
5958 return X == Y;
5959}
5960
5961unsigned clang_hashCursor(CXCursor C) {
5962 unsigned Index = 0;
5963 if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
5964 Index = 1;
5965
5966 return llvm::DenseMapInfo<std::pair<unsigned, const void *>>::getHashValue(
5967 std::make_pair(C.kind, C.data[Index]));
5968}
5969
5970unsigned clang_isInvalid(enum CXCursorKind K) {
5971 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
5972}
5973
5974unsigned clang_isDeclaration(enum CXCursorKind K) {
5975 return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
5976 (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
5977}
5978
5979unsigned clang_isInvalidDeclaration(CXCursor C) {
5980 if (clang_isDeclaration(C.kind)) {
5981 if (const Decl *D = getCursorDecl(C))
5982 return D->isInvalidDecl();
5983 }
5984
5985 return 0;
5986}
5987
5988unsigned clang_isReference(enum CXCursorKind K) {
5989 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
5990}
5991
5992unsigned clang_isExpression(enum CXCursorKind K) {
5993 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
5994}
5995
5996unsigned clang_isStatement(enum CXCursorKind K) {
5997 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
5998}
5999
6000unsigned clang_isAttribute(enum CXCursorKind K) {
6001 return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
6002}
6003
6004unsigned clang_isTranslationUnit(enum CXCursorKind K) {
6005 return K == CXCursor_TranslationUnit;
6006}
6007
6008unsigned clang_isPreprocessing(enum CXCursorKind K) {
6009 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
6010}
6011
6012unsigned clang_isUnexposed(enum CXCursorKind K) {
6013 switch (K) {
6014 case CXCursor_UnexposedDecl:
6015 case CXCursor_UnexposedExpr:
6016 case CXCursor_UnexposedStmt:
6017 case CXCursor_UnexposedAttr:
6018 return true;
6019 default:
6020 return false;
6021 }
6022}
6023
6024CXCursorKind clang_getCursorKind(CXCursor C) { return C.kind; }
6025
6026CXSourceLocation clang_getCursorLocation(CXCursor C) {
6027 if (clang_isReference(C.kind)) {
6028 switch (C.kind) {
6029 case CXCursor_ObjCSuperClassRef: {
6030 std::pair<const ObjCInterfaceDecl *, SourceLocation> P =
6031 getCursorObjCSuperClassRef(C);
6032 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
6033 }
6034
6035 case CXCursor_ObjCProtocolRef: {
6036 std::pair<const ObjCProtocolDecl *, SourceLocation> P =
6037 getCursorObjCProtocolRef(C);
6038 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
6039 }
6040
6041 case CXCursor_ObjCClassRef: {
6042 std::pair<const ObjCInterfaceDecl *, SourceLocation> P =
6043 getCursorObjCClassRef(C);
6044 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
6045 }
6046
6047 case CXCursor_TypeRef: {
6048 std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
6049