Bug Summary

File:tools/clang/tools/libclang/CIndex.cpp
Warning:line 1399, column 7
Null pointer passed as an argument to a 'nonnull' parameter

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~svn325874/build-llvm/tools/clang/tools/libclang -I /build/llvm-toolchain-snapshot-7~svn325874/tools/clang/tools/libclang -I /build/llvm-toolchain-snapshot-7~svn325874/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn325874/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn325874/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn325874/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/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/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~svn325874/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-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-02-23-163436-368-1 -x c++ /build/llvm-toolchain-snapshot-7~svn325874/tools/clang/tools/libclang/CIndex.cpp

/build/llvm-toolchain-snapshot-7~svn325874/tools/clang/tools/libclang/CIndex.cpp

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