Bug Summary

File:tools/clang/tools/libclang/CIndex.cpp
Warning:line 8469, column 42
Dereference of null pointer

Annotated Source Code

Press '?' to see keyboard shortcuts

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