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