RecursiveASTVisitor.h revision 309124
1//===--- RecursiveASTVisitor.h - Recursive AST Visitor ----------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file defines the RecursiveASTVisitor interface, which recursively
11//  traverses the entire AST.
12//
13//===----------------------------------------------------------------------===//
14#ifndef LLVM_CLANG_AST_RECURSIVEASTVISITOR_H
15#define LLVM_CLANG_AST_RECURSIVEASTVISITOR_H
16
17#include <type_traits>
18
19#include "clang/AST/Attr.h"
20#include "clang/AST/Decl.h"
21#include "clang/AST/DeclCXX.h"
22#include "clang/AST/DeclFriend.h"
23#include "clang/AST/DeclObjC.h"
24#include "clang/AST/DeclOpenMP.h"
25#include "clang/AST/DeclTemplate.h"
26#include "clang/AST/Expr.h"
27#include "clang/AST/ExprCXX.h"
28#include "clang/AST/ExprObjC.h"
29#include "clang/AST/ExprOpenMP.h"
30#include "clang/AST/NestedNameSpecifier.h"
31#include "clang/AST/Stmt.h"
32#include "clang/AST/StmtCXX.h"
33#include "clang/AST/StmtObjC.h"
34#include "clang/AST/StmtOpenMP.h"
35#include "clang/AST/TemplateBase.h"
36#include "clang/AST/TemplateName.h"
37#include "clang/AST/Type.h"
38#include "clang/AST/TypeLoc.h"
39
40// The following three macros are used for meta programming.  The code
41// using them is responsible for defining macro OPERATOR().
42
43// All unary operators.
44#define UNARYOP_LIST()                                                         \
45  OPERATOR(PostInc) OPERATOR(PostDec) OPERATOR(PreInc) OPERATOR(PreDec)        \
46      OPERATOR(AddrOf) OPERATOR(Deref) OPERATOR(Plus) OPERATOR(Minus)          \
47      OPERATOR(Not) OPERATOR(LNot) OPERATOR(Real) OPERATOR(Imag)               \
48      OPERATOR(Extension) OPERATOR(Coawait)
49
50// All binary operators (excluding compound assign operators).
51#define BINOP_LIST()                                                           \
52  OPERATOR(PtrMemD) OPERATOR(PtrMemI) OPERATOR(Mul) OPERATOR(Div)              \
53      OPERATOR(Rem) OPERATOR(Add) OPERATOR(Sub) OPERATOR(Shl) OPERATOR(Shr)    \
54      OPERATOR(LT) OPERATOR(GT) OPERATOR(LE) OPERATOR(GE) OPERATOR(EQ)         \
55      OPERATOR(NE) OPERATOR(And) OPERATOR(Xor) OPERATOR(Or) OPERATOR(LAnd)     \
56      OPERATOR(LOr) OPERATOR(Assign) OPERATOR(Comma)
57
58// All compound assign operators.
59#define CAO_LIST()                                                             \
60  OPERATOR(Mul) OPERATOR(Div) OPERATOR(Rem) OPERATOR(Add) OPERATOR(Sub)        \
61      OPERATOR(Shl) OPERATOR(Shr) OPERATOR(And) OPERATOR(Or) OPERATOR(Xor)
62
63namespace clang {
64
65// A helper macro to implement short-circuiting when recursing.  It
66// invokes CALL_EXPR, which must be a method call, on the derived
67// object (s.t. a user of RecursiveASTVisitor can override the method
68// in CALL_EXPR).
69#define TRY_TO(CALL_EXPR)                                                      \
70  do {                                                                         \
71    if (!getDerived().CALL_EXPR)                                               \
72      return false;                                                            \
73  } while (0)
74
75/// \brief A class that does preordor or postorder
76/// depth-first traversal on the entire Clang AST and visits each node.
77///
78/// This class performs three distinct tasks:
79///   1. traverse the AST (i.e. go to each node);
80///   2. at a given node, walk up the class hierarchy, starting from
81///      the node's dynamic type, until the top-most class (e.g. Stmt,
82///      Decl, or Type) is reached.
83///   3. given a (node, class) combination, where 'class' is some base
84///      class of the dynamic type of 'node', call a user-overridable
85///      function to actually visit the node.
86///
87/// These tasks are done by three groups of methods, respectively:
88///   1. TraverseDecl(Decl *x) does task #1.  It is the entry point
89///      for traversing an AST rooted at x.  This method simply
90///      dispatches (i.e. forwards) to TraverseFoo(Foo *x) where Foo
91///      is the dynamic type of *x, which calls WalkUpFromFoo(x) and
92///      then recursively visits the child nodes of x.
93///      TraverseStmt(Stmt *x) and TraverseType(QualType x) work
94///      similarly.
95///   2. WalkUpFromFoo(Foo *x) does task #2.  It does not try to visit
96///      any child node of x.  Instead, it first calls WalkUpFromBar(x)
97///      where Bar is the direct parent class of Foo (unless Foo has
98///      no parent), and then calls VisitFoo(x) (see the next list item).
99///   3. VisitFoo(Foo *x) does task #3.
100///
101/// These three method groups are tiered (Traverse* > WalkUpFrom* >
102/// Visit*).  A method (e.g. Traverse*) may call methods from the same
103/// tier (e.g. other Traverse*) or one tier lower (e.g. WalkUpFrom*).
104/// It may not call methods from a higher tier.
105///
106/// Note that since WalkUpFromFoo() calls WalkUpFromBar() (where Bar
107/// is Foo's super class) before calling VisitFoo(), the result is
108/// that the Visit*() methods for a given node are called in the
109/// top-down order (e.g. for a node of type NamespaceDecl, the order will
110/// be VisitDecl(), VisitNamedDecl(), and then VisitNamespaceDecl()).
111///
112/// This scheme guarantees that all Visit*() calls for the same AST
113/// node are grouped together.  In other words, Visit*() methods for
114/// different nodes are never interleaved.
115///
116/// Clients of this visitor should subclass the visitor (providing
117/// themselves as the template argument, using the curiously recurring
118/// template pattern) and override any of the Traverse*, WalkUpFrom*,
119/// and Visit* methods for declarations, types, statements,
120/// expressions, or other AST nodes where the visitor should customize
121/// behavior.  Most users only need to override Visit*.  Advanced
122/// users may override Traverse* and WalkUpFrom* to implement custom
123/// traversal strategies.  Returning false from one of these overridden
124/// functions will abort the entire traversal.
125///
126/// By default, this visitor tries to visit every part of the explicit
127/// source code exactly once.  The default policy towards templates
128/// is to descend into the 'pattern' class or function body, not any
129/// explicit or implicit instantiations.  Explicit specializations
130/// are still visited, and the patterns of partial specializations
131/// are visited separately.  This behavior can be changed by
132/// overriding shouldVisitTemplateInstantiations() in the derived class
133/// to return true, in which case all known implicit and explicit
134/// instantiations will be visited at the same time as the pattern
135/// from which they were produced.
136///
137/// By default, this visitor preorder traverses the AST. If postorder traversal
138/// is needed, the \c shouldTraversePostOrder method needs to be overriden
139/// to return \c true.
140template <typename Derived> class RecursiveASTVisitor {
141public:
142  /// A queue used for performing data recursion over statements.
143  /// Parameters involving this type are used to implement data
144  /// recursion over Stmts and Exprs within this class, and should
145  /// typically not be explicitly specified by derived classes.
146  /// The bool bit indicates whether the statement has been traversed or not.
147  typedef SmallVectorImpl<llvm::PointerIntPair<Stmt *, 1, bool>>
148    DataRecursionQueue;
149
150  /// \brief Return a reference to the derived class.
151  Derived &getDerived() { return *static_cast<Derived *>(this); }
152
153  /// \brief Return whether this visitor should recurse into
154  /// template instantiations.
155  bool shouldVisitTemplateInstantiations() const { return false; }
156
157  /// \brief Return whether this visitor should recurse into the types of
158  /// TypeLocs.
159  bool shouldWalkTypesOfTypeLocs() const { return true; }
160
161  /// \brief Return whether this visitor should recurse into implicit
162  /// code, e.g., implicit constructors and destructors.
163  bool shouldVisitImplicitCode() const { return false; }
164
165  /// \brief Return whether this visitor should traverse post-order.
166  bool shouldTraversePostOrder() const { return false; }
167
168  /// \brief Recursively visit a statement or expression, by
169  /// dispatching to Traverse*() based on the argument's dynamic type.
170  ///
171  /// \returns false if the visitation was terminated early, true
172  /// otherwise (including when the argument is nullptr).
173  bool TraverseStmt(Stmt *S, DataRecursionQueue *Queue = nullptr);
174
175  /// Invoked before visiting a statement or expression via data recursion.
176  ///
177  /// \returns false to skip visiting the node, true otherwise.
178  bool dataTraverseStmtPre(Stmt *S) { return true; }
179
180  /// Invoked after visiting a statement or expression via data recursion.
181  /// This is not invoked if the previously invoked \c dataTraverseStmtPre
182  /// returned false.
183  ///
184  /// \returns false if the visitation was terminated early, true otherwise.
185  bool dataTraverseStmtPost(Stmt *S) { return true; }
186
187  /// \brief Recursively visit a type, by dispatching to
188  /// Traverse*Type() based on the argument's getTypeClass() property.
189  ///
190  /// \returns false if the visitation was terminated early, true
191  /// otherwise (including when the argument is a Null type).
192  bool TraverseType(QualType T);
193
194  /// \brief Recursively visit a type with location, by dispatching to
195  /// Traverse*TypeLoc() based on the argument type's getTypeClass() property.
196  ///
197  /// \returns false if the visitation was terminated early, true
198  /// otherwise (including when the argument is a Null type location).
199  bool TraverseTypeLoc(TypeLoc TL);
200
201  /// \brief Recursively visit an attribute, by dispatching to
202  /// Traverse*Attr() based on the argument's dynamic type.
203  ///
204  /// \returns false if the visitation was terminated early, true
205  /// otherwise (including when the argument is a Null type location).
206  bool TraverseAttr(Attr *At);
207
208  /// \brief Recursively visit a declaration, by dispatching to
209  /// Traverse*Decl() based on the argument's dynamic type.
210  ///
211  /// \returns false if the visitation was terminated early, true
212  /// otherwise (including when the argument is NULL).
213  bool TraverseDecl(Decl *D);
214
215  /// \brief Recursively visit a C++ nested-name-specifier.
216  ///
217  /// \returns false if the visitation was terminated early, true otherwise.
218  bool TraverseNestedNameSpecifier(NestedNameSpecifier *NNS);
219
220  /// \brief Recursively visit a C++ nested-name-specifier with location
221  /// information.
222  ///
223  /// \returns false if the visitation was terminated early, true otherwise.
224  bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS);
225
226  /// \brief Recursively visit a name with its location information.
227  ///
228  /// \returns false if the visitation was terminated early, true otherwise.
229  bool TraverseDeclarationNameInfo(DeclarationNameInfo NameInfo);
230
231  /// \brief Recursively visit a template name and dispatch to the
232  /// appropriate method.
233  ///
234  /// \returns false if the visitation was terminated early, true otherwise.
235  bool TraverseTemplateName(TemplateName Template);
236
237  /// \brief Recursively visit a template argument and dispatch to the
238  /// appropriate method for the argument type.
239  ///
240  /// \returns false if the visitation was terminated early, true otherwise.
241  // FIXME: migrate callers to TemplateArgumentLoc instead.
242  bool TraverseTemplateArgument(const TemplateArgument &Arg);
243
244  /// \brief Recursively visit a template argument location and dispatch to the
245  /// appropriate method for the argument type.
246  ///
247  /// \returns false if the visitation was terminated early, true otherwise.
248  bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc);
249
250  /// \brief Recursively visit a set of template arguments.
251  /// This can be overridden by a subclass, but it's not expected that
252  /// will be needed -- this visitor always dispatches to another.
253  ///
254  /// \returns false if the visitation was terminated early, true otherwise.
255  // FIXME: take a TemplateArgumentLoc* (or TemplateArgumentListInfo) instead.
256  bool TraverseTemplateArguments(const TemplateArgument *Args,
257                                 unsigned NumArgs);
258
259  /// \brief Recursively visit a constructor initializer.  This
260  /// automatically dispatches to another visitor for the initializer
261  /// expression, but not for the name of the initializer, so may
262  /// be overridden for clients that need access to the name.
263  ///
264  /// \returns false if the visitation was terminated early, true otherwise.
265  bool TraverseConstructorInitializer(CXXCtorInitializer *Init);
266
267  /// \brief Recursively visit a lambda capture.
268  ///
269  /// \returns false if the visitation was terminated early, true otherwise.
270  bool TraverseLambdaCapture(LambdaExpr *LE, const LambdaCapture *C);
271
272  /// \brief Recursively visit the body of a lambda expression.
273  ///
274  /// This provides a hook for visitors that need more context when visiting
275  /// \c LE->getBody().
276  ///
277  /// \returns false if the visitation was terminated early, true otherwise.
278  bool TraverseLambdaBody(LambdaExpr *LE, DataRecursionQueue *Queue = nullptr);
279
280  /// \brief Recursively visit the syntactic or semantic form of an
281  /// initialization list.
282  ///
283  /// \returns false if the visitation was terminated early, true otherwise.
284  bool TraverseSynOrSemInitListExpr(InitListExpr *S,
285                                    DataRecursionQueue *Queue = nullptr);
286
287  // ---- Methods on Attrs ----
288
289  // \brief Visit an attribute.
290  bool VisitAttr(Attr *A) { return true; }
291
292// Declare Traverse* and empty Visit* for all Attr classes.
293#define ATTR_VISITOR_DECLS_ONLY
294#include "clang/AST/AttrVisitor.inc"
295#undef ATTR_VISITOR_DECLS_ONLY
296
297// ---- Methods on Stmts ----
298
299private:
300  template<typename T, typename U>
301  struct has_same_member_pointer_type : std::false_type {};
302  template<typename T, typename U, typename R, typename... P>
303  struct has_same_member_pointer_type<R (T::*)(P...), R (U::*)(P...)>
304      : std::true_type {};
305
306  // Traverse the given statement. If the most-derived traverse function takes a
307  // data recursion queue, pass it on; otherwise, discard it. Note that the
308  // first branch of this conditional must compile whether or not the derived
309  // class can take a queue, so if we're taking the second arm, make the first
310  // arm call our function rather than the derived class version.
311#define TRAVERSE_STMT_BASE(NAME, CLASS, VAR, QUEUE)                            \
312  (has_same_member_pointer_type<decltype(                                      \
313                                    &RecursiveASTVisitor::Traverse##NAME),     \
314                                decltype(&Derived::Traverse##NAME)>::value     \
315       ? static_cast<typename std::conditional<                                \
316             has_same_member_pointer_type<                                     \
317                 decltype(&RecursiveASTVisitor::Traverse##NAME),               \
318                 decltype(&Derived::Traverse##NAME)>::value,                   \
319             Derived &, RecursiveASTVisitor &>::type>(*this)                   \
320             .Traverse##NAME(static_cast<CLASS *>(VAR), QUEUE)                 \
321       : getDerived().Traverse##NAME(static_cast<CLASS *>(VAR)))
322
323// Try to traverse the given statement, or enqueue it if we're performing data
324// recursion in the middle of traversing another statement. Can only be called
325// from within a DEF_TRAVERSE_STMT body or similar context.
326#define TRY_TO_TRAVERSE_OR_ENQUEUE_STMT(S)                                     \
327  do {                                                                         \
328    if (!TRAVERSE_STMT_BASE(Stmt, Stmt, S, Queue))                             \
329      return false;                                                            \
330  } while (0)
331
332public:
333// Declare Traverse*() for all concrete Stmt classes.
334#define ABSTRACT_STMT(STMT)
335#define STMT(CLASS, PARENT) \
336  bool Traverse##CLASS(CLASS *S, DataRecursionQueue *Queue = nullptr);
337#include "clang/AST/StmtNodes.inc"
338  // The above header #undefs ABSTRACT_STMT and STMT upon exit.
339
340  // Define WalkUpFrom*() and empty Visit*() for all Stmt classes.
341  bool WalkUpFromStmt(Stmt *S) { return getDerived().VisitStmt(S); }
342  bool VisitStmt(Stmt *S) { return true; }
343#define STMT(CLASS, PARENT)                                                    \
344  bool WalkUpFrom##CLASS(CLASS *S) {                                           \
345    TRY_TO(WalkUpFrom##PARENT(S));                                             \
346    TRY_TO(Visit##CLASS(S));                                                   \
347    return true;                                                               \
348  }                                                                            \
349  bool Visit##CLASS(CLASS *S) { return true; }
350#include "clang/AST/StmtNodes.inc"
351
352// Define Traverse*(), WalkUpFrom*(), and Visit*() for unary
353// operator methods.  Unary operators are not classes in themselves
354// (they're all opcodes in UnaryOperator) but do have visitors.
355#define OPERATOR(NAME)                                                         \
356  bool TraverseUnary##NAME(UnaryOperator *S,                                   \
357                           DataRecursionQueue *Queue = nullptr) {              \
358    TRY_TO(WalkUpFromUnary##NAME(S));                                          \
359    TRY_TO_TRAVERSE_OR_ENQUEUE_STMT(S->getSubExpr());                          \
360    return true;                                                               \
361  }                                                                            \
362  bool WalkUpFromUnary##NAME(UnaryOperator *S) {                               \
363    TRY_TO(WalkUpFromUnaryOperator(S));                                        \
364    TRY_TO(VisitUnary##NAME(S));                                               \
365    return true;                                                               \
366  }                                                                            \
367  bool VisitUnary##NAME(UnaryOperator *S) { return true; }
368
369  UNARYOP_LIST()
370#undef OPERATOR
371
372// Define Traverse*(), WalkUpFrom*(), and Visit*() for binary
373// operator methods.  Binary operators are not classes in themselves
374// (they're all opcodes in BinaryOperator) but do have visitors.
375#define GENERAL_BINOP_FALLBACK(NAME, BINOP_TYPE)                               \
376  bool TraverseBin##NAME(BINOP_TYPE *S, DataRecursionQueue *Queue = nullptr) { \
377    if (!getDerived().shouldTraversePostOrder())                               \
378      TRY_TO(WalkUpFromBin##NAME(S));                                          \
379    TRY_TO_TRAVERSE_OR_ENQUEUE_STMT(S->getLHS());                              \
380    TRY_TO_TRAVERSE_OR_ENQUEUE_STMT(S->getRHS());                              \
381    return true;                                                               \
382  }                                                                            \
383  bool WalkUpFromBin##NAME(BINOP_TYPE *S) {                                    \
384    TRY_TO(WalkUpFrom##BINOP_TYPE(S));                                         \
385    TRY_TO(VisitBin##NAME(S));                                                 \
386    return true;                                                               \
387  }                                                                            \
388  bool VisitBin##NAME(BINOP_TYPE *S) { return true; }
389
390#define OPERATOR(NAME) GENERAL_BINOP_FALLBACK(NAME, BinaryOperator)
391  BINOP_LIST()
392#undef OPERATOR
393
394// Define Traverse*(), WalkUpFrom*(), and Visit*() for compound
395// assignment methods.  Compound assignment operators are not
396// classes in themselves (they're all opcodes in
397// CompoundAssignOperator) but do have visitors.
398#define OPERATOR(NAME)                                                         \
399  GENERAL_BINOP_FALLBACK(NAME##Assign, CompoundAssignOperator)
400
401  CAO_LIST()
402#undef OPERATOR
403#undef GENERAL_BINOP_FALLBACK
404
405// ---- Methods on Types ----
406// FIXME: revamp to take TypeLoc's rather than Types.
407
408// Declare Traverse*() for all concrete Type classes.
409#define ABSTRACT_TYPE(CLASS, BASE)
410#define TYPE(CLASS, BASE) bool Traverse##CLASS##Type(CLASS##Type *T);
411#include "clang/AST/TypeNodes.def"
412  // The above header #undefs ABSTRACT_TYPE and TYPE upon exit.
413
414  // Define WalkUpFrom*() and empty Visit*() for all Type classes.
415  bool WalkUpFromType(Type *T) { return getDerived().VisitType(T); }
416  bool VisitType(Type *T) { return true; }
417#define TYPE(CLASS, BASE)                                                      \
418  bool WalkUpFrom##CLASS##Type(CLASS##Type *T) {                               \
419    TRY_TO(WalkUpFrom##BASE(T));                                               \
420    TRY_TO(Visit##CLASS##Type(T));                                             \
421    return true;                                                               \
422  }                                                                            \
423  bool Visit##CLASS##Type(CLASS##Type *T) { return true; }
424#include "clang/AST/TypeNodes.def"
425
426// ---- Methods on TypeLocs ----
427// FIXME: this currently just calls the matching Type methods
428
429// Declare Traverse*() for all concrete TypeLoc classes.
430#define ABSTRACT_TYPELOC(CLASS, BASE)
431#define TYPELOC(CLASS, BASE) bool Traverse##CLASS##TypeLoc(CLASS##TypeLoc TL);
432#include "clang/AST/TypeLocNodes.def"
433  // The above header #undefs ABSTRACT_TYPELOC and TYPELOC upon exit.
434
435  // Define WalkUpFrom*() and empty Visit*() for all TypeLoc classes.
436  bool WalkUpFromTypeLoc(TypeLoc TL) { return getDerived().VisitTypeLoc(TL); }
437  bool VisitTypeLoc(TypeLoc TL) { return true; }
438
439  // QualifiedTypeLoc and UnqualTypeLoc are not declared in
440  // TypeNodes.def and thus need to be handled specially.
441  bool WalkUpFromQualifiedTypeLoc(QualifiedTypeLoc TL) {
442    return getDerived().VisitUnqualTypeLoc(TL.getUnqualifiedLoc());
443  }
444  bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { return true; }
445  bool WalkUpFromUnqualTypeLoc(UnqualTypeLoc TL) {
446    return getDerived().VisitUnqualTypeLoc(TL.getUnqualifiedLoc());
447  }
448  bool VisitUnqualTypeLoc(UnqualTypeLoc TL) { return true; }
449
450// Note that BASE includes trailing 'Type' which CLASS doesn't.
451#define TYPE(CLASS, BASE)                                                      \
452  bool WalkUpFrom##CLASS##TypeLoc(CLASS##TypeLoc TL) {                         \
453    TRY_TO(WalkUpFrom##BASE##Loc(TL));                                         \
454    TRY_TO(Visit##CLASS##TypeLoc(TL));                                         \
455    return true;                                                               \
456  }                                                                            \
457  bool Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { return true; }
458#include "clang/AST/TypeNodes.def"
459
460// ---- Methods on Decls ----
461
462// Declare Traverse*() for all concrete Decl classes.
463#define ABSTRACT_DECL(DECL)
464#define DECL(CLASS, BASE) bool Traverse##CLASS##Decl(CLASS##Decl *D);
465#include "clang/AST/DeclNodes.inc"
466  // The above header #undefs ABSTRACT_DECL and DECL upon exit.
467
468  // Define WalkUpFrom*() and empty Visit*() for all Decl classes.
469  bool WalkUpFromDecl(Decl *D) { return getDerived().VisitDecl(D); }
470  bool VisitDecl(Decl *D) { return true; }
471#define DECL(CLASS, BASE)                                                      \
472  bool WalkUpFrom##CLASS##Decl(CLASS##Decl *D) {                               \
473    TRY_TO(WalkUpFrom##BASE(D));                                               \
474    TRY_TO(Visit##CLASS##Decl(D));                                             \
475    return true;                                                               \
476  }                                                                            \
477  bool Visit##CLASS##Decl(CLASS##Decl *D) { return true; }
478#include "clang/AST/DeclNodes.inc"
479
480private:
481  // These are helper methods used by more than one Traverse* method.
482  bool TraverseTemplateParameterListHelper(TemplateParameterList *TPL);
483#define DEF_TRAVERSE_TMPL_INST(TMPLDECLKIND)                                   \
484  bool TraverseTemplateInstantiations(TMPLDECLKIND##TemplateDecl *D);
485  DEF_TRAVERSE_TMPL_INST(Class)
486  DEF_TRAVERSE_TMPL_INST(Var)
487  DEF_TRAVERSE_TMPL_INST(Function)
488#undef DEF_TRAVERSE_TMPL_INST
489  bool TraverseTemplateArgumentLocsHelper(const TemplateArgumentLoc *TAL,
490                                          unsigned Count);
491  bool TraverseArrayTypeLocHelper(ArrayTypeLoc TL);
492  bool TraverseRecordHelper(RecordDecl *D);
493  bool TraverseCXXRecordHelper(CXXRecordDecl *D);
494  bool TraverseDeclaratorHelper(DeclaratorDecl *D);
495  bool TraverseDeclContextHelper(DeclContext *DC);
496  bool TraverseFunctionHelper(FunctionDecl *D);
497  bool TraverseVarHelper(VarDecl *D);
498  bool TraverseOMPExecutableDirective(OMPExecutableDirective *S);
499  bool TraverseOMPLoopDirective(OMPLoopDirective *S);
500  bool TraverseOMPClause(OMPClause *C);
501#define OPENMP_CLAUSE(Name, Class) bool Visit##Class(Class *C);
502#include "clang/Basic/OpenMPKinds.def"
503  /// \brief Process clauses with list of variables.
504  template <typename T> bool VisitOMPClauseList(T *Node);
505  /// Process clauses with pre-initis.
506  bool VisitOMPClauseWithPreInit(OMPClauseWithPreInit *Node);
507  bool VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *Node);
508
509  bool dataTraverseNode(Stmt *S, DataRecursionQueue *Queue);
510  bool PostVisitStmt(Stmt *S);
511};
512
513template <typename Derived>
514bool RecursiveASTVisitor<Derived>::dataTraverseNode(Stmt *S,
515                                                    DataRecursionQueue *Queue) {
516#define DISPATCH_STMT(NAME, CLASS, VAR)                                        \
517  return TRAVERSE_STMT_BASE(NAME, CLASS, VAR, Queue);
518
519  // If we have a binary expr, dispatch to the subcode of the binop.  A smart
520  // optimizer (e.g. LLVM) will fold this comparison into the switch stmt
521  // below.
522  if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
523    switch (BinOp->getOpcode()) {
524#define OPERATOR(NAME)                                                         \
525  case BO_##NAME:                                                              \
526    DISPATCH_STMT(Bin##NAME, BinaryOperator, S);
527
528      BINOP_LIST()
529#undef OPERATOR
530#undef BINOP_LIST
531
532#define OPERATOR(NAME)                                                         \
533  case BO_##NAME##Assign:                                                      \
534    DISPATCH_STMT(Bin##NAME##Assign, CompoundAssignOperator, S);
535
536      CAO_LIST()
537#undef OPERATOR
538#undef CAO_LIST
539    }
540  } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(S)) {
541    switch (UnOp->getOpcode()) {
542#define OPERATOR(NAME)                                                         \
543  case UO_##NAME:                                                              \
544    DISPATCH_STMT(Unary##NAME, UnaryOperator, S);
545
546      UNARYOP_LIST()
547#undef OPERATOR
548#undef UNARYOP_LIST
549    }
550  }
551
552  // Top switch stmt: dispatch to TraverseFooStmt for each concrete FooStmt.
553  switch (S->getStmtClass()) {
554  case Stmt::NoStmtClass:
555    break;
556#define ABSTRACT_STMT(STMT)
557#define STMT(CLASS, PARENT)                                                    \
558  case Stmt::CLASS##Class:                                                     \
559    DISPATCH_STMT(CLASS, CLASS, S);
560#include "clang/AST/StmtNodes.inc"
561  }
562
563  return true;
564}
565
566#undef DISPATCH_STMT
567
568
569template <typename Derived>
570bool RecursiveASTVisitor<Derived>::PostVisitStmt(Stmt *S) {
571  switch (S->getStmtClass()) {
572  case Stmt::NoStmtClass:
573    break;
574#define ABSTRACT_STMT(STMT)
575#define STMT(CLASS, PARENT)                                                    \
576  case Stmt::CLASS##Class:                                                     \
577    TRY_TO(WalkUpFrom##CLASS(static_cast<CLASS *>(S))); break;
578#include "clang/AST/StmtNodes.inc"
579  }
580
581  return true;
582}
583
584#undef DISPATCH_STMT
585
586template <typename Derived>
587bool RecursiveASTVisitor<Derived>::TraverseStmt(Stmt *S,
588                                                DataRecursionQueue *Queue) {
589  if (!S)
590    return true;
591
592  if (Queue) {
593    Queue->push_back({S, false});
594    return true;
595  }
596
597  SmallVector<llvm::PointerIntPair<Stmt *, 1, bool>, 8> LocalQueue;
598  LocalQueue.push_back({S, false});
599
600  while (!LocalQueue.empty()) {
601    auto &CurrSAndVisited = LocalQueue.back();
602    Stmt *CurrS = CurrSAndVisited.getPointer();
603    bool Visited = CurrSAndVisited.getInt();
604    if (Visited) {
605      LocalQueue.pop_back();
606      TRY_TO(dataTraverseStmtPost(CurrS));
607      if (getDerived().shouldTraversePostOrder()) {
608        TRY_TO(PostVisitStmt(CurrS));
609      }
610      continue;
611    }
612
613    if (getDerived().dataTraverseStmtPre(CurrS)) {
614      CurrSAndVisited.setInt(true);
615      size_t N = LocalQueue.size();
616      TRY_TO(dataTraverseNode(CurrS, &LocalQueue));
617      // Process new children in the order they were added.
618      std::reverse(LocalQueue.begin() + N, LocalQueue.end());
619    } else {
620      LocalQueue.pop_back();
621    }
622  }
623
624  return true;
625}
626
627#define DISPATCH(NAME, CLASS, VAR)                                             \
628  return getDerived().Traverse##NAME(static_cast<CLASS *>(VAR))
629
630template <typename Derived>
631bool RecursiveASTVisitor<Derived>::TraverseType(QualType T) {
632  if (T.isNull())
633    return true;
634
635  switch (T->getTypeClass()) {
636#define ABSTRACT_TYPE(CLASS, BASE)
637#define TYPE(CLASS, BASE)                                                      \
638  case Type::CLASS:                                                            \
639    DISPATCH(CLASS##Type, CLASS##Type, const_cast<Type *>(T.getTypePtr()));
640#include "clang/AST/TypeNodes.def"
641  }
642
643  return true;
644}
645
646template <typename Derived>
647bool RecursiveASTVisitor<Derived>::TraverseTypeLoc(TypeLoc TL) {
648  if (TL.isNull())
649    return true;
650
651  switch (TL.getTypeLocClass()) {
652#define ABSTRACT_TYPELOC(CLASS, BASE)
653#define TYPELOC(CLASS, BASE)                                                   \
654  case TypeLoc::CLASS:                                                         \
655    return getDerived().Traverse##CLASS##TypeLoc(TL.castAs<CLASS##TypeLoc>());
656#include "clang/AST/TypeLocNodes.def"
657  }
658
659  return true;
660}
661
662// Define the Traverse*Attr(Attr* A) methods
663#define VISITORCLASS RecursiveASTVisitor
664#include "clang/AST/AttrVisitor.inc"
665#undef VISITORCLASS
666
667template <typename Derived>
668bool RecursiveASTVisitor<Derived>::TraverseDecl(Decl *D) {
669  if (!D)
670    return true;
671
672  // As a syntax visitor, by default we want to ignore declarations for
673  // implicit declarations (ones not typed explicitly by the user).
674  if (!getDerived().shouldVisitImplicitCode() && D->isImplicit())
675    return true;
676
677  switch (D->getKind()) {
678#define ABSTRACT_DECL(DECL)
679#define DECL(CLASS, BASE)                                                      \
680  case Decl::CLASS:                                                            \
681    if (!getDerived().Traverse##CLASS##Decl(static_cast<CLASS##Decl *>(D)))    \
682      return false;                                                            \
683    break;
684#include "clang/AST/DeclNodes.inc"
685  }
686
687  // Visit any attributes attached to this declaration.
688  for (auto *I : D->attrs()) {
689    if (!getDerived().TraverseAttr(I))
690      return false;
691  }
692  return true;
693}
694
695#undef DISPATCH
696
697template <typename Derived>
698bool RecursiveASTVisitor<Derived>::TraverseNestedNameSpecifier(
699    NestedNameSpecifier *NNS) {
700  if (!NNS)
701    return true;
702
703  if (NNS->getPrefix())
704    TRY_TO(TraverseNestedNameSpecifier(NNS->getPrefix()));
705
706  switch (NNS->getKind()) {
707  case NestedNameSpecifier::Identifier:
708  case NestedNameSpecifier::Namespace:
709  case NestedNameSpecifier::NamespaceAlias:
710  case NestedNameSpecifier::Global:
711  case NestedNameSpecifier::Super:
712    return true;
713
714  case NestedNameSpecifier::TypeSpec:
715  case NestedNameSpecifier::TypeSpecWithTemplate:
716    TRY_TO(TraverseType(QualType(NNS->getAsType(), 0)));
717  }
718
719  return true;
720}
721
722template <typename Derived>
723bool RecursiveASTVisitor<Derived>::TraverseNestedNameSpecifierLoc(
724    NestedNameSpecifierLoc NNS) {
725  if (!NNS)
726    return true;
727
728  if (NestedNameSpecifierLoc Prefix = NNS.getPrefix())
729    TRY_TO(TraverseNestedNameSpecifierLoc(Prefix));
730
731  switch (NNS.getNestedNameSpecifier()->getKind()) {
732  case NestedNameSpecifier::Identifier:
733  case NestedNameSpecifier::Namespace:
734  case NestedNameSpecifier::NamespaceAlias:
735  case NestedNameSpecifier::Global:
736  case NestedNameSpecifier::Super:
737    return true;
738
739  case NestedNameSpecifier::TypeSpec:
740  case NestedNameSpecifier::TypeSpecWithTemplate:
741    TRY_TO(TraverseTypeLoc(NNS.getTypeLoc()));
742    break;
743  }
744
745  return true;
746}
747
748template <typename Derived>
749bool RecursiveASTVisitor<Derived>::TraverseDeclarationNameInfo(
750    DeclarationNameInfo NameInfo) {
751  switch (NameInfo.getName().getNameKind()) {
752  case DeclarationName::CXXConstructorName:
753  case DeclarationName::CXXDestructorName:
754  case DeclarationName::CXXConversionFunctionName:
755    if (TypeSourceInfo *TSInfo = NameInfo.getNamedTypeInfo())
756      TRY_TO(TraverseTypeLoc(TSInfo->getTypeLoc()));
757
758    break;
759
760  case DeclarationName::Identifier:
761  case DeclarationName::ObjCZeroArgSelector:
762  case DeclarationName::ObjCOneArgSelector:
763  case DeclarationName::ObjCMultiArgSelector:
764  case DeclarationName::CXXOperatorName:
765  case DeclarationName::CXXLiteralOperatorName:
766  case DeclarationName::CXXUsingDirective:
767    break;
768  }
769
770  return true;
771}
772
773template <typename Derived>
774bool RecursiveASTVisitor<Derived>::TraverseTemplateName(TemplateName Template) {
775  if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
776    TRY_TO(TraverseNestedNameSpecifier(DTN->getQualifier()));
777  else if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
778    TRY_TO(TraverseNestedNameSpecifier(QTN->getQualifier()));
779
780  return true;
781}
782
783template <typename Derived>
784bool RecursiveASTVisitor<Derived>::TraverseTemplateArgument(
785    const TemplateArgument &Arg) {
786  switch (Arg.getKind()) {
787  case TemplateArgument::Null:
788  case TemplateArgument::Declaration:
789  case TemplateArgument::Integral:
790  case TemplateArgument::NullPtr:
791    return true;
792
793  case TemplateArgument::Type:
794    return getDerived().TraverseType(Arg.getAsType());
795
796  case TemplateArgument::Template:
797  case TemplateArgument::TemplateExpansion:
798    return getDerived().TraverseTemplateName(
799        Arg.getAsTemplateOrTemplatePattern());
800
801  case TemplateArgument::Expression:
802    return getDerived().TraverseStmt(Arg.getAsExpr());
803
804  case TemplateArgument::Pack:
805    return getDerived().TraverseTemplateArguments(Arg.pack_begin(),
806                                                  Arg.pack_size());
807  }
808
809  return true;
810}
811
812// FIXME: no template name location?
813// FIXME: no source locations for a template argument pack?
814template <typename Derived>
815bool RecursiveASTVisitor<Derived>::TraverseTemplateArgumentLoc(
816    const TemplateArgumentLoc &ArgLoc) {
817  const TemplateArgument &Arg = ArgLoc.getArgument();
818
819  switch (Arg.getKind()) {
820  case TemplateArgument::Null:
821  case TemplateArgument::Declaration:
822  case TemplateArgument::Integral:
823  case TemplateArgument::NullPtr:
824    return true;
825
826  case TemplateArgument::Type: {
827    // FIXME: how can TSI ever be NULL?
828    if (TypeSourceInfo *TSI = ArgLoc.getTypeSourceInfo())
829      return getDerived().TraverseTypeLoc(TSI->getTypeLoc());
830    else
831      return getDerived().TraverseType(Arg.getAsType());
832  }
833
834  case TemplateArgument::Template:
835  case TemplateArgument::TemplateExpansion:
836    if (ArgLoc.getTemplateQualifierLoc())
837      TRY_TO(getDerived().TraverseNestedNameSpecifierLoc(
838          ArgLoc.getTemplateQualifierLoc()));
839    return getDerived().TraverseTemplateName(
840        Arg.getAsTemplateOrTemplatePattern());
841
842  case TemplateArgument::Expression:
843    return getDerived().TraverseStmt(ArgLoc.getSourceExpression());
844
845  case TemplateArgument::Pack:
846    return getDerived().TraverseTemplateArguments(Arg.pack_begin(),
847                                                  Arg.pack_size());
848  }
849
850  return true;
851}
852
853template <typename Derived>
854bool RecursiveASTVisitor<Derived>::TraverseTemplateArguments(
855    const TemplateArgument *Args, unsigned NumArgs) {
856  for (unsigned I = 0; I != NumArgs; ++I) {
857    TRY_TO(TraverseTemplateArgument(Args[I]));
858  }
859
860  return true;
861}
862
863template <typename Derived>
864bool RecursiveASTVisitor<Derived>::TraverseConstructorInitializer(
865    CXXCtorInitializer *Init) {
866  if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo())
867    TRY_TO(TraverseTypeLoc(TInfo->getTypeLoc()));
868
869  if (Init->isWritten() || getDerived().shouldVisitImplicitCode())
870    TRY_TO(TraverseStmt(Init->getInit()));
871
872  if (getDerived().shouldVisitImplicitCode())
873    // The braces for this one-line loop are required for MSVC2013.  It
874    // refuses to compile
875    //     for (int i : int_vec)
876    //       do {} while(false);
877    // without braces on the for loop.
878    for (VarDecl *VD : Init->getArrayIndices()) {
879      TRY_TO(TraverseDecl(VD));
880    }
881
882  return true;
883}
884
885template <typename Derived>
886bool
887RecursiveASTVisitor<Derived>::TraverseLambdaCapture(LambdaExpr *LE,
888                                                    const LambdaCapture *C) {
889  if (LE->isInitCapture(C))
890    TRY_TO(TraverseDecl(C->getCapturedVar()));
891  return true;
892}
893
894template <typename Derived>
895bool RecursiveASTVisitor<Derived>::TraverseLambdaBody(
896    LambdaExpr *LE, DataRecursionQueue *Queue) {
897  TRY_TO_TRAVERSE_OR_ENQUEUE_STMT(LE->getBody());
898  return true;
899}
900
901// ----------------- Type traversal -----------------
902
903// This macro makes available a variable T, the passed-in type.
904#define DEF_TRAVERSE_TYPE(TYPE, CODE)                                          \
905  template <typename Derived>                                                  \
906  bool RecursiveASTVisitor<Derived>::Traverse##TYPE(TYPE *T) {                 \
907    if (!getDerived().shouldTraversePostOrder())                               \
908      TRY_TO(WalkUpFrom##TYPE(T));                                             \
909    { CODE; }                                                                  \
910    if (getDerived().shouldTraversePostOrder())                                \
911      TRY_TO(WalkUpFrom##TYPE(T));                                             \
912    return true;                                                               \
913  }
914
915DEF_TRAVERSE_TYPE(BuiltinType, {})
916
917DEF_TRAVERSE_TYPE(ComplexType, { TRY_TO(TraverseType(T->getElementType())); })
918
919DEF_TRAVERSE_TYPE(PointerType, { TRY_TO(TraverseType(T->getPointeeType())); })
920
921DEF_TRAVERSE_TYPE(BlockPointerType,
922                  { TRY_TO(TraverseType(T->getPointeeType())); })
923
924DEF_TRAVERSE_TYPE(LValueReferenceType,
925                  { TRY_TO(TraverseType(T->getPointeeType())); })
926
927DEF_TRAVERSE_TYPE(RValueReferenceType,
928                  { TRY_TO(TraverseType(T->getPointeeType())); })
929
930DEF_TRAVERSE_TYPE(MemberPointerType, {
931  TRY_TO(TraverseType(QualType(T->getClass(), 0)));
932  TRY_TO(TraverseType(T->getPointeeType()));
933})
934
935DEF_TRAVERSE_TYPE(AdjustedType, { TRY_TO(TraverseType(T->getOriginalType())); })
936
937DEF_TRAVERSE_TYPE(DecayedType, { TRY_TO(TraverseType(T->getOriginalType())); })
938
939DEF_TRAVERSE_TYPE(ConstantArrayType,
940                  { TRY_TO(TraverseType(T->getElementType())); })
941
942DEF_TRAVERSE_TYPE(IncompleteArrayType,
943                  { TRY_TO(TraverseType(T->getElementType())); })
944
945DEF_TRAVERSE_TYPE(VariableArrayType, {
946  TRY_TO(TraverseType(T->getElementType()));
947  TRY_TO(TraverseStmt(T->getSizeExpr()));
948})
949
950DEF_TRAVERSE_TYPE(DependentSizedArrayType, {
951  TRY_TO(TraverseType(T->getElementType()));
952  if (T->getSizeExpr())
953    TRY_TO(TraverseStmt(T->getSizeExpr()));
954})
955
956DEF_TRAVERSE_TYPE(DependentSizedExtVectorType, {
957  if (T->getSizeExpr())
958    TRY_TO(TraverseStmt(T->getSizeExpr()));
959  TRY_TO(TraverseType(T->getElementType()));
960})
961
962DEF_TRAVERSE_TYPE(VectorType, { TRY_TO(TraverseType(T->getElementType())); })
963
964DEF_TRAVERSE_TYPE(ExtVectorType, { TRY_TO(TraverseType(T->getElementType())); })
965
966DEF_TRAVERSE_TYPE(FunctionNoProtoType,
967                  { TRY_TO(TraverseType(T->getReturnType())); })
968
969DEF_TRAVERSE_TYPE(FunctionProtoType, {
970  TRY_TO(TraverseType(T->getReturnType()));
971
972  for (const auto &A : T->param_types()) {
973    TRY_TO(TraverseType(A));
974  }
975
976  for (const auto &E : T->exceptions()) {
977    TRY_TO(TraverseType(E));
978  }
979
980  if (Expr *NE = T->getNoexceptExpr())
981    TRY_TO(TraverseStmt(NE));
982})
983
984DEF_TRAVERSE_TYPE(UnresolvedUsingType, {})
985DEF_TRAVERSE_TYPE(TypedefType, {})
986
987DEF_TRAVERSE_TYPE(TypeOfExprType,
988                  { TRY_TO(TraverseStmt(T->getUnderlyingExpr())); })
989
990DEF_TRAVERSE_TYPE(TypeOfType, { TRY_TO(TraverseType(T->getUnderlyingType())); })
991
992DEF_TRAVERSE_TYPE(DecltypeType,
993                  { TRY_TO(TraverseStmt(T->getUnderlyingExpr())); })
994
995DEF_TRAVERSE_TYPE(UnaryTransformType, {
996  TRY_TO(TraverseType(T->getBaseType()));
997  TRY_TO(TraverseType(T->getUnderlyingType()));
998})
999
1000DEF_TRAVERSE_TYPE(AutoType, { TRY_TO(TraverseType(T->getDeducedType())); })
1001
1002DEF_TRAVERSE_TYPE(RecordType, {})
1003DEF_TRAVERSE_TYPE(EnumType, {})
1004DEF_TRAVERSE_TYPE(TemplateTypeParmType, {})
1005DEF_TRAVERSE_TYPE(SubstTemplateTypeParmType, {})
1006DEF_TRAVERSE_TYPE(SubstTemplateTypeParmPackType, {})
1007
1008DEF_TRAVERSE_TYPE(TemplateSpecializationType, {
1009  TRY_TO(TraverseTemplateName(T->getTemplateName()));
1010  TRY_TO(TraverseTemplateArguments(T->getArgs(), T->getNumArgs()));
1011})
1012
1013DEF_TRAVERSE_TYPE(InjectedClassNameType, {})
1014
1015DEF_TRAVERSE_TYPE(AttributedType,
1016                  { TRY_TO(TraverseType(T->getModifiedType())); })
1017
1018DEF_TRAVERSE_TYPE(ParenType, { TRY_TO(TraverseType(T->getInnerType())); })
1019
1020DEF_TRAVERSE_TYPE(ElaboratedType, {
1021  if (T->getQualifier()) {
1022    TRY_TO(TraverseNestedNameSpecifier(T->getQualifier()));
1023  }
1024  TRY_TO(TraverseType(T->getNamedType()));
1025})
1026
1027DEF_TRAVERSE_TYPE(DependentNameType,
1028                  { TRY_TO(TraverseNestedNameSpecifier(T->getQualifier())); })
1029
1030DEF_TRAVERSE_TYPE(DependentTemplateSpecializationType, {
1031  TRY_TO(TraverseNestedNameSpecifier(T->getQualifier()));
1032  TRY_TO(TraverseTemplateArguments(T->getArgs(), T->getNumArgs()));
1033})
1034
1035DEF_TRAVERSE_TYPE(PackExpansionType, { TRY_TO(TraverseType(T->getPattern())); })
1036
1037DEF_TRAVERSE_TYPE(ObjCInterfaceType, {})
1038
1039DEF_TRAVERSE_TYPE(ObjCObjectType, {
1040  // We have to watch out here because an ObjCInterfaceType's base
1041  // type is itself.
1042  if (T->getBaseType().getTypePtr() != T)
1043    TRY_TO(TraverseType(T->getBaseType()));
1044  for (auto typeArg : T->getTypeArgsAsWritten()) {
1045    TRY_TO(TraverseType(typeArg));
1046  }
1047})
1048
1049DEF_TRAVERSE_TYPE(ObjCObjectPointerType,
1050                  { TRY_TO(TraverseType(T->getPointeeType())); })
1051
1052DEF_TRAVERSE_TYPE(AtomicType, { TRY_TO(TraverseType(T->getValueType())); })
1053
1054DEF_TRAVERSE_TYPE(PipeType, { TRY_TO(TraverseType(T->getElementType())); })
1055
1056#undef DEF_TRAVERSE_TYPE
1057
1058// ----------------- TypeLoc traversal -----------------
1059
1060// This macro makes available a variable TL, the passed-in TypeLoc.
1061// If requested, it calls WalkUpFrom* for the Type in the given TypeLoc,
1062// in addition to WalkUpFrom* for the TypeLoc itself, such that existing
1063// clients that override the WalkUpFrom*Type() and/or Visit*Type() methods
1064// continue to work.
1065#define DEF_TRAVERSE_TYPELOC(TYPE, CODE)                                       \
1066  template <typename Derived>                                                  \
1067  bool RecursiveASTVisitor<Derived>::Traverse##TYPE##Loc(TYPE##Loc TL) {       \
1068    if (getDerived().shouldWalkTypesOfTypeLocs())                              \
1069      TRY_TO(WalkUpFrom##TYPE(const_cast<TYPE *>(TL.getTypePtr())));           \
1070    TRY_TO(WalkUpFrom##TYPE##Loc(TL));                                         \
1071    { CODE; }                                                                  \
1072    return true;                                                               \
1073  }
1074
1075template <typename Derived>
1076bool
1077RecursiveASTVisitor<Derived>::TraverseQualifiedTypeLoc(QualifiedTypeLoc TL) {
1078  // Move this over to the 'main' typeloc tree.  Note that this is a
1079  // move -- we pretend that we were really looking at the unqualified
1080  // typeloc all along -- rather than a recursion, so we don't follow
1081  // the normal CRTP plan of going through
1082  // getDerived().TraverseTypeLoc.  If we did, we'd be traversing
1083  // twice for the same type (once as a QualifiedTypeLoc version of
1084  // the type, once as an UnqualifiedTypeLoc version of the type),
1085  // which in effect means we'd call VisitTypeLoc twice with the
1086  // 'same' type.  This solves that problem, at the cost of never
1087  // seeing the qualified version of the type (unless the client
1088  // subclasses TraverseQualifiedTypeLoc themselves).  It's not a
1089  // perfect solution.  A perfect solution probably requires making
1090  // QualifiedTypeLoc a wrapper around TypeLoc -- like QualType is a
1091  // wrapper around Type* -- rather than being its own class in the
1092  // type hierarchy.
1093  return TraverseTypeLoc(TL.getUnqualifiedLoc());
1094}
1095
1096DEF_TRAVERSE_TYPELOC(BuiltinType, {})
1097
1098// FIXME: ComplexTypeLoc is unfinished
1099DEF_TRAVERSE_TYPELOC(ComplexType, {
1100  TRY_TO(TraverseType(TL.getTypePtr()->getElementType()));
1101})
1102
1103DEF_TRAVERSE_TYPELOC(PointerType,
1104                     { TRY_TO(TraverseTypeLoc(TL.getPointeeLoc())); })
1105
1106DEF_TRAVERSE_TYPELOC(BlockPointerType,
1107                     { TRY_TO(TraverseTypeLoc(TL.getPointeeLoc())); })
1108
1109DEF_TRAVERSE_TYPELOC(LValueReferenceType,
1110                     { TRY_TO(TraverseTypeLoc(TL.getPointeeLoc())); })
1111
1112DEF_TRAVERSE_TYPELOC(RValueReferenceType,
1113                     { TRY_TO(TraverseTypeLoc(TL.getPointeeLoc())); })
1114
1115// FIXME: location of base class?
1116// We traverse this in the type case as well, but how is it not reached through
1117// the pointee type?
1118DEF_TRAVERSE_TYPELOC(MemberPointerType, {
1119  TRY_TO(TraverseType(QualType(TL.getTypePtr()->getClass(), 0)));
1120  TRY_TO(TraverseTypeLoc(TL.getPointeeLoc()));
1121})
1122
1123DEF_TRAVERSE_TYPELOC(AdjustedType,
1124                     { TRY_TO(TraverseTypeLoc(TL.getOriginalLoc())); })
1125
1126DEF_TRAVERSE_TYPELOC(DecayedType,
1127                     { TRY_TO(TraverseTypeLoc(TL.getOriginalLoc())); })
1128
1129template <typename Derived>
1130bool RecursiveASTVisitor<Derived>::TraverseArrayTypeLocHelper(ArrayTypeLoc TL) {
1131  // This isn't available for ArrayType, but is for the ArrayTypeLoc.
1132  TRY_TO(TraverseStmt(TL.getSizeExpr()));
1133  return true;
1134}
1135
1136DEF_TRAVERSE_TYPELOC(ConstantArrayType, {
1137  TRY_TO(TraverseTypeLoc(TL.getElementLoc()));
1138  return TraverseArrayTypeLocHelper(TL);
1139})
1140
1141DEF_TRAVERSE_TYPELOC(IncompleteArrayType, {
1142  TRY_TO(TraverseTypeLoc(TL.getElementLoc()));
1143  return TraverseArrayTypeLocHelper(TL);
1144})
1145
1146DEF_TRAVERSE_TYPELOC(VariableArrayType, {
1147  TRY_TO(TraverseTypeLoc(TL.getElementLoc()));
1148  return TraverseArrayTypeLocHelper(TL);
1149})
1150
1151DEF_TRAVERSE_TYPELOC(DependentSizedArrayType, {
1152  TRY_TO(TraverseTypeLoc(TL.getElementLoc()));
1153  return TraverseArrayTypeLocHelper(TL);
1154})
1155
1156// FIXME: order? why not size expr first?
1157// FIXME: base VectorTypeLoc is unfinished
1158DEF_TRAVERSE_TYPELOC(DependentSizedExtVectorType, {
1159  if (TL.getTypePtr()->getSizeExpr())
1160    TRY_TO(TraverseStmt(TL.getTypePtr()->getSizeExpr()));
1161  TRY_TO(TraverseType(TL.getTypePtr()->getElementType()));
1162})
1163
1164// FIXME: VectorTypeLoc is unfinished
1165DEF_TRAVERSE_TYPELOC(VectorType, {
1166  TRY_TO(TraverseType(TL.getTypePtr()->getElementType()));
1167})
1168
1169// FIXME: size and attributes
1170// FIXME: base VectorTypeLoc is unfinished
1171DEF_TRAVERSE_TYPELOC(ExtVectorType, {
1172  TRY_TO(TraverseType(TL.getTypePtr()->getElementType()));
1173})
1174
1175DEF_TRAVERSE_TYPELOC(FunctionNoProtoType,
1176                     { TRY_TO(TraverseTypeLoc(TL.getReturnLoc())); })
1177
1178// FIXME: location of exception specifications (attributes?)
1179DEF_TRAVERSE_TYPELOC(FunctionProtoType, {
1180  TRY_TO(TraverseTypeLoc(TL.getReturnLoc()));
1181
1182  const FunctionProtoType *T = TL.getTypePtr();
1183
1184  for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
1185    if (TL.getParam(I)) {
1186      TRY_TO(TraverseDecl(TL.getParam(I)));
1187    } else if (I < T->getNumParams()) {
1188      TRY_TO(TraverseType(T->getParamType(I)));
1189    }
1190  }
1191
1192  for (const auto &E : T->exceptions()) {
1193    TRY_TO(TraverseType(E));
1194  }
1195
1196  if (Expr *NE = T->getNoexceptExpr())
1197    TRY_TO(TraverseStmt(NE));
1198})
1199
1200DEF_TRAVERSE_TYPELOC(UnresolvedUsingType, {})
1201DEF_TRAVERSE_TYPELOC(TypedefType, {})
1202
1203DEF_TRAVERSE_TYPELOC(TypeOfExprType,
1204                     { TRY_TO(TraverseStmt(TL.getUnderlyingExpr())); })
1205
1206DEF_TRAVERSE_TYPELOC(TypeOfType, {
1207  TRY_TO(TraverseTypeLoc(TL.getUnderlyingTInfo()->getTypeLoc()));
1208})
1209
1210// FIXME: location of underlying expr
1211DEF_TRAVERSE_TYPELOC(DecltypeType, {
1212  TRY_TO(TraverseStmt(TL.getTypePtr()->getUnderlyingExpr()));
1213})
1214
1215DEF_TRAVERSE_TYPELOC(UnaryTransformType, {
1216  TRY_TO(TraverseTypeLoc(TL.getUnderlyingTInfo()->getTypeLoc()));
1217})
1218
1219DEF_TRAVERSE_TYPELOC(AutoType, {
1220  TRY_TO(TraverseType(TL.getTypePtr()->getDeducedType()));
1221})
1222
1223DEF_TRAVERSE_TYPELOC(RecordType, {})
1224DEF_TRAVERSE_TYPELOC(EnumType, {})
1225DEF_TRAVERSE_TYPELOC(TemplateTypeParmType, {})
1226DEF_TRAVERSE_TYPELOC(SubstTemplateTypeParmType, {})
1227DEF_TRAVERSE_TYPELOC(SubstTemplateTypeParmPackType, {})
1228
1229// FIXME: use the loc for the template name?
1230DEF_TRAVERSE_TYPELOC(TemplateSpecializationType, {
1231  TRY_TO(TraverseTemplateName(TL.getTypePtr()->getTemplateName()));
1232  for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
1233    TRY_TO(TraverseTemplateArgumentLoc(TL.getArgLoc(I)));
1234  }
1235})
1236
1237DEF_TRAVERSE_TYPELOC(InjectedClassNameType, {})
1238
1239DEF_TRAVERSE_TYPELOC(ParenType, { TRY_TO(TraverseTypeLoc(TL.getInnerLoc())); })
1240
1241DEF_TRAVERSE_TYPELOC(AttributedType,
1242                     { TRY_TO(TraverseTypeLoc(TL.getModifiedLoc())); })
1243
1244DEF_TRAVERSE_TYPELOC(ElaboratedType, {
1245  if (TL.getQualifierLoc()) {
1246    TRY_TO(TraverseNestedNameSpecifierLoc(TL.getQualifierLoc()));
1247  }
1248  TRY_TO(TraverseTypeLoc(TL.getNamedTypeLoc()));
1249})
1250
1251DEF_TRAVERSE_TYPELOC(DependentNameType, {
1252  TRY_TO(TraverseNestedNameSpecifierLoc(TL.getQualifierLoc()));
1253})
1254
1255DEF_TRAVERSE_TYPELOC(DependentTemplateSpecializationType, {
1256  if (TL.getQualifierLoc()) {
1257    TRY_TO(TraverseNestedNameSpecifierLoc(TL.getQualifierLoc()));
1258  }
1259
1260  for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
1261    TRY_TO(TraverseTemplateArgumentLoc(TL.getArgLoc(I)));
1262  }
1263})
1264
1265DEF_TRAVERSE_TYPELOC(PackExpansionType,
1266                     { TRY_TO(TraverseTypeLoc(TL.getPatternLoc())); })
1267
1268DEF_TRAVERSE_TYPELOC(ObjCInterfaceType, {})
1269
1270DEF_TRAVERSE_TYPELOC(ObjCObjectType, {
1271  // We have to watch out here because an ObjCInterfaceType's base
1272  // type is itself.
1273  if (TL.getTypePtr()->getBaseType().getTypePtr() != TL.getTypePtr())
1274    TRY_TO(TraverseTypeLoc(TL.getBaseLoc()));
1275  for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i)
1276    TRY_TO(TraverseTypeLoc(TL.getTypeArgTInfo(i)->getTypeLoc()));
1277})
1278
1279DEF_TRAVERSE_TYPELOC(ObjCObjectPointerType,
1280                     { TRY_TO(TraverseTypeLoc(TL.getPointeeLoc())); })
1281
1282DEF_TRAVERSE_TYPELOC(AtomicType, { TRY_TO(TraverseTypeLoc(TL.getValueLoc())); })
1283
1284DEF_TRAVERSE_TYPELOC(PipeType, { TRY_TO(TraverseTypeLoc(TL.getValueLoc())); })
1285
1286#undef DEF_TRAVERSE_TYPELOC
1287
1288// ----------------- Decl traversal -----------------
1289//
1290// For a Decl, we automate (in the DEF_TRAVERSE_DECL macro) traversing
1291// the children that come from the DeclContext associated with it.
1292// Therefore each Traverse* only needs to worry about children other
1293// than those.
1294
1295template <typename Derived>
1296bool RecursiveASTVisitor<Derived>::TraverseDeclContextHelper(DeclContext *DC) {
1297  if (!DC)
1298    return true;
1299
1300  for (auto *Child : DC->decls()) {
1301    // BlockDecls and CapturedDecls are traversed through BlockExprs and
1302    // CapturedStmts respectively.
1303    if (!isa<BlockDecl>(Child) && !isa<CapturedDecl>(Child))
1304      TRY_TO(TraverseDecl(Child));
1305  }
1306
1307  return true;
1308}
1309
1310// This macro makes available a variable D, the passed-in decl.
1311#define DEF_TRAVERSE_DECL(DECL, CODE)                                          \
1312  template <typename Derived>                                                  \
1313  bool RecursiveASTVisitor<Derived>::Traverse##DECL(DECL *D) {                 \
1314    bool ShouldVisitChildren = true;                                           \
1315    bool ReturnValue = true;                                                   \
1316    if (!getDerived().shouldTraversePostOrder())                               \
1317      TRY_TO(WalkUpFrom##DECL(D));                                             \
1318    { CODE; }                                                                  \
1319    if (ReturnValue && ShouldVisitChildren)                                    \
1320      TRY_TO(TraverseDeclContextHelper(dyn_cast<DeclContext>(D)));             \
1321    if (ReturnValue && getDerived().shouldTraversePostOrder())                 \
1322      TRY_TO(WalkUpFrom##DECL(D));                                             \
1323    return ReturnValue;                                                        \
1324  }
1325
1326DEF_TRAVERSE_DECL(AccessSpecDecl, {})
1327
1328DEF_TRAVERSE_DECL(BlockDecl, {
1329  if (TypeSourceInfo *TInfo = D->getSignatureAsWritten())
1330    TRY_TO(TraverseTypeLoc(TInfo->getTypeLoc()));
1331  TRY_TO(TraverseStmt(D->getBody()));
1332  for (const auto &I : D->captures()) {
1333    if (I.hasCopyExpr()) {
1334      TRY_TO(TraverseStmt(I.getCopyExpr()));
1335    }
1336  }
1337  ShouldVisitChildren = false;
1338})
1339
1340DEF_TRAVERSE_DECL(CapturedDecl, {
1341  TRY_TO(TraverseStmt(D->getBody()));
1342  ShouldVisitChildren = false;
1343})
1344
1345DEF_TRAVERSE_DECL(EmptyDecl, {})
1346
1347DEF_TRAVERSE_DECL(FileScopeAsmDecl,
1348                  { TRY_TO(TraverseStmt(D->getAsmString())); })
1349
1350DEF_TRAVERSE_DECL(ImportDecl, {})
1351
1352DEF_TRAVERSE_DECL(FriendDecl, {
1353  // Friend is either decl or a type.
1354  if (D->getFriendType())
1355    TRY_TO(TraverseTypeLoc(D->getFriendType()->getTypeLoc()));
1356  else
1357    TRY_TO(TraverseDecl(D->getFriendDecl()));
1358})
1359
1360DEF_TRAVERSE_DECL(FriendTemplateDecl, {
1361  if (D->getFriendType())
1362    TRY_TO(TraverseTypeLoc(D->getFriendType()->getTypeLoc()));
1363  else
1364    TRY_TO(TraverseDecl(D->getFriendDecl()));
1365  for (unsigned I = 0, E = D->getNumTemplateParameters(); I < E; ++I) {
1366    TemplateParameterList *TPL = D->getTemplateParameterList(I);
1367    for (TemplateParameterList::iterator ITPL = TPL->begin(), ETPL = TPL->end();
1368         ITPL != ETPL; ++ITPL) {
1369      TRY_TO(TraverseDecl(*ITPL));
1370    }
1371  }
1372})
1373
1374DEF_TRAVERSE_DECL(ClassScopeFunctionSpecializationDecl, {
1375  TRY_TO(TraverseDecl(D->getSpecialization()));
1376
1377  if (D->hasExplicitTemplateArgs()) {
1378    const TemplateArgumentListInfo &args = D->templateArgs();
1379    TRY_TO(TraverseTemplateArgumentLocsHelper(args.getArgumentArray(),
1380                                              args.size()));
1381  }
1382})
1383
1384DEF_TRAVERSE_DECL(LinkageSpecDecl, {})
1385
1386DEF_TRAVERSE_DECL(ObjCPropertyImplDecl, {// FIXME: implement this
1387                                        })
1388
1389DEF_TRAVERSE_DECL(StaticAssertDecl, {
1390  TRY_TO(TraverseStmt(D->getAssertExpr()));
1391  TRY_TO(TraverseStmt(D->getMessage()));
1392})
1393
1394DEF_TRAVERSE_DECL(
1395    TranslationUnitDecl,
1396    {// Code in an unnamed namespace shows up automatically in
1397     // decls_begin()/decls_end().  Thus we don't need to recurse on
1398     // D->getAnonymousNamespace().
1399    })
1400
1401DEF_TRAVERSE_DECL(PragmaCommentDecl, {})
1402
1403DEF_TRAVERSE_DECL(PragmaDetectMismatchDecl, {})
1404
1405DEF_TRAVERSE_DECL(ExternCContextDecl, {})
1406
1407DEF_TRAVERSE_DECL(NamespaceAliasDecl, {
1408  TRY_TO(TraverseNestedNameSpecifierLoc(D->getQualifierLoc()));
1409
1410  // We shouldn't traverse an aliased namespace, since it will be
1411  // defined (and, therefore, traversed) somewhere else.
1412  ShouldVisitChildren = false;
1413})
1414
1415DEF_TRAVERSE_DECL(LabelDecl, {// There is no code in a LabelDecl.
1416                             })
1417
1418DEF_TRAVERSE_DECL(
1419    NamespaceDecl,
1420    {// Code in an unnamed namespace shows up automatically in
1421     // decls_begin()/decls_end().  Thus we don't need to recurse on
1422     // D->getAnonymousNamespace().
1423    })
1424
1425DEF_TRAVERSE_DECL(ObjCCompatibleAliasDecl, {// FIXME: implement
1426                                           })
1427
1428DEF_TRAVERSE_DECL(ObjCCategoryDecl, {// FIXME: implement
1429  if (ObjCTypeParamList *typeParamList = D->getTypeParamList()) {
1430    for (auto typeParam : *typeParamList) {
1431      TRY_TO(TraverseObjCTypeParamDecl(typeParam));
1432    }
1433  }
1434})
1435
1436DEF_TRAVERSE_DECL(ObjCCategoryImplDecl, {// FIXME: implement
1437                                        })
1438
1439DEF_TRAVERSE_DECL(ObjCImplementationDecl, {// FIXME: implement
1440                                          })
1441
1442DEF_TRAVERSE_DECL(ObjCInterfaceDecl, {// FIXME: implement
1443  if (ObjCTypeParamList *typeParamList = D->getTypeParamListAsWritten()) {
1444    for (auto typeParam : *typeParamList) {
1445      TRY_TO(TraverseObjCTypeParamDecl(typeParam));
1446    }
1447  }
1448
1449  if (TypeSourceInfo *superTInfo = D->getSuperClassTInfo()) {
1450    TRY_TO(TraverseTypeLoc(superTInfo->getTypeLoc()));
1451  }
1452})
1453
1454DEF_TRAVERSE_DECL(ObjCProtocolDecl, {// FIXME: implement
1455                                    })
1456
1457DEF_TRAVERSE_DECL(ObjCMethodDecl, {
1458  if (D->getReturnTypeSourceInfo()) {
1459    TRY_TO(TraverseTypeLoc(D->getReturnTypeSourceInfo()->getTypeLoc()));
1460  }
1461  for (ParmVarDecl *Parameter : D->parameters()) {
1462    TRY_TO(TraverseDecl(Parameter));
1463  }
1464  if (D->isThisDeclarationADefinition()) {
1465    TRY_TO(TraverseStmt(D->getBody()));
1466  }
1467  ShouldVisitChildren = false;
1468})
1469
1470DEF_TRAVERSE_DECL(ObjCTypeParamDecl, {
1471  if (D->hasExplicitBound()) {
1472    TRY_TO(TraverseTypeLoc(D->getTypeSourceInfo()->getTypeLoc()));
1473    // We shouldn't traverse D->getTypeForDecl(); it's a result of
1474    // declaring the type alias, not something that was written in the
1475    // source.
1476  }
1477})
1478
1479DEF_TRAVERSE_DECL(ObjCPropertyDecl, {
1480  if (D->getTypeSourceInfo())
1481    TRY_TO(TraverseTypeLoc(D->getTypeSourceInfo()->getTypeLoc()));
1482  else
1483    TRY_TO(TraverseType(D->getType()));
1484  ShouldVisitChildren = false;
1485})
1486
1487DEF_TRAVERSE_DECL(UsingDecl, {
1488  TRY_TO(TraverseNestedNameSpecifierLoc(D->getQualifierLoc()));
1489  TRY_TO(TraverseDeclarationNameInfo(D->getNameInfo()));
1490})
1491
1492DEF_TRAVERSE_DECL(UsingDirectiveDecl, {
1493  TRY_TO(TraverseNestedNameSpecifierLoc(D->getQualifierLoc()));
1494})
1495
1496DEF_TRAVERSE_DECL(UsingShadowDecl, {})
1497
1498DEF_TRAVERSE_DECL(ConstructorUsingShadowDecl, {})
1499
1500DEF_TRAVERSE_DECL(OMPThreadPrivateDecl, {
1501  for (auto *I : D->varlists()) {
1502    TRY_TO(TraverseStmt(I));
1503  }
1504})
1505
1506DEF_TRAVERSE_DECL(OMPDeclareReductionDecl, {
1507  TRY_TO(TraverseStmt(D->getCombiner()));
1508  if (auto *Initializer = D->getInitializer())
1509    TRY_TO(TraverseStmt(Initializer));
1510  TRY_TO(TraverseType(D->getType()));
1511  return true;
1512})
1513
1514DEF_TRAVERSE_DECL(OMPCapturedExprDecl, { TRY_TO(TraverseVarHelper(D)); })
1515
1516// A helper method for TemplateDecl's children.
1517template <typename Derived>
1518bool RecursiveASTVisitor<Derived>::TraverseTemplateParameterListHelper(
1519    TemplateParameterList *TPL) {
1520  if (TPL) {
1521    for (TemplateParameterList::iterator I = TPL->begin(), E = TPL->end();
1522         I != E; ++I) {
1523      TRY_TO(TraverseDecl(*I));
1524    }
1525  }
1526  return true;
1527}
1528
1529template <typename Derived>
1530bool RecursiveASTVisitor<Derived>::TraverseTemplateInstantiations(
1531    ClassTemplateDecl *D) {
1532  for (auto *SD : D->specializations()) {
1533    for (auto *RD : SD->redecls()) {
1534      // We don't want to visit injected-class-names in this traversal.
1535      if (cast<CXXRecordDecl>(RD)->isInjectedClassName())
1536        continue;
1537
1538      switch (
1539          cast<ClassTemplateSpecializationDecl>(RD)->getSpecializationKind()) {
1540      // Visit the implicit instantiations with the requested pattern.
1541      case TSK_Undeclared:
1542      case TSK_ImplicitInstantiation:
1543        TRY_TO(TraverseDecl(RD));
1544        break;
1545
1546      // We don't need to do anything on an explicit instantiation
1547      // or explicit specialization because there will be an explicit
1548      // node for it elsewhere.
1549      case TSK_ExplicitInstantiationDeclaration:
1550      case TSK_ExplicitInstantiationDefinition:
1551      case TSK_ExplicitSpecialization:
1552        break;
1553      }
1554    }
1555  }
1556
1557  return true;
1558}
1559
1560template <typename Derived>
1561bool RecursiveASTVisitor<Derived>::TraverseTemplateInstantiations(
1562    VarTemplateDecl *D) {
1563  for (auto *SD : D->specializations()) {
1564    for (auto *RD : SD->redecls()) {
1565      switch (
1566          cast<VarTemplateSpecializationDecl>(RD)->getSpecializationKind()) {
1567      case TSK_Undeclared:
1568      case TSK_ImplicitInstantiation:
1569        TRY_TO(TraverseDecl(RD));
1570        break;
1571
1572      case TSK_ExplicitInstantiationDeclaration:
1573      case TSK_ExplicitInstantiationDefinition:
1574      case TSK_ExplicitSpecialization:
1575        break;
1576      }
1577    }
1578  }
1579
1580  return true;
1581}
1582
1583// A helper method for traversing the instantiations of a
1584// function while skipping its specializations.
1585template <typename Derived>
1586bool RecursiveASTVisitor<Derived>::TraverseTemplateInstantiations(
1587    FunctionTemplateDecl *D) {
1588  for (auto *FD : D->specializations()) {
1589    for (auto *RD : FD->redecls()) {
1590      switch (RD->getTemplateSpecializationKind()) {
1591      case TSK_Undeclared:
1592      case TSK_ImplicitInstantiation:
1593        // We don't know what kind of FunctionDecl this is.
1594        TRY_TO(TraverseDecl(RD));
1595        break;
1596
1597      // FIXME: For now traverse explicit instantiations here. Change that
1598      // once they are represented as dedicated nodes in the AST.
1599      case TSK_ExplicitInstantiationDeclaration:
1600      case TSK_ExplicitInstantiationDefinition:
1601        TRY_TO(TraverseDecl(RD));
1602        break;
1603
1604      case TSK_ExplicitSpecialization:
1605        break;
1606      }
1607    }
1608  }
1609
1610  return true;
1611}
1612
1613// This macro unifies the traversal of class, variable and function
1614// template declarations.
1615#define DEF_TRAVERSE_TMPL_DECL(TMPLDECLKIND)                                   \
1616  DEF_TRAVERSE_DECL(TMPLDECLKIND##TemplateDecl, {                              \
1617    TRY_TO(TraverseDecl(D->getTemplatedDecl()));                               \
1618    TRY_TO(TraverseTemplateParameterListHelper(D->getTemplateParameters()));   \
1619                                                                               \
1620    /* By default, we do not traverse the instantiations of                    \
1621       class templates since they do not appear in the user code. The          \
1622       following code optionally traverses them.                               \
1623                                                                               \
1624       We only traverse the class instantiations when we see the canonical     \
1625       declaration of the template, to ensure we only visit them once. */      \
1626    if (getDerived().shouldVisitTemplateInstantiations() &&                    \
1627        D == D->getCanonicalDecl())                                            \
1628      TRY_TO(TraverseTemplateInstantiations(D));                               \
1629                                                                               \
1630    /* Note that getInstantiatedFromMemberTemplate() is just a link            \
1631       from a template instantiation back to the template from which           \
1632       it was instantiated, and thus should not be traversed. */               \
1633  })
1634
1635DEF_TRAVERSE_TMPL_DECL(Class)
1636DEF_TRAVERSE_TMPL_DECL(Var)
1637DEF_TRAVERSE_TMPL_DECL(Function)
1638
1639DEF_TRAVERSE_DECL(TemplateTemplateParmDecl, {
1640  // D is the "T" in something like
1641  //   template <template <typename> class T> class container { };
1642  TRY_TO(TraverseDecl(D->getTemplatedDecl()));
1643  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
1644    TRY_TO(TraverseTemplateArgumentLoc(D->getDefaultArgument()));
1645  }
1646  TRY_TO(TraverseTemplateParameterListHelper(D->getTemplateParameters()));
1647})
1648
1649DEF_TRAVERSE_DECL(BuiltinTemplateDecl, {
1650  TRY_TO(TraverseTemplateParameterListHelper(D->getTemplateParameters()));
1651})
1652
1653DEF_TRAVERSE_DECL(TemplateTypeParmDecl, {
1654  // D is the "T" in something like "template<typename T> class vector;"
1655  if (D->getTypeForDecl())
1656    TRY_TO(TraverseType(QualType(D->getTypeForDecl(), 0)));
1657  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
1658    TRY_TO(TraverseTypeLoc(D->getDefaultArgumentInfo()->getTypeLoc()));
1659})
1660
1661DEF_TRAVERSE_DECL(TypedefDecl, {
1662  TRY_TO(TraverseTypeLoc(D->getTypeSourceInfo()->getTypeLoc()));
1663  // We shouldn't traverse D->getTypeForDecl(); it's a result of
1664  // declaring the typedef, not something that was written in the
1665  // source.
1666})
1667
1668DEF_TRAVERSE_DECL(TypeAliasDecl, {
1669  TRY_TO(TraverseTypeLoc(D->getTypeSourceInfo()->getTypeLoc()));
1670  // We shouldn't traverse D->getTypeForDecl(); it's a result of
1671  // declaring the type alias, not something that was written in the
1672  // source.
1673})
1674
1675DEF_TRAVERSE_DECL(TypeAliasTemplateDecl, {
1676  TRY_TO(TraverseDecl(D->getTemplatedDecl()));
1677  TRY_TO(TraverseTemplateParameterListHelper(D->getTemplateParameters()));
1678})
1679
1680DEF_TRAVERSE_DECL(UnresolvedUsingTypenameDecl, {
1681  // A dependent using declaration which was marked with 'typename'.
1682  //   template<class T> class A : public B<T> { using typename B<T>::foo; };
1683  TRY_TO(TraverseNestedNameSpecifierLoc(D->getQualifierLoc()));
1684  // We shouldn't traverse D->getTypeForDecl(); it's a result of
1685  // declaring the type, not something that was written in the
1686  // source.
1687})
1688
1689DEF_TRAVERSE_DECL(EnumDecl, {
1690  if (D->getTypeForDecl())
1691    TRY_TO(TraverseType(QualType(D->getTypeForDecl(), 0)));
1692
1693  TRY_TO(TraverseNestedNameSpecifierLoc(D->getQualifierLoc()));
1694  // The enumerators are already traversed by
1695  // decls_begin()/decls_end().
1696})
1697
1698// Helper methods for RecordDecl and its children.
1699template <typename Derived>
1700bool RecursiveASTVisitor<Derived>::TraverseRecordHelper(RecordDecl *D) {
1701  // We shouldn't traverse D->getTypeForDecl(); it's a result of
1702  // declaring the type, not something that was written in the source.
1703
1704  TRY_TO(TraverseNestedNameSpecifierLoc(D->getQualifierLoc()));
1705  return true;
1706}
1707
1708template <typename Derived>
1709bool RecursiveASTVisitor<Derived>::TraverseCXXRecordHelper(CXXRecordDecl *D) {
1710  if (!TraverseRecordHelper(D))
1711    return false;
1712  if (D->isCompleteDefinition()) {
1713    for (const auto &I : D->bases()) {
1714      TRY_TO(TraverseTypeLoc(I.getTypeSourceInfo()->getTypeLoc()));
1715    }
1716    // We don't traverse the friends or the conversions, as they are
1717    // already in decls_begin()/decls_end().
1718  }
1719  return true;
1720}
1721
1722DEF_TRAVERSE_DECL(RecordDecl, { TRY_TO(TraverseRecordHelper(D)); })
1723
1724DEF_TRAVERSE_DECL(CXXRecordDecl, { TRY_TO(TraverseCXXRecordHelper(D)); })
1725
1726#define DEF_TRAVERSE_TMPL_SPEC_DECL(TMPLDECLKIND)                              \
1727  DEF_TRAVERSE_DECL(TMPLDECLKIND##TemplateSpecializationDecl, {                \
1728    /* For implicit instantiations ("set<int> x;"), we don't want to           \
1729       recurse at all, since the instatiated template isn't written in         \
1730       the source code anywhere.  (Note the instatiated *type* --              \
1731       set<int> -- is written, and will still get a callback of                \
1732       TemplateSpecializationType).  For explicit instantiations               \
1733       ("template set<int>;"), we do need a callback, since this               \
1734       is the only callback that's made for this instantiation.                \
1735       We use getTypeAsWritten() to distinguish. */                            \
1736    if (TypeSourceInfo *TSI = D->getTypeAsWritten())                           \
1737      TRY_TO(TraverseTypeLoc(TSI->getTypeLoc()));                              \
1738                                                                               \
1739    if (!getDerived().shouldVisitTemplateInstantiations() &&                   \
1740        D->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)      \
1741      /* Returning from here skips traversing the                              \
1742         declaration context of the *TemplateSpecializationDecl                \
1743         (embedded in the DEF_TRAVERSE_DECL() macro)                           \
1744         which contains the instantiated members of the template. */           \
1745      return true;                                                             \
1746  })
1747
1748DEF_TRAVERSE_TMPL_SPEC_DECL(Class)
1749DEF_TRAVERSE_TMPL_SPEC_DECL(Var)
1750
1751template <typename Derived>
1752bool RecursiveASTVisitor<Derived>::TraverseTemplateArgumentLocsHelper(
1753    const TemplateArgumentLoc *TAL, unsigned Count) {
1754  for (unsigned I = 0; I < Count; ++I) {
1755    TRY_TO(TraverseTemplateArgumentLoc(TAL[I]));
1756  }
1757  return true;
1758}
1759
1760#define DEF_TRAVERSE_TMPL_PART_SPEC_DECL(TMPLDECLKIND, DECLKIND)               \
1761  DEF_TRAVERSE_DECL(TMPLDECLKIND##TemplatePartialSpecializationDecl, {         \
1762    /* The partial specialization. */                                          \
1763    if (TemplateParameterList *TPL = D->getTemplateParameters()) {             \
1764      for (TemplateParameterList::iterator I = TPL->begin(), E = TPL->end();   \
1765           I != E; ++I) {                                                      \
1766        TRY_TO(TraverseDecl(*I));                                              \
1767      }                                                                        \
1768    }                                                                          \
1769    /* The args that remains unspecialized. */                                 \
1770    TRY_TO(TraverseTemplateArgumentLocsHelper(                                 \
1771        D->getTemplateArgsAsWritten()->getTemplateArgs(),                      \
1772        D->getTemplateArgsAsWritten()->NumTemplateArgs));                      \
1773                                                                               \
1774    /* Don't need the *TemplatePartialSpecializationHelper, even               \
1775       though that's our parent class -- we already visit all the              \
1776       template args here. */                                                  \
1777    TRY_TO(Traverse##DECLKIND##Helper(D));                                     \
1778                                                                               \
1779    /* Instantiations will have been visited with the primary template. */     \
1780  })
1781
1782DEF_TRAVERSE_TMPL_PART_SPEC_DECL(Class, CXXRecord)
1783DEF_TRAVERSE_TMPL_PART_SPEC_DECL(Var, Var)
1784
1785DEF_TRAVERSE_DECL(EnumConstantDecl, { TRY_TO(TraverseStmt(D->getInitExpr())); })
1786
1787DEF_TRAVERSE_DECL(UnresolvedUsingValueDecl, {
1788  // Like UnresolvedUsingTypenameDecl, but without the 'typename':
1789  //    template <class T> Class A : public Base<T> { using Base<T>::foo; };
1790  TRY_TO(TraverseNestedNameSpecifierLoc(D->getQualifierLoc()));
1791  TRY_TO(TraverseDeclarationNameInfo(D->getNameInfo()));
1792})
1793
1794DEF_TRAVERSE_DECL(IndirectFieldDecl, {})
1795
1796template <typename Derived>
1797bool RecursiveASTVisitor<Derived>::TraverseDeclaratorHelper(DeclaratorDecl *D) {
1798  TRY_TO(TraverseNestedNameSpecifierLoc(D->getQualifierLoc()));
1799  if (D->getTypeSourceInfo())
1800    TRY_TO(TraverseTypeLoc(D->getTypeSourceInfo()->getTypeLoc()));
1801  else
1802    TRY_TO(TraverseType(D->getType()));
1803  return true;
1804}
1805
1806DEF_TRAVERSE_DECL(MSPropertyDecl, { TRY_TO(TraverseDeclaratorHelper(D)); })
1807
1808DEF_TRAVERSE_DECL(FieldDecl, {
1809  TRY_TO(TraverseDeclaratorHelper(D));
1810  if (D->isBitField())
1811    TRY_TO(TraverseStmt(D->getBitWidth()));
1812  else if (D->hasInClassInitializer())
1813    TRY_TO(TraverseStmt(D->getInClassInitializer()));
1814})
1815
1816DEF_TRAVERSE_DECL(ObjCAtDefsFieldDecl, {
1817  TRY_TO(TraverseDeclaratorHelper(D));
1818  if (D->isBitField())
1819    TRY_TO(TraverseStmt(D->getBitWidth()));
1820  // FIXME: implement the rest.
1821})
1822
1823DEF_TRAVERSE_DECL(ObjCIvarDecl, {
1824  TRY_TO(TraverseDeclaratorHelper(D));
1825  if (D->isBitField())
1826    TRY_TO(TraverseStmt(D->getBitWidth()));
1827  // FIXME: implement the rest.
1828})
1829
1830template <typename Derived>
1831bool RecursiveASTVisitor<Derived>::TraverseFunctionHelper(FunctionDecl *D) {
1832  TRY_TO(TraverseNestedNameSpecifierLoc(D->getQualifierLoc()));
1833  TRY_TO(TraverseDeclarationNameInfo(D->getNameInfo()));
1834
1835  // If we're an explicit template specialization, iterate over the
1836  // template args that were explicitly specified.  If we were doing
1837  // this in typing order, we'd do it between the return type and
1838  // the function args, but both are handled by the FunctionTypeLoc
1839  // above, so we have to choose one side.  I've decided to do before.
1840  if (const FunctionTemplateSpecializationInfo *FTSI =
1841          D->getTemplateSpecializationInfo()) {
1842    if (FTSI->getTemplateSpecializationKind() != TSK_Undeclared &&
1843        FTSI->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
1844      // A specialization might not have explicit template arguments if it has
1845      // a templated return type and concrete arguments.
1846      if (const ASTTemplateArgumentListInfo *TALI =
1847              FTSI->TemplateArgumentsAsWritten) {
1848        TRY_TO(TraverseTemplateArgumentLocsHelper(TALI->getTemplateArgs(),
1849                                                  TALI->NumTemplateArgs));
1850      }
1851    }
1852  }
1853
1854  // Visit the function type itself, which can be either
1855  // FunctionNoProtoType or FunctionProtoType, or a typedef.  This
1856  // also covers the return type and the function parameters,
1857  // including exception specifications.
1858  if (TypeSourceInfo *TSI = D->getTypeSourceInfo()) {
1859    TRY_TO(TraverseTypeLoc(TSI->getTypeLoc()));
1860  } else if (getDerived().shouldVisitImplicitCode()) {
1861    // Visit parameter variable declarations of the implicit function
1862    // if the traverser is visiting implicit code. Parameter variable
1863    // declarations do not have valid TypeSourceInfo, so to visit them
1864    // we need to traverse the declarations explicitly.
1865    for (ParmVarDecl *Parameter : D->parameters()) {
1866      TRY_TO(TraverseDecl(Parameter));
1867    }
1868  }
1869
1870  if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(D)) {
1871    // Constructor initializers.
1872    for (auto *I : Ctor->inits()) {
1873      TRY_TO(TraverseConstructorInitializer(I));
1874    }
1875  }
1876
1877  if (D->isThisDeclarationADefinition()) {
1878    TRY_TO(TraverseStmt(D->getBody())); // Function body.
1879  }
1880  return true;
1881}
1882
1883DEF_TRAVERSE_DECL(FunctionDecl, {
1884  // We skip decls_begin/decls_end, which are already covered by
1885  // TraverseFunctionHelper().
1886  ShouldVisitChildren = false;
1887  ReturnValue = TraverseFunctionHelper(D);
1888})
1889
1890DEF_TRAVERSE_DECL(CXXMethodDecl, {
1891  // We skip decls_begin/decls_end, which are already covered by
1892  // TraverseFunctionHelper().
1893  ShouldVisitChildren = false;
1894  ReturnValue = TraverseFunctionHelper(D);
1895})
1896
1897DEF_TRAVERSE_DECL(CXXConstructorDecl, {
1898  // We skip decls_begin/decls_end, which are already covered by
1899  // TraverseFunctionHelper().
1900  ShouldVisitChildren = false;
1901  ReturnValue = TraverseFunctionHelper(D);
1902})
1903
1904// CXXConversionDecl is the declaration of a type conversion operator.
1905// It's not a cast expression.
1906DEF_TRAVERSE_DECL(CXXConversionDecl, {
1907  // We skip decls_begin/decls_end, which are already covered by
1908  // TraverseFunctionHelper().
1909  ShouldVisitChildren = false;
1910  ReturnValue = TraverseFunctionHelper(D);
1911})
1912
1913DEF_TRAVERSE_DECL(CXXDestructorDecl, {
1914  // We skip decls_begin/decls_end, which are already covered by
1915  // TraverseFunctionHelper().
1916  ShouldVisitChildren = false;
1917  ReturnValue = TraverseFunctionHelper(D);
1918})
1919
1920template <typename Derived>
1921bool RecursiveASTVisitor<Derived>::TraverseVarHelper(VarDecl *D) {
1922  TRY_TO(TraverseDeclaratorHelper(D));
1923  // Default params are taken care of when we traverse the ParmVarDecl.
1924  if (!isa<ParmVarDecl>(D) &&
1925      (!D->isCXXForRangeDecl() || getDerived().shouldVisitImplicitCode()))
1926    TRY_TO(TraverseStmt(D->getInit()));
1927  return true;
1928}
1929
1930DEF_TRAVERSE_DECL(VarDecl, { TRY_TO(TraverseVarHelper(D)); })
1931
1932DEF_TRAVERSE_DECL(ImplicitParamDecl, { TRY_TO(TraverseVarHelper(D)); })
1933
1934DEF_TRAVERSE_DECL(NonTypeTemplateParmDecl, {
1935  // A non-type template parameter, e.g. "S" in template<int S> class Foo ...
1936  TRY_TO(TraverseDeclaratorHelper(D));
1937  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
1938    TRY_TO(TraverseStmt(D->getDefaultArgument()));
1939})
1940
1941DEF_TRAVERSE_DECL(ParmVarDecl, {
1942  TRY_TO(TraverseVarHelper(D));
1943
1944  if (D->hasDefaultArg() && D->hasUninstantiatedDefaultArg() &&
1945      !D->hasUnparsedDefaultArg())
1946    TRY_TO(TraverseStmt(D->getUninstantiatedDefaultArg()));
1947
1948  if (D->hasDefaultArg() && !D->hasUninstantiatedDefaultArg() &&
1949      !D->hasUnparsedDefaultArg())
1950    TRY_TO(TraverseStmt(D->getDefaultArg()));
1951})
1952
1953#undef DEF_TRAVERSE_DECL
1954
1955// ----------------- Stmt traversal -----------------
1956//
1957// For stmts, we automate (in the DEF_TRAVERSE_STMT macro) iterating
1958// over the children defined in children() (every stmt defines these,
1959// though sometimes the range is empty).  Each individual Traverse*
1960// method only needs to worry about children other than those.  To see
1961// what children() does for a given class, see, e.g.,
1962//   http://clang.llvm.org/doxygen/Stmt_8cpp_source.html
1963
1964// This macro makes available a variable S, the passed-in stmt.
1965#define DEF_TRAVERSE_STMT(STMT, CODE)                                          \
1966  template <typename Derived>                                                  \
1967  bool RecursiveASTVisitor<Derived>::Traverse##STMT(                           \
1968      STMT *S, DataRecursionQueue *Queue) {                                    \
1969    bool ShouldVisitChildren = true;                                           \
1970    bool ReturnValue = true;                                                   \
1971    if (!getDerived().shouldTraversePostOrder())                               \
1972      TRY_TO(WalkUpFrom##STMT(S));                                             \
1973    { CODE; }                                                                  \
1974    if (ShouldVisitChildren) {                                                 \
1975      for (Stmt *SubStmt : S->children()) {                                    \
1976        TRY_TO_TRAVERSE_OR_ENQUEUE_STMT(SubStmt);                              \
1977      }                                                                        \
1978    }                                                                          \
1979    if (!Queue && ReturnValue && getDerived().shouldTraversePostOrder())       \
1980      TRY_TO(WalkUpFrom##STMT(S));                                             \
1981    return ReturnValue;                                                        \
1982  }
1983
1984DEF_TRAVERSE_STMT(GCCAsmStmt, {
1985  TRY_TO_TRAVERSE_OR_ENQUEUE_STMT(S->getAsmString());
1986  for (unsigned I = 0, E = S->getNumInputs(); I < E; ++I) {
1987    TRY_TO_TRAVERSE_OR_ENQUEUE_STMT(S->getInputConstraintLiteral(I));
1988  }
1989  for (unsigned I = 0, E = S->getNumOutputs(); I < E; ++I) {
1990    TRY_TO_TRAVERSE_OR_ENQUEUE_STMT(S->getOutputConstraintLiteral(I));
1991  }
1992  for (unsigned I = 0, E = S->getNumClobbers(); I < E; ++I) {
1993    TRY_TO_TRAVERSE_OR_ENQUEUE_STMT(S->getClobberStringLiteral(I));
1994  }
1995  // children() iterates over inputExpr and outputExpr.
1996})
1997
1998DEF_TRAVERSE_STMT(
1999    MSAsmStmt,
2000    {// FIXME: MS Asm doesn't currently parse Constraints, Clobbers, etc.  Once
2001     // added this needs to be implemented.
2002    })
2003
2004DEF_TRAVERSE_STMT(CXXCatchStmt, {
2005  TRY_TO(TraverseDecl(S->getExceptionDecl()));
2006  // children() iterates over the handler block.
2007})
2008
2009DEF_TRAVERSE_STMT(DeclStmt, {
2010  for (auto *I : S->decls()) {
2011    TRY_TO(TraverseDecl(I));
2012  }
2013  // Suppress the default iteration over children() by
2014  // returning.  Here's why: A DeclStmt looks like 'type var [=
2015  // initializer]'.  The decls above already traverse over the
2016  // initializers, so we don't have to do it again (which
2017  // children() would do).
2018  ShouldVisitChildren = false;
2019})
2020
2021// These non-expr stmts (most of them), do not need any action except
2022// iterating over the children.
2023DEF_TRAVERSE_STMT(BreakStmt, {})
2024DEF_TRAVERSE_STMT(CXXTryStmt, {})
2025DEF_TRAVERSE_STMT(CaseStmt, {})
2026DEF_TRAVERSE_STMT(CompoundStmt, {})
2027DEF_TRAVERSE_STMT(ContinueStmt, {})
2028DEF_TRAVERSE_STMT(DefaultStmt, {})
2029DEF_TRAVERSE_STMT(DoStmt, {})
2030DEF_TRAVERSE_STMT(ForStmt, {})
2031DEF_TRAVERSE_STMT(GotoStmt, {})
2032DEF_TRAVERSE_STMT(IfStmt, {})
2033DEF_TRAVERSE_STMT(IndirectGotoStmt, {})
2034DEF_TRAVERSE_STMT(LabelStmt, {})
2035DEF_TRAVERSE_STMT(AttributedStmt, {})
2036DEF_TRAVERSE_STMT(NullStmt, {})
2037DEF_TRAVERSE_STMT(ObjCAtCatchStmt, {})
2038DEF_TRAVERSE_STMT(ObjCAtFinallyStmt, {})
2039DEF_TRAVERSE_STMT(ObjCAtSynchronizedStmt, {})
2040DEF_TRAVERSE_STMT(ObjCAtThrowStmt, {})
2041DEF_TRAVERSE_STMT(ObjCAtTryStmt, {})
2042DEF_TRAVERSE_STMT(ObjCForCollectionStmt, {})
2043DEF_TRAVERSE_STMT(ObjCAutoreleasePoolStmt, {})
2044DEF_TRAVERSE_STMT(CXXForRangeStmt, {
2045  if (!getDerived().shouldVisitImplicitCode()) {
2046    TRY_TO_TRAVERSE_OR_ENQUEUE_STMT(S->getLoopVarStmt());
2047    TRY_TO_TRAVERSE_OR_ENQUEUE_STMT(S->getRangeInit());
2048    TRY_TO_TRAVERSE_OR_ENQUEUE_STMT(S->getBody());
2049    // Visit everything else only if shouldVisitImplicitCode().
2050    ShouldVisitChildren = false;
2051  }
2052})
2053DEF_TRAVERSE_STMT(MSDependentExistsStmt, {
2054  TRY_TO(TraverseNestedNameSpecifierLoc(S->getQualifierLoc()));
2055  TRY_TO(TraverseDeclarationNameInfo(S->getNameInfo()));
2056})
2057DEF_TRAVERSE_STMT(ReturnStmt, {})
2058DEF_TRAVERSE_STMT(SwitchStmt, {})
2059DEF_TRAVERSE_STMT(WhileStmt, {})
2060
2061DEF_TRAVERSE_STMT(CXXDependentScopeMemberExpr, {
2062  TRY_TO(TraverseNestedNameSpecifierLoc(S->getQualifierLoc()));
2063  TRY_TO(TraverseDeclarationNameInfo(S->getMemberNameInfo()));
2064  if (S->hasExplicitTemplateArgs()) {
2065    TRY_TO(TraverseTemplateArgumentLocsHelper(S->getTemplateArgs(),
2066                                              S->getNumTemplateArgs()));
2067  }
2068})
2069
2070DEF_TRAVERSE_STMT(DeclRefExpr, {
2071  TRY_TO(TraverseNestedNameSpecifierLoc(S->getQualifierLoc()));
2072  TRY_TO(TraverseDeclarationNameInfo(S->getNameInfo()));
2073  TRY_TO(TraverseTemplateArgumentLocsHelper(S->getTemplateArgs(),
2074                                            S->getNumTemplateArgs()));
2075})
2076
2077DEF_TRAVERSE_STMT(DependentScopeDeclRefExpr, {
2078  TRY_TO(TraverseNestedNameSpecifierLoc(S->getQualifierLoc()));
2079  TRY_TO(TraverseDeclarationNameInfo(S->getNameInfo()));
2080  if (S->hasExplicitTemplateArgs()) {
2081    TRY_TO(TraverseTemplateArgumentLocsHelper(S->getTemplateArgs(),
2082                                              S->getNumTemplateArgs()));
2083  }
2084})
2085
2086DEF_TRAVERSE_STMT(MemberExpr, {
2087  TRY_TO(TraverseNestedNameSpecifierLoc(S->getQualifierLoc()));
2088  TRY_TO(TraverseDeclarationNameInfo(S->getMemberNameInfo()));
2089  TRY_TO(TraverseTemplateArgumentLocsHelper(S->getTemplateArgs(),
2090                                            S->getNumTemplateArgs()));
2091})
2092
2093DEF_TRAVERSE_STMT(
2094    ImplicitCastExpr,
2095    {// We don't traverse the cast type, as it's not written in the
2096     // source code.
2097    })
2098
2099DEF_TRAVERSE_STMT(CStyleCastExpr, {
2100  TRY_TO(TraverseTypeLoc(S->getTypeInfoAsWritten()->getTypeLoc()));
2101})
2102
2103DEF_TRAVERSE_STMT(CXXFunctionalCastExpr, {
2104  TRY_TO(TraverseTypeLoc(S->getTypeInfoAsWritten()->getTypeLoc()));
2105})
2106
2107DEF_TRAVERSE_STMT(CXXConstCastExpr, {
2108  TRY_TO(TraverseTypeLoc(S->getTypeInfoAsWritten()->getTypeLoc()));
2109})
2110
2111DEF_TRAVERSE_STMT(CXXDynamicCastExpr, {
2112  TRY_TO(TraverseTypeLoc(S->getTypeInfoAsWritten()->getTypeLoc()));
2113})
2114
2115DEF_TRAVERSE_STMT(CXXReinterpretCastExpr, {
2116  TRY_TO(TraverseTypeLoc(S->getTypeInfoAsWritten()->getTypeLoc()));
2117})
2118
2119DEF_TRAVERSE_STMT(CXXStaticCastExpr, {
2120  TRY_TO(TraverseTypeLoc(S->getTypeInfoAsWritten()->getTypeLoc()));
2121})
2122
2123template <typename Derived>
2124bool RecursiveASTVisitor<Derived>::TraverseSynOrSemInitListExpr(
2125    InitListExpr *S, DataRecursionQueue *Queue) {
2126  if (S) {
2127    // Skip this if we traverse postorder. We will visit it later
2128    // in PostVisitStmt.
2129    if (!getDerived().shouldTraversePostOrder())
2130      TRY_TO(WalkUpFromInitListExpr(S));
2131
2132    // All we need are the default actions.  FIXME: use a helper function.
2133    for (Stmt *SubStmt : S->children()) {
2134      TRY_TO_TRAVERSE_OR_ENQUEUE_STMT(SubStmt);
2135    }
2136  }
2137  return true;
2138}
2139
2140// This method is called once for each pair of syntactic and semantic
2141// InitListExpr, and it traverses the subtrees defined by the two forms. This
2142// may cause some of the children to be visited twice, if they appear both in
2143// the syntactic and the semantic form.
2144//
2145// There is no guarantee about which form \p S takes when this method is called.
2146DEF_TRAVERSE_STMT(InitListExpr, {
2147  TRY_TO(TraverseSynOrSemInitListExpr(
2148      S->isSemanticForm() ? S->getSyntacticForm() : S, Queue));
2149  TRY_TO(TraverseSynOrSemInitListExpr(
2150      S->isSemanticForm() ? S : S->getSemanticForm(), Queue));
2151  ShouldVisitChildren = false;
2152})
2153
2154// GenericSelectionExpr is a special case because the types and expressions
2155// are interleaved.  We also need to watch out for null types (default
2156// generic associations).
2157DEF_TRAVERSE_STMT(GenericSelectionExpr, {
2158  TRY_TO(TraverseStmt(S->getControllingExpr()));
2159  for (unsigned i = 0; i != S->getNumAssocs(); ++i) {
2160    if (TypeSourceInfo *TS = S->getAssocTypeSourceInfo(i))
2161      TRY_TO(TraverseTypeLoc(TS->getTypeLoc()));
2162    TRY_TO_TRAVERSE_OR_ENQUEUE_STMT(S->getAssocExpr(i));
2163  }
2164  ShouldVisitChildren = false;
2165})
2166
2167// PseudoObjectExpr is a special case because of the weirdness with
2168// syntactic expressions and opaque values.
2169DEF_TRAVERSE_STMT(PseudoObjectExpr, {
2170  TRY_TO_TRAVERSE_OR_ENQUEUE_STMT(S->getSyntacticForm());
2171  for (PseudoObjectExpr::semantics_iterator i = S->semantics_begin(),
2172                                            e = S->semantics_end();
2173       i != e; ++i) {
2174    Expr *sub = *i;
2175    if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(sub))
2176      sub = OVE->getSourceExpr();
2177    TRY_TO_TRAVERSE_OR_ENQUEUE_STMT(sub);
2178  }
2179  ShouldVisitChildren = false;
2180})
2181
2182DEF_TRAVERSE_STMT(CXXScalarValueInitExpr, {
2183  // This is called for code like 'return T()' where T is a built-in
2184  // (i.e. non-class) type.
2185  TRY_TO(TraverseTypeLoc(S->getTypeSourceInfo()->getTypeLoc()));
2186})
2187
2188DEF_TRAVERSE_STMT(CXXNewExpr, {
2189  // The child-iterator will pick up the other arguments.
2190  TRY_TO(TraverseTypeLoc(S->getAllocatedTypeSourceInfo()->getTypeLoc()));
2191})
2192
2193DEF_TRAVERSE_STMT(OffsetOfExpr, {
2194  // The child-iterator will pick up the expression representing
2195  // the field.
2196  // FIMXE: for code like offsetof(Foo, a.b.c), should we get
2197  // making a MemberExpr callbacks for Foo.a, Foo.a.b, and Foo.a.b.c?
2198  TRY_TO(TraverseTypeLoc(S->getTypeSourceInfo()->getTypeLoc()));
2199})
2200
2201DEF_TRAVERSE_STMT(UnaryExprOrTypeTraitExpr, {
2202  // The child-iterator will pick up the arg if it's an expression,
2203  // but not if it's a type.
2204  if (S->isArgumentType())
2205    TRY_TO(TraverseTypeLoc(S->getArgumentTypeInfo()->getTypeLoc()));
2206})
2207
2208DEF_TRAVERSE_STMT(CXXTypeidExpr, {
2209  // The child-iterator will pick up the arg if it's an expression,
2210  // but not if it's a type.
2211  if (S->isTypeOperand())
2212    TRY_TO(TraverseTypeLoc(S->getTypeOperandSourceInfo()->getTypeLoc()));
2213})
2214
2215DEF_TRAVERSE_STMT(MSPropertyRefExpr, {
2216  TRY_TO(TraverseNestedNameSpecifierLoc(S->getQualifierLoc()));
2217})
2218
2219DEF_TRAVERSE_STMT(MSPropertySubscriptExpr, {})
2220
2221DEF_TRAVERSE_STMT(CXXUuidofExpr, {
2222  // The child-iterator will pick up the arg if it's an expression,
2223  // but not if it's a type.
2224  if (S->isTypeOperand())
2225    TRY_TO(TraverseTypeLoc(S->getTypeOperandSourceInfo()->getTypeLoc()));
2226})
2227
2228DEF_TRAVERSE_STMT(TypeTraitExpr, {
2229  for (unsigned I = 0, N = S->getNumArgs(); I != N; ++I)
2230    TRY_TO(TraverseTypeLoc(S->getArg(I)->getTypeLoc()));
2231})
2232
2233DEF_TRAVERSE_STMT(ArrayTypeTraitExpr, {
2234  TRY_TO(TraverseTypeLoc(S->getQueriedTypeSourceInfo()->getTypeLoc()));
2235})
2236
2237DEF_TRAVERSE_STMT(ExpressionTraitExpr,
2238                  { TRY_TO_TRAVERSE_OR_ENQUEUE_STMT(S->getQueriedExpression()); })
2239
2240DEF_TRAVERSE_STMT(VAArgExpr, {
2241  // The child-iterator will pick up the expression argument.
2242  TRY_TO(TraverseTypeLoc(S->getWrittenTypeInfo()->getTypeLoc()));
2243})
2244
2245DEF_TRAVERSE_STMT(CXXTemporaryObjectExpr, {
2246  // This is called for code like 'return T()' where T is a class type.
2247  TRY_TO(TraverseTypeLoc(S->getTypeSourceInfo()->getTypeLoc()));
2248})
2249
2250// Walk only the visible parts of lambda expressions.
2251DEF_TRAVERSE_STMT(LambdaExpr, {
2252  for (LambdaExpr::capture_iterator C = S->explicit_capture_begin(),
2253                                    CEnd = S->explicit_capture_end();
2254       C != CEnd; ++C) {
2255    TRY_TO(TraverseLambdaCapture(S, C));
2256  }
2257
2258  TypeLoc TL = S->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
2259  FunctionProtoTypeLoc Proto = TL.castAs<FunctionProtoTypeLoc>();
2260
2261  if (S->hasExplicitParameters() && S->hasExplicitResultType()) {
2262    // Visit the whole type.
2263    TRY_TO(TraverseTypeLoc(TL));
2264  } else {
2265    if (S->hasExplicitParameters()) {
2266      // Visit parameters.
2267      for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I) {
2268        TRY_TO(TraverseDecl(Proto.getParam(I)));
2269      }
2270    } else if (S->hasExplicitResultType()) {
2271      TRY_TO(TraverseTypeLoc(Proto.getReturnLoc()));
2272    }
2273
2274    auto *T = Proto.getTypePtr();
2275    for (const auto &E : T->exceptions()) {
2276      TRY_TO(TraverseType(E));
2277    }
2278
2279    if (Expr *NE = T->getNoexceptExpr())
2280      TRY_TO_TRAVERSE_OR_ENQUEUE_STMT(NE);
2281  }
2282
2283  ReturnValue = TRAVERSE_STMT_BASE(LambdaBody, LambdaExpr, S, Queue);
2284  ShouldVisitChildren = false;
2285})
2286
2287DEF_TRAVERSE_STMT(CXXUnresolvedConstructExpr, {
2288  // This is called for code like 'T()', where T is a template argument.
2289  TRY_TO(TraverseTypeLoc(S->getTypeSourceInfo()->getTypeLoc()));
2290})
2291
2292// These expressions all might take explicit template arguments.
2293// We traverse those if so.  FIXME: implement these.
2294DEF_TRAVERSE_STMT(CXXConstructExpr, {})
2295DEF_TRAVERSE_STMT(CallExpr, {})
2296DEF_TRAVERSE_STMT(CXXMemberCallExpr, {})
2297
2298// These exprs (most of them), do not need any action except iterating
2299// over the children.
2300DEF_TRAVERSE_STMT(AddrLabelExpr, {})
2301DEF_TRAVERSE_STMT(ArraySubscriptExpr, {})
2302DEF_TRAVERSE_STMT(OMPArraySectionExpr, {})
2303DEF_TRAVERSE_STMT(BlockExpr, {
2304  TRY_TO(TraverseDecl(S->getBlockDecl()));
2305  return true; // no child statements to loop through.
2306})
2307DEF_TRAVERSE_STMT(ChooseExpr, {})
2308DEF_TRAVERSE_STMT(CompoundLiteralExpr, {
2309  TRY_TO(TraverseTypeLoc(S->getTypeSourceInfo()->getTypeLoc()));
2310})
2311DEF_TRAVERSE_STMT(CXXBindTemporaryExpr, {})
2312DEF_TRAVERSE_STMT(CXXBoolLiteralExpr, {})
2313DEF_TRAVERSE_STMT(CXXDefaultArgExpr, {})
2314DEF_TRAVERSE_STMT(CXXDefaultInitExpr, {})
2315DEF_TRAVERSE_STMT(CXXDeleteExpr, {})
2316DEF_TRAVERSE_STMT(ExprWithCleanups, {})
2317DEF_TRAVERSE_STMT(CXXInheritedCtorInitExpr, {})
2318DEF_TRAVERSE_STMT(CXXNullPtrLiteralExpr, {})
2319DEF_TRAVERSE_STMT(CXXStdInitializerListExpr, {})
2320DEF_TRAVERSE_STMT(CXXPseudoDestructorExpr, {
2321  TRY_TO(TraverseNestedNameSpecifierLoc(S->getQualifierLoc()));
2322  if (TypeSourceInfo *ScopeInfo = S->getScopeTypeInfo())
2323    TRY_TO(TraverseTypeLoc(ScopeInfo->getTypeLoc()));
2324  if (TypeSourceInfo *DestroyedTypeInfo = S->getDestroyedTypeInfo())
2325    TRY_TO(TraverseTypeLoc(DestroyedTypeInfo->getTypeLoc()));
2326})
2327DEF_TRAVERSE_STMT(CXXThisExpr, {})
2328DEF_TRAVERSE_STMT(CXXThrowExpr, {})
2329DEF_TRAVERSE_STMT(UserDefinedLiteral, {})
2330DEF_TRAVERSE_STMT(DesignatedInitExpr, {})
2331DEF_TRAVERSE_STMT(DesignatedInitUpdateExpr, {})
2332DEF_TRAVERSE_STMT(ExtVectorElementExpr, {})
2333DEF_TRAVERSE_STMT(GNUNullExpr, {})
2334DEF_TRAVERSE_STMT(ImplicitValueInitExpr, {})
2335DEF_TRAVERSE_STMT(NoInitExpr, {})
2336DEF_TRAVERSE_STMT(ObjCBoolLiteralExpr, {})
2337DEF_TRAVERSE_STMT(ObjCEncodeExpr, {
2338  if (TypeSourceInfo *TInfo = S->getEncodedTypeSourceInfo())
2339    TRY_TO(TraverseTypeLoc(TInfo->getTypeLoc()));
2340})
2341DEF_TRAVERSE_STMT(ObjCIsaExpr, {})
2342DEF_TRAVERSE_STMT(ObjCIvarRefExpr, {})
2343DEF_TRAVERSE_STMT(ObjCMessageExpr, {
2344  if (TypeSourceInfo *TInfo = S->getClassReceiverTypeInfo())
2345    TRY_TO(TraverseTypeLoc(TInfo->getTypeLoc()));
2346})
2347DEF_TRAVERSE_STMT(ObjCPropertyRefExpr, {})
2348DEF_TRAVERSE_STMT(ObjCSubscriptRefExpr, {})
2349DEF_TRAVERSE_STMT(ObjCProtocolExpr, {})
2350DEF_TRAVERSE_STMT(ObjCSelectorExpr, {})
2351DEF_TRAVERSE_STMT(ObjCIndirectCopyRestoreExpr, {})
2352DEF_TRAVERSE_STMT(ObjCBridgedCastExpr, {
2353  TRY_TO(TraverseTypeLoc(S->getTypeInfoAsWritten()->getTypeLoc()));
2354})
2355DEF_TRAVERSE_STMT(ObjCAvailabilityCheckExpr, {})
2356DEF_TRAVERSE_STMT(ParenExpr, {})
2357DEF_TRAVERSE_STMT(ParenListExpr, {})
2358DEF_TRAVERSE_STMT(PredefinedExpr, {})
2359DEF_TRAVERSE_STMT(ShuffleVectorExpr, {})
2360DEF_TRAVERSE_STMT(ConvertVectorExpr, {})
2361DEF_TRAVERSE_STMT(StmtExpr, {})
2362DEF_TRAVERSE_STMT(UnresolvedLookupExpr, {
2363  TRY_TO(TraverseNestedNameSpecifierLoc(S->getQualifierLoc()));
2364  if (S->hasExplicitTemplateArgs()) {
2365    TRY_TO(TraverseTemplateArgumentLocsHelper(S->getTemplateArgs(),
2366                                              S->getNumTemplateArgs()));
2367  }
2368})
2369
2370DEF_TRAVERSE_STMT(UnresolvedMemberExpr, {
2371  TRY_TO(TraverseNestedNameSpecifierLoc(S->getQualifierLoc()));
2372  if (S->hasExplicitTemplateArgs()) {
2373    TRY_TO(TraverseTemplateArgumentLocsHelper(S->getTemplateArgs(),
2374                                              S->getNumTemplateArgs()));
2375  }
2376})
2377
2378DEF_TRAVERSE_STMT(SEHTryStmt, {})
2379DEF_TRAVERSE_STMT(SEHExceptStmt, {})
2380DEF_TRAVERSE_STMT(SEHFinallyStmt, {})
2381DEF_TRAVERSE_STMT(SEHLeaveStmt, {})
2382DEF_TRAVERSE_STMT(CapturedStmt, { TRY_TO(TraverseDecl(S->getCapturedDecl())); })
2383
2384DEF_TRAVERSE_STMT(CXXOperatorCallExpr, {})
2385DEF_TRAVERSE_STMT(OpaqueValueExpr, {})
2386DEF_TRAVERSE_STMT(TypoExpr, {})
2387DEF_TRAVERSE_STMT(CUDAKernelCallExpr, {})
2388
2389// These operators (all of them) do not need any action except
2390// iterating over the children.
2391DEF_TRAVERSE_STMT(BinaryConditionalOperator, {})
2392DEF_TRAVERSE_STMT(ConditionalOperator, {})
2393DEF_TRAVERSE_STMT(UnaryOperator, {})
2394DEF_TRAVERSE_STMT(BinaryOperator, {})
2395DEF_TRAVERSE_STMT(CompoundAssignOperator, {})
2396DEF_TRAVERSE_STMT(CXXNoexceptExpr, {})
2397DEF_TRAVERSE_STMT(PackExpansionExpr, {})
2398DEF_TRAVERSE_STMT(SizeOfPackExpr, {})
2399DEF_TRAVERSE_STMT(SubstNonTypeTemplateParmPackExpr, {})
2400DEF_TRAVERSE_STMT(SubstNonTypeTemplateParmExpr, {})
2401DEF_TRAVERSE_STMT(FunctionParmPackExpr, {})
2402DEF_TRAVERSE_STMT(MaterializeTemporaryExpr, {})
2403DEF_TRAVERSE_STMT(CXXFoldExpr, {})
2404DEF_TRAVERSE_STMT(AtomicExpr, {})
2405
2406// For coroutines expressions, traverse either the operand
2407// as written or the implied calls, depending on what the
2408// derived class requests.
2409DEF_TRAVERSE_STMT(CoroutineBodyStmt, {
2410  if (!getDerived().shouldVisitImplicitCode()) {
2411    TRY_TO_TRAVERSE_OR_ENQUEUE_STMT(S->getBody());
2412    ShouldVisitChildren = false;
2413  }
2414})
2415DEF_TRAVERSE_STMT(CoreturnStmt, {
2416  if (!getDerived().shouldVisitImplicitCode()) {
2417    TRY_TO_TRAVERSE_OR_ENQUEUE_STMT(S->getOperand());
2418    ShouldVisitChildren = false;
2419  }
2420})
2421DEF_TRAVERSE_STMT(CoawaitExpr, {
2422  if (!getDerived().shouldVisitImplicitCode()) {
2423    TRY_TO_TRAVERSE_OR_ENQUEUE_STMT(S->getOperand());
2424    ShouldVisitChildren = false;
2425  }
2426})
2427DEF_TRAVERSE_STMT(CoyieldExpr, {
2428  if (!getDerived().shouldVisitImplicitCode()) {
2429    TRY_TO_TRAVERSE_OR_ENQUEUE_STMT(S->getOperand());
2430    ShouldVisitChildren = false;
2431  }
2432})
2433
2434// These literals (all of them) do not need any action.
2435DEF_TRAVERSE_STMT(IntegerLiteral, {})
2436DEF_TRAVERSE_STMT(CharacterLiteral, {})
2437DEF_TRAVERSE_STMT(FloatingLiteral, {})
2438DEF_TRAVERSE_STMT(ImaginaryLiteral, {})
2439DEF_TRAVERSE_STMT(StringLiteral, {})
2440DEF_TRAVERSE_STMT(ObjCStringLiteral, {})
2441DEF_TRAVERSE_STMT(ObjCBoxedExpr, {})
2442DEF_TRAVERSE_STMT(ObjCArrayLiteral, {})
2443DEF_TRAVERSE_STMT(ObjCDictionaryLiteral, {})
2444
2445// Traverse OpenCL: AsType, Convert.
2446DEF_TRAVERSE_STMT(AsTypeExpr, {})
2447
2448// OpenMP directives.
2449template <typename Derived>
2450bool RecursiveASTVisitor<Derived>::TraverseOMPExecutableDirective(
2451    OMPExecutableDirective *S) {
2452  for (auto *C : S->clauses()) {
2453    TRY_TO(TraverseOMPClause(C));
2454  }
2455  return true;
2456}
2457
2458template <typename Derived>
2459bool
2460RecursiveASTVisitor<Derived>::TraverseOMPLoopDirective(OMPLoopDirective *S) {
2461  return TraverseOMPExecutableDirective(S);
2462}
2463
2464DEF_TRAVERSE_STMT(OMPParallelDirective,
2465                  { TRY_TO(TraverseOMPExecutableDirective(S)); })
2466
2467DEF_TRAVERSE_STMT(OMPSimdDirective,
2468                  { TRY_TO(TraverseOMPExecutableDirective(S)); })
2469
2470DEF_TRAVERSE_STMT(OMPForDirective,
2471                  { TRY_TO(TraverseOMPExecutableDirective(S)); })
2472
2473DEF_TRAVERSE_STMT(OMPForSimdDirective,
2474                  { TRY_TO(TraverseOMPExecutableDirective(S)); })
2475
2476DEF_TRAVERSE_STMT(OMPSectionsDirective,
2477                  { TRY_TO(TraverseOMPExecutableDirective(S)); })
2478
2479DEF_TRAVERSE_STMT(OMPSectionDirective,
2480                  { TRY_TO(TraverseOMPExecutableDirective(S)); })
2481
2482DEF_TRAVERSE_STMT(OMPSingleDirective,
2483                  { TRY_TO(TraverseOMPExecutableDirective(S)); })
2484
2485DEF_TRAVERSE_STMT(OMPMasterDirective,
2486                  { TRY_TO(TraverseOMPExecutableDirective(S)); })
2487
2488DEF_TRAVERSE_STMT(OMPCriticalDirective, {
2489  TRY_TO(TraverseDeclarationNameInfo(S->getDirectiveName()));
2490  TRY_TO(TraverseOMPExecutableDirective(S));
2491})
2492
2493DEF_TRAVERSE_STMT(OMPParallelForDirective,
2494                  { TRY_TO(TraverseOMPExecutableDirective(S)); })
2495
2496DEF_TRAVERSE_STMT(OMPParallelForSimdDirective,
2497                  { TRY_TO(TraverseOMPExecutableDirective(S)); })
2498
2499DEF_TRAVERSE_STMT(OMPParallelSectionsDirective,
2500                  { TRY_TO(TraverseOMPExecutableDirective(S)); })
2501
2502DEF_TRAVERSE_STMT(OMPTaskDirective,
2503                  { TRY_TO(TraverseOMPExecutableDirective(S)); })
2504
2505DEF_TRAVERSE_STMT(OMPTaskyieldDirective,
2506                  { TRY_TO(TraverseOMPExecutableDirective(S)); })
2507
2508DEF_TRAVERSE_STMT(OMPBarrierDirective,
2509                  { TRY_TO(TraverseOMPExecutableDirective(S)); })
2510
2511DEF_TRAVERSE_STMT(OMPTaskwaitDirective,
2512                  { TRY_TO(TraverseOMPExecutableDirective(S)); })
2513
2514DEF_TRAVERSE_STMT(OMPTaskgroupDirective,
2515                  { TRY_TO(TraverseOMPExecutableDirective(S)); })
2516
2517DEF_TRAVERSE_STMT(OMPCancellationPointDirective,
2518                  { TRY_TO(TraverseOMPExecutableDirective(S)); })
2519
2520DEF_TRAVERSE_STMT(OMPCancelDirective,
2521                  { TRY_TO(TraverseOMPExecutableDirective(S)); })
2522
2523DEF_TRAVERSE_STMT(OMPFlushDirective,
2524                  { TRY_TO(TraverseOMPExecutableDirective(S)); })
2525
2526DEF_TRAVERSE_STMT(OMPOrderedDirective,
2527                  { TRY_TO(TraverseOMPExecutableDirective(S)); })
2528
2529DEF_TRAVERSE_STMT(OMPAtomicDirective,
2530                  { TRY_TO(TraverseOMPExecutableDirective(S)); })
2531
2532DEF_TRAVERSE_STMT(OMPTargetDirective,
2533                  { TRY_TO(TraverseOMPExecutableDirective(S)); })
2534
2535DEF_TRAVERSE_STMT(OMPTargetDataDirective,
2536                  { TRY_TO(TraverseOMPExecutableDirective(S)); })
2537
2538DEF_TRAVERSE_STMT(OMPTargetEnterDataDirective,
2539                  { TRY_TO(TraverseOMPExecutableDirective(S)); })
2540
2541DEF_TRAVERSE_STMT(OMPTargetExitDataDirective,
2542                  { TRY_TO(TraverseOMPExecutableDirective(S)); })
2543
2544DEF_TRAVERSE_STMT(OMPTargetParallelDirective,
2545                  { TRY_TO(TraverseOMPExecutableDirective(S)); })
2546
2547DEF_TRAVERSE_STMT(OMPTargetParallelForDirective,
2548                  { TRY_TO(TraverseOMPExecutableDirective(S)); })
2549
2550DEF_TRAVERSE_STMT(OMPTeamsDirective,
2551                  { TRY_TO(TraverseOMPExecutableDirective(S)); })
2552
2553DEF_TRAVERSE_STMT(OMPTargetUpdateDirective,
2554                  { TRY_TO(TraverseOMPExecutableDirective(S)); })
2555
2556DEF_TRAVERSE_STMT(OMPTaskLoopDirective,
2557                  { TRY_TO(TraverseOMPExecutableDirective(S)); })
2558
2559DEF_TRAVERSE_STMT(OMPTaskLoopSimdDirective,
2560                  { TRY_TO(TraverseOMPExecutableDirective(S)); })
2561
2562DEF_TRAVERSE_STMT(OMPDistributeDirective,
2563                  { TRY_TO(TraverseOMPExecutableDirective(S)); })
2564
2565DEF_TRAVERSE_STMT(OMPDistributeParallelForDirective,
2566                  { TRY_TO(TraverseOMPExecutableDirective(S)); })
2567
2568DEF_TRAVERSE_STMT(OMPDistributeParallelForSimdDirective,
2569                  { TRY_TO(TraverseOMPExecutableDirective(S)); })
2570
2571DEF_TRAVERSE_STMT(OMPDistributeSimdDirective,
2572                  { TRY_TO(TraverseOMPExecutableDirective(S)); })
2573
2574DEF_TRAVERSE_STMT(OMPTargetParallelForSimdDirective,
2575                  { TRY_TO(TraverseOMPExecutableDirective(S)); })
2576
2577// OpenMP clauses.
2578template <typename Derived>
2579bool RecursiveASTVisitor<Derived>::TraverseOMPClause(OMPClause *C) {
2580  if (!C)
2581    return true;
2582  switch (C->getClauseKind()) {
2583#define OPENMP_CLAUSE(Name, Class)                                             \
2584  case OMPC_##Name:                                                            \
2585    TRY_TO(Visit##Class(static_cast<Class *>(C)));                             \
2586    break;
2587#include "clang/Basic/OpenMPKinds.def"
2588  case OMPC_threadprivate:
2589  case OMPC_uniform:
2590  case OMPC_unknown:
2591    break;
2592  }
2593  return true;
2594}
2595
2596template <typename Derived>
2597bool RecursiveASTVisitor<Derived>::VisitOMPClauseWithPreInit(
2598    OMPClauseWithPreInit *Node) {
2599  TRY_TO(TraverseStmt(Node->getPreInitStmt()));
2600  return true;
2601}
2602
2603template <typename Derived>
2604bool RecursiveASTVisitor<Derived>::VisitOMPClauseWithPostUpdate(
2605    OMPClauseWithPostUpdate *Node) {
2606  TRY_TO(VisitOMPClauseWithPreInit(Node));
2607  TRY_TO(TraverseStmt(Node->getPostUpdateExpr()));
2608  return true;
2609}
2610
2611template <typename Derived>
2612bool RecursiveASTVisitor<Derived>::VisitOMPIfClause(OMPIfClause *C) {
2613  TRY_TO(TraverseStmt(C->getCondition()));
2614  return true;
2615}
2616
2617template <typename Derived>
2618bool RecursiveASTVisitor<Derived>::VisitOMPFinalClause(OMPFinalClause *C) {
2619  TRY_TO(TraverseStmt(C->getCondition()));
2620  return true;
2621}
2622
2623template <typename Derived>
2624bool
2625RecursiveASTVisitor<Derived>::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
2626  TRY_TO(TraverseStmt(C->getNumThreads()));
2627  return true;
2628}
2629
2630template <typename Derived>
2631bool RecursiveASTVisitor<Derived>::VisitOMPSafelenClause(OMPSafelenClause *C) {
2632  TRY_TO(TraverseStmt(C->getSafelen()));
2633  return true;
2634}
2635
2636template <typename Derived>
2637bool RecursiveASTVisitor<Derived>::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
2638  TRY_TO(TraverseStmt(C->getSimdlen()));
2639  return true;
2640}
2641
2642template <typename Derived>
2643bool
2644RecursiveASTVisitor<Derived>::VisitOMPCollapseClause(OMPCollapseClause *C) {
2645  TRY_TO(TraverseStmt(C->getNumForLoops()));
2646  return true;
2647}
2648
2649template <typename Derived>
2650bool RecursiveASTVisitor<Derived>::VisitOMPDefaultClause(OMPDefaultClause *) {
2651  return true;
2652}
2653
2654template <typename Derived>
2655bool RecursiveASTVisitor<Derived>::VisitOMPProcBindClause(OMPProcBindClause *) {
2656  return true;
2657}
2658
2659template <typename Derived>
2660bool
2661RecursiveASTVisitor<Derived>::VisitOMPScheduleClause(OMPScheduleClause *C) {
2662  TRY_TO(VisitOMPClauseWithPreInit(C));
2663  TRY_TO(TraverseStmt(C->getChunkSize()));
2664  return true;
2665}
2666
2667template <typename Derived>
2668bool RecursiveASTVisitor<Derived>::VisitOMPOrderedClause(OMPOrderedClause *C) {
2669  TRY_TO(TraverseStmt(C->getNumForLoops()));
2670  return true;
2671}
2672
2673template <typename Derived>
2674bool RecursiveASTVisitor<Derived>::VisitOMPNowaitClause(OMPNowaitClause *) {
2675  return true;
2676}
2677
2678template <typename Derived>
2679bool RecursiveASTVisitor<Derived>::VisitOMPUntiedClause(OMPUntiedClause *) {
2680  return true;
2681}
2682
2683template <typename Derived>
2684bool
2685RecursiveASTVisitor<Derived>::VisitOMPMergeableClause(OMPMergeableClause *) {
2686  return true;
2687}
2688
2689template <typename Derived>
2690bool RecursiveASTVisitor<Derived>::VisitOMPReadClause(OMPReadClause *) {
2691  return true;
2692}
2693
2694template <typename Derived>
2695bool RecursiveASTVisitor<Derived>::VisitOMPWriteClause(OMPWriteClause *) {
2696  return true;
2697}
2698
2699template <typename Derived>
2700bool RecursiveASTVisitor<Derived>::VisitOMPUpdateClause(OMPUpdateClause *) {
2701  return true;
2702}
2703
2704template <typename Derived>
2705bool RecursiveASTVisitor<Derived>::VisitOMPCaptureClause(OMPCaptureClause *) {
2706  return true;
2707}
2708
2709template <typename Derived>
2710bool RecursiveASTVisitor<Derived>::VisitOMPSeqCstClause(OMPSeqCstClause *) {
2711  return true;
2712}
2713
2714template <typename Derived>
2715bool RecursiveASTVisitor<Derived>::VisitOMPThreadsClause(OMPThreadsClause *) {
2716  return true;
2717}
2718
2719template <typename Derived>
2720bool RecursiveASTVisitor<Derived>::VisitOMPSIMDClause(OMPSIMDClause *) {
2721  return true;
2722}
2723
2724template <typename Derived>
2725bool RecursiveASTVisitor<Derived>::VisitOMPNogroupClause(OMPNogroupClause *) {
2726  return true;
2727}
2728
2729template <typename Derived>
2730template <typename T>
2731bool RecursiveASTVisitor<Derived>::VisitOMPClauseList(T *Node) {
2732  for (auto *E : Node->varlists()) {
2733    TRY_TO(TraverseStmt(E));
2734  }
2735  return true;
2736}
2737
2738template <typename Derived>
2739bool RecursiveASTVisitor<Derived>::VisitOMPPrivateClause(OMPPrivateClause *C) {
2740  TRY_TO(VisitOMPClauseList(C));
2741  for (auto *E : C->private_copies()) {
2742    TRY_TO(TraverseStmt(E));
2743  }
2744  return true;
2745}
2746
2747template <typename Derived>
2748bool RecursiveASTVisitor<Derived>::VisitOMPFirstprivateClause(
2749    OMPFirstprivateClause *C) {
2750  TRY_TO(VisitOMPClauseList(C));
2751  TRY_TO(VisitOMPClauseWithPreInit(C));
2752  for (auto *E : C->private_copies()) {
2753    TRY_TO(TraverseStmt(E));
2754  }
2755  for (auto *E : C->inits()) {
2756    TRY_TO(TraverseStmt(E));
2757  }
2758  return true;
2759}
2760
2761template <typename Derived>
2762bool RecursiveASTVisitor<Derived>::VisitOMPLastprivateClause(
2763    OMPLastprivateClause *C) {
2764  TRY_TO(VisitOMPClauseList(C));
2765  TRY_TO(VisitOMPClauseWithPostUpdate(C));
2766  for (auto *E : C->private_copies()) {
2767    TRY_TO(TraverseStmt(E));
2768  }
2769  for (auto *E : C->source_exprs()) {
2770    TRY_TO(TraverseStmt(E));
2771  }
2772  for (auto *E : C->destination_exprs()) {
2773    TRY_TO(TraverseStmt(E));
2774  }
2775  for (auto *E : C->assignment_ops()) {
2776    TRY_TO(TraverseStmt(E));
2777  }
2778  return true;
2779}
2780
2781template <typename Derived>
2782bool RecursiveASTVisitor<Derived>::VisitOMPSharedClause(OMPSharedClause *C) {
2783  TRY_TO(VisitOMPClauseList(C));
2784  return true;
2785}
2786
2787template <typename Derived>
2788bool RecursiveASTVisitor<Derived>::VisitOMPLinearClause(OMPLinearClause *C) {
2789  TRY_TO(TraverseStmt(C->getStep()));
2790  TRY_TO(TraverseStmt(C->getCalcStep()));
2791  TRY_TO(VisitOMPClauseList(C));
2792  TRY_TO(VisitOMPClauseWithPostUpdate(C));
2793  for (auto *E : C->privates()) {
2794    TRY_TO(TraverseStmt(E));
2795  }
2796  for (auto *E : C->inits()) {
2797    TRY_TO(TraverseStmt(E));
2798  }
2799  for (auto *E : C->updates()) {
2800    TRY_TO(TraverseStmt(E));
2801  }
2802  for (auto *E : C->finals()) {
2803    TRY_TO(TraverseStmt(E));
2804  }
2805  return true;
2806}
2807
2808template <typename Derived>
2809bool RecursiveASTVisitor<Derived>::VisitOMPAlignedClause(OMPAlignedClause *C) {
2810  TRY_TO(TraverseStmt(C->getAlignment()));
2811  TRY_TO(VisitOMPClauseList(C));
2812  return true;
2813}
2814
2815template <typename Derived>
2816bool RecursiveASTVisitor<Derived>::VisitOMPCopyinClause(OMPCopyinClause *C) {
2817  TRY_TO(VisitOMPClauseList(C));
2818  for (auto *E : C->source_exprs()) {
2819    TRY_TO(TraverseStmt(E));
2820  }
2821  for (auto *E : C->destination_exprs()) {
2822    TRY_TO(TraverseStmt(E));
2823  }
2824  for (auto *E : C->assignment_ops()) {
2825    TRY_TO(TraverseStmt(E));
2826  }
2827  return true;
2828}
2829
2830template <typename Derived>
2831bool RecursiveASTVisitor<Derived>::VisitOMPCopyprivateClause(
2832    OMPCopyprivateClause *C) {
2833  TRY_TO(VisitOMPClauseList(C));
2834  for (auto *E : C->source_exprs()) {
2835    TRY_TO(TraverseStmt(E));
2836  }
2837  for (auto *E : C->destination_exprs()) {
2838    TRY_TO(TraverseStmt(E));
2839  }
2840  for (auto *E : C->assignment_ops()) {
2841    TRY_TO(TraverseStmt(E));
2842  }
2843  return true;
2844}
2845
2846template <typename Derived>
2847bool
2848RecursiveASTVisitor<Derived>::VisitOMPReductionClause(OMPReductionClause *C) {
2849  TRY_TO(TraverseNestedNameSpecifierLoc(C->getQualifierLoc()));
2850  TRY_TO(TraverseDeclarationNameInfo(C->getNameInfo()));
2851  TRY_TO(VisitOMPClauseList(C));
2852  TRY_TO(VisitOMPClauseWithPostUpdate(C));
2853  for (auto *E : C->privates()) {
2854    TRY_TO(TraverseStmt(E));
2855  }
2856  for (auto *E : C->lhs_exprs()) {
2857    TRY_TO(TraverseStmt(E));
2858  }
2859  for (auto *E : C->rhs_exprs()) {
2860    TRY_TO(TraverseStmt(E));
2861  }
2862  for (auto *E : C->reduction_ops()) {
2863    TRY_TO(TraverseStmt(E));
2864  }
2865  return true;
2866}
2867
2868template <typename Derived>
2869bool RecursiveASTVisitor<Derived>::VisitOMPFlushClause(OMPFlushClause *C) {
2870  TRY_TO(VisitOMPClauseList(C));
2871  return true;
2872}
2873
2874template <typename Derived>
2875bool RecursiveASTVisitor<Derived>::VisitOMPDependClause(OMPDependClause *C) {
2876  TRY_TO(VisitOMPClauseList(C));
2877  return true;
2878}
2879
2880template <typename Derived>
2881bool RecursiveASTVisitor<Derived>::VisitOMPDeviceClause(OMPDeviceClause *C) {
2882  TRY_TO(TraverseStmt(C->getDevice()));
2883  return true;
2884}
2885
2886template <typename Derived>
2887bool RecursiveASTVisitor<Derived>::VisitOMPMapClause(OMPMapClause *C) {
2888  TRY_TO(VisitOMPClauseList(C));
2889  return true;
2890}
2891
2892template <typename Derived>
2893bool RecursiveASTVisitor<Derived>::VisitOMPNumTeamsClause(
2894    OMPNumTeamsClause *C) {
2895  TRY_TO(TraverseStmt(C->getNumTeams()));
2896  return true;
2897}
2898
2899template <typename Derived>
2900bool RecursiveASTVisitor<Derived>::VisitOMPThreadLimitClause(
2901    OMPThreadLimitClause *C) {
2902  TRY_TO(TraverseStmt(C->getThreadLimit()));
2903  return true;
2904}
2905
2906template <typename Derived>
2907bool RecursiveASTVisitor<Derived>::VisitOMPPriorityClause(
2908    OMPPriorityClause *C) {
2909  TRY_TO(TraverseStmt(C->getPriority()));
2910  return true;
2911}
2912
2913template <typename Derived>
2914bool RecursiveASTVisitor<Derived>::VisitOMPGrainsizeClause(
2915    OMPGrainsizeClause *C) {
2916  TRY_TO(TraverseStmt(C->getGrainsize()));
2917  return true;
2918}
2919
2920template <typename Derived>
2921bool RecursiveASTVisitor<Derived>::VisitOMPNumTasksClause(
2922    OMPNumTasksClause *C) {
2923  TRY_TO(TraverseStmt(C->getNumTasks()));
2924  return true;
2925}
2926
2927template <typename Derived>
2928bool RecursiveASTVisitor<Derived>::VisitOMPHintClause(OMPHintClause *C) {
2929  TRY_TO(TraverseStmt(C->getHint()));
2930  return true;
2931}
2932
2933template <typename Derived>
2934bool RecursiveASTVisitor<Derived>::VisitOMPDistScheduleClause(
2935    OMPDistScheduleClause *C) {
2936  TRY_TO(VisitOMPClauseWithPreInit(C));
2937  TRY_TO(TraverseStmt(C->getChunkSize()));
2938  return true;
2939}
2940
2941template <typename Derived>
2942bool
2943RecursiveASTVisitor<Derived>::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
2944  return true;
2945}
2946
2947template <typename Derived>
2948bool RecursiveASTVisitor<Derived>::VisitOMPToClause(OMPToClause *C) {
2949  TRY_TO(VisitOMPClauseList(C));
2950  return true;
2951}
2952
2953template <typename Derived>
2954bool RecursiveASTVisitor<Derived>::VisitOMPFromClause(OMPFromClause *C) {
2955  TRY_TO(VisitOMPClauseList(C));
2956  return true;
2957}
2958
2959template <typename Derived>
2960bool RecursiveASTVisitor<Derived>::VisitOMPUseDevicePtrClause(
2961    OMPUseDevicePtrClause *C) {
2962  TRY_TO(VisitOMPClauseList(C));
2963  return true;
2964}
2965
2966template <typename Derived>
2967bool RecursiveASTVisitor<Derived>::VisitOMPIsDevicePtrClause(
2968    OMPIsDevicePtrClause *C) {
2969  TRY_TO(VisitOMPClauseList(C));
2970  return true;
2971}
2972
2973// FIXME: look at the following tricky-seeming exprs to see if we
2974// need to recurse on anything.  These are ones that have methods
2975// returning decls or qualtypes or nestednamespecifier -- though I'm
2976// not sure if they own them -- or just seemed very complicated, or
2977// had lots of sub-types to explore.
2978//
2979// VisitOverloadExpr and its children: recurse on template args? etc?
2980
2981// FIXME: go through all the stmts and exprs again, and see which of them
2982// create new types, and recurse on the types (TypeLocs?) of those.
2983// Candidates:
2984//
2985//    http://clang.llvm.org/doxygen/classclang_1_1CXXTypeidExpr.html
2986//    http://clang.llvm.org/doxygen/classclang_1_1UnaryExprOrTypeTraitExpr.html
2987//    http://clang.llvm.org/doxygen/classclang_1_1TypesCompatibleExpr.html
2988//    Every class that has getQualifier.
2989
2990#undef DEF_TRAVERSE_STMT
2991#undef TRAVERSE_STMT
2992#undef TRAVERSE_STMT_BASE
2993
2994#undef TRY_TO
2995
2996} // end namespace clang
2997
2998#endif // LLVM_CLANG_AST_RECURSIVEASTVISITOR_H
2999