Coverage Report

Created: 2021-01-23 06:44

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/tools/libclang/CIndex.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// This file implements the main API hooks in the Clang-C Source Indexing
10
// library.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "CIndexDiagnostic.h"
15
#include "CIndexer.h"
16
#include "CLog.h"
17
#include "CXCursor.h"
18
#include "CXSourceLocation.h"
19
#include "CXString.h"
20
#include "CXTranslationUnit.h"
21
#include "CXType.h"
22
#include "CursorVisitor.h"
23
#include "clang-c/FatalErrorHandler.h"
24
#include "clang/AST/Attr.h"
25
#include "clang/AST/DeclObjCCommon.h"
26
#include "clang/AST/Mangle.h"
27
#include "clang/AST/OpenMPClause.h"
28
#include "clang/AST/StmtVisitor.h"
29
#include "clang/Basic/Diagnostic.h"
30
#include "clang/Basic/DiagnosticCategories.h"
31
#include "clang/Basic/DiagnosticIDs.h"
32
#include "clang/Basic/Stack.h"
33
#include "clang/Basic/TargetInfo.h"
34
#include "clang/Basic/Version.h"
35
#include "clang/Frontend/ASTUnit.h"
36
#include "clang/Frontend/CompilerInstance.h"
37
#include "clang/Index/CommentToXML.h"
38
#include "clang/Lex/HeaderSearch.h"
39
#include "clang/Lex/Lexer.h"
40
#include "clang/Lex/PreprocessingRecord.h"
41
#include "clang/Lex/Preprocessor.h"
42
#include "llvm/ADT/Optional.h"
43
#include "llvm/ADT/STLExtras.h"
44
#include "llvm/ADT/StringSwitch.h"
45
#include "llvm/Config/llvm-config.h"
46
#include "llvm/Support/Compiler.h"
47
#include "llvm/Support/CrashRecoveryContext.h"
48
#include "llvm/Support/Format.h"
49
#include "llvm/Support/ManagedStatic.h"
50
#include "llvm/Support/MemoryBuffer.h"
51
#include "llvm/Support/Program.h"
52
#include "llvm/Support/SaveAndRestore.h"
53
#include "llvm/Support/Signals.h"
54
#include "llvm/Support/TargetSelect.h"
55
#include "llvm/Support/Threading.h"
56
#include "llvm/Support/Timer.h"
57
#include "llvm/Support/raw_ostream.h"
58
#include <mutex>
59
60
#if LLVM_ENABLE_THREADS != 0 && defined(__APPLE__)
61
#define USE_DARWIN_THREADS
62
#endif
63
64
#ifdef USE_DARWIN_THREADS
65
#include <pthread.h>
66
#endif
67
68
using namespace clang;
69
using namespace clang::cxcursor;
70
using namespace clang::cxtu;
71
using namespace clang::cxindex;
72
73
CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx,
74
1.05k
                                              std::unique_ptr<ASTUnit> AU) {
75
1.05k
  if (!AU)
76
2
    return nullptr;
77
1.04k
  assert(CIdx);
78
1.04k
  CXTranslationUnit D = new CXTranslationUnitImpl();
79
1.04k
  D->CIdx = CIdx;
80
1.04k
  D->TheASTUnit = AU.release();
81
1.04k
  D->StringPool = new cxstring::CXStringPool();
82
1.04k
  D->Diagnostics = nullptr;
83
1.04k
  D->OverridenCursorsPool = createOverridenCXCursorsPool();
84
1.04k
  D->CommentToXML = nullptr;
85
1.04k
  D->ParsingOptions = 0;
86
1.04k
  D->Arguments = {};
87
1.04k
  return D;
88
1.04k
}
89
90
1.02k
bool cxtu::isASTReadError(ASTUnit *AU) {
91
1.02k
  for (ASTUnit::stored_diag_iterator D = AU->stored_diag_begin(),
92
1.02k
                                     DEnd = AU->stored_diag_end();
93
6.07k
       D != DEnd; 
++D5.05k
) {
94
5.05k
    if (D->getLevel() >= DiagnosticsEngine::Error &&
95
1.69k
        DiagnosticIDs::getCategoryNumberForDiag(D->getID()) ==
96
1.69k
            diag::DiagCat_AST_Deserialization_Issue)
97
2
      return true;
98
5.05k
  }
99
1.01k
  return false;
100
1.02k
}
101
102
39
cxtu::CXTUOwner::~CXTUOwner() {
103
39
  if (TU)
104
39
    clang_disposeTranslationUnit(TU);
105
39
}
106
107
/// Compare two source ranges to determine their relative position in
108
/// the translation unit.
109
static RangeComparisonResult RangeCompare(SourceManager &SM, SourceRange R1,
110
36.3k
                                          SourceRange R2) {
111
36.3k
  assert(R1.isValid() && "First range is invalid?");
112
36.3k
  assert(R2.isValid() && "Second range is invalid?");
113
36.3k
  if (R1.getEnd() != R2.getBegin() &&
114
35.8k
      SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
115
16.5k
    return RangeBefore;
116
19.7k
  if (R2.getEnd() != R1.getBegin() &&
117
19.3k
      SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
118
3.29k
    return RangeAfter;
119
16.4k
  return RangeOverlap;
120
16.4k
}
121
122
/// Determine if a source location falls within, before, or after a
123
///   a given source range.
124
static RangeComparisonResult LocationCompare(SourceManager &SM,
125
23.6M
                                             SourceLocation L, SourceRange R) {
126
23.6M
  assert(R.isValid() && "First range is invalid?");
127
23.6M
  assert(L.isValid() && "Second range is invalid?");
128
23.6M
  if (L == R.getBegin() || 
L == R.getEnd()23.6M
)
129
23.9k
    return RangeOverlap;
130
23.6M
  if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
131
23.6M
    return RangeBefore;
132
24.3k
  if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
133
18.2k
    return RangeAfter;
134
6.15k
  return RangeOverlap;
135
6.15k
}
136
137
/// Translate a Clang source range into a CIndex source range.
138
///
139
/// Clang internally represents ranges where the end location points to the
140
/// start of the token at the end. However, for external clients it is more
141
/// useful to have a CXSourceRange be a proper half-open interval. This routine
142
/// does the appropriate translation.
143
CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
144
                                          const LangOptions &LangOpts,
145
335k
                                          const CharSourceRange &R) {
146
  // We want the last character in this location, so we will adjust the
147
  // location accordingly.
148
335k
  SourceLocation EndLoc = R.getEnd();
149
335k
  bool IsTokenRange = R.isTokenRange();
150
335k
  if (EndLoc.isValid() && 
EndLoc.isMacroID()335k
&&
151
928
      !SM.isMacroArgExpansion(EndLoc)) {
152
397
    CharSourceRange Expansion = SM.getExpansionRange(EndLoc);
153
397
    EndLoc = Expansion.getEnd();
154
397
    IsTokenRange = Expansion.isTokenRange();
155
397
  }
156
335k
  if (IsTokenRange && 
EndLoc.isValid()335k
) {
157
335k
    unsigned Length =
158
335k
        Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc), SM, LangOpts);
159
335k
    EndLoc = EndLoc.getLocWithOffset(Length);
160
335k
  }
161
162
335k
  CXSourceRange Result = {
163
335k
      {&SM, &LangOpts}, R.getBegin().getRawEncoding(), EndLoc.getRawEncoding()};
164
335k
  return Result;
165
335k
}
166
167
4
CharSourceRange cxloc::translateCXRangeToCharRange(CXSourceRange R) {
168
4
  return CharSourceRange::getCharRange(
169
4
      SourceLocation::getFromRawEncoding(R.begin_int_data),
170
4
      SourceLocation::getFromRawEncoding(R.end_int_data));
171
4
}
172
173
//===----------------------------------------------------------------------===//
174
// Cursor visitor.
175
//===----------------------------------------------------------------------===//
176
177
static SourceRange getRawCursorExtent(CXCursor C);
178
static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
179
180
25.5k
RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
181
25.5k
  return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
182
25.5k
}
183
184
/// Visit the given cursor and, if requested by the visitor,
185
/// its children.
186
///
187
/// \param Cursor the cursor to visit.
188
///
189
/// \param CheckedRegionOfInterest if true, then the caller already checked
190
/// that this cursor is within the region of interest.
191
///
192
/// \returns true if the visitation should be aborted, false if it
193
/// should continue.
194
84.5k
bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
195
84.5k
  if (clang_isInvalid(Cursor.kind))
196
1
    return false;
197
198
84.5k
  if (clang_isDeclaration(Cursor.kind)) {
199
9.76k
    const Decl *D = getCursorDecl(Cursor);
200
9.76k
    if (!D) {
201
0
      assert(0 && "Invalid declaration cursor");
202
0
      return true; // abort.
203
0
    }
204
205
    // Ignore implicit declarations, unless it's an objc method because
206
    // currently we should report implicit methods for properties when indexing.
207
9.76k
    if (D->isImplicit() && 
!isa<ObjCMethodDecl>(D)2.04k
)
208
1.92k
      return false;
209
82.6k
  }
210
211
  // If we have a range of interest, and this cursor doesn't intersect with it,
212
  // we're done.
213
82.6k
  if (RegionOfInterest.isValid() && 
!CheckedRegionOfInterest11.3k
) {
214
9.26k
    SourceRange Range = getRawCursorExtent(Cursor);
215
9.26k
    if (Range.isInvalid() || 
CompareRegionOfInterest(Range)9.26k
)
216
7.15k
      return false;
217
75.4k
  }
218
219
75.4k
  switch (Visitor(Cursor, Parent, ClientData)) {
220
18
  case CXChildVisit_Break:
221
18
    return true;
222
223
6.31k
  case CXChildVisit_Continue:
224
6.31k
    return false;
225
226
69.1k
  case CXChildVisit_Recurse: {
227
69.1k
    bool ret = VisitChildren(Cursor);
228
69.1k
    if (PostChildrenVisitor)
229
1.20k
      if (PostChildrenVisitor(Cursor, ClientData))
230
0
        return true;
231
69.1k
    return ret;
232
69.1k
  }
233
0
  }
234
235
0
  llvm_unreachable("Invalid CXChildVisitResult!");
236
0
}
237
238
static bool visitPreprocessedEntitiesInRange(SourceRange R,
239
                                             PreprocessingRecord &PPRec,
240
9.57k
                                             CursorVisitor &Visitor) {
241
9.57k
  SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
242
9.57k
  FileID FID;
243
244
9.57k
  if (!Visitor.shouldVisitIncludedEntities()) {
245
    // If the begin/end of the range lie in the same FileID, do the optimization
246
    // where we skip preprocessed entities that do not come from the same
247
    // FileID.
248
9.57k
    FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
249
9.57k
    if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
250
0
      FID = FileID();
251
9.57k
  }
252
253
9.57k
  const auto &Entities = PPRec.getPreprocessedEntitiesInRange(R);
254
9.57k
  return Visitor.visitPreprocessedEntities(Entities.begin(), Entities.end(),
255
9.57k
                                           PPRec, FID);
256
9.57k
}
257
258
9.53k
bool CursorVisitor::visitFileRegion() {
259
9.53k
  if (RegionOfInterest.isInvalid())
260
0
    return false;
261
262
9.53k
  ASTUnit *Unit = cxtu::getASTUnit(TU);
263
9.53k
  SourceManager &SM = Unit->getSourceManager();
264
265
9.53k
  std::pair<FileID, unsigned> Begin = SM.getDecomposedLoc(
266
9.53k
                                  SM.getFileLoc(RegionOfInterest.getBegin())),
267
9.53k
                              End = SM.getDecomposedLoc(
268
9.53k
                                  SM.getFileLoc(RegionOfInterest.getEnd()));
269
270
9.53k
  if (End.first != Begin.first) {
271
    // If the end does not reside in the same file, try to recover by
272
    // picking the end of the file of begin location.
273
0
    End.first = Begin.first;
274
0
    End.second = SM.getFileIDSize(Begin.first);
275
0
  }
276
277
9.53k
  assert(Begin.first == End.first);
278
9.53k
  if (Begin.second > End.second)
279
0
    return false;
280
281
9.53k
  FileID File = Begin.first;
282
9.53k
  unsigned Offset = Begin.second;
283
9.53k
  unsigned Length = End.second - Begin.second;
284
285
9.53k
  if (!VisitDeclsOnly && 
!VisitPreprocessorLast9.50k
)
286
0
    if (visitPreprocessedEntitiesInRegion())
287
0
      return true; // visitation break.
288
289
9.53k
  if (visitDeclsFromFileRegion(File, Offset, Length))
290
13
    return true; // visitation break.
291
292
9.51k
  if (!VisitDeclsOnly && 
VisitPreprocessorLast9.49k
)
293
9.49k
    return visitPreprocessedEntitiesInRegion();
294
295
24
  return false;
296
24
}
297
298
10.7k
static bool isInLexicalContext(Decl *D, DeclContext *DC) {
299
10.7k
  if (!DC)
300
9.63k
    return false;
301
302
2.26k
  
for (DeclContext *DeclDC = D->getLexicalDeclContext(); 1.15k
DeclDC;
303
1.15k
       
DeclDC = DeclDC->getLexicalParent()1.11k
) {
304
1.15k
    if (DeclDC == DC)
305
40
      return true;
306
1.15k
  }
307
1.11k
  return false;
308
1.15k
}
309
310
bool CursorVisitor::visitDeclsFromFileRegion(FileID File, unsigned Offset,
311
9.53k
                                             unsigned Length) {
312
9.53k
  ASTUnit *Unit = cxtu::getASTUnit(TU);
313
9.53k
  SourceManager &SM = Unit->getSourceManager();
314
9.53k
  SourceRange Range = RegionOfInterest;
315
316
9.53k
  SmallVector<Decl *, 16> Decls;
317
9.53k
  Unit->findFileRegionDecls(File, Offset, Length, Decls);
318
319
  // If we didn't find any file level decls for the file, try looking at the
320
  // file that it was included from.
321
9.54k
  while (Decls.empty() || 
Decls.front()->isTopLevelDeclInObjCContainer()9.51k
) {
322
29
    bool Invalid = false;
323
29
    const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
324
29
    if (Invalid)
325
0
      return false;
326
327
29
    SourceLocation Outer;
328
29
    if (SLEntry.isFile())
329
29
      Outer = SLEntry.getFile().getIncludeLoc();
330
0
    else
331
0
      Outer = SLEntry.getExpansion().getExpansionLocStart();
332
29
    if (Outer.isInvalid())
333
14
      return false;
334
335
15
    std::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
336
15
    Length = 0;
337
15
    Unit->findFileRegionDecls(File, Offset, Length, Decls);
338
15
  }
339
340
9.51k
  assert(!Decls.empty());
341
342
9.51k
  bool VisitedAtLeastOnce = false;
343
9.51k
  DeclContext *CurDC = nullptr;
344
9.51k
  SmallVectorImpl<Decl *>::iterator DIt = Decls.begin();
345
18.4k
  for (SmallVectorImpl<Decl *>::iterator DE = Decls.end(); DIt != DE; 
++DIt8.95k
) {
346
10.7k
    Decl *D = *DIt;
347
10.7k
    if (D->getSourceRange().isInvalid())
348
0
      continue;
349
350
10.7k
    if (isInLexicalContext(D, CurDC))
351
40
      continue;
352
353
10.7k
    CurDC = dyn_cast<DeclContext>(D);
354
355
10.7k
    if (TagDecl *TD = dyn_cast<TagDecl>(D))
356
299
      if (!TD->isFreeStanding())
357
42
        continue;
358
359
10.7k
    RangeComparisonResult CompRes =
360
10.7k
        RangeCompare(SM, D->getSourceRange(), Range);
361
10.7k
    if (CompRes == RangeBefore)
362
7.50k
      continue;
363
3.20k
    if (CompRes == RangeAfter)
364
1.82k
      break;
365
366
1.38k
    assert(CompRes == RangeOverlap);
367
1.38k
    VisitedAtLeastOnce = true;
368
369
1.38k
    if (isa<ObjCContainerDecl>(D)) {
370
503
      FileDI_current = &DIt;
371
503
      FileDE_current = DE;
372
879
    } else {
373
879
      FileDI_current = nullptr;
374
879
    }
375
376
1.38k
    if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
377
13
      return true; // visitation break.
378
1.38k
  }
379
380
9.50k
  if (VisitedAtLeastOnce)
381
1.11k
    return false;
382
383
  // No Decls overlapped with the range. Move up the lexical context until there
384
  // is a context that contains the range or we reach the translation unit
385
  // level.
386
8.39k
  DeclContext *DC = DIt == Decls.begin()
387
1.08k
                        ? (*DIt)->getLexicalDeclContext()
388
7.30k
                        : (*(DIt - 1))->getLexicalDeclContext();
389
390
8.39k
  while (DC && !DC->isTranslationUnit()) {
391
0
    Decl *D = cast<Decl>(DC);
392
0
    SourceRange CurDeclRange = D->getSourceRange();
393
0
    if (CurDeclRange.isInvalid())
394
0
      break;
395
396
0
    if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
397
0
      if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
398
0
        return true; // visitation break.
399
0
    }
400
401
0
    DC = D->getLexicalDeclContext();
402
0
  }
403
404
8.39k
  return false;
405
8.39k
}
406
407
9.76k
bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
408
9.76k
  if (!AU->getPreprocessor().getPreprocessingRecord())
409
0
    return false;
410
411
9.76k
  PreprocessingRecord &PPRec = *AU->getPreprocessor().getPreprocessingRecord();
412
9.76k
  SourceManager &SM = AU->getSourceManager();
413
414
9.76k
  if (RegionOfInterest.isValid()) {
415
9.57k
    SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
416
9.57k
    SourceLocation B = MappedRange.getBegin();
417
9.57k
    SourceLocation E = MappedRange.getEnd();
418
419
9.57k
    if (AU->isInPreambleFileID(B)) {
420
22
      if (SM.isLoadedSourceLocation(E))
421
15
        return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec,
422
15
                                                *this);
423
424
      // Beginning of range lies in the preamble but it also extends beyond
425
      // it into the main file. Split the range into 2 parts, one covering
426
      // the preamble and another covering the main file. This allows subsequent
427
      // calls to visitPreprocessedEntitiesInRange to accept a source range that
428
      // lies in the same FileID, allowing it to skip preprocessed entities that
429
      // do not come from the same FileID.
430
7
      bool breaked = visitPreprocessedEntitiesInRange(
431
7
          SourceRange(B, AU->getEndOfPreambleFileID()), PPRec, *this);
432
7
      if (breaked)
433
0
        return true;
434
7
      return visitPreprocessedEntitiesInRange(
435
7
          SourceRange(AU->getStartOfMainFileID(), E), PPRec, *this);
436
7
    }
437
438
9.55k
    return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
439
9.55k
  }
440
441
193
  bool OnlyLocalDecls = !AU->isMainFileAST() && 
AU->getOnlyLocalDecls()174
;
442
443
193
  if (OnlyLocalDecls)
444
42
    return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
445
42
                                     PPRec);
446
447
151
  return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
448
151
}
449
450
template <typename InputIterator>
451
bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
452
                                              InputIterator Last,
453
                                              PreprocessingRecord &PPRec,
454
9.77k
                                              FileID FID) {
455
83.8k
  for (; First != Last; 
++First74.1k
) {
456
74.1k
    if (!FID.isInvalid() && 
!PPRec.isEntityInFileID(First, FID)9.42k
)
457
3.46k
      continue;
458
459
70.6k
    PreprocessedEntity *PPE = *First;
460
70.6k
    if (!PPE)
461
0
      continue;
462
463
70.6k
    if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
464
5.81k
      if (Visit(MakeMacroExpansionCursor(ME, TU)))
465
1
        return true;
466
467
5.81k
      continue;
468
5.81k
    }
469
470
64.8k
    if (MacroDefinitionRecord *MD = dyn_cast<MacroDefinitionRecord>(PPE)) {
471
64.5k
      if (Visit(MakeMacroDefinitionCursor(MD, TU)))
472
0
        return true;
473
474
64.5k
      continue;
475
64.5k
    }
476
477
309
    if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
478
309
      if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
479
0
        return true;
480
481
309
      continue;
482
309
    }
483
309
  }
484
485
9.77k
  return false;
486
9.77k
}
487
488
/// Visit the children of the given cursor.
489
///
490
/// \returns true if the visitation should be aborted, false if it
491
/// should continue.
492
69.3k
bool CursorVisitor::VisitChildren(CXCursor Cursor) {
493
69.3k
  if (clang_isReference(Cursor.kind) &&
494
2.01k
      Cursor.kind != CXCursor_CXXBaseSpecifier) {
495
    // By definition, references have no children.
496
1.89k
    return false;
497
1.89k
  }
498
499
  // Set the Parent field to Cursor, then back to its old value once we're
500
  // done.
501
67.4k
  SetParentRAII SetParent(Parent, StmtParent, Cursor);
502
503
67.4k
  if (clang_isDeclaration(Cursor.kind)) {
504
7.09k
    Decl *D = const_cast<Decl *>(getCursorDecl(Cursor));
505
7.09k
    if (!D)
506
0
      return false;
507
508
7.09k
    return VisitAttributes(D) || Visit(D);
509
7.09k
  }
510
511
60.3k
  if (clang_isStatement(Cursor.kind)) {
512
762
    if (const Stmt *S = getCursorStmt(Cursor))
513
762
      return Visit(S);
514
515
0
    return false;
516
0
  }
517
518
59.5k
  if (clang_isExpression(Cursor.kind)) {
519
343
    if (const Expr *E = getCursorExpr(Cursor))
520
343
      return Visit(E);
521
522
0
    return false;
523
0
  }
524
525
59.2k
  if (clang_isTranslationUnit(Cursor.kind)) {
526
195
    CXTranslationUnit TU = getCursorTU(Cursor);
527
195
    ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
528
529
195
    int VisitOrder[2] = {VisitPreprocessorLast, !VisitPreprocessorLast};
530
581
    for (unsigned I = 0; I != 2; 
++I386
) {
531
390
      if (VisitOrder[I]) {
532
195
        if (!CXXUnit->isMainFileAST() && 
CXXUnit->getOnlyLocalDecls()176
&&
533
44
            RegionOfInterest.isInvalid()) {
534
44
          for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
535
44
                                           TLEnd = CXXUnit->top_level_end();
536
329
               TL != TLEnd; 
++TL285
) {
537
285
            const Optional<bool> V = handleDeclForVisitation(*TL);
538
285
            if (!V.hasValue())
539
285
              continue;
540
0
            return V.getValue();
541
0
          }
542
151
        } else if (VisitDeclContext(
543
151
                       CXXUnit->getASTContext().getTranslationUnitDecl()))
544
4
          return true;
545
191
        continue;
546
191
      }
547
548
      // Walk the preprocessing record.
549
195
      if (CXXUnit->getPreprocessor().getPreprocessingRecord())
550
193
        visitPreprocessedEntitiesInRegion();
551
195
    }
552
553
191
    return false;
554
59.0k
  }
555
556
59.0k
  if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
557
121
    if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
558
121
      if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
559
121
        return Visit(BaseTSInfo->getTypeLoc());
560
121
      }
561
58.9k
    }
562
121
  }
563
564
58.9k
  if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
565
3
    const IBOutletCollectionAttr *A =
566
3
        cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
567
3
    if (const ObjCObjectType *ObjT = A->getInterface()->getAs<ObjCObjectType>())
568
2
      return Visit(cxcursor::MakeCursorObjCClassRef(
569
2
          ObjT->getInterface(),
570
2
          A->getInterfaceLoc()->getTypeLoc().getBeginLoc(), TU));
571
58.9k
  }
572
573
  // If pointing inside a macro definition, check if the token is an identifier
574
  // that was ever defined as a macro. In such a case, create a "pseudo" macro
575
  // expansion cursor for that token.
576
58.9k
  SourceLocation BeginLoc = RegionOfInterest.getBegin();
577
58.9k
  if (Cursor.kind == CXCursor_MacroDefinition &&
578
58.3k
      BeginLoc == RegionOfInterest.getEnd()) {
579
58.3k
    SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc);
580
58.3k
    const MacroInfo *MI =
581
58.3k
        getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU);
582
58.3k
    if (MacroDefinitionRecord *MacroDef =
583
12
            checkForMacroInMacroDefinition(MI, Loc, TU))
584
12
      return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU));
585
58.9k
  }
586
587
  // Nothing to visit at the moment.
588
58.9k
  return false;
589
58.9k
}
590
591
8
bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
592
8
  if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
593
8
    if (Visit(TSInfo->getTypeLoc()))
594
0
      return true;
595
596
8
  if (Stmt *Body = B->getBody())
597
8
    return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
598
599
0
  return false;
600
0
}
601
602
7.48k
Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
603
7.48k
  if (RegionOfInterest.isValid()) {
604
2.39k
    SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
605
2.39k
    if (Range.isInvalid())
606
8
      return None;
607
608
2.39k
    switch (CompareRegionOfInterest(Range)) {
609
1.29k
    case RangeBefore:
610
      // This declaration comes before the region of interest; skip it.
611
1.29k
      return None;
612
613
297
    case RangeAfter:
614
      // This declaration comes after the region of interest; we're done.
615
297
      return false;
616
617
795
    case RangeOverlap:
618
      // This declaration overlaps the region of interest; visit it.
619
795
      break;
620
5.88k
    }
621
5.88k
  }
622
5.88k
  return true;
623
5.88k
}
624
625
1.68k
bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
626
1.68k
  DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
627
628
  // FIXME: Eventually remove.  This part of a hack to support proper
629
  // iteration over all Decls contained lexically within an ObjC container.
630
1.68k
  SaveAndRestore<DeclContext::decl_iterator *> DI_saved(DI_current, &I);
631
1.68k
  SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
632
633
8.55k
  for (; I != E; 
++I6.87k
) {
634
7.15k
    Decl *D = *I;
635
7.15k
    if (D->getLexicalDeclContext() != DC)
636
0
      continue;
637
    // Filter out synthesized property accessor redeclarations.
638
7.15k
    if (isa<ObjCImplDecl>(DC))
639
173
      if (auto *OMD = dyn_cast<ObjCMethodDecl>(D))
640
110
        if (OMD->isSynthesizedAccessorStub())
641
41
          continue;
642
7.11k
    const Optional<bool> V = handleDeclForVisitation(D);
643
7.11k
    if (!V.hasValue())
644
6.82k
      continue;
645
284
    return V.getValue();
646
284
  }
647
1.39k
  return false;
648
1.68k
}
649
650
7.39k
Optional<bool> CursorVisitor::handleDeclForVisitation(const Decl *D) {
651
7.39k
  CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
652
653
  // Ignore synthesized ivars here, otherwise if we have something like:
654
  //   @synthesize prop = _prop;
655
  // and '_prop' is not declared, we will encounter a '_prop' ivar before
656
  // encountering the 'prop' synthesize declaration and we will think that
657
  // we passed the region-of-interest.
658
7.39k
  if (auto *ivarD = dyn_cast<ObjCIvarDecl>(D)) {
659
127
    if (ivarD->getSynthesize())
660
18
      return None;
661
7.38k
  }
662
663
  // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
664
  // declarations is a mismatch with the compiler semantics.
665
7.38k
  if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
666
159
    auto *ID = cast<ObjCInterfaceDecl>(D);
667
159
    if (!ID->isThisDeclarationADefinition())
668
42
      Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
669
670
7.22k
  } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
671
16
    auto *PD = cast<ObjCProtocolDecl>(D);
672
16
    if (!PD->isThisDeclarationADefinition())
673
0
      Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
674
16
  }
675
676
7.38k
  const Optional<bool> V = shouldVisitCursor(Cursor);
677
7.38k
  if (!V.hasValue())
678
1.26k
    return None;
679
6.11k
  if (!V.getValue())
680
277
    return false;
681
5.83k
  if (Visit(Cursor, true))
682
7
    return true;
683
5.83k
  return None;
684
5.83k
}
685
686
0
bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
687
0
  llvm_unreachable("Translation units are visited directly by Visit()");
688
0
}
689
690
13
bool CursorVisitor::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
691
13
  if (VisitTemplateParameters(D->getTemplateParameters()))
692
0
    return true;
693
694
13
  return Visit(MakeCXCursor(D->getTemplatedDecl(), TU, RegionOfInterest));
695
13
}
696
697
40
bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
698
40
  if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
699
40
    return Visit(TSInfo->getTypeLoc());
700
701
0
  return false;
702
0
}
703
704
256
bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
705
256
  if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
706
256
    return Visit(TSInfo->getTypeLoc());
707
708
0
  return false;
709
0
}
710
711
800
bool CursorVisitor::VisitTagDecl(TagDecl *D) { return VisitDeclContext(D); }
712
713
bool CursorVisitor::VisitClassTemplateSpecializationDecl(
714
21
    ClassTemplateSpecializationDecl *D) {
715
21
  bool ShouldVisitBody = false;
716
21
  switch (D->getSpecializationKind()) {
717
0
  case TSK_Undeclared:
718
0
  case TSK_ImplicitInstantiation:
719
    // Nothing to visit
720
0
    return false;
721
722
2
  case TSK_ExplicitInstantiationDeclaration:
723
10
  case TSK_ExplicitInstantiationDefinition:
724
10
    break;
725
726
11
  case TSK_ExplicitSpecialization:
727
11
    ShouldVisitBody = true;
728
11
    break;
729
21
  }
730
731
  // Visit the template arguments used in the specialization.
732
21
  if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
733
21
    TypeLoc TL = SpecType->getTypeLoc();
734
21
    if (TemplateSpecializationTypeLoc TSTLoc =
735
21
            TL.getAs<TemplateSpecializationTypeLoc>()) {
736
52
      for (unsigned I = 0, N = TSTLoc.getNumArgs(); I != N; 
++I31
)
737
31
        if (VisitTemplateArgumentLoc(TSTLoc.getArgLoc(I)))
738
0
          return true;
739
21
    }
740
21
  }
741
742
21
  return ShouldVisitBody && 
VisitCXXRecordDecl(D)11
;
743
21
}
744
745
bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
746
8
    ClassTemplatePartialSpecializationDecl *D) {
747
  // FIXME: Visit the "outer" template parameter lists on the TagDecl
748
  // before visiting these template parameters.
749
8
  if (VisitTemplateParameters(D->getTemplateParameters()))
750
0
    return true;
751
752
  // Visit the partial specialization arguments.
753
8
  const ASTTemplateArgumentListInfo *Info = D->getTemplateArgsAsWritten();
754
8
  const TemplateArgumentLoc *TemplateArgs = Info->getTemplateArgs();
755
24
  for (unsigned I = 0, N = Info->NumTemplateArgs; I != N; 
++I16
)
756
16
    if (VisitTemplateArgumentLoc(TemplateArgs[I]))
757
0
      return true;
758
759
8
  return VisitCXXRecordDecl(D);
760
8
}
761
762
305
bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
763
305
  if (const auto *TC = D->getTypeConstraint())
764
0
    if (Visit(MakeCXCursor(TC->getImmediatelyDeclaredConstraint(), StmtParent,
765
0
                           TU, RegionOfInterest)))
766
0
      return true;
767
768
  // Visit the default argument.
769
305
  if (D->hasDefaultArgument() && 
!D->defaultArgumentWasInherited()10
)
770
10
    if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
771
10
      if (Visit(DefArg->getTypeLoc()))
772
0
        return true;
773
774
305
  return false;
775
305
}
776
777
239
bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
778
239
  if (Expr *Init = D->getInitExpr())
779
19
    return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
780
220
  return false;
781
220
}
782
783
2.07k
bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
784
2.07k
  unsigned NumParamList = DD->getNumTemplateParameterLists();
785
2.07k
  for (unsigned i = 0; i < NumParamList; 
i++1
) {
786
1
    TemplateParameterList *Params = DD->getTemplateParameterList(i);
787
1
    if (VisitTemplateParameters(Params))
788
0
      return true;
789
1
  }
790
791
2.07k
  if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
792
2.02k
    if (Visit(TSInfo->getTypeLoc()))
793
0
      return true;
794
795
  // Visit the nested-name-specifier, if present.
796
2.07k
  if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
797
1
    if (VisitNestedNameSpecifierLoc(QualifierLoc))
798
0
      return true;
799
800
2.07k
  return false;
801
2.07k
}
802
803
1.84k
static bool HasTrailingReturnType(FunctionDecl *ND) {
804
1.84k
  const QualType Ty = ND->getType();
805
1.84k
  if (const FunctionType *AFT = Ty->getAs<FunctionType>()) {
806
1.84k
    if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(AFT))
807
1.72k
      return FT->hasTrailingReturn();
808
124
  }
809
810
124
  return false;
811
124
}
812
813
/// Compare two base or member initializers based on their source order.
814
static int CompareCXXCtorInitializers(CXXCtorInitializer *const *X,
815
10
                                      CXXCtorInitializer *const *Y) {
816
10
  return (*X)->getSourceOrder() - (*Y)->getSourceOrder();
817
10
}
818
819
1.84k
bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
820
1.84k
  unsigned NumParamList = ND->getNumTemplateParameterLists();
821
1.86k
  for (unsigned i = 0; i < NumParamList; 
i++20
) {
822
20
    TemplateParameterList *Params = ND->getTemplateParameterList(i);
823
20
    if (VisitTemplateParameters(Params))
824
0
      return true;
825
20
  }
826
827
1.84k
  if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
828
    // Visit the function declaration's syntactic components in the order
829
    // written. This requires a bit of work.
830
1.84k
    TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
831
1.84k
    FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>();
832
1.84k
    const bool HasTrailingRT = HasTrailingReturnType(ND);
833
834
    // If we have a function declared directly (without the use of a typedef),
835
    // visit just the return type. Otherwise, just visit the function's type
836
    // now.
837
1.84k
    if ((FTL && !isa<CXXConversionDecl>(ND) && 
!HasTrailingRT1.84k
&&
838
1.84k
         Visit(FTL.getReturnLoc())) ||
839
1.84k
        (!FTL && 
Visit(TL)0
))
840
0
      return true;
841
842
    // Visit the nested-name-specifier, if present.
843
1.84k
    if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
844
44
      if (VisitNestedNameSpecifierLoc(QualifierLoc))
845
0
        return true;
846
847
    // Visit the declaration name.
848
1.84k
    if (!isa<CXXDestructorDecl>(ND))
849
1.82k
      if (VisitDeclarationNameInfo(ND->getNameInfo()))
850
0
        return true;
851
852
    // FIXME: Visit explicitly-specified template arguments!
853
854
    // Visit the function parameters, if we have a function type.
855
1.84k
    if (FTL && VisitFunctionTypeLoc(FTL, true))
856
0
      return true;
857
858
    // Visit the function's trailing return type.
859
1.84k
    if (FTL && HasTrailingRT && 
Visit(FTL.getReturnLoc())3
)
860
0
      return true;
861
862
    // FIXME: Attributes?
863
1.84k
  }
864
865
1.84k
  if (ND->doesThisDeclarationHaveABody() && 
!ND->isLateTemplateParsed()816
) {
866
816
    if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
867
      // Find the initializers that were written in the source.
868
42
      SmallVector<CXXCtorInitializer *, 4> WrittenInits;
869
41
      for (auto *I : Constructor->inits()) {
870
41
        if (!I->isWritten())
871
5
          continue;
872
873
36
        WrittenInits.push_back(I);
874
36
      }
875
876
      // Sort the initializers in source order
877
42
      llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
878
42
                           &CompareCXXCtorInitializers);
879
880
      // Visit the initializers in source order
881
78
      for (unsigned I = 0, N = WrittenInits.size(); I != N; 
++I36
) {
882
36
        CXXCtorInitializer *Init = WrittenInits[I];
883
36
        if (Init->isAnyMemberInitializer()) {
884
22
          if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
885
22
                                        Init->getMemberLocation(), TU)))
886
0
            return true;
887
14
        } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
888
14
          if (Visit(TInfo->getTypeLoc()))
889
0
            return true;
890
36
        }
891
892
        // Visit the initializer value.
893
36
        if (Expr *Initializer = Init->getInit())
894
36
          if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
895
0
            return true;
896
36
      }
897
42
    }
898
899
816
    if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
900
2
      return true;
901
1.84k
  }
902
903
1.84k
  return false;
904
1.84k
}
905
906
476
bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
907
476
  if (VisitDeclaratorDecl(D))
908
0
    return true;
909
910
476
  if (Expr *BitWidth = D->getBitWidth())
911
20
    return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
912
913
456
  if (Expr *Init = D->getInClassInitializer())
914
5
    return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
915
916
451
  return false;
917
451
}
918
919
1.56k
bool CursorVisitor::VisitVarDecl(VarDecl *D) {
920
1.56k
  if (VisitDeclaratorDecl(D))
921
0
    return true;
922
923
1.56k
  if (Expr *Init = D->getInit())
924
261
    return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
925
926
1.30k
  return false;
927
1.30k
}
928
929
37
bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
930
37
  if (VisitDeclaratorDecl(D))
931
0
    return true;
932
933
37
  if (D->hasDefaultArgument() && 
!D->defaultArgumentWasInherited()2
)
934
2
    if (Expr *DefArg = D->getDefaultArgument())
935
2
      return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
936
937
35
  return false;
938
35
}
939
940
110
bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
941
  // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
942
  // before visiting these template parameters.
943
110
  if (VisitTemplateParameters(D->getTemplateParameters()))
944
0
    return true;
945
946
110
  auto *FD = D->getTemplatedDecl();
947
110
  return VisitAttributes(FD) || VisitFunctionDecl(FD);
948
110
}
949
950
110
bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
951
  // FIXME: Visit the "outer" template parameter lists on the TagDecl
952
  // before visiting these template parameters.
953
110
  if (VisitTemplateParameters(D->getTemplateParameters()))
954
0
    return true;
955
956
110
  auto *CD = D->getTemplatedDecl();
957
110
  return VisitAttributes(CD) || VisitCXXRecordDecl(CD);
958
110
}
959
960
23
bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
961
23
  if (VisitTemplateParameters(D->getTemplateParameters()))
962
0
    return true;
963
964
23
  if (D->hasDefaultArgument() && 
!D->defaultArgumentWasInherited()2
&&
965
2
      VisitTemplateArgumentLoc(D->getDefaultArgument()))
966
0
    return true;
967
968
23
  return false;
969
23
}
970
971
11
bool CursorVisitor::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
972
  // Visit the bound, if it's explicit.
973
11
  if (D->hasExplicitBound()) {
974
8
    if (auto TInfo = D->getTypeSourceInfo()) {
975
8
      if (Visit(TInfo->getTypeLoc()))
976
0
        return true;
977
11
    }
978
8
  }
979
980
11
  return false;
981
11
}
982
983
428
bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
984
428
  if (TypeSourceInfo *TSInfo = ND->getReturnTypeSourceInfo())
985
266
    if (Visit(TSInfo->getTypeLoc()))
986
0
      return true;
987
988
428
  for (const auto *P : ND->parameters()) {
989
171
    if (Visit(MakeCXCursor(P, TU, RegionOfInterest)))
990
0
      return true;
991
171
  }
992
993
428
  return ND->isThisDeclarationADefinition() &&
994
65
         Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest));
995
428
}
996
997
template <typename DeclIt>
998
static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
999
                                      SourceManager &SM, SourceLocation EndLoc,
1000
555
                                      SmallVectorImpl<Decl *> &Decls) {
1001
555
  DeclIt next = *DI_current;
1002
593
  while (++next != DE_current) {
1003
462
    Decl *D_next = *next;
1004
462
    if (!D_next)
1005
0
      break;
1006
462
    SourceLocation L = D_next->getBeginLoc();
1007
462
    if (!L.isValid())
1008
0
      break;
1009
462
    if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
1010
38
      *DI_current = next;
1011
38
      Decls.push_back(D_next);
1012
38
      continue;
1013
38
    }
1014
424
    break;
1015
424
  }
1016
555
}
CIndex.cpp:void addRangedDeclsInContainer<clang::DeclContext::decl_iterator>(clang::DeclContext::decl_iterator*, clang::DeclContext::decl_iterator, clang::SourceManager&, clang::SourceLocation, llvm::SmallVectorImpl<clang::Decl*>&)
Line
Count
Source
1000
90
                                      SmallVectorImpl<Decl *> &Decls) {
1001
90
  DeclIt next = *DI_current;
1002
90
  while (++next != DE_current) {
1003
75
    Decl *D_next = *next;
1004
75
    if (!D_next)
1005
0
      break;
1006
75
    SourceLocation L = D_next->getBeginLoc();
1007
75
    if (!L.isValid())
1008
0
      break;
1009
75
    if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
1010
0
      *DI_current = next;
1011
0
      Decls.push_back(D_next);
1012
0
      continue;
1013
0
    }
1014
75
    break;
1015
75
  }
1016
90
}
CIndex.cpp:void addRangedDeclsInContainer<clang::Decl**>(clang::Decl***, clang::Decl**, clang::SourceManager&, clang::SourceLocation, llvm::SmallVectorImpl<clang::Decl*>&)
Line
Count
Source
1000
465
                                      SmallVectorImpl<Decl *> &Decls) {
1001
465
  DeclIt next = *DI_current;
1002
503
  while (++next != DE_current) {
1003
387
    Decl *D_next = *next;
1004
387
    if (!D_next)
1005
0
      break;
1006
387
    SourceLocation L = D_next->getBeginLoc();
1007
387
    if (!L.isValid())
1008
0
      break;
1009
387
    if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
1010
38
      *DI_current = next;
1011
38
      Decls.push_back(D_next);
1012
38
      continue;
1013
38
    }
1014
349
    break;
1015
349
  }
1016
465
}
1017
1018
649
bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
1019
  // FIXME: Eventually convert back to just 'VisitDeclContext()'.  Essentially
1020
  // an @implementation can lexically contain Decls that are not properly
1021
  // nested in the AST.  When we identify such cases, we need to retrofit
1022
  // this nesting here.
1023
649
  if (!DI_current && 
!FileDI_current559
)
1024
94
    return VisitDeclContext(D);
1025
1026
  // Scan the Decls that immediately come after the container
1027
  // in the current DeclContext.  If any fall within the
1028
  // container's lexical region, stash them into a vector
1029
  // for later processing.
1030
555
  SmallVector<Decl *, 24> DeclsInContainer;
1031
555
  SourceLocation EndLoc = D->getSourceRange().getEnd();
1032
555
  SourceManager &SM = AU->getSourceManager();
1033
555
  if (EndLoc.isValid()) {
1034
555
    if (DI_current) {
1035
90
      addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
1036
90
                                DeclsInContainer);
1037
465
    } else {
1038
465
      addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
1039
465
                                DeclsInContainer);
1040
465
    }
1041
555
  }
1042
1043
  // The common case.
1044
555
  if (DeclsInContainer.empty())
1045
523
    return VisitDeclContext(D);
1046
1047
  // Get all the Decls in the DeclContext, and sort them with the
1048
  // additional ones we've collected.  Then visit them.
1049
84
  
for (auto *SubDecl : D->decls())32
{
1050
84
    if (!SubDecl || SubDecl->getLexicalDeclContext() != D ||
1051
84
        SubDecl->getBeginLoc().isInvalid())
1052
0
      continue;
1053
84
    DeclsInContainer.push_back(SubDecl);
1054
84
  }
1055
1056
  // Now sort the Decls so that they appear in lexical order.
1057
90
  llvm::sort(DeclsInContainer, [&SM](Decl *A, Decl *B) {
1058
90
    SourceLocation L_A = A->getBeginLoc();
1059
90
    SourceLocation L_B = B->getBeginLoc();
1060
90
    return L_A != L_B
1061
65
               ? SM.isBeforeInTranslationUnit(L_A, L_B)
1062
25
               : SM.isBeforeInTranslationUnit(A->getEndLoc(), B->getEndLoc());
1063
90
  });
1064
1065
  // Now visit the decls.
1066
32
  for (SmallVectorImpl<Decl *>::iterator I = DeclsInContainer.begin(),
1067
32
                                         E = DeclsInContainer.end();
1068
119
       I != E; 
++I87
) {
1069
107
    CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
1070
107
    const Optional<bool> &V = shouldVisitCursor(Cursor);
1071
107
    if (!V.hasValue())
1072
41
      continue;
1073
66
    if (!V.getValue())
1074
20
      return false;
1075
46
    if (Visit(Cursor, true))
1076
0
      return true;
1077
46
  }
1078
12
  return false;
1079
32
}
1080
1081
126
bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
1082
126
  if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
1083
126
                                   TU)))
1084
0
    return true;
1085
1086
126
  if (VisitObjCTypeParamList(ND->getTypeParamList()))
1087
0
    return true;
1088
1089
126
  ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
1090
126
  for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
1091
126
                                           E = ND->protocol_end();
1092
128
       I != E; 
++I, ++PL2
)
1093
2
    if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1094
0
      return true;
1095
1096
126
  return VisitObjCContainerDecl(ND);
1097
126
}
1098
1099
106
bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1100
106
  if (!PID->isThisDeclarationADefinition())
1101
0
    return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
1102
1103
106
  ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
1104
106
  for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
1105
106
                                           E = PID->protocol_end();
1106
154
       I != E; 
++I, ++PL48
)
1107
48
    if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1108
0
      return true;
1109
1110
106
  return VisitObjCContainerDecl(PID);
1111
106
}
1112
1113
62
bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
1114
62
  if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
1115
0
    return true;
1116
1117
  // FIXME: This implements a workaround with @property declarations also being
1118
  // installed in the DeclContext for the @interface.  Eventually this code
1119
  // should be removed.
1120
62
  ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
1121
62
  if (!CDecl || 
!CDecl->IsClassExtension()16
)
1122
49
    return false;
1123
1124
13
  ObjCInterfaceDecl *ID = CDecl->getClassInterface();
1125
13
  if (!ID)
1126
0
    return false;
1127
1128
13
  IdentifierInfo *PropertyId = PD->getIdentifier();
1129
13
  ObjCPropertyDecl *prevDecl = ObjCPropertyDecl::findPropertyDecl(
1130
13
      cast<DeclContext>(ID), PropertyId, PD->getQueryKind());
1131
1132
13
  if (!prevDecl)
1133
0
    return false;
1134
1135
  // Visit synthesized methods since they will be skipped when visiting
1136
  // the @interface.
1137
13
  if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
1138
13
    if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1139
10
      if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1140
0
        return true;
1141
1142
13
  if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
1143
13
    if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
1144
12
      if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
1145
0
        return true;
1146
1147
13
  return false;
1148
13
}
1149
1150
483
bool CursorVisitor::VisitObjCTypeParamList(ObjCTypeParamList *typeParamList) {
1151
483
  if (!typeParamList)
1152
475
    return false;
1153
1154
15
  
for (auto *typeParam : *typeParamList)8
{
1155
    // Visit the type parameter.
1156
15
    if (Visit(MakeCXCursor(typeParam, TU, RegionOfInterest)))
1157
0
      return true;
1158
15
  }
1159
1160
8
  return false;
1161
8
}
1162
1163
387
bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
1164
387
  if (!D->isThisDeclarationADefinition()) {
1165
    // Forward declaration is treated like a reference.
1166
30
    return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
1167
30
  }
1168
1169
  // Objective-C type parameters.
1170
357
  if (VisitObjCTypeParamList(D->getTypeParamListAsWritten()))
1171
0
    return true;
1172
1173
  // Issue callbacks for super class.
1174
357
  if (D->getSuperClass() && Visit(MakeCursorObjCSuperClassRef(
1175
134
                                D->getSuperClass(), D->getSuperClassLoc(), TU)))
1176
0
    return true;
1177
1178
357
  if (TypeSourceInfo *SuperClassTInfo = D->getSuperClassTInfo())
1179
134
    if (Visit(SuperClassTInfo->getTypeLoc()))
1180
6
      return true;
1181
1182
351
  ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1183
351
  for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1184
351
                                            E = D->protocol_end();
1185
437
       I != E; 
++I, ++PL86
)
1186
86
    if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
1187
0
      return true;
1188
1189
351
  return VisitObjCContainerDecl(D);
1190
351
}
1191
1192
66
bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1193
66
  return VisitObjCContainerDecl(D);
1194
66
}
1195
1196
5
bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1197
  // 'ID' could be null when dealing with invalid code.
1198
5
  if (ObjCInterfaceDecl *ID = D->getClassInterface())
1199
5
    if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1200
0
      return true;
1201
1202
5
  return VisitObjCImplDecl(D);
1203
5
}
1204
1205
61
bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1206
#if 0
1207
  // Issue callbacks for super class.
1208
  // FIXME: No source location information!
1209
  if (D->getSuperClass() &&
1210
      Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
1211
                                        D->getSuperClassLoc(),
1212
                                        TU)))
1213
    return true;
1214
#endif
1215
1216
61
  return VisitObjCImplDecl(D);
1217
61
}
1218
1219
18
bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
1220
18
  if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
1221
14
    if (PD->isIvarNameSpecified())
1222
10
      return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
1223
1224
8
  return false;
1225
8
}
1226
1227
108
bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1228
108
  return VisitDeclContext(D);
1229
108
}
1230
1231
7
bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1232
  // Visit nested-name-specifier.
1233
7
  if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1234
2
    if (VisitNestedNameSpecifierLoc(QualifierLoc))
1235
0
      return true;
1236
1237
7
  return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1238
7
                                      D->getTargetNameLoc(), TU));
1239
7
}
1240
1241
7
bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
1242
  // Visit nested-name-specifier.
1243
7
  if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1244
7
    if (VisitNestedNameSpecifierLoc(QualifierLoc))
1245
0
      return true;
1246
7
  }
1247
1248
7
  if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1249
0
    return true;
1250
1251
7
  return VisitDeclarationNameInfo(D->getNameInfo());
1252
7
}
1253
1254
5
bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1255
  // Visit nested-name-specifier.
1256
5
  if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1257
1
    if (VisitNestedNameSpecifierLoc(QualifierLoc))
1258
0
      return true;
1259
1260
5
  return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1261
5
                                      D->getIdentLocation(), TU));
1262
5
}
1263
1264
4
bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1265
  // Visit nested-name-specifier.
1266
4
  if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
1267
4
    if (VisitNestedNameSpecifierLoc(QualifierLoc))
1268
0
      return true;
1269
4
  }
1270
1271
4
  return VisitDeclarationNameInfo(D->getNameInfo());
1272
4
}
1273
1274
bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1275
3
    UnresolvedUsingTypenameDecl *D) {
1276
  // Visit nested-name-specifier.
1277
3
  if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1278
3
    if (VisitNestedNameSpecifierLoc(QualifierLoc))
1279
0
      return true;
1280
1281
3
  return false;
1282
3
}
1283
1284
1
bool CursorVisitor::VisitStaticAssertDecl(StaticAssertDecl *D) {
1285
1
  if (Visit(MakeCXCursor(D->getAssertExpr(), StmtParent, TU, RegionOfInterest)))
1286
0
    return true;
1287
1
  if (StringLiteral *Message = D->getMessage())
1288
1
    if (Visit(MakeCXCursor(Message, StmtParent, TU, RegionOfInterest)))
1289
0
      return true;
1290
1
  return false;
1291
1
}
1292
1293
41
bool CursorVisitor::VisitFriendDecl(FriendDecl *D) {
1294
41
  if (NamedDecl *FriendD = D->getFriendDecl()) {
1295
32
    if (Visit(MakeCXCursor(FriendD, TU, RegionOfInterest)))
1296
0
      return true;
1297
9
  } else if (TypeSourceInfo *TI = D->getFriendType()) {
1298
9
    if (Visit(TI->getTypeLoc()))
1299
0
      return true;
1300
41
  }
1301
41
  return false;
1302
41
}
1303
1304
1
bool CursorVisitor::VisitDecompositionDecl(DecompositionDecl *D) {
1305
2
  for (auto *B : D->bindings()) {
1306
2
    if (Visit(MakeCXCursor(B, TU, RegionOfInterest)))
1307
0
      return true;
1308
2
  }
1309
1
  return VisitVarDecl(D);
1310
1
}
1311
1312
3.58k
bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1313
3.58k
  switch (Name.getName().getNameKind()) {
1314
3.35k
  case clang::DeclarationName::Identifier:
1315
3.35k
  case clang::DeclarationName::CXXLiteralOperatorName:
1316
3.35k
  case clang::DeclarationName::CXXDeductionGuideName:
1317
3.48k
  case clang::DeclarationName::CXXOperatorName:
1318
3.48k
  case clang::DeclarationName::CXXUsingDirective:
1319
3.48k
    return false;
1320
1321
95
  case clang::DeclarationName::CXXConstructorName:
1322
95
  case clang::DeclarationName::CXXDestructorName:
1323
102
  case clang::DeclarationName::CXXConversionFunctionName:
1324
102
    if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1325
7
      return Visit(TSInfo->getTypeLoc());
1326
95
    return false;
1327
1328
0
  case clang::DeclarationName::ObjCZeroArgSelector:
1329
0
  case clang::DeclarationName::ObjCOneArgSelector:
1330
0
  case clang::DeclarationName::ObjCMultiArgSelector:
1331
    // FIXME: Per-identifier location info?
1332
0
    return false;
1333
0
  }
1334
1335
0
  llvm_unreachable("Invalid DeclarationName::Kind!");
1336
0
}
1337
1338
bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1339
0
                                             SourceRange Range) {
1340
  // FIXME: This whole routine is a hack to work around the lack of proper
1341
  // source information in nested-name-specifiers (PR5791). Since we do have
1342
  // a beginning source location, we can visit the first component of the
1343
  // nested-name-specifier, if it's a single-token component.
1344
0
  if (!NNS)
1345
0
    return false;
1346
1347
  // Get the first component in the nested-name-specifier.
1348
0
  while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1349
0
    NNS = Prefix;
1350
1351
0
  switch (NNS->getKind()) {
1352
0
  case NestedNameSpecifier::Namespace:
1353
0
    return Visit(
1354
0
        MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(), TU));
1355
1356
0
  case NestedNameSpecifier::NamespaceAlias:
1357
0
    return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1358
0
                                        Range.getBegin(), TU));
1359
1360
0
  case NestedNameSpecifier::TypeSpec: {
1361
    // If the type has a form where we know that the beginning of the source
1362
    // range matches up with a reference cursor. Visit the appropriate reference
1363
    // cursor.
1364
0
    const Type *T = NNS->getAsType();
1365
0
    if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1366
0
      return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1367
0
    if (const TagType *Tag = dyn_cast<TagType>(T))
1368
0
      return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1369
0
    if (const TemplateSpecializationType *TST =
1370
0
            dyn_cast<TemplateSpecializationType>(T))
1371
0
      return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1372
0
    break;
1373
0
  }
1374
1375
0
  case NestedNameSpecifier::TypeSpecWithTemplate:
1376
0
  case NestedNameSpecifier::Global:
1377
0
  case NestedNameSpecifier::Identifier:
1378
0
  case NestedNameSpecifier::Super:
1379
0
    break;
1380
0
  }
1381
1382
0
  return false;
1383
0
}
1384
1385
bool CursorVisitor::VisitNestedNameSpecifierLoc(
1386
370
    NestedNameSpecifierLoc Qualifier) {
1387
370
  SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
1388
647
  for (; Qualifier; 
Qualifier = Qualifier.getPrefix()277
)
1389
277
    Qualifiers.push_back(Qualifier);
1390
1391
647
  while (!Qualifiers.empty()) {
1392
277
    NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
1393
277
    NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
1394
277
    switch (NNS->getKind()) {
1395
138
    case NestedNameSpecifier::Namespace:
1396
138
      if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
1397
138
                                       Q.getLocalBeginLoc(), TU)))
1398
0
        return true;
1399
1400
138
      break;
1401
1402
17
    case NestedNameSpecifier::NamespaceAlias:
1403
17
      if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
1404
17
                                       Q.getLocalBeginLoc(), TU)))
1405
0
        return true;
1406
1407
17
      break;
1408
1409
104
    case NestedNameSpecifier::TypeSpec:
1410
106
    case NestedNameSpecifier::TypeSpecWithTemplate:
1411
106
      if (Visit(Q.getTypeLoc()))
1412
0
        return true;
1413
1414
106
      break;
1415
1416
11
    case NestedNameSpecifier::Global:
1417
16
    case NestedNameSpecifier::Identifier:
1418
16
    case NestedNameSpecifier::Super:
1419
16
      break;
1420
277
    }
1421
277
  }
1422
1423
370
  return false;
1424
370
}
1425
1426
bool CursorVisitor::VisitTemplateParameters(
1427
285
    const TemplateParameterList *Params) {
1428
285
  if (!Params)
1429
0
    return false;
1430
1431
285
  for (TemplateParameterList::const_iterator P = Params->begin(),
1432
285
                                             PEnd = Params->end();
1433
654
       P != PEnd; 
++P369
) {
1434
369
    if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
1435
0
      return true;
1436
369
  }
1437
1438
285
  return false;
1439
285
}
1440
1441
158
bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1442
158
  switch (Name.getKind()) {
1443
157
  case TemplateName::Template:
1444
157
    return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1445
1446
0
  case TemplateName::OverloadedTemplate:
1447
    // Visit the overloaded template set.
1448
0
    if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1449
0
      return true;
1450
1451
0
    return false;
1452
1453
0
  case TemplateName::AssumedTemplate:
1454
    // FIXME: Visit DeclarationName?
1455
0
    return false;
1456
1457
1
  case TemplateName::DependentTemplate:
1458
    // FIXME: Visit nested-name-specifier.
1459
1
    return false;
1460
1461
0
  case TemplateName::QualifiedTemplate:
1462
    // FIXME: Visit nested-name-specifier.
1463
0
    return Visit(MakeCursorTemplateRef(
1464
0
        Name.getAsQualifiedTemplateName()->getDecl(), Loc, TU));
1465
1466
0
  case TemplateName::SubstTemplateTemplateParm:
1467
0
    return Visit(MakeCursorTemplateRef(
1468
0
        Name.getAsSubstTemplateTemplateParm()->getParameter(), Loc, TU));
1469
1470
0
  case TemplateName::SubstTemplateTemplateParmPack:
1471
0
    return Visit(MakeCursorTemplateRef(
1472
0
        Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(), Loc,
1473
0
        TU));
1474
0
  }
1475
1476
0
  llvm_unreachable("Invalid TemplateName::Kind!");
1477
0
}
1478
1479
269
bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1480
269
  switch (TAL.getArgument().getKind()) {
1481
0
  case TemplateArgument::Null:
1482
0
  case TemplateArgument::Integral:
1483
0
  case TemplateArgument::Pack:
1484
0
    return false;
1485
1486
249
  case TemplateArgument::Type:
1487
249
    if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1488
249
      return Visit(TSInfo->getTypeLoc());
1489
0
    return false;
1490
1491
0
  case TemplateArgument::Declaration:
1492
0
    if (Expr *E = TAL.getSourceDeclExpression())
1493
0
      return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1494
0
    return false;
1495
1496
0
  case TemplateArgument::NullPtr:
1497
0
    if (Expr *E = TAL.getSourceNullPtrExpression())
1498
0
      return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1499
0
    return false;
1500
1501
14
  case TemplateArgument::Expression:
1502
14
    if (Expr *E = TAL.getSourceExpression())
1503
14
      return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
1504
0
    return false;
1505
1506
6
  case TemplateArgument::Template:
1507
6
  case TemplateArgument::TemplateExpansion:
1508
6
    if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
1509
0
      return true;
1510
1511
6
    return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
1512
6
                             TAL.getTemplateNameLoc());
1513
0
  }
1514
1515
0
  llvm_unreachable("Invalid TemplateArgument::Kind!");
1516
0
}
1517
1518
7
bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1519
7
  return VisitDeclContext(D);
1520
7
}
1521
1522
173
bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1523
173
  return Visit(TL.getUnqualifiedLoc());
1524
173
}
1525
1526
3.50k
bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1527
3.50k
  ASTContext &Context = AU->getASTContext();
1528
1529
  // Some builtin types (such as Objective-C's "id", "sel", and
1530
  // "Class") have associated declarations. Create cursors for those.
1531
3.50k
  QualType VisitType;
1532
3.50k
  switch (TL.getTypePtr()->getKind()) {
1533
1534
1.34k
  case BuiltinType::Void:
1535
1.34k
  case BuiltinType::NullPtr:
1536
1.35k
  case BuiltinType::Dependent:
1537
1.35k
#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix)                   \
1538
49.4k
  case BuiltinType::Id:
1539
49.4k
#include 
"clang/Basic/OpenCLImageTypes.def"1.35k
1540
16.6k
#define EXT_OPAQUE_TYPE(ExtTYpe, Id, Ext) case BuiltinType::Id:
1541
16.6k
#include 
"clang/Basic/OpenCLExtensionTypes.def"1.39k
1542
1.39k
  case BuiltinType::OCLSampler:
1543
1.39k
  case BuiltinType::OCLEvent:
1544
1.39k
  case BuiltinType::OCLClkEvent:
1545
1.39k
  case BuiltinType::OCLQueue:
1546
1.39k
  case BuiltinType::OCLReserveID:
1547
68.1k
#define SVE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
1548
68.1k
#include 
"clang/Basic/AArch64SVEACLETypes.def"1.39k
1549
2.78k
#define PPC_VECTOR_TYPE(Name, Id, Size) case BuiltinType::Id:
1550
2.78k
#include 
"clang/Basic/PPCTypes.def"1.39k
1551
2.78k
#define BUILTIN_TYPE(Id, SingletonId)
1552
56.6k
#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1553
54.7k
#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
1554
24.0k
#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
1555
34.5k
#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
1556
3.45k
#include 
"clang/AST/BuiltinTypes.def"1.39k
1557
3.45k
    break;
1558
1559
48
  case BuiltinType::ObjCId:
1560
48
    VisitType = Context.getObjCIdType();
1561
48
    break;
1562
1563
0
  case BuiltinType::ObjCClass:
1564
0
    VisitType = Context.getObjCClassType();
1565
0
    break;
1566
1567
0
  case BuiltinType::ObjCSel:
1568
0
    VisitType = Context.getObjCSelType();
1569
0
    break;
1570
3.50k
  }
1571
1572
3.50k
  if (!VisitType.isNull()) {
1573
48
    if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
1574
48
      return Visit(
1575
48
          MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(), TU));
1576
3.45k
  }
1577
1578
3.45k
  return false;
1579
3.45k
}
1580
1581
416
bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1582
416
  return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
1583
416
}
1584
1585
0
bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1586
0
  return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1587
0
}
1588
1589
635
bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1590
635
  if (TL.isDefinition())
1591
63
    return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
1592
1593
572
  return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1594
572
}
1595
1596
258
bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1597
258
  return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1598
258
}
1599
1600
319
bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1601
319
  return Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU));
1602
319
}
1603
1604
5
bool CursorVisitor::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
1605
5
  if (Visit(MakeCursorTypeRef(TL.getDecl(), TL.getBeginLoc(), TU)))
1606
0
    return true;
1607
5
  for (unsigned I = 0, N = TL.getNumProtocols(); I != N; 
++I0
) {
1608
0
    if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1609
0
                                        TU)))
1610
0
      return true;
1611
0
  }
1612
1613
5
  return false;
1614
5
}
1615
1616
56
bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1617
56
  if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1618
0
    return true;
1619
1620
70
  
for (unsigned I = 0, N = TL.getNumTypeArgs(); 56
I != N;
++I14
) {
1621
14
    if (Visit(TL.getTypeArgTInfo(I)->getTypeLoc()))
1622
0
      return true;
1623
14
  }
1624
1625
106
  
for (unsigned I = 0, N = TL.getNumProtocols(); 56
I != N;
++I50
) {
1626
50
    if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1627
50
                                        TU)))
1628
0
      return true;
1629
50
  }
1630
1631
56
  return false;
1632
56
}
1633
1634
202
bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1635
202
  return Visit(TL.getPointeeLoc());
1636
202
}
1637
1638
41
bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
1639
41
  return Visit(TL.getInnerLoc());
1640
41
}
1641
1642
0
bool CursorVisitor::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
1643
0
  return Visit(TL.getInnerLoc());
1644
0
}
1645
1646
284
bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1647
284
  return Visit(TL.getPointeeLoc());
1648
284
}
1649
1650
4
bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1651
4
  return Visit(TL.getPointeeLoc());
1652
4
}
1653
1654
3
bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1655
3
  return Visit(TL.getPointeeLoc());
1656
3
}
1657
1658
113
bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1659
113
  return Visit(TL.getPointeeLoc());
1660
113
}
1661
1662
4
bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1663
4
  return Visit(TL.getPointeeLoc());
1664
4
}
1665
1666
9
bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
1667
9
  return Visit(TL.getModifiedLoc());
1668
9
}
1669
1670
bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1671
1.91k
                                         bool SkipResultType) {
1672
1.91k
  if (!SkipResultType && 
Visit(TL.getReturnLoc())63
)
1673
0
    return true;
1674
1675
3.41k
  
for (unsigned I = 0, N = TL.getNumParams(); 1.91k
I != N;
++I1.49k
)
1676
1.49k
    if (Decl *D = TL.getParam(I))
1677
1.49k
      if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
1678
0
        return true;
1679
1680
1.91k
  return false;
1681
1.91k
}
1682
1683
54
bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1684
54
  if (Visit(TL.getElementLoc()))
1685
0
    return true;
1686
1687
54
  if (Expr *Size = TL.getSizeExpr())
1688
27
    return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
1689
1690
27
  return false;
1691
27
}
1692
1693
0
bool CursorVisitor::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
1694
0
  return Visit(TL.getOriginalLoc());
1695
0
}
1696
1697
0
bool CursorVisitor::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
1698
0
  return Visit(TL.getOriginalLoc());
1699
0
}
1700
1701
bool CursorVisitor::VisitDeducedTemplateSpecializationTypeLoc(
1702
0
    DeducedTemplateSpecializationTypeLoc TL) {
1703
0
  if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1704
0
                        TL.getTemplateNameLoc()))
1705
0
    return true;
1706
1707
0
  return false;
1708
0
}
1709
1710
bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1711
152
    TemplateSpecializationTypeLoc TL) {
1712
  // Visit the template name.
1713
152
  if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1714
152
                        TL.getTemplateNameLoc()))
1715
0
    return true;
1716
1717
  // Visit the template arguments.
1718
350
  
for (unsigned I = 0, N = TL.getNumArgs(); 152
I != N;
++I198
)
1719
198
    if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1720
0
      return true;
1721
1722
152
  return false;
1723
152
}
1724
1725
0
bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1726
0
  return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1727
0
}
1728
1729
0
bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1730
0
  if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1731
0
    return Visit(TSInfo->getTypeLoc());
1732
1733
0
  return false;
1734
0
}
1735
1736
0
bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
1737
0
  if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1738
0
    return Visit(TSInfo->getTypeLoc());
1739
1740
0
  return false;
1741
0
}
1742
1743
21
bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1744
21
  return VisitNestedNameSpecifierLoc(TL.getQualifierLoc());
1745
21
}
1746
1747
bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
1748
4
    DependentTemplateSpecializationTypeLoc TL) {
1749
  // Visit the nested-name-specifier, if there is one.
1750
4
  if (TL.getQualifierLoc() && VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1751
0
    return true;
1752
1753
  // Visit the template arguments.
1754
8
  
for (unsigned I = 0, N = TL.getNumArgs(); 4
I != N;
++I4
)
1755
4
    if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1756
0
      return true;
1757
1758
4
  return false;
1759
4
}
1760
1761
258
bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1762
258
  if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
1763
0
    return true;
1764
1765
258
  return Visit(TL.getNamedTypeLoc());
1766
258
}
1767
1768
1
bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
1769
1
  return Visit(TL.getPatternLoc());
1770
1
}
1771
1772
1
bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
1773
1
  if (Expr *E = TL.getUnderlyingExpr())
1774
1
    return Visit(MakeCXCursor(E, StmtParent, TU));
1775
1776
0
  return false;
1777
0
}
1778
1779
7
bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
1780
7
  return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1781
7
}
1782
1783
3
bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
1784
3
  return Visit(TL.getValueLoc());
1785
3
}
1786
1787
2
bool CursorVisitor::VisitPipeTypeLoc(PipeTypeLoc TL) {
1788
2
  return Visit(TL.getValueLoc());
1789
2
}
1790
1791
#define DEFAULT_TYPELOC_IMPL(CLASS, PARENT)                                    \
1792
790
  bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) {               \
1793
790
    return Visit##PARENT##Loc(TL);                                             \
1794
790
  }
Unexecuted instantiation: clang::cxcursor::CursorVisitor::VisitComplexTypeLoc(clang::ComplexTypeLoc)
clang::cxcursor::CursorVisitor::VisitConstantArrayTypeLoc(clang::ConstantArrayTypeLoc)
Line
Count
Source
1792
19
  bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) {               \
1793
19
    return Visit##PARENT##Loc(TL);                                             \
1794
19
  }
clang::cxcursor::CursorVisitor::VisitIncompleteArrayTypeLoc(clang::IncompleteArrayTypeLoc)
Line
Count
Source
1792
27
  bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) {               \
1793
27
    return Visit##PARENT##Loc(TL);                                             \
1794
27
  }
clang::cxcursor::CursorVisitor::VisitVariableArrayTypeLoc(clang::VariableArrayTypeLoc)
Line
Count
Source
1792
5
  bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) {               \
1793
5
    return Visit##PARENT##Loc(TL);                                             \
1794
5
  }
clang::cxcursor::CursorVisitor::VisitDependentSizedArrayTypeLoc(clang::DependentSizedArrayTypeLoc)
Line
Count
Source
1792
3
  bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) {               \
1793
3
    return Visit##PARENT##Loc(TL);                                             \
1794
3
  }
Unexecuted instantiation: clang::cxcursor::CursorVisitor::VisitDependentAddressSpaceTypeLoc(clang::DependentAddressSpaceTypeLoc)
Unexecuted instantiation: clang::cxcursor::CursorVisitor::VisitDependentVectorTypeLoc(clang::DependentVectorTypeLoc)
Unexecuted instantiation: clang::cxcursor::CursorVisitor::VisitDependentSizedExtVectorTypeLoc(clang::DependentSizedExtVectorTypeLoc)
clang::cxcursor::CursorVisitor::VisitVectorTypeLoc(clang::VectorTypeLoc)
Line
Count
Source
1792
7
  bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) {               \
1793
7
    return Visit##PARENT##Loc(TL);                                             \
1794
7
  }
clang::cxcursor::CursorVisitor::VisitExtVectorTypeLoc(clang::ExtVectorTypeLoc)
Line
Count
Source
1792
4
  bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) {               \
1793
4
    return Visit##PARENT##Loc(TL);                                             \
1794
4
  }
Unexecuted instantiation: clang::cxcursor::CursorVisitor::VisitConstantMatrixTypeLoc(clang::ConstantMatrixTypeLoc)
Unexecuted instantiation: clang::cxcursor::CursorVisitor::VisitDependentSizedMatrixTypeLoc(clang::DependentSizedMatrixTypeLoc)
clang::cxcursor::CursorVisitor::VisitFunctionProtoTypeLoc(clang::FunctionProtoTypeLoc)
Line
Count
Source
1792
60
  bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) {               \
1793
60
    return Visit##PARENT##Loc(TL);                                             \
1794
60
  }
clang::cxcursor::CursorVisitor::VisitFunctionNoProtoTypeLoc(clang::FunctionNoProtoTypeLoc)
Line
Count
Source
1792
3
  bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) {               \
1793
3
    return Visit##PARENT##Loc(TL);                                             \
1794
3
  }
clang::cxcursor::CursorVisitor::VisitRecordTypeLoc(clang::RecordTypeLoc)
Line
Count
Source
1792
612
  bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) {               \
1793
612
    return Visit##PARENT##Loc(TL);                                             \
1794
612
  }
clang::cxcursor::CursorVisitor::VisitEnumTypeLoc(clang::EnumTypeLoc)
Line
Count
Source
1792
23
  bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) {               \
1793
23
    return Visit##PARENT##Loc(TL);                                             \
1794
23
  }
clang::cxcursor::CursorVisitor::VisitSubstTemplateTypeParmTypeLoc(clang::SubstTemplateTypeParmTypeLoc)
Line
Count
Source
1792
3
  bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) {               \
1793
3
    return Visit##PARENT##Loc(TL);                                             \
1794
3
  }
Unexecuted instantiation: clang::cxcursor::CursorVisitor::VisitSubstTemplateTypeParmPackTypeLoc(clang::SubstTemplateTypeParmPackTypeLoc)
clang::cxcursor::CursorVisitor::VisitAutoTypeLoc(clang::AutoTypeLoc)
Line
Count
Source
1792
24
  bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) {               \
1793
24
    return Visit##PARENT##Loc(TL);                                             \
1794
24
  }
Unexecuted instantiation: clang::cxcursor::CursorVisitor::VisitExtIntTypeLoc(clang::ExtIntTypeLoc)
Unexecuted instantiation: clang::cxcursor::CursorVisitor::VisitDependentExtIntTypeLoc(clang::DependentExtIntTypeLoc)
1795
1796
DEFAULT_TYPELOC_IMPL(Complex, Type)
1797
DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
1798
DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
1799
DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
1800
DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
1801
DEFAULT_TYPELOC_IMPL(DependentAddressSpace, Type)
1802
DEFAULT_TYPELOC_IMPL(DependentVector, Type)
1803
DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
1804
DEFAULT_TYPELOC_IMPL(Vector, Type)
1805
DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
1806
DEFAULT_TYPELOC_IMPL(ConstantMatrix, MatrixType)
1807
DEFAULT_TYPELOC_IMPL(DependentSizedMatrix, MatrixType)
1808
DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
1809
DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
1810
DEFAULT_TYPELOC_IMPL(Record, TagType)
1811
DEFAULT_TYPELOC_IMPL(Enum, TagType)
1812
DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
1813
DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
1814
DEFAULT_TYPELOC_IMPL(Auto, Type)
1815
DEFAULT_TYPELOC_IMPL(ExtInt, Type)
1816
DEFAULT_TYPELOC_IMPL(DependentExtInt, Type)
1817
1818
603
bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1819
  // Visit the nested-name-specifier, if present.
1820
603
  if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
1821
1
    if (VisitNestedNameSpecifierLoc(QualifierLoc))
1822
0
      return true;
1823
1824
603
  if (D->isCompleteDefinition()) {
1825
125
    for (const auto &I : D->bases()) {
1826
125
      if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU)))
1827
0
        return true;
1828
125
    }
1829
565
  }
1830
1831
603
  return VisitTagDecl(D);
1832
603
}
1833
1834
7.31k
bool CursorVisitor::VisitAttributes(Decl *D) {
1835
7.31k
  for (const auto *I : D->attrs())
1836
186
    if ((TU->ParsingOptions & CXTranslationUnit_VisitImplicitAttributes ||
1837
184
         !I->isImplicit()) &&
1838
178
        Visit(MakeCXCursor(I, D, TU)))
1839
0
      return true;
1840
1841
7.31k
  return false;
1842
7.31k
}
1843
1844
//===----------------------------------------------------------------------===//
1845
// Data-recursive visitor methods.
1846
//===----------------------------------------------------------------------===//
1847
1848
namespace {
1849
#define DEF_JOB(NAME, DATA, KIND)                                              \
1850
  class NAME : public VisitorJob {                                             \
1851
  public:                                                                      \
1852
    NAME(const DATA *d, CXCursor parent)                                       \
1853
26.4k
        : VisitorJob(parent, VisitorJob::KIND, d) {}                           \
CIndex.cpp:(anonymous namespace)::PostChildrenVisit::PostChildrenVisit(void const*, CXCursor)
Line
Count
Source
1853
6.31k
        : VisitorJob(parent, VisitorJob::KIND, d) {}                           \
CIndex.cpp:(anonymous namespace)::StmtVisit::StmtVisit(clang::Stmt const*, CXCursor)
Line
Count
Source
1853
18.3k
        : VisitorJob(parent, VisitorJob::KIND, d) {}                           \
CIndex.cpp:(anonymous namespace)::DeclRefExprParts::DeclRefExprParts(clang::DeclRefExpr const*, CXCursor)
Line
Count
Source
1853
1.19k
        : VisitorJob(parent, VisitorJob::KIND, d) {}                           \
CIndex.cpp:(anonymous namespace)::LambdaExprParts::LambdaExprParts(clang::LambdaExpr const*, CXCursor)
Line
Count
Source
1853
4
        : VisitorJob(parent, VisitorJob::KIND, d) {}                           \
CIndex.cpp:(anonymous namespace)::MemberExprParts::MemberExprParts(clang::MemberExpr const*, CXCursor)
Line
Count
Source
1853
527
        : VisitorJob(parent, VisitorJob::KIND, d) {}                           \
CIndex.cpp:(anonymous namespace)::OverloadExprParts::OverloadExprParts(clang::OverloadExpr const*, CXCursor)
Line
Count
Source
1853
15
        : VisitorJob(parent, VisitorJob::KIND, d) {}                           \
CIndex.cpp:(anonymous namespace)::SizeOfPackExprParts::SizeOfPackExprParts(clang::SizeOfPackExpr const*, CXCursor)
Line
Count
Source
1853
2
        : VisitorJob(parent, VisitorJob::KIND, d) {}                           \
1854
20.0k
    static bool classof(const VisitorJob *VJ) {                                \
1855
20.0k
      return VJ->getKind() == KIND;                                            \
1856
20.0k
    }                                                                          \
CIndex.cpp:(anonymous namespace)::StmtVisit::classof(clang::cxcursor::VisitorJob const*)
Line
Count
Source
1854
18.3k
    static bool classof(const VisitorJob *VJ) {                                \
1855
18.3k
      return VJ->getKind() == KIND;                                            \
1856
18.3k
    }                                                                          \
CIndex.cpp:(anonymous namespace)::MemberExprParts::classof(clang::cxcursor::VisitorJob const*)
Line
Count
Source
1854
527
    static bool classof(const VisitorJob *VJ) {                                \
1855
527
      return VJ->getKind() == KIND;                                            \
1856
527
    }                                                                          \
CIndex.cpp:(anonymous namespace)::DeclRefExprParts::classof(clang::cxcursor::VisitorJob const*)
Line
Count
Source
1854
1.19k
    static bool classof(const VisitorJob *VJ) {                                \
1855
1.19k
      return VJ->getKind() == KIND;                                            \
1856
1.19k
    }                                                                          \
CIndex.cpp:(anonymous namespace)::OverloadExprParts::classof(clang::cxcursor::VisitorJob const*)
Line
Count
Source
1854
15
    static bool classof(const VisitorJob *VJ) {                                \
1855
15
      return VJ->getKind() == KIND;                                            \
1856
15
    }                                                                          \
CIndex.cpp:(anonymous namespace)::SizeOfPackExprParts::classof(clang::cxcursor::VisitorJob const*)
Line
Count
Source
1854
2
    static bool classof(const VisitorJob *VJ) {                                \
1855
2
      return VJ->getKind() == KIND;                                            \
1856
2
    }                                                                          \
CIndex.cpp:(anonymous namespace)::LambdaExprParts::classof(clang::cxcursor::VisitorJob const*)
Line
Count
Source
1854
4
    static bool classof(const VisitorJob *VJ) {                                \
1855
4
      return VJ->getKind() == KIND;                                            \
1856
4
    }                                                                          \
Unexecuted instantiation: CIndex.cpp:(anonymous namespace)::PostChildrenVisit::classof(clang::cxcursor::VisitorJob const*)
1857
20.0k
    const DATA *get() const { return static_cast<const DATA *>(data[0]); }     \
CIndex.cpp:(anonymous namespace)::StmtVisit::get() const
Line
Count
Source
1857
18.3k
    const DATA *get() const { return static_cast<const DATA *>(data[0]); }     \
CIndex.cpp:(anonymous namespace)::MemberExprParts::get() const
Line
Count
Source
1857
527
    const DATA *get() const { return static_cast<const DATA *>(data[0]); }     \
CIndex.cpp:(anonymous namespace)::DeclRefExprParts::get() const
Line
Count
Source
1857
1.19k
    const DATA *get() const { return static_cast<const DATA *>(data[0]); }     \
CIndex.cpp:(anonymous namespace)::OverloadExprParts::get() const
Line
Count
Source
1857
15
    const DATA *get() const { return static_cast<const DATA *>(data[0]); }     \
CIndex.cpp:(anonymous namespace)::SizeOfPackExprParts::get() const
Line
Count
Source
1857
2
    const DATA *get() const { return static_cast<const DATA *>(data[0]); }     \
CIndex.cpp:(anonymous namespace)::LambdaExprParts::get() const
Line
Count
Source
1857
4
    const DATA *get() const { return static_cast<const DATA *>(data[0]); }     \
Unexecuted instantiation: CIndex.cpp:(anonymous namespace)::PostChildrenVisit::get() const
1858
  };
1859
1860
DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
1861
DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
1862
DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
1863
DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
1864
DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
1865
DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
1866
DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
1867
#undef DEF_JOB
1868
1869
class ExplicitTemplateArgsVisit : public VisitorJob {
1870
public:
1871
  ExplicitTemplateArgsVisit(const TemplateArgumentLoc *Begin,
1872
                            const TemplateArgumentLoc *End, CXCursor parent)
1873
      : VisitorJob(parent, VisitorJob::ExplicitTemplateArgsVisitKind, Begin,
1874
12
                   End) {}
1875
12
  static bool classof(const VisitorJob *VJ) {
1876
12
    return VJ->getKind() == ExplicitTemplateArgsVisitKind;
1877
12
  }
1878
12
  const TemplateArgumentLoc *begin() const {
1879
12
    return static_cast<const TemplateArgumentLoc *>(data[0]);
1880
12
  }
1881
12
  const TemplateArgumentLoc *end() {
1882
12
    return static_cast<const TemplateArgumentLoc *>(data[1]);
1883
12
  }
1884
};
1885
class DeclVisit : public VisitorJob {
1886
public:
1887
  DeclVisit(const Decl *D, CXCursor parent, bool isFirst)
1888
      : VisitorJob(parent, VisitorJob::DeclVisitKind, D,
1889
355
                   isFirst ? (void *)1 : (void *)nullptr) {}
1890
710
  static bool classof(const VisitorJob *VJ) {
1891
710
    return VJ->getKind() == DeclVisitKind;
1892
710
  }
1893
355
  const Decl *get() const { return static_cast<const Decl *>(data[0]); }
1894
355
  bool isFirst() const { return data[1] != nullptr; }
1895
};
1896
class TypeLocVisit : public VisitorJob {
1897
public:
1898
  TypeLocVisit(TypeLoc tl, CXCursor parent)
1899
      : VisitorJob(parent, VisitorJob::TypeLocVisitKind,
1900
186
                   tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
1901
1902
186
  static bool classof(const VisitorJob *VJ) {
1903
186
    return VJ->getKind() == TypeLocVisitKind;
1904
186
  }
1905
1906
186
  TypeLoc get() const {
1907
186
    QualType T = QualType::getFromOpaquePtr(data[0]);
1908
186
    return TypeLoc(T, const_cast<void *>(data[1]));
1909
186
  }
1910
};
1911
1912
class LabelRefVisit : public VisitorJob {
1913
public:
1914
  LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
1915
      : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
1916
3
                   labelLoc.getPtrEncoding()) {}
1917
1918
5
  static bool classof(const VisitorJob *VJ) {
1919
5
    return VJ->getKind() == VisitorJob::LabelRefVisitKind;
1920
5
  }
1921
3
  const LabelDecl *get() const {
1922
3
    return static_cast<const LabelDecl *>(data[0]);
1923
3
  }
1924
2
  SourceLocation getLoc() const {
1925
2
    return SourceLocation::getFromPtrEncoding(data[1]);
1926
2
  }
1927
};
1928
1929
class NestedNameSpecifierLocVisit : public VisitorJob {
1930
public:
1931
  NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
1932
      : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
1933
                   Qualifier.getNestedNameSpecifier(),
1934
6
                   Qualifier.getOpaqueData()) {}
1935
1936
6
  static bool classof(const VisitorJob *VJ) {
1937
6
    return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
1938
6
  }
1939
1940
6
  NestedNameSpecifierLoc get() const {
1941
6
    return NestedNameSpecifierLoc(
1942
6
        const_cast<NestedNameSpecifier *>(
1943
6
            static_cast<const NestedNameSpecifier *>(data[0])),
1944
6
        const_cast<void *>(data[1]));
1945
6
  }
1946
};
1947
1948
class DeclarationNameInfoVisit : public VisitorJob {
1949
public:
1950
  DeclarationNameInfoVisit(const Stmt *S, CXCursor parent)
1951
6
      : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
1952
6
  static bool classof(const VisitorJob *VJ) {
1953
6
    return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
1954
6
  }
1955
6
  DeclarationNameInfo get() const {
1956
6
    const Stmt *S = static_cast<const Stmt *>(data[0]);
1957
6
    switch (S->getStmtClass()) {
1958
0
    default:
1959
0
      llvm_unreachable("Unhandled Stmt");
1960
2
    case clang::Stmt::MSDependentExistsStmtClass:
1961
2
      return cast<MSDependentExistsStmt>(S)->getNameInfo();
1962
3
    case Stmt::CXXDependentScopeMemberExprClass:
1963
3
      return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
1964
1
    case Stmt::DependentScopeDeclRefExprClass:
1965
1
      return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
1966
0
    case Stmt::OMPCriticalDirectiveClass:
1967
0
      return cast<OMPCriticalDirective>(S)->getDirectiveName();
1968
6
    }
1969
6
  }
1970
};
1971
class MemberRefVisit : public VisitorJob {
1972
public:
1973
  MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent)
1974
      : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
1975
18
                   L.getPtrEncoding()) {}
1976
18
  static bool classof(const VisitorJob *VJ) {
1977
18
    return VJ->getKind() == VisitorJob::MemberRefVisitKind;
1978
18
  }
1979
18
  const FieldDecl *get() const {
1980
18
    return static_cast<const FieldDecl *>(data[0]);
1981
18
  }
1982
18
  SourceLocation getLoc() const {
1983
18
    return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t)data[1]);
1984
18
  }
1985
};
1986
class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitor, void> {
1987
  friend class OMPClauseEnqueue;
1988
  VisitorWorkList &WL;
1989
  CXCursor Parent;
1990
1991
public:
1992
  EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
1993
12.8k
      : WL(wl), Parent(parent) {}
1994
1995
  void VisitAddrLabelExpr(const AddrLabelExpr *E);
1996
  void VisitBlockExpr(const BlockExpr *B);
1997
  void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1998
  void VisitCompoundStmt(const CompoundStmt *S);
1999
0
  void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */
2000
0
  }
2001
  void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S);
2002
  void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E);
2003
  void VisitCXXNewExpr(const CXXNewExpr *E);
2004
  void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
2005
  void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E);
2006
  void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
2007
  void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E);
2008
  void VisitCXXTypeidExpr(const CXXTypeidExpr *E);
2009
  void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E);
2010
  void VisitCXXUuidofExpr(const CXXUuidofExpr *E);
2011
  void VisitCXXCatchStmt(const CXXCatchStmt *S);
2012
  void VisitCXXForRangeStmt(const CXXForRangeStmt *S);
2013
  void VisitDeclRefExpr(const DeclRefExpr *D);
2014
  void VisitDeclStmt(const DeclStmt *S);
2015
  void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E);
2016
  void VisitDesignatedInitExpr(const DesignatedInitExpr *E);
2017
  void VisitExplicitCastExpr(const ExplicitCastExpr *E);
2018
  void VisitForStmt(const ForStmt *FS);
2019
  void VisitGotoStmt(const GotoStmt *GS);
2020
  void VisitIfStmt(const IfStmt *If);
2021
  void VisitInitListExpr(const InitListExpr *IE);
2022
  void VisitMemberExpr(const MemberExpr *M);
2023
  void VisitOffsetOfExpr(const OffsetOfExpr *E);
2024
  void VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
2025
  void VisitObjCMessageExpr(const ObjCMessageExpr *M);
2026
  void VisitOverloadExpr(const OverloadExpr *E);
2027
  void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
2028
  void VisitStmt(const Stmt *S);
2029
  void VisitSwitchStmt(const SwitchStmt *S);
2030
  void VisitWhileStmt(const WhileStmt *W);
2031
  void VisitTypeTraitExpr(const TypeTraitExpr *E);
2032
  void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E);
2033
  void VisitExpressionTraitExpr(const ExpressionTraitExpr *E);
2034
  void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U);
2035
  void VisitVAArgExpr(const VAArgExpr *E);
2036
  void VisitSizeOfPackExpr(const SizeOfPackExpr *E);
2037
  void VisitPseudoObjectExpr(const PseudoObjectExpr *E);
2038
  void VisitOpaqueValueExpr(const OpaqueValueExpr *E);
2039
  void VisitLambdaExpr(const LambdaExpr *E);
2040
  void VisitOMPExecutableDirective(const OMPExecutableDirective *D);
2041
  void VisitOMPLoopDirective(const OMPLoopDirective *D);
2042
  void VisitOMPParallelDirective(const OMPParallelDirective *D);
2043
  void VisitOMPSimdDirective(const OMPSimdDirective *D);
2044
  void VisitOMPForDirective(const OMPForDirective *D);
2045
  void VisitOMPForSimdDirective(const OMPForSimdDirective *D);
2046
  void VisitOMPSectionsDirective(const OMPSectionsDirective *D);
2047
  void VisitOMPSectionDirective(const OMPSectionDirective *D);
2048
  void VisitOMPSingleDirective(const OMPSingleDirective *D);
2049
  void VisitOMPMasterDirective(const OMPMasterDirective *D);
2050
  void VisitOMPCriticalDirective(const OMPCriticalDirective *D);
2051
  void VisitOMPParallelForDirective(const OMPParallelForDirective *D);
2052
  void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D);
2053
  void VisitOMPParallelMasterDirective(const OMPParallelMasterDirective *D);
2054
  void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D);
2055
  void VisitOMPTaskDirective(const OMPTaskDirective *D);
2056
  void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D);
2057
  void VisitOMPBarrierDirective(const OMPBarrierDirective *D);
2058
  void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D);
2059
  void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D);
2060
  void
2061
  VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D);
2062
  void VisitOMPCancelDirective(const OMPCancelDirective *D);
2063
  void VisitOMPFlushDirective(const OMPFlushDirective *D);
2064
  void VisitOMPDepobjDirective(const OMPDepobjDirective *D);
2065
  void VisitOMPScanDirective(const OMPScanDirective *D);
2066
  void VisitOMPOrderedDirective(const OMPOrderedDirective *D);
2067
  void VisitOMPAtomicDirective(const OMPAtomicDirective *D);
2068
  void VisitOMPTargetDirective(const OMPTargetDirective *D);
2069
  void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D);
2070
  void VisitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective *D);
2071
  void VisitOMPTargetExitDataDirective(const OMPTargetExitDataDirective *D);
2072
  void VisitOMPTargetParallelDirective(const OMPTargetParallelDirective *D);
2073
  void
2074
  VisitOMPTargetParallelForDirective(const OMPTargetParallelForDirective *D);
2075
  void VisitOMPTeamsDirective(const OMPTeamsDirective *D);
2076
  void VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D);
2077
  void VisitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective *D);
2078
  void VisitOMPMasterTaskLoopDirective(const OMPMasterTaskLoopDirective *D);
2079
  void
2080
  VisitOMPMasterTaskLoopSimdDirective(const OMPMasterTaskLoopSimdDirective *D);
2081
  void VisitOMPParallelMasterTaskLoopDirective(
2082
      const OMPParallelMasterTaskLoopDirective *D);
2083
  void VisitOMPParallelMasterTaskLoopSimdDirective(
2084
      const OMPParallelMasterTaskLoopSimdDirective *D);
2085
  void VisitOMPDistributeDirective(const OMPDistributeDirective *D);
2086
  void VisitOMPDistributeParallelForDirective(
2087
      const OMPDistributeParallelForDirective *D);
2088
  void VisitOMPDistributeParallelForSimdDirective(
2089
      const OMPDistributeParallelForSimdDirective *D);
2090
  void VisitOMPDistributeSimdDirective(const OMPDistributeSimdDirective *D);
2091
  void VisitOMPTargetParallelForSimdDirective(
2092
      const OMPTargetParallelForSimdDirective *D);
2093
  void VisitOMPTargetSimdDirective(const OMPTargetSimdDirective *D);
2094
  void VisitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective *D);
2095
  void VisitOMPTeamsDistributeSimdDirective(
2096
      const OMPTeamsDistributeSimdDirective *D);
2097
  void VisitOMPTeamsDistributeParallelForSimdDirective(
2098
      const OMPTeamsDistributeParallelForSimdDirective *D);
2099
  void VisitOMPTeamsDistributeParallelForDirective(
2100
      const OMPTeamsDistributeParallelForDirective *D);
2101
  void VisitOMPTargetTeamsDirective(const OMPTargetTeamsDirective *D);
2102
  void VisitOMPTargetTeamsDistributeDirective(
2103
      const OMPTargetTeamsDistributeDirective *D);
2104
  void VisitOMPTargetTeamsDistributeParallelForDirective(
2105
      const OMPTargetTeamsDistributeParallelForDirective *D);
2106
  void VisitOMPTargetTeamsDistributeParallelForSimdDirective(
2107
      const OMPTargetTeamsDistributeParallelForSimdDirective *D);
2108
  void VisitOMPTargetTeamsDistributeSimdDirective(
2109
      const OMPTargetTeamsDistributeSimdDirective *D);
2110
2111
private:
2112
  void AddDeclarationNameInfo(const Stmt *S);
2113
  void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
2114
  void AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2115
                               unsigned NumTemplateArgs);
2116
  void AddMemberRef(const FieldDecl *D, SourceLocation L);
2117
  void AddStmt(const Stmt *S);
2118
  void AddDecl(const Decl *D, bool isFirst = true);
2119
  void AddTypeLoc(TypeSourceInfo *TI);
2120
  void EnqueueChildren(const Stmt *S);
2121
  void EnqueueChildren(const OMPClause *S);
2122
};
2123
} // namespace
2124
2125
6
void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
2126
  // 'S' should always be non-null, since it comes from the
2127
  // statement we are visiting.
2128
6
  WL.push_back(DeclarationNameInfoVisit(S, Parent));
2129
6
}
2130
2131
void EnqueueVisitor::AddNestedNameSpecifierLoc(
2132
6
    NestedNameSpecifierLoc Qualifier) {
2133
6
  if (Qualifier)
2134
6
    WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
2135
6
}
2136
2137
18.3k
void EnqueueVisitor::AddStmt(const Stmt *S) {
2138
18.3k
  if (S)
2139
18.3k
    WL.push_back(StmtVisit(S, Parent));
2140
18.3k
}
2141
374
void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
2142
374
  if (D)
2143
355
    WL.push_back(DeclVisit(D, Parent, isFirst));
2144
374
}
2145
void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
2146
12
                                             unsigned NumTemplateArgs) {
2147
12
  WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent));
2148
12
}
2149
18
void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
2150
18
  if (D)
2151
18
    WL.push_back(MemberRefVisit(D, L, Parent));
2152
18
}
2153
312
void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
2154
312
  if (TI)
2155
186
    WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
2156
312
}
2157
4.97k
void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
2158
4.97k
  unsigned size = WL.size();
2159
5.61k
  for (const Stmt *SubStmt : S->children()) {
2160
5.61k
    AddStmt(SubStmt);
2161
5.61k
  }
2162
4.97k
  if (size == WL.size())
2163
949
    return;
2164
  // Now reverse the entries we just added.  This will match the DFS
2165
  // ordering performed by the worklist.
2166
4.03k
  VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2167
4.03k
  std::reverse(I, E);
2168
4.03k
}
2169
namespace {
2170
class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
2171
  EnqueueVisitor *Visitor;
2172
  /// Process clauses with list of variables.
2173
  template <typename T> void VisitOMPClauseList(T *Node);
2174
2175
public:
2176
0
  OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) {}
2177
#define GEN_CLANG_CLAUSE_CLASS
2178
#define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(const Class *C);
2179
#include "llvm/Frontend/OpenMP/OMP.inc"
2180
  void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C);
2181
  void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C);
2182
};
2183
2184
void OMPClauseEnqueue::VisitOMPClauseWithPreInit(
2185
0
    const OMPClauseWithPreInit *C) {
2186
0
  Visitor->AddStmt(C->getPreInitStmt());
2187
0
}
2188
2189
void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate(
2190
0
    const OMPClauseWithPostUpdate *C) {
2191
0
  VisitOMPClauseWithPreInit(C);
2192
0
  Visitor->AddStmt(C->getPostUpdateExpr());
2193
0
}
2194
2195
0
void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
2196
0
  VisitOMPClauseWithPreInit(C);
2197
0
  Visitor->AddStmt(C->getCondition());
2198
0
}
2199
2200
0
void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
2201
0
  Visitor->AddStmt(C->getCondition());
2202
0
}
2203
2204
0
void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
2205
0
  VisitOMPClauseWithPreInit(C);
2206
0
  Visitor->AddStmt(C->getNumThreads());
2207
0
}
2208
2209
0
void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
2210
0
  Visitor->AddStmt(C->getSafelen());
2211
0
}
2212
2213
0
void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
2214
0
  Visitor->AddStmt(C->getSimdlen());
2215
0
}
2216
2217
0
void OMPClauseEnqueue::VisitOMPAllocatorClause(const OMPAllocatorClause *C) {
2218
0
  Visitor->AddStmt(C->getAllocator());
2219
0
}
2220
2221
0
void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
2222
0
  Visitor->AddStmt(C->getNumForLoops());
2223
0
}
2224
2225
0
void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) {}
2226
2227
0
void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) {}
2228
2229
0
void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
2230
0
  VisitOMPClauseWithPreInit(C);
2231
0
  Visitor->AddStmt(C->getChunkSize());
2232
0
}
2233
2234
0
void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
2235
0
  Visitor->AddStmt(C->getNumForLoops());
2236
0
}
2237
2238
0
void OMPClauseEnqueue::VisitOMPDetachClause(const OMPDetachClause *C) {
2239
0
  Visitor->AddStmt(C->getEventHandler());
2240
0
}
2241
2242
0
void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
2243
2244
0
void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
2245
2246
0
void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
2247
2248
0
void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
2249
2250
0
void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
2251
2252
0
void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
2253
2254
0
void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
2255
2256
0
void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
2257
2258
0
void OMPClauseEnqueue::VisitOMPAcqRelClause(const OMPAcqRelClause *) {}
2259
2260
0
void OMPClauseEnqueue::VisitOMPAcquireClause(const OMPAcquireClause *) {}
2261
2262
0
void OMPClauseEnqueue::VisitOMPReleaseClause(const OMPReleaseClause *) {}
2263
2264
0
void OMPClauseEnqueue::VisitOMPRelaxedClause(const OMPRelaxedClause *) {}
2265
2266
0
void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
2267
2268
0
void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
2269
2270
0
void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
2271
2272
0
void OMPClauseEnqueue::VisitOMPDestroyClause(const OMPDestroyClause *) {}
2273
2274
void OMPClauseEnqueue::VisitOMPUnifiedAddressClause(
2275
0
    const OMPUnifiedAddressClause *) {}
2276
2277
void OMPClauseEnqueue::VisitOMPUnifiedSharedMemoryClause(
2278
0
    const OMPUnifiedSharedMemoryClause *) {}
2279
2280
void OMPClauseEnqueue::VisitOMPReverseOffloadClause(
2281
0
    const OMPReverseOffloadClause *) {}
2282
2283
void OMPClauseEnqueue::VisitOMPDynamicAllocatorsClause(
2284
0
    const OMPDynamicAllocatorsClause *) {}
2285
2286
void OMPClauseEnqueue::VisitOMPAtomicDefaultMemOrderClause(
2287
0
    const OMPAtomicDefaultMemOrderClause *) {}
2288
2289
0
void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
2290
0
  Visitor->AddStmt(C->getDevice());
2291
0
}
2292
2293
0
void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
2294
0
  VisitOMPClauseWithPreInit(C);
2295
0
  Visitor->AddStmt(C->getNumTeams());
2296
0
}
2297
2298
void OMPClauseEnqueue::VisitOMPThreadLimitClause(
2299
0
    const OMPThreadLimitClause *C) {
2300
0
  VisitOMPClauseWithPreInit(C);
2301
0
  Visitor->AddStmt(C->getThreadLimit());
2302
0
}
2303
2304
0
void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
2305
0
  Visitor->AddStmt(C->getPriority());
2306
0
}
2307
2308
0
void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
2309
0
  Visitor->AddStmt(C->getGrainsize());
2310
0
}
2311
2312
0
void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
2313
0
  Visitor->AddStmt(C->getNumTasks());
2314
0
}
2315
2316
0
void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
2317
0
  Visitor->AddStmt(C->getHint());
2318
0
}
2319
2320
0
template <typename T> void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
2321
0
  for (const auto *I : Node->varlists()) {
2322
0
    Visitor->AddStmt(I);
2323
0
  }
2324
0
}
Unexecuted instantiation: CIndex.cpp:void (anonymous namespace)::OMPClauseEnqueue::VisitOMPClauseList<clang::OMPAlignedClause const>(clang::OMPAlignedClause const*)
Unexecuted instantiation: CIndex.cpp:void (anonymous namespace)::OMPClauseEnqueue::VisitOMPClauseList<clang::OMPAllocateClause const>(clang::OMPAllocateClause const*)
Unexecuted instantiation: CIndex.cpp:void (anonymous namespace)::OMPClauseEnqueue::VisitOMPClauseList<clang::OMPCopyprivateClause const>(clang::OMPCopyprivateClause const*)
Unexecuted instantiation: CIndex.cpp:void (anonymous namespace)::OMPClauseEnqueue::VisitOMPClauseList<clang::OMPCopyinClause const>(clang::OMPCopyinClause const*)
Unexecuted instantiation: CIndex.cpp:void (anonymous namespace)::OMPClauseEnqueue::VisitOMPClauseList<clang::OMPDependClause const>(clang::OMPDependClause const*)
Unexecuted instantiation: CIndex.cpp:void (anonymous namespace)::OMPClauseEnqueue::VisitOMPClauseList<clang::OMPExclusiveClause const>(clang::OMPExclusiveClause const*)
Unexecuted instantiation: CIndex.cpp:void (anonymous namespace)::OMPClauseEnqueue::VisitOMPClauseList<clang::OMPFirstprivateClause const>(clang::OMPFirstprivateClause const*)
Unexecuted instantiation: CIndex.cpp:void (anonymous namespace)::OMPClauseEnqueue::VisitOMPClauseList<clang::OMPFlushClause const>(clang::OMPFlushClause const*)
Unexecuted instantiation: CIndex.cpp:void (anonymous namespace)::OMPClauseEnqueue::VisitOMPClauseList<clang::OMPFromClause const>(clang::OMPFromClause const*)
Unexecuted instantiation: CIndex.cpp:void (anonymous namespace)::OMPClauseEnqueue::VisitOMPClauseList<clang::OMPInReductionClause const>(clang::OMPInReductionClause const*)
Unexecuted instantiation: CIndex.cpp:void (anonymous namespace)::OMPClauseEnqueue::VisitOMPClauseList<clang::OMPInclusiveClause const>(clang::OMPInclusiveClause const*)
Unexecuted instantiation: CIndex.cpp:void (anonymous namespace)::OMPClauseEnqueue::VisitOMPClauseList<clang::OMPIsDevicePtrClause const>(clang::OMPIsDevicePtrClause const*)
Unexecuted instantiation: CIndex.cpp:void (anonymous namespace)::OMPClauseEnqueue::VisitOMPClauseList<clang::OMPLastprivateClause const>(clang::OMPLastprivateClause const*)
Unexecuted instantiation: CIndex.cpp:void (anonymous namespace)::OMPClauseEnqueue::VisitOMPClauseList<clang::OMPLinearClause const>(clang::OMPLinearClause const*)
Unexecuted instantiation: CIndex.cpp:void (anonymous namespace)::OMPClauseEnqueue::VisitOMPClauseList<clang::OMPMapClause const>(clang::OMPMapClause const*)
Unexecuted instantiation: CIndex.cpp:void (anonymous namespace)::OMPClauseEnqueue::VisitOMPClauseList<clang::OMPNontemporalClause const>(clang::OMPNontemporalClause const*)
Unexecuted instantiation: CIndex.cpp:void (anonymous namespace)::OMPClauseEnqueue::VisitOMPClauseList<clang::OMPPrivateClause const>(clang::OMPPrivateClause const*)
Unexecuted instantiation: CIndex.cpp:void (anonymous namespace)::OMPClauseEnqueue::VisitOMPClauseList<clang::OMPReductionClause const>(clang::OMPReductionClause const*)
Unexecuted instantiation: CIndex.cpp:void (anonymous namespace)::OMPClauseEnqueue::VisitOMPClauseList<clang::OMPSharedClause const>(clang::OMPSharedClause const*)
Unexecuted instantiation: CIndex.cpp:void (anonymous namespace)::OMPClauseEnqueue::VisitOMPClauseList<clang::OMPTaskReductionClause const>(clang::OMPTaskReductionClause const*)
Unexecuted instantiation: CIndex.cpp:void (anonymous namespace)::OMPClauseEnqueue::VisitOMPClauseList<clang::OMPToClause const>(clang::OMPToClause const*)
Unexecuted instantiation: CIndex.cpp:void (anonymous namespace)::OMPClauseEnqueue::VisitOMPClauseList<clang::OMPUseDeviceAddrClause const>(clang::OMPUseDeviceAddrClause const*)
Unexecuted instantiation: CIndex.cpp:void (anonymous namespace)::OMPClauseEnqueue::VisitOMPClauseList<clang::OMPUseDevicePtrClause const>(clang::OMPUseDevicePtrClause const*)
2325
2326
0
void OMPClauseEnqueue::VisitOMPInclusiveClause(const OMPInclusiveClause *C) {
2327
0
  VisitOMPClauseList(C);
2328
0
}
2329
0
void OMPClauseEnqueue::VisitOMPExclusiveClause(const OMPExclusiveClause *C) {
2330
0
  VisitOMPClauseList(C);
2331
0
}
2332
0
void OMPClauseEnqueue::VisitOMPAllocateClause(const OMPAllocateClause *C) {
2333
0
  VisitOMPClauseList(C);
2334
0
  Visitor->AddStmt(C->getAllocator());
2335
0
}
2336
0
void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
2337
0
  VisitOMPClauseList(C);
2338
0
  for (const auto *E : C->private_copies()) {
2339
0
    Visitor->AddStmt(E);
2340
0
  }
2341
0
}
2342
void OMPClauseEnqueue::VisitOMPFirstprivateClause(
2343
0
    const OMPFirstprivateClause *C) {
2344
0
  VisitOMPClauseList(C);
2345
0
  VisitOMPClauseWithPreInit(C);
2346
0
  for (const auto *E : C->private_copies()) {
2347
0
    Visitor->AddStmt(E);
2348
0
  }
2349
0
  for (const auto *E : C->inits()) {
2350
0
    Visitor->AddStmt(E);
2351
0
  }
2352
0
}
2353
void OMPClauseEnqueue::VisitOMPLastprivateClause(
2354
0
    const OMPLastprivateClause *C) {
2355
0
  VisitOMPClauseList(C);
2356
0
  VisitOMPClauseWithPostUpdate(C);
2357
0
  for (auto *E : C->private_copies()) {
2358
0
    Visitor->AddStmt(E);
2359
0
  }
2360
0
  for (auto *E : C->source_exprs()) {
2361
0
    Visitor->AddStmt(E);
2362
0
  }
2363
0
  for (auto *E : C->destination_exprs()) {
2364
0
    Visitor->AddStmt(E);
2365
0
  }
2366
0
  for (auto *E : C->assignment_ops()) {
2367
0
    Visitor->AddStmt(E);
2368
0
  }
2369
0
}
2370
0
void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
2371
0
  VisitOMPClauseList(C);
2372
0
}
2373
0
void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
2374
0
  VisitOMPClauseList(C);
2375
0
  VisitOMPClauseWithPostUpdate(C);
2376
0
  for (auto *E : C->privates()) {
2377
0
    Visitor->AddStmt(E);
2378
0
  }
2379
0
  for (auto *E : C->lhs_exprs()) {
2380
0
    Visitor->AddStmt(E);
2381
0
  }
2382
0
  for (auto *E : C->rhs_exprs()) {
2383
0
    Visitor->AddStmt(E);
2384
0
  }
2385
0
  for (auto *E : C->reduction_ops()) {
2386
0
    Visitor->AddStmt(E);
2387
0
  }
2388
0
  if (C->getModifier() == clang::OMPC_REDUCTION_inscan) {
2389
0
    for (auto *E : C->copy_ops()) {
2390
0
      Visitor->AddStmt(E);
2391
0
    }
2392
0
    for (auto *E : C->copy_array_temps()) {
2393
0
      Visitor->AddStmt(E);
2394
0
    }
2395
0
    for (auto *E : C->copy_array_elems()) {
2396
0
      Visitor->AddStmt(E);
2397
0
    }
2398
0
  }
2399
0
}
2400
void OMPClauseEnqueue::VisitOMPTaskReductionClause(
2401
0
    const OMPTaskReductionClause *C) {
2402
0
  VisitOMPClauseList(C);
2403
0
  VisitOMPClauseWithPostUpdate(C);
2404
0
  for (auto *E : C->privates()) {
2405
0
    Visitor->AddStmt(E);
2406
0
  }
2407
0
  for (auto *E : C->lhs_exprs()) {
2408
0
    Visitor->AddStmt(E);
2409
0
  }
2410
0
  for (auto *E : C->rhs_exprs()) {
2411
0
    Visitor->AddStmt(E);
2412
0
  }
2413
0
  for (auto *E : C->reduction_ops()) {
2414
0
    Visitor->AddStmt(E);
2415
0
  }
2416
0
}
2417
void OMPClauseEnqueue::VisitOMPInReductionClause(
2418
0
    const OMPInReductionClause *C) {
2419
0
  VisitOMPClauseList(C);
2420
0
  VisitOMPClauseWithPostUpdate(C);
2421
0
  for (auto *E : C->privates()) {
2422
0
    Visitor->AddStmt(E);
2423
0
  }
2424
0
  for (auto *E : C->lhs_exprs()) {
2425
0
    Visitor->AddStmt(E);
2426
0
  }
2427
0
  for (auto *E : C->rhs_exprs()) {
2428
0
    Visitor->AddStmt(E);
2429
0
  }
2430
0
  for (auto *E : C->reduction_ops()) {
2431
0
    Visitor->AddStmt(E);
2432
0
  }
2433
0
  for (auto *E : C->taskgroup_descriptors())
2434
0
    Visitor->AddStmt(E);
2435
0
}
2436
0
void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
2437
0
  VisitOMPClauseList(C);
2438
0
  VisitOMPClauseWithPostUpdate(C);
2439
0
  for (const auto *E : C->privates()) {
2440
0
    Visitor->AddStmt(E);
2441
0
  }
2442
0
  for (const auto *E : C->inits()) {
2443
0
    Visitor->AddStmt(E);
2444
0
  }
2445
0
  for (const auto *E : C->updates()) {
2446
0
    Visitor->AddStmt(E);
2447
0
  }
2448
0
  for (const auto *E : C->finals()) {
2449
0
    Visitor->AddStmt(E);
2450
0
  }
2451
0
  Visitor->AddStmt(C->getStep());
2452
0
  Visitor->AddStmt(C->getCalcStep());
2453
0
}
2454
0
void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
2455
0
  VisitOMPClauseList(C);
2456
0
  Visitor->AddStmt(C->getAlignment());
2457
0
}
2458
0
void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
2459
0
  VisitOMPClauseList(C);
2460
0
  for (auto *E : C->source_exprs()) {
2461
0
    Visitor->AddStmt(E);
2462
0
  }
2463
0
  for (auto *E : C->destination_exprs()) {
2464
0
    Visitor->AddStmt(E);
2465
0
  }
2466
0
  for (auto *E : C->assignment_ops()) {
2467
0
    Visitor->AddStmt(E);
2468
0
  }
2469
0
}
2470
void OMPClauseEnqueue::VisitOMPCopyprivateClause(
2471
0
    const OMPCopyprivateClause *C) {
2472
0
  VisitOMPClauseList(C);
2473
0
  for (auto *E : C->source_exprs()) {
2474
0
    Visitor->AddStmt(E);
2475
0
  }
2476
0
  for (auto *E : C->destination_exprs()) {
2477
0
    Visitor->AddStmt(E);
2478
0
  }
2479
0
  for (auto *E : C->assignment_ops()) {
2480
0
    Visitor->AddStmt(E);
2481
0
  }
2482
0
}
2483
0
void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
2484
0
  VisitOMPClauseList(C);
2485
0
}
2486
0
void OMPClauseEnqueue::VisitOMPDepobjClause(const OMPDepobjClause *C) {
2487
0
  Visitor->AddStmt(C->getDepobj());
2488
0
}
2489
0
void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
2490
0
  VisitOMPClauseList(C);
2491
0
}
2492
0
void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
2493
0
  VisitOMPClauseList(C);
2494
0
}
2495
void OMPClauseEnqueue::VisitOMPDistScheduleClause(
2496
0
    const OMPDistScheduleClause *C) {
2497
0
  VisitOMPClauseWithPreInit(C);
2498
0
  Visitor->AddStmt(C->getChunkSize());
2499
0
}
2500
void OMPClauseEnqueue::VisitOMPDefaultmapClause(
2501
0
    const OMPDefaultmapClause * /*C*/) {}
2502
0
void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
2503
0
  VisitOMPClauseList(C);
2504
0
}
2505
0
void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
2506
0
  VisitOMPClauseList(C);
2507
0
}
2508
void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(
2509
0
    const OMPUseDevicePtrClause *C) {
2510
0
  VisitOMPClauseList(C);
2511
0
}
2512
void OMPClauseEnqueue::VisitOMPUseDeviceAddrClause(
2513
0
    const OMPUseDeviceAddrClause *C) {
2514
0
  VisitOMPClauseList(C);
2515
0
}
2516
void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(
2517
0
    const OMPIsDevicePtrClause *C) {
2518
0
  VisitOMPClauseList(C);
2519
0
}
2520
void OMPClauseEnqueue::VisitOMPNontemporalClause(
2521
0
    const OMPNontemporalClause *C) {
2522
0
  VisitOMPClauseList(C);
2523
0
  for (const auto *E : C->private_refs())
2524
0
    Visitor->AddStmt(E);
2525
0
}
2526
0
void OMPClauseEnqueue::VisitOMPOrderClause(const OMPOrderClause *C) {}
2527
void OMPClauseEnqueue::VisitOMPUsesAllocatorsClause(
2528
0
    const OMPUsesAllocatorsClause *C) {
2529
0
  for (unsigned I = 0, E = C->getNumberOfAllocators(); I < E; ++I) {
2530
0
    const OMPUsesAllocatorsClause::Data &D = C->getAllocatorData(I);
2531
0
    Visitor->AddStmt(D.Allocator);
2532
0
    Visitor->AddStmt(D.AllocatorTraits);
2533
0
  }
2534
0
}
2535
0
void OMPClauseEnqueue::VisitOMPAffinityClause(const OMPAffinityClause *C) {
2536
0
  Visitor->AddStmt(C->getModifier());
2537
0
  for (const Expr *E : C->varlists())
2538
0
    Visitor->AddStmt(E);
2539
0
}
2540
} // namespace
2541
2542
0
void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
2543
0
  unsigned size = WL.size();
2544
0
  OMPClauseEnqueue Visitor(this);
2545
0
  Visitor.Visit(S);
2546
0
  if (size == WL.size())
2547
0
    return;
2548
  // Now reverse the entries we just added.  This will match the DFS
2549
  // ordering performed by the worklist.
2550
0
  VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2551
0
  std::reverse(I, E);
2552
0
}
2553
1
void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
2554
1
  WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
2555
1
}
2556
6
void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
2557
6
  AddDecl(B->getBlockDecl());
2558
6
}
2559
4
void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2560
4
  EnqueueChildren(E);
2561
4
  AddTypeLoc(E->getTypeSourceInfo());
2562
4
}
2563
802
void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
2564
802
  for (auto &I : llvm::reverse(S->body()))
2565
2.32k
    AddStmt(I);
2566
802
}
2567
void EnqueueVisitor::VisitMSDependentExistsStmt(
2568
2
    const MSDependentExistsStmt *S) {
2569
2
  AddStmt(S->getSubStmt());
2570
2
  AddDeclarationNameInfo(S);
2571
2
  if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
2572
2
    AddNestedNameSpecifierLoc(QualifierLoc);
2573
2
}
2574
2575
void EnqueueVisitor::VisitCXXDependentScopeMemberExpr(
2576
3
    const CXXDependentScopeMemberExpr *E) {
2577
3
  if (E->hasExplicitTemplateArgs())
2578
1
    AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
2579
3
  AddDeclarationNameInfo(E);
2580
3
  if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2581
2
    AddNestedNameSpecifierLoc(QualifierLoc);
2582
3
  if (!E->isImplicitAccess())
2583
3
    AddStmt(E->getBase());
2584
3
}
2585
5
void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
2586
  // Enqueue the initializer , if any.
2587
5
  AddStmt(E->getInitializer());
2588
  // Enqueue the array size, if any.
2589
5
  AddStmt(E->getArraySize().getValueOr(nullptr));
2590
  // Enqueue the allocated type.
2591
5
  AddTypeLoc(E->getAllocatedTypeSourceInfo());
2592
  // Enqueue the placement arguments.
2593
6
  for (unsigned I = E->getNumPlacementArgs(); I > 0; 
--I1
)
2594
1
    AddStmt(E->getPlacementArg(I - 1));
2595
5
}
2596
4.89k
void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
2597
4.92k
  for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; 
--I31
)
2598
31
    AddStmt(CE->getArg(I - 1));
2599
4.89k
  AddStmt(CE->getCallee());
2600
4.89k
  AddStmt(CE->getArg(0));
2601
4.89k
}
2602
void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
2603
2
    const CXXPseudoDestructorExpr *E) {
2604
  // Visit the name of the type being destroyed.
2605
2
  AddTypeLoc(E->getDestroyedTypeInfo());
2606
  // Visit the scope type that looks disturbingly like the nested-name-specifier
2607
  // but isn't.
2608
2
  AddTypeLoc(E->getScopeTypeInfo());
2609
  // Visit the nested-name-specifier.
2610
2
  if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
2611
1
    AddNestedNameSpecifierLoc(QualifierLoc);
2612
  // Visit base expression.
2613
2
  AddStmt(E->getBase());
2614
2
}
2615
void EnqueueVisitor::VisitCXXScalarValueInitExpr(
2616
2
    const CXXScalarValueInitExpr *E) {
2617
2
  AddTypeLoc(E->getTypeSourceInfo());
2618
2
}
2619
void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
2620
39
    const CXXTemporaryObjectExpr *E) {
2621
39
  EnqueueChildren(E);
2622
39
  AddTypeLoc(E->getTypeSourceInfo());
2623
39
}
2624
2
void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2625
2
  EnqueueChildren(E);
2626
2
  if (E->isTypeOperand())
2627
1
    AddTypeLoc(E->getTypeOperandSourceInfo());
2628
2
}
2629
2630
void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
2631
6
    const CXXUnresolvedConstructExpr *E) {
2632
6
  EnqueueChildren(E);
2633
6
  AddTypeLoc(E->getTypeSourceInfo());
2634
6
}
2635
0
void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
2636
0
  EnqueueChildren(E);
2637
0
  if (E->isTypeOperand())
2638
0
    AddTypeLoc(E->getTypeOperandSourceInfo());
2639
0
}
2640
2641
4
void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
2642
4
  EnqueueChildren(S);
2643
4
  AddDecl(S->getExceptionDecl());
2644
4
}
2645
2646
4
void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
2647
4
  AddStmt(S->getBody());
2648
4
  AddStmt(S->getRangeInit());
2649
4
  AddDecl(S->getLoopVariable());
2650
4
}
2651
2652
1.19k
void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
2653
1.19k
  if (DR->hasExplicitTemplateArgs())
2654
6
    AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
2655
1.19k
  WL.push_back(DeclRefExprParts(DR, Parent));
2656
1.19k
}
2657
void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
2658
1
    const DependentScopeDeclRefExpr *E) {
2659
1
  if (E->hasExplicitTemplateArgs())
2660
1
    AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
2661
1
  AddDeclarationNameInfo(E);
2662
1
  AddNestedNameSpecifierLoc(E->getQualifierLoc());
2663
1
}
2664
323
void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
2665
323
  unsigned size = WL.size();
2666
323
  bool isFirst = true;
2667
335
  for (const auto *D : S->decls()) {
2668
335
    AddDecl(D, isFirst);
2669
335
    isFirst = false;
2670
335
  }
2671
323
  if (size == WL.size())
2672
0
    return;
2673
  // Now reverse the entries we just added.  This will match the DFS
2674
  // ordering performed by the worklist.
2675
323
  VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
2676
323
  std::reverse(I, E);
2677
323
}
2678
14
void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
2679
14
  AddStmt(E->getInit());
2680
14
  for (const DesignatedInitExpr::Designator &D :
2681
18
       llvm::reverse(E->designators())) {
2682
18
    if (D.isFieldDesignator()) {
2683
16
      if (FieldDecl *Field = D.getField())
2684
16
        AddMemberRef(Field, D.getFieldLoc());
2685
16
      continue;
2686
16
    }
2687
2
    if (D.isArrayDesignator()) {
2688
2
      AddStmt(E->getArrayIndex(D));
2689
2
      continue;
2690
2
    }
2691
0
    assert(D.isArrayRangeDesignator() && "Unknown designator kind");
2692
0
    AddStmt(E->getArrayRangeEnd(D));
2693
0
    AddStmt(E->getArrayRangeStart(D));
2694
0
  }
2695
14
}
2696
75
void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
2697
75
  EnqueueChildren(E);
2698
75
  AddTypeLoc(E->getTypeInfoAsWritten());
2699
75
}
2700
1
void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
2701
1
  AddStmt(FS->getBody());
2702
1
  AddStmt(FS->getInc());
2703
1
  AddStmt(FS->getCond());
2704
1
  AddDecl(FS->getConditionVariable());
2705
1
  AddStmt(FS->getInit());
2706
1
}
2707
2
void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
2708
2
  WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
2709
2
}
2710
10
void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
2711
10
  AddStmt(If->getElse());
2712
10
  AddStmt(If->getThen());
2713
10
  AddStmt(If->getCond());
2714
10
  AddStmt(If->getInit());
2715
10
  AddDecl(If->getConditionVariable());
2716
10
}
2717
17
void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
2718
  // We care about the syntactic form of the initializer list, only.
2719
17
  if (InitListExpr *Syntactic = IE->getSyntacticForm())
2720
15
    IE = Syntactic;
2721
17
  EnqueueChildren(IE);
2722
17
}
2723
527
void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
2724
527
  WL.push_back(MemberExprParts(M, Parent));
2725
2726
  // If the base of the member access expression is an implicit 'this', don't
2727
  // visit it.
2728
  // FIXME: If we ever want to show these implicit accesses, this will be
2729
  // unfortunate. However, clang_getCursor() relies on this behavior.
2730
527
  if (M->isImplicitAccess())
2731
37
    return;
2732
2733
  // Ignore base anonymous struct/union fields, otherwise they will shadow the
2734
  // real field that we are interested in.
2735
490
  if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
2736
4
    if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
2737
4
      if (FD->isAnonymousStructOrUnion()) {
2738
4
        AddStmt(SubME->getBase());
2739
4
        return;
2740
4
      }
2741
486
    }
2742
4
  }
2743
2744
486
  AddStmt(M->getBase());
2745
486
}
2746
1
void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
2747
1
  AddTypeLoc(E->getEncodedTypeSourceInfo());
2748
1
}
2749
154
void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
2750
154
  EnqueueChildren(M);
2751
154
  AddTypeLoc(M->getClassReceiverTypeInfo());
2752
154
}
2753
1
void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
2754
  // Visit the components of the offsetof expression.
2755
4
  for (unsigned N = E->getNumComponents(), I = N; I > 0; 
--I3
) {
2756
3
    const OffsetOfNode &Node = E->getComponent(I - 1);
2757
3
    switch (Node.getKind()) {
2758
1
    case OffsetOfNode::Array:
2759
1
      AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
2760
1
      break;
2761
2
    case OffsetOfNode::Field:
2762
2
      AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
2763
2
      break;
2764
0
    case OffsetOfNode::Identifier:
2765
0
    case OffsetOfNode::Base:
2766
0
      continue;
2767
3
    }
2768
3
  }
2769
  // Visit the type into which we're computing the offset.
2770
1
  AddTypeLoc(E->getTypeSourceInfo());
2771
1
}
2772
15
void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
2773
15
  if (E->hasExplicitTemplateArgs())
2774
4
    AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
2775
15
  WL.push_back(OverloadExprParts(E, Parent));
2776
15
}
2777
void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
2778
5
    const UnaryExprOrTypeTraitExpr *E) {
2779
5
  EnqueueChildren(E);
2780
5
  if (E->isArgumentType())
2781
5
    AddTypeLoc(E->getArgumentTypeInfo());
2782
5
}
2783
4.67k
void EnqueueVisitor::VisitStmt(const Stmt *S) { EnqueueChildren(S); }
2784
12
void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
2785
12
  AddStmt(S->getBody());
2786
12
  AddStmt(S->getCond());
2787
12
  AddDecl(S->getConditionVariable());
2788
12
}
2789
2790
2
void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
2791
2
  AddStmt(W->getBody());
2792
2
  AddStmt(W->getCond());
2793
2
  AddDecl(W->getConditionVariable());
2794
2
}
2795
2796
6
void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
2797
18
  for (unsigned I = E->getNumArgs(); I > 0; 
--I12
)
2798
12
    AddTypeLoc(E->getArg(I - 1));
2799
6
}
2800
2801
0
void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
2802
0
  AddTypeLoc(E->getQueriedTypeSourceInfo());
2803
0
}
2804
2805
0
void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
2806
0
  EnqueueChildren(E);
2807
0
}
2808
2809
5
void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
2810
5
  VisitOverloadExpr(U);
2811
5
  if (!U->isImplicitAccess())
2812
4
    AddStmt(U->getBase());
2813
5
}
2814
3
void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
2815
3
  AddStmt(E->getSubExpr());
2816
3
  AddTypeLoc(E->getWrittenTypeInfo());
2817
3
}
2818
2
void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
2819
2
  WL.push_back(SizeOfPackExprParts(E, Parent));
2820
2
}
2821
50
void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
2822
  // If the opaque value has a source expression, just transparently
2823
  // visit that.  This is useful for (e.g.) pseudo-object expressions.
2824
50
  if (Expr *SourceExpr = E->getSourceExpr())
2825
48
    return Visit(SourceExpr);
2826
50
}
2827
4
void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
2828
4
  AddStmt(E->getBody());
2829
4
  WL.push_back(LambdaExprParts(E, Parent));
2830
4
}
2831
17
void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
2832
  // Treat the expression like its syntactic form.
2833
17
  Visit(E->getSyntacticForm());
2834
17
}
2835
2836
void EnqueueVisitor::VisitOMPExecutableDirective(
2837
0
    const OMPExecutableDirective *D) {
2838
0
  EnqueueChildren(D);
2839
0
  for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
2840
0
                                       E = D->clauses().end();
2841
0
       I != E; ++I)
2842
0
    EnqueueChildren(*I);
2843
0
}
2844
2845
0
void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
2846
0
  VisitOMPExecutableDirective(D);
2847
0
}
2848
2849
0
void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
2850
0
  VisitOMPExecutableDirective(D);
2851
0
}
2852
2853
0
void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
2854
0
  VisitOMPLoopDirective(D);
2855
0
}
2856
2857
0
void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
2858
0
  VisitOMPLoopDirective(D);
2859
0
}
2860
2861
0
void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
2862
0
  VisitOMPLoopDirective(D);
2863
0
}
2864
2865
0
void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
2866
0
  VisitOMPExecutableDirective(D);
2867
0
}
2868
2869
0
void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
2870
0
  VisitOMPExecutableDirective(D);
2871
0
}
2872
2873
0
void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
2874
0
  VisitOMPExecutableDirective(D);
2875
0
}
2876
2877
0
void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
2878
0
  VisitOMPExecutableDirective(D);
2879
0
}
2880
2881
0
void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
2882
0
  VisitOMPExecutableDirective(D);
2883
0
  AddDeclarationNameInfo(D);
2884
0
}
2885
2886
void EnqueueVisitor::VisitOMPParallelForDirective(
2887
0
    const OMPParallelForDirective *D) {
2888
0
  VisitOMPLoopDirective(D);
2889
0
}
2890
2891
void EnqueueVisitor::VisitOMPParallelForSimdDirective(
2892
0
    const OMPParallelForSimdDirective *D) {
2893
0
  VisitOMPLoopDirective(D);
2894
0
}
2895
2896
void EnqueueVisitor::VisitOMPParallelMasterDirective(
2897
0
    const OMPParallelMasterDirective *D) {
2898
0
  VisitOMPExecutableDirective(D);
2899
0
}
2900
2901
void EnqueueVisitor::VisitOMPParallelSectionsDirective(
2902
0
    const OMPParallelSectionsDirective *D) {
2903
0
  VisitOMPExecutableDirective(D);
2904
0
}
2905
2906
0
void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
2907
0
  VisitOMPExecutableDirective(D);
2908
0
}
2909
2910
void EnqueueVisitor::VisitOMPTaskyieldDirective(
2911
0
    const OMPTaskyieldDirective *D) {
2912
0
  VisitOMPExecutableDirective(D);
2913
0
}
2914
2915
0
void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
2916
0
  VisitOMPExecutableDirective(D);
2917
0
}
2918
2919
0
void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
2920
0
  VisitOMPExecutableDirective(D);
2921
0
}
2922
2923
void EnqueueVisitor::VisitOMPTaskgroupDirective(
2924
0
    const OMPTaskgroupDirective *D) {
2925
0
  VisitOMPExecutableDirective(D);
2926
0
  if (const Expr *E = D->getReductionRef())
2927
0
    VisitStmt(E);
2928
0
}
2929
2930
0
void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
2931
0
  VisitOMPExecutableDirective(D);
2932
0
}
2933
2934
0
void EnqueueVisitor::VisitOMPDepobjDirective(const OMPDepobjDirective *D) {
2935
0
  VisitOMPExecutableDirective(D);
2936
0
}
2937
2938
0
void EnqueueVisitor::VisitOMPScanDirective(const OMPScanDirective *D) {
2939
0
  VisitOMPExecutableDirective(D);
2940
0
}
2941
2942
0
void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
2943
0
  VisitOMPExecutableDirective(D);
2944
0
}
2945
2946
0
void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
2947
0
  VisitOMPExecutableDirective(D);
2948
0
}
2949
2950
0
void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
2951
0
  VisitOMPExecutableDirective(D);
2952
0
}
2953
2954
void EnqueueVisitor::VisitOMPTargetDataDirective(
2955
0
    const OMPTargetDataDirective *D) {
2956
0
  VisitOMPExecutableDirective(D);
2957
0
}
2958
2959
void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
2960
0
    const OMPTargetEnterDataDirective *D) {
2961
0
  VisitOMPExecutableDirective(D);
2962
0
}
2963
2964
void EnqueueVisitor::VisitOMPTargetExitDataDirective(
2965
0
    const OMPTargetExitDataDirective *D) {
2966
0
  VisitOMPExecutableDirective(D);
2967
0
}
2968
2969
void EnqueueVisitor::VisitOMPTargetParallelDirective(
2970
0
    const OMPTargetParallelDirective *D) {
2971
0
  VisitOMPExecutableDirective(D);
2972
0
}
2973
2974
void EnqueueVisitor::VisitOMPTargetParallelForDirective(
2975
0
    const OMPTargetParallelForDirective *D) {
2976
0
  VisitOMPLoopDirective(D);
2977
0
}
2978
2979
0
void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
2980
0
  VisitOMPExecutableDirective(D);
2981
0
}
2982
2983
void EnqueueVisitor::VisitOMPCancellationPointDirective(
2984
0
    const OMPCancellationPointDirective *D) {
2985
0
  VisitOMPExecutableDirective(D);
2986
0
}
2987
2988
0
void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
2989
0
  VisitOMPExecutableDirective(D);
2990
0
}
2991
2992
0
void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
2993
0
  VisitOMPLoopDirective(D);
2994
0
}
2995
2996
void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
2997
0
    const OMPTaskLoopSimdDirective *D) {
2998
0
  VisitOMPLoopDirective(D);
2999
0
}
3000
3001
void EnqueueVisitor::VisitOMPMasterTaskLoopDirective(
3002
0
    const OMPMasterTaskLoopDirective *D) {
3003
0
  VisitOMPLoopDirective(D);
3004
0
}
3005
3006
void EnqueueVisitor::VisitOMPMasterTaskLoopSimdDirective(
3007
0
    const OMPMasterTaskLoopSimdDirective *D) {
3008
0
  VisitOMPLoopDirective(D);
3009
0
}
3010
3011
void EnqueueVisitor::VisitOMPParallelMasterTaskLoopDirective(
3012
0
    const OMPParallelMasterTaskLoopDirective *D) {
3013
0
  VisitOMPLoopDirective(D);
3014
0
}
3015
3016
void EnqueueVisitor::VisitOMPParallelMasterTaskLoopSimdDirective(
3017
0
    const OMPParallelMasterTaskLoopSimdDirective *D) {
3018
0
  VisitOMPLoopDirective(D);
3019
0
}
3020
3021
void EnqueueVisitor::VisitOMPDistributeDirective(
3022
0
    const OMPDistributeDirective *D) {
3023
0
  VisitOMPLoopDirective(D);
3024
0
}
3025
3026
void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
3027
0
    const OMPDistributeParallelForDirective *D) {
3028
0
  VisitOMPLoopDirective(D);
3029
0
}
3030
3031
void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
3032
0
    const OMPDistributeParallelForSimdDirective *D) {
3033
0
  VisitOMPLoopDirective(D);
3034
0
}
3035
3036
void EnqueueVisitor::VisitOMPDistributeSimdDirective(
3037
0
    const OMPDistributeSimdDirective *D) {
3038
0
  VisitOMPLoopDirective(D);
3039
0
}
3040
3041
void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
3042
0
    const OMPTargetParallelForSimdDirective *D) {
3043
0
  VisitOMPLoopDirective(D);
3044
0
}
3045
3046
void EnqueueVisitor::VisitOMPTargetSimdDirective(
3047
0
    const OMPTargetSimdDirective *D) {
3048
0
  VisitOMPLoopDirective(D);
3049
0
}
3050
3051
void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
3052
0
    const OMPTeamsDistributeDirective *D) {
3053
0
  VisitOMPLoopDirective(D);
3054
0
}
3055
3056
void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
3057
0
    const OMPTeamsDistributeSimdDirective *D) {
3058
0
  VisitOMPLoopDirective(D);
3059
0
}
3060
3061
void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective(
3062
0
    const OMPTeamsDistributeParallelForSimdDirective *D) {
3063
0
  VisitOMPLoopDirective(D);
3064
0
}
3065
3066
void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective(
3067
0
    const OMPTeamsDistributeParallelForDirective *D) {
3068
0
  VisitOMPLoopDirective(D);
3069
0
}
3070
3071
void EnqueueVisitor::VisitOMPTargetTeamsDirective(
3072
0
    const OMPTargetTeamsDirective *D) {
3073
0
  VisitOMPExecutableDirective(D);
3074
0
}
3075
3076
void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective(
3077
0
    const OMPTargetTeamsDistributeDirective *D) {
3078
0
  VisitOMPLoopDirective(D);
3079
0
}
3080
3081
void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective(
3082
0
    const OMPTargetTeamsDistributeParallelForDirective *D) {
3083
0
  VisitOMPLoopDirective(D);
3084
0
}
3085
3086
void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
3087
0
    const OMPTargetTeamsDistributeParallelForSimdDirective *D) {
3088
0
  VisitOMPLoopDirective(D);
3089
0
}
3090
3091
void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective(
3092
0
    const OMPTargetTeamsDistributeSimdDirective *D) {
3093
0
  VisitOMPLoopDirective(D);
3094
0
}
3095
3096
12.8k
void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
3097
12.8k
  EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU, RegionOfInterest))
3098
12.8k
      .Visit(S);
3099
12.8k
}
3100
3101
18.3k
bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
3102
18.3k
  if (RegionOfInterest.isValid()) {
3103
13.9k
    SourceRange Range = getRawCursorExtent(C);
3104
13.9k
    if (Range.isInvalid() || 
CompareRegionOfInterest(Range)13.9k
)
3105
1.75k
      return false;
3106
16.5k
  }
3107
16.5k
  return true;
3108
16.5k
}
3109
3110
1.11k
bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
3111
28.0k
  while (!WL.empty()) {
3112
    // Dequeue the worklist item.
3113
26.9k
    VisitorJob LI = WL.pop_back_val();
3114
3115
    // Set the Parent field, then back to its old value once we're done.
3116
26.9k
    SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
3117
3118
26.9k
    switch (LI.getKind()) {
3119
355
    case VisitorJob::DeclVisitKind: {
3120
355
      const Decl *D = cast<DeclVisit>(&LI)->get();
3121
355
      if (!D)
3122
0
        continue;
3123
3124
      // For now, perform default visitation for Decls.
3125
355
      if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
3126
355
                             cast<DeclVisit>(&LI)->isFirst())))
3127
1
        return true;
3128
3129
354
      continue;
3130
354
    }
3131
12
    case VisitorJob::ExplicitTemplateArgsVisitKind: {
3132
12
      for (const TemplateArgumentLoc &Arg :
3133
16
           *cast<ExplicitTemplateArgsVisit>(&LI)) {
3134
16
        if (VisitTemplateArgumentLoc(Arg))
3135
0
          return true;
3136
16
      }
3137
12
      continue;
3138
12
    }
3139
186
    case VisitorJob::TypeLocVisitKind: {
3140
      // Perform default visitation for TypeLocs.
3141
186
      if (Visit(cast<TypeLocVisit>(&LI)->get()))
3142
0
        return true;
3143
186
      continue;
3144
186
    }
3145
3
    case VisitorJob::LabelRefVisitKind: {
3146
3
      const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
3147
3
      if (LabelStmt *stmt = LS->getStmt()) {
3148
2
        if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
3149
0
                                     TU))) {
3150
0
          return true;
3151
0
        }
3152
3
      }
3153
3
      continue;
3154
3
    }
3155
3156
6
    case VisitorJob::NestedNameSpecifierLocVisitKind: {
3157
6
      NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
3158
6
      if (VisitNestedNameSpecifierLoc(V->get()))
3159
0
        return true;
3160
6
      continue;
3161
6
    }
3162
3163
6
    case VisitorJob::DeclarationNameInfoVisitKind: {
3164
6
      if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)->get()))
3165
0
        return true;
3166
6
      continue;
3167
6
    }
3168
18
    case VisitorJob::MemberRefVisitKind: {
3169
18
      MemberRefVisit *V = cast<MemberRefVisit>(&LI);
3170
18
      if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
3171
0
        return true;
3172
18
      continue;
3173
18
    }
3174
18.3k
    case VisitorJob::StmtVisitKind: {
3175
18.3k
      const Stmt *S = cast<StmtVisit>(&LI)->get();
3176
18.3k
      if (!S)
3177
0
        continue;
3178
3179
      // Update the current cursor.
3180
18.3k
      CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
3181
18.3k
      if (!IsInRegionOfInterest(Cursor))
3182
1.75k
        continue;
3183
16.5k
      switch (Visitor(Cursor, Parent, ClientData)) {
3184
1
      case CXChildVisit_Break:
3185
1
        return true;
3186
4.87k
      case CXChildVisit_Continue:
3187
4.87k
        break;
3188
11.7k
      case CXChildVisit_Recurse:
3189
11.7k
        if (PostChildrenVisitor)
3190
6.31k
          WL.push_back(PostChildrenVisit(nullptr, Cursor));
3191
11.7k
        EnqueueWorkList(WL, S);
3192
11.7k
        break;
3193
16.5k
      }
3194
16.5k
      continue;
3195
16.5k
    }
3196
527
    case VisitorJob::MemberExprPartsKind: {
3197
      // Handle the other pieces in the MemberExpr besides the base.
3198
527
      const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
3199
3200
      // Visit the nested-name-specifier
3201
527
      if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
3202
5
        if (VisitNestedNameSpecifierLoc(QualifierLoc))
3203
0
          return true;
3204
3205
      // Visit the declaration name.
3206
527
      if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
3207
0
        return true;
3208
3209
      // Visit the explicitly-specified template arguments, if any.
3210
527
      if (M->hasExplicitTemplateArgs()) {
3211
2
        for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
3212
2
                                       *ArgEnd = Arg + M->getNumTemplateArgs();
3213
4
             Arg != ArgEnd; 
++Arg2
) {
3214
2
          if (VisitTemplateArgumentLoc(*Arg))
3215
0
            return true;
3216
2
        }
3217
2
      }
3218
527
      continue;
3219
527
    }
3220
1.19k
    case VisitorJob::DeclRefExprPartsKind: {
3221
1.19k
      const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
3222
      // Visit nested-name-specifier, if present.
3223
1.19k
      if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
3224
2
        if (VisitNestedNameSpecifierLoc(QualifierLoc))
3225
0
          return true;
3226
      // Visit declaration name.
3227
1.19k
      if (VisitDeclarationNameInfo(DR->getNameInfo()))
3228
0
        return true;
3229
1.19k
      continue;
3230
1.19k
    }
3231
15
    case VisitorJob::OverloadExprPartsKind: {
3232
15
      const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
3233
      // Visit the nested-name-specifier.
3234
15
      if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
3235
5
        if (VisitNestedNameSpecifierLoc(QualifierLoc))
3236
0
          return true;
3237
      // Visit the declaration name.
3238
15
      if (VisitDeclarationNameInfo(O->getNameInfo()))
3239
0
        return true;
3240
      // Visit the overloaded declaration reference.
3241
15
      if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
3242
0
        return true;
3243
15
      continue;
3244
15
    }
3245
2
    case VisitorJob::SizeOfPackExprPartsKind: {
3246
2
      const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
3247
2
      NamedDecl *Pack = E->getPack();
3248
2
      if (isa<TemplateTypeParmDecl>(Pack)) {
3249
1
        if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
3250
1
                                    E->getPackLoc(), TU)))
3251
0
          return true;
3252
3253
1
        continue;
3254
1
      }
3255
3256
1
      if (isa<TemplateTemplateParmDecl>(Pack)) {
3257
0
        if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
3258
0
                                        E->getPackLoc(), TU)))
3259
0
          return true;
3260
3261
0
        continue;
3262
0
      }
3263
3264
      // Non-type template parameter packs and function parameter packs are
3265
      // treated like DeclRefExpr cursors.
3266
1
      continue;
3267
1
    }
3268
3269
4
    case VisitorJob::LambdaExprPartsKind: {
3270
      // Visit non-init captures.
3271
4
      const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
3272
4
      for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
3273
4
                                        CEnd = E->explicit_capture_end();
3274
10
           C != CEnd; 
++C6
) {
3275
6
        if (!C->capturesVariable())
3276
1
          continue;
3277
3278
5
        if (Visit(MakeCursorVariableRef(C->getCapturedVar(), C->getLocation(),
3279
5
                                        TU)))
3280
0
          return true;
3281
5
      }
3282
      // Visit init captures
3283
6
      
for (auto InitExpr : E->capture_inits())4
{
3284
6
        if (InitExpr && 
Visit(InitExpr)5
)
3285
0
          return true;
3286
6
      }
3287
3288
4
      TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
3289
      // Visit parameters and return type, if present.
3290
4
      if (FunctionTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) {
3291
4
        if (E->hasExplicitParameters()) {
3292
          // Visit parameters.
3293
6
          for (unsigned I = 0, N = Proto.getNumParams(); I != N; 
++I3
)
3294
3
            if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
3295
0
              return true;
3296
3
        }
3297
4
        if (E->hasExplicitResultType()) {
3298
          // Visit result type.
3299
2
          if (Visit(Proto.getReturnLoc()))
3300
0
            return true;
3301
4
        }
3302
4
      }
3303
4
      break;
3304
4
    }
3305
3306
6.31k
    case VisitorJob::PostChildrenVisitKind:
3307
6.31k
      if (PostChildrenVisitor(Parent, ClientData))
3308
0
        return true;
3309
6.31k
      break;
3310
26.9k
    }
3311
26.9k
  }
3312
1.10k
  return false;
3313
1.11k
}
3314
3315
1.11k
bool CursorVisitor::Visit(const Stmt *S) {
3316
1.11k
  VisitorWorkList *WL = nullptr;
3317
1.11k
  if (!WorkListFreeList.empty()) {
3318
485
    WL = WorkListFreeList.back();
3319
485
    WL->clear();
3320
485
    WorkListFreeList.pop_back();
3321
625
  } else {
3322
625
    WL = new VisitorWorkList();
3323
625
    WorkListCache.push_back(WL);
3324
625
  }
3325
1.11k
  EnqueueWorkList(*WL, S);
3326
1.11k
  bool result = RunVisitorWorkList(*WL);
3327
1.11k
  WorkListFreeList.push_back(WL);
3328
1.11k
  return result;
3329
1.11k
}
3330
3331
namespace {
3332
typedef SmallVector<SourceRange, 4> RefNamePieces;
3333
RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
3334
                          const DeclarationNameInfo &NI, SourceRange QLoc,
3335
65.9k
                          const SourceRange *TemplateArgsLoc = nullptr) {
3336
65.9k
  const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
3337
65.9k
  const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
3338
65.9k
  const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
3339
3340
65.9k
  const DeclarationName::NameKind Kind = NI.getName().getNameKind();
3341
3342
65.9k
  RefNamePieces Pieces;
3343
3344
65.9k
  if (WantQualifier && QLoc.isValid())
3345
86
    Pieces.push_back(QLoc);
3346
3347
65.9k
  if (Kind != DeclarationName::CXXOperatorName || 
IsMemberRefExpr60.6k
)
3348
5.33k
    Pieces.push_back(NI.getLoc());
3349
3350
65.9k
  if (WantTemplateArgs && 
TemplateArgsLoc51.3k
&&
TemplateArgsLoc->isValid()49.0k
)
3351
20
    Pieces.push_back(*TemplateArgsLoc);
3352
3353
65.9k
  if (Kind == DeclarationName::CXXOperatorName) {
3354
60.6k
    Pieces.push_back(SourceLocation::getFromRawEncoding(
3355
60.6k
        NI.getInfo().CXXOperatorName.BeginOpNameLoc));
3356
60.6k
    Pieces.push_back(SourceLocation::getFromRawEncoding(
3357
60.6k
        NI.getInfo().CXXOperatorName.EndOpNameLoc));
3358
60.6k
  }
3359
3360
65.9k
  if (WantSinglePiece) {
3361
13.2k
    SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
3362
13.2k
    Pieces.clear();
3363
13.2k
    Pieces.push_back(R);
3364
13.2k
  }
3365
3366
65.9k
  return Pieces;
3367
65.9k
}
3368
} // namespace
3369
3370
//===----------------------------------------------------------------------===//
3371
// Misc. API hooks.
3372
//===----------------------------------------------------------------------===//
3373
3374
namespace {
3375
struct RegisterFatalErrorHandler {
3376
1.05k
  RegisterFatalErrorHandler() {
3377
1.05k
    clang_install_aborting_llvm_fatal_error_handler();
3378
1.05k
  }
3379
};
3380
} // namespace
3381
3382
static llvm::ManagedStatic<RegisterFatalErrorHandler>
3383
    RegisterFatalErrorHandlerOnce;
3384
3385
CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
3386
1.05k
                          int displayDiagnostics) {
3387
  // We use crash recovery to make some of our APIs more reliable, implicitly
3388
  // enable it.
3389
1.05k
  if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
3390
1.05k
    llvm::CrashRecoveryContext::Enable();
3391
3392
  // Look through the managed static to trigger construction of the managed
3393
  // static which registers our fatal error handler. This ensures it is only
3394
  // registered once.
3395
1.05k
  (void)*RegisterFatalErrorHandlerOnce;
3396
3397
  // Initialize targets for clang module support.
3398
1.05k
  llvm::InitializeAllTargets();
3399
1.05k
  llvm::InitializeAllTargetMCs();
3400
1.05k
  llvm::InitializeAllAsmPrinters();
3401
1.05k
  llvm::InitializeAllAsmParsers();
3402
3403
1.05k
  CIndexer *CIdxr = new CIndexer();
3404
3405
1.05k
  if (excludeDeclarationsFromPCH)
3406
279
    CIdxr->setOnlyLocalDecls();
3407
1.05k
  if (displayDiagnostics)
3408
499
    CIdxr->setDisplayDiagnostics();
3409
3410
1.05k
  if (getenv("LIBCLANG_BGPRIO_INDEX"))
3411
0
    CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3412
0
                               CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
3413
1.05k
  if (getenv("LIBCLANG_BGPRIO_EDIT"))
3414
0
    CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
3415
0
                               CXGlobalOpt_ThreadBackgroundPriorityForEditing);
3416
3417
1.05k
  return CIdxr;
3418
1.05k
}
3419
3420
1.05k
void clang_disposeIndex(CXIndex CIdx) {
3421
1.05k
  if (CIdx)
3422
1.05k
    delete static_cast<CIndexer *>(CIdx);
3423
1.05k
}
3424
3425
0
void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
3426
0
  if (CIdx)
3427
0
    static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
3428
0
}
3429
3430
0
unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
3431
0
  if (CIdx)
3432
0
    return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
3433
0
  return 0;
3434
0
}
3435
3436
void clang_CXIndex_setInvocationEmissionPathOption(CXIndex CIdx,
3437
7
                                                   const char *Path) {
3438
7
  if (CIdx)
3439
7
    static_cast<CIndexer *>(CIdx)->setInvocationEmissionPath(Path ? Path : 
""0
);
3440
7
}
3441
3442
2
void clang_toggleCrashRecovery(unsigned isEnabled) {
3443
2
  if (isEnabled)
3444
0
    llvm::CrashRecoveryContext::Enable();
3445
2
  else
3446
2
    llvm::CrashRecoveryContext::Disable();
3447
2
}
3448
3449
CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
3450
2
                                              const char *ast_filename) {
3451
2
  CXTranslationUnit TU;
3452
2
  enum CXErrorCode Result =
3453
2
      clang_createTranslationUnit2(CIdx, ast_filename, &TU);
3454
2
  (void)Result;
3455
2
  assert((TU && Result == CXError_Success) ||
3456
2
         (!TU && Result != CXError_Success));
3457
2
  return TU;
3458
2
}
3459
3460
enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
3461
                                              const char *ast_filename,
3462
36
                                              CXTranslationUnit *out_TU) {
3463
36
  if (out_TU)
3464
35
    *out_TU = nullptr;
3465
3466
36
  if (!CIdx || 
!ast_filename33
||
!out_TU33
)
3467
3
    return CXError_InvalidArguments;
3468
3469
33
  LOG_FUNC_SECTION 
{ *Log << ast_filename; }0
3470
3471
33
  CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3472
33
  FileSystemOptions FileSystemOpts;
3473
3474
33
  IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
3475
33
      CompilerInstance::createDiagnostics(new DiagnosticOptions());
3476
33
  std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
3477
33
      ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(),
3478
33
      ASTUnit::LoadEverything, Diags, FileSystemOpts, /*UseDebugInfo=*/false,
3479
33
      CXXIdx->getOnlyLocalDecls(), CaptureDiagsKind::All,
3480
33
      /*AllowASTWithCompilerErrors=*/true,
3481
33
      /*UserFilesAreVolatile=*/true);
3482
33
  *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU));
3483
32
  return *out_TU ? CXError_Success : 
CXError_Failure1
;
3484
33
}
3485
3486
126
unsigned clang_defaultEditingTranslationUnitOptions() {
3487
126
  return CXTranslationUnit_PrecompiledPreamble |
3488
126
         CXTranslationUnit_CacheCompletionResults;
3489
126
}
3490
3491
CXTranslationUnit clang_createTranslationUnitFromSourceFile(
3492
    CXIndex CIdx, const char *source_filename, int num_command_line_args,
3493
    const char *const *command_line_args, unsigned num_unsaved_files,
3494
0
    struct CXUnsavedFile *unsaved_files) {
3495
0
  unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
3496
0
  return clang_parseTranslationUnit(CIdx, source_filename, command_line_args,
3497
0
                                    num_command_line_args, unsaved_files,
3498
0
                                    num_unsaved_files, Options);
3499
0
}
3500
3501
static CXErrorCode
3502
clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
3503
                                const char *const *command_line_args,
3504
                                int num_command_line_args,
3505
                                ArrayRef<CXUnsavedFile> unsaved_files,
3506
989
                                unsigned options, CXTranslationUnit *out_TU) {
3507
  // Set up the initial return values.
3508
989
  if (out_TU)
3509
988
    *out_TU = nullptr;
3510
3511
  // Check arguments.
3512
989
  if (!CIdx || 
!out_TU988
)
3513
1
    return CXError_InvalidArguments;
3514
3515
988
  CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
3516
3517
988
  if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
3518
0
    setThreadBackgroundPriority();
3519
3520
988
  bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
3521
988
  bool CreatePreambleOnFirstParse =
3522
988
      options & CXTranslationUnit_CreatePreambleOnFirstParse;
3523
  // FIXME: Add a flag for modules.
3524
988
  TranslationUnitKind TUKind = (options & (CXTranslationUnit_Incomplete |
3525
988
                                           CXTranslationUnit_SingleFileParse))
3526
61
                                   ? TU_Prefix
3527
927
                                   : TU_Complete;
3528
988
  bool CacheCodeCompletionResults =
3529
988
      options & CXTranslationUnit_CacheCompletionResults;
3530
988
  bool IncludeBriefCommentsInCodeCompletion =
3531
988
      options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
3532
988
  bool SingleFileParse = options & CXTranslationUnit_SingleFileParse;
3533
988
  bool ForSerialization = options & CXTranslationUnit_ForSerialization;
3534
988
  bool RetainExcludedCB =
3535
988
      options & CXTranslationUnit_RetainExcludedConditionalBlocks;
3536
988
  SkipFunctionBodiesScope SkipFunctionBodies = SkipFunctionBodiesScope::None;
3537
988
  if (options & CXTranslationUnit_SkipFunctionBodies) {
3538
6
    SkipFunctionBodies =
3539
6
        (options & CXTranslationUnit_LimitSkipFunctionBodiesToPreamble)
3540
1
            ? SkipFunctionBodiesScope::Preamble
3541
5
            : SkipFunctionBodiesScope::PreambleAndMainFile;
3542
6
  }
3543
3544
  // Configure the diagnostics.
3545
988
  IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
3546
988
      CompilerInstance::createDiagnostics(new DiagnosticOptions));
3547
3548
988
  if (options & CXTranslationUnit_KeepGoing)
3549
5
    Diags->setFatalsAsError(true);
3550
3551
988
  CaptureDiagsKind CaptureDiagnostics = CaptureDiagsKind::All;
3552
988
  if (options & CXTranslationUnit_IgnoreNonErrorsFromIncludedFiles)
3553
1
    CaptureDiagnostics = CaptureDiagsKind::AllWithoutNonErrorsFromIncludes;
3554
3555
  // Recover resources if we crash before exiting this function.
3556
988
  llvm::CrashRecoveryContextCleanupRegistrar<
3557
988
      DiagnosticsEngine,
3558
988
      llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
3559
988
      DiagCleanup(Diags.get());
3560
3561
988
  std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
3562
988
      new std::vector<ASTUnit::RemappedFile>());
3563
3564
  // Recover resources if we crash before exiting this function.
3565
988
  llvm::CrashRecoveryContextCleanupRegistrar<std::vector<ASTUnit::RemappedFile>>
3566
988
      RemappedCleanup(RemappedFiles.get());
3567
3568
4
  for (auto &UF : unsaved_files) {
3569
4
    std::unique_ptr<llvm::MemoryBuffer> MB =
3570
4
        llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
3571
4
    RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
3572
4
  }
3573
3574
988
  std::unique_ptr<std::vector<const char *>> Args(
3575
988
      new std::vector<const char *>());
3576
3577
  // Recover resources if we crash before exiting this method.
3578
988
  llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char *>>
3579
988
      ArgsCleanup(Args.get());
3580
3581
  // Since the Clang C library is primarily used by batch tools dealing with
3582
  // (often very broken) source code, where spell-checking can have a
3583
  // significant negative impact on performance (particularly when
3584
  // precompiled headers are involved), we disable it by default.
3585
  // Only do this if we haven't found a spell-checking-related argument.
3586
988
  bool FoundSpellCheckingArgument = false;
3587
3.75k
  for (int I = 0; I != num_command_line_args; 
++I2.76k
) {
3588
2.76k
    if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
3589
2.76k
        strcmp(command_line_args[I], "-fspell-checking") == 0) {
3590
2
      FoundSpellCheckingArgument = true;
3591
2
      break;
3592
2
    }
3593
2.76k
  }
3594
988
  Args->insert(Args->end(), command_line_args,
3595
988
               command_line_args + num_command_line_args);
3596
3597
988
  if (!FoundSpellCheckingArgument)
3598
986
    Args->insert(Args->begin() + 1, "-fno-spell-checking");
3599
3600
  // The 'source_filename' argument is optional.  If the caller does not
3601
  // specify it then it is assumed that the source file is specified
3602
  // in the actual argument list.
3603
  // Put the source file after command_line_args otherwise if '-x' flag is
3604
  // present it will be unused.
3605
988
  if (source_filename)
3606
213
    Args->push_back(source_filename);
3607
3608
  // Do we need the detailed preprocessing record?
3609
988
  if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
3610
986
    Args->push_back("-Xclang");
3611
986
    Args->push_back("-detailed-preprocessing-record");
3612
986
  }
3613
3614
  // Suppress any editor placeholder diagnostics.
3615
988
  Args->push_back("-fallow-editor-placeholders");
3616
3617
988
  unsigned NumErrors = Diags->getClient()->getNumErrors();
3618
988
  std::unique_ptr<ASTUnit> ErrUnit;
3619
  // Unless the user specified that they want the preamble on the first parse
3620
  // set it up to be created on the first reparse. This makes the first parse
3621
  // faster, trading for a slower (first) reparse.
3622
988
  unsigned PrecompilePreambleAfterNParses =
3623
862
      !PrecompilePreamble ? 0 : 
2 - CreatePreambleOnFirstParse126
;
3624
3625
988
  LibclangInvocationReporter InvocationReporter(
3626
988
      *CXXIdx, LibclangInvocationReporter::OperationKind::ParseOperation,
3627
988
      options, llvm::makeArrayRef(*Args), /*InvocationArgs=*/None,
3628
988
      unsaved_files);
3629
988
  std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
3630
988
      Args->data(), Args->data() + Args->size(),
3631
988
      CXXIdx->getPCHContainerOperations(), Diags,
3632
988
      CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
3633
988
      CaptureDiagnostics, *RemappedFiles.get(),
3634
988
      /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
3635
988
      TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
3636
988
      /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, SingleFileParse,
3637
988
      /*UserFilesAreVolatile=*/true, ForSerialization, RetainExcludedCB,
3638
988
      CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
3639
988
      &ErrUnit));
3640
3641
  // Early failures in LoadFromCommandLine may return with ErrUnit unset.
3642
988
  if (!Unit && 
!ErrUnit2
)
3643
0
    return CXError_ASTReadError;
3644
3645
988
  if (NumErrors != Diags->getClient()->getNumErrors()) {
3646
    // Make sure to check that 'Unit' is non-NULL.
3647
428
    if (CXXIdx->getDisplayDiagnostics())
3648
69
      printDiagsToStderr(Unit ? 
Unit.get()67
:
ErrUnit.get()2
);
3649
428
  }
3650
3651
988
  if (isASTReadError(Unit ? 
Unit.get()979
:
ErrUnit.get()9
))
3652
2
    return CXError_ASTReadError;
3653
3654
986
  *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit));
3655
986
  if (CXTranslationUnitImpl *TU = *out_TU) {
3656
978
    TU->ParsingOptions = options;
3657
978
    TU->Arguments.reserve(Args->size());
3658
978
    for (const char *Arg : *Args)
3659
6.83k
      TU->Arguments.push_back(Arg);
3660
978
    return CXError_Success;
3661
978
  }
3662
8
  return CXError_Failure;
3663
8
}
3664
3665
CXTranslationUnit
3666
clang_parseTranslationUnit(CXIndex CIdx, const char *source_filename,
3667
                           const char *const *command_line_args,
3668
                           int num_command_line_args,
3669
                           struct CXUnsavedFile *unsaved_files,
3670
20
                           unsigned num_unsaved_files, unsigned options) {
3671
20
  CXTranslationUnit TU;
3672
20
  enum CXErrorCode Result = clang_parseTranslationUnit2(
3673
20
      CIdx, source_filename, command_line_args, num_command_line_args,
3674
20
      unsaved_files, num_unsaved_files, options, &TU);
3675
20
  (void)Result;
3676
20
  assert((TU && Result == CXError_Success) ||
3677
20
         (!TU && Result != CXError_Success));
3678
20
  return TU;
3679
20
}
3680
3681
enum CXErrorCode clang_parseTranslationUnit2(
3682
    CXIndex CIdx, const char *source_filename,
3683
    const char *const *command_line_args, int num_command_line_args,
3684
    struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3685
988
    unsigned options, CXTranslationUnit *out_TU) {
3686
988
  noteBottomOfStack();
3687
988
  SmallVector<const char *, 4> Args;
3688
988
  Args.push_back("clang");
3689
988
  Args.append(command_line_args, command_line_args + num_command_line_args);
3690
988
  return clang_parseTranslationUnit2FullArgv(
3691
988
      CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
3692
988
      num_unsaved_files, options, out_TU);
3693
988
}
3694
3695
enum CXErrorCode clang_parseTranslationUnit2FullArgv(
3696
    CXIndex CIdx, const char *source_filename,
3697
    const char *const *command_line_args, int num_command_line_args,
3698
    struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
3699
989
    unsigned options, CXTranslationUnit *out_TU) {
3700
989
  LOG_FUNC_SECTION {
3701
0
    *Log << source_filename << ": ";
3702
0
    for (int i = 0; i != num_command_line_args; ++i)
3703
0
      *Log << command_line_args[i] << " ";
3704
0
  }
3705
3706
989
  if (num_unsaved_files && 
!unsaved_files4
)
3707
0
    return CXError_InvalidArguments;
3708
3709
989
  CXErrorCode result = CXError_Failure;
3710
989
  auto ParseTranslationUnitImpl = [=, &result] {
3711
989
    noteBottomOfStack();
3712
989
    result = clang_parseTranslationUnit_Impl(
3713
989
        CIdx, source_filename, command_line_args, num_command_line_args,
3714
989
        llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
3715
989
  };
3716
3717
989
  llvm::CrashRecoveryContext CRC;
3718
3719
989
  if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
3720
7
    fprintf(stderr, "libclang: crash detected during parsing: {\n");
3721
7
    fprintf(stderr, "  'source_filename' : '%s'\n", source_filename);
3722
7
    fprintf(stderr, "  'command_line_args' : [");
3723
36
    for (int i = 0; i != num_command_line_args; 
++i29
) {
3724
29
      if (i)
3725
22
        fprintf(stderr, ", ");
3726
29
      fprintf(stderr, "'%s'", command_line_args[i]);
3727
29
    }
3728
7
    fprintf(stderr, "],\n");
3729
7
    fprintf(stderr, "  'unsaved_files' : [");
3730
9
    for (unsigned i = 0; i != num_unsaved_files; 
++i2
) {
3731
2
      if (i)
3732
0
        fprintf(stderr, ", ");
3733
2
      fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
3734
2
              unsaved_files[i].Length);
3735
2
    }
3736
7
    fprintf(stderr, "],\n");
3737
7
    fprintf(stderr, "  'options' : %d,\n", options);
3738
7
    fprintf(stderr, "}\n");
3739
3740
7
    return CXError_Crashed;
3741
982
  } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
3742
0
    if (CXTranslationUnit *TU = out_TU)
3743
0
      PrintLibclangResourceUsage(*TU);
3744
0
  }
3745
3746
982
  return result;
3747
989
}
3748
3749
0
CXString clang_Type_getObjCEncoding(CXType CT) {
3750
0
  CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
3751
0
  ASTContext &Ctx = getASTUnit(tu)->getASTContext();
3752
0
  std::string encoding;
3753
0
  Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]), encoding);
3754
3755
0
  return cxstring::createDup(encoding);
3756
0
}
3757
3758
5
static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
3759
5
  if (C.kind == CXCursor_MacroDefinition) {
3760
2
    if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
3761
2
      return MDR->getName();
3762
3
  } else if (C.kind == CXCursor_MacroExpansion) {
3763
3
    MacroExpansionCursor ME = getCursorMacroExpansion(C);
3764
3
    return ME.getName();
3765
3
  }
3766
0
  return nullptr;
3767
0
}
3768
3769
2
unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
3770
2
  const IdentifierInfo *II = getMacroIdentifier(C);
3771
2
  if (!II) {
3772
0
    return false;
3773
0
  }
3774
2
  ASTUnit *ASTU = getCursorASTUnit(C);
3775
2
  Preprocessor &PP = ASTU->getPreprocessor();
3776
2
  if (const MacroInfo *MI = PP.getMacroInfo(II))
3777
2
    return MI->isFunctionLike();
3778
0
  return false;
3779
0
}
3780
3781
3
unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
3782
3
  const IdentifierInfo *II = getMacroIdentifier(C);
3783
3
  if (!II) {
3784
0
    return false;
3785
0
  }
3786
3
  ASTUnit *ASTU = getCursorASTUnit(C);
3787
3
  Preprocessor &PP = ASTU->getPreprocessor();
3788
3
  if (const MacroInfo *MI = PP.getMacroInfo(II))
3789
3
    return MI->isBuiltinMacro();
3790
0
  return false;
3791
0
}
3792
3793
0
unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
3794
0
  const Decl *D = getCursorDecl(C);
3795
0
  const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
3796
0
  if (!FD) {
3797
0
    return false;
3798
0
  }
3799
0
  return FD->isInlined();
3800
0
}
3801
3802
0
static StringLiteral *getCFSTR_value(CallExpr *callExpr) {
3803
0
  if (callExpr->getNumArgs() != 1) {
3804
0
    return nullptr;
3805
0
  }
3806
3807
0
  StringLiteral *S = nullptr;
3808
0
  auto *arg = callExpr->getArg(0);
3809
0
  if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
3810
0
    ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
3811
0
    auto *subExpr = I->getSubExprAsWritten();
3812
3813
0
    if (subExpr->getStmtClass() != Stmt::StringLiteralClass) {
3814
0
      return nullptr;
3815
0
    }
3816
3817
0
    S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
3818
0
  } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
3819
0
    S = static_cast<StringLiteral *>(callExpr->getArg(0));
3820
0
  } else {
3821
0
    return nullptr;
3822
0
  }
3823
0
  return S;
3824
0
}
3825
3826
struct ExprEvalResult {
3827
  CXEvalResultKind EvalType;
3828
  union {
3829
    unsigned long long unsignedVal;
3830
    long long intVal;
3831
    double floatVal;
3832
    char *stringVal;
3833
  } EvalData;
3834
  bool IsUnsignedInt;
3835
13
  ~ExprEvalResult() {
3836
13
    if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
3837
13
        EvalType != CXEval_Int) {
3838
1
      delete[] EvalData.stringVal;
3839
1
    }
3840
13
  }
3841
};
3842
3843
13
void clang_EvalResult_dispose(CXEvalResult E) {
3844
13
  delete static_cast<ExprEvalResult *>(E);
3845
13
}
3846
3847
13
CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
3848
13
  if (!E) {
3849
0
    return CXEval_UnExposed;
3850
0
  }
3851
13
  return ((ExprEvalResult *)E)->EvalType;
3852
13
}
3853
3854
0
int clang_EvalResult_getAsInt(CXEvalResult E) {
3855
0
  return clang_EvalResult_getAsLongLong(E);
3856
0
}
3857
3858
5
long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
3859
5
  if (!E) {
3860
0
    return 0;
3861
0
  }
3862
5
  ExprEvalResult *Result = (ExprEvalResult *)E;
3863
5
  if (Result->IsUnsignedInt)
3864
0
    return Result->EvalData.unsignedVal;
3865
5
  return Result->EvalData.intVal;
3866
5
}
3867
3868
12
unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
3869
12
  return ((ExprEvalResult *)E)->IsUnsignedInt;
3870
12
}
3871
3872
7
unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
3873
7
  if (!E) {
3874
0
    return 0;
3875
0
  }
3876
3877
7
  ExprEvalResult *Result = (ExprEvalResult *)E;
3878
7
  if (Result->IsUnsignedInt)
3879
7
    return Result->EvalData.unsignedVal;
3880
0
  return Result->EvalData.intVal;
3881
0
}
3882
3883
0
double clang_EvalResult_getAsDouble(CXEvalResult E) {
3884
0
  if (!E) {
3885
0
    return 0;
3886
0
  }
3887
0
  return ((ExprEvalResult *)E)->EvalData.floatVal;
3888
0
}
3889
3890
0
const char *clang_EvalResult_getAsStr(CXEvalResult E) {
3891
0
  if (!E) {
3892
0
    return nullptr;
3893
0
  }
3894
0
  return ((ExprEvalResult *)E)->EvalData.stringVal;
3895
0
}
3896
3897
14
static const ExprEvalResult *evaluateExpr(Expr *expr, CXCursor C) {
3898
14
  Expr::EvalResult ER;
3899
14
  ASTContext &ctx = getCursorContext(C);
3900
14
  if (!expr)
3901
0
    return nullptr;
3902
3903
14
  expr = expr->IgnoreParens();
3904
14
  if (expr->isValueDependent())
3905
1
    return nullptr;
3906
13
  if (!expr->EvaluateAsRValue(ER, ctx))
3907
0
    return nullptr;
3908
3909
13
  QualType rettype;
3910
13
  CallExpr *callExpr;
3911
13
  auto result = std::make_unique<ExprEvalResult>();
3912
13
  result->EvalType = CXEval_UnExposed;
3913
13
  result->IsUnsignedInt = false;
3914
3915
13
  if (ER.Val.isInt()) {
3916
12
    result->EvalType = CXEval_Int;
3917
3918
12
    auto &val = ER.Val.getInt();
3919
12
    if (val.isUnsigned()) {
3920
7
      result->IsUnsignedInt = true;
3921
7
      result->EvalData.unsignedVal = val.getZExtValue();
3922
5
    } else {
3923
5
      result->EvalData.intVal = val.getExtValue();
3924
5
    }
3925
3926
12
    return result.release();
3927
12
  }
3928
3929
1
  if (ER.Val.isFloat()) {
3930
0
    llvm::SmallVector<char, 100> Buffer;
3931
0
    ER.Val.getFloat().toString(Buffer);
3932
0
    std::string floatStr(Buffer.data(), Buffer.size());
3933
0
    result->EvalType = CXEval_Float;
3934
0
    bool ignored;
3935
0
    llvm::APFloat apFloat = ER.Val.getFloat();
3936
0
    apFloat.convert(llvm::APFloat::IEEEdouble(),
3937
0
                    llvm::APFloat::rmNearestTiesToEven, &ignored);
3938
0
    result->EvalData.floatVal = apFloat.convertToDouble();
3939
0
    return result.release();
3940
0
  }
3941
3942
1
  if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
3943
0
    const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
3944
0
    auto *subExpr = I->getSubExprAsWritten();
3945
0
    if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
3946
0
        subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
3947
0
      const StringLiteral *StrE = nullptr;
3948
0
      const ObjCStringLiteral *ObjCExpr;
3949
0
      ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
3950
3951
0
      if (ObjCExpr) {
3952
0
        StrE = ObjCExpr->getString();
3953
0
        result->EvalType = CXEval_ObjCStrLiteral;
3954
0
      } else {
3955
0
        StrE = cast<StringLiteral>(I->getSubExprAsWritten());
3956
0
        result->EvalType = CXEval_StrLiteral;
3957
0
      }
3958
3959
0
      std::string strRef(StrE->getString().str());
3960
0
      result->EvalData.stringVal = new char[strRef.size() + 1];
3961
0
      strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
3962
0
              strRef.size());
3963
0
      result->EvalData.stringVal[strRef.size()] = '\0';
3964
0
      return result.release();
3965
0
    }
3966
1
  } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
3967
1
             
expr->getStmtClass() == Stmt::StringLiteralClass0
) {
3968
1
    const StringLiteral *StrE = nullptr;
3969
1
    const ObjCStringLiteral *ObjCExpr;
3970
1
    ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
3971
3972
1
    if (ObjCExpr) {
3973
1
      StrE = ObjCExpr->getString();
3974
1
      result->EvalType = CXEval_ObjCStrLiteral;
3975
0
    } else {
3976
0
      StrE = cast<StringLiteral>(expr);
3977
0
      result->EvalType = CXEval_StrLiteral;
3978
0
    }
3979
3980
1
    std::string strRef(StrE->getString().str());
3981
1
    result->EvalData.stringVal = new char[strRef.size() + 1];
3982
1
    strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
3983
1
    result->EvalData.stringVal[strRef.size()] = '\0';
3984
1
    return result.release();
3985
1
  }
3986
3987
0
  if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
3988
0
    CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
3989
3990
0
    rettype = CC->getType();
3991
0
    if (rettype.getAsString() == "CFStringRef" &&
3992
0
        CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
3993
3994
0
      callExpr = static_cast<CallExpr *>(CC->getSubExpr());
3995
0
      StringLiteral *S = getCFSTR_value(callExpr);
3996
0
      if (S) {
3997
0
        std::string strLiteral(S->getString().str());
3998
0
        result->EvalType = CXEval_CFStr;
3999
4000
0
        result->EvalData.stringVal = new char[strLiteral.size() + 1];
4001
0
        strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
4002
0
                strLiteral.size());
4003
0
        result->EvalData.stringVal[strLiteral.size()] = '\0';
4004
0
        return result.release();
4005
0
      }
4006
0
    }
4007
4008
0
  } else if (expr->getStmtClass() == Stmt::CallExprClass) {
4009
0
    callExpr = static_cast<CallExpr *>(expr);
4010
0
    rettype = callExpr->getCallReturnType(ctx);
4011
4012
0
    if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
4013
0
      return nullptr;
4014
4015
0
    if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
4016
0
      if (callExpr->getNumArgs() == 1 &&
4017
0
          !callExpr->getArg(0)->getType()->isIntegralType(ctx))
4018
0
        return nullptr;
4019
0
    } else if (rettype.getAsString() == "CFStringRef") {
4020
4021
0
      StringLiteral *S = getCFSTR_value(callExpr);
4022
0
      if (S) {
4023
0
        std::string strLiteral(S->getString().str());
4024
0
        result->EvalType = CXEval_CFStr;
4025
0
        result->EvalData.stringVal = new char[strLiteral.size() + 1];
4026
0
        strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
4027
0
                strLiteral.size());
4028
0
        result->EvalData.stringVal[strLiteral.size()] = '\0';
4029
0
        return result.release();
4030
0
      }
4031
0
    }
4032
0
  } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
4033
0
    DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
4034
0
    ValueDecl *V = D->getDecl();
4035
0
    if (V->getKind() == Decl::Function) {
4036
0
      std::string strName = V->getNameAsString();
4037
0
      result->EvalType = CXEval_Other;
4038
0
      result->EvalData.stringVal = new char[strName.size() + 1];
4039
0
      strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
4040
0
      result->EvalData.stringVal[strName.size()] = '\0';
4041
0
      return result.release();
4042
0
    }
4043
0
  }
4044
4045
0
  return nullptr;
4046
0
}
4047
4048
9
static const Expr *evaluateDeclExpr(const Decl *D) {
4049
9
  if (!D)
4050
0
    return nullptr;
4051
9
  if (auto *Var = dyn_cast<VarDecl>(D))
4052
8
    return Var->getInit();
4053
1
  else if (auto *Field = dyn_cast<FieldDecl>(D))
4054
1
    return Field->getInClassInitializer();
4055
0
  return nullptr;
4056
0
}
4057
4058
1
static const Expr *evaluateCompoundStmtExpr(const CompoundStmt *CS) {
4059
1
  assert(CS && "invalid compound statement");
4060
1
  for (auto *bodyIterator : CS->body()) {
4061
1
    if (const auto *E = dyn_cast<Expr>(bodyIterator))
4062
1
      return E;
4063
1
  }
4064
0
  return nullptr;
4065
1
}
4066
4067
15
CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
4068
15
  const Expr *E = nullptr;
4069
15
  if (clang_getCursorKind(C) == CXCursor_CompoundStmt)
4070
1
    E = evaluateCompoundStmtExpr(cast<CompoundStmt>(getCursorStmt(C)));
4071
14
  else if (clang_isDeclaration(C.kind))
4072
9
    E = evaluateDeclExpr(getCursorDecl(C));
4073
5
  else if (clang_isExpression(C.kind))
4074
4
    E = getCursorExpr(C);
4075
15
  if (E)
4076
14
    return const_cast<CXEvalResult>(
4077
14
        reinterpret_cast<const void *>(evaluateExpr(const_cast<Expr *>(E), C)));
4078
1
  return nullptr;
4079
1
}
4080
4081
0
unsigned clang_Cursor_hasAttrs(CXCursor C) {
4082
0
  const Decl *D = getCursorDecl(C);
4083
0
  if (!D) {
4084
0
    return 0;
4085
0
  }
4086
4087
0
  if (D->hasAttrs()) {
4088
0
    return 1;
4089
0
  }
4090
4091
0
  return 0;
4092
0
}
4093
59
unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
4094
59
  return CXSaveTranslationUnit_None;
4095
59
}
4096
4097
static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
4098
                                                  const char *FileName,
4099
59
                                                  unsigned options) {
4100
59
  CIndexer *CXXIdx = TU->CIdx;
4101
59
  if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
4102
0
    setThreadBackgroundPriority();
4103
4104
59
  bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
4105
59
  return hadError ? 
CXSaveError_Unknown0
: CXSaveError_None;
4106
59
}
4107
4108
int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
4109
59
                              unsigned options) {
4110
59
  LOG_FUNC_SECTION 
{ *Log << TU << ' ' << FileName; }0
4111
4112
59
  if (isNotUsableTU(TU)) {
4113
0
    LOG_BAD_TU(TU);
4114
0
    return CXSaveError_InvalidTU;
4115
0
  }
4116
4117
59
  ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4118
59
  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4119
59
  if (!CXXUnit->hasSema())
4120
0
    return CXSaveError_InvalidTU;
4121
4122
59
  CXSaveError result;
4123
59
  auto SaveTranslationUnitImpl = [=, &result]() {
4124
59
    result = clang_saveTranslationUnit_Impl(TU, FileName, options);
4125
59
  };
4126
4127
59
  if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred()) {
4128
54
    SaveTranslationUnitImpl();
4129
4130
54
    if (getenv("LIBCLANG_RESOURCE_USAGE"))
4131
0
      PrintLibclangResourceUsage(TU);
4132
4133
54
    return result;
4134
54
  }
4135
4136
  // We have an AST that has invalid nodes due to compiler errors.
4137
  // Use a crash recovery thread for protection.
4138
4139
5
  llvm::CrashRecoveryContext CRC;
4140
4141
5
  if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
4142
0
    fprintf(stderr, "libclang: crash detected during AST saving: {\n");
4143
0
    fprintf(stderr, "  'filename' : '%s'\n", FileName);
4144
0
    fprintf(stderr, "  'options' : %d,\n", options);
4145
0
    fprintf(stderr, "}\n");
4146
4147
0
    return CXSaveError_Unknown;
4148
4149
5
  } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
4150
0
    PrintLibclangResourceUsage(TU);
4151
0
  }
4152
4153
5
  return result;
4154
5
}
4155
4156
1.04k
void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
4157
1.04k
  if (CTUnit) {
4158
    // If the translation unit has been marked as unsafe to free, just discard
4159
    // it.
4160
1.04k
    ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4161
1.04k
    if (Unit && Unit->isUnsafeToFree())
4162
1
      return;
4163
4164
1.04k
    delete cxtu::getASTUnit(CTUnit);
4165
1.04k
    delete CTUnit->StringPool;
4166
1.04k
    delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
4167
1.04k
    disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
4168
1.04k
    delete CTUnit->CommentToXML;
4169
1.04k
    delete CTUnit;
4170
1.04k
  }
4171
1.04k
}
4172
4173
25
unsigned clang_suspendTranslationUnit(CXTranslationUnit CTUnit) {
4174
25
  if (CTUnit) {
4175
25
    ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
4176
4177
25
    if (Unit && Unit->isUnsafeToFree())
4178
0
      return false;
4179
4180
25
    Unit->ResetForParse();
4181
25
    return true;
4182
25
  }
4183
4184
0
  return false;
4185
0
}
4186
4187
813
unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
4188
813
  return CXReparse_None;
4189
813
}
4190
4191
static CXErrorCode
4192
clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
4193
                                  ArrayRef<CXUnsavedFile> unsaved_files,
4194
813
                                  unsigned options) {
4195
  // Check arguments.
4196
813
  if (isNotUsableTU(TU)) {
4197
0
    LOG_BAD_TU(TU);
4198
0
    return CXError_InvalidArguments;
4199
0
  }
4200
4201
  // Reset the associated diagnostics.
4202
813
  delete static_cast<CXDiagnosticSetImpl *>(TU->Diagnostics);
4203
813
  TU->Diagnostics = nullptr;
4204
4205
813
  CIndexer *CXXIdx = TU->CIdx;
4206
813
  if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
4207
0
    setThreadBackgroundPriority();
4208
4209
813
  ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4210
813
  ASTUnit::ConcurrencyCheck Check(*CXXUnit);
4211
4212
813
  std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
4213
813
      new std::vector<ASTUnit::RemappedFile>());
4214
4215
  // Recover resources if we crash before exiting this function.
4216
813
  llvm::CrashRecoveryContextCleanupRegistrar<std::vector<ASTUnit::RemappedFile>>
4217
813
      RemappedCleanup(RemappedFiles.get());
4218
4219
12
  for (auto &UF : unsaved_files) {
4220
12
    std::unique_ptr<llvm::MemoryBuffer> MB =
4221
12
        llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
4222
12
    RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
4223
12
  }
4224
4225
813
  if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
4226
813
                        *RemappedFiles.get()))
4227
812
    return CXError_Success;
4228
1
  if (isASTReadError(CXXUnit))
4229
0
    return CXError_ASTReadError;
4230
1
  return CXError_Failure;
4231
1
}
4232
4233
int clang_reparseTranslationUnit(CXTranslationUnit TU,
4234
                                 unsigned num_unsaved_files,
4235
                                 struct CXUnsavedFile *unsaved_files,
4236
813
                                 unsigned options) {
4237
813
  LOG_FUNC_SECTION 
{ *Log << TU; }0
4238
4239
813
  if (num_unsaved_files && 
!unsaved_files12
)
4240
0
    return CXError_InvalidArguments;
4241
4242
813
  CXErrorCode result;
4243
813
  auto ReparseTranslationUnitImpl = [=, &result]() {
4244
813
    result = clang_reparseTranslationUnit_Impl(
4245
813
        TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
4246
813
  };
4247
4248
813
  llvm::CrashRecoveryContext CRC;
4249
4250
813
  if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
4251
1
    fprintf(stderr, "libclang: crash detected during reparsing\n");
4252
1
    cxtu::getASTUnit(TU)->setUnsafeToFree(true);
4253
1
    return CXError_Crashed;
4254
812
  } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
4255
0
    PrintLibclangResourceUsage(TU);
4256
4257
812
  return result;
4258
813
}
4259
4260
0
CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
4261
0
  if (isNotUsableTU(CTUnit)) {
4262
0
    LOG_BAD_TU(CTUnit);
4263
0
    return cxstring::createEmpty();
4264
0
  }
4265
4266
0
  ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4267
0
  return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
4268
0
}
4269
4270
198
CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
4271
198
  if (isNotUsableTU(TU)) {
4272
0
    LOG_BAD_TU(TU);
4273
0
    return clang_getNullCursor();
4274
0
  }
4275
4276
198
  ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4277
198
  return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
4278
198
}
4279
4280
2
CXTargetInfo clang_getTranslationUnitTargetInfo(CXTranslationUnit CTUnit) {
4281
2
  if (isNotUsableTU(CTUnit)) {
4282
0
    LOG_BAD_TU(CTUnit);
4283
0
    return nullptr;
4284
0
  }
4285
4286
2
  CXTargetInfoImpl *impl = new CXTargetInfoImpl();
4287
2
  impl->TranslationUnit = CTUnit;
4288
2
  return impl;
4289
2
}
4290
4291
2
CXString clang_TargetInfo_getTriple(CXTargetInfo TargetInfo) {
4292
2
  if (!TargetInfo)
4293
0
    return cxstring::createEmpty();
4294
4295
2
  CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4296
2
  assert(!isNotUsableTU(CTUnit) &&
4297
2
         "Unexpected unusable translation unit in TargetInfo");
4298
4299
2
  ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4300
2
  std::string Triple =
4301
2
      CXXUnit->getASTContext().getTargetInfo().getTriple().normalize();
4302
2
  return cxstring::createDup(Triple);
4303
2
}
4304
4305
2
int clang_TargetInfo_getPointerWidth(CXTargetInfo TargetInfo) {
4306
2
  if (!TargetInfo)
4307
0
    return -1;
4308
4309
2
  CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
4310
2
  assert(!isNotUsableTU(CTUnit) &&
4311
2
         "Unexpected unusable translation unit in TargetInfo");
4312
4313
2
  ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
4314
2
  return CXXUnit->getASTContext().getTargetInfo().getMaxPointerWidth();
4315
2
}
4316
4317
2
void clang_TargetInfo_dispose(CXTargetInfo TargetInfo) {
4318
2
  if (!TargetInfo)
4319
0
    return;
4320
4321
2
  delete TargetInfo;
4322
2
}
4323
4324
//===----------------------------------------------------------------------===//
4325
// CXFile Operations.
4326
//===----------------------------------------------------------------------===//
4327
4328
62.2k
CXString clang_getFileName(CXFile SFile) {
4329
62.2k
  if (!SFile)
4330
48.7k
    return cxstring::createNull();
4331
4332
13.4k
  FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4333
13.4k
  return cxstring::createRef(FEnt->getName());
4334
13.4k
}
4335
4336
0
time_t clang_getFileTime(CXFile SFile) {
4337
0
  if (!SFile)
4338
0
    return 0;
4339
4340
0
  FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4341
0
  return FEnt->getModificationTime();
4342
0
}
4343
4344
473
CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
4345
473
  if (isNotUsableTU(TU)) {
4346
0
    LOG_BAD_TU(TU);
4347
0
    return nullptr;
4348
0
  }
4349
4350
473
  ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4351
4352
473
  FileManager &FMgr = CXXUnit->getFileManager();
4353
473
  auto File = FMgr.getFile(file_name);
4354
473
  if (!File)
4355
0
    return nullptr;
4356
473
  return const_cast<FileEntry *>(*File);
4357
473
}
4358
4359
const char *clang_getFileContents(CXTranslationUnit TU, CXFile file,
4360
0
                                  size_t *size) {
4361
0
  if (isNotUsableTU(TU)) {
4362
0
    LOG_BAD_TU(TU);
4363
0
    return nullptr;
4364
0
  }
4365
4366
0
  const SourceManager &SM = cxtu::getASTUnit(TU)->getSourceManager();
4367
0
  FileID fid = SM.translateFile(static_cast<FileEntry *>(file));
4368
0
  llvm::Optional<llvm::MemoryBufferRef> buf = SM.getBufferOrNone(fid);
4369
0
  if (!buf) {
4370
0
    if (size)
4371
0
      *size = 0;
4372
0
    return nullptr;
4373
0
  }
4374
0
  if (size)
4375
0
    *size = buf->getBufferSize();
4376
0
  return buf->getBufferStart();
4377
0
}
4378
4379
327
unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU, CXFile file) {
4380
327
  if (isNotUsableTU(TU)) {
4381
0
    LOG_BAD_TU(TU);
4382
0
    return 0;
4383
0
  }
4384
4385
327
  if (!file)
4386
4
    return 0;
4387
4388
323
  ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
4389
323
  FileEntry *FEnt = static_cast<FileEntry *>(file);
4390
323
  return CXXUnit->getPreprocessor()
4391
323
      .getHeaderSearchInfo()
4392
323
      .isFileMultipleIncludeGuarded(FEnt);
4393
323
}
4394
4395
0
int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
4396
0
  if (!file || !outID)
4397
0
    return 1;
4398
4399
0
  FileEntry *FEnt = static_cast<FileEntry *>(file);
4400
0
  const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
4401
0
  outID->data[0] = ID.getDevice();
4402
0
  outID->data[1] = ID.getFile();
4403
0
  outID->data[2] = FEnt->getModificationTime();
4404
0
  return 0;
4405
0
}
4406
4407
0
int clang_File_isEqual(CXFile file1, CXFile file2) {
4408
0
  if (file1 == file2)
4409
0
    return true;
4410
4411
0
  if (!file1 || !file2)
4412
0
    return false;
4413
4414
0
  FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
4415
0
  FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
4416
0
  return FEnt1->getUniqueID() == FEnt2->getUniqueID();
4417
0
}
4418
4419
1
CXString clang_File_tryGetRealPathName(CXFile SFile) {
4420
1
  if (!SFile)
4421
0
    return cxstring::createNull();
4422
4423
1
  FileEntry *FEnt = static_cast<FileEntry *>(SFile);
4424
1
  return cxstring::createRef(FEnt->tryGetRealPathName());
4425
1
}
4426
4427
//===----------------------------------------------------------------------===//
4428
// CXCursor Operations.
4429
//===----------------------------------------------------------------------===//
4430
4431
38.4k
static const Decl *getDeclFromExpr(const Stmt *E) {
4432
38.4k
  if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
4433
2.55k
    return getDeclFromExpr(CE->getSubExpr());
4434
4435
35.8k
  if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
4436
26.5k
    return RefExpr->getDecl();
4437
9.35k
  if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
4438
2.55k
    return ME->getMemberDecl();
4439
6.79k
  if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
4440
4
    return RE->getDecl();
4441
6.79k
  if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
4442
19
    if (PRE->isExplicitProperty())
4443
10
      return PRE->getExplicitProperty();
4444
    // It could be messaging both getter and setter as in:
4445
    // ++myobj.myprop;
4446
    // in which case prefer to associate the setter since it is less obvious
4447
    // from inspecting the source that the setter is going to get called.
4448
9
    if (PRE->isMessagingSetter())
4449
6
      return PRE->getImplicitPropertySetter();
4450
3
    return PRE->getImplicitPropertyGetter();
4451
3
  }
4452
6.77k
  if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
4453
0
    return getDeclFromExpr(POE->getSyntacticForm());
4454
6.77k
  if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
4455
2
    if (Expr *Src = OVE->getSourceExpr())
4456
2
      return getDeclFromExpr(Src);
4457
4458
6.77k
  if (const CallExpr *CE = dyn_cast<CallExpr>(E))
4459
958
    return getDeclFromExpr(CE->getCallee());
4460
5.81k
  if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
4461
198
    if (!CE->isElidable())
4462
172
      return CE->getConstructor();
4463
5.64k
  if (const CXXInheritedCtorInitExpr *CE =
4464
0
          dyn_cast<CXXInheritedCtorInitExpr>(E))
4465
0
    return CE->getConstructor();
4466
5.64k
  if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
4467
208
    return OME->getMethodDecl();
4468
4469
5.43k
  if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
4470
12
    return PE->getProtocol();
4471
5.42k
  if (const SubstNonTypeTemplateParmPackExpr *NTTP =
4472
0
          dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
4473
0
    return NTTP->getParameterPack();
4474
5.42k
  if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
4475
18
    if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
4476
18
        isa<ParmVarDecl>(SizeOfPack->getPack()))
4477
10
      return SizeOfPack->getPack();
4478
4479
5.41k
  return nullptr;
4480
5.41k
}
4481
4482
10.2k
static SourceLocation getLocationFromExpr(const Expr *E) {
4483
10.2k
  if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
4484
2.23k
    return getLocationFromExpr(CE->getSubExpr());
4485
4486
8.00k
  if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
4487
44
    return /*FIXME:*/ Msg->getLeftLoc();
4488
7.96k
  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
4489
2.41k
    return DRE->getLocation();
4490
5.54k
  if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
4491
819
    return Member->getMemberLoc();
4492
4.72k
  if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
4493
0
    return Ivar->getLocation();
4494
4.72k
  if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
4495
0
    return SizeOfPack->getPackLoc();
4496
4.72k
  if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
4497
10
    return PropRef->getLocation();
4498
4499
4.71k
  return E->getBeginLoc();
4500
4.71k
}
4501
4502
extern "C" {
4503
4504
unsigned clang_visitChildren(CXCursor parent, CXCursorVisitor visitor,
4505
203
                             CXClientData client_data) {
4506
203
  CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
4507
203
                          /*VisitPreprocessorLast=*/false);
4508
203
  return CursorVis.VisitChildren(parent);
4509
203
}
4510
4511
#ifndef __has_feature
4512
#define __has_feature(x) 0
4513
#endif
4514
#if __has_feature(blocks)
4515
typedef enum CXChildVisitResult (^CXCursorVisitorBlock)(CXCursor cursor,
4516
                                                        CXCursor parent);
4517
4518
static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4519
0
                                              CXClientData client_data) {
4520
0
  CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4521
0
  return block(cursor, parent);
4522
0
}
4523
#else
4524
// If we are compiled with a compiler that doesn't have native blocks support,
4525
// define and call the block manually, so the
4526
typedef struct _CXChildVisitResult {
4527
  void *isa;
4528
  int flags;
4529
  int reserved;
4530
  enum CXChildVisitResult (*invoke)(struct _CXChildVisitResult *, CXCursor,
4531
                                    CXCursor);
4532
} * CXCursorVisitorBlock;
4533
4534
static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
4535
                                              CXClientData client_data) {
4536
  CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
4537
  return block->invoke(block, cursor, parent);
4538
}
4539
#endif
4540
4541
unsigned clang_visitChildrenWithBlock(CXCursor parent,
4542
0
                                      CXCursorVisitorBlock block) {
4543
0
  return clang_visitChildren(parent, visitWithBlock, block);
4544
0
}
4545
4546
22.1k
static CXString getDeclSpelling(const Decl *D) {
4547
22.1k
  if (!D)
4548
0
    return cxstring::createEmpty();
4549
4550
22.1k
  const NamedDecl *ND = dyn_cast<NamedDecl>(D);
4551
22.1k
  if (!ND) {
4552
191
    if (const ObjCPropertyImplDecl *PropImpl =
4553
28
            dyn_cast<ObjCPropertyImplDecl>(D))
4554
28
      if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
4555
28
        return cxstring::createDup(Property->getIdentifier()->getName());
4556
4557
163
    if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
4558
13
      if (Module *Mod = ImportD->getImportedModule())
4559
13
        return cxstring::createDup(Mod->getFullModuleName());
4560
4561
150
    return cxstring::createEmpty();
4562
150
  }
4563
4564
21.9k
  if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
4565
515
    return cxstring::createDup(OMD->getSelector().getAsString());
4566
4567
21.4k
  if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
4568
    // No, this isn't the same as the code below. getIdentifier() is non-virtual
4569
    // and returns different names. NamedDecl returns the class name and
4570
    // ObjCCategoryImplDecl returns the category name.
4571
5
    return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
4572
4573
21.4k
  if (isa<UsingDirectiveDecl>(D))
4574
8
    return cxstring::createEmpty();
4575
4576
21.4k
  SmallString<1024> S;
4577
21.4k
  llvm::raw_svector_ostream os(S);
4578
21.4k
  ND->printName(os);
4579
4580
21.4k
  return cxstring::createDup(os.str());
4581
21.4k
}
4582
4583
82.0k
CXString clang_getCursorSpelling(CXCursor C) {
4584
82.0k
  if (clang_isTranslationUnit(C.kind))
4585
0
    return clang_getTranslationUnitSpelling(getCursorTU(C));
4586
4587
82.0k
  if (clang_isReference(C.kind)) {
4588
1.84k
    switch (C.kind) {
4589
25
    case CXCursor_ObjCSuperClassRef: {
4590
25
      const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
4591
25
      return cxstring::createRef(Super->getIdentifier()->getNameStart());
4592
0
    }
4593
214
    case CXCursor_ObjCClassRef: {
4594
214
      const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
4595
214
      return cxstring::createRef(Class->getIdentifier()->getNameStart());
4596
0
    }
4597
29
    case CXCursor_ObjCProtocolRef: {
4598
29
      const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
4599
29
      assert(OID && "getCursorSpelling(): Missing protocol decl");
4600
29
      return cxstring::createRef(OID->getIdentifier()->getNameStart());
4601
0
    }
4602
166
    case CXCursor_CXXBaseSpecifier: {
4603
166
      const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
4604
166
      return cxstring::createDup(B->getType().getAsString());
4605
0
    }
4606
1.05k
    case CXCursor_TypeRef: {
4607
1.05k
      const TypeDecl *Type = getCursorTypeRef(C).first;
4608
1.05k
      assert(Type && "Missing type decl");
4609
4610
1.05k
      return cxstring::createDup(
4611
1.05k
          getCursorContext(C).getTypeDeclType(Type).getAsString());
4612
0
    }
4613
138
    case CXCursor_TemplateRef: {
4614
138
      const TemplateDecl *Template = getCursorTemplateRef(C).first;
4615
138
      assert(Template && "Missing template decl");
4616
4617
138
      return cxstring::createDup(Template->getNameAsString());
4618
0
    }
4619
4620
133
    case CXCursor_NamespaceRef: {
4621
133
      const NamedDecl *NS = getCursorNamespaceRef(C).first;
4622
133
      assert(NS && "Missing namespace decl");
4623
4624
133
      return cxstring::createDup(NS->getNameAsString());
4625
0
    }
4626
4627
46
    case CXCursor_MemberRef: {
4628
46
      const FieldDecl *Field = getCursorMemberRef(C).first;
4629
46
      assert(Field && "Missing member decl");
4630
4631
46
      return cxstring::createDup(Field->getNameAsString());
4632
0
    }
4633
4634
2
    case CXCursor_LabelRef: {
4635
2
      const LabelStmt *Label = getCursorLabelRef(C).first;
4636
2
      assert(Label && "Missing label");
4637
4638
2
      return cxstring::createRef(Label->getName());
4639
0
    }
4640
4641
21
    case CXCursor_OverloadedDeclRef: {
4642
21
      OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
4643
21
      if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
4644
6
        if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
4645
6
          return cxstring::createDup(ND->getNameAsString());
4646
0
        return cxstring::createEmpty();
4647
0
      }
4648
15
      if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
4649
15
        return cxstring::createDup(E->getName().getAsString());
4650
0
      OverloadedTemplateStorage *Ovl =
4651
0
          Storage.get<OverloadedTemplateStorage *>();
4652
0
      if (Ovl->size() == 0)
4653
0
        return cxstring::createEmpty();
4654
0
      return cxstring::createDup((*Ovl->begin())->getNameAsString());
4655
0
    }
4656
4657
14
    case CXCursor_VariableRef: {
4658
14
      const VarDecl *Var = getCursorVariableRef(C).first;
4659
14
      assert(Var && "Missing variable decl");
4660
4661
14
      return cxstring::createDup(Var->getNameAsString());
4662
0
    }
4663
4664
0
    default:
4665
0
      return cxstring::createRef("<not implemented>");
4666
80.2k
    }
4667
80.2k
  }
4668
4669
80.2k
  if (clang_isExpression(C.kind)) {
4670
17.3k
    const Expr *E = getCursorExpr(C);
4671
4672
17.3k
    if (C.kind == CXCursor_ObjCStringLiteral ||
4673
17.3k
        C.kind == CXCursor_StringLiteral) {
4674
173
      const StringLiteral *SLit;
4675
173
      if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
4676
2
        SLit = OSL->getString();
4677
171
      } else {
4678
171
        SLit = cast<StringLiteral>(E);
4679
171
      }
4680
173
      SmallString<256> Buf;
4681
173
      llvm::raw_svector_ostream OS(Buf);
4682
173
      SLit->outputString(OS);
4683
173
      return cxstring::createDup(OS.str());
4684
173
    }
4685
4686
17.1k
    const Decl *D = getDeclFromExpr(getCursorExpr(C));
4687
17.1k
    if (D)
4688
14.6k
      return getDeclSpelling(D);
4689
2.54k
    return cxstring::createEmpty();
4690
2.54k
  }
4691
4692
62.8k
  if (clang_isStatement(C.kind)) {
4693
845
    const Stmt *S = getCursorStmt(C);
4694
845
    if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
4695
1
      return cxstring::createRef(Label->getName());
4696
4697
844
    return cxstring::createEmpty();
4698
844
  }
4699
4700
62.0k
  if (C.kind == CXCursor_MacroExpansion)
4701
140
    return cxstring::createRef(
4702
140
        getCursorMacroExpansion(C).getName()->getNameStart());
4703
4704
61.9k
  if (C.kind == CXCursor_MacroDefinition)
4705
53.6k
    return cxstring::createRef(
4706
53.6k
        getCursorMacroDefinition(C)->getName()->getNameStart());
4707
4708
8.25k
  if (C.kind == CXCursor_InclusionDirective)
4709
331
    return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
4710
4711
7.92k
  if (clang_isDeclaration(C.kind))
4712
7.56k
    return getDeclSpelling(getCursorDecl(C));
4713
4714
361
  if (C.kind == CXCursor_AnnotateAttr) {
4715
15
    const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
4716
15
    return cxstring::createDup(AA->getAnnotation());
4717
15
  }
4718
4719
346
  if (C.kind == CXCursor_AsmLabelAttr) {
4720
1
    const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
4721
1
    return cxstring::createDup(AA->getLabel());
4722
1
  }
4723
4724
345
  if (C.kind == CXCursor_PackedAttr) {
4725
13
    return cxstring::createRef("packed");
4726
13
  }
4727
4728
332
  if (C.kind == CXCursor_VisibilityAttr) {
4729
12
    const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
4730
12
    switch (AA->getVisibility()) {
4731
6
    case VisibilityAttr::VisibilityType::Default:
4732
6
      return cxstring::createRef("default");
4733
4
    case VisibilityAttr::VisibilityType::Hidden:
4734
4
      return cxstring::createRef("hidden");
4735
2
    case VisibilityAttr::VisibilityType::Protected:
4736
2
      return cxstring::createRef("protected");
4737
0
    }
4738
0
    llvm_unreachable("unknown visibility type");
4739
0
  }
4740
4741
320
  return cxstring::createEmpty();
4742
320
}
4743
4744
CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C, unsigned pieceIndex,
4745
490
                                                unsigned options) {
4746
490
  if (clang_Cursor_isNull(C))
4747
0
    return clang_getNullRange();
4748
4749
490
  ASTContext &Ctx = getCursorContext(C);
4750
4751
490
  if (clang_isStatement(C.kind)) {
4752
0
    const Stmt *S = getCursorStmt(C);
4753
0
    if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
4754
0
      if (pieceIndex > 0)
4755
0
        return clang_getNullRange();
4756
0
      return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
4757
0
    }
4758
4759
0
    return clang_getNullRange();
4760
0
  }
4761
4762
490
  if (C.kind == CXCursor_ObjCMessageExpr) {
4763
41
    if (const ObjCMessageExpr *ME =
4764
41
            dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
4765
41
      if (pieceIndex >= ME->getNumSelectorLocs())
4766
20
        return clang_getNullRange();
4767
21
      return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
4768
21
    }
4769
41
  }
4770
4771
449
  if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
4772
428
      C.kind == CXCursor_ObjCClassMethodDecl) {
4773
21
    if (const ObjCMethodDecl *MD =
4774
21
            dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
4775
21
      if (pieceIndex >= MD->getNumSelectorLocs())
4776
10
        return clang_getNullRange();
4777
11
      return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
4778
11
    }
4779
21
  }
4780
4781
428
  if (C.kind == CXCursor_ObjCCategoryDecl ||
4782
426
      C.kind == CXCursor_ObjCCategoryImplDecl) {
4783
4
    if (pieceIndex > 0)
4784
2
      return clang_getNullRange();
4785
2
    if (const ObjCCategoryDecl *CD =
4786
1
            dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
4787
1
      return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
4788
1
    if (const ObjCCategoryImplDecl *CID =
4789
1
            dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
4790
1
      return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
4791
424
  }
4792
4793
424
  if (C.kind == CXCursor_ModuleImportDecl) {
4794
2
    if (pieceIndex > 0)
4795
1
      return clang_getNullRange();
4796
1
    if (const ImportDecl *ImportD =
4797
1
            dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
4798
1
      ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
4799
1
      if (!Locs.empty())
4800
1
        return cxloc::translateSourceRange(
4801
1
            Ctx, SourceRange(Locs.front(), Locs.back()));
4802
0
    }
4803
0
    return clang_getNullRange();
4804
0
  }
4805
4806
422
  if (C.kind == CXCursor_CXXMethod || 
C.kind == CXCursor_Destructor330
||
4807
328
      C.kind == CXCursor_ConversionFunction ||
4808
326
      C.kind == CXCursor_FunctionDecl) {
4809
110
    if (pieceIndex > 0)
4810
55
      return clang_getNullRange();
4811
55
    if (const FunctionDecl *FD =
4812
55
            dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
4813
55
      DeclarationNameInfo FunctionName = FD->getNameInfo();
4814
55
      return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
4815
55
    }
4816
0
    return clang_getNullRange();
4817
0
  }
4818
4819
  // FIXME: A CXCursor_InclusionDirective should give the location of the
4820
  // filename, but we don't keep track of this.
4821
4822
  // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
4823
  // but we don't keep track of this.
4824
4825
  // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
4826
  // but we don't keep track of this.
4827
4828
  // Default handling, give the location of the cursor.
4829
4830
312
  if (pieceIndex > 0)
4831
156
    return clang_getNullRange();
4832
4833
156
  CXSourceLocation CXLoc = clang_getCursorLocation(C);
4834
156
  SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
4835
156
  return cxloc::translateSourceRange(Ctx, Loc);
4836
156
}
4837
4838
1.15k
CXString clang_Cursor_getMangling(CXCursor C) {
4839
1.15k
  if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4840
1.13k
    return cxstring::createEmpty();
4841
4842
  // Mangling only works for functions and variables.
4843
15
  const Decl *D = getCursorDecl(C);
4844
15
  if (!D || !(isa<FunctionDecl>(D) || 
isa<VarDecl>(D)3
))
4845
3
    return cxstring::createEmpty();
4846
4847
12
  ASTContext &Ctx = D->getASTContext();
4848
12
  ASTNameGenerator ASTNameGen(Ctx);
4849
12
  return cxstring::createDup(ASTNameGen.getName(D));
4850
12
}
4851
4852
64
CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
4853
64
  if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4854
0
    return nullptr;
4855
4856
64
  const Decl *D = getCursorDecl(C);
4857
64
  if (!(isa<CXXRecordDecl>(D) || 
isa<CXXMethodDecl>(D)43
))
4858
4
    return nullptr;
4859
4860
60
  ASTContext &Ctx = D->getASTContext();
4861
60
  ASTNameGenerator ASTNameGen(Ctx);
4862
60
  std::vector<std::string> Manglings = ASTNameGen.getAllManglings(D);
4863
60
  return cxstring::createSet(Manglings);
4864
60
}
4865
4866
64
CXStringSet *clang_Cursor_getObjCManglings(CXCursor C) {
4867
64
  if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
4868
0
    return nullptr;
4869
4870
64
  const Decl *D = getCursorDecl(C);
4871
64
  if (!(isa<ObjCInterfaceDecl>(D) || 
isa<ObjCImplementationDecl>(D)62
))
4872
60
    return nullptr;
4873
4874
4
  ASTContext &Ctx = D->getASTContext();
4875
4
  ASTNameGenerator ASTNameGen(Ctx);
4876
4
  std::vector<std::string> Manglings = ASTNameGen.getAllManglings(D);
4877
4
  return cxstring::createSet(Manglings);
4878
4
}
4879
4880
414
CXPrintingPolicy clang_getCursorPrintingPolicy(CXCursor C) {
4881
414
  if (clang_Cursor_isNull(C))
4882
0
    return 0;
4883
414
  return new PrintingPolicy(getCursorContext(C).getPrintingPolicy());
4884
414
}
4885
4886
414
void clang_PrintingPolicy_dispose(CXPrintingPolicy Policy) {
4887
414
  if (Policy)
4888
414
    delete static_cast<PrintingPolicy *>(Policy);
4889
414
}
4890
4891
unsigned
4892
clang_PrintingPolicy_getProperty(CXPrintingPolicy Policy,
4893
50
                                 enum CXPrintingPolicyProperty Property) {
4894
50
  if (!Policy)
4895
0
    return 0;
4896
4897
50
  PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4898
50
  switch (Property) {
4899
2
  case CXPrintingPolicy_Indentation:
4900
2
    return P->Indentation;
4901
2
  case CXPrintingPolicy_SuppressSpecifiers:
4902
2
    return P->SuppressSpecifiers;
4903
2
  case CXPrintingPolicy_SuppressTagKeyword:
4904
2
    return P->SuppressTagKeyword;
4905
2
  case CXPrintingPolicy_IncludeTagDefinition:
4906
2
    return P->IncludeTagDefinition;
4907
2
  case CXPrintingPolicy_SuppressScope:
4908
2
    return P->SuppressScope;
4909
2
  case CXPrintingPolicy_SuppressUnwrittenScope:
4910
2
    return P->SuppressUnwrittenScope;
4911
2
  case CXPrintingPolicy_SuppressInitializers:
4912
2
    return P->SuppressInitializers;
4913
2
  case CXPrintingPolicy_ConstantArraySizeAsWritten:
4914
2
    return P->ConstantArraySizeAsWritten;
4915
2
  case CXPrintingPolicy_AnonymousTagLocations:
4916
2
    return P->AnonymousTagLocations;
4917
2
  case CXPrintingPolicy_SuppressStrongLifetime:
4918
2
    return P->SuppressStrongLifetime;
4919
2
  case CXPrintingPolicy_SuppressLifetimeQualifiers:
4920
2
    return P->SuppressLifetimeQualifiers;
4921
2
  case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
4922
2
    return P->SuppressTemplateArgsInCXXConstructors;
4923
2
  case CXPrintingPolicy_Bool:
4924
2
    return P->Bool;
4925
2
  case CXPrintingPolicy_Restrict:
4926
2
    return P->Restrict;
4927
2
  case CXPrintingPolicy_Alignof:
4928
2
    return P->Alignof;
4929
2
  case CXPrintingPolicy_UnderscoreAlignof:
4930
2
    return P->UnderscoreAlignof;
4931
2
  case CXPrintingPolicy_UseVoidForZeroParams:
4932
2
    return P->UseVoidForZeroParams;
4933
2
  case CXPrintingPolicy_TerseOutput:
4934
2
    return P->TerseOutput;
4935
2
  case CXPrintingPolicy_PolishForDeclaration:
4936
2
    return P->PolishForDeclaration;
4937
2
  case CXPrintingPolicy_Half:
4938
2
    return P->Half;
4939
2
  case CXPrintingPolicy_MSWChar:
4940
2
    return P->MSWChar;
4941
2
  case CXPrintingPolicy_IncludeNewlines:
4942
2
    return P->IncludeNewlines;
4943
2
  case CXPrintingPolicy_MSVCFormatting:
4944
2
    return P->MSVCFormatting;
4945
2
  case CXPrintingPolicy_ConstantsAsWritten:
4946
2
    return P->ConstantsAsWritten;
4947
2
  case CXPrintingPolicy_SuppressImplicitBase:
4948
2
    return P->SuppressImplicitBase;
4949
0
  case CXPrintingPolicy_FullyQualifiedName:
4950
0
    return P->FullyQualifiedName;
4951
0
  }
4952
4953
0
  assert(false && "Invalid CXPrintingPolicyProperty");
4954
0
  return 0;
4955
0
}
4956
4957
void clang_PrintingPolicy_setProperty(CXPrintingPolicy Policy,
4958
                                      enum CXPrintingPolicyProperty Property,
4959
463
                                      unsigned Value) {
4960
463
  if (!Policy)
4961
0
    return;
4962
4963
463
  PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
4964
463
  switch (Property) {
4965
2
  case CXPrintingPolicy_Indentation:
4966
2
    P->Indentation = Value;
4967
2
    return;
4968
2
  case CXPrintingPolicy_SuppressSpecifiers:
4969
2
    P->SuppressSpecifiers = Value;
4970
2
    return;
4971
2
  case CXPrintingPolicy_SuppressTagKeyword:
4972
2
    P->SuppressTagKeyword = Value;
4973
2
    return;
4974
2
  case CXPrintingPolicy_IncludeTagDefinition:
4975
2
    P->IncludeTagDefinition = Value;
4976
2
    return;
4977
2
  case CXPrintingPolicy_SuppressScope:
4978
2
    P->SuppressScope = Value;
4979