xref: /freebsd/contrib/llvm-project/clang/lib/Sema/TreeTransform.h (revision ba3c1f5972d7b90feb6e6da47905ff2757e0fe57)
1 //===------- TreeTransform.h - Semantic Tree Transformation -----*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //===----------------------------------------------------------------------===//
7 //
8 //  This file implements a semantic tree transformation that takes a given
9 //  AST and rebuilds it, possibly transforming some nodes in the process.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H
14 #define LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H
15 
16 #include "CoroutineStmtBuilder.h"
17 #include "TypeLocBuilder.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprConcepts.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/ExprObjC.h"
25 #include "clang/AST/ExprOpenMP.h"
26 #include "clang/AST/OpenMPClause.h"
27 #include "clang/AST/Stmt.h"
28 #include "clang/AST/StmtCXX.h"
29 #include "clang/AST/StmtObjC.h"
30 #include "clang/AST/StmtOpenMP.h"
31 #include "clang/Basic/DiagnosticParse.h"
32 #include "clang/Basic/OpenMPKinds.h"
33 #include "clang/Sema/Designator.h"
34 #include "clang/Sema/Lookup.h"
35 #include "clang/Sema/Ownership.h"
36 #include "clang/Sema/ParsedTemplate.h"
37 #include "clang/Sema/ScopeInfo.h"
38 #include "clang/Sema/SemaDiagnostic.h"
39 #include "clang/Sema/SemaInternal.h"
40 #include "llvm/ADT/ArrayRef.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include <algorithm>
43 #include <optional>
44 
45 using namespace llvm::omp;
46 
47 namespace clang {
48 using namespace sema;
49 
50 /// A semantic tree transformation that allows one to transform one
51 /// abstract syntax tree into another.
52 ///
53 /// A new tree transformation is defined by creating a new subclass \c X of
54 /// \c TreeTransform<X> and then overriding certain operations to provide
55 /// behavior specific to that transformation. For example, template
56 /// instantiation is implemented as a tree transformation where the
57 /// transformation of TemplateTypeParmType nodes involves substituting the
58 /// template arguments for their corresponding template parameters; a similar
59 /// transformation is performed for non-type template parameters and
60 /// template template parameters.
61 ///
62 /// This tree-transformation template uses static polymorphism to allow
63 /// subclasses to customize any of its operations. Thus, a subclass can
64 /// override any of the transformation or rebuild operators by providing an
65 /// operation with the same signature as the default implementation. The
66 /// overriding function should not be virtual.
67 ///
68 /// Semantic tree transformations are split into two stages, either of which
69 /// can be replaced by a subclass. The "transform" step transforms an AST node
70 /// or the parts of an AST node using the various transformation functions,
71 /// then passes the pieces on to the "rebuild" step, which constructs a new AST
72 /// node of the appropriate kind from the pieces. The default transformation
73 /// routines recursively transform the operands to composite AST nodes (e.g.,
74 /// the pointee type of a PointerType node) and, if any of those operand nodes
75 /// were changed by the transformation, invokes the rebuild operation to create
76 /// a new AST node.
77 ///
78 /// Subclasses can customize the transformation at various levels. The
79 /// most coarse-grained transformations involve replacing TransformType(),
80 /// TransformExpr(), TransformDecl(), TransformNestedNameSpecifierLoc(),
81 /// TransformTemplateName(), or TransformTemplateArgument() with entirely
82 /// new implementations.
83 ///
84 /// For more fine-grained transformations, subclasses can replace any of the
85 /// \c TransformXXX functions (where XXX is the name of an AST node, e.g.,
86 /// PointerType, StmtExpr) to alter the transformation. As mentioned previously,
87 /// replacing TransformTemplateTypeParmType() allows template instantiation
88 /// to substitute template arguments for their corresponding template
89 /// parameters. Additionally, subclasses can override the \c RebuildXXX
90 /// functions to control how AST nodes are rebuilt when their operands change.
91 /// By default, \c TreeTransform will invoke semantic analysis to rebuild
92 /// AST nodes. However, certain other tree transformations (e.g, cloning) may
93 /// be able to use more efficient rebuild steps.
94 ///
95 /// There are a handful of other functions that can be overridden, allowing one
96 /// to avoid traversing nodes that don't need any transformation
97 /// (\c AlreadyTransformed()), force rebuilding AST nodes even when their
98 /// operands have not changed (\c AlwaysRebuild()), and customize the
99 /// default locations and entity names used for type-checking
100 /// (\c getBaseLocation(), \c getBaseEntity()).
101 template<typename Derived>
102 class TreeTransform {
103   /// Private RAII object that helps us forget and then re-remember
104   /// the template argument corresponding to a partially-substituted parameter
105   /// pack.
106   class ForgetPartiallySubstitutedPackRAII {
107     Derived &Self;
108     TemplateArgument Old;
109 
110   public:
111     ForgetPartiallySubstitutedPackRAII(Derived &Self) : Self(Self) {
112       Old = Self.ForgetPartiallySubstitutedPack();
113     }
114 
115     ~ForgetPartiallySubstitutedPackRAII() {
116       Self.RememberPartiallySubstitutedPack(Old);
117     }
118   };
119 
120 protected:
121   Sema &SemaRef;
122 
123   /// The set of local declarations that have been transformed, for
124   /// cases where we are forced to build new declarations within the transformer
125   /// rather than in the subclass (e.g., lambda closure types).
126   llvm::DenseMap<Decl *, Decl *> TransformedLocalDecls;
127 
128 public:
129   /// Initializes a new tree transformer.
130   TreeTransform(Sema &SemaRef) : SemaRef(SemaRef) { }
131 
132   /// Retrieves a reference to the derived class.
133   Derived &getDerived() { return static_cast<Derived&>(*this); }
134 
135   /// Retrieves a reference to the derived class.
136   const Derived &getDerived() const {
137     return static_cast<const Derived&>(*this);
138   }
139 
140   static inline ExprResult Owned(Expr *E) { return E; }
141   static inline StmtResult Owned(Stmt *S) { return S; }
142 
143   /// Retrieves a reference to the semantic analysis object used for
144   /// this tree transform.
145   Sema &getSema() const { return SemaRef; }
146 
147   /// Whether the transformation should always rebuild AST nodes, even
148   /// if none of the children have changed.
149   ///
150   /// Subclasses may override this function to specify when the transformation
151   /// should rebuild all AST nodes.
152   ///
153   /// We must always rebuild all AST nodes when performing variadic template
154   /// pack expansion, in order to avoid violating the AST invariant that each
155   /// statement node appears at most once in its containing declaration.
156   bool AlwaysRebuild() { return SemaRef.ArgumentPackSubstitutionIndex != -1; }
157 
158   /// Whether the transformation is forming an expression or statement that
159   /// replaces the original. In this case, we'll reuse mangling numbers from
160   /// existing lambdas.
161   bool ReplacingOriginal() { return false; }
162 
163   /// Wether CXXConstructExpr can be skipped when they are implicit.
164   /// They will be reconstructed when used if needed.
165   /// This is useful when the user that cause rebuilding of the
166   /// CXXConstructExpr is outside of the expression at which the TreeTransform
167   /// started.
168   bool AllowSkippingCXXConstructExpr() { return true; }
169 
170   /// Returns the location of the entity being transformed, if that
171   /// information was not available elsewhere in the AST.
172   ///
173   /// By default, returns no source-location information. Subclasses can
174   /// provide an alternative implementation that provides better location
175   /// information.
176   SourceLocation getBaseLocation() { return SourceLocation(); }
177 
178   /// Returns the name of the entity being transformed, if that
179   /// information was not available elsewhere in the AST.
180   ///
181   /// By default, returns an empty name. Subclasses can provide an alternative
182   /// implementation with a more precise name.
183   DeclarationName getBaseEntity() { return DeclarationName(); }
184 
185   /// Sets the "base" location and entity when that
186   /// information is known based on another transformation.
187   ///
188   /// By default, the source location and entity are ignored. Subclasses can
189   /// override this function to provide a customized implementation.
190   void setBase(SourceLocation Loc, DeclarationName Entity) { }
191 
192   /// RAII object that temporarily sets the base location and entity
193   /// used for reporting diagnostics in types.
194   class TemporaryBase {
195     TreeTransform &Self;
196     SourceLocation OldLocation;
197     DeclarationName OldEntity;
198 
199   public:
200     TemporaryBase(TreeTransform &Self, SourceLocation Location,
201                   DeclarationName Entity) : Self(Self) {
202       OldLocation = Self.getDerived().getBaseLocation();
203       OldEntity = Self.getDerived().getBaseEntity();
204 
205       if (Location.isValid())
206         Self.getDerived().setBase(Location, Entity);
207     }
208 
209     ~TemporaryBase() {
210       Self.getDerived().setBase(OldLocation, OldEntity);
211     }
212   };
213 
214   /// Determine whether the given type \p T has already been
215   /// transformed.
216   ///
217   /// Subclasses can provide an alternative implementation of this routine
218   /// to short-circuit evaluation when it is known that a given type will
219   /// not change. For example, template instantiation need not traverse
220   /// non-dependent types.
221   bool AlreadyTransformed(QualType T) {
222     return T.isNull();
223   }
224 
225   /// Transform a template parameter depth level.
226   ///
227   /// During a transformation that transforms template parameters, this maps
228   /// an old template parameter depth to a new depth.
229   unsigned TransformTemplateDepth(unsigned Depth) {
230     return Depth;
231   }
232 
233   /// Determine whether the given call argument should be dropped, e.g.,
234   /// because it is a default argument.
235   ///
236   /// Subclasses can provide an alternative implementation of this routine to
237   /// determine which kinds of call arguments get dropped. By default,
238   /// CXXDefaultArgument nodes are dropped (prior to transformation).
239   bool DropCallArgument(Expr *E) {
240     return E->isDefaultArgument();
241   }
242 
243   /// Determine whether we should expand a pack expansion with the
244   /// given set of parameter packs into separate arguments by repeatedly
245   /// transforming the pattern.
246   ///
247   /// By default, the transformer never tries to expand pack expansions.
248   /// Subclasses can override this routine to provide different behavior.
249   ///
250   /// \param EllipsisLoc The location of the ellipsis that identifies the
251   /// pack expansion.
252   ///
253   /// \param PatternRange The source range that covers the entire pattern of
254   /// the pack expansion.
255   ///
256   /// \param Unexpanded The set of unexpanded parameter packs within the
257   /// pattern.
258   ///
259   /// \param ShouldExpand Will be set to \c true if the transformer should
260   /// expand the corresponding pack expansions into separate arguments. When
261   /// set, \c NumExpansions must also be set.
262   ///
263   /// \param RetainExpansion Whether the caller should add an unexpanded
264   /// pack expansion after all of the expanded arguments. This is used
265   /// when extending explicitly-specified template argument packs per
266   /// C++0x [temp.arg.explicit]p9.
267   ///
268   /// \param NumExpansions The number of separate arguments that will be in
269   /// the expanded form of the corresponding pack expansion. This is both an
270   /// input and an output parameter, which can be set by the caller if the
271   /// number of expansions is known a priori (e.g., due to a prior substitution)
272   /// and will be set by the callee when the number of expansions is known.
273   /// The callee must set this value when \c ShouldExpand is \c true; it may
274   /// set this value in other cases.
275   ///
276   /// \returns true if an error occurred (e.g., because the parameter packs
277   /// are to be instantiated with arguments of different lengths), false
278   /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
279   /// must be set.
280   bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
281                                SourceRange PatternRange,
282                                ArrayRef<UnexpandedParameterPack> Unexpanded,
283                                bool &ShouldExpand, bool &RetainExpansion,
284                                std::optional<unsigned> &NumExpansions) {
285     ShouldExpand = false;
286     return false;
287   }
288 
289   /// "Forget" about the partially-substituted pack template argument,
290   /// when performing an instantiation that must preserve the parameter pack
291   /// use.
292   ///
293   /// This routine is meant to be overridden by the template instantiator.
294   TemplateArgument ForgetPartiallySubstitutedPack() {
295     return TemplateArgument();
296   }
297 
298   /// "Remember" the partially-substituted pack template argument
299   /// after performing an instantiation that must preserve the parameter pack
300   /// use.
301   ///
302   /// This routine is meant to be overridden by the template instantiator.
303   void RememberPartiallySubstitutedPack(TemplateArgument Arg) { }
304 
305   /// Note to the derived class when a function parameter pack is
306   /// being expanded.
307   void ExpandingFunctionParameterPack(ParmVarDecl *Pack) { }
308 
309   /// Transforms the given type into another type.
310   ///
311   /// By default, this routine transforms a type by creating a
312   /// TypeSourceInfo for it and delegating to the appropriate
313   /// function.  This is expensive, but we don't mind, because
314   /// this method is deprecated anyway;  all users should be
315   /// switched to storing TypeSourceInfos.
316   ///
317   /// \returns the transformed type.
318   QualType TransformType(QualType T);
319 
320   /// Transforms the given type-with-location into a new
321   /// type-with-location.
322   ///
323   /// By default, this routine transforms a type by delegating to the
324   /// appropriate TransformXXXType to build a new type.  Subclasses
325   /// may override this function (to take over all type
326   /// transformations) or some set of the TransformXXXType functions
327   /// to alter the transformation.
328   TypeSourceInfo *TransformType(TypeSourceInfo *DI);
329 
330   /// Transform the given type-with-location into a new
331   /// type, collecting location information in the given builder
332   /// as necessary.
333   ///
334   QualType TransformType(TypeLocBuilder &TLB, TypeLoc TL);
335 
336   /// Transform a type that is permitted to produce a
337   /// DeducedTemplateSpecializationType.
338   ///
339   /// This is used in the (relatively rare) contexts where it is acceptable
340   /// for transformation to produce a class template type with deduced
341   /// template arguments.
342   /// @{
343   QualType TransformTypeWithDeducedTST(QualType T);
344   TypeSourceInfo *TransformTypeWithDeducedTST(TypeSourceInfo *DI);
345   /// @}
346 
347   /// The reason why the value of a statement is not discarded, if any.
348   enum StmtDiscardKind {
349     SDK_Discarded,
350     SDK_NotDiscarded,
351     SDK_StmtExprResult,
352   };
353 
354   /// Transform the given statement.
355   ///
356   /// By default, this routine transforms a statement by delegating to the
357   /// appropriate TransformXXXStmt function to transform a specific kind of
358   /// statement or the TransformExpr() function to transform an expression.
359   /// Subclasses may override this function to transform statements using some
360   /// other mechanism.
361   ///
362   /// \returns the transformed statement.
363   StmtResult TransformStmt(Stmt *S, StmtDiscardKind SDK = SDK_Discarded);
364 
365   /// Transform the given statement.
366   ///
367   /// By default, this routine transforms a statement by delegating to the
368   /// appropriate TransformOMPXXXClause function to transform a specific kind
369   /// of clause. Subclasses may override this function to transform statements
370   /// using some other mechanism.
371   ///
372   /// \returns the transformed OpenMP clause.
373   OMPClause *TransformOMPClause(OMPClause *S);
374 
375   /// Transform the given attribute.
376   ///
377   /// By default, this routine transforms a statement by delegating to the
378   /// appropriate TransformXXXAttr function to transform a specific kind
379   /// of attribute. Subclasses may override this function to transform
380   /// attributed statements using some other mechanism.
381   ///
382   /// \returns the transformed attribute
383   const Attr *TransformAttr(const Attr *S);
384 
385 /// Transform the specified attribute.
386 ///
387 /// Subclasses should override the transformation of attributes with a pragma
388 /// spelling to transform expressions stored within the attribute.
389 ///
390 /// \returns the transformed attribute.
391 #define ATTR(X)
392 #define PRAGMA_SPELLING_ATTR(X)                                                \
393   const X##Attr *Transform##X##Attr(const X##Attr *R) { return R; }
394 #include "clang/Basic/AttrList.inc"
395 
396   /// Transform the given expression.
397   ///
398   /// By default, this routine transforms an expression by delegating to the
399   /// appropriate TransformXXXExpr function to build a new expression.
400   /// Subclasses may override this function to transform expressions using some
401   /// other mechanism.
402   ///
403   /// \returns the transformed expression.
404   ExprResult TransformExpr(Expr *E);
405 
406   /// Transform the given initializer.
407   ///
408   /// By default, this routine transforms an initializer by stripping off the
409   /// semantic nodes added by initialization, then passing the result to
410   /// TransformExpr or TransformExprs.
411   ///
412   /// \returns the transformed initializer.
413   ExprResult TransformInitializer(Expr *Init, bool NotCopyInit);
414 
415   /// Transform the given list of expressions.
416   ///
417   /// This routine transforms a list of expressions by invoking
418   /// \c TransformExpr() for each subexpression. However, it also provides
419   /// support for variadic templates by expanding any pack expansions (if the
420   /// derived class permits such expansion) along the way. When pack expansions
421   /// are present, the number of outputs may not equal the number of inputs.
422   ///
423   /// \param Inputs The set of expressions to be transformed.
424   ///
425   /// \param NumInputs The number of expressions in \c Inputs.
426   ///
427   /// \param IsCall If \c true, then this transform is being performed on
428   /// function-call arguments, and any arguments that should be dropped, will
429   /// be.
430   ///
431   /// \param Outputs The transformed input expressions will be added to this
432   /// vector.
433   ///
434   /// \param ArgChanged If non-NULL, will be set \c true if any argument changed
435   /// due to transformation.
436   ///
437   /// \returns true if an error occurred, false otherwise.
438   bool TransformExprs(Expr *const *Inputs, unsigned NumInputs, bool IsCall,
439                       SmallVectorImpl<Expr *> &Outputs,
440                       bool *ArgChanged = nullptr);
441 
442   /// Transform the given declaration, which is referenced from a type
443   /// or expression.
444   ///
445   /// By default, acts as the identity function on declarations, unless the
446   /// transformer has had to transform the declaration itself. Subclasses
447   /// may override this function to provide alternate behavior.
448   Decl *TransformDecl(SourceLocation Loc, Decl *D) {
449     llvm::DenseMap<Decl *, Decl *>::iterator Known
450       = TransformedLocalDecls.find(D);
451     if (Known != TransformedLocalDecls.end())
452       return Known->second;
453 
454     return D;
455   }
456 
457   /// Transform the specified condition.
458   ///
459   /// By default, this transforms the variable and expression and rebuilds
460   /// the condition.
461   Sema::ConditionResult TransformCondition(SourceLocation Loc, VarDecl *Var,
462                                            Expr *Expr,
463                                            Sema::ConditionKind Kind);
464 
465   /// Transform the attributes associated with the given declaration and
466   /// place them on the new declaration.
467   ///
468   /// By default, this operation does nothing. Subclasses may override this
469   /// behavior to transform attributes.
470   void transformAttrs(Decl *Old, Decl *New) { }
471 
472   /// Note that a local declaration has been transformed by this
473   /// transformer.
474   ///
475   /// Local declarations are typically transformed via a call to
476   /// TransformDefinition. However, in some cases (e.g., lambda expressions),
477   /// the transformer itself has to transform the declarations. This routine
478   /// can be overridden by a subclass that keeps track of such mappings.
479   void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> New) {
480     assert(New.size() == 1 &&
481            "must override transformedLocalDecl if performing pack expansion");
482     TransformedLocalDecls[Old] = New.front();
483   }
484 
485   /// Transform the definition of the given declaration.
486   ///
487   /// By default, invokes TransformDecl() to transform the declaration.
488   /// Subclasses may override this function to provide alternate behavior.
489   Decl *TransformDefinition(SourceLocation Loc, Decl *D) {
490     return getDerived().TransformDecl(Loc, D);
491   }
492 
493   /// Transform the given declaration, which was the first part of a
494   /// nested-name-specifier in a member access expression.
495   ///
496   /// This specific declaration transformation only applies to the first
497   /// identifier in a nested-name-specifier of a member access expression, e.g.,
498   /// the \c T in \c x->T::member
499   ///
500   /// By default, invokes TransformDecl() to transform the declaration.
501   /// Subclasses may override this function to provide alternate behavior.
502   NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc) {
503     return cast_or_null<NamedDecl>(getDerived().TransformDecl(Loc, D));
504   }
505 
506   /// Transform the set of declarations in an OverloadExpr.
507   bool TransformOverloadExprDecls(OverloadExpr *Old, bool RequiresADL,
508                                   LookupResult &R);
509 
510   /// Transform the given nested-name-specifier with source-location
511   /// information.
512   ///
513   /// By default, transforms all of the types and declarations within the
514   /// nested-name-specifier. Subclasses may override this function to provide
515   /// alternate behavior.
516   NestedNameSpecifierLoc
517   TransformNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
518                                   QualType ObjectType = QualType(),
519                                   NamedDecl *FirstQualifierInScope = nullptr);
520 
521   /// Transform the given declaration name.
522   ///
523   /// By default, transforms the types of conversion function, constructor,
524   /// and destructor names and then (if needed) rebuilds the declaration name.
525   /// Identifiers and selectors are returned unmodified. Subclasses may
526   /// override this function to provide alternate behavior.
527   DeclarationNameInfo
528   TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo);
529 
530   bool TransformRequiresExprRequirements(ArrayRef<concepts::Requirement *> Reqs,
531       llvm::SmallVectorImpl<concepts::Requirement *> &Transformed);
532   concepts::TypeRequirement *
533   TransformTypeRequirement(concepts::TypeRequirement *Req);
534   concepts::ExprRequirement *
535   TransformExprRequirement(concepts::ExprRequirement *Req);
536   concepts::NestedRequirement *
537   TransformNestedRequirement(concepts::NestedRequirement *Req);
538 
539   /// Transform the given template name.
540   ///
541   /// \param SS The nested-name-specifier that qualifies the template
542   /// name. This nested-name-specifier must already have been transformed.
543   ///
544   /// \param Name The template name to transform.
545   ///
546   /// \param NameLoc The source location of the template name.
547   ///
548   /// \param ObjectType If we're translating a template name within a member
549   /// access expression, this is the type of the object whose member template
550   /// is being referenced.
551   ///
552   /// \param FirstQualifierInScope If the first part of a nested-name-specifier
553   /// also refers to a name within the current (lexical) scope, this is the
554   /// declaration it refers to.
555   ///
556   /// By default, transforms the template name by transforming the declarations
557   /// and nested-name-specifiers that occur within the template name.
558   /// Subclasses may override this function to provide alternate behavior.
559   TemplateName
560   TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
561                         SourceLocation NameLoc,
562                         QualType ObjectType = QualType(),
563                         NamedDecl *FirstQualifierInScope = nullptr,
564                         bool AllowInjectedClassName = false);
565 
566   /// Transform the given template argument.
567   ///
568   /// By default, this operation transforms the type, expression, or
569   /// declaration stored within the template argument and constructs a
570   /// new template argument from the transformed result. Subclasses may
571   /// override this function to provide alternate behavior.
572   ///
573   /// Returns true if there was an error.
574   bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
575                                  TemplateArgumentLoc &Output,
576                                  bool Uneval = false);
577 
578   /// Transform the given set of template arguments.
579   ///
580   /// By default, this operation transforms all of the template arguments
581   /// in the input set using \c TransformTemplateArgument(), and appends
582   /// the transformed arguments to the output list.
583   ///
584   /// Note that this overload of \c TransformTemplateArguments() is merely
585   /// a convenience function. Subclasses that wish to override this behavior
586   /// should override the iterator-based member template version.
587   ///
588   /// \param Inputs The set of template arguments to be transformed.
589   ///
590   /// \param NumInputs The number of template arguments in \p Inputs.
591   ///
592   /// \param Outputs The set of transformed template arguments output by this
593   /// routine.
594   ///
595   /// Returns true if an error occurred.
596   bool TransformTemplateArguments(const TemplateArgumentLoc *Inputs,
597                                   unsigned NumInputs,
598                                   TemplateArgumentListInfo &Outputs,
599                                   bool Uneval = false) {
600     return TransformTemplateArguments(Inputs, Inputs + NumInputs, Outputs,
601                                       Uneval);
602   }
603 
604   /// Transform the given set of template arguments.
605   ///
606   /// By default, this operation transforms all of the template arguments
607   /// in the input set using \c TransformTemplateArgument(), and appends
608   /// the transformed arguments to the output list.
609   ///
610   /// \param First An iterator to the first template argument.
611   ///
612   /// \param Last An iterator one step past the last template argument.
613   ///
614   /// \param Outputs The set of transformed template arguments output by this
615   /// routine.
616   ///
617   /// Returns true if an error occurred.
618   template<typename InputIterator>
619   bool TransformTemplateArguments(InputIterator First,
620                                   InputIterator Last,
621                                   TemplateArgumentListInfo &Outputs,
622                                   bool Uneval = false);
623 
624   /// Fakes up a TemplateArgumentLoc for a given TemplateArgument.
625   void InventTemplateArgumentLoc(const TemplateArgument &Arg,
626                                  TemplateArgumentLoc &ArgLoc);
627 
628   /// Fakes up a TypeSourceInfo for a type.
629   TypeSourceInfo *InventTypeSourceInfo(QualType T) {
630     return SemaRef.Context.getTrivialTypeSourceInfo(T,
631                        getDerived().getBaseLocation());
632   }
633 
634 #define ABSTRACT_TYPELOC(CLASS, PARENT)
635 #define TYPELOC(CLASS, PARENT)                                   \
636   QualType Transform##CLASS##Type(TypeLocBuilder &TLB, CLASS##TypeLoc T);
637 #include "clang/AST/TypeLocNodes.def"
638 
639   QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
640                                          TemplateTypeParmTypeLoc TL,
641                                          bool SuppressObjCLifetime);
642   QualType
643   TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
644                                          SubstTemplateTypeParmPackTypeLoc TL,
645                                          bool SuppressObjCLifetime);
646 
647   template<typename Fn>
648   QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
649                                       FunctionProtoTypeLoc TL,
650                                       CXXRecordDecl *ThisContext,
651                                       Qualifiers ThisTypeQuals,
652                                       Fn TransformExceptionSpec);
653 
654   bool TransformExceptionSpec(SourceLocation Loc,
655                               FunctionProtoType::ExceptionSpecInfo &ESI,
656                               SmallVectorImpl<QualType> &Exceptions,
657                               bool &Changed);
658 
659   StmtResult TransformSEHHandler(Stmt *Handler);
660 
661   QualType
662   TransformTemplateSpecializationType(TypeLocBuilder &TLB,
663                                       TemplateSpecializationTypeLoc TL,
664                                       TemplateName Template);
665 
666   QualType
667   TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
668                                       DependentTemplateSpecializationTypeLoc TL,
669                                                TemplateName Template,
670                                                CXXScopeSpec &SS);
671 
672   QualType TransformDependentTemplateSpecializationType(
673       TypeLocBuilder &TLB, DependentTemplateSpecializationTypeLoc TL,
674       NestedNameSpecifierLoc QualifierLoc);
675 
676   /// Transforms the parameters of a function type into the
677   /// given vectors.
678   ///
679   /// The result vectors should be kept in sync; null entries in the
680   /// variables vector are acceptable.
681   ///
682   /// LastParamTransformed, if non-null, will be set to the index of the last
683   /// parameter on which transfromation was started. In the event of an error,
684   /// this will contain the parameter which failed to instantiate.
685   ///
686   /// Return true on error.
687   bool TransformFunctionTypeParams(
688       SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
689       const QualType *ParamTypes,
690       const FunctionProtoType::ExtParameterInfo *ParamInfos,
691       SmallVectorImpl<QualType> &PTypes, SmallVectorImpl<ParmVarDecl *> *PVars,
692       Sema::ExtParameterInfoBuilder &PInfos, unsigned *LastParamTransformed);
693 
694   bool TransformFunctionTypeParams(
695       SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
696       const QualType *ParamTypes,
697       const FunctionProtoType::ExtParameterInfo *ParamInfos,
698       SmallVectorImpl<QualType> &PTypes, SmallVectorImpl<ParmVarDecl *> *PVars,
699       Sema::ExtParameterInfoBuilder &PInfos) {
700     return getDerived().TransformFunctionTypeParams(
701         Loc, Params, ParamTypes, ParamInfos, PTypes, PVars, PInfos, nullptr);
702   }
703 
704   /// Transforms the parameters of a requires expresison into the given vectors.
705   ///
706   /// The result vectors should be kept in sync; null entries in the
707   /// variables vector are acceptable.
708   ///
709   /// Returns an unset ExprResult on success.  Returns an ExprResult the 'not
710   /// satisfied' RequiresExpr if subsitution failed, OR an ExprError, both of
711   /// which are cases where transformation shouldn't continue.
712   ExprResult TransformRequiresTypeParams(
713       SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
714       RequiresExprBodyDecl *Body, ArrayRef<ParmVarDecl *> Params,
715       SmallVectorImpl<QualType> &PTypes,
716       SmallVectorImpl<ParmVarDecl *> &TransParams,
717       Sema::ExtParameterInfoBuilder &PInfos) {
718     if (getDerived().TransformFunctionTypeParams(
719             KWLoc, Params, /*ParamTypes=*/nullptr,
720             /*ParamInfos=*/nullptr, PTypes, &TransParams, PInfos))
721       return ExprError();
722 
723     return ExprResult{};
724   }
725 
726   /// Transforms a single function-type parameter.  Return null
727   /// on error.
728   ///
729   /// \param indexAdjustment - A number to add to the parameter's
730   ///   scope index;  can be negative
731   ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
732                                           int indexAdjustment,
733                                           std::optional<unsigned> NumExpansions,
734                                           bool ExpectParameterPack);
735 
736   /// Transform the body of a lambda-expression.
737   StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body);
738   /// Alternative implementation of TransformLambdaBody that skips transforming
739   /// the body.
740   StmtResult SkipLambdaBody(LambdaExpr *E, Stmt *Body);
741 
742   QualType TransformReferenceType(TypeLocBuilder &TLB, ReferenceTypeLoc TL);
743 
744   StmtResult TransformCompoundStmt(CompoundStmt *S, bool IsStmtExpr);
745   ExprResult TransformCXXNamedCastExpr(CXXNamedCastExpr *E);
746 
747   TemplateParameterList *TransformTemplateParameterList(
748         TemplateParameterList *TPL) {
749     return TPL;
750   }
751 
752   ExprResult TransformAddressOfOperand(Expr *E);
753 
754   ExprResult TransformDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E,
755                                                 bool IsAddressOfOperand,
756                                                 TypeSourceInfo **RecoveryTSI);
757 
758   ExprResult TransformParenDependentScopeDeclRefExpr(
759       ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool IsAddressOfOperand,
760       TypeSourceInfo **RecoveryTSI);
761 
762   StmtResult TransformOMPExecutableDirective(OMPExecutableDirective *S);
763 
764 // FIXME: We use LLVM_ATTRIBUTE_NOINLINE because inlining causes a ridiculous
765 // amount of stack usage with clang.
766 #define STMT(Node, Parent)                        \
767   LLVM_ATTRIBUTE_NOINLINE \
768   StmtResult Transform##Node(Node *S);
769 #define VALUESTMT(Node, Parent)                   \
770   LLVM_ATTRIBUTE_NOINLINE \
771   StmtResult Transform##Node(Node *S, StmtDiscardKind SDK);
772 #define EXPR(Node, Parent)                        \
773   LLVM_ATTRIBUTE_NOINLINE \
774   ExprResult Transform##Node(Node *E);
775 #define ABSTRACT_STMT(Stmt)
776 #include "clang/AST/StmtNodes.inc"
777 
778 #define GEN_CLANG_CLAUSE_CLASS
779 #define CLAUSE_CLASS(Enum, Str, Class)                                         \
780   LLVM_ATTRIBUTE_NOINLINE                                                      \
781   OMPClause *Transform##Class(Class *S);
782 #include "llvm/Frontend/OpenMP/OMP.inc"
783 
784   /// Build a new qualified type given its unqualified type and type location.
785   ///
786   /// By default, this routine adds type qualifiers only to types that can
787   /// have qualifiers, and silently suppresses those qualifiers that are not
788   /// permitted. Subclasses may override this routine to provide different
789   /// behavior.
790   QualType RebuildQualifiedType(QualType T, QualifiedTypeLoc TL);
791 
792   /// Build a new pointer type given its pointee type.
793   ///
794   /// By default, performs semantic analysis when building the pointer type.
795   /// Subclasses may override this routine to provide different behavior.
796   QualType RebuildPointerType(QualType PointeeType, SourceLocation Sigil);
797 
798   /// Build a new block pointer type given its pointee type.
799   ///
800   /// By default, performs semantic analysis when building the block pointer
801   /// type. Subclasses may override this routine to provide different behavior.
802   QualType RebuildBlockPointerType(QualType PointeeType, SourceLocation Sigil);
803 
804   /// Build a new reference type given the type it references.
805   ///
806   /// By default, performs semantic analysis when building the
807   /// reference type. Subclasses may override this routine to provide
808   /// different behavior.
809   ///
810   /// \param LValue whether the type was written with an lvalue sigil
811   /// or an rvalue sigil.
812   QualType RebuildReferenceType(QualType ReferentType,
813                                 bool LValue,
814                                 SourceLocation Sigil);
815 
816   /// Build a new member pointer type given the pointee type and the
817   /// class type it refers into.
818   ///
819   /// By default, performs semantic analysis when building the member pointer
820   /// type. Subclasses may override this routine to provide different behavior.
821   QualType RebuildMemberPointerType(QualType PointeeType, QualType ClassType,
822                                     SourceLocation Sigil);
823 
824   QualType RebuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
825                                     SourceLocation ProtocolLAngleLoc,
826                                     ArrayRef<ObjCProtocolDecl *> Protocols,
827                                     ArrayRef<SourceLocation> ProtocolLocs,
828                                     SourceLocation ProtocolRAngleLoc);
829 
830   /// Build an Objective-C object type.
831   ///
832   /// By default, performs semantic analysis when building the object type.
833   /// Subclasses may override this routine to provide different behavior.
834   QualType RebuildObjCObjectType(QualType BaseType,
835                                  SourceLocation Loc,
836                                  SourceLocation TypeArgsLAngleLoc,
837                                  ArrayRef<TypeSourceInfo *> TypeArgs,
838                                  SourceLocation TypeArgsRAngleLoc,
839                                  SourceLocation ProtocolLAngleLoc,
840                                  ArrayRef<ObjCProtocolDecl *> Protocols,
841                                  ArrayRef<SourceLocation> ProtocolLocs,
842                                  SourceLocation ProtocolRAngleLoc);
843 
844   /// Build a new Objective-C object pointer type given the pointee type.
845   ///
846   /// By default, directly builds the pointer type, with no additional semantic
847   /// analysis.
848   QualType RebuildObjCObjectPointerType(QualType PointeeType,
849                                         SourceLocation Star);
850 
851   /// Build a new array type given the element type, size
852   /// modifier, size of the array (if known), size expression, and index type
853   /// qualifiers.
854   ///
855   /// By default, performs semantic analysis when building the array type.
856   /// Subclasses may override this routine to provide different behavior.
857   /// Also by default, all of the other Rebuild*Array
858   QualType RebuildArrayType(QualType ElementType,
859                             ArrayType::ArraySizeModifier SizeMod,
860                             const llvm::APInt *Size,
861                             Expr *SizeExpr,
862                             unsigned IndexTypeQuals,
863                             SourceRange BracketsRange);
864 
865   /// Build a new constant array type given the element type, size
866   /// modifier, (known) size of the array, and index type qualifiers.
867   ///
868   /// By default, performs semantic analysis when building the array type.
869   /// Subclasses may override this routine to provide different behavior.
870   QualType RebuildConstantArrayType(QualType ElementType,
871                                     ArrayType::ArraySizeModifier SizeMod,
872                                     const llvm::APInt &Size,
873                                     Expr *SizeExpr,
874                                     unsigned IndexTypeQuals,
875                                     SourceRange BracketsRange);
876 
877   /// Build a new incomplete array type given the element type, size
878   /// modifier, and index type qualifiers.
879   ///
880   /// By default, performs semantic analysis when building the array type.
881   /// Subclasses may override this routine to provide different behavior.
882   QualType RebuildIncompleteArrayType(QualType ElementType,
883                                       ArrayType::ArraySizeModifier SizeMod,
884                                       unsigned IndexTypeQuals,
885                                       SourceRange BracketsRange);
886 
887   /// Build a new variable-length array type given the element type,
888   /// size modifier, size expression, and index type qualifiers.
889   ///
890   /// By default, performs semantic analysis when building the array type.
891   /// Subclasses may override this routine to provide different behavior.
892   QualType RebuildVariableArrayType(QualType ElementType,
893                                     ArrayType::ArraySizeModifier SizeMod,
894                                     Expr *SizeExpr,
895                                     unsigned IndexTypeQuals,
896                                     SourceRange BracketsRange);
897 
898   /// Build a new dependent-sized array type given the element type,
899   /// size modifier, size expression, and index type qualifiers.
900   ///
901   /// By default, performs semantic analysis when building the array type.
902   /// Subclasses may override this routine to provide different behavior.
903   QualType RebuildDependentSizedArrayType(QualType ElementType,
904                                           ArrayType::ArraySizeModifier SizeMod,
905                                           Expr *SizeExpr,
906                                           unsigned IndexTypeQuals,
907                                           SourceRange BracketsRange);
908 
909   /// Build a new vector type given the element type and
910   /// number of elements.
911   ///
912   /// By default, performs semantic analysis when building the vector type.
913   /// Subclasses may override this routine to provide different behavior.
914   QualType RebuildVectorType(QualType ElementType, unsigned NumElements,
915                              VectorType::VectorKind VecKind);
916 
917   /// Build a new potentially dependently-sized extended vector type
918   /// given the element type and number of elements.
919   ///
920   /// By default, performs semantic analysis when building the vector type.
921   /// Subclasses may override this routine to provide different behavior.
922   QualType RebuildDependentVectorType(QualType ElementType, Expr *SizeExpr,
923                                            SourceLocation AttributeLoc,
924                                            VectorType::VectorKind);
925 
926   /// Build a new extended vector type given the element type and
927   /// number of elements.
928   ///
929   /// By default, performs semantic analysis when building the vector type.
930   /// Subclasses may override this routine to provide different behavior.
931   QualType RebuildExtVectorType(QualType ElementType, unsigned NumElements,
932                                 SourceLocation AttributeLoc);
933 
934   /// Build a new potentially dependently-sized extended vector type
935   /// given the element type and number of elements.
936   ///
937   /// By default, performs semantic analysis when building the vector type.
938   /// Subclasses may override this routine to provide different behavior.
939   QualType RebuildDependentSizedExtVectorType(QualType ElementType,
940                                               Expr *SizeExpr,
941                                               SourceLocation AttributeLoc);
942 
943   /// Build a new matrix type given the element type and dimensions.
944   QualType RebuildConstantMatrixType(QualType ElementType, unsigned NumRows,
945                                      unsigned NumColumns);
946 
947   /// Build a new matrix type given the type and dependently-defined
948   /// dimensions.
949   QualType RebuildDependentSizedMatrixType(QualType ElementType, Expr *RowExpr,
950                                            Expr *ColumnExpr,
951                                            SourceLocation AttributeLoc);
952 
953   /// Build a new DependentAddressSpaceType or return the pointee
954   /// type variable with the correct address space (retrieved from
955   /// AddrSpaceExpr) applied to it. The former will be returned in cases
956   /// where the address space remains dependent.
957   ///
958   /// By default, performs semantic analysis when building the type with address
959   /// space applied. Subclasses may override this routine to provide different
960   /// behavior.
961   QualType RebuildDependentAddressSpaceType(QualType PointeeType,
962                                             Expr *AddrSpaceExpr,
963                                             SourceLocation AttributeLoc);
964 
965   /// Build a new function type.
966   ///
967   /// By default, performs semantic analysis when building the function type.
968   /// Subclasses may override this routine to provide different behavior.
969   QualType RebuildFunctionProtoType(QualType T,
970                                     MutableArrayRef<QualType> ParamTypes,
971                                     const FunctionProtoType::ExtProtoInfo &EPI);
972 
973   /// Build a new unprototyped function type.
974   QualType RebuildFunctionNoProtoType(QualType ResultType);
975 
976   /// Rebuild an unresolved typename type, given the decl that
977   /// the UnresolvedUsingTypenameDecl was transformed to.
978   QualType RebuildUnresolvedUsingType(SourceLocation NameLoc, Decl *D);
979 
980   /// Build a new type found via an alias.
981   QualType RebuildUsingType(UsingShadowDecl *Found, QualType Underlying) {
982     return SemaRef.Context.getUsingType(Found, Underlying);
983   }
984 
985   /// Build a new typedef type.
986   QualType RebuildTypedefType(TypedefNameDecl *Typedef) {
987     return SemaRef.Context.getTypeDeclType(Typedef);
988   }
989 
990   /// Build a new MacroDefined type.
991   QualType RebuildMacroQualifiedType(QualType T,
992                                      const IdentifierInfo *MacroII) {
993     return SemaRef.Context.getMacroQualifiedType(T, MacroII);
994   }
995 
996   /// Build a new class/struct/union type.
997   QualType RebuildRecordType(RecordDecl *Record) {
998     return SemaRef.Context.getTypeDeclType(Record);
999   }
1000 
1001   /// Build a new Enum type.
1002   QualType RebuildEnumType(EnumDecl *Enum) {
1003     return SemaRef.Context.getTypeDeclType(Enum);
1004   }
1005 
1006   /// Build a new typeof(expr) type.
1007   ///
1008   /// By default, performs semantic analysis when building the typeof type.
1009   /// Subclasses may override this routine to provide different behavior.
1010   QualType RebuildTypeOfExprType(Expr *Underlying, SourceLocation Loc,
1011                                  TypeOfKind Kind);
1012 
1013   /// Build a new typeof(type) type.
1014   ///
1015   /// By default, builds a new TypeOfType with the given underlying type.
1016   QualType RebuildTypeOfType(QualType Underlying, TypeOfKind Kind);
1017 
1018   /// Build a new unary transform type.
1019   QualType RebuildUnaryTransformType(QualType BaseType,
1020                                      UnaryTransformType::UTTKind UKind,
1021                                      SourceLocation Loc);
1022 
1023   /// Build a new C++11 decltype type.
1024   ///
1025   /// By default, performs semantic analysis when building the decltype type.
1026   /// Subclasses may override this routine to provide different behavior.
1027   QualType RebuildDecltypeType(Expr *Underlying, SourceLocation Loc);
1028 
1029   /// Build a new C++11 auto type.
1030   ///
1031   /// By default, builds a new AutoType with the given deduced type.
1032   QualType RebuildAutoType(QualType Deduced, AutoTypeKeyword Keyword,
1033                            ConceptDecl *TypeConstraintConcept,
1034                            ArrayRef<TemplateArgument> TypeConstraintArgs) {
1035     // Note, IsDependent is always false here: we implicitly convert an 'auto'
1036     // which has been deduced to a dependent type into an undeduced 'auto', so
1037     // that we'll retry deduction after the transformation.
1038     return SemaRef.Context.getAutoType(Deduced, Keyword,
1039                                        /*IsDependent*/ false, /*IsPack=*/false,
1040                                        TypeConstraintConcept,
1041                                        TypeConstraintArgs);
1042   }
1043 
1044   /// By default, builds a new DeducedTemplateSpecializationType with the given
1045   /// deduced type.
1046   QualType RebuildDeducedTemplateSpecializationType(TemplateName Template,
1047       QualType Deduced) {
1048     return SemaRef.Context.getDeducedTemplateSpecializationType(
1049         Template, Deduced, /*IsDependent*/ false);
1050   }
1051 
1052   /// Build a new template specialization type.
1053   ///
1054   /// By default, performs semantic analysis when building the template
1055   /// specialization type. Subclasses may override this routine to provide
1056   /// different behavior.
1057   QualType RebuildTemplateSpecializationType(TemplateName Template,
1058                                              SourceLocation TemplateLoc,
1059                                              TemplateArgumentListInfo &Args);
1060 
1061   /// Build a new parenthesized type.
1062   ///
1063   /// By default, builds a new ParenType type from the inner type.
1064   /// Subclasses may override this routine to provide different behavior.
1065   QualType RebuildParenType(QualType InnerType) {
1066     return SemaRef.BuildParenType(InnerType);
1067   }
1068 
1069   /// Build a new qualified name type.
1070   ///
1071   /// By default, builds a new ElaboratedType type from the keyword,
1072   /// the nested-name-specifier and the named type.
1073   /// Subclasses may override this routine to provide different behavior.
1074   QualType RebuildElaboratedType(SourceLocation KeywordLoc,
1075                                  ElaboratedTypeKeyword Keyword,
1076                                  NestedNameSpecifierLoc QualifierLoc,
1077                                  QualType Named) {
1078     return SemaRef.Context.getElaboratedType(Keyword,
1079                                          QualifierLoc.getNestedNameSpecifier(),
1080                                              Named);
1081   }
1082 
1083   /// Build a new typename type that refers to a template-id.
1084   ///
1085   /// By default, builds a new DependentNameType type from the
1086   /// nested-name-specifier and the given type. Subclasses may override
1087   /// this routine to provide different behavior.
1088   QualType RebuildDependentTemplateSpecializationType(
1089                                           ElaboratedTypeKeyword Keyword,
1090                                           NestedNameSpecifierLoc QualifierLoc,
1091                                           SourceLocation TemplateKWLoc,
1092                                           const IdentifierInfo *Name,
1093                                           SourceLocation NameLoc,
1094                                           TemplateArgumentListInfo &Args,
1095                                           bool AllowInjectedClassName) {
1096     // Rebuild the template name.
1097     // TODO: avoid TemplateName abstraction
1098     CXXScopeSpec SS;
1099     SS.Adopt(QualifierLoc);
1100     TemplateName InstName = getDerived().RebuildTemplateName(
1101         SS, TemplateKWLoc, *Name, NameLoc, QualType(), nullptr,
1102         AllowInjectedClassName);
1103 
1104     if (InstName.isNull())
1105       return QualType();
1106 
1107     // If it's still dependent, make a dependent specialization.
1108     if (InstName.getAsDependentTemplateName())
1109       return SemaRef.Context.getDependentTemplateSpecializationType(
1110           Keyword, QualifierLoc.getNestedNameSpecifier(), Name,
1111           Args.arguments());
1112 
1113     // Otherwise, make an elaborated type wrapping a non-dependent
1114     // specialization.
1115     QualType T =
1116         getDerived().RebuildTemplateSpecializationType(InstName, NameLoc, Args);
1117     if (T.isNull())
1118       return QualType();
1119     return SemaRef.Context.getElaboratedType(
1120         Keyword, QualifierLoc.getNestedNameSpecifier(), T);
1121   }
1122 
1123   /// Build a new typename type that refers to an identifier.
1124   ///
1125   /// By default, performs semantic analysis when building the typename type
1126   /// (or elaborated type). Subclasses may override this routine to provide
1127   /// different behavior.
1128   QualType RebuildDependentNameType(ElaboratedTypeKeyword Keyword,
1129                                     SourceLocation KeywordLoc,
1130                                     NestedNameSpecifierLoc QualifierLoc,
1131                                     const IdentifierInfo *Id,
1132                                     SourceLocation IdLoc,
1133                                     bool DeducedTSTContext) {
1134     CXXScopeSpec SS;
1135     SS.Adopt(QualifierLoc);
1136 
1137     if (QualifierLoc.getNestedNameSpecifier()->isDependent()) {
1138       // If the name is still dependent, just build a new dependent name type.
1139       if (!SemaRef.computeDeclContext(SS))
1140         return SemaRef.Context.getDependentNameType(Keyword,
1141                                           QualifierLoc.getNestedNameSpecifier(),
1142                                                     Id);
1143     }
1144 
1145     if (Keyword == ETK_None || Keyword == ETK_Typename) {
1146       return SemaRef.CheckTypenameType(Keyword, KeywordLoc, QualifierLoc,
1147                                        *Id, IdLoc, DeducedTSTContext);
1148     }
1149 
1150     TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
1151 
1152     // We had a dependent elaborated-type-specifier that has been transformed
1153     // into a non-dependent elaborated-type-specifier. Find the tag we're
1154     // referring to.
1155     LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1156     DeclContext *DC = SemaRef.computeDeclContext(SS, false);
1157     if (!DC)
1158       return QualType();
1159 
1160     if (SemaRef.RequireCompleteDeclContext(SS, DC))
1161       return QualType();
1162 
1163     TagDecl *Tag = nullptr;
1164     SemaRef.LookupQualifiedName(Result, DC);
1165     switch (Result.getResultKind()) {
1166       case LookupResult::NotFound:
1167       case LookupResult::NotFoundInCurrentInstantiation:
1168         break;
1169 
1170       case LookupResult::Found:
1171         Tag = Result.getAsSingle<TagDecl>();
1172         break;
1173 
1174       case LookupResult::FoundOverloaded:
1175       case LookupResult::FoundUnresolvedValue:
1176         llvm_unreachable("Tag lookup cannot find non-tags");
1177 
1178       case LookupResult::Ambiguous:
1179         // Let the LookupResult structure handle ambiguities.
1180         return QualType();
1181     }
1182 
1183     if (!Tag) {
1184       // Check where the name exists but isn't a tag type and use that to emit
1185       // better diagnostics.
1186       LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1187       SemaRef.LookupQualifiedName(Result, DC);
1188       switch (Result.getResultKind()) {
1189         case LookupResult::Found:
1190         case LookupResult::FoundOverloaded:
1191         case LookupResult::FoundUnresolvedValue: {
1192           NamedDecl *SomeDecl = Result.getRepresentativeDecl();
1193           Sema::NonTagKind NTK = SemaRef.getNonTagTypeDeclKind(SomeDecl, Kind);
1194           SemaRef.Diag(IdLoc, diag::err_tag_reference_non_tag) << SomeDecl
1195                                                                << NTK << Kind;
1196           SemaRef.Diag(SomeDecl->getLocation(), diag::note_declared_at);
1197           break;
1198         }
1199         default:
1200           SemaRef.Diag(IdLoc, diag::err_not_tag_in_scope)
1201               << Kind << Id << DC << QualifierLoc.getSourceRange();
1202           break;
1203       }
1204       return QualType();
1205     }
1206 
1207     if (!SemaRef.isAcceptableTagRedeclaration(Tag, Kind, /*isDefinition*/false,
1208                                               IdLoc, Id)) {
1209       SemaRef.Diag(KeywordLoc, diag::err_use_with_wrong_tag) << Id;
1210       SemaRef.Diag(Tag->getLocation(), diag::note_previous_use);
1211       return QualType();
1212     }
1213 
1214     // Build the elaborated-type-specifier type.
1215     QualType T = SemaRef.Context.getTypeDeclType(Tag);
1216     return SemaRef.Context.getElaboratedType(Keyword,
1217                                          QualifierLoc.getNestedNameSpecifier(),
1218                                              T);
1219   }
1220 
1221   /// Build a new pack expansion type.
1222   ///
1223   /// By default, builds a new PackExpansionType type from the given pattern.
1224   /// Subclasses may override this routine to provide different behavior.
1225   QualType RebuildPackExpansionType(QualType Pattern, SourceRange PatternRange,
1226                                     SourceLocation EllipsisLoc,
1227                                     std::optional<unsigned> NumExpansions) {
1228     return getSema().CheckPackExpansion(Pattern, PatternRange, EllipsisLoc,
1229                                         NumExpansions);
1230   }
1231 
1232   /// Build a new atomic type given its value type.
1233   ///
1234   /// By default, performs semantic analysis when building the atomic type.
1235   /// Subclasses may override this routine to provide different behavior.
1236   QualType RebuildAtomicType(QualType ValueType, SourceLocation KWLoc);
1237 
1238   /// Build a new pipe type given its value type.
1239   QualType RebuildPipeType(QualType ValueType, SourceLocation KWLoc,
1240                            bool isReadPipe);
1241 
1242   /// Build a bit-precise int given its value type.
1243   QualType RebuildBitIntType(bool IsUnsigned, unsigned NumBits,
1244                              SourceLocation Loc);
1245 
1246   /// Build a dependent bit-precise int given its value type.
1247   QualType RebuildDependentBitIntType(bool IsUnsigned, Expr *NumBitsExpr,
1248                                       SourceLocation Loc);
1249 
1250   /// Build a new template name given a nested name specifier, a flag
1251   /// indicating whether the "template" keyword was provided, and the template
1252   /// that the template name refers to.
1253   ///
1254   /// By default, builds the new template name directly. Subclasses may override
1255   /// this routine to provide different behavior.
1256   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1257                                    bool TemplateKW,
1258                                    TemplateDecl *Template);
1259 
1260   /// Build a new template name given a nested name specifier and the
1261   /// name that is referred to as a template.
1262   ///
1263   /// By default, performs semantic analysis to determine whether the name can
1264   /// be resolved to a specific template, then builds the appropriate kind of
1265   /// template name. Subclasses may override this routine to provide different
1266   /// behavior.
1267   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1268                                    SourceLocation TemplateKWLoc,
1269                                    const IdentifierInfo &Name,
1270                                    SourceLocation NameLoc, QualType ObjectType,
1271                                    NamedDecl *FirstQualifierInScope,
1272                                    bool AllowInjectedClassName);
1273 
1274   /// Build a new template name given a nested name specifier and the
1275   /// overloaded operator name that is referred to as a template.
1276   ///
1277   /// By default, performs semantic analysis to determine whether the name can
1278   /// be resolved to a specific template, then builds the appropriate kind of
1279   /// template name. Subclasses may override this routine to provide different
1280   /// behavior.
1281   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1282                                    SourceLocation TemplateKWLoc,
1283                                    OverloadedOperatorKind Operator,
1284                                    SourceLocation NameLoc, QualType ObjectType,
1285                                    bool AllowInjectedClassName);
1286 
1287   /// Build a new template name given a template template parameter pack
1288   /// and the
1289   ///
1290   /// By default, performs semantic analysis to determine whether the name can
1291   /// be resolved to a specific template, then builds the appropriate kind of
1292   /// template name. Subclasses may override this routine to provide different
1293   /// behavior.
1294   TemplateName RebuildTemplateName(const TemplateArgument &ArgPack,
1295                                    Decl *AssociatedDecl, unsigned Index,
1296                                    bool Final) {
1297     return getSema().Context.getSubstTemplateTemplateParmPack(
1298         ArgPack, AssociatedDecl, Index, Final);
1299   }
1300 
1301   /// Build a new compound statement.
1302   ///
1303   /// By default, performs semantic analysis to build the new statement.
1304   /// Subclasses may override this routine to provide different behavior.
1305   StmtResult RebuildCompoundStmt(SourceLocation LBraceLoc,
1306                                        MultiStmtArg Statements,
1307                                        SourceLocation RBraceLoc,
1308                                        bool IsStmtExpr) {
1309     return getSema().ActOnCompoundStmt(LBraceLoc, RBraceLoc, Statements,
1310                                        IsStmtExpr);
1311   }
1312 
1313   /// Build a new case statement.
1314   ///
1315   /// By default, performs semantic analysis to build the new statement.
1316   /// Subclasses may override this routine to provide different behavior.
1317   StmtResult RebuildCaseStmt(SourceLocation CaseLoc,
1318                                    Expr *LHS,
1319                                    SourceLocation EllipsisLoc,
1320                                    Expr *RHS,
1321                                    SourceLocation ColonLoc) {
1322     return getSema().ActOnCaseStmt(CaseLoc, LHS, EllipsisLoc, RHS,
1323                                    ColonLoc);
1324   }
1325 
1326   /// Attach the body to a new case statement.
1327   ///
1328   /// By default, performs semantic analysis to build the new statement.
1329   /// Subclasses may override this routine to provide different behavior.
1330   StmtResult RebuildCaseStmtBody(Stmt *S, Stmt *Body) {
1331     getSema().ActOnCaseStmtBody(S, Body);
1332     return S;
1333   }
1334 
1335   /// Build a new default statement.
1336   ///
1337   /// By default, performs semantic analysis to build the new statement.
1338   /// Subclasses may override this routine to provide different behavior.
1339   StmtResult RebuildDefaultStmt(SourceLocation DefaultLoc,
1340                                       SourceLocation ColonLoc,
1341                                       Stmt *SubStmt) {
1342     return getSema().ActOnDefaultStmt(DefaultLoc, ColonLoc, SubStmt,
1343                                       /*CurScope=*/nullptr);
1344   }
1345 
1346   /// Build a new label statement.
1347   ///
1348   /// By default, performs semantic analysis to build the new statement.
1349   /// Subclasses may override this routine to provide different behavior.
1350   StmtResult RebuildLabelStmt(SourceLocation IdentLoc, LabelDecl *L,
1351                               SourceLocation ColonLoc, Stmt *SubStmt) {
1352     return SemaRef.ActOnLabelStmt(IdentLoc, L, ColonLoc, SubStmt);
1353   }
1354 
1355   /// Build a new attributed statement.
1356   ///
1357   /// By default, performs semantic analysis to build the new statement.
1358   /// Subclasses may override this routine to provide different behavior.
1359   StmtResult RebuildAttributedStmt(SourceLocation AttrLoc,
1360                                    ArrayRef<const Attr *> Attrs,
1361                                    Stmt *SubStmt) {
1362     return SemaRef.BuildAttributedStmt(AttrLoc, Attrs, SubStmt);
1363   }
1364 
1365   /// Build a new "if" statement.
1366   ///
1367   /// By default, performs semantic analysis to build the new statement.
1368   /// Subclasses may override this routine to provide different behavior.
1369   StmtResult RebuildIfStmt(SourceLocation IfLoc, IfStatementKind Kind,
1370                            SourceLocation LParenLoc, Sema::ConditionResult Cond,
1371                            SourceLocation RParenLoc, Stmt *Init, Stmt *Then,
1372                            SourceLocation ElseLoc, Stmt *Else) {
1373     return getSema().ActOnIfStmt(IfLoc, Kind, LParenLoc, Init, Cond, RParenLoc,
1374                                  Then, ElseLoc, Else);
1375   }
1376 
1377   /// Start building a new switch statement.
1378   ///
1379   /// By default, performs semantic analysis to build the new statement.
1380   /// Subclasses may override this routine to provide different behavior.
1381   StmtResult RebuildSwitchStmtStart(SourceLocation SwitchLoc,
1382                                     SourceLocation LParenLoc, Stmt *Init,
1383                                     Sema::ConditionResult Cond,
1384                                     SourceLocation RParenLoc) {
1385     return getSema().ActOnStartOfSwitchStmt(SwitchLoc, LParenLoc, Init, Cond,
1386                                             RParenLoc);
1387   }
1388 
1389   /// Attach the body to the switch statement.
1390   ///
1391   /// By default, performs semantic analysis to build the new statement.
1392   /// Subclasses may override this routine to provide different behavior.
1393   StmtResult RebuildSwitchStmtBody(SourceLocation SwitchLoc,
1394                                    Stmt *Switch, Stmt *Body) {
1395     return getSema().ActOnFinishSwitchStmt(SwitchLoc, Switch, Body);
1396   }
1397 
1398   /// Build a new while statement.
1399   ///
1400   /// By default, performs semantic analysis to build the new statement.
1401   /// Subclasses may override this routine to provide different behavior.
1402   StmtResult RebuildWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc,
1403                               Sema::ConditionResult Cond,
1404                               SourceLocation RParenLoc, Stmt *Body) {
1405     return getSema().ActOnWhileStmt(WhileLoc, LParenLoc, Cond, RParenLoc, Body);
1406   }
1407 
1408   /// Build a new do-while statement.
1409   ///
1410   /// By default, performs semantic analysis to build the new statement.
1411   /// Subclasses may override this routine to provide different behavior.
1412   StmtResult RebuildDoStmt(SourceLocation DoLoc, Stmt *Body,
1413                            SourceLocation WhileLoc, SourceLocation LParenLoc,
1414                            Expr *Cond, SourceLocation RParenLoc) {
1415     return getSema().ActOnDoStmt(DoLoc, Body, WhileLoc, LParenLoc,
1416                                  Cond, RParenLoc);
1417   }
1418 
1419   /// Build a new for statement.
1420   ///
1421   /// By default, performs semantic analysis to build the new statement.
1422   /// Subclasses may override this routine to provide different behavior.
1423   StmtResult RebuildForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1424                             Stmt *Init, Sema::ConditionResult Cond,
1425                             Sema::FullExprArg Inc, SourceLocation RParenLoc,
1426                             Stmt *Body) {
1427     return getSema().ActOnForStmt(ForLoc, LParenLoc, Init, Cond,
1428                                   Inc, RParenLoc, Body);
1429   }
1430 
1431   /// Build a new goto statement.
1432   ///
1433   /// By default, performs semantic analysis to build the new statement.
1434   /// Subclasses may override this routine to provide different behavior.
1435   StmtResult RebuildGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
1436                              LabelDecl *Label) {
1437     return getSema().ActOnGotoStmt(GotoLoc, LabelLoc, Label);
1438   }
1439 
1440   /// Build a new indirect goto statement.
1441   ///
1442   /// By default, performs semantic analysis to build the new statement.
1443   /// Subclasses may override this routine to provide different behavior.
1444   StmtResult RebuildIndirectGotoStmt(SourceLocation GotoLoc,
1445                                      SourceLocation StarLoc,
1446                                      Expr *Target) {
1447     return getSema().ActOnIndirectGotoStmt(GotoLoc, StarLoc, Target);
1448   }
1449 
1450   /// Build a new return statement.
1451   ///
1452   /// By default, performs semantic analysis to build the new statement.
1453   /// Subclasses may override this routine to provide different behavior.
1454   StmtResult RebuildReturnStmt(SourceLocation ReturnLoc, Expr *Result) {
1455     return getSema().BuildReturnStmt(ReturnLoc, Result);
1456   }
1457 
1458   /// Build a new declaration statement.
1459   ///
1460   /// By default, performs semantic analysis to build the new statement.
1461   /// Subclasses may override this routine to provide different behavior.
1462   StmtResult RebuildDeclStmt(MutableArrayRef<Decl *> Decls,
1463                              SourceLocation StartLoc, SourceLocation EndLoc) {
1464     Sema::DeclGroupPtrTy DG = getSema().BuildDeclaratorGroup(Decls);
1465     return getSema().ActOnDeclStmt(DG, StartLoc, EndLoc);
1466   }
1467 
1468   /// Build a new inline asm statement.
1469   ///
1470   /// By default, performs semantic analysis to build the new statement.
1471   /// Subclasses may override this routine to provide different behavior.
1472   StmtResult RebuildGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
1473                                bool IsVolatile, unsigned NumOutputs,
1474                                unsigned NumInputs, IdentifierInfo **Names,
1475                                MultiExprArg Constraints, MultiExprArg Exprs,
1476                                Expr *AsmString, MultiExprArg Clobbers,
1477                                unsigned NumLabels,
1478                                SourceLocation RParenLoc) {
1479     return getSema().ActOnGCCAsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs,
1480                                      NumInputs, Names, Constraints, Exprs,
1481                                      AsmString, Clobbers, NumLabels, RParenLoc);
1482   }
1483 
1484   /// Build a new MS style inline asm statement.
1485   ///
1486   /// By default, performs semantic analysis to build the new statement.
1487   /// Subclasses may override this routine to provide different behavior.
1488   StmtResult RebuildMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
1489                               ArrayRef<Token> AsmToks,
1490                               StringRef AsmString,
1491                               unsigned NumOutputs, unsigned NumInputs,
1492                               ArrayRef<StringRef> Constraints,
1493                               ArrayRef<StringRef> Clobbers,
1494                               ArrayRef<Expr*> Exprs,
1495                               SourceLocation EndLoc) {
1496     return getSema().ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmString,
1497                                     NumOutputs, NumInputs,
1498                                     Constraints, Clobbers, Exprs, EndLoc);
1499   }
1500 
1501   /// Build a new co_return statement.
1502   ///
1503   /// By default, performs semantic analysis to build the new statement.
1504   /// Subclasses may override this routine to provide different behavior.
1505   StmtResult RebuildCoreturnStmt(SourceLocation CoreturnLoc, Expr *Result,
1506                                  bool IsImplicit) {
1507     return getSema().BuildCoreturnStmt(CoreturnLoc, Result, IsImplicit);
1508   }
1509 
1510   /// Build a new co_await expression.
1511   ///
1512   /// By default, performs semantic analysis to build the new expression.
1513   /// Subclasses may override this routine to provide different behavior.
1514   ExprResult RebuildCoawaitExpr(SourceLocation CoawaitLoc, Expr *Operand,
1515                                 UnresolvedLookupExpr *OpCoawaitLookup,
1516                                 bool IsImplicit) {
1517     // This function rebuilds a coawait-expr given its operator.
1518     // For an explicit coawait-expr, the rebuild involves the full set
1519     // of transformations performed by BuildUnresolvedCoawaitExpr(),
1520     // including calling await_transform().
1521     // For an implicit coawait-expr, we need to rebuild the "operator
1522     // coawait" but not await_transform(), so use BuildResolvedCoawaitExpr().
1523     // This mirrors how the implicit CoawaitExpr is originally created
1524     // in Sema::ActOnCoroutineBodyStart().
1525     if (IsImplicit) {
1526       ExprResult Suspend = getSema().BuildOperatorCoawaitCall(
1527           CoawaitLoc, Operand, OpCoawaitLookup);
1528       if (Suspend.isInvalid())
1529         return ExprError();
1530       return getSema().BuildResolvedCoawaitExpr(CoawaitLoc, Operand,
1531                                                 Suspend.get(), true);
1532     }
1533 
1534     return getSema().BuildUnresolvedCoawaitExpr(CoawaitLoc, Operand,
1535                                                 OpCoawaitLookup);
1536   }
1537 
1538   /// Build a new co_await expression.
1539   ///
1540   /// By default, performs semantic analysis to build the new expression.
1541   /// Subclasses may override this routine to provide different behavior.
1542   ExprResult RebuildDependentCoawaitExpr(SourceLocation CoawaitLoc,
1543                                          Expr *Result,
1544                                          UnresolvedLookupExpr *Lookup) {
1545     return getSema().BuildUnresolvedCoawaitExpr(CoawaitLoc, Result, Lookup);
1546   }
1547 
1548   /// Build a new co_yield expression.
1549   ///
1550   /// By default, performs semantic analysis to build the new expression.
1551   /// Subclasses may override this routine to provide different behavior.
1552   ExprResult RebuildCoyieldExpr(SourceLocation CoyieldLoc, Expr *Result) {
1553     return getSema().BuildCoyieldExpr(CoyieldLoc, Result);
1554   }
1555 
1556   StmtResult RebuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1557     return getSema().BuildCoroutineBodyStmt(Args);
1558   }
1559 
1560   /// Build a new Objective-C \@try statement.
1561   ///
1562   /// By default, performs semantic analysis to build the new statement.
1563   /// Subclasses may override this routine to provide different behavior.
1564   StmtResult RebuildObjCAtTryStmt(SourceLocation AtLoc,
1565                                         Stmt *TryBody,
1566                                         MultiStmtArg CatchStmts,
1567                                         Stmt *Finally) {
1568     return getSema().ActOnObjCAtTryStmt(AtLoc, TryBody, CatchStmts,
1569                                         Finally);
1570   }
1571 
1572   /// Rebuild an Objective-C exception declaration.
1573   ///
1574   /// By default, performs semantic analysis to build the new declaration.
1575   /// Subclasses may override this routine to provide different behavior.
1576   VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1577                                     TypeSourceInfo *TInfo, QualType T) {
1578     return getSema().BuildObjCExceptionDecl(TInfo, T,
1579                                             ExceptionDecl->getInnerLocStart(),
1580                                             ExceptionDecl->getLocation(),
1581                                             ExceptionDecl->getIdentifier());
1582   }
1583 
1584   /// Build a new Objective-C \@catch statement.
1585   ///
1586   /// By default, performs semantic analysis to build the new statement.
1587   /// Subclasses may override this routine to provide different behavior.
1588   StmtResult RebuildObjCAtCatchStmt(SourceLocation AtLoc,
1589                                           SourceLocation RParenLoc,
1590                                           VarDecl *Var,
1591                                           Stmt *Body) {
1592     return getSema().ActOnObjCAtCatchStmt(AtLoc, RParenLoc,
1593                                           Var, Body);
1594   }
1595 
1596   /// Build a new Objective-C \@finally statement.
1597   ///
1598   /// By default, performs semantic analysis to build the new statement.
1599   /// Subclasses may override this routine to provide different behavior.
1600   StmtResult RebuildObjCAtFinallyStmt(SourceLocation AtLoc,
1601                                             Stmt *Body) {
1602     return getSema().ActOnObjCAtFinallyStmt(AtLoc, Body);
1603   }
1604 
1605   /// Build a new Objective-C \@throw statement.
1606   ///
1607   /// By default, performs semantic analysis to build the new statement.
1608   /// Subclasses may override this routine to provide different behavior.
1609   StmtResult RebuildObjCAtThrowStmt(SourceLocation AtLoc,
1610                                           Expr *Operand) {
1611     return getSema().BuildObjCAtThrowStmt(AtLoc, Operand);
1612   }
1613 
1614   /// Build a new OpenMP Canonical loop.
1615   ///
1616   /// Ensures that the outermost loop in @p LoopStmt is wrapped by a
1617   /// OMPCanonicalLoop.
1618   StmtResult RebuildOMPCanonicalLoop(Stmt *LoopStmt) {
1619     return getSema().ActOnOpenMPCanonicalLoop(LoopStmt);
1620   }
1621 
1622   /// Build a new OpenMP executable directive.
1623   ///
1624   /// By default, performs semantic analysis to build the new statement.
1625   /// Subclasses may override this routine to provide different behavior.
1626   StmtResult RebuildOMPExecutableDirective(OpenMPDirectiveKind Kind,
1627                                            DeclarationNameInfo DirName,
1628                                            OpenMPDirectiveKind CancelRegion,
1629                                            ArrayRef<OMPClause *> Clauses,
1630                                            Stmt *AStmt, SourceLocation StartLoc,
1631                                            SourceLocation EndLoc) {
1632     return getSema().ActOnOpenMPExecutableDirective(
1633         Kind, DirName, CancelRegion, Clauses, AStmt, StartLoc, EndLoc);
1634   }
1635 
1636   /// Build a new OpenMP 'if' clause.
1637   ///
1638   /// By default, performs semantic analysis to build the new OpenMP clause.
1639   /// Subclasses may override this routine to provide different behavior.
1640   OMPClause *RebuildOMPIfClause(OpenMPDirectiveKind NameModifier,
1641                                 Expr *Condition, SourceLocation StartLoc,
1642                                 SourceLocation LParenLoc,
1643                                 SourceLocation NameModifierLoc,
1644                                 SourceLocation ColonLoc,
1645                                 SourceLocation EndLoc) {
1646     return getSema().ActOnOpenMPIfClause(NameModifier, Condition, StartLoc,
1647                                          LParenLoc, NameModifierLoc, ColonLoc,
1648                                          EndLoc);
1649   }
1650 
1651   /// Build a new OpenMP 'final' clause.
1652   ///
1653   /// By default, performs semantic analysis to build the new OpenMP clause.
1654   /// Subclasses may override this routine to provide different behavior.
1655   OMPClause *RebuildOMPFinalClause(Expr *Condition, SourceLocation StartLoc,
1656                                    SourceLocation LParenLoc,
1657                                    SourceLocation EndLoc) {
1658     return getSema().ActOnOpenMPFinalClause(Condition, StartLoc, LParenLoc,
1659                                             EndLoc);
1660   }
1661 
1662   /// Build a new OpenMP 'num_threads' clause.
1663   ///
1664   /// By default, performs semantic analysis to build the new OpenMP clause.
1665   /// Subclasses may override this routine to provide different behavior.
1666   OMPClause *RebuildOMPNumThreadsClause(Expr *NumThreads,
1667                                         SourceLocation StartLoc,
1668                                         SourceLocation LParenLoc,
1669                                         SourceLocation EndLoc) {
1670     return getSema().ActOnOpenMPNumThreadsClause(NumThreads, StartLoc,
1671                                                  LParenLoc, EndLoc);
1672   }
1673 
1674   /// Build a new OpenMP 'safelen' clause.
1675   ///
1676   /// By default, performs semantic analysis to build the new OpenMP clause.
1677   /// Subclasses may override this routine to provide different behavior.
1678   OMPClause *RebuildOMPSafelenClause(Expr *Len, SourceLocation StartLoc,
1679                                      SourceLocation LParenLoc,
1680                                      SourceLocation EndLoc) {
1681     return getSema().ActOnOpenMPSafelenClause(Len, StartLoc, LParenLoc, EndLoc);
1682   }
1683 
1684   /// Build a new OpenMP 'simdlen' clause.
1685   ///
1686   /// By default, performs semantic analysis to build the new OpenMP clause.
1687   /// Subclasses may override this routine to provide different behavior.
1688   OMPClause *RebuildOMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
1689                                      SourceLocation LParenLoc,
1690                                      SourceLocation EndLoc) {
1691     return getSema().ActOnOpenMPSimdlenClause(Len, StartLoc, LParenLoc, EndLoc);
1692   }
1693 
1694   OMPClause *RebuildOMPSizesClause(ArrayRef<Expr *> Sizes,
1695                                    SourceLocation StartLoc,
1696                                    SourceLocation LParenLoc,
1697                                    SourceLocation EndLoc) {
1698     return getSema().ActOnOpenMPSizesClause(Sizes, StartLoc, LParenLoc, EndLoc);
1699   }
1700 
1701   /// Build a new OpenMP 'full' clause.
1702   OMPClause *RebuildOMPFullClause(SourceLocation StartLoc,
1703                                   SourceLocation EndLoc) {
1704     return getSema().ActOnOpenMPFullClause(StartLoc, EndLoc);
1705   }
1706 
1707   /// Build a new OpenMP 'partial' clause.
1708   OMPClause *RebuildOMPPartialClause(Expr *Factor, SourceLocation StartLoc,
1709                                      SourceLocation LParenLoc,
1710                                      SourceLocation EndLoc) {
1711     return getSema().ActOnOpenMPPartialClause(Factor, StartLoc, LParenLoc,
1712                                               EndLoc);
1713   }
1714 
1715   /// Build a new OpenMP 'allocator' clause.
1716   ///
1717   /// By default, performs semantic analysis to build the new OpenMP clause.
1718   /// Subclasses may override this routine to provide different behavior.
1719   OMPClause *RebuildOMPAllocatorClause(Expr *A, SourceLocation StartLoc,
1720                                        SourceLocation LParenLoc,
1721                                        SourceLocation EndLoc) {
1722     return getSema().ActOnOpenMPAllocatorClause(A, StartLoc, LParenLoc, EndLoc);
1723   }
1724 
1725   /// Build a new OpenMP 'collapse' clause.
1726   ///
1727   /// By default, performs semantic analysis to build the new OpenMP clause.
1728   /// Subclasses may override this routine to provide different behavior.
1729   OMPClause *RebuildOMPCollapseClause(Expr *Num, SourceLocation StartLoc,
1730                                       SourceLocation LParenLoc,
1731                                       SourceLocation EndLoc) {
1732     return getSema().ActOnOpenMPCollapseClause(Num, StartLoc, LParenLoc,
1733                                                EndLoc);
1734   }
1735 
1736   /// Build a new OpenMP 'default' clause.
1737   ///
1738   /// By default, performs semantic analysis to build the new OpenMP clause.
1739   /// Subclasses may override this routine to provide different behavior.
1740   OMPClause *RebuildOMPDefaultClause(DefaultKind Kind, SourceLocation KindKwLoc,
1741                                      SourceLocation StartLoc,
1742                                      SourceLocation LParenLoc,
1743                                      SourceLocation EndLoc) {
1744     return getSema().ActOnOpenMPDefaultClause(Kind, KindKwLoc,
1745                                               StartLoc, LParenLoc, EndLoc);
1746   }
1747 
1748   /// Build a new OpenMP 'proc_bind' clause.
1749   ///
1750   /// By default, performs semantic analysis to build the new OpenMP clause.
1751   /// Subclasses may override this routine to provide different behavior.
1752   OMPClause *RebuildOMPProcBindClause(ProcBindKind Kind,
1753                                       SourceLocation KindKwLoc,
1754                                       SourceLocation StartLoc,
1755                                       SourceLocation LParenLoc,
1756                                       SourceLocation EndLoc) {
1757     return getSema().ActOnOpenMPProcBindClause(Kind, KindKwLoc,
1758                                                StartLoc, LParenLoc, EndLoc);
1759   }
1760 
1761   /// Build a new OpenMP 'schedule' clause.
1762   ///
1763   /// By default, performs semantic analysis to build the new OpenMP clause.
1764   /// Subclasses may override this routine to provide different behavior.
1765   OMPClause *RebuildOMPScheduleClause(
1766       OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
1767       OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
1768       SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
1769       SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
1770     return getSema().ActOnOpenMPScheduleClause(
1771         M1, M2, Kind, ChunkSize, StartLoc, LParenLoc, M1Loc, M2Loc, KindLoc,
1772         CommaLoc, EndLoc);
1773   }
1774 
1775   /// Build a new OpenMP 'ordered' clause.
1776   ///
1777   /// By default, performs semantic analysis to build the new OpenMP clause.
1778   /// Subclasses may override this routine to provide different behavior.
1779   OMPClause *RebuildOMPOrderedClause(SourceLocation StartLoc,
1780                                      SourceLocation EndLoc,
1781                                      SourceLocation LParenLoc, Expr *Num) {
1782     return getSema().ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Num);
1783   }
1784 
1785   /// Build a new OpenMP 'private' clause.
1786   ///
1787   /// By default, performs semantic analysis to build the new OpenMP clause.
1788   /// Subclasses may override this routine to provide different behavior.
1789   OMPClause *RebuildOMPPrivateClause(ArrayRef<Expr *> VarList,
1790                                      SourceLocation StartLoc,
1791                                      SourceLocation LParenLoc,
1792                                      SourceLocation EndLoc) {
1793     return getSema().ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc,
1794                                               EndLoc);
1795   }
1796 
1797   /// Build a new OpenMP 'firstprivate' clause.
1798   ///
1799   /// By default, performs semantic analysis to build the new OpenMP clause.
1800   /// Subclasses may override this routine to provide different behavior.
1801   OMPClause *RebuildOMPFirstprivateClause(ArrayRef<Expr *> VarList,
1802                                           SourceLocation StartLoc,
1803                                           SourceLocation LParenLoc,
1804                                           SourceLocation EndLoc) {
1805     return getSema().ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc,
1806                                                    EndLoc);
1807   }
1808 
1809   /// Build a new OpenMP 'lastprivate' clause.
1810   ///
1811   /// By default, performs semantic analysis to build the new OpenMP clause.
1812   /// Subclasses may override this routine to provide different behavior.
1813   OMPClause *RebuildOMPLastprivateClause(ArrayRef<Expr *> VarList,
1814                                          OpenMPLastprivateModifier LPKind,
1815                                          SourceLocation LPKindLoc,
1816                                          SourceLocation ColonLoc,
1817                                          SourceLocation StartLoc,
1818                                          SourceLocation LParenLoc,
1819                                          SourceLocation EndLoc) {
1820     return getSema().ActOnOpenMPLastprivateClause(
1821         VarList, LPKind, LPKindLoc, ColonLoc, StartLoc, LParenLoc, EndLoc);
1822   }
1823 
1824   /// Build a new OpenMP 'shared' clause.
1825   ///
1826   /// By default, performs semantic analysis to build the new OpenMP clause.
1827   /// Subclasses may override this routine to provide different behavior.
1828   OMPClause *RebuildOMPSharedClause(ArrayRef<Expr *> VarList,
1829                                     SourceLocation StartLoc,
1830                                     SourceLocation LParenLoc,
1831                                     SourceLocation EndLoc) {
1832     return getSema().ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc,
1833                                              EndLoc);
1834   }
1835 
1836   /// Build a new OpenMP 'reduction' clause.
1837   ///
1838   /// By default, performs semantic analysis to build the new statement.
1839   /// Subclasses may override this routine to provide different behavior.
1840   OMPClause *RebuildOMPReductionClause(
1841       ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier,
1842       SourceLocation StartLoc, SourceLocation LParenLoc,
1843       SourceLocation ModifierLoc, SourceLocation ColonLoc,
1844       SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
1845       const DeclarationNameInfo &ReductionId,
1846       ArrayRef<Expr *> UnresolvedReductions) {
1847     return getSema().ActOnOpenMPReductionClause(
1848         VarList, Modifier, StartLoc, LParenLoc, ModifierLoc, ColonLoc, EndLoc,
1849         ReductionIdScopeSpec, ReductionId, UnresolvedReductions);
1850   }
1851 
1852   /// Build a new OpenMP 'task_reduction' clause.
1853   ///
1854   /// By default, performs semantic analysis to build the new statement.
1855   /// Subclasses may override this routine to provide different behavior.
1856   OMPClause *RebuildOMPTaskReductionClause(
1857       ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1858       SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
1859       CXXScopeSpec &ReductionIdScopeSpec,
1860       const DeclarationNameInfo &ReductionId,
1861       ArrayRef<Expr *> UnresolvedReductions) {
1862     return getSema().ActOnOpenMPTaskReductionClause(
1863         VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1864         ReductionId, UnresolvedReductions);
1865   }
1866 
1867   /// Build a new OpenMP 'in_reduction' clause.
1868   ///
1869   /// By default, performs semantic analysis to build the new statement.
1870   /// Subclasses may override this routine to provide different behavior.
1871   OMPClause *
1872   RebuildOMPInReductionClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1873                               SourceLocation LParenLoc, SourceLocation ColonLoc,
1874                               SourceLocation EndLoc,
1875                               CXXScopeSpec &ReductionIdScopeSpec,
1876                               const DeclarationNameInfo &ReductionId,
1877                               ArrayRef<Expr *> UnresolvedReductions) {
1878     return getSema().ActOnOpenMPInReductionClause(
1879         VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1880         ReductionId, UnresolvedReductions);
1881   }
1882 
1883   /// Build a new OpenMP 'linear' clause.
1884   ///
1885   /// By default, performs semantic analysis to build the new OpenMP clause.
1886   /// Subclasses may override this routine to provide different behavior.
1887   OMPClause *RebuildOMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
1888                                     SourceLocation StartLoc,
1889                                     SourceLocation LParenLoc,
1890                                     OpenMPLinearClauseKind Modifier,
1891                                     SourceLocation ModifierLoc,
1892                                     SourceLocation ColonLoc,
1893                                     SourceLocation EndLoc) {
1894     return getSema().ActOnOpenMPLinearClause(VarList, Step, StartLoc, LParenLoc,
1895                                              Modifier, ModifierLoc, ColonLoc,
1896                                              EndLoc);
1897   }
1898 
1899   /// Build a new OpenMP 'aligned' clause.
1900   ///
1901   /// By default, performs semantic analysis to build the new OpenMP clause.
1902   /// Subclasses may override this routine to provide different behavior.
1903   OMPClause *RebuildOMPAlignedClause(ArrayRef<Expr *> VarList, Expr *Alignment,
1904                                      SourceLocation StartLoc,
1905                                      SourceLocation LParenLoc,
1906                                      SourceLocation ColonLoc,
1907                                      SourceLocation EndLoc) {
1908     return getSema().ActOnOpenMPAlignedClause(VarList, Alignment, StartLoc,
1909                                               LParenLoc, ColonLoc, EndLoc);
1910   }
1911 
1912   /// Build a new OpenMP 'copyin' clause.
1913   ///
1914   /// By default, performs semantic analysis to build the new OpenMP clause.
1915   /// Subclasses may override this routine to provide different behavior.
1916   OMPClause *RebuildOMPCopyinClause(ArrayRef<Expr *> VarList,
1917                                     SourceLocation StartLoc,
1918                                     SourceLocation LParenLoc,
1919                                     SourceLocation EndLoc) {
1920     return getSema().ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc,
1921                                              EndLoc);
1922   }
1923 
1924   /// Build a new OpenMP 'copyprivate' clause.
1925   ///
1926   /// By default, performs semantic analysis to build the new OpenMP clause.
1927   /// Subclasses may override this routine to provide different behavior.
1928   OMPClause *RebuildOMPCopyprivateClause(ArrayRef<Expr *> VarList,
1929                                          SourceLocation StartLoc,
1930                                          SourceLocation LParenLoc,
1931                                          SourceLocation EndLoc) {
1932     return getSema().ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc,
1933                                                   EndLoc);
1934   }
1935 
1936   /// Build a new OpenMP 'flush' pseudo clause.
1937   ///
1938   /// By default, performs semantic analysis to build the new OpenMP clause.
1939   /// Subclasses may override this routine to provide different behavior.
1940   OMPClause *RebuildOMPFlushClause(ArrayRef<Expr *> VarList,
1941                                    SourceLocation StartLoc,
1942                                    SourceLocation LParenLoc,
1943                                    SourceLocation EndLoc) {
1944     return getSema().ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc,
1945                                             EndLoc);
1946   }
1947 
1948   /// Build a new OpenMP 'depobj' pseudo clause.
1949   ///
1950   /// By default, performs semantic analysis to build the new OpenMP clause.
1951   /// Subclasses may override this routine to provide different behavior.
1952   OMPClause *RebuildOMPDepobjClause(Expr *Depobj, SourceLocation StartLoc,
1953                                     SourceLocation LParenLoc,
1954                                     SourceLocation EndLoc) {
1955     return getSema().ActOnOpenMPDepobjClause(Depobj, StartLoc, LParenLoc,
1956                                              EndLoc);
1957   }
1958 
1959   /// Build a new OpenMP 'depend' pseudo clause.
1960   ///
1961   /// By default, performs semantic analysis to build the new OpenMP clause.
1962   /// Subclasses may override this routine to provide different behavior.
1963   OMPClause *RebuildOMPDependClause(OMPDependClause::DependDataTy Data,
1964                                     Expr *DepModifier, ArrayRef<Expr *> VarList,
1965                                     SourceLocation StartLoc,
1966                                     SourceLocation LParenLoc,
1967                                     SourceLocation EndLoc) {
1968     return getSema().ActOnOpenMPDependClause(Data, DepModifier, VarList,
1969                                              StartLoc, LParenLoc, EndLoc);
1970   }
1971 
1972   /// Build a new OpenMP 'device' clause.
1973   ///
1974   /// By default, performs semantic analysis to build the new statement.
1975   /// Subclasses may override this routine to provide different behavior.
1976   OMPClause *RebuildOMPDeviceClause(OpenMPDeviceClauseModifier Modifier,
1977                                     Expr *Device, SourceLocation StartLoc,
1978                                     SourceLocation LParenLoc,
1979                                     SourceLocation ModifierLoc,
1980                                     SourceLocation EndLoc) {
1981     return getSema().ActOnOpenMPDeviceClause(Modifier, Device, StartLoc,
1982                                              LParenLoc, ModifierLoc, EndLoc);
1983   }
1984 
1985   /// Build a new OpenMP 'map' clause.
1986   ///
1987   /// By default, performs semantic analysis to build the new OpenMP clause.
1988   /// Subclasses may override this routine to provide different behavior.
1989   OMPClause *RebuildOMPMapClause(
1990       Expr *IteratorModifier, ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
1991       ArrayRef<SourceLocation> MapTypeModifiersLoc,
1992       CXXScopeSpec MapperIdScopeSpec, DeclarationNameInfo MapperId,
1993       OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
1994       SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
1995       const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
1996     return getSema().ActOnOpenMPMapClause(
1997         IteratorModifier, MapTypeModifiers, MapTypeModifiersLoc,
1998         MapperIdScopeSpec, MapperId, MapType, IsMapTypeImplicit, MapLoc,
1999         ColonLoc, VarList, Locs,
2000         /*NoDiagnose=*/false, UnresolvedMappers);
2001   }
2002 
2003   /// Build a new OpenMP 'allocate' clause.
2004   ///
2005   /// By default, performs semantic analysis to build the new OpenMP clause.
2006   /// Subclasses may override this routine to provide different behavior.
2007   OMPClause *RebuildOMPAllocateClause(Expr *Allocate, ArrayRef<Expr *> VarList,
2008                                       SourceLocation StartLoc,
2009                                       SourceLocation LParenLoc,
2010                                       SourceLocation ColonLoc,
2011                                       SourceLocation EndLoc) {
2012     return getSema().ActOnOpenMPAllocateClause(Allocate, VarList, StartLoc,
2013                                                LParenLoc, ColonLoc, EndLoc);
2014   }
2015 
2016   /// Build a new OpenMP 'num_teams' clause.
2017   ///
2018   /// By default, performs semantic analysis to build the new statement.
2019   /// Subclasses may override this routine to provide different behavior.
2020   OMPClause *RebuildOMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
2021                                       SourceLocation LParenLoc,
2022                                       SourceLocation EndLoc) {
2023     return getSema().ActOnOpenMPNumTeamsClause(NumTeams, StartLoc, LParenLoc,
2024                                                EndLoc);
2025   }
2026 
2027   /// Build a new OpenMP 'thread_limit' clause.
2028   ///
2029   /// By default, performs semantic analysis to build the new statement.
2030   /// Subclasses may override this routine to provide different behavior.
2031   OMPClause *RebuildOMPThreadLimitClause(Expr *ThreadLimit,
2032                                          SourceLocation StartLoc,
2033                                          SourceLocation LParenLoc,
2034                                          SourceLocation EndLoc) {
2035     return getSema().ActOnOpenMPThreadLimitClause(ThreadLimit, StartLoc,
2036                                                   LParenLoc, EndLoc);
2037   }
2038 
2039   /// Build a new OpenMP 'priority' clause.
2040   ///
2041   /// By default, performs semantic analysis to build the new statement.
2042   /// Subclasses may override this routine to provide different behavior.
2043   OMPClause *RebuildOMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
2044                                       SourceLocation LParenLoc,
2045                                       SourceLocation EndLoc) {
2046     return getSema().ActOnOpenMPPriorityClause(Priority, StartLoc, LParenLoc,
2047                                                EndLoc);
2048   }
2049 
2050   /// Build a new OpenMP 'grainsize' clause.
2051   ///
2052   /// By default, performs semantic analysis to build the new statement.
2053   /// Subclasses may override this routine to provide different behavior.
2054   OMPClause *RebuildOMPGrainsizeClause(OpenMPGrainsizeClauseModifier Modifier,
2055                                        Expr *Device, SourceLocation StartLoc,
2056                                        SourceLocation LParenLoc,
2057                                        SourceLocation ModifierLoc,
2058                                        SourceLocation EndLoc) {
2059     return getSema().ActOnOpenMPGrainsizeClause(Modifier, Device, StartLoc,
2060                                                 LParenLoc, ModifierLoc, EndLoc);
2061   }
2062 
2063   /// Build a new OpenMP 'num_tasks' clause.
2064   ///
2065   /// By default, performs semantic analysis to build the new statement.
2066   /// Subclasses may override this routine to provide different behavior.
2067   OMPClause *RebuildOMPNumTasksClause(OpenMPNumTasksClauseModifier Modifier,
2068                                       Expr *NumTasks, SourceLocation StartLoc,
2069                                       SourceLocation LParenLoc,
2070                                       SourceLocation ModifierLoc,
2071                                       SourceLocation EndLoc) {
2072     return getSema().ActOnOpenMPNumTasksClause(Modifier, NumTasks, StartLoc,
2073                                                LParenLoc, ModifierLoc, EndLoc);
2074   }
2075 
2076   /// Build a new OpenMP 'hint' clause.
2077   ///
2078   /// By default, performs semantic analysis to build the new statement.
2079   /// Subclasses may override this routine to provide different behavior.
2080   OMPClause *RebuildOMPHintClause(Expr *Hint, SourceLocation StartLoc,
2081                                   SourceLocation LParenLoc,
2082                                   SourceLocation EndLoc) {
2083     return getSema().ActOnOpenMPHintClause(Hint, StartLoc, LParenLoc, EndLoc);
2084   }
2085 
2086   /// Build a new OpenMP 'detach' clause.
2087   ///
2088   /// By default, performs semantic analysis to build the new statement.
2089   /// Subclasses may override this routine to provide different behavior.
2090   OMPClause *RebuildOMPDetachClause(Expr *Evt, SourceLocation StartLoc,
2091                                     SourceLocation LParenLoc,
2092                                     SourceLocation EndLoc) {
2093     return getSema().ActOnOpenMPDetachClause(Evt, StartLoc, LParenLoc, EndLoc);
2094   }
2095 
2096   /// Build a new OpenMP 'dist_schedule' clause.
2097   ///
2098   /// By default, performs semantic analysis to build the new OpenMP clause.
2099   /// Subclasses may override this routine to provide different behavior.
2100   OMPClause *
2101   RebuildOMPDistScheduleClause(OpenMPDistScheduleClauseKind Kind,
2102                                Expr *ChunkSize, SourceLocation StartLoc,
2103                                SourceLocation LParenLoc, SourceLocation KindLoc,
2104                                SourceLocation CommaLoc, SourceLocation EndLoc) {
2105     return getSema().ActOnOpenMPDistScheduleClause(
2106         Kind, ChunkSize, StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc);
2107   }
2108 
2109   /// Build a new OpenMP 'to' clause.
2110   ///
2111   /// By default, performs semantic analysis to build the new statement.
2112   /// Subclasses may override this routine to provide different behavior.
2113   OMPClause *
2114   RebuildOMPToClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
2115                      ArrayRef<SourceLocation> MotionModifiersLoc,
2116                      CXXScopeSpec &MapperIdScopeSpec,
2117                      DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
2118                      ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
2119                      ArrayRef<Expr *> UnresolvedMappers) {
2120     return getSema().ActOnOpenMPToClause(MotionModifiers, MotionModifiersLoc,
2121                                          MapperIdScopeSpec, MapperId, ColonLoc,
2122                                          VarList, Locs, UnresolvedMappers);
2123   }
2124 
2125   /// Build a new OpenMP 'from' clause.
2126   ///
2127   /// By default, performs semantic analysis to build the new statement.
2128   /// Subclasses may override this routine to provide different behavior.
2129   OMPClause *
2130   RebuildOMPFromClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
2131                        ArrayRef<SourceLocation> MotionModifiersLoc,
2132                        CXXScopeSpec &MapperIdScopeSpec,
2133                        DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
2134                        ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
2135                        ArrayRef<Expr *> UnresolvedMappers) {
2136     return getSema().ActOnOpenMPFromClause(
2137         MotionModifiers, MotionModifiersLoc, MapperIdScopeSpec, MapperId,
2138         ColonLoc, VarList, Locs, UnresolvedMappers);
2139   }
2140 
2141   /// Build a new OpenMP 'use_device_ptr' clause.
2142   ///
2143   /// By default, performs semantic analysis to build the new OpenMP clause.
2144   /// Subclasses may override this routine to provide different behavior.
2145   OMPClause *RebuildOMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
2146                                           const OMPVarListLocTy &Locs) {
2147     return getSema().ActOnOpenMPUseDevicePtrClause(VarList, Locs);
2148   }
2149 
2150   /// Build a new OpenMP 'use_device_addr' clause.
2151   ///
2152   /// By default, performs semantic analysis to build the new OpenMP clause.
2153   /// Subclasses may override this routine to provide different behavior.
2154   OMPClause *RebuildOMPUseDeviceAddrClause(ArrayRef<Expr *> VarList,
2155                                            const OMPVarListLocTy &Locs) {
2156     return getSema().ActOnOpenMPUseDeviceAddrClause(VarList, Locs);
2157   }
2158 
2159   /// Build a new OpenMP 'is_device_ptr' clause.
2160   ///
2161   /// By default, performs semantic analysis to build the new OpenMP clause.
2162   /// Subclasses may override this routine to provide different behavior.
2163   OMPClause *RebuildOMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
2164                                          const OMPVarListLocTy &Locs) {
2165     return getSema().ActOnOpenMPIsDevicePtrClause(VarList, Locs);
2166   }
2167 
2168   /// Build a new OpenMP 'has_device_addr' clause.
2169   ///
2170   /// By default, performs semantic analysis to build the new OpenMP clause.
2171   /// Subclasses may override this routine to provide different behavior.
2172   OMPClause *RebuildOMPHasDeviceAddrClause(ArrayRef<Expr *> VarList,
2173                                            const OMPVarListLocTy &Locs) {
2174     return getSema().ActOnOpenMPHasDeviceAddrClause(VarList, Locs);
2175   }
2176 
2177   /// Build a new OpenMP 'defaultmap' clause.
2178   ///
2179   /// By default, performs semantic analysis to build the new OpenMP clause.
2180   /// Subclasses may override this routine to provide different behavior.
2181   OMPClause *RebuildOMPDefaultmapClause(OpenMPDefaultmapClauseModifier M,
2182                                         OpenMPDefaultmapClauseKind Kind,
2183                                         SourceLocation StartLoc,
2184                                         SourceLocation LParenLoc,
2185                                         SourceLocation MLoc,
2186                                         SourceLocation KindLoc,
2187                                         SourceLocation EndLoc) {
2188     return getSema().ActOnOpenMPDefaultmapClause(M, Kind, StartLoc, LParenLoc,
2189                                                  MLoc, KindLoc, EndLoc);
2190   }
2191 
2192   /// Build a new OpenMP 'nontemporal' clause.
2193   ///
2194   /// By default, performs semantic analysis to build the new OpenMP clause.
2195   /// Subclasses may override this routine to provide different behavior.
2196   OMPClause *RebuildOMPNontemporalClause(ArrayRef<Expr *> VarList,
2197                                          SourceLocation StartLoc,
2198                                          SourceLocation LParenLoc,
2199                                          SourceLocation EndLoc) {
2200     return getSema().ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc,
2201                                                   EndLoc);
2202   }
2203 
2204   /// Build a new OpenMP 'inclusive' clause.
2205   ///
2206   /// By default, performs semantic analysis to build the new OpenMP clause.
2207   /// Subclasses may override this routine to provide different behavior.
2208   OMPClause *RebuildOMPInclusiveClause(ArrayRef<Expr *> VarList,
2209                                        SourceLocation StartLoc,
2210                                        SourceLocation LParenLoc,
2211                                        SourceLocation EndLoc) {
2212     return getSema().ActOnOpenMPInclusiveClause(VarList, StartLoc, LParenLoc,
2213                                                 EndLoc);
2214   }
2215 
2216   /// Build a new OpenMP 'exclusive' clause.
2217   ///
2218   /// By default, performs semantic analysis to build the new OpenMP clause.
2219   /// Subclasses may override this routine to provide different behavior.
2220   OMPClause *RebuildOMPExclusiveClause(ArrayRef<Expr *> VarList,
2221                                        SourceLocation StartLoc,
2222                                        SourceLocation LParenLoc,
2223                                        SourceLocation EndLoc) {
2224     return getSema().ActOnOpenMPExclusiveClause(VarList, StartLoc, LParenLoc,
2225                                                 EndLoc);
2226   }
2227 
2228   /// Build a new OpenMP 'uses_allocators' clause.
2229   ///
2230   /// By default, performs semantic analysis to build the new OpenMP clause.
2231   /// Subclasses may override this routine to provide different behavior.
2232   OMPClause *RebuildOMPUsesAllocatorsClause(
2233       ArrayRef<Sema::UsesAllocatorsData> Data, SourceLocation StartLoc,
2234       SourceLocation LParenLoc, SourceLocation EndLoc) {
2235     return getSema().ActOnOpenMPUsesAllocatorClause(StartLoc, LParenLoc, EndLoc,
2236                                                     Data);
2237   }
2238 
2239   /// Build a new OpenMP 'affinity' clause.
2240   ///
2241   /// By default, performs semantic analysis to build the new OpenMP clause.
2242   /// Subclasses may override this routine to provide different behavior.
2243   OMPClause *RebuildOMPAffinityClause(SourceLocation StartLoc,
2244                                       SourceLocation LParenLoc,
2245                                       SourceLocation ColonLoc,
2246                                       SourceLocation EndLoc, Expr *Modifier,
2247                                       ArrayRef<Expr *> Locators) {
2248     return getSema().ActOnOpenMPAffinityClause(StartLoc, LParenLoc, ColonLoc,
2249                                                EndLoc, Modifier, Locators);
2250   }
2251 
2252   /// Build a new OpenMP 'order' clause.
2253   ///
2254   /// By default, performs semantic analysis to build the new OpenMP clause.
2255   /// Subclasses may override this routine to provide different behavior.
2256   OMPClause *RebuildOMPOrderClause(
2257       OpenMPOrderClauseKind Kind, SourceLocation KindKwLoc,
2258       SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc,
2259       OpenMPOrderClauseModifier Modifier, SourceLocation ModifierKwLoc) {
2260     return getSema().ActOnOpenMPOrderClause(Modifier, Kind, StartLoc, LParenLoc,
2261                                             ModifierKwLoc, KindKwLoc, EndLoc);
2262   }
2263 
2264   /// Build a new OpenMP 'init' clause.
2265   ///
2266   /// By default, performs semantic analysis to build the new OpenMP clause.
2267   /// Subclasses may override this routine to provide different behavior.
2268   OMPClause *RebuildOMPInitClause(Expr *InteropVar, OMPInteropInfo &InteropInfo,
2269                                   SourceLocation StartLoc,
2270                                   SourceLocation LParenLoc,
2271                                   SourceLocation VarLoc,
2272                                   SourceLocation EndLoc) {
2273     return getSema().ActOnOpenMPInitClause(InteropVar, InteropInfo, StartLoc,
2274                                            LParenLoc, VarLoc, EndLoc);
2275   }
2276 
2277   /// Build a new OpenMP 'use' clause.
2278   ///
2279   /// By default, performs semantic analysis to build the new OpenMP clause.
2280   /// Subclasses may override this routine to provide different behavior.
2281   OMPClause *RebuildOMPUseClause(Expr *InteropVar, SourceLocation StartLoc,
2282                                  SourceLocation LParenLoc,
2283                                  SourceLocation VarLoc, SourceLocation EndLoc) {
2284     return getSema().ActOnOpenMPUseClause(InteropVar, StartLoc, LParenLoc,
2285                                           VarLoc, EndLoc);
2286   }
2287 
2288   /// Build a new OpenMP 'destroy' clause.
2289   ///
2290   /// By default, performs semantic analysis to build the new OpenMP clause.
2291   /// Subclasses may override this routine to provide different behavior.
2292   OMPClause *RebuildOMPDestroyClause(Expr *InteropVar, SourceLocation StartLoc,
2293                                      SourceLocation LParenLoc,
2294                                      SourceLocation VarLoc,
2295                                      SourceLocation EndLoc) {
2296     return getSema().ActOnOpenMPDestroyClause(InteropVar, StartLoc, LParenLoc,
2297                                               VarLoc, EndLoc);
2298   }
2299 
2300   /// Build a new OpenMP 'novariants' clause.
2301   ///
2302   /// By default, performs semantic analysis to build the new OpenMP clause.
2303   /// Subclasses may override this routine to provide different behavior.
2304   OMPClause *RebuildOMPNovariantsClause(Expr *Condition,
2305                                         SourceLocation StartLoc,
2306                                         SourceLocation LParenLoc,
2307                                         SourceLocation EndLoc) {
2308     return getSema().ActOnOpenMPNovariantsClause(Condition, StartLoc, LParenLoc,
2309                                                  EndLoc);
2310   }
2311 
2312   /// Build a new OpenMP 'nocontext' clause.
2313   ///
2314   /// By default, performs semantic analysis to build the new OpenMP clause.
2315   /// Subclasses may override this routine to provide different behavior.
2316   OMPClause *RebuildOMPNocontextClause(Expr *Condition, SourceLocation StartLoc,
2317                                        SourceLocation LParenLoc,
2318                                        SourceLocation EndLoc) {
2319     return getSema().ActOnOpenMPNocontextClause(Condition, StartLoc, LParenLoc,
2320                                                 EndLoc);
2321   }
2322 
2323   /// Build a new OpenMP 'filter' clause.
2324   ///
2325   /// By default, performs semantic analysis to build the new OpenMP clause.
2326   /// Subclasses may override this routine to provide different behavior.
2327   OMPClause *RebuildOMPFilterClause(Expr *ThreadID, SourceLocation StartLoc,
2328                                     SourceLocation LParenLoc,
2329                                     SourceLocation EndLoc) {
2330     return getSema().ActOnOpenMPFilterClause(ThreadID, StartLoc, LParenLoc,
2331                                              EndLoc);
2332   }
2333 
2334   /// Build a new OpenMP 'bind' clause.
2335   ///
2336   /// By default, performs semantic analysis to build the new OpenMP clause.
2337   /// Subclasses may override this routine to provide different behavior.
2338   OMPClause *RebuildOMPBindClause(OpenMPBindClauseKind Kind,
2339                                   SourceLocation KindLoc,
2340                                   SourceLocation StartLoc,
2341                                   SourceLocation LParenLoc,
2342                                   SourceLocation EndLoc) {
2343     return getSema().ActOnOpenMPBindClause(Kind, KindLoc, StartLoc, LParenLoc,
2344                                            EndLoc);
2345   }
2346 
2347   /// Build a new OpenMP 'ompx_dyn_cgroup_mem' clause.
2348   ///
2349   /// By default, performs semantic analysis to build the new OpenMP clause.
2350   /// Subclasses may override this routine to provide different behavior.
2351   OMPClause *RebuildOMPXDynCGroupMemClause(Expr *Size, SourceLocation StartLoc,
2352                                            SourceLocation LParenLoc,
2353                                            SourceLocation EndLoc) {
2354     return getSema().ActOnOpenMPXDynCGroupMemClause(Size, StartLoc, LParenLoc,
2355                                                     EndLoc);
2356   }
2357 
2358   /// Build a new OpenMP 'align' clause.
2359   ///
2360   /// By default, performs semantic analysis to build the new OpenMP clause.
2361   /// Subclasses may override this routine to provide different behavior.
2362   OMPClause *RebuildOMPAlignClause(Expr *A, SourceLocation StartLoc,
2363                                    SourceLocation LParenLoc,
2364                                    SourceLocation EndLoc) {
2365     return getSema().ActOnOpenMPAlignClause(A, StartLoc, LParenLoc, EndLoc);
2366   }
2367 
2368   /// Build a new OpenMP 'at' clause.
2369   ///
2370   /// By default, performs semantic analysis to build the new OpenMP clause.
2371   /// Subclasses may override this routine to provide different behavior.
2372   OMPClause *RebuildOMPAtClause(OpenMPAtClauseKind Kind, SourceLocation KwLoc,
2373                                 SourceLocation StartLoc,
2374                                 SourceLocation LParenLoc,
2375                                 SourceLocation EndLoc) {
2376     return getSema().ActOnOpenMPAtClause(Kind, KwLoc, StartLoc, LParenLoc,
2377                                          EndLoc);
2378   }
2379 
2380   /// Build a new OpenMP 'severity' clause.
2381   ///
2382   /// By default, performs semantic analysis to build the new OpenMP clause.
2383   /// Subclasses may override this routine to provide different behavior.
2384   OMPClause *RebuildOMPSeverityClause(OpenMPSeverityClauseKind Kind,
2385                                       SourceLocation KwLoc,
2386                                       SourceLocation StartLoc,
2387                                       SourceLocation LParenLoc,
2388                                       SourceLocation EndLoc) {
2389     return getSema().ActOnOpenMPSeverityClause(Kind, KwLoc, StartLoc, LParenLoc,
2390                                                EndLoc);
2391   }
2392 
2393   /// Build a new OpenMP 'message' clause.
2394   ///
2395   /// By default, performs semantic analysis to build the new OpenMP clause.
2396   /// Subclasses may override this routine to provide different behavior.
2397   OMPClause *RebuildOMPMessageClause(Expr *MS, SourceLocation StartLoc,
2398                                      SourceLocation LParenLoc,
2399                                      SourceLocation EndLoc) {
2400     return getSema().ActOnOpenMPMessageClause(MS, StartLoc, LParenLoc, EndLoc);
2401   }
2402 
2403   /// Rebuild the operand to an Objective-C \@synchronized statement.
2404   ///
2405   /// By default, performs semantic analysis to build the new statement.
2406   /// Subclasses may override this routine to provide different behavior.
2407   ExprResult RebuildObjCAtSynchronizedOperand(SourceLocation atLoc,
2408                                               Expr *object) {
2409     return getSema().ActOnObjCAtSynchronizedOperand(atLoc, object);
2410   }
2411 
2412   /// Build a new Objective-C \@synchronized statement.
2413   ///
2414   /// By default, performs semantic analysis to build the new statement.
2415   /// Subclasses may override this routine to provide different behavior.
2416   StmtResult RebuildObjCAtSynchronizedStmt(SourceLocation AtLoc,
2417                                            Expr *Object, Stmt *Body) {
2418     return getSema().ActOnObjCAtSynchronizedStmt(AtLoc, Object, Body);
2419   }
2420 
2421   /// Build a new Objective-C \@autoreleasepool statement.
2422   ///
2423   /// By default, performs semantic analysis to build the new statement.
2424   /// Subclasses may override this routine to provide different behavior.
2425   StmtResult RebuildObjCAutoreleasePoolStmt(SourceLocation AtLoc,
2426                                             Stmt *Body) {
2427     return getSema().ActOnObjCAutoreleasePoolStmt(AtLoc, Body);
2428   }
2429 
2430   /// Build a new Objective-C fast enumeration statement.
2431   ///
2432   /// By default, performs semantic analysis to build the new statement.
2433   /// Subclasses may override this routine to provide different behavior.
2434   StmtResult RebuildObjCForCollectionStmt(SourceLocation ForLoc,
2435                                           Stmt *Element,
2436                                           Expr *Collection,
2437                                           SourceLocation RParenLoc,
2438                                           Stmt *Body) {
2439     StmtResult ForEachStmt = getSema().ActOnObjCForCollectionStmt(ForLoc,
2440                                                 Element,
2441                                                 Collection,
2442                                                 RParenLoc);
2443     if (ForEachStmt.isInvalid())
2444       return StmtError();
2445 
2446     return getSema().FinishObjCForCollectionStmt(ForEachStmt.get(), Body);
2447   }
2448 
2449   /// Build a new C++ exception declaration.
2450   ///
2451   /// By default, performs semantic analysis to build the new decaration.
2452   /// Subclasses may override this routine to provide different behavior.
2453   VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
2454                                 TypeSourceInfo *Declarator,
2455                                 SourceLocation StartLoc,
2456                                 SourceLocation IdLoc,
2457                                 IdentifierInfo *Id) {
2458     VarDecl *Var = getSema().BuildExceptionDeclaration(nullptr, Declarator,
2459                                                        StartLoc, IdLoc, Id);
2460     if (Var)
2461       getSema().CurContext->addDecl(Var);
2462     return Var;
2463   }
2464 
2465   /// Build a new C++ catch statement.
2466   ///
2467   /// By default, performs semantic analysis to build the new statement.
2468   /// Subclasses may override this routine to provide different behavior.
2469   StmtResult RebuildCXXCatchStmt(SourceLocation CatchLoc,
2470                                  VarDecl *ExceptionDecl,
2471                                  Stmt *Handler) {
2472     return Owned(new (getSema().Context) CXXCatchStmt(CatchLoc, ExceptionDecl,
2473                                                       Handler));
2474   }
2475 
2476   /// Build a new C++ try statement.
2477   ///
2478   /// By default, performs semantic analysis to build the new statement.
2479   /// Subclasses may override this routine to provide different behavior.
2480   StmtResult RebuildCXXTryStmt(SourceLocation TryLoc, Stmt *TryBlock,
2481                                ArrayRef<Stmt *> Handlers) {
2482     return getSema().ActOnCXXTryBlock(TryLoc, TryBlock, Handlers);
2483   }
2484 
2485   /// Build a new C++0x range-based for statement.
2486   ///
2487   /// By default, performs semantic analysis to build the new statement.
2488   /// Subclasses may override this routine to provide different behavior.
2489   StmtResult RebuildCXXForRangeStmt(SourceLocation ForLoc,
2490                                     SourceLocation CoawaitLoc, Stmt *Init,
2491                                     SourceLocation ColonLoc, Stmt *Range,
2492                                     Stmt *Begin, Stmt *End, Expr *Cond,
2493                                     Expr *Inc, Stmt *LoopVar,
2494                                     SourceLocation RParenLoc) {
2495     // If we've just learned that the range is actually an Objective-C
2496     // collection, treat this as an Objective-C fast enumeration loop.
2497     if (DeclStmt *RangeStmt = dyn_cast<DeclStmt>(Range)) {
2498       if (RangeStmt->isSingleDecl()) {
2499         if (VarDecl *RangeVar = dyn_cast<VarDecl>(RangeStmt->getSingleDecl())) {
2500           if (RangeVar->isInvalidDecl())
2501             return StmtError();
2502 
2503           Expr *RangeExpr = RangeVar->getInit();
2504           if (!RangeExpr->isTypeDependent() &&
2505               RangeExpr->getType()->isObjCObjectPointerType()) {
2506             // FIXME: Support init-statements in Objective-C++20 ranged for
2507             // statement.
2508             if (Init) {
2509               return SemaRef.Diag(Init->getBeginLoc(),
2510                                   diag::err_objc_for_range_init_stmt)
2511                          << Init->getSourceRange();
2512             }
2513             return getSema().ActOnObjCForCollectionStmt(ForLoc, LoopVar,
2514                                                         RangeExpr, RParenLoc);
2515           }
2516         }
2517       }
2518     }
2519 
2520     return getSema().BuildCXXForRangeStmt(ForLoc, CoawaitLoc, Init, ColonLoc,
2521                                           Range, Begin, End, Cond, Inc, LoopVar,
2522                                           RParenLoc, Sema::BFRK_Rebuild);
2523   }
2524 
2525   /// Build a new C++0x range-based for statement.
2526   ///
2527   /// By default, performs semantic analysis to build the new statement.
2528   /// Subclasses may override this routine to provide different behavior.
2529   StmtResult RebuildMSDependentExistsStmt(SourceLocation KeywordLoc,
2530                                           bool IsIfExists,
2531                                           NestedNameSpecifierLoc QualifierLoc,
2532                                           DeclarationNameInfo NameInfo,
2533                                           Stmt *Nested) {
2534     return getSema().BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
2535                                                 QualifierLoc, NameInfo, Nested);
2536   }
2537 
2538   /// Attach body to a C++0x range-based for statement.
2539   ///
2540   /// By default, performs semantic analysis to finish the new statement.
2541   /// Subclasses may override this routine to provide different behavior.
2542   StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body) {
2543     return getSema().FinishCXXForRangeStmt(ForRange, Body);
2544   }
2545 
2546   StmtResult RebuildSEHTryStmt(bool IsCXXTry, SourceLocation TryLoc,
2547                                Stmt *TryBlock, Stmt *Handler) {
2548     return getSema().ActOnSEHTryBlock(IsCXXTry, TryLoc, TryBlock, Handler);
2549   }
2550 
2551   StmtResult RebuildSEHExceptStmt(SourceLocation Loc, Expr *FilterExpr,
2552                                   Stmt *Block) {
2553     return getSema().ActOnSEHExceptBlock(Loc, FilterExpr, Block);
2554   }
2555 
2556   StmtResult RebuildSEHFinallyStmt(SourceLocation Loc, Stmt *Block) {
2557     return SEHFinallyStmt::Create(getSema().getASTContext(), Loc, Block);
2558   }
2559 
2560   ExprResult RebuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
2561                                              SourceLocation LParen,
2562                                              SourceLocation RParen,
2563                                              TypeSourceInfo *TSI) {
2564     return getSema().BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI);
2565   }
2566 
2567   /// Build a new predefined expression.
2568   ///
2569   /// By default, performs semantic analysis to build the new expression.
2570   /// Subclasses may override this routine to provide different behavior.
2571   ExprResult RebuildPredefinedExpr(SourceLocation Loc,
2572                                    PredefinedExpr::IdentKind IK) {
2573     return getSema().BuildPredefinedExpr(Loc, IK);
2574   }
2575 
2576   /// Build a new expression that references a declaration.
2577   ///
2578   /// By default, performs semantic analysis to build the new expression.
2579   /// Subclasses may override this routine to provide different behavior.
2580   ExprResult RebuildDeclarationNameExpr(const CXXScopeSpec &SS,
2581                                         LookupResult &R,
2582                                         bool RequiresADL) {
2583     return getSema().BuildDeclarationNameExpr(SS, R, RequiresADL);
2584   }
2585 
2586 
2587   /// Build a new expression that references a declaration.
2588   ///
2589   /// By default, performs semantic analysis to build the new expression.
2590   /// Subclasses may override this routine to provide different behavior.
2591   ExprResult RebuildDeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
2592                                 ValueDecl *VD,
2593                                 const DeclarationNameInfo &NameInfo,
2594                                 NamedDecl *Found,
2595                                 TemplateArgumentListInfo *TemplateArgs) {
2596     CXXScopeSpec SS;
2597     SS.Adopt(QualifierLoc);
2598     return getSema().BuildDeclarationNameExpr(SS, NameInfo, VD, Found,
2599                                               TemplateArgs);
2600   }
2601 
2602   /// Build a new expression in parentheses.
2603   ///
2604   /// By default, performs semantic analysis to build the new expression.
2605   /// Subclasses may override this routine to provide different behavior.
2606   ExprResult RebuildParenExpr(Expr *SubExpr, SourceLocation LParen,
2607                                     SourceLocation RParen) {
2608     return getSema().ActOnParenExpr(LParen, RParen, SubExpr);
2609   }
2610 
2611   /// Build a new pseudo-destructor expression.
2612   ///
2613   /// By default, performs semantic analysis to build the new expression.
2614   /// Subclasses may override this routine to provide different behavior.
2615   ExprResult RebuildCXXPseudoDestructorExpr(Expr *Base,
2616                                             SourceLocation OperatorLoc,
2617                                             bool isArrow,
2618                                             CXXScopeSpec &SS,
2619                                             TypeSourceInfo *ScopeType,
2620                                             SourceLocation CCLoc,
2621                                             SourceLocation TildeLoc,
2622                                         PseudoDestructorTypeStorage Destroyed);
2623 
2624   /// Build a new unary operator expression.
2625   ///
2626   /// By default, performs semantic analysis to build the new expression.
2627   /// Subclasses may override this routine to provide different behavior.
2628   ExprResult RebuildUnaryOperator(SourceLocation OpLoc,
2629                                         UnaryOperatorKind Opc,
2630                                         Expr *SubExpr) {
2631     return getSema().BuildUnaryOp(/*Scope=*/nullptr, OpLoc, Opc, SubExpr);
2632   }
2633 
2634   /// Build a new builtin offsetof expression.
2635   ///
2636   /// By default, performs semantic analysis to build the new expression.
2637   /// Subclasses may override this routine to provide different behavior.
2638   ExprResult RebuildOffsetOfExpr(SourceLocation OperatorLoc,
2639                                  TypeSourceInfo *Type,
2640                                  ArrayRef<Sema::OffsetOfComponent> Components,
2641                                  SourceLocation RParenLoc) {
2642     return getSema().BuildBuiltinOffsetOf(OperatorLoc, Type, Components,
2643                                           RParenLoc);
2644   }
2645 
2646   /// Build a new sizeof, alignof or vec_step expression with a
2647   /// type argument.
2648   ///
2649   /// By default, performs semantic analysis to build the new expression.
2650   /// Subclasses may override this routine to provide different behavior.
2651   ExprResult RebuildUnaryExprOrTypeTrait(TypeSourceInfo *TInfo,
2652                                          SourceLocation OpLoc,
2653                                          UnaryExprOrTypeTrait ExprKind,
2654                                          SourceRange R) {
2655     return getSema().CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R);
2656   }
2657 
2658   /// Build a new sizeof, alignof or vec step expression with an
2659   /// expression argument.
2660   ///
2661   /// By default, performs semantic analysis to build the new expression.
2662   /// Subclasses may override this routine to provide different behavior.
2663   ExprResult RebuildUnaryExprOrTypeTrait(Expr *SubExpr, SourceLocation OpLoc,
2664                                          UnaryExprOrTypeTrait ExprKind,
2665                                          SourceRange R) {
2666     ExprResult Result
2667       = getSema().CreateUnaryExprOrTypeTraitExpr(SubExpr, OpLoc, ExprKind);
2668     if (Result.isInvalid())
2669       return ExprError();
2670 
2671     return Result;
2672   }
2673 
2674   /// Build a new array subscript expression.
2675   ///
2676   /// By default, performs semantic analysis to build the new expression.
2677   /// Subclasses may override this routine to provide different behavior.
2678   ExprResult RebuildArraySubscriptExpr(Expr *LHS,
2679                                              SourceLocation LBracketLoc,
2680                                              Expr *RHS,
2681                                              SourceLocation RBracketLoc) {
2682     return getSema().ActOnArraySubscriptExpr(/*Scope=*/nullptr, LHS,
2683                                              LBracketLoc, RHS,
2684                                              RBracketLoc);
2685   }
2686 
2687   /// Build a new matrix subscript expression.
2688   ///
2689   /// By default, performs semantic analysis to build the new expression.
2690   /// Subclasses may override this routine to provide different behavior.
2691   ExprResult RebuildMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
2692                                         Expr *ColumnIdx,
2693                                         SourceLocation RBracketLoc) {
2694     return getSema().CreateBuiltinMatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
2695                                                       RBracketLoc);
2696   }
2697 
2698   /// Build a new array section expression.
2699   ///
2700   /// By default, performs semantic analysis to build the new expression.
2701   /// Subclasses may override this routine to provide different behavior.
2702   ExprResult RebuildOMPArraySectionExpr(Expr *Base, SourceLocation LBracketLoc,
2703                                         Expr *LowerBound,
2704                                         SourceLocation ColonLocFirst,
2705                                         SourceLocation ColonLocSecond,
2706                                         Expr *Length, Expr *Stride,
2707                                         SourceLocation RBracketLoc) {
2708     return getSema().ActOnOMPArraySectionExpr(Base, LBracketLoc, LowerBound,
2709                                               ColonLocFirst, ColonLocSecond,
2710                                               Length, Stride, RBracketLoc);
2711   }
2712 
2713   /// Build a new array shaping expression.
2714   ///
2715   /// By default, performs semantic analysis to build the new expression.
2716   /// Subclasses may override this routine to provide different behavior.
2717   ExprResult RebuildOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
2718                                         SourceLocation RParenLoc,
2719                                         ArrayRef<Expr *> Dims,
2720                                         ArrayRef<SourceRange> BracketsRanges) {
2721     return getSema().ActOnOMPArrayShapingExpr(Base, LParenLoc, RParenLoc, Dims,
2722                                               BracketsRanges);
2723   }
2724 
2725   /// Build a new iterator expression.
2726   ///
2727   /// By default, performs semantic analysis to build the new expression.
2728   /// Subclasses may override this routine to provide different behavior.
2729   ExprResult RebuildOMPIteratorExpr(
2730       SourceLocation IteratorKwLoc, SourceLocation LLoc, SourceLocation RLoc,
2731       ArrayRef<Sema::OMPIteratorData> Data) {
2732     return getSema().ActOnOMPIteratorExpr(/*Scope=*/nullptr, IteratorKwLoc,
2733                                           LLoc, RLoc, Data);
2734   }
2735 
2736   /// Build a new call expression.
2737   ///
2738   /// By default, performs semantic analysis to build the new expression.
2739   /// Subclasses may override this routine to provide different behavior.
2740   ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
2741                                    MultiExprArg Args,
2742                                    SourceLocation RParenLoc,
2743                                    Expr *ExecConfig = nullptr) {
2744     return getSema().ActOnCallExpr(
2745         /*Scope=*/nullptr, Callee, LParenLoc, Args, RParenLoc, ExecConfig);
2746   }
2747 
2748   ExprResult RebuildCxxSubscriptExpr(Expr *Callee, SourceLocation LParenLoc,
2749                                      MultiExprArg Args,
2750                                      SourceLocation RParenLoc) {
2751     return getSema().ActOnArraySubscriptExpr(
2752         /*Scope=*/nullptr, Callee, LParenLoc, Args, RParenLoc);
2753   }
2754 
2755   /// Build a new member access expression.
2756   ///
2757   /// By default, performs semantic analysis to build the new expression.
2758   /// Subclasses may override this routine to provide different behavior.
2759   ExprResult RebuildMemberExpr(Expr *Base, SourceLocation OpLoc,
2760                                bool isArrow,
2761                                NestedNameSpecifierLoc QualifierLoc,
2762                                SourceLocation TemplateKWLoc,
2763                                const DeclarationNameInfo &MemberNameInfo,
2764                                ValueDecl *Member,
2765                                NamedDecl *FoundDecl,
2766                         const TemplateArgumentListInfo *ExplicitTemplateArgs,
2767                                NamedDecl *FirstQualifierInScope) {
2768     ExprResult BaseResult = getSema().PerformMemberExprBaseConversion(Base,
2769                                                                       isArrow);
2770     if (!Member->getDeclName()) {
2771       // We have a reference to an unnamed field.  This is always the
2772       // base of an anonymous struct/union member access, i.e. the
2773       // field is always of record type.
2774       assert(Member->getType()->isRecordType() &&
2775              "unnamed member not of record type?");
2776 
2777       BaseResult =
2778         getSema().PerformObjectMemberConversion(BaseResult.get(),
2779                                                 QualifierLoc.getNestedNameSpecifier(),
2780                                                 FoundDecl, Member);
2781       if (BaseResult.isInvalid())
2782         return ExprError();
2783       Base = BaseResult.get();
2784 
2785       CXXScopeSpec EmptySS;
2786       return getSema().BuildFieldReferenceExpr(
2787           Base, isArrow, OpLoc, EmptySS, cast<FieldDecl>(Member),
2788           DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()), MemberNameInfo);
2789     }
2790 
2791     CXXScopeSpec SS;
2792     SS.Adopt(QualifierLoc);
2793 
2794     Base = BaseResult.get();
2795     QualType BaseType = Base->getType();
2796 
2797     if (isArrow && !BaseType->isPointerType())
2798       return ExprError();
2799 
2800     // FIXME: this involves duplicating earlier analysis in a lot of
2801     // cases; we should avoid this when possible.
2802     LookupResult R(getSema(), MemberNameInfo, Sema::LookupMemberName);
2803     R.addDecl(FoundDecl);
2804     R.resolveKind();
2805 
2806     return getSema().BuildMemberReferenceExpr(Base, BaseType, OpLoc, isArrow,
2807                                               SS, TemplateKWLoc,
2808                                               FirstQualifierInScope,
2809                                               R, ExplicitTemplateArgs,
2810                                               /*S*/nullptr);
2811   }
2812 
2813   /// Build a new binary operator expression.
2814   ///
2815   /// By default, performs semantic analysis to build the new expression.
2816   /// Subclasses may override this routine to provide different behavior.
2817   ExprResult RebuildBinaryOperator(SourceLocation OpLoc,
2818                                          BinaryOperatorKind Opc,
2819                                          Expr *LHS, Expr *RHS) {
2820     return getSema().BuildBinOp(/*Scope=*/nullptr, OpLoc, Opc, LHS, RHS);
2821   }
2822 
2823   /// Build a new rewritten operator expression.
2824   ///
2825   /// By default, performs semantic analysis to build the new expression.
2826   /// Subclasses may override this routine to provide different behavior.
2827   ExprResult RebuildCXXRewrittenBinaryOperator(
2828       SourceLocation OpLoc, BinaryOperatorKind Opcode,
2829       const UnresolvedSetImpl &UnqualLookups, Expr *LHS, Expr *RHS) {
2830     return getSema().CreateOverloadedBinOp(OpLoc, Opcode, UnqualLookups, LHS,
2831                                            RHS, /*RequiresADL*/false);
2832   }
2833 
2834   /// Build a new conditional operator expression.
2835   ///
2836   /// By default, performs semantic analysis to build the new expression.
2837   /// Subclasses may override this routine to provide different behavior.
2838   ExprResult RebuildConditionalOperator(Expr *Cond,
2839                                         SourceLocation QuestionLoc,
2840                                         Expr *LHS,
2841                                         SourceLocation ColonLoc,
2842                                         Expr *RHS) {
2843     return getSema().ActOnConditionalOp(QuestionLoc, ColonLoc, Cond,
2844                                         LHS, RHS);
2845   }
2846 
2847   /// Build a new C-style cast expression.
2848   ///
2849   /// By default, performs semantic analysis to build the new expression.
2850   /// Subclasses may override this routine to provide different behavior.
2851   ExprResult RebuildCStyleCastExpr(SourceLocation LParenLoc,
2852                                          TypeSourceInfo *TInfo,
2853                                          SourceLocation RParenLoc,
2854                                          Expr *SubExpr) {
2855     return getSema().BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc,
2856                                          SubExpr);
2857   }
2858 
2859   /// Build a new compound literal expression.
2860   ///
2861   /// By default, performs semantic analysis to build the new expression.
2862   /// Subclasses may override this routine to provide different behavior.
2863   ExprResult RebuildCompoundLiteralExpr(SourceLocation LParenLoc,
2864                                               TypeSourceInfo *TInfo,
2865                                               SourceLocation RParenLoc,
2866                                               Expr *Init) {
2867     return getSema().BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc,
2868                                               Init);
2869   }
2870 
2871   /// Build a new extended vector element access expression.
2872   ///
2873   /// By default, performs semantic analysis to build the new expression.
2874   /// Subclasses may override this routine to provide different behavior.
2875   ExprResult RebuildExtVectorElementExpr(Expr *Base, SourceLocation OpLoc,
2876                                          bool IsArrow,
2877                                          SourceLocation AccessorLoc,
2878                                          IdentifierInfo &Accessor) {
2879 
2880     CXXScopeSpec SS;
2881     DeclarationNameInfo NameInfo(&Accessor, AccessorLoc);
2882     return getSema().BuildMemberReferenceExpr(
2883         Base, Base->getType(), OpLoc, IsArrow, SS, SourceLocation(),
2884         /*FirstQualifierInScope*/ nullptr, NameInfo,
2885         /* TemplateArgs */ nullptr,
2886         /*S*/ nullptr);
2887   }
2888 
2889   /// Build a new initializer list expression.
2890   ///
2891   /// By default, performs semantic analysis to build the new expression.
2892   /// Subclasses may override this routine to provide different behavior.
2893   ExprResult RebuildInitList(SourceLocation LBraceLoc,
2894                              MultiExprArg Inits,
2895                              SourceLocation RBraceLoc) {
2896     return SemaRef.BuildInitList(LBraceLoc, Inits, RBraceLoc);
2897   }
2898 
2899   /// Build a new designated initializer expression.
2900   ///
2901   /// By default, performs semantic analysis to build the new expression.
2902   /// Subclasses may override this routine to provide different behavior.
2903   ExprResult RebuildDesignatedInitExpr(Designation &Desig,
2904                                              MultiExprArg ArrayExprs,
2905                                              SourceLocation EqualOrColonLoc,
2906                                              bool GNUSyntax,
2907                                              Expr *Init) {
2908     ExprResult Result
2909       = SemaRef.ActOnDesignatedInitializer(Desig, EqualOrColonLoc, GNUSyntax,
2910                                            Init);
2911     if (Result.isInvalid())
2912       return ExprError();
2913 
2914     return Result;
2915   }
2916 
2917   /// Build a new value-initialized expression.
2918   ///
2919   /// By default, builds the implicit value initialization without performing
2920   /// any semantic analysis. Subclasses may override this routine to provide
2921   /// different behavior.
2922   ExprResult RebuildImplicitValueInitExpr(QualType T) {
2923     return new (SemaRef.Context) ImplicitValueInitExpr(T);
2924   }
2925 
2926   /// Build a new \c va_arg expression.
2927   ///
2928   /// By default, performs semantic analysis to build the new expression.
2929   /// Subclasses may override this routine to provide different behavior.
2930   ExprResult RebuildVAArgExpr(SourceLocation BuiltinLoc,
2931                                     Expr *SubExpr, TypeSourceInfo *TInfo,
2932                                     SourceLocation RParenLoc) {
2933     return getSema().BuildVAArgExpr(BuiltinLoc,
2934                                     SubExpr, TInfo,
2935                                     RParenLoc);
2936   }
2937 
2938   /// Build a new expression list in parentheses.
2939   ///
2940   /// By default, performs semantic analysis to build the new expression.
2941   /// Subclasses may override this routine to provide different behavior.
2942   ExprResult RebuildParenListExpr(SourceLocation LParenLoc,
2943                                   MultiExprArg SubExprs,
2944                                   SourceLocation RParenLoc) {
2945     return getSema().ActOnParenListExpr(LParenLoc, RParenLoc, SubExprs);
2946   }
2947 
2948   /// Build a new address-of-label expression.
2949   ///
2950   /// By default, performs semantic analysis, using the name of the label
2951   /// rather than attempting to map the label statement itself.
2952   /// Subclasses may override this routine to provide different behavior.
2953   ExprResult RebuildAddrLabelExpr(SourceLocation AmpAmpLoc,
2954                                   SourceLocation LabelLoc, LabelDecl *Label) {
2955     return getSema().ActOnAddrLabel(AmpAmpLoc, LabelLoc, Label);
2956   }
2957 
2958   /// Build a new GNU statement expression.
2959   ///
2960   /// By default, performs semantic analysis to build the new expression.
2961   /// Subclasses may override this routine to provide different behavior.
2962   ExprResult RebuildStmtExpr(SourceLocation LParenLoc, Stmt *SubStmt,
2963                              SourceLocation RParenLoc, unsigned TemplateDepth) {
2964     return getSema().BuildStmtExpr(LParenLoc, SubStmt, RParenLoc,
2965                                    TemplateDepth);
2966   }
2967 
2968   /// Build a new __builtin_choose_expr expression.
2969   ///
2970   /// By default, performs semantic analysis to build the new expression.
2971   /// Subclasses may override this routine to provide different behavior.
2972   ExprResult RebuildChooseExpr(SourceLocation BuiltinLoc,
2973                                      Expr *Cond, Expr *LHS, Expr *RHS,
2974                                      SourceLocation RParenLoc) {
2975     return SemaRef.ActOnChooseExpr(BuiltinLoc,
2976                                    Cond, LHS, RHS,
2977                                    RParenLoc);
2978   }
2979 
2980   /// Build a new generic selection expression.
2981   ///
2982   /// By default, performs semantic analysis to build the new expression.
2983   /// Subclasses may override this routine to provide different behavior.
2984   ExprResult RebuildGenericSelectionExpr(SourceLocation KeyLoc,
2985                                          SourceLocation DefaultLoc,
2986                                          SourceLocation RParenLoc,
2987                                          Expr *ControllingExpr,
2988                                          ArrayRef<TypeSourceInfo *> Types,
2989                                          ArrayRef<Expr *> Exprs) {
2990     return getSema().CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
2991                                                 ControllingExpr, Types, Exprs);
2992   }
2993 
2994   /// Build a new overloaded operator call expression.
2995   ///
2996   /// By default, performs semantic analysis to build the new expression.
2997   /// The semantic analysis provides the behavior of template instantiation,
2998   /// copying with transformations that turn what looks like an overloaded
2999   /// operator call into a use of a builtin operator, performing
3000   /// argument-dependent lookup, etc. Subclasses may override this routine to
3001   /// provide different behavior.
3002   ExprResult RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
3003                                               SourceLocation OpLoc,
3004                                               Expr *Callee,
3005                                               Expr *First,
3006                                               Expr *Second);
3007 
3008   /// Build a new C++ "named" cast expression, such as static_cast or
3009   /// reinterpret_cast.
3010   ///
3011   /// By default, this routine dispatches to one of the more-specific routines
3012   /// for a particular named case, e.g., RebuildCXXStaticCastExpr().
3013   /// Subclasses may override this routine to provide different behavior.
3014   ExprResult RebuildCXXNamedCastExpr(SourceLocation OpLoc,
3015                                            Stmt::StmtClass Class,
3016                                            SourceLocation LAngleLoc,
3017                                            TypeSourceInfo *TInfo,
3018                                            SourceLocation RAngleLoc,
3019                                            SourceLocation LParenLoc,
3020                                            Expr *SubExpr,
3021                                            SourceLocation RParenLoc) {
3022     switch (Class) {
3023     case Stmt::CXXStaticCastExprClass:
3024       return getDerived().RebuildCXXStaticCastExpr(OpLoc, LAngleLoc, TInfo,
3025                                                    RAngleLoc, LParenLoc,
3026                                                    SubExpr, RParenLoc);
3027 
3028     case Stmt::CXXDynamicCastExprClass:
3029       return getDerived().RebuildCXXDynamicCastExpr(OpLoc, LAngleLoc, TInfo,
3030                                                     RAngleLoc, LParenLoc,
3031                                                     SubExpr, RParenLoc);
3032 
3033     case Stmt::CXXReinterpretCastExprClass:
3034       return getDerived().RebuildCXXReinterpretCastExpr(OpLoc, LAngleLoc, TInfo,
3035                                                         RAngleLoc, LParenLoc,
3036                                                         SubExpr,
3037                                                         RParenLoc);
3038 
3039     case Stmt::CXXConstCastExprClass:
3040       return getDerived().RebuildCXXConstCastExpr(OpLoc, LAngleLoc, TInfo,
3041                                                    RAngleLoc, LParenLoc,
3042                                                    SubExpr, RParenLoc);
3043 
3044     case Stmt::CXXAddrspaceCastExprClass:
3045       return getDerived().RebuildCXXAddrspaceCastExpr(
3046           OpLoc, LAngleLoc, TInfo, RAngleLoc, LParenLoc, SubExpr, RParenLoc);
3047 
3048     default:
3049       llvm_unreachable("Invalid C++ named cast");
3050     }
3051   }
3052 
3053   /// Build a new C++ static_cast expression.
3054   ///
3055   /// By default, performs semantic analysis to build the new expression.
3056   /// Subclasses may override this routine to provide different behavior.
3057   ExprResult RebuildCXXStaticCastExpr(SourceLocation OpLoc,
3058                                             SourceLocation LAngleLoc,
3059                                             TypeSourceInfo *TInfo,
3060                                             SourceLocation RAngleLoc,
3061                                             SourceLocation LParenLoc,
3062                                             Expr *SubExpr,
3063                                             SourceLocation RParenLoc) {
3064     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_static_cast,
3065                                        TInfo, SubExpr,
3066                                        SourceRange(LAngleLoc, RAngleLoc),
3067                                        SourceRange(LParenLoc, RParenLoc));
3068   }
3069 
3070   /// Build a new C++ dynamic_cast expression.
3071   ///
3072   /// By default, performs semantic analysis to build the new expression.
3073   /// Subclasses may override this routine to provide different behavior.
3074   ExprResult RebuildCXXDynamicCastExpr(SourceLocation OpLoc,
3075                                              SourceLocation LAngleLoc,
3076                                              TypeSourceInfo *TInfo,
3077                                              SourceLocation RAngleLoc,
3078                                              SourceLocation LParenLoc,
3079                                              Expr *SubExpr,
3080                                              SourceLocation RParenLoc) {
3081     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_dynamic_cast,
3082                                        TInfo, SubExpr,
3083                                        SourceRange(LAngleLoc, RAngleLoc),
3084                                        SourceRange(LParenLoc, RParenLoc));
3085   }
3086 
3087   /// Build a new C++ reinterpret_cast expression.
3088   ///
3089   /// By default, performs semantic analysis to build the new expression.
3090   /// Subclasses may override this routine to provide different behavior.
3091   ExprResult RebuildCXXReinterpretCastExpr(SourceLocation OpLoc,
3092                                                  SourceLocation LAngleLoc,
3093                                                  TypeSourceInfo *TInfo,
3094                                                  SourceLocation RAngleLoc,
3095                                                  SourceLocation LParenLoc,
3096                                                  Expr *SubExpr,
3097                                                  SourceLocation RParenLoc) {
3098     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_reinterpret_cast,
3099                                        TInfo, SubExpr,
3100                                        SourceRange(LAngleLoc, RAngleLoc),
3101                                        SourceRange(LParenLoc, RParenLoc));
3102   }
3103 
3104   /// Build a new C++ const_cast expression.
3105   ///
3106   /// By default, performs semantic analysis to build the new expression.
3107   /// Subclasses may override this routine to provide different behavior.
3108   ExprResult RebuildCXXConstCastExpr(SourceLocation OpLoc,
3109                                            SourceLocation LAngleLoc,
3110                                            TypeSourceInfo *TInfo,
3111                                            SourceLocation RAngleLoc,
3112                                            SourceLocation LParenLoc,
3113                                            Expr *SubExpr,
3114                                            SourceLocation RParenLoc) {
3115     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_const_cast,
3116                                        TInfo, SubExpr,
3117                                        SourceRange(LAngleLoc, RAngleLoc),
3118                                        SourceRange(LParenLoc, RParenLoc));
3119   }
3120 
3121   ExprResult
3122   RebuildCXXAddrspaceCastExpr(SourceLocation OpLoc, SourceLocation LAngleLoc,
3123                               TypeSourceInfo *TInfo, SourceLocation RAngleLoc,
3124                               SourceLocation LParenLoc, Expr *SubExpr,
3125                               SourceLocation RParenLoc) {
3126     return getSema().BuildCXXNamedCast(
3127         OpLoc, tok::kw_addrspace_cast, TInfo, SubExpr,
3128         SourceRange(LAngleLoc, RAngleLoc), SourceRange(LParenLoc, RParenLoc));
3129   }
3130 
3131   /// Build a new C++ functional-style cast expression.
3132   ///
3133   /// By default, performs semantic analysis to build the new expression.
3134   /// Subclasses may override this routine to provide different behavior.
3135   ExprResult RebuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
3136                                           SourceLocation LParenLoc,
3137                                           Expr *Sub,
3138                                           SourceLocation RParenLoc,
3139                                           bool ListInitialization) {
3140     // If Sub is a ParenListExpr, then Sub is the syntatic form of a
3141     // CXXParenListInitExpr. Pass its expanded arguments so that the
3142     // CXXParenListInitExpr can be rebuilt.
3143     if (auto *PLE = dyn_cast<ParenListExpr>(Sub))
3144       return getSema().BuildCXXTypeConstructExpr(
3145           TInfo, LParenLoc, MultiExprArg(PLE->getExprs(), PLE->getNumExprs()),
3146           RParenLoc, ListInitialization);
3147     return getSema().BuildCXXTypeConstructExpr(TInfo, LParenLoc,
3148                                                MultiExprArg(&Sub, 1), RParenLoc,
3149                                                ListInitialization);
3150   }
3151 
3152   /// Build a new C++ __builtin_bit_cast expression.
3153   ///
3154   /// By default, performs semantic analysis to build the new expression.
3155   /// Subclasses may override this routine to provide different behavior.
3156   ExprResult RebuildBuiltinBitCastExpr(SourceLocation KWLoc,
3157                                        TypeSourceInfo *TSI, Expr *Sub,
3158                                        SourceLocation RParenLoc) {
3159     return getSema().BuildBuiltinBitCastExpr(KWLoc, TSI, Sub, RParenLoc);
3160   }
3161 
3162   /// Build a new C++ typeid(type) expression.
3163   ///
3164   /// By default, performs semantic analysis to build the new expression.
3165   /// Subclasses may override this routine to provide different behavior.
3166   ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
3167                                         SourceLocation TypeidLoc,
3168                                         TypeSourceInfo *Operand,
3169                                         SourceLocation RParenLoc) {
3170     return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
3171                                     RParenLoc);
3172   }
3173 
3174 
3175   /// Build a new C++ typeid(expr) expression.
3176   ///
3177   /// By default, performs semantic analysis to build the new expression.
3178   /// Subclasses may override this routine to provide different behavior.
3179   ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
3180                                         SourceLocation TypeidLoc,
3181                                         Expr *Operand,
3182                                         SourceLocation RParenLoc) {
3183     return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
3184                                     RParenLoc);
3185   }
3186 
3187   /// Build a new C++ __uuidof(type) expression.
3188   ///
3189   /// By default, performs semantic analysis to build the new expression.
3190   /// Subclasses may override this routine to provide different behavior.
3191   ExprResult RebuildCXXUuidofExpr(QualType Type, SourceLocation TypeidLoc,
3192                                   TypeSourceInfo *Operand,
3193                                   SourceLocation RParenLoc) {
3194     return getSema().BuildCXXUuidof(Type, TypeidLoc, Operand, RParenLoc);
3195   }
3196 
3197   /// Build a new C++ __uuidof(expr) expression.
3198   ///
3199   /// By default, performs semantic analysis to build the new expression.
3200   /// Subclasses may override this routine to provide different behavior.
3201   ExprResult RebuildCXXUuidofExpr(QualType Type, SourceLocation TypeidLoc,
3202                                   Expr *Operand, SourceLocation RParenLoc) {
3203     return getSema().BuildCXXUuidof(Type, TypeidLoc, Operand, RParenLoc);
3204   }
3205 
3206   /// Build a new C++ "this" expression.
3207   ///
3208   /// By default, builds a new "this" expression without performing any
3209   /// semantic analysis. Subclasses may override this routine to provide
3210   /// different behavior.
3211   ExprResult RebuildCXXThisExpr(SourceLocation ThisLoc,
3212                                 QualType ThisType,
3213                                 bool isImplicit) {
3214     return getSema().BuildCXXThisExpr(ThisLoc, ThisType, isImplicit);
3215   }
3216 
3217   /// Build a new C++ throw expression.
3218   ///
3219   /// By default, performs semantic analysis to build the new expression.
3220   /// Subclasses may override this routine to provide different behavior.
3221   ExprResult RebuildCXXThrowExpr(SourceLocation ThrowLoc, Expr *Sub,
3222                                  bool IsThrownVariableInScope) {
3223     return getSema().BuildCXXThrow(ThrowLoc, Sub, IsThrownVariableInScope);
3224   }
3225 
3226   /// Build a new C++ default-argument expression.
3227   ///
3228   /// By default, builds a new default-argument expression, which does not
3229   /// require any semantic analysis. Subclasses may override this routine to
3230   /// provide different behavior.
3231   ExprResult RebuildCXXDefaultArgExpr(SourceLocation Loc, ParmVarDecl *Param,
3232                                       Expr *RewrittenExpr) {
3233     return CXXDefaultArgExpr::Create(getSema().Context, Loc, Param,
3234                                      RewrittenExpr, getSema().CurContext);
3235   }
3236 
3237   /// Build a new C++11 default-initialization expression.
3238   ///
3239   /// By default, builds a new default field initialization expression, which
3240   /// does not require any semantic analysis. Subclasses may override this
3241   /// routine to provide different behavior.
3242   ExprResult RebuildCXXDefaultInitExpr(SourceLocation Loc,
3243                                        FieldDecl *Field) {
3244     return getSema().BuildCXXDefaultInitExpr(Loc, Field);
3245   }
3246 
3247   /// Build a new C++ zero-initialization expression.
3248   ///
3249   /// By default, performs semantic analysis to build the new expression.
3250   /// Subclasses may override this routine to provide different behavior.
3251   ExprResult RebuildCXXScalarValueInitExpr(TypeSourceInfo *TSInfo,
3252                                            SourceLocation LParenLoc,
3253                                            SourceLocation RParenLoc) {
3254     return getSema().BuildCXXTypeConstructExpr(TSInfo, LParenLoc, std::nullopt,
3255                                                RParenLoc,
3256                                                /*ListInitialization=*/false);
3257   }
3258 
3259   /// Build a new C++ "new" expression.
3260   ///
3261   /// By default, performs semantic analysis to build the new expression.
3262   /// Subclasses may override this routine to provide different behavior.
3263   ExprResult RebuildCXXNewExpr(SourceLocation StartLoc, bool UseGlobal,
3264                                SourceLocation PlacementLParen,
3265                                MultiExprArg PlacementArgs,
3266                                SourceLocation PlacementRParen,
3267                                SourceRange TypeIdParens, QualType AllocatedType,
3268                                TypeSourceInfo *AllocatedTypeInfo,
3269                                std::optional<Expr *> ArraySize,
3270                                SourceRange DirectInitRange, Expr *Initializer) {
3271     return getSema().BuildCXXNew(StartLoc, UseGlobal,
3272                                  PlacementLParen,
3273                                  PlacementArgs,
3274                                  PlacementRParen,
3275                                  TypeIdParens,
3276                                  AllocatedType,
3277                                  AllocatedTypeInfo,
3278                                  ArraySize,
3279                                  DirectInitRange,
3280                                  Initializer);
3281   }
3282 
3283   /// Build a new C++ "delete" expression.
3284   ///
3285   /// By default, performs semantic analysis to build the new expression.
3286   /// Subclasses may override this routine to provide different behavior.
3287   ExprResult RebuildCXXDeleteExpr(SourceLocation StartLoc,
3288                                         bool IsGlobalDelete,
3289                                         bool IsArrayForm,
3290                                         Expr *Operand) {
3291     return getSema().ActOnCXXDelete(StartLoc, IsGlobalDelete, IsArrayForm,
3292                                     Operand);
3293   }
3294 
3295   /// Build a new type trait expression.
3296   ///
3297   /// By default, performs semantic analysis to build the new expression.
3298   /// Subclasses may override this routine to provide different behavior.
3299   ExprResult RebuildTypeTrait(TypeTrait Trait,
3300                               SourceLocation StartLoc,
3301                               ArrayRef<TypeSourceInfo *> Args,
3302                               SourceLocation RParenLoc) {
3303     return getSema().BuildTypeTrait(Trait, StartLoc, Args, RParenLoc);
3304   }
3305 
3306   /// Build a new array type trait expression.
3307   ///
3308   /// By default, performs semantic analysis to build the new expression.
3309   /// Subclasses may override this routine to provide different behavior.
3310   ExprResult RebuildArrayTypeTrait(ArrayTypeTrait Trait,
3311                                    SourceLocation StartLoc,
3312                                    TypeSourceInfo *TSInfo,
3313                                    Expr *DimExpr,
3314                                    SourceLocation RParenLoc) {
3315     return getSema().BuildArrayTypeTrait(Trait, StartLoc, TSInfo, DimExpr, RParenLoc);
3316   }
3317 
3318   /// Build a new expression trait expression.
3319   ///
3320   /// By default, performs semantic analysis to build the new expression.
3321   /// Subclasses may override this routine to provide different behavior.
3322   ExprResult RebuildExpressionTrait(ExpressionTrait Trait,
3323                                    SourceLocation StartLoc,
3324                                    Expr *Queried,
3325                                    SourceLocation RParenLoc) {
3326     return getSema().BuildExpressionTrait(Trait, StartLoc, Queried, RParenLoc);
3327   }
3328 
3329   /// Build a new (previously unresolved) declaration reference
3330   /// expression.
3331   ///
3332   /// By default, performs semantic analysis to build the new expression.
3333   /// Subclasses may override this routine to provide different behavior.
3334   ExprResult RebuildDependentScopeDeclRefExpr(
3335                                           NestedNameSpecifierLoc QualifierLoc,
3336                                           SourceLocation TemplateKWLoc,
3337                                        const DeclarationNameInfo &NameInfo,
3338                               const TemplateArgumentListInfo *TemplateArgs,
3339                                           bool IsAddressOfOperand,
3340                                           TypeSourceInfo **RecoveryTSI) {
3341     CXXScopeSpec SS;
3342     SS.Adopt(QualifierLoc);
3343 
3344     if (TemplateArgs || TemplateKWLoc.isValid())
3345       return getSema().BuildQualifiedTemplateIdExpr(SS, TemplateKWLoc, NameInfo,
3346                                                     TemplateArgs);
3347 
3348     return getSema().BuildQualifiedDeclarationNameExpr(
3349         SS, NameInfo, IsAddressOfOperand, /*S*/nullptr, RecoveryTSI);
3350   }
3351 
3352   /// Build a new template-id expression.
3353   ///
3354   /// By default, performs semantic analysis to build the new expression.
3355   /// Subclasses may override this routine to provide different behavior.
3356   ExprResult RebuildTemplateIdExpr(const CXXScopeSpec &SS,
3357                                    SourceLocation TemplateKWLoc,
3358                                    LookupResult &R,
3359                                    bool RequiresADL,
3360                               const TemplateArgumentListInfo *TemplateArgs) {
3361     return getSema().BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL,
3362                                          TemplateArgs);
3363   }
3364 
3365   /// Build a new object-construction expression.
3366   ///
3367   /// By default, performs semantic analysis to build the new expression.
3368   /// Subclasses may override this routine to provide different behavior.
3369   ExprResult RebuildCXXConstructExpr(QualType T,
3370                                      SourceLocation Loc,
3371                                      CXXConstructorDecl *Constructor,
3372                                      bool IsElidable,
3373                                      MultiExprArg Args,
3374                                      bool HadMultipleCandidates,
3375                                      bool ListInitialization,
3376                                      bool StdInitListInitialization,
3377                                      bool RequiresZeroInit,
3378                              CXXConstructExpr::ConstructionKind ConstructKind,
3379                                      SourceRange ParenRange) {
3380     // Reconstruct the constructor we originally found, which might be
3381     // different if this is a call to an inherited constructor.
3382     CXXConstructorDecl *FoundCtor = Constructor;
3383     if (Constructor->isInheritingConstructor())
3384       FoundCtor = Constructor->getInheritedConstructor().getConstructor();
3385 
3386     SmallVector<Expr *, 8> ConvertedArgs;
3387     if (getSema().CompleteConstructorCall(FoundCtor, T, Args, Loc,
3388                                           ConvertedArgs))
3389       return ExprError();
3390 
3391     return getSema().BuildCXXConstructExpr(Loc, T, Constructor,
3392                                            IsElidable,
3393                                            ConvertedArgs,
3394                                            HadMultipleCandidates,
3395                                            ListInitialization,
3396                                            StdInitListInitialization,
3397                                            RequiresZeroInit, ConstructKind,
3398                                            ParenRange);
3399   }
3400 
3401   /// Build a new implicit construction via inherited constructor
3402   /// expression.
3403   ExprResult RebuildCXXInheritedCtorInitExpr(QualType T, SourceLocation Loc,
3404                                              CXXConstructorDecl *Constructor,
3405                                              bool ConstructsVBase,
3406                                              bool InheritedFromVBase) {
3407     return new (getSema().Context) CXXInheritedCtorInitExpr(
3408         Loc, T, Constructor, ConstructsVBase, InheritedFromVBase);
3409   }
3410 
3411   /// Build a new object-construction expression.
3412   ///
3413   /// By default, performs semantic analysis to build the new expression.
3414   /// Subclasses may override this routine to provide different behavior.
3415   ExprResult RebuildCXXTemporaryObjectExpr(TypeSourceInfo *TSInfo,
3416                                            SourceLocation LParenOrBraceLoc,
3417                                            MultiExprArg Args,
3418                                            SourceLocation RParenOrBraceLoc,
3419                                            bool ListInitialization) {
3420     return getSema().BuildCXXTypeConstructExpr(
3421         TSInfo, LParenOrBraceLoc, Args, RParenOrBraceLoc, ListInitialization);
3422   }
3423 
3424   /// Build a new object-construction expression.
3425   ///
3426   /// By default, performs semantic analysis to build the new expression.
3427   /// Subclasses may override this routine to provide different behavior.
3428   ExprResult RebuildCXXUnresolvedConstructExpr(TypeSourceInfo *TSInfo,
3429                                                SourceLocation LParenLoc,
3430                                                MultiExprArg Args,
3431                                                SourceLocation RParenLoc,
3432                                                bool ListInitialization) {
3433     return getSema().BuildCXXTypeConstructExpr(TSInfo, LParenLoc, Args,
3434                                                RParenLoc, ListInitialization);
3435   }
3436 
3437   /// Build a new member reference expression.
3438   ///
3439   /// By default, performs semantic analysis to build the new expression.
3440   /// Subclasses may override this routine to provide different behavior.
3441   ExprResult RebuildCXXDependentScopeMemberExpr(Expr *BaseE,
3442                                                 QualType BaseType,
3443                                                 bool IsArrow,
3444                                                 SourceLocation OperatorLoc,
3445                                           NestedNameSpecifierLoc QualifierLoc,
3446                                                 SourceLocation TemplateKWLoc,
3447                                             NamedDecl *FirstQualifierInScope,
3448                                    const DeclarationNameInfo &MemberNameInfo,
3449                               const TemplateArgumentListInfo *TemplateArgs) {
3450     CXXScopeSpec SS;
3451     SS.Adopt(QualifierLoc);
3452 
3453     return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
3454                                             OperatorLoc, IsArrow,
3455                                             SS, TemplateKWLoc,
3456                                             FirstQualifierInScope,
3457                                             MemberNameInfo,
3458                                             TemplateArgs, /*S*/nullptr);
3459   }
3460 
3461   /// Build a new member reference expression.
3462   ///
3463   /// By default, performs semantic analysis to build the new expression.
3464   /// Subclasses may override this routine to provide different behavior.
3465   ExprResult RebuildUnresolvedMemberExpr(Expr *BaseE, QualType BaseType,
3466                                          SourceLocation OperatorLoc,
3467                                          bool IsArrow,
3468                                          NestedNameSpecifierLoc QualifierLoc,
3469                                          SourceLocation TemplateKWLoc,
3470                                          NamedDecl *FirstQualifierInScope,
3471                                          LookupResult &R,
3472                                 const TemplateArgumentListInfo *TemplateArgs) {
3473     CXXScopeSpec SS;
3474     SS.Adopt(QualifierLoc);
3475 
3476     return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
3477                                             OperatorLoc, IsArrow,
3478                                             SS, TemplateKWLoc,
3479                                             FirstQualifierInScope,
3480                                             R, TemplateArgs, /*S*/nullptr);
3481   }
3482 
3483   /// Build a new noexcept expression.
3484   ///
3485   /// By default, performs semantic analysis to build the new expression.
3486   /// Subclasses may override this routine to provide different behavior.
3487   ExprResult RebuildCXXNoexceptExpr(SourceRange Range, Expr *Arg) {
3488     return SemaRef.BuildCXXNoexceptExpr(Range.getBegin(), Arg, Range.getEnd());
3489   }
3490 
3491   /// Build a new expression to compute the length of a parameter pack.
3492   ExprResult RebuildSizeOfPackExpr(SourceLocation OperatorLoc, NamedDecl *Pack,
3493                                    SourceLocation PackLoc,
3494                                    SourceLocation RParenLoc,
3495                                    std::optional<unsigned> Length,
3496                                    ArrayRef<TemplateArgument> PartialArgs) {
3497     return SizeOfPackExpr::Create(SemaRef.Context, OperatorLoc, Pack, PackLoc,
3498                                   RParenLoc, Length, PartialArgs);
3499   }
3500 
3501   /// Build a new expression representing a call to a source location
3502   ///  builtin.
3503   ///
3504   /// By default, performs semantic analysis to build the new expression.
3505   /// Subclasses may override this routine to provide different behavior.
3506   ExprResult RebuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
3507                                   QualType ResultTy, SourceLocation BuiltinLoc,
3508                                   SourceLocation RPLoc,
3509                                   DeclContext *ParentContext) {
3510     return getSema().BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc,
3511                                         ParentContext);
3512   }
3513 
3514   /// Build a new Objective-C boxed expression.
3515   ///
3516   /// By default, performs semantic analysis to build the new expression.
3517   /// Subclasses may override this routine to provide different behavior.
3518   ExprResult RebuildConceptSpecializationExpr(NestedNameSpecifierLoc NNS,
3519       SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo,
3520       NamedDecl *FoundDecl, ConceptDecl *NamedConcept,
3521       TemplateArgumentListInfo *TALI) {
3522     CXXScopeSpec SS;
3523     SS.Adopt(NNS);
3524     ExprResult Result = getSema().CheckConceptTemplateId(SS, TemplateKWLoc,
3525                                                          ConceptNameInfo,
3526                                                          FoundDecl,
3527                                                          NamedConcept, TALI);
3528     if (Result.isInvalid())
3529       return ExprError();
3530     return Result;
3531   }
3532 
3533   /// \brief Build a new requires expression.
3534   ///
3535   /// By default, performs semantic analysis to build the new expression.
3536   /// Subclasses may override this routine to provide different behavior.
3537   ExprResult RebuildRequiresExpr(SourceLocation RequiresKWLoc,
3538                                  RequiresExprBodyDecl *Body,
3539                                  ArrayRef<ParmVarDecl *> LocalParameters,
3540                                  ArrayRef<concepts::Requirement *> Requirements,
3541                                  SourceLocation ClosingBraceLoc) {
3542     return RequiresExpr::Create(SemaRef.Context, RequiresKWLoc, Body,
3543                                 LocalParameters, Requirements, ClosingBraceLoc);
3544   }
3545 
3546   concepts::TypeRequirement *
3547   RebuildTypeRequirement(
3548       concepts::Requirement::SubstitutionDiagnostic *SubstDiag) {
3549     return SemaRef.BuildTypeRequirement(SubstDiag);
3550   }
3551 
3552   concepts::TypeRequirement *RebuildTypeRequirement(TypeSourceInfo *T) {
3553     return SemaRef.BuildTypeRequirement(T);
3554   }
3555 
3556   concepts::ExprRequirement *
3557   RebuildExprRequirement(
3558       concepts::Requirement::SubstitutionDiagnostic *SubstDiag, bool IsSimple,
3559       SourceLocation NoexceptLoc,
3560       concepts::ExprRequirement::ReturnTypeRequirement Ret) {
3561     return SemaRef.BuildExprRequirement(SubstDiag, IsSimple, NoexceptLoc,
3562                                         std::move(Ret));
3563   }
3564 
3565   concepts::ExprRequirement *
3566   RebuildExprRequirement(Expr *E, bool IsSimple, SourceLocation NoexceptLoc,
3567                          concepts::ExprRequirement::ReturnTypeRequirement Ret) {
3568     return SemaRef.BuildExprRequirement(E, IsSimple, NoexceptLoc,
3569                                         std::move(Ret));
3570   }
3571 
3572   concepts::NestedRequirement *
3573   RebuildNestedRequirement(StringRef InvalidConstraintEntity,
3574                            const ASTConstraintSatisfaction &Satisfaction) {
3575     return SemaRef.BuildNestedRequirement(InvalidConstraintEntity,
3576                                           Satisfaction);
3577   }
3578 
3579   concepts::NestedRequirement *RebuildNestedRequirement(Expr *Constraint) {
3580     return SemaRef.BuildNestedRequirement(Constraint);
3581   }
3582 
3583   /// \brief Build a new Objective-C boxed expression.
3584   ///
3585   /// By default, performs semantic analysis to build the new expression.
3586   /// Subclasses may override this routine to provide different behavior.
3587   ExprResult RebuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
3588     return getSema().BuildObjCBoxedExpr(SR, ValueExpr);
3589   }
3590 
3591   /// Build a new Objective-C array literal.
3592   ///
3593   /// By default, performs semantic analysis to build the new expression.
3594   /// Subclasses may override this routine to provide different behavior.
3595   ExprResult RebuildObjCArrayLiteral(SourceRange Range,
3596                                      Expr **Elements, unsigned NumElements) {
3597     return getSema().BuildObjCArrayLiteral(Range,
3598                                            MultiExprArg(Elements, NumElements));
3599   }
3600 
3601   ExprResult RebuildObjCSubscriptRefExpr(SourceLocation RB,
3602                                          Expr *Base, Expr *Key,
3603                                          ObjCMethodDecl *getterMethod,
3604                                          ObjCMethodDecl *setterMethod) {
3605     return  getSema().BuildObjCSubscriptExpression(RB, Base, Key,
3606                                                    getterMethod, setterMethod);
3607   }
3608 
3609   /// Build a new Objective-C dictionary literal.
3610   ///
3611   /// By default, performs semantic analysis to build the new expression.
3612   /// Subclasses may override this routine to provide different behavior.
3613   ExprResult RebuildObjCDictionaryLiteral(SourceRange Range,
3614                               MutableArrayRef<ObjCDictionaryElement> Elements) {
3615     return getSema().BuildObjCDictionaryLiteral(Range, Elements);
3616   }
3617 
3618   /// Build a new Objective-C \@encode expression.
3619   ///
3620   /// By default, performs semantic analysis to build the new expression.
3621   /// Subclasses may override this routine to provide different behavior.
3622   ExprResult RebuildObjCEncodeExpr(SourceLocation AtLoc,
3623                                          TypeSourceInfo *EncodeTypeInfo,
3624                                          SourceLocation RParenLoc) {
3625     return SemaRef.BuildObjCEncodeExpression(AtLoc, EncodeTypeInfo, RParenLoc);
3626   }
3627 
3628   /// Build a new Objective-C class message.
3629   ExprResult RebuildObjCMessageExpr(TypeSourceInfo *ReceiverTypeInfo,
3630                                           Selector Sel,
3631                                           ArrayRef<SourceLocation> SelectorLocs,
3632                                           ObjCMethodDecl *Method,
3633                                           SourceLocation LBracLoc,
3634                                           MultiExprArg Args,
3635                                           SourceLocation RBracLoc) {
3636     return SemaRef.BuildClassMessage(ReceiverTypeInfo,
3637                                      ReceiverTypeInfo->getType(),
3638                                      /*SuperLoc=*/SourceLocation(),
3639                                      Sel, Method, LBracLoc, SelectorLocs,
3640                                      RBracLoc, Args);
3641   }
3642 
3643   /// Build a new Objective-C instance message.
3644   ExprResult RebuildObjCMessageExpr(Expr *Receiver,
3645                                           Selector Sel,
3646                                           ArrayRef<SourceLocation> SelectorLocs,
3647                                           ObjCMethodDecl *Method,
3648                                           SourceLocation LBracLoc,
3649                                           MultiExprArg Args,
3650                                           SourceLocation RBracLoc) {
3651     return SemaRef.BuildInstanceMessage(Receiver,
3652                                         Receiver->getType(),
3653                                         /*SuperLoc=*/SourceLocation(),
3654                                         Sel, Method, LBracLoc, SelectorLocs,
3655                                         RBracLoc, Args);
3656   }
3657 
3658   /// Build a new Objective-C instance/class message to 'super'.
3659   ExprResult RebuildObjCMessageExpr(SourceLocation SuperLoc,
3660                                     Selector Sel,
3661                                     ArrayRef<SourceLocation> SelectorLocs,
3662                                     QualType SuperType,
3663                                     ObjCMethodDecl *Method,
3664                                     SourceLocation LBracLoc,
3665                                     MultiExprArg Args,
3666                                     SourceLocation RBracLoc) {
3667     return Method->isInstanceMethod() ? SemaRef.BuildInstanceMessage(nullptr,
3668                                           SuperType,
3669                                           SuperLoc,
3670                                           Sel, Method, LBracLoc, SelectorLocs,
3671                                           RBracLoc, Args)
3672                                       : SemaRef.BuildClassMessage(nullptr,
3673                                           SuperType,
3674                                           SuperLoc,
3675                                           Sel, Method, LBracLoc, SelectorLocs,
3676                                           RBracLoc, Args);
3677 
3678 
3679   }
3680 
3681   /// Build a new Objective-C ivar reference expression.
3682   ///
3683   /// By default, performs semantic analysis to build the new expression.
3684   /// Subclasses may override this routine to provide different behavior.
3685   ExprResult RebuildObjCIvarRefExpr(Expr *BaseArg, ObjCIvarDecl *Ivar,
3686                                           SourceLocation IvarLoc,
3687                                           bool IsArrow, bool IsFreeIvar) {
3688     CXXScopeSpec SS;
3689     DeclarationNameInfo NameInfo(Ivar->getDeclName(), IvarLoc);
3690     ExprResult Result = getSema().BuildMemberReferenceExpr(
3691         BaseArg, BaseArg->getType(),
3692         /*FIXME:*/ IvarLoc, IsArrow, SS, SourceLocation(),
3693         /*FirstQualifierInScope=*/nullptr, NameInfo,
3694         /*TemplateArgs=*/nullptr,
3695         /*S=*/nullptr);
3696     if (IsFreeIvar && Result.isUsable())
3697       cast<ObjCIvarRefExpr>(Result.get())->setIsFreeIvar(IsFreeIvar);
3698     return Result;
3699   }
3700 
3701   /// Build a new Objective-C property reference expression.
3702   ///
3703   /// By default, performs semantic analysis to build the new expression.
3704   /// Subclasses may override this routine to provide different behavior.
3705   ExprResult RebuildObjCPropertyRefExpr(Expr *BaseArg,
3706                                         ObjCPropertyDecl *Property,
3707                                         SourceLocation PropertyLoc) {
3708     CXXScopeSpec SS;
3709     DeclarationNameInfo NameInfo(Property->getDeclName(), PropertyLoc);
3710     return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3711                                               /*FIXME:*/PropertyLoc,
3712                                               /*IsArrow=*/false,
3713                                               SS, SourceLocation(),
3714                                               /*FirstQualifierInScope=*/nullptr,
3715                                               NameInfo,
3716                                               /*TemplateArgs=*/nullptr,
3717                                               /*S=*/nullptr);
3718   }
3719 
3720   /// Build a new Objective-C property reference expression.
3721   ///
3722   /// By default, performs semantic analysis to build the new expression.
3723   /// Subclasses may override this routine to provide different behavior.
3724   ExprResult RebuildObjCPropertyRefExpr(Expr *Base, QualType T,
3725                                         ObjCMethodDecl *Getter,
3726                                         ObjCMethodDecl *Setter,
3727                                         SourceLocation PropertyLoc) {
3728     // Since these expressions can only be value-dependent, we do not
3729     // need to perform semantic analysis again.
3730     return Owned(
3731       new (getSema().Context) ObjCPropertyRefExpr(Getter, Setter, T,
3732                                                   VK_LValue, OK_ObjCProperty,
3733                                                   PropertyLoc, Base));
3734   }
3735 
3736   /// Build a new Objective-C "isa" expression.
3737   ///
3738   /// By default, performs semantic analysis to build the new expression.
3739   /// Subclasses may override this routine to provide different behavior.
3740   ExprResult RebuildObjCIsaExpr(Expr *BaseArg, SourceLocation IsaLoc,
3741                                 SourceLocation OpLoc, bool IsArrow) {
3742     CXXScopeSpec SS;
3743     DeclarationNameInfo NameInfo(&getSema().Context.Idents.get("isa"), IsaLoc);
3744     return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3745                                               OpLoc, IsArrow,
3746                                               SS, SourceLocation(),
3747                                               /*FirstQualifierInScope=*/nullptr,
3748                                               NameInfo,
3749                                               /*TemplateArgs=*/nullptr,
3750                                               /*S=*/nullptr);
3751   }
3752 
3753   /// Build a new shuffle vector expression.
3754   ///
3755   /// By default, performs semantic analysis to build the new expression.
3756   /// Subclasses may override this routine to provide different behavior.
3757   ExprResult RebuildShuffleVectorExpr(SourceLocation BuiltinLoc,
3758                                       MultiExprArg SubExprs,
3759                                       SourceLocation RParenLoc) {
3760     // Find the declaration for __builtin_shufflevector
3761     const IdentifierInfo &Name
3762       = SemaRef.Context.Idents.get("__builtin_shufflevector");
3763     TranslationUnitDecl *TUDecl = SemaRef.Context.getTranslationUnitDecl();
3764     DeclContext::lookup_result Lookup = TUDecl->lookup(DeclarationName(&Name));
3765     assert(!Lookup.empty() && "No __builtin_shufflevector?");
3766 
3767     // Build a reference to the __builtin_shufflevector builtin
3768     FunctionDecl *Builtin = cast<FunctionDecl>(Lookup.front());
3769     Expr *Callee = new (SemaRef.Context)
3770         DeclRefExpr(SemaRef.Context, Builtin, false,
3771                     SemaRef.Context.BuiltinFnTy, VK_PRValue, BuiltinLoc);
3772     QualType CalleePtrTy = SemaRef.Context.getPointerType(Builtin->getType());
3773     Callee = SemaRef.ImpCastExprToType(Callee, CalleePtrTy,
3774                                        CK_BuiltinFnToFnPtr).get();
3775 
3776     // Build the CallExpr
3777     ExprResult TheCall = CallExpr::Create(
3778         SemaRef.Context, Callee, SubExprs, Builtin->getCallResultType(),
3779         Expr::getValueKindForType(Builtin->getReturnType()), RParenLoc,
3780         FPOptionsOverride());
3781 
3782     // Type-check the __builtin_shufflevector expression.
3783     return SemaRef.SemaBuiltinShuffleVector(cast<CallExpr>(TheCall.get()));
3784   }
3785 
3786   /// Build a new convert vector expression.
3787   ExprResult RebuildConvertVectorExpr(SourceLocation BuiltinLoc,
3788                                       Expr *SrcExpr, TypeSourceInfo *DstTInfo,
3789                                       SourceLocation RParenLoc) {
3790     return SemaRef.SemaConvertVectorExpr(SrcExpr, DstTInfo,
3791                                          BuiltinLoc, RParenLoc);
3792   }
3793 
3794   /// Build a new template argument pack expansion.
3795   ///
3796   /// By default, performs semantic analysis to build a new pack expansion
3797   /// for a template argument. Subclasses may override this routine to provide
3798   /// different behavior.
3799   TemplateArgumentLoc
3800   RebuildPackExpansion(TemplateArgumentLoc Pattern, SourceLocation EllipsisLoc,
3801                        std::optional<unsigned> NumExpansions) {
3802     switch (Pattern.getArgument().getKind()) {
3803     case TemplateArgument::Expression: {
3804       ExprResult Result
3805         = getSema().CheckPackExpansion(Pattern.getSourceExpression(),
3806                                        EllipsisLoc, NumExpansions);
3807       if (Result.isInvalid())
3808         return TemplateArgumentLoc();
3809 
3810       return TemplateArgumentLoc(Result.get(), Result.get());
3811     }
3812 
3813     case TemplateArgument::Template:
3814       return TemplateArgumentLoc(
3815           SemaRef.Context,
3816           TemplateArgument(Pattern.getArgument().getAsTemplate(),
3817                            NumExpansions),
3818           Pattern.getTemplateQualifierLoc(), Pattern.getTemplateNameLoc(),
3819           EllipsisLoc);
3820 
3821     case TemplateArgument::Null:
3822     case TemplateArgument::Integral:
3823     case TemplateArgument::Declaration:
3824     case TemplateArgument::Pack:
3825     case TemplateArgument::TemplateExpansion:
3826     case TemplateArgument::NullPtr:
3827       llvm_unreachable("Pack expansion pattern has no parameter packs");
3828 
3829     case TemplateArgument::Type:
3830       if (TypeSourceInfo *Expansion
3831             = getSema().CheckPackExpansion(Pattern.getTypeSourceInfo(),
3832                                            EllipsisLoc,
3833                                            NumExpansions))
3834         return TemplateArgumentLoc(TemplateArgument(Expansion->getType()),
3835                                    Expansion);
3836       break;
3837     }
3838 
3839     return TemplateArgumentLoc();
3840   }
3841 
3842   /// Build a new expression pack expansion.
3843   ///
3844   /// By default, performs semantic analysis to build a new pack expansion
3845   /// for an expression. Subclasses may override this routine to provide
3846   /// different behavior.
3847   ExprResult RebuildPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
3848                                   std::optional<unsigned> NumExpansions) {
3849     return getSema().CheckPackExpansion(Pattern, EllipsisLoc, NumExpansions);
3850   }
3851 
3852   /// Build a new C++1z fold-expression.
3853   ///
3854   /// By default, performs semantic analysis in order to build a new fold
3855   /// expression.
3856   ExprResult RebuildCXXFoldExpr(UnresolvedLookupExpr *ULE,
3857                                 SourceLocation LParenLoc, Expr *LHS,
3858                                 BinaryOperatorKind Operator,
3859                                 SourceLocation EllipsisLoc, Expr *RHS,
3860                                 SourceLocation RParenLoc,
3861                                 std::optional<unsigned> NumExpansions) {
3862     return getSema().BuildCXXFoldExpr(ULE, LParenLoc, LHS, Operator,
3863                                       EllipsisLoc, RHS, RParenLoc,
3864                                       NumExpansions);
3865   }
3866 
3867   /// Build an empty C++1z fold-expression with the given operator.
3868   ///
3869   /// By default, produces the fallback value for the fold-expression, or
3870   /// produce an error if there is no fallback value.
3871   ExprResult RebuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
3872                                      BinaryOperatorKind Operator) {
3873     return getSema().BuildEmptyCXXFoldExpr(EllipsisLoc, Operator);
3874   }
3875 
3876   /// Build a new atomic operation expression.
3877   ///
3878   /// By default, performs semantic analysis to build the new expression.
3879   /// Subclasses may override this routine to provide different behavior.
3880   ExprResult RebuildAtomicExpr(SourceLocation BuiltinLoc, MultiExprArg SubExprs,
3881                                AtomicExpr::AtomicOp Op,
3882                                SourceLocation RParenLoc) {
3883     // Use this for all of the locations, since we don't know the difference
3884     // between the call and the expr at this point.
3885     SourceRange Range{BuiltinLoc, RParenLoc};
3886     return getSema().BuildAtomicExpr(Range, Range, RParenLoc, SubExprs, Op,
3887                                      Sema::AtomicArgumentOrder::AST);
3888   }
3889 
3890   ExprResult RebuildRecoveryExpr(SourceLocation BeginLoc, SourceLocation EndLoc,
3891                                  ArrayRef<Expr *> SubExprs, QualType Type) {
3892     return getSema().CreateRecoveryExpr(BeginLoc, EndLoc, SubExprs, Type);
3893   }
3894 
3895 private:
3896   TypeLoc TransformTypeInObjectScope(TypeLoc TL,
3897                                      QualType ObjectType,
3898                                      NamedDecl *FirstQualifierInScope,
3899                                      CXXScopeSpec &SS);
3900 
3901   TypeSourceInfo *TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
3902                                              QualType ObjectType,
3903                                              NamedDecl *FirstQualifierInScope,
3904                                              CXXScopeSpec &SS);
3905 
3906   TypeSourceInfo *TransformTSIInObjectScope(TypeLoc TL, QualType ObjectType,
3907                                             NamedDecl *FirstQualifierInScope,
3908                                             CXXScopeSpec &SS);
3909 
3910   QualType TransformDependentNameType(TypeLocBuilder &TLB,
3911                                       DependentNameTypeLoc TL,
3912                                       bool DeducibleTSTContext);
3913 };
3914 
3915 template <typename Derived>
3916 StmtResult TreeTransform<Derived>::TransformStmt(Stmt *S, StmtDiscardKind SDK) {
3917   if (!S)
3918     return S;
3919 
3920   switch (S->getStmtClass()) {
3921   case Stmt::NoStmtClass: break;
3922 
3923   // Transform individual statement nodes
3924   // Pass SDK into statements that can produce a value
3925 #define STMT(Node, Parent)                                              \
3926   case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(S));
3927 #define VALUESTMT(Node, Parent)                                         \
3928   case Stmt::Node##Class:                                               \
3929     return getDerived().Transform##Node(cast<Node>(S), SDK);
3930 #define ABSTRACT_STMT(Node)
3931 #define EXPR(Node, Parent)
3932 #include "clang/AST/StmtNodes.inc"
3933 
3934   // Transform expressions by calling TransformExpr.
3935 #define STMT(Node, Parent)
3936 #define ABSTRACT_STMT(Stmt)
3937 #define EXPR(Node, Parent) case Stmt::Node##Class:
3938 #include "clang/AST/StmtNodes.inc"
3939     {
3940       ExprResult E = getDerived().TransformExpr(cast<Expr>(S));
3941 
3942       if (SDK == SDK_StmtExprResult)
3943         E = getSema().ActOnStmtExprResult(E);
3944       return getSema().ActOnExprStmt(E, SDK == SDK_Discarded);
3945     }
3946   }
3947 
3948   return S;
3949 }
3950 
3951 template<typename Derived>
3952 OMPClause *TreeTransform<Derived>::TransformOMPClause(OMPClause *S) {
3953   if (!S)
3954     return S;
3955 
3956   switch (S->getClauseKind()) {
3957   default: break;
3958   // Transform individual clause nodes
3959 #define GEN_CLANG_CLAUSE_CLASS
3960 #define CLAUSE_CLASS(Enum, Str, Class)                                         \
3961   case Enum:                                                                   \
3962     return getDerived().Transform##Class(cast<Class>(S));
3963 #include "llvm/Frontend/OpenMP/OMP.inc"
3964   }
3965 
3966   return S;
3967 }
3968 
3969 
3970 template<typename Derived>
3971 ExprResult TreeTransform<Derived>::TransformExpr(Expr *E) {
3972   if (!E)
3973     return E;
3974 
3975   switch (E->getStmtClass()) {
3976     case Stmt::NoStmtClass: break;
3977 #define STMT(Node, Parent) case Stmt::Node##Class: break;
3978 #define ABSTRACT_STMT(Stmt)
3979 #define EXPR(Node, Parent)                                              \
3980     case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(E));
3981 #include "clang/AST/StmtNodes.inc"
3982   }
3983 
3984   return E;
3985 }
3986 
3987 template<typename Derived>
3988 ExprResult TreeTransform<Derived>::TransformInitializer(Expr *Init,
3989                                                         bool NotCopyInit) {
3990   // Initializers are instantiated like expressions, except that various outer
3991   // layers are stripped.
3992   if (!Init)
3993     return Init;
3994 
3995   if (auto *FE = dyn_cast<FullExpr>(Init))
3996     Init = FE->getSubExpr();
3997 
3998   if (auto *AIL = dyn_cast<ArrayInitLoopExpr>(Init)) {
3999     OpaqueValueExpr *OVE = AIL->getCommonExpr();
4000     Init = OVE->getSourceExpr();
4001   }
4002 
4003   if (MaterializeTemporaryExpr *MTE = dyn_cast<MaterializeTemporaryExpr>(Init))
4004     Init = MTE->getSubExpr();
4005 
4006   while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
4007     Init = Binder->getSubExpr();
4008 
4009   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
4010     Init = ICE->getSubExprAsWritten();
4011 
4012   if (CXXStdInitializerListExpr *ILE =
4013           dyn_cast<CXXStdInitializerListExpr>(Init))
4014     return TransformInitializer(ILE->getSubExpr(), NotCopyInit);
4015 
4016   // If this is copy-initialization, we only need to reconstruct
4017   // InitListExprs. Other forms of copy-initialization will be a no-op if
4018   // the initializer is already the right type.
4019   CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init);
4020   if (!NotCopyInit && !(Construct && Construct->isListInitialization()))
4021     return getDerived().TransformExpr(Init);
4022 
4023   // Revert value-initialization back to empty parens.
4024   if (CXXScalarValueInitExpr *VIE = dyn_cast<CXXScalarValueInitExpr>(Init)) {
4025     SourceRange Parens = VIE->getSourceRange();
4026     return getDerived().RebuildParenListExpr(Parens.getBegin(), std::nullopt,
4027                                              Parens.getEnd());
4028   }
4029 
4030   // FIXME: We shouldn't build ImplicitValueInitExprs for direct-initialization.
4031   if (isa<ImplicitValueInitExpr>(Init))
4032     return getDerived().RebuildParenListExpr(SourceLocation(), std::nullopt,
4033                                              SourceLocation());
4034 
4035   // Revert initialization by constructor back to a parenthesized or braced list
4036   // of expressions. Any other form of initializer can just be reused directly.
4037   if (!Construct || isa<CXXTemporaryObjectExpr>(Construct))
4038     return getDerived().TransformExpr(Init);
4039 
4040   // If the initialization implicitly converted an initializer list to a
4041   // std::initializer_list object, unwrap the std::initializer_list too.
4042   if (Construct && Construct->isStdInitListInitialization())
4043     return TransformInitializer(Construct->getArg(0), NotCopyInit);
4044 
4045   // Enter a list-init context if this was list initialization.
4046   EnterExpressionEvaluationContext Context(
4047       getSema(), EnterExpressionEvaluationContext::InitList,
4048       Construct->isListInitialization());
4049 
4050   SmallVector<Expr*, 8> NewArgs;
4051   bool ArgChanged = false;
4052   if (getDerived().TransformExprs(Construct->getArgs(), Construct->getNumArgs(),
4053                                   /*IsCall*/true, NewArgs, &ArgChanged))
4054     return ExprError();
4055 
4056   // If this was list initialization, revert to syntactic list form.
4057   if (Construct->isListInitialization())
4058     return getDerived().RebuildInitList(Construct->getBeginLoc(), NewArgs,
4059                                         Construct->getEndLoc());
4060 
4061   // Build a ParenListExpr to represent anything else.
4062   SourceRange Parens = Construct->getParenOrBraceRange();
4063   if (Parens.isInvalid()) {
4064     // This was a variable declaration's initialization for which no initializer
4065     // was specified.
4066     assert(NewArgs.empty() &&
4067            "no parens or braces but have direct init with arguments?");
4068     return ExprEmpty();
4069   }
4070   return getDerived().RebuildParenListExpr(Parens.getBegin(), NewArgs,
4071                                            Parens.getEnd());
4072 }
4073 
4074 template<typename Derived>
4075 bool TreeTransform<Derived>::TransformExprs(Expr *const *Inputs,
4076                                             unsigned NumInputs,
4077                                             bool IsCall,
4078                                       SmallVectorImpl<Expr *> &Outputs,
4079                                             bool *ArgChanged) {
4080   for (unsigned I = 0; I != NumInputs; ++I) {
4081     // If requested, drop call arguments that need to be dropped.
4082     if (IsCall && getDerived().DropCallArgument(Inputs[I])) {
4083       if (ArgChanged)
4084         *ArgChanged = true;
4085 
4086       break;
4087     }
4088 
4089     if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Inputs[I])) {
4090       Expr *Pattern = Expansion->getPattern();
4091 
4092       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4093       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
4094       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
4095 
4096       // Determine whether the set of unexpanded parameter packs can and should
4097       // be expanded.
4098       bool Expand = true;
4099       bool RetainExpansion = false;
4100       std::optional<unsigned> OrigNumExpansions = Expansion->getNumExpansions();
4101       std::optional<unsigned> NumExpansions = OrigNumExpansions;
4102       if (getDerived().TryExpandParameterPacks(Expansion->getEllipsisLoc(),
4103                                                Pattern->getSourceRange(),
4104                                                Unexpanded,
4105                                                Expand, RetainExpansion,
4106                                                NumExpansions))
4107         return true;
4108 
4109       if (!Expand) {
4110         // The transform has determined that we should perform a simple
4111         // transformation on the pack expansion, producing another pack
4112         // expansion.
4113         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4114         ExprResult OutPattern = getDerived().TransformExpr(Pattern);
4115         if (OutPattern.isInvalid())
4116           return true;
4117 
4118         ExprResult Out = getDerived().RebuildPackExpansion(OutPattern.get(),
4119                                                 Expansion->getEllipsisLoc(),
4120                                                            NumExpansions);
4121         if (Out.isInvalid())
4122           return true;
4123 
4124         if (ArgChanged)
4125           *ArgChanged = true;
4126         Outputs.push_back(Out.get());
4127         continue;
4128       }
4129 
4130       // Record right away that the argument was changed.  This needs
4131       // to happen even if the array expands to nothing.
4132       if (ArgChanged) *ArgChanged = true;
4133 
4134       // The transform has determined that we should perform an elementwise
4135       // expansion of the pattern. Do so.
4136       for (unsigned I = 0; I != *NumExpansions; ++I) {
4137         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
4138         ExprResult Out = getDerived().TransformExpr(Pattern);
4139         if (Out.isInvalid())
4140           return true;
4141 
4142         if (Out.get()->containsUnexpandedParameterPack()) {
4143           Out = getDerived().RebuildPackExpansion(
4144               Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
4145           if (Out.isInvalid())
4146             return true;
4147         }
4148 
4149         Outputs.push_back(Out.get());
4150       }
4151 
4152       // If we're supposed to retain a pack expansion, do so by temporarily
4153       // forgetting the partially-substituted parameter pack.
4154       if (RetainExpansion) {
4155         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
4156 
4157         ExprResult Out = getDerived().TransformExpr(Pattern);
4158         if (Out.isInvalid())
4159           return true;
4160 
4161         Out = getDerived().RebuildPackExpansion(
4162             Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
4163         if (Out.isInvalid())
4164           return true;
4165 
4166         Outputs.push_back(Out.get());
4167       }
4168 
4169       continue;
4170     }
4171 
4172     ExprResult Result =
4173       IsCall ? getDerived().TransformInitializer(Inputs[I], /*DirectInit*/false)
4174              : getDerived().TransformExpr(Inputs[I]);
4175     if (Result.isInvalid())
4176       return true;
4177 
4178     if (Result.get() != Inputs[I] && ArgChanged)
4179       *ArgChanged = true;
4180 
4181     Outputs.push_back(Result.get());
4182   }
4183 
4184   return false;
4185 }
4186 
4187 template <typename Derived>
4188 Sema::ConditionResult TreeTransform<Derived>::TransformCondition(
4189     SourceLocation Loc, VarDecl *Var, Expr *Expr, Sema::ConditionKind Kind) {
4190   if (Var) {
4191     VarDecl *ConditionVar = cast_or_null<VarDecl>(
4192         getDerived().TransformDefinition(Var->getLocation(), Var));
4193 
4194     if (!ConditionVar)
4195       return Sema::ConditionError();
4196 
4197     return getSema().ActOnConditionVariable(ConditionVar, Loc, Kind);
4198   }
4199 
4200   if (Expr) {
4201     ExprResult CondExpr = getDerived().TransformExpr(Expr);
4202 
4203     if (CondExpr.isInvalid())
4204       return Sema::ConditionError();
4205 
4206     return getSema().ActOnCondition(nullptr, Loc, CondExpr.get(), Kind,
4207                                     /*MissingOK=*/true);
4208   }
4209 
4210   return Sema::ConditionResult();
4211 }
4212 
4213 template <typename Derived>
4214 NestedNameSpecifierLoc TreeTransform<Derived>::TransformNestedNameSpecifierLoc(
4215     NestedNameSpecifierLoc NNS, QualType ObjectType,
4216     NamedDecl *FirstQualifierInScope) {
4217   SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
4218 
4219   auto insertNNS = [&Qualifiers](NestedNameSpecifierLoc NNS) {
4220     for (NestedNameSpecifierLoc Qualifier = NNS; Qualifier;
4221          Qualifier = Qualifier.getPrefix())
4222       Qualifiers.push_back(Qualifier);
4223   };
4224   insertNNS(NNS);
4225 
4226   CXXScopeSpec SS;
4227   while (!Qualifiers.empty()) {
4228     NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
4229     NestedNameSpecifier *QNNS = Q.getNestedNameSpecifier();
4230 
4231     switch (QNNS->getKind()) {
4232     case NestedNameSpecifier::Identifier: {
4233       Sema::NestedNameSpecInfo IdInfo(QNNS->getAsIdentifier(),
4234                                       Q.getLocalBeginLoc(), Q.getLocalEndLoc(),
4235                                       ObjectType);
4236       if (SemaRef.BuildCXXNestedNameSpecifier(/*Scope=*/nullptr, IdInfo, false,
4237                                               SS, FirstQualifierInScope, false))
4238         return NestedNameSpecifierLoc();
4239       break;
4240     }
4241 
4242     case NestedNameSpecifier::Namespace: {
4243       NamespaceDecl *NS =
4244           cast_or_null<NamespaceDecl>(getDerived().TransformDecl(
4245               Q.getLocalBeginLoc(), QNNS->getAsNamespace()));
4246       SS.Extend(SemaRef.Context, NS, Q.getLocalBeginLoc(), Q.getLocalEndLoc());
4247       break;
4248     }
4249 
4250     case NestedNameSpecifier::NamespaceAlias: {
4251       NamespaceAliasDecl *Alias =
4252           cast_or_null<NamespaceAliasDecl>(getDerived().TransformDecl(
4253               Q.getLocalBeginLoc(), QNNS->getAsNamespaceAlias()));
4254       SS.Extend(SemaRef.Context, Alias, Q.getLocalBeginLoc(),
4255                 Q.getLocalEndLoc());
4256       break;
4257     }
4258 
4259     case NestedNameSpecifier::Global:
4260       // There is no meaningful transformation that one could perform on the
4261       // global scope.
4262       SS.MakeGlobal(SemaRef.Context, Q.getBeginLoc());
4263       break;
4264 
4265     case NestedNameSpecifier::Super: {
4266       CXXRecordDecl *RD =
4267           cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
4268               SourceLocation(), QNNS->getAsRecordDecl()));
4269       SS.MakeSuper(SemaRef.Context, RD, Q.getBeginLoc(), Q.getEndLoc());
4270       break;
4271     }
4272 
4273     case NestedNameSpecifier::TypeSpecWithTemplate:
4274     case NestedNameSpecifier::TypeSpec: {
4275       TypeLoc TL = TransformTypeInObjectScope(Q.getTypeLoc(), ObjectType,
4276                                               FirstQualifierInScope, SS);
4277 
4278       if (!TL)
4279         return NestedNameSpecifierLoc();
4280 
4281       QualType T = TL.getType();
4282       if (T->isDependentType() || T->isRecordType() ||
4283           (SemaRef.getLangOpts().CPlusPlus11 && T->isEnumeralType())) {
4284         if (T->isEnumeralType())
4285           SemaRef.Diag(TL.getBeginLoc(),
4286                        diag::warn_cxx98_compat_enum_nested_name_spec);
4287 
4288         if (const auto ETL = TL.getAs<ElaboratedTypeLoc>()) {
4289           SS.Adopt(ETL.getQualifierLoc());
4290           TL = ETL.getNamedTypeLoc();
4291         }
4292         SS.Extend(SemaRef.Context, /*FIXME:*/ SourceLocation(), TL,
4293                   Q.getLocalEndLoc());
4294         break;
4295       }
4296       // If the nested-name-specifier is an invalid type def, don't emit an
4297       // error because a previous error should have already been emitted.
4298       TypedefTypeLoc TTL = TL.getAsAdjusted<TypedefTypeLoc>();
4299       if (!TTL || !TTL.getTypedefNameDecl()->isInvalidDecl()) {
4300         SemaRef.Diag(TL.getBeginLoc(), diag::err_nested_name_spec_non_tag)
4301             << T << SS.getRange();
4302       }
4303       return NestedNameSpecifierLoc();
4304     }
4305     }
4306 
4307     // The qualifier-in-scope and object type only apply to the leftmost entity.
4308     FirstQualifierInScope = nullptr;
4309     ObjectType = QualType();
4310   }
4311 
4312   // Don't rebuild the nested-name-specifier if we don't have to.
4313   if (SS.getScopeRep() == NNS.getNestedNameSpecifier() &&
4314       !getDerived().AlwaysRebuild())
4315     return NNS;
4316 
4317   // If we can re-use the source-location data from the original
4318   // nested-name-specifier, do so.
4319   if (SS.location_size() == NNS.getDataLength() &&
4320       memcmp(SS.location_data(), NNS.getOpaqueData(), SS.location_size()) == 0)
4321     return NestedNameSpecifierLoc(SS.getScopeRep(), NNS.getOpaqueData());
4322 
4323   // Allocate new nested-name-specifier location information.
4324   return SS.getWithLocInContext(SemaRef.Context);
4325 }
4326 
4327 template<typename Derived>
4328 DeclarationNameInfo
4329 TreeTransform<Derived>
4330 ::TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo) {
4331   DeclarationName Name = NameInfo.getName();
4332   if (!Name)
4333     return DeclarationNameInfo();
4334 
4335   switch (Name.getNameKind()) {
4336   case DeclarationName::Identifier:
4337   case DeclarationName::ObjCZeroArgSelector:
4338   case DeclarationName::ObjCOneArgSelector:
4339   case DeclarationName::ObjCMultiArgSelector:
4340   case DeclarationName::CXXOperatorName:
4341   case DeclarationName::CXXLiteralOperatorName:
4342   case DeclarationName::CXXUsingDirective:
4343     return NameInfo;
4344 
4345   case DeclarationName::CXXDeductionGuideName: {
4346     TemplateDecl *OldTemplate = Name.getCXXDeductionGuideTemplate();
4347     TemplateDecl *NewTemplate = cast_or_null<TemplateDecl>(
4348         getDerived().TransformDecl(NameInfo.getLoc(), OldTemplate));
4349     if (!NewTemplate)
4350       return DeclarationNameInfo();
4351 
4352     DeclarationNameInfo NewNameInfo(NameInfo);
4353     NewNameInfo.setName(
4354         SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(NewTemplate));
4355     return NewNameInfo;
4356   }
4357 
4358   case DeclarationName::CXXConstructorName:
4359   case DeclarationName::CXXDestructorName:
4360   case DeclarationName::CXXConversionFunctionName: {
4361     TypeSourceInfo *NewTInfo;
4362     CanQualType NewCanTy;
4363     if (TypeSourceInfo *OldTInfo = NameInfo.getNamedTypeInfo()) {
4364       NewTInfo = getDerived().TransformType(OldTInfo);
4365       if (!NewTInfo)
4366         return DeclarationNameInfo();
4367       NewCanTy = SemaRef.Context.getCanonicalType(NewTInfo->getType());
4368     }
4369     else {
4370       NewTInfo = nullptr;
4371       TemporaryBase Rebase(*this, NameInfo.getLoc(), Name);
4372       QualType NewT = getDerived().TransformType(Name.getCXXNameType());
4373       if (NewT.isNull())
4374         return DeclarationNameInfo();
4375       NewCanTy = SemaRef.Context.getCanonicalType(NewT);
4376     }
4377 
4378     DeclarationName NewName
4379       = SemaRef.Context.DeclarationNames.getCXXSpecialName(Name.getNameKind(),
4380                                                            NewCanTy);
4381     DeclarationNameInfo NewNameInfo(NameInfo);
4382     NewNameInfo.setName(NewName);
4383     NewNameInfo.setNamedTypeInfo(NewTInfo);
4384     return NewNameInfo;
4385   }
4386   }
4387 
4388   llvm_unreachable("Unknown name kind.");
4389 }
4390 
4391 template<typename Derived>
4392 TemplateName
4393 TreeTransform<Derived>::TransformTemplateName(CXXScopeSpec &SS,
4394                                               TemplateName Name,
4395                                               SourceLocation NameLoc,
4396                                               QualType ObjectType,
4397                                               NamedDecl *FirstQualifierInScope,
4398                                               bool AllowInjectedClassName) {
4399   if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) {
4400     TemplateDecl *Template = QTN->getUnderlyingTemplate().getAsTemplateDecl();
4401     assert(Template && "qualified template name must refer to a template");
4402 
4403     TemplateDecl *TransTemplate
4404       = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
4405                                                               Template));
4406     if (!TransTemplate)
4407       return TemplateName();
4408 
4409     if (!getDerived().AlwaysRebuild() &&
4410         SS.getScopeRep() == QTN->getQualifier() &&
4411         TransTemplate == Template)
4412       return Name;
4413 
4414     return getDerived().RebuildTemplateName(SS, QTN->hasTemplateKeyword(),
4415                                             TransTemplate);
4416   }
4417 
4418   if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
4419     if (SS.getScopeRep()) {
4420       // These apply to the scope specifier, not the template.
4421       ObjectType = QualType();
4422       FirstQualifierInScope = nullptr;
4423     }
4424 
4425     if (!getDerived().AlwaysRebuild() &&
4426         SS.getScopeRep() == DTN->getQualifier() &&
4427         ObjectType.isNull())
4428       return Name;
4429 
4430     // FIXME: Preserve the location of the "template" keyword.
4431     SourceLocation TemplateKWLoc = NameLoc;
4432 
4433     if (DTN->isIdentifier()) {
4434       return getDerived().RebuildTemplateName(SS,
4435                                               TemplateKWLoc,
4436                                               *DTN->getIdentifier(),
4437                                               NameLoc,
4438                                               ObjectType,
4439                                               FirstQualifierInScope,
4440                                               AllowInjectedClassName);
4441     }
4442 
4443     return getDerived().RebuildTemplateName(SS, TemplateKWLoc,
4444                                             DTN->getOperator(), NameLoc,
4445                                             ObjectType, AllowInjectedClassName);
4446   }
4447 
4448   if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4449     TemplateDecl *TransTemplate
4450       = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
4451                                                               Template));
4452     if (!TransTemplate)
4453       return TemplateName();
4454 
4455     if (!getDerived().AlwaysRebuild() &&
4456         TransTemplate == Template)
4457       return Name;
4458 
4459     return TemplateName(TransTemplate);
4460   }
4461 
4462   if (SubstTemplateTemplateParmPackStorage *SubstPack
4463       = Name.getAsSubstTemplateTemplateParmPack()) {
4464     return getDerived().RebuildTemplateName(
4465         SubstPack->getArgumentPack(), SubstPack->getAssociatedDecl(),
4466         SubstPack->getIndex(), SubstPack->getFinal());
4467   }
4468 
4469   // These should be getting filtered out before they reach the AST.
4470   llvm_unreachable("overloaded function decl survived to here");
4471 }
4472 
4473 template<typename Derived>
4474 void TreeTransform<Derived>::InventTemplateArgumentLoc(
4475                                          const TemplateArgument &Arg,
4476                                          TemplateArgumentLoc &Output) {
4477   Output = getSema().getTrivialTemplateArgumentLoc(
4478       Arg, QualType(), getDerived().getBaseLocation());
4479 }
4480 
4481 template <typename Derived>
4482 bool TreeTransform<Derived>::TransformTemplateArgument(
4483     const TemplateArgumentLoc &Input, TemplateArgumentLoc &Output,
4484     bool Uneval) {
4485   const TemplateArgument &Arg = Input.getArgument();
4486   switch (Arg.getKind()) {
4487   case TemplateArgument::Null:
4488   case TemplateArgument::Pack:
4489     llvm_unreachable("Unexpected TemplateArgument");
4490 
4491   case TemplateArgument::Integral:
4492   case TemplateArgument::NullPtr:
4493   case TemplateArgument::Declaration: {
4494     // Transform a resolved template argument straight to a resolved template
4495     // argument. We get here when substituting into an already-substituted
4496     // template type argument during concept satisfaction checking.
4497     QualType T = Arg.getNonTypeTemplateArgumentType();
4498     QualType NewT = getDerived().TransformType(T);
4499     if (NewT.isNull())
4500       return true;
4501 
4502     ValueDecl *D = Arg.getKind() == TemplateArgument::Declaration
4503                        ? Arg.getAsDecl()
4504                        : nullptr;
4505     ValueDecl *NewD = D ? cast_or_null<ValueDecl>(getDerived().TransformDecl(
4506                               getDerived().getBaseLocation(), D))
4507                         : nullptr;
4508     if (D && !NewD)
4509       return true;
4510 
4511     if (NewT == T && D == NewD)
4512       Output = Input;
4513     else if (Arg.getKind() == TemplateArgument::Integral)
4514       Output = TemplateArgumentLoc(
4515           TemplateArgument(getSema().Context, Arg.getAsIntegral(), NewT),
4516           TemplateArgumentLocInfo());
4517     else if (Arg.getKind() == TemplateArgument::NullPtr)
4518       Output = TemplateArgumentLoc(TemplateArgument(NewT, /*IsNullPtr=*/true),
4519                                    TemplateArgumentLocInfo());
4520     else
4521       Output = TemplateArgumentLoc(TemplateArgument(NewD, NewT),
4522                                    TemplateArgumentLocInfo());
4523 
4524     return false;
4525   }
4526 
4527   case TemplateArgument::Type: {
4528     TypeSourceInfo *DI = Input.getTypeSourceInfo();
4529     if (!DI)
4530       DI = InventTypeSourceInfo(Input.getArgument().getAsType());
4531 
4532     DI = getDerived().TransformType(DI);
4533     if (!DI)
4534       return true;
4535 
4536     Output = TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4537     return false;
4538   }
4539 
4540   case TemplateArgument::Template: {
4541     NestedNameSpecifierLoc QualifierLoc = Input.getTemplateQualifierLoc();
4542     if (QualifierLoc) {
4543       QualifierLoc = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc);
4544       if (!QualifierLoc)
4545         return true;
4546     }
4547 
4548     CXXScopeSpec SS;
4549     SS.Adopt(QualifierLoc);
4550     TemplateName Template = getDerived().TransformTemplateName(
4551         SS, Arg.getAsTemplate(), Input.getTemplateNameLoc());
4552     if (Template.isNull())
4553       return true;
4554 
4555     Output = TemplateArgumentLoc(SemaRef.Context, TemplateArgument(Template),
4556                                  QualifierLoc, Input.getTemplateNameLoc());
4557     return false;
4558   }
4559 
4560   case TemplateArgument::TemplateExpansion:
4561     llvm_unreachable("Caller should expand pack expansions");
4562 
4563   case TemplateArgument::Expression: {
4564     // Template argument expressions are constant expressions.
4565     EnterExpressionEvaluationContext Unevaluated(
4566         getSema(),
4567         Uneval ? Sema::ExpressionEvaluationContext::Unevaluated
4568                : Sema::ExpressionEvaluationContext::ConstantEvaluated,
4569         Sema::ReuseLambdaContextDecl, /*ExprContext=*/
4570         Sema::ExpressionEvaluationContextRecord::EK_TemplateArgument);
4571 
4572     Expr *InputExpr = Input.getSourceExpression();
4573     if (!InputExpr)
4574       InputExpr = Input.getArgument().getAsExpr();
4575 
4576     ExprResult E = getDerived().TransformExpr(InputExpr);
4577     E = SemaRef.ActOnConstantExpression(E);
4578     if (E.isInvalid())
4579       return true;
4580     Output = TemplateArgumentLoc(TemplateArgument(E.get()), E.get());
4581     return false;
4582   }
4583   }
4584 
4585   // Work around bogus GCC warning
4586   return true;
4587 }
4588 
4589 /// Iterator adaptor that invents template argument location information
4590 /// for each of the template arguments in its underlying iterator.
4591 template<typename Derived, typename InputIterator>
4592 class TemplateArgumentLocInventIterator {
4593   TreeTransform<Derived> &Self;
4594   InputIterator Iter;
4595 
4596 public:
4597   typedef TemplateArgumentLoc value_type;
4598   typedef TemplateArgumentLoc reference;
4599   typedef typename std::iterator_traits<InputIterator>::difference_type
4600     difference_type;
4601   typedef std::input_iterator_tag iterator_category;
4602 
4603   class pointer {
4604     TemplateArgumentLoc Arg;
4605 
4606   public:
4607     explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
4608 
4609     const TemplateArgumentLoc *operator->() const { return &Arg; }
4610   };
4611 
4612   TemplateArgumentLocInventIterator() { }
4613 
4614   explicit TemplateArgumentLocInventIterator(TreeTransform<Derived> &Self,
4615                                              InputIterator Iter)
4616     : Self(Self), Iter(Iter) { }
4617 
4618   TemplateArgumentLocInventIterator &operator++() {
4619     ++Iter;
4620     return *this;
4621   }
4622 
4623   TemplateArgumentLocInventIterator operator++(int) {
4624     TemplateArgumentLocInventIterator Old(*this);
4625     ++(*this);
4626     return Old;
4627   }
4628 
4629   reference operator*() const {
4630     TemplateArgumentLoc Result;
4631     Self.InventTemplateArgumentLoc(*Iter, Result);
4632     return Result;
4633   }
4634 
4635   pointer operator->() const { return pointer(**this); }
4636 
4637   friend bool operator==(const TemplateArgumentLocInventIterator &X,
4638                          const TemplateArgumentLocInventIterator &Y) {
4639     return X.Iter == Y.Iter;
4640   }
4641 
4642   friend bool operator!=(const TemplateArgumentLocInventIterator &X,
4643                          const TemplateArgumentLocInventIterator &Y) {
4644     return X.Iter != Y.Iter;
4645   }
4646 };
4647 
4648 template<typename Derived>
4649 template<typename InputIterator>
4650 bool TreeTransform<Derived>::TransformTemplateArguments(
4651     InputIterator First, InputIterator Last, TemplateArgumentListInfo &Outputs,
4652     bool Uneval) {
4653   for (; First != Last; ++First) {
4654     TemplateArgumentLoc Out;
4655     TemplateArgumentLoc In = *First;
4656 
4657     if (In.getArgument().getKind() == TemplateArgument::Pack) {
4658       // Unpack argument packs, which we translate them into separate
4659       // arguments.
4660       // FIXME: We could do much better if we could guarantee that the
4661       // TemplateArgumentLocInfo for the pack expansion would be usable for
4662       // all of the template arguments in the argument pack.
4663       typedef TemplateArgumentLocInventIterator<Derived,
4664                                                 TemplateArgument::pack_iterator>
4665         PackLocIterator;
4666       if (TransformTemplateArguments(PackLocIterator(*this,
4667                                                  In.getArgument().pack_begin()),
4668                                      PackLocIterator(*this,
4669                                                    In.getArgument().pack_end()),
4670                                      Outputs, Uneval))
4671         return true;
4672 
4673       continue;
4674     }
4675 
4676     if (In.getArgument().isPackExpansion()) {
4677       // We have a pack expansion, for which we will be substituting into
4678       // the pattern.
4679       SourceLocation Ellipsis;
4680       std::optional<unsigned> OrigNumExpansions;
4681       TemplateArgumentLoc Pattern
4682         = getSema().getTemplateArgumentPackExpansionPattern(
4683               In, Ellipsis, OrigNumExpansions);
4684 
4685       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4686       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
4687       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
4688 
4689       // Determine whether the set of unexpanded parameter packs can and should
4690       // be expanded.
4691       bool Expand = true;
4692       bool RetainExpansion = false;
4693       std::optional<unsigned> NumExpansions = OrigNumExpansions;
4694       if (getDerived().TryExpandParameterPacks(Ellipsis,
4695                                                Pattern.getSourceRange(),
4696                                                Unexpanded,
4697                                                Expand,
4698                                                RetainExpansion,
4699                                                NumExpansions))
4700         return true;
4701 
4702       if (!Expand) {
4703         // The transform has determined that we should perform a simple
4704         // transformation on the pack expansion, producing another pack
4705         // expansion.
4706         TemplateArgumentLoc OutPattern;
4707         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4708         if (getDerived().TransformTemplateArgument(Pattern, OutPattern, Uneval))
4709           return true;
4710 
4711         Out = getDerived().RebuildPackExpansion(OutPattern, Ellipsis,
4712                                                 NumExpansions);
4713         if (Out.getArgument().isNull())
4714           return true;
4715 
4716         Outputs.addArgument(Out);
4717         continue;
4718       }
4719 
4720       // The transform has determined that we should perform an elementwise
4721       // expansion of the pattern. Do so.
4722       for (unsigned I = 0; I != *NumExpansions; ++I) {
4723         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
4724 
4725         if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4726           return true;
4727 
4728         if (Out.getArgument().containsUnexpandedParameterPack()) {
4729           Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4730                                                   OrigNumExpansions);
4731           if (Out.getArgument().isNull())
4732             return true;
4733         }
4734 
4735         Outputs.addArgument(Out);
4736       }
4737 
4738       // If we're supposed to retain a pack expansion, do so by temporarily
4739       // forgetting the partially-substituted parameter pack.
4740       if (RetainExpansion) {
4741         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
4742 
4743         if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4744           return true;
4745 
4746         Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4747                                                 OrigNumExpansions);
4748         if (Out.getArgument().isNull())
4749           return true;
4750 
4751         Outputs.addArgument(Out);
4752       }
4753 
4754       continue;
4755     }
4756 
4757     // The simple case:
4758     if (getDerived().TransformTemplateArgument(In, Out, Uneval))
4759       return true;
4760 
4761     Outputs.addArgument(Out);
4762   }
4763 
4764   return false;
4765 
4766 }
4767 
4768 //===----------------------------------------------------------------------===//
4769 // Type transformation
4770 //===----------------------------------------------------------------------===//
4771 
4772 template<typename Derived>
4773 QualType TreeTransform<Derived>::TransformType(QualType T) {
4774   if (getDerived().AlreadyTransformed(T))
4775     return T;
4776 
4777   // Temporary workaround.  All of these transformations should
4778   // eventually turn into transformations on TypeLocs.
4779   TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4780                                                 getDerived().getBaseLocation());
4781 
4782   TypeSourceInfo *NewDI = getDerived().TransformType(DI);
4783 
4784   if (!NewDI)
4785     return QualType();
4786 
4787   return NewDI->getType();
4788 }
4789 
4790 template<typename Derived>
4791 TypeSourceInfo *TreeTransform<Derived>::TransformType(TypeSourceInfo *DI) {
4792   // Refine the base location to the type's location.
4793   TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4794                        getDerived().getBaseEntity());
4795   if (getDerived().AlreadyTransformed(DI->getType()))
4796     return DI;
4797 
4798   TypeLocBuilder TLB;
4799 
4800   TypeLoc TL = DI->getTypeLoc();
4801   TLB.reserve(TL.getFullDataSize());
4802 
4803   QualType Result = getDerived().TransformType(TLB, TL);
4804   if (Result.isNull())
4805     return nullptr;
4806 
4807   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4808 }
4809 
4810 template<typename Derived>
4811 QualType
4812 TreeTransform<Derived>::TransformType(TypeLocBuilder &TLB, TypeLoc T) {
4813   switch (T.getTypeLocClass()) {
4814 #define ABSTRACT_TYPELOC(CLASS, PARENT)
4815 #define TYPELOC(CLASS, PARENT)                                                 \
4816   case TypeLoc::CLASS:                                                         \
4817     return getDerived().Transform##CLASS##Type(TLB,                            \
4818                                                T.castAs<CLASS##TypeLoc>());
4819 #include "clang/AST/TypeLocNodes.def"
4820   }
4821 
4822   llvm_unreachable("unhandled type loc!");
4823 }
4824 
4825 template<typename Derived>
4826 QualType TreeTransform<Derived>::TransformTypeWithDeducedTST(QualType T) {
4827   if (!isa<DependentNameType>(T))
4828     return TransformType(T);
4829 
4830   if (getDerived().AlreadyTransformed(T))
4831     return T;
4832   TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4833                                                 getDerived().getBaseLocation());
4834   TypeSourceInfo *NewDI = getDerived().TransformTypeWithDeducedTST(DI);
4835   return NewDI ? NewDI->getType() : QualType();
4836 }
4837 
4838 template<typename Derived>
4839 TypeSourceInfo *
4840 TreeTransform<Derived>::TransformTypeWithDeducedTST(TypeSourceInfo *DI) {
4841   if (!isa<DependentNameType>(DI->getType()))
4842     return TransformType(DI);
4843 
4844   // Refine the base location to the type's location.
4845   TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4846                        getDerived().getBaseEntity());
4847   if (getDerived().AlreadyTransformed(DI->getType()))
4848     return DI;
4849 
4850   TypeLocBuilder TLB;
4851 
4852   TypeLoc TL = DI->getTypeLoc();
4853   TLB.reserve(TL.getFullDataSize());
4854 
4855   auto QTL = TL.getAs<QualifiedTypeLoc>();
4856   if (QTL)
4857     TL = QTL.getUnqualifiedLoc();
4858 
4859   auto DNTL = TL.castAs<DependentNameTypeLoc>();
4860 
4861   QualType Result = getDerived().TransformDependentNameType(
4862       TLB, DNTL, /*DeducedTSTContext*/true);
4863   if (Result.isNull())
4864     return nullptr;
4865 
4866   if (QTL) {
4867     Result = getDerived().RebuildQualifiedType(Result, QTL);
4868     if (Result.isNull())
4869       return nullptr;
4870     TLB.TypeWasModifiedSafely(Result);
4871   }
4872 
4873   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4874 }
4875 
4876 template<typename Derived>
4877 QualType
4878 TreeTransform<Derived>::TransformQualifiedType(TypeLocBuilder &TLB,
4879                                                QualifiedTypeLoc T) {
4880   QualType Result;
4881   TypeLoc UnqualTL = T.getUnqualifiedLoc();
4882   auto SuppressObjCLifetime =
4883       T.getType().getLocalQualifiers().hasObjCLifetime();
4884   if (auto TTP = UnqualTL.getAs<TemplateTypeParmTypeLoc>()) {
4885     Result = getDerived().TransformTemplateTypeParmType(TLB, TTP,
4886                                                         SuppressObjCLifetime);
4887   } else if (auto STTP = UnqualTL.getAs<SubstTemplateTypeParmPackTypeLoc>()) {
4888     Result = getDerived().TransformSubstTemplateTypeParmPackType(
4889         TLB, STTP, SuppressObjCLifetime);
4890   } else {
4891     Result = getDerived().TransformType(TLB, UnqualTL);
4892   }
4893 
4894   if (Result.isNull())
4895     return QualType();
4896 
4897   Result = getDerived().RebuildQualifiedType(Result, T);
4898 
4899   if (Result.isNull())
4900     return QualType();
4901 
4902   // RebuildQualifiedType might have updated the type, but not in a way
4903   // that invalidates the TypeLoc. (There's no location information for
4904   // qualifiers.)
4905   TLB.TypeWasModifiedSafely(Result);
4906 
4907   return Result;
4908 }
4909 
4910 template <typename Derived>
4911 QualType TreeTransform<Derived>::RebuildQualifiedType(QualType T,
4912                                                       QualifiedTypeLoc TL) {
4913 
4914   SourceLocation Loc = TL.getBeginLoc();
4915   Qualifiers Quals = TL.getType().getLocalQualifiers();
4916 
4917   if ((T.getAddressSpace() != LangAS::Default &&
4918        Quals.getAddressSpace() != LangAS::Default) &&
4919       T.getAddressSpace() != Quals.getAddressSpace()) {
4920     SemaRef.Diag(Loc, diag::err_address_space_mismatch_templ_inst)
4921         << TL.getType() << T;
4922     return QualType();
4923   }
4924 
4925   // C++ [dcl.fct]p7:
4926   //   [When] adding cv-qualifications on top of the function type [...] the
4927   //   cv-qualifiers are ignored.
4928   if (T->isFunctionType()) {
4929     T = SemaRef.getASTContext().getAddrSpaceQualType(T,
4930                                                      Quals.getAddressSpace());
4931     return T;
4932   }
4933 
4934   // C++ [dcl.ref]p1:
4935   //   when the cv-qualifiers are introduced through the use of a typedef-name
4936   //   or decltype-specifier [...] the cv-qualifiers are ignored.
4937   // Note that [dcl.ref]p1 lists all cases in which cv-qualifiers can be
4938   // applied to a reference type.
4939   if (T->isReferenceType()) {
4940     // The only qualifier that applies to a reference type is restrict.
4941     if (!Quals.hasRestrict())
4942       return T;
4943     Quals = Qualifiers::fromCVRMask(Qualifiers::Restrict);
4944   }
4945 
4946   // Suppress Objective-C lifetime qualifiers if they don't make sense for the
4947   // resulting type.
4948   if (Quals.hasObjCLifetime()) {
4949     if (!T->isObjCLifetimeType() && !T->isDependentType())
4950       Quals.removeObjCLifetime();
4951     else if (T.getObjCLifetime()) {
4952       // Objective-C ARC:
4953       //   A lifetime qualifier applied to a substituted template parameter
4954       //   overrides the lifetime qualifier from the template argument.
4955       const AutoType *AutoTy;
4956       if ((AutoTy = dyn_cast<AutoType>(T)) && AutoTy->isDeduced()) {
4957         // 'auto' types behave the same way as template parameters.
4958         QualType Deduced = AutoTy->getDeducedType();
4959         Qualifiers Qs = Deduced.getQualifiers();
4960         Qs.removeObjCLifetime();
4961         Deduced =
4962             SemaRef.Context.getQualifiedType(Deduced.getUnqualifiedType(), Qs);
4963         T = SemaRef.Context.getAutoType(Deduced, AutoTy->getKeyword(),
4964                                         AutoTy->isDependentType(),
4965                                         /*isPack=*/false,
4966                                         AutoTy->getTypeConstraintConcept(),
4967                                         AutoTy->getTypeConstraintArguments());
4968       } else {
4969         // Otherwise, complain about the addition of a qualifier to an
4970         // already-qualified type.
4971         // FIXME: Why is this check not in Sema::BuildQualifiedType?
4972         SemaRef.Diag(Loc, diag::err_attr_objc_ownership_redundant) << T;
4973         Quals.removeObjCLifetime();
4974       }
4975     }
4976   }
4977 
4978   return SemaRef.BuildQualifiedType(T, Loc, Quals);
4979 }
4980 
4981 template<typename Derived>
4982 TypeLoc
4983 TreeTransform<Derived>::TransformTypeInObjectScope(TypeLoc TL,
4984                                                    QualType ObjectType,
4985                                                    NamedDecl *UnqualLookup,
4986                                                    CXXScopeSpec &SS) {
4987   if (getDerived().AlreadyTransformed(TL.getType()))
4988     return TL;
4989 
4990   TypeSourceInfo *TSI =
4991       TransformTSIInObjectScope(TL, ObjectType, UnqualLookup, SS);
4992   if (TSI)
4993     return TSI->getTypeLoc();
4994   return TypeLoc();
4995 }
4996 
4997 template<typename Derived>
4998 TypeSourceInfo *
4999 TreeTransform<Derived>::TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
5000                                                    QualType ObjectType,
5001                                                    NamedDecl *UnqualLookup,
5002                                                    CXXScopeSpec &SS) {
5003   if (getDerived().AlreadyTransformed(TSInfo->getType()))
5004     return TSInfo;
5005 
5006   return TransformTSIInObjectScope(TSInfo->getTypeLoc(), ObjectType,
5007                                    UnqualLookup, SS);
5008 }
5009 
5010 template <typename Derived>
5011 TypeSourceInfo *TreeTransform<Derived>::TransformTSIInObjectScope(
5012     TypeLoc TL, QualType ObjectType, NamedDecl *UnqualLookup,
5013     CXXScopeSpec &SS) {
5014   QualType T = TL.getType();
5015   assert(!getDerived().AlreadyTransformed(T));
5016 
5017   TypeLocBuilder TLB;
5018   QualType Result;
5019 
5020   if (isa<TemplateSpecializationType>(T)) {
5021     TemplateSpecializationTypeLoc SpecTL =
5022         TL.castAs<TemplateSpecializationTypeLoc>();
5023 
5024     TemplateName Template = getDerived().TransformTemplateName(
5025         SS, SpecTL.getTypePtr()->getTemplateName(), SpecTL.getTemplateNameLoc(),
5026         ObjectType, UnqualLookup, /*AllowInjectedClassName*/true);
5027     if (Template.isNull())
5028       return nullptr;
5029 
5030     Result = getDerived().TransformTemplateSpecializationType(TLB, SpecTL,
5031                                                               Template);
5032   } else if (isa<DependentTemplateSpecializationType>(T)) {
5033     DependentTemplateSpecializationTypeLoc SpecTL =
5034         TL.castAs<DependentTemplateSpecializationTypeLoc>();
5035 
5036     TemplateName Template
5037       = getDerived().RebuildTemplateName(SS,
5038                                          SpecTL.getTemplateKeywordLoc(),
5039                                          *SpecTL.getTypePtr()->getIdentifier(),
5040                                          SpecTL.getTemplateNameLoc(),
5041                                          ObjectType, UnqualLookup,
5042                                          /*AllowInjectedClassName*/true);
5043     if (Template.isNull())
5044       return nullptr;
5045 
5046     Result = getDerived().TransformDependentTemplateSpecializationType(TLB,
5047                                                                        SpecTL,
5048                                                                        Template,
5049                                                                        SS);
5050   } else {
5051     // Nothing special needs to be done for these.
5052     Result = getDerived().TransformType(TLB, TL);
5053   }
5054 
5055   if (Result.isNull())
5056     return nullptr;
5057 
5058   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
5059 }
5060 
5061 template <class TyLoc> static inline
5062 QualType TransformTypeSpecType(TypeLocBuilder &TLB, TyLoc T) {
5063   TyLoc NewT = TLB.push<TyLoc>(T.getType());
5064   NewT.setNameLoc(T.getNameLoc());
5065   return T.getType();
5066 }
5067 
5068 template<typename Derived>
5069 QualType TreeTransform<Derived>::TransformBuiltinType(TypeLocBuilder &TLB,
5070                                                       BuiltinTypeLoc T) {
5071   BuiltinTypeLoc NewT = TLB.push<BuiltinTypeLoc>(T.getType());
5072   NewT.setBuiltinLoc(T.getBuiltinLoc());
5073   if (T.needsExtraLocalData())
5074     NewT.getWrittenBuiltinSpecs() = T.getWrittenBuiltinSpecs();
5075   return T.getType();
5076 }
5077 
5078 template<typename Derived>
5079 QualType TreeTransform<Derived>::TransformComplexType(TypeLocBuilder &TLB,
5080                                                       ComplexTypeLoc T) {
5081   // FIXME: recurse?
5082   return TransformTypeSpecType(TLB, T);
5083 }
5084 
5085 template <typename Derived>
5086 QualType TreeTransform<Derived>::TransformAdjustedType(TypeLocBuilder &TLB,
5087                                                        AdjustedTypeLoc TL) {
5088   // Adjustments applied during transformation are handled elsewhere.
5089   return getDerived().TransformType(TLB, TL.getOriginalLoc());
5090 }
5091 
5092 template<typename Derived>
5093 QualType TreeTransform<Derived>::TransformDecayedType(TypeLocBuilder &TLB,
5094                                                       DecayedTypeLoc TL) {
5095   QualType OriginalType = getDerived().TransformType(TLB, TL.getOriginalLoc());
5096   if (OriginalType.isNull())
5097     return QualType();
5098 
5099   QualType Result = TL.getType();
5100   if (getDerived().AlwaysRebuild() ||
5101       OriginalType != TL.getOriginalLoc().getType())
5102     Result = SemaRef.Context.getDecayedType(OriginalType);
5103   TLB.push<DecayedTypeLoc>(Result);
5104   // Nothing to set for DecayedTypeLoc.
5105   return Result;
5106 }
5107 
5108 template<typename Derived>
5109 QualType TreeTransform<Derived>::TransformPointerType(TypeLocBuilder &TLB,
5110                                                       PointerTypeLoc TL) {
5111   QualType PointeeType
5112     = getDerived().TransformType(TLB, TL.getPointeeLoc());
5113   if (PointeeType.isNull())
5114     return QualType();
5115 
5116   QualType Result = TL.getType();
5117   if (PointeeType->getAs<ObjCObjectType>()) {
5118     // A dependent pointer type 'T *' has is being transformed such
5119     // that an Objective-C class type is being replaced for 'T'. The
5120     // resulting pointer type is an ObjCObjectPointerType, not a
5121     // PointerType.
5122     Result = SemaRef.Context.getObjCObjectPointerType(PointeeType);
5123 
5124     ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
5125     NewT.setStarLoc(TL.getStarLoc());
5126     return Result;
5127   }
5128 
5129   if (getDerived().AlwaysRebuild() ||
5130       PointeeType != TL.getPointeeLoc().getType()) {
5131     Result = getDerived().RebuildPointerType(PointeeType, TL.getSigilLoc());
5132     if (Result.isNull())
5133       return QualType();
5134   }
5135 
5136   // Objective-C ARC can add lifetime qualifiers to the type that we're
5137   // pointing to.
5138   TLB.TypeWasModifiedSafely(Result->getPointeeType());
5139 
5140   PointerTypeLoc NewT = TLB.push<PointerTypeLoc>(Result);
5141   NewT.setSigilLoc(TL.getSigilLoc());
5142   return Result;
5143 }
5144 
5145 template<typename Derived>
5146 QualType
5147 TreeTransform<Derived>::TransformBlockPointerType(TypeLocBuilder &TLB,
5148                                                   BlockPointerTypeLoc TL) {
5149   QualType PointeeType
5150     = getDerived().TransformType(TLB, TL.getPointeeLoc());
5151   if (PointeeType.isNull())
5152     return QualType();
5153 
5154   QualType Result = TL.getType();
5155   if (getDerived().AlwaysRebuild() ||
5156       PointeeType != TL.getPointeeLoc().getType()) {
5157     Result = getDerived().RebuildBlockPointerType(PointeeType,
5158                                                   TL.getSigilLoc());
5159     if (Result.isNull())
5160       return QualType();
5161   }
5162 
5163   BlockPointerTypeLoc NewT = TLB.push<BlockPointerTypeLoc>(Result);
5164   NewT.setSigilLoc(TL.getSigilLoc());
5165   return Result;
5166 }
5167 
5168 /// Transforms a reference type.  Note that somewhat paradoxically we
5169 /// don't care whether the type itself is an l-value type or an r-value
5170 /// type;  we only care if the type was *written* as an l-value type
5171 /// or an r-value type.
5172 template<typename Derived>
5173 QualType
5174 TreeTransform<Derived>::TransformReferenceType(TypeLocBuilder &TLB,
5175                                                ReferenceTypeLoc TL) {
5176   const ReferenceType *T = TL.getTypePtr();
5177 
5178   // Note that this works with the pointee-as-written.
5179   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
5180   if (PointeeType.isNull())
5181     return QualType();
5182 
5183   QualType Result = TL.getType();
5184   if (getDerived().AlwaysRebuild() ||
5185       PointeeType != T->getPointeeTypeAsWritten()) {
5186     Result = getDerived().RebuildReferenceType(PointeeType,
5187                                                T->isSpelledAsLValue(),
5188                                                TL.getSigilLoc());
5189     if (Result.isNull())
5190       return QualType();
5191   }
5192 
5193   // Objective-C ARC can add lifetime qualifiers to the type that we're
5194   // referring to.
5195   TLB.TypeWasModifiedSafely(
5196       Result->castAs<ReferenceType>()->getPointeeTypeAsWritten());
5197 
5198   // r-value references can be rebuilt as l-value references.
5199   ReferenceTypeLoc NewTL;
5200   if (isa<LValueReferenceType>(Result))
5201     NewTL = TLB.push<LValueReferenceTypeLoc>(Result);
5202   else
5203     NewTL = TLB.push<RValueReferenceTypeLoc>(Result);
5204   NewTL.setSigilLoc(TL.getSigilLoc());
5205 
5206   return Result;
5207 }
5208 
5209 template<typename Derived>
5210 QualType
5211 TreeTransform<Derived>::TransformLValueReferenceType(TypeLocBuilder &TLB,
5212                                                  LValueReferenceTypeLoc TL) {
5213   return TransformReferenceType(TLB, TL);
5214 }
5215 
5216 template<typename Derived>
5217 QualType
5218 TreeTransform<Derived>::TransformRValueReferenceType(TypeLocBuilder &TLB,
5219                                                  RValueReferenceTypeLoc TL) {
5220   return TransformReferenceType(TLB, TL);
5221 }
5222 
5223 template<typename Derived>
5224 QualType
5225 TreeTransform<Derived>::TransformMemberPointerType(TypeLocBuilder &TLB,
5226                                                    MemberPointerTypeLoc TL) {
5227   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
5228   if (PointeeType.isNull())
5229     return QualType();
5230 
5231   TypeSourceInfo* OldClsTInfo = TL.getClassTInfo();
5232   TypeSourceInfo *NewClsTInfo = nullptr;
5233   if (OldClsTInfo) {
5234     NewClsTInfo = getDerived().TransformType(OldClsTInfo);
5235     if (!NewClsTInfo)
5236       return QualType();
5237   }
5238 
5239   const MemberPointerType *T = TL.getTypePtr();
5240   QualType OldClsType = QualType(T->getClass(), 0);
5241   QualType NewClsType;
5242   if (NewClsTInfo)
5243     NewClsType = NewClsTInfo->getType();
5244   else {
5245     NewClsType = getDerived().TransformType(OldClsType);
5246     if (NewClsType.isNull())
5247       return QualType();
5248   }
5249 
5250   QualType Result = TL.getType();
5251   if (getDerived().AlwaysRebuild() ||
5252       PointeeType != T->getPointeeType() ||
5253       NewClsType != OldClsType) {
5254     Result = getDerived().RebuildMemberPointerType(PointeeType, NewClsType,
5255                                                    TL.getStarLoc());
5256     if (Result.isNull())
5257       return QualType();
5258   }
5259 
5260   // If we had to adjust the pointee type when building a member pointer, make
5261   // sure to push TypeLoc info for it.
5262   const MemberPointerType *MPT = Result->getAs<MemberPointerType>();
5263   if (MPT && PointeeType != MPT->getPointeeType()) {
5264     assert(isa<AdjustedType>(MPT->getPointeeType()));
5265     TLB.push<AdjustedTypeLoc>(MPT->getPointeeType());
5266   }
5267 
5268   MemberPointerTypeLoc NewTL = TLB.push<MemberPointerTypeLoc>(Result);
5269   NewTL.setSigilLoc(TL.getSigilLoc());
5270   NewTL.setClassTInfo(NewClsTInfo);
5271 
5272   return Result;
5273 }
5274 
5275 template<typename Derived>
5276 QualType
5277 TreeTransform<Derived>::TransformConstantArrayType(TypeLocBuilder &TLB,
5278                                                    ConstantArrayTypeLoc TL) {
5279   const ConstantArrayType *T = TL.getTypePtr();
5280   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5281   if (ElementType.isNull())
5282     return QualType();
5283 
5284   // Prefer the expression from the TypeLoc;  the other may have been uniqued.
5285   Expr *OldSize = TL.getSizeExpr();
5286   if (!OldSize)
5287     OldSize = const_cast<Expr*>(T->getSizeExpr());
5288   Expr *NewSize = nullptr;
5289   if (OldSize) {
5290     EnterExpressionEvaluationContext Unevaluated(
5291         SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5292     NewSize = getDerived().TransformExpr(OldSize).template getAs<Expr>();
5293     NewSize = SemaRef.ActOnConstantExpression(NewSize).get();
5294   }
5295 
5296   QualType Result = TL.getType();
5297   if (getDerived().AlwaysRebuild() ||
5298       ElementType != T->getElementType() ||
5299       (T->getSizeExpr() && NewSize != OldSize)) {
5300     Result = getDerived().RebuildConstantArrayType(ElementType,
5301                                                    T->getSizeModifier(),
5302                                                    T->getSize(), NewSize,
5303                                              T->getIndexTypeCVRQualifiers(),
5304                                                    TL.getBracketsRange());
5305     if (Result.isNull())
5306       return QualType();
5307   }
5308 
5309   // We might have either a ConstantArrayType or a VariableArrayType now:
5310   // a ConstantArrayType is allowed to have an element type which is a
5311   // VariableArrayType if the type is dependent.  Fortunately, all array
5312   // types have the same location layout.
5313   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
5314   NewTL.setLBracketLoc(TL.getLBracketLoc());
5315   NewTL.setRBracketLoc(TL.getRBracketLoc());
5316   NewTL.setSizeExpr(NewSize);
5317 
5318   return Result;
5319 }
5320 
5321 template<typename Derived>
5322 QualType TreeTransform<Derived>::TransformIncompleteArrayType(
5323                                               TypeLocBuilder &TLB,
5324                                               IncompleteArrayTypeLoc TL) {
5325   const IncompleteArrayType *T = TL.getTypePtr();
5326   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5327   if (ElementType.isNull())
5328     return QualType();
5329 
5330   QualType Result = TL.getType();
5331   if (getDerived().AlwaysRebuild() ||
5332       ElementType != T->getElementType()) {
5333     Result = getDerived().RebuildIncompleteArrayType(ElementType,
5334                                                      T->getSizeModifier(),
5335                                            T->getIndexTypeCVRQualifiers(),
5336                                                      TL.getBracketsRange());
5337     if (Result.isNull())
5338       return QualType();
5339   }
5340 
5341   IncompleteArrayTypeLoc NewTL = TLB.push<IncompleteArrayTypeLoc>(Result);
5342   NewTL.setLBracketLoc(TL.getLBracketLoc());
5343   NewTL.setRBracketLoc(TL.getRBracketLoc());
5344   NewTL.setSizeExpr(nullptr);
5345 
5346   return Result;
5347 }
5348 
5349 template<typename Derived>
5350 QualType
5351 TreeTransform<Derived>::TransformVariableArrayType(TypeLocBuilder &TLB,
5352                                                    VariableArrayTypeLoc TL) {
5353   const VariableArrayType *T = TL.getTypePtr();
5354   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5355   if (ElementType.isNull())
5356     return QualType();
5357 
5358   ExprResult SizeResult;
5359   {
5360     EnterExpressionEvaluationContext Context(
5361         SemaRef, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
5362     SizeResult = getDerived().TransformExpr(T->getSizeExpr());
5363   }
5364   if (SizeResult.isInvalid())
5365     return QualType();
5366   SizeResult =
5367       SemaRef.ActOnFinishFullExpr(SizeResult.get(), /*DiscardedValue*/ false);
5368   if (SizeResult.isInvalid())
5369     return QualType();
5370 
5371   Expr *Size = SizeResult.get();
5372 
5373   QualType Result = TL.getType();
5374   if (getDerived().AlwaysRebuild() ||
5375       ElementType != T->getElementType() ||
5376       Size != T->getSizeExpr()) {
5377     Result = getDerived().RebuildVariableArrayType(ElementType,
5378                                                    T->getSizeModifier(),
5379                                                    Size,
5380                                              T->getIndexTypeCVRQualifiers(),
5381                                                    TL.getBracketsRange());
5382     if (Result.isNull())
5383       return QualType();
5384   }
5385 
5386   // We might have constant size array now, but fortunately it has the same
5387   // location layout.
5388   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
5389   NewTL.setLBracketLoc(TL.getLBracketLoc());
5390   NewTL.setRBracketLoc(TL.getRBracketLoc());
5391   NewTL.setSizeExpr(Size);
5392 
5393   return Result;
5394 }
5395 
5396 template<typename Derived>
5397 QualType
5398 TreeTransform<Derived>::TransformDependentSizedArrayType(TypeLocBuilder &TLB,
5399                                              DependentSizedArrayTypeLoc TL) {
5400   const DependentSizedArrayType *T = TL.getTypePtr();
5401   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5402   if (ElementType.isNull())
5403     return QualType();
5404 
5405   // Array bounds are constant expressions.
5406   EnterExpressionEvaluationContext Unevaluated(
5407       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5408 
5409   // Prefer the expression from the TypeLoc;  the other may have been uniqued.
5410   Expr *origSize = TL.getSizeExpr();
5411   if (!origSize) origSize = T->getSizeExpr();
5412 
5413   ExprResult sizeResult
5414     = getDerived().TransformExpr(origSize);
5415   sizeResult = SemaRef.ActOnConstantExpression(sizeResult);
5416   if (sizeResult.isInvalid())
5417     return QualType();
5418 
5419   Expr *size = sizeResult.get();
5420 
5421   QualType Result = TL.getType();
5422   if (getDerived().AlwaysRebuild() ||
5423       ElementType != T->getElementType() ||
5424       size != origSize) {
5425     Result = getDerived().RebuildDependentSizedArrayType(ElementType,
5426                                                          T->getSizeModifier(),
5427                                                          size,
5428                                                 T->getIndexTypeCVRQualifiers(),
5429                                                         TL.getBracketsRange());
5430     if (Result.isNull())
5431       return QualType();
5432   }
5433 
5434   // We might have any sort of array type now, but fortunately they
5435   // all have the same location layout.
5436   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
5437   NewTL.setLBracketLoc(TL.getLBracketLoc());
5438   NewTL.setRBracketLoc(TL.getRBracketLoc());
5439   NewTL.setSizeExpr(size);
5440 
5441   return Result;
5442 }
5443 
5444 template <typename Derived>
5445 QualType TreeTransform<Derived>::TransformDependentVectorType(
5446     TypeLocBuilder &TLB, DependentVectorTypeLoc TL) {
5447   const DependentVectorType *T = TL.getTypePtr();
5448   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5449   if (ElementType.isNull())
5450     return QualType();
5451 
5452   EnterExpressionEvaluationContext Unevaluated(
5453       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5454 
5455   ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
5456   Size = SemaRef.ActOnConstantExpression(Size);
5457   if (Size.isInvalid())
5458     return QualType();
5459 
5460   QualType Result = TL.getType();
5461   if (getDerived().AlwaysRebuild() || ElementType != T->getElementType() ||
5462       Size.get() != T->getSizeExpr()) {
5463     Result = getDerived().RebuildDependentVectorType(
5464         ElementType, Size.get(), T->getAttributeLoc(), T->getVectorKind());
5465     if (Result.isNull())
5466       return QualType();
5467   }
5468 
5469   // Result might be dependent or not.
5470   if (isa<DependentVectorType>(Result)) {
5471     DependentVectorTypeLoc NewTL =
5472         TLB.push<DependentVectorTypeLoc>(Result);
5473     NewTL.setNameLoc(TL.getNameLoc());
5474   } else {
5475     VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
5476     NewTL.setNameLoc(TL.getNameLoc());
5477   }
5478 
5479   return Result;
5480 }
5481 
5482 template<typename Derived>
5483 QualType TreeTransform<Derived>::TransformDependentSizedExtVectorType(
5484                                       TypeLocBuilder &TLB,
5485                                       DependentSizedExtVectorTypeLoc TL) {
5486   const DependentSizedExtVectorType *T = TL.getTypePtr();
5487 
5488   // FIXME: ext vector locs should be nested
5489   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5490   if (ElementType.isNull())
5491     return QualType();
5492 
5493   // Vector sizes are constant expressions.
5494   EnterExpressionEvaluationContext Unevaluated(
5495       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5496 
5497   ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
5498   Size = SemaRef.ActOnConstantExpression(Size);
5499   if (Size.isInvalid())
5500     return QualType();
5501 
5502   QualType Result = TL.getType();
5503   if (getDerived().AlwaysRebuild() ||
5504       ElementType != T->getElementType() ||
5505       Size.get() != T->getSizeExpr()) {
5506     Result = getDerived().RebuildDependentSizedExtVectorType(ElementType,
5507                                                              Size.get(),
5508                                                          T->getAttributeLoc());
5509     if (Result.isNull())
5510       return QualType();
5511   }
5512 
5513   // Result might be dependent or not.
5514   if (isa<DependentSizedExtVectorType>(Result)) {
5515     DependentSizedExtVectorTypeLoc NewTL
5516       = TLB.push<DependentSizedExtVectorTypeLoc>(Result);
5517     NewTL.setNameLoc(TL.getNameLoc());
5518   } else {
5519     ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
5520     NewTL.setNameLoc(TL.getNameLoc());
5521   }
5522 
5523   return Result;
5524 }
5525 
5526 template <typename Derived>
5527 QualType
5528 TreeTransform<Derived>::TransformConstantMatrixType(TypeLocBuilder &TLB,
5529                                                     ConstantMatrixTypeLoc TL) {
5530   const ConstantMatrixType *T = TL.getTypePtr();
5531   QualType ElementType = getDerived().TransformType(T->getElementType());
5532   if (ElementType.isNull())
5533     return QualType();
5534 
5535   QualType Result = TL.getType();
5536   if (getDerived().AlwaysRebuild() || ElementType != T->getElementType()) {
5537     Result = getDerived().RebuildConstantMatrixType(
5538         ElementType, T->getNumRows(), T->getNumColumns());
5539     if (Result.isNull())
5540       return QualType();
5541   }
5542 
5543   ConstantMatrixTypeLoc NewTL = TLB.push<ConstantMatrixTypeLoc>(Result);
5544   NewTL.setAttrNameLoc(TL.getAttrNameLoc());
5545   NewTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5546   NewTL.setAttrRowOperand(TL.getAttrRowOperand());
5547   NewTL.setAttrColumnOperand(TL.getAttrColumnOperand());
5548 
5549   return Result;
5550 }
5551 
5552 template <typename Derived>
5553 QualType TreeTransform<Derived>::TransformDependentSizedMatrixType(
5554     TypeLocBuilder &TLB, DependentSizedMatrixTypeLoc TL) {
5555   const DependentSizedMatrixType *T = TL.getTypePtr();
5556 
5557   QualType ElementType = getDerived().TransformType(T->getElementType());
5558   if (ElementType.isNull()) {
5559     return QualType();
5560   }
5561 
5562   // Matrix dimensions are constant expressions.
5563   EnterExpressionEvaluationContext Unevaluated(
5564       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5565 
5566   Expr *origRows = TL.getAttrRowOperand();
5567   if (!origRows)
5568     origRows = T->getRowExpr();
5569   Expr *origColumns = TL.getAttrColumnOperand();
5570   if (!origColumns)
5571     origColumns = T->getColumnExpr();
5572 
5573   ExprResult rowResult = getDerived().TransformExpr(origRows);
5574   rowResult = SemaRef.ActOnConstantExpression(rowResult);
5575   if (rowResult.isInvalid())
5576     return QualType();
5577 
5578   ExprResult columnResult = getDerived().TransformExpr(origColumns);
5579   columnResult = SemaRef.ActOnConstantExpression(columnResult);
5580   if (columnResult.isInvalid())
5581     return QualType();
5582 
5583   Expr *rows = rowResult.get();
5584   Expr *columns = columnResult.get();
5585 
5586   QualType Result = TL.getType();
5587   if (getDerived().AlwaysRebuild() || ElementType != T->getElementType() ||
5588       rows != origRows || columns != origColumns) {
5589     Result = getDerived().RebuildDependentSizedMatrixType(
5590         ElementType, rows, columns, T->getAttributeLoc());
5591 
5592     if (Result.isNull())
5593       return QualType();
5594   }
5595 
5596   // We might have any sort of matrix type now, but fortunately they
5597   // all have the same location layout.
5598   MatrixTypeLoc NewTL = TLB.push<MatrixTypeLoc>(Result);
5599   NewTL.setAttrNameLoc(TL.getAttrNameLoc());
5600   NewTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5601   NewTL.setAttrRowOperand(rows);
5602   NewTL.setAttrColumnOperand(columns);
5603   return Result;
5604 }
5605 
5606 template <typename Derived>
5607 QualType TreeTransform<Derived>::TransformDependentAddressSpaceType(
5608     TypeLocBuilder &TLB, DependentAddressSpaceTypeLoc TL) {
5609   const DependentAddressSpaceType *T = TL.getTypePtr();
5610 
5611   QualType pointeeType = getDerived().TransformType(T->getPointeeType());
5612 
5613   if (pointeeType.isNull())
5614     return QualType();
5615 
5616   // Address spaces are constant expressions.
5617   EnterExpressionEvaluationContext Unevaluated(
5618       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5619 
5620   ExprResult AddrSpace = getDerived().TransformExpr(T->getAddrSpaceExpr());
5621   AddrSpace = SemaRef.ActOnConstantExpression(AddrSpace);
5622   if (AddrSpace.isInvalid())
5623     return QualType();
5624 
5625   QualType Result = TL.getType();
5626   if (getDerived().AlwaysRebuild() || pointeeType != T->getPointeeType() ||
5627       AddrSpace.get() != T->getAddrSpaceExpr()) {
5628     Result = getDerived().RebuildDependentAddressSpaceType(
5629         pointeeType, AddrSpace.get(), T->getAttributeLoc());
5630     if (Result.isNull())
5631       return QualType();
5632   }
5633 
5634   // Result might be dependent or not.
5635   if (isa<DependentAddressSpaceType>(Result)) {
5636     DependentAddressSpaceTypeLoc NewTL =
5637         TLB.push<DependentAddressSpaceTypeLoc>(Result);
5638 
5639     NewTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5640     NewTL.setAttrExprOperand(TL.getAttrExprOperand());
5641     NewTL.setAttrNameLoc(TL.getAttrNameLoc());
5642 
5643   } else {
5644     TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(
5645         Result, getDerived().getBaseLocation());
5646     TransformType(TLB, DI->getTypeLoc());
5647   }
5648 
5649   return Result;
5650 }
5651 
5652 template <typename Derived>
5653 QualType TreeTransform<Derived>::TransformVectorType(TypeLocBuilder &TLB,
5654                                                      VectorTypeLoc TL) {
5655   const VectorType *T = TL.getTypePtr();
5656   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5657   if (ElementType.isNull())
5658     return QualType();
5659 
5660   QualType Result = TL.getType();
5661   if (getDerived().AlwaysRebuild() ||
5662       ElementType != T->getElementType()) {
5663     Result = getDerived().RebuildVectorType(ElementType, T->getNumElements(),
5664                                             T->getVectorKind());
5665     if (Result.isNull())
5666       return QualType();
5667   }
5668 
5669   VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
5670   NewTL.setNameLoc(TL.getNameLoc());
5671 
5672   return Result;
5673 }
5674 
5675 template<typename Derived>
5676 QualType TreeTransform<Derived>::TransformExtVectorType(TypeLocBuilder &TLB,
5677                                                         ExtVectorTypeLoc TL) {
5678   const VectorType *T = TL.getTypePtr();
5679   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5680   if (ElementType.isNull())
5681     return QualType();
5682 
5683   QualType Result = TL.getType();
5684   if (getDerived().AlwaysRebuild() ||
5685       ElementType != T->getElementType()) {
5686     Result = getDerived().RebuildExtVectorType(ElementType,
5687                                                T->getNumElements(),
5688                                                /*FIXME*/ SourceLocation());
5689     if (Result.isNull())
5690       return QualType();
5691   }
5692 
5693   ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
5694   NewTL.setNameLoc(TL.getNameLoc());
5695 
5696   return Result;
5697 }
5698 
5699 template <typename Derived>
5700 ParmVarDecl *TreeTransform<Derived>::TransformFunctionTypeParam(
5701     ParmVarDecl *OldParm, int indexAdjustment,
5702     std::optional<unsigned> NumExpansions, bool ExpectParameterPack) {
5703   TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
5704   TypeSourceInfo *NewDI = nullptr;
5705 
5706   if (NumExpansions && isa<PackExpansionType>(OldDI->getType())) {
5707     // If we're substituting into a pack expansion type and we know the
5708     // length we want to expand to, just substitute for the pattern.
5709     TypeLoc OldTL = OldDI->getTypeLoc();
5710     PackExpansionTypeLoc OldExpansionTL = OldTL.castAs<PackExpansionTypeLoc>();
5711 
5712     TypeLocBuilder TLB;
5713     TypeLoc NewTL = OldDI->getTypeLoc();
5714     TLB.reserve(NewTL.getFullDataSize());
5715 
5716     QualType Result = getDerived().TransformType(TLB,
5717                                                OldExpansionTL.getPatternLoc());
5718     if (Result.isNull())
5719       return nullptr;
5720 
5721     Result = RebuildPackExpansionType(Result,
5722                                 OldExpansionTL.getPatternLoc().getSourceRange(),
5723                                       OldExpansionTL.getEllipsisLoc(),
5724                                       NumExpansions);
5725     if (Result.isNull())
5726       return nullptr;
5727 
5728     PackExpansionTypeLoc NewExpansionTL
5729       = TLB.push<PackExpansionTypeLoc>(Result);
5730     NewExpansionTL.setEllipsisLoc(OldExpansionTL.getEllipsisLoc());
5731     NewDI = TLB.getTypeSourceInfo(SemaRef.Context, Result);
5732   } else
5733     NewDI = getDerived().TransformType(OldDI);
5734   if (!NewDI)
5735     return nullptr;
5736 
5737   if (NewDI == OldDI && indexAdjustment == 0)
5738     return OldParm;
5739 
5740   ParmVarDecl *newParm = ParmVarDecl::Create(SemaRef.Context,
5741                                              OldParm->getDeclContext(),
5742                                              OldParm->getInnerLocStart(),
5743                                              OldParm->getLocation(),
5744                                              OldParm->getIdentifier(),
5745                                              NewDI->getType(),
5746                                              NewDI,
5747                                              OldParm->getStorageClass(),
5748                                              /* DefArg */ nullptr);
5749   newParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
5750                         OldParm->getFunctionScopeIndex() + indexAdjustment);
5751   transformedLocalDecl(OldParm, {newParm});
5752   return newParm;
5753 }
5754 
5755 template <typename Derived>
5756 bool TreeTransform<Derived>::TransformFunctionTypeParams(
5757     SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
5758     const QualType *ParamTypes,
5759     const FunctionProtoType::ExtParameterInfo *ParamInfos,
5760     SmallVectorImpl<QualType> &OutParamTypes,
5761     SmallVectorImpl<ParmVarDecl *> *PVars,
5762     Sema::ExtParameterInfoBuilder &PInfos,
5763     unsigned *LastParamTransformed) {
5764   int indexAdjustment = 0;
5765 
5766   unsigned NumParams = Params.size();
5767   for (unsigned i = 0; i != NumParams; ++i) {
5768     if (LastParamTransformed)
5769       *LastParamTransformed = i;
5770     if (ParmVarDecl *OldParm = Params[i]) {
5771       assert(OldParm->getFunctionScopeIndex() == i);
5772 
5773       std::optional<unsigned> NumExpansions;
5774       ParmVarDecl *NewParm = nullptr;
5775       if (OldParm->isParameterPack()) {
5776         // We have a function parameter pack that may need to be expanded.
5777         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5778 
5779         // Find the parameter packs that could be expanded.
5780         TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc();
5781         PackExpansionTypeLoc ExpansionTL = TL.castAs<PackExpansionTypeLoc>();
5782         TypeLoc Pattern = ExpansionTL.getPatternLoc();
5783         SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
5784 
5785         // Determine whether we should expand the parameter packs.
5786         bool ShouldExpand = false;
5787         bool RetainExpansion = false;
5788         std::optional<unsigned> OrigNumExpansions;
5789         if (Unexpanded.size() > 0) {
5790           OrigNumExpansions = ExpansionTL.getTypePtr()->getNumExpansions();
5791           NumExpansions = OrigNumExpansions;
5792           if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
5793                                                    Pattern.getSourceRange(),
5794                                                    Unexpanded,
5795                                                    ShouldExpand,
5796                                                    RetainExpansion,
5797                                                    NumExpansions)) {
5798             return true;
5799           }
5800         } else {
5801 #ifndef NDEBUG
5802           const AutoType *AT =
5803               Pattern.getType().getTypePtr()->getContainedAutoType();
5804           assert((AT && (!AT->isDeduced() || AT->getDeducedType().isNull())) &&
5805                  "Could not find parameter packs or undeduced auto type!");
5806 #endif
5807         }
5808 
5809         if (ShouldExpand) {
5810           // Expand the function parameter pack into multiple, separate
5811           // parameters.
5812           getDerived().ExpandingFunctionParameterPack(OldParm);
5813           for (unsigned I = 0; I != *NumExpansions; ++I) {
5814             Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
5815             ParmVarDecl *NewParm
5816               = getDerived().TransformFunctionTypeParam(OldParm,
5817                                                         indexAdjustment++,
5818                                                         OrigNumExpansions,
5819                                                 /*ExpectParameterPack=*/false);
5820             if (!NewParm)
5821               return true;
5822 
5823             if (ParamInfos)
5824               PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5825             OutParamTypes.push_back(NewParm->getType());
5826             if (PVars)
5827               PVars->push_back(NewParm);
5828           }
5829 
5830           // If we're supposed to retain a pack expansion, do so by temporarily
5831           // forgetting the partially-substituted parameter pack.
5832           if (RetainExpansion) {
5833             ForgetPartiallySubstitutedPackRAII Forget(getDerived());
5834             ParmVarDecl *NewParm
5835               = getDerived().TransformFunctionTypeParam(OldParm,
5836                                                         indexAdjustment++,
5837                                                         OrigNumExpansions,
5838                                                 /*ExpectParameterPack=*/false);
5839             if (!NewParm)
5840               return true;
5841 
5842             if (ParamInfos)
5843               PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5844             OutParamTypes.push_back(NewParm->getType());
5845             if (PVars)
5846               PVars->push_back(NewParm);
5847           }
5848 
5849           // The next parameter should have the same adjustment as the
5850           // last thing we pushed, but we post-incremented indexAdjustment
5851           // on every push.  Also, if we push nothing, the adjustment should
5852           // go down by one.
5853           indexAdjustment--;
5854 
5855           // We're done with the pack expansion.
5856           continue;
5857         }
5858 
5859         // We'll substitute the parameter now without expanding the pack
5860         // expansion.
5861         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5862         NewParm = getDerived().TransformFunctionTypeParam(OldParm,
5863                                                           indexAdjustment,
5864                                                           NumExpansions,
5865                                                   /*ExpectParameterPack=*/true);
5866         assert(NewParm->isParameterPack() &&
5867                "Parameter pack no longer a parameter pack after "
5868                "transformation.");
5869       } else {
5870         NewParm = getDerived().TransformFunctionTypeParam(
5871             OldParm, indexAdjustment, std::nullopt,
5872             /*ExpectParameterPack=*/false);
5873       }
5874 
5875       if (!NewParm)
5876         return true;
5877 
5878       if (ParamInfos)
5879         PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5880       OutParamTypes.push_back(NewParm->getType());
5881       if (PVars)
5882         PVars->push_back(NewParm);
5883       continue;
5884     }
5885 
5886     // Deal with the possibility that we don't have a parameter
5887     // declaration for this parameter.
5888     assert(ParamTypes);
5889     QualType OldType = ParamTypes[i];
5890     bool IsPackExpansion = false;
5891     std::optional<unsigned> NumExpansions;
5892     QualType NewType;
5893     if (const PackExpansionType *Expansion
5894                                        = dyn_cast<PackExpansionType>(OldType)) {
5895       // We have a function parameter pack that may need to be expanded.
5896       QualType Pattern = Expansion->getPattern();
5897       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5898       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
5899 
5900       // Determine whether we should expand the parameter packs.
5901       bool ShouldExpand = false;
5902       bool RetainExpansion = false;
5903       if (getDerived().TryExpandParameterPacks(Loc, SourceRange(),
5904                                                Unexpanded,
5905                                                ShouldExpand,
5906                                                RetainExpansion,
5907                                                NumExpansions)) {
5908         return true;
5909       }
5910 
5911       if (ShouldExpand) {
5912         // Expand the function parameter pack into multiple, separate
5913         // parameters.
5914         for (unsigned I = 0; I != *NumExpansions; ++I) {
5915           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
5916           QualType NewType = getDerived().TransformType(Pattern);
5917           if (NewType.isNull())
5918             return true;
5919 
5920           if (NewType->containsUnexpandedParameterPack()) {
5921             NewType = getSema().getASTContext().getPackExpansionType(
5922                 NewType, std::nullopt);
5923 
5924             if (NewType.isNull())
5925               return true;
5926           }
5927 
5928           if (ParamInfos)
5929             PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5930           OutParamTypes.push_back(NewType);
5931           if (PVars)
5932             PVars->push_back(nullptr);
5933         }
5934 
5935         // We're done with the pack expansion.
5936         continue;
5937       }
5938 
5939       // If we're supposed to retain a pack expansion, do so by temporarily
5940       // forgetting the partially-substituted parameter pack.
5941       if (RetainExpansion) {
5942         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
5943         QualType NewType = getDerived().TransformType(Pattern);
5944         if (NewType.isNull())
5945           return true;
5946 
5947         if (ParamInfos)
5948           PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5949         OutParamTypes.push_back(NewType);
5950         if (PVars)
5951           PVars->push_back(nullptr);
5952       }
5953 
5954       // We'll substitute the parameter now without expanding the pack
5955       // expansion.
5956       OldType = Expansion->getPattern();
5957       IsPackExpansion = true;
5958       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5959       NewType = getDerived().TransformType(OldType);
5960     } else {
5961       NewType = getDerived().TransformType(OldType);
5962     }
5963 
5964     if (NewType.isNull())
5965       return true;
5966 
5967     if (IsPackExpansion)
5968       NewType = getSema().Context.getPackExpansionType(NewType,
5969                                                        NumExpansions);
5970 
5971     if (ParamInfos)
5972       PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5973     OutParamTypes.push_back(NewType);
5974     if (PVars)
5975       PVars->push_back(nullptr);
5976   }
5977 
5978 #ifndef NDEBUG
5979   if (PVars) {
5980     for (unsigned i = 0, e = PVars->size(); i != e; ++i)
5981       if (ParmVarDecl *parm = (*PVars)[i])
5982         assert(parm->getFunctionScopeIndex() == i);
5983   }
5984 #endif
5985 
5986   return false;
5987 }
5988 
5989 template<typename Derived>
5990 QualType
5991 TreeTransform<Derived>::TransformFunctionProtoType(TypeLocBuilder &TLB,
5992                                                    FunctionProtoTypeLoc TL) {
5993   SmallVector<QualType, 4> ExceptionStorage;
5994   TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
5995   return getDerived().TransformFunctionProtoType(
5996       TLB, TL, nullptr, Qualifiers(),
5997       [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
5998         return This->getDerived().TransformExceptionSpec(
5999             TL.getBeginLoc(), ESI, ExceptionStorage, Changed);
6000       });
6001 }
6002 
6003 template<typename Derived> template<typename Fn>
6004 QualType TreeTransform<Derived>::TransformFunctionProtoType(
6005     TypeLocBuilder &TLB, FunctionProtoTypeLoc TL, CXXRecordDecl *ThisContext,
6006     Qualifiers ThisTypeQuals, Fn TransformExceptionSpec) {
6007 
6008   // Transform the parameters and return type.
6009   //
6010   // We are required to instantiate the params and return type in source order.
6011   // When the function has a trailing return type, we instantiate the
6012   // parameters before the return type,  since the return type can then refer
6013   // to the parameters themselves (via decltype, sizeof, etc.).
6014   //
6015   SmallVector<QualType, 4> ParamTypes;
6016   SmallVector<ParmVarDecl*, 4> ParamDecls;
6017   Sema::ExtParameterInfoBuilder ExtParamInfos;
6018   const FunctionProtoType *T = TL.getTypePtr();
6019 
6020   QualType ResultType;
6021 
6022   if (T->hasTrailingReturn()) {
6023     if (getDerived().TransformFunctionTypeParams(
6024             TL.getBeginLoc(), TL.getParams(),
6025             TL.getTypePtr()->param_type_begin(),
6026             T->getExtParameterInfosOrNull(),
6027             ParamTypes, &ParamDecls, ExtParamInfos))
6028       return QualType();
6029 
6030     {
6031       // C++11 [expr.prim.general]p3:
6032       //   If a declaration declares a member function or member function
6033       //   template of a class X, the expression this is a prvalue of type
6034       //   "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
6035       //   and the end of the function-definition, member-declarator, or
6036       //   declarator.
6037       Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals);
6038 
6039       ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
6040       if (ResultType.isNull())
6041         return QualType();
6042     }
6043   }
6044   else {
6045     ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
6046     if (ResultType.isNull())
6047       return QualType();
6048 
6049     if (getDerived().TransformFunctionTypeParams(
6050             TL.getBeginLoc(), TL.getParams(),
6051             TL.getTypePtr()->param_type_begin(),
6052             T->getExtParameterInfosOrNull(),
6053             ParamTypes, &ParamDecls, ExtParamInfos))
6054       return QualType();
6055   }
6056 
6057   FunctionProtoType::ExtProtoInfo EPI = T->getExtProtoInfo();
6058 
6059   bool EPIChanged = false;
6060   if (TransformExceptionSpec(EPI.ExceptionSpec, EPIChanged))
6061     return QualType();
6062 
6063   // Handle extended parameter information.
6064   if (auto NewExtParamInfos =
6065         ExtParamInfos.getPointerOrNull(ParamTypes.size())) {
6066     if (!EPI.ExtParameterInfos ||
6067         llvm::ArrayRef(EPI.ExtParameterInfos, TL.getNumParams()) !=
6068             llvm::ArrayRef(NewExtParamInfos, ParamTypes.size())) {
6069       EPIChanged = true;
6070     }
6071     EPI.ExtParameterInfos = NewExtParamInfos;
6072   } else if (EPI.ExtParameterInfos) {
6073     EPIChanged = true;
6074     EPI.ExtParameterInfos = nullptr;
6075   }
6076 
6077   QualType Result = TL.getType();
6078   if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType() ||
6079       T->getParamTypes() != llvm::ArrayRef(ParamTypes) || EPIChanged) {
6080     Result = getDerived().RebuildFunctionProtoType(ResultType, ParamTypes, EPI);
6081     if (Result.isNull())
6082       return QualType();
6083   }
6084 
6085   FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
6086   NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
6087   NewTL.setLParenLoc(TL.getLParenLoc());
6088   NewTL.setRParenLoc(TL.getRParenLoc());
6089   NewTL.setExceptionSpecRange(TL.getExceptionSpecRange());
6090   NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
6091   for (unsigned i = 0, e = NewTL.getNumParams(); i != e; ++i)
6092     NewTL.setParam(i, ParamDecls[i]);
6093 
6094   return Result;
6095 }
6096 
6097 template<typename Derived>
6098 bool TreeTransform<Derived>::TransformExceptionSpec(
6099     SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI,
6100     SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
6101   assert(ESI.Type != EST_Uninstantiated && ESI.Type != EST_Unevaluated);
6102 
6103   // Instantiate a dynamic noexcept expression, if any.
6104   if (isComputedNoexcept(ESI.Type)) {
6105     EnterExpressionEvaluationContext Unevaluated(
6106         getSema(), Sema::ExpressionEvaluationContext::ConstantEvaluated);
6107     ExprResult NoexceptExpr = getDerived().TransformExpr(ESI.NoexceptExpr);
6108     if (NoexceptExpr.isInvalid())
6109       return true;
6110 
6111     ExceptionSpecificationType EST = ESI.Type;
6112     NoexceptExpr =
6113         getSema().ActOnNoexceptSpec(NoexceptExpr.get(), EST);
6114     if (NoexceptExpr.isInvalid())
6115       return true;
6116 
6117     if (ESI.NoexceptExpr != NoexceptExpr.get() || EST != ESI.Type)
6118       Changed = true;
6119     ESI.NoexceptExpr = NoexceptExpr.get();
6120     ESI.Type = EST;
6121   }
6122 
6123   if (ESI.Type != EST_Dynamic)
6124     return false;
6125 
6126   // Instantiate a dynamic exception specification's type.
6127   for (QualType T : ESI.Exceptions) {
6128     if (const PackExpansionType *PackExpansion =
6129             T->getAs<PackExpansionType>()) {
6130       Changed = true;
6131 
6132       // We have a pack expansion. Instantiate it.
6133       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
6134       SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
6135                                               Unexpanded);
6136       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
6137 
6138       // Determine whether the set of unexpanded parameter packs can and
6139       // should
6140       // be expanded.
6141       bool Expand = false;
6142       bool RetainExpansion = false;
6143       std::optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
6144       // FIXME: Track the location of the ellipsis (and track source location
6145       // information for the types in the exception specification in general).
6146       if (getDerived().TryExpandParameterPacks(
6147               Loc, SourceRange(), Unexpanded, Expand,
6148               RetainExpansion, NumExpansions))
6149         return true;
6150 
6151       if (!Expand) {
6152         // We can't expand this pack expansion into separate arguments yet;
6153         // just substitute into the pattern and create a new pack expansion
6154         // type.
6155         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
6156         QualType U = getDerived().TransformType(PackExpansion->getPattern());
6157         if (U.isNull())
6158           return true;
6159 
6160         U = SemaRef.Context.getPackExpansionType(U, NumExpansions);
6161         Exceptions.push_back(U);
6162         continue;
6163       }
6164 
6165       // Substitute into the pack expansion pattern for each slice of the
6166       // pack.
6167       for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
6168         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
6169 
6170         QualType U = getDerived().TransformType(PackExpansion->getPattern());
6171         if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
6172           return true;
6173 
6174         Exceptions.push_back(U);
6175       }
6176     } else {
6177       QualType U = getDerived().TransformType(T);
6178       if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
6179         return true;
6180       if (T != U)
6181         Changed = true;
6182 
6183       Exceptions.push_back(U);
6184     }
6185   }
6186 
6187   ESI.Exceptions = Exceptions;
6188   if (ESI.Exceptions.empty())
6189     ESI.Type = EST_DynamicNone;
6190   return false;
6191 }
6192 
6193 template<typename Derived>
6194 QualType TreeTransform<Derived>::TransformFunctionNoProtoType(
6195                                                  TypeLocBuilder &TLB,
6196                                                  FunctionNoProtoTypeLoc TL) {
6197   const FunctionNoProtoType *T = TL.getTypePtr();
6198   QualType ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
6199   if (ResultType.isNull())
6200     return QualType();
6201 
6202   QualType Result = TL.getType();
6203   if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType())
6204     Result = getDerived().RebuildFunctionNoProtoType(ResultType);
6205 
6206   FunctionNoProtoTypeLoc NewTL = TLB.push<FunctionNoProtoTypeLoc>(Result);
6207   NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
6208   NewTL.setLParenLoc(TL.getLParenLoc());
6209   NewTL.setRParenLoc(TL.getRParenLoc());
6210   NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
6211 
6212   return Result;
6213 }
6214 
6215 template <typename Derived>
6216 QualType TreeTransform<Derived>::TransformUnresolvedUsingType(
6217     TypeLocBuilder &TLB, UnresolvedUsingTypeLoc TL) {
6218   const UnresolvedUsingType *T = TL.getTypePtr();
6219   Decl *D = getDerived().TransformDecl(TL.getNameLoc(), T->getDecl());
6220   if (!D)
6221     return QualType();
6222 
6223   QualType Result = TL.getType();
6224   if (getDerived().AlwaysRebuild() || D != T->getDecl()) {
6225     Result = getDerived().RebuildUnresolvedUsingType(TL.getNameLoc(), D);
6226     if (Result.isNull())
6227       return QualType();
6228   }
6229 
6230   // We might get an arbitrary type spec type back.  We should at
6231   // least always get a type spec type, though.
6232   TypeSpecTypeLoc NewTL = TLB.pushTypeSpec(Result);
6233   NewTL.setNameLoc(TL.getNameLoc());
6234 
6235   return Result;
6236 }
6237 
6238 template <typename Derived>
6239 QualType TreeTransform<Derived>::TransformUsingType(TypeLocBuilder &TLB,
6240                                                     UsingTypeLoc TL) {
6241   const UsingType *T = TL.getTypePtr();
6242 
6243   auto *Found = cast_or_null<UsingShadowDecl>(getDerived().TransformDecl(
6244       TL.getLocalSourceRange().getBegin(), T->getFoundDecl()));
6245   if (!Found)
6246     return QualType();
6247 
6248   QualType Underlying = getDerived().TransformType(T->desugar());
6249   if (Underlying.isNull())
6250     return QualType();
6251 
6252   QualType Result = TL.getType();
6253   if (getDerived().AlwaysRebuild() || Found != T->getFoundDecl() ||
6254       Underlying != T->getUnderlyingType()) {
6255     Result = getDerived().RebuildUsingType(Found, Underlying);
6256     if (Result.isNull())
6257       return QualType();
6258   }
6259 
6260   TLB.pushTypeSpec(Result).setNameLoc(TL.getNameLoc());
6261   return Result;
6262 }
6263 
6264 template<typename Derived>
6265 QualType TreeTransform<Derived>::TransformTypedefType(TypeLocBuilder &TLB,
6266                                                       TypedefTypeLoc TL) {
6267   const TypedefType *T = TL.getTypePtr();
6268   TypedefNameDecl *Typedef
6269     = cast_or_null<TypedefNameDecl>(getDerived().TransformDecl(TL.getNameLoc(),
6270                                                                T->getDecl()));
6271   if (!Typedef)
6272     return QualType();
6273 
6274   QualType Result = TL.getType();
6275   if (getDerived().AlwaysRebuild() ||
6276       Typedef != T->getDecl()) {
6277     Result = getDerived().RebuildTypedefType(Typedef);
6278     if (Result.isNull())
6279       return QualType();
6280   }
6281 
6282   TypedefTypeLoc NewTL = TLB.push<TypedefTypeLoc>(Result);
6283   NewTL.setNameLoc(TL.getNameLoc());
6284 
6285   return Result;
6286 }
6287 
6288 template<typename Derived>
6289 QualType TreeTransform<Derived>::TransformTypeOfExprType(TypeLocBuilder &TLB,
6290                                                       TypeOfExprTypeLoc TL) {
6291   // typeof expressions are not potentially evaluated contexts
6292   EnterExpressionEvaluationContext Unevaluated(
6293       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
6294       Sema::ReuseLambdaContextDecl);
6295 
6296   ExprResult E = getDerived().TransformExpr(TL.getUnderlyingExpr());
6297   if (E.isInvalid())
6298     return QualType();
6299 
6300   E = SemaRef.HandleExprEvaluationContextForTypeof(E.get());
6301   if (E.isInvalid())
6302     return QualType();
6303 
6304   QualType Result = TL.getType();
6305   TypeOfKind Kind = Result->getAs<TypeOfExprType>()->getKind();
6306   if (getDerived().AlwaysRebuild() || E.get() != TL.getUnderlyingExpr()) {
6307     Result =
6308         getDerived().RebuildTypeOfExprType(E.get(), TL.getTypeofLoc(), Kind);
6309     if (Result.isNull())
6310       return QualType();
6311   }
6312 
6313   TypeOfExprTypeLoc NewTL = TLB.push<TypeOfExprTypeLoc>(Result);
6314   NewTL.setTypeofLoc(TL.getTypeofLoc());
6315   NewTL.setLParenLoc(TL.getLParenLoc());
6316   NewTL.setRParenLoc(TL.getRParenLoc());
6317 
6318   return Result;
6319 }
6320 
6321 template<typename Derived>
6322 QualType TreeTransform<Derived>::TransformTypeOfType(TypeLocBuilder &TLB,
6323                                                      TypeOfTypeLoc TL) {
6324   TypeSourceInfo* Old_Under_TI = TL.getUnmodifiedTInfo();
6325   TypeSourceInfo* New_Under_TI = getDerived().TransformType(Old_Under_TI);
6326   if (!New_Under_TI)
6327     return QualType();
6328 
6329   QualType Result = TL.getType();
6330   TypeOfKind Kind = Result->getAs<TypeOfType>()->getKind();
6331   if (getDerived().AlwaysRebuild() || New_Under_TI != Old_Under_TI) {
6332     Result = getDerived().RebuildTypeOfType(New_Under_TI->getType(), Kind);
6333     if (Result.isNull())
6334       return QualType();
6335   }
6336 
6337   TypeOfTypeLoc NewTL = TLB.push<TypeOfTypeLoc>(Result);
6338   NewTL.setTypeofLoc(TL.getTypeofLoc());
6339   NewTL.setLParenLoc(TL.getLParenLoc());
6340   NewTL.setRParenLoc(TL.getRParenLoc());
6341   NewTL.setUnmodifiedTInfo(New_Under_TI);
6342 
6343   return Result;
6344 }
6345 
6346 template<typename Derived>
6347 QualType TreeTransform<Derived>::TransformDecltypeType(TypeLocBuilder &TLB,
6348                                                        DecltypeTypeLoc TL) {
6349   const DecltypeType *T = TL.getTypePtr();
6350 
6351   // decltype expressions are not potentially evaluated contexts
6352   EnterExpressionEvaluationContext Unevaluated(
6353       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated, nullptr,
6354       Sema::ExpressionEvaluationContextRecord::EK_Decltype);
6355 
6356   ExprResult E = getDerived().TransformExpr(T->getUnderlyingExpr());
6357   if (E.isInvalid())
6358     return QualType();
6359 
6360   E = getSema().ActOnDecltypeExpression(E.get());
6361   if (E.isInvalid())
6362     return QualType();
6363 
6364   QualType Result = TL.getType();
6365   if (getDerived().AlwaysRebuild() ||
6366       E.get() != T->getUnderlyingExpr()) {
6367     Result = getDerived().RebuildDecltypeType(E.get(), TL.getDecltypeLoc());
6368     if (Result.isNull())
6369       return QualType();
6370   }
6371   else E.get();
6372 
6373   DecltypeTypeLoc NewTL = TLB.push<DecltypeTypeLoc>(Result);
6374   NewTL.setDecltypeLoc(TL.getDecltypeLoc());
6375   NewTL.setRParenLoc(TL.getRParenLoc());
6376   return Result;
6377 }
6378 
6379 template<typename Derived>
6380 QualType TreeTransform<Derived>::TransformUnaryTransformType(
6381                                                             TypeLocBuilder &TLB,
6382                                                      UnaryTransformTypeLoc TL) {
6383   QualType Result = TL.getType();
6384   if (Result->isDependentType()) {
6385     const UnaryTransformType *T = TL.getTypePtr();
6386     QualType NewBase =
6387       getDerived().TransformType(TL.getUnderlyingTInfo())->getType();
6388     Result = getDerived().RebuildUnaryTransformType(NewBase,
6389                                                     T->getUTTKind(),
6390                                                     TL.getKWLoc());
6391     if (Result.isNull())
6392       return QualType();
6393   }
6394 
6395   UnaryTransformTypeLoc NewTL = TLB.push<UnaryTransformTypeLoc>(Result);
6396   NewTL.setKWLoc(TL.getKWLoc());
6397   NewTL.setParensRange(TL.getParensRange());
6398   NewTL.setUnderlyingTInfo(TL.getUnderlyingTInfo());
6399   return Result;
6400 }
6401 
6402 template<typename Derived>
6403 QualType TreeTransform<Derived>::TransformDeducedTemplateSpecializationType(
6404     TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) {
6405   const DeducedTemplateSpecializationType *T = TL.getTypePtr();
6406 
6407   CXXScopeSpec SS;
6408   TemplateName TemplateName = getDerived().TransformTemplateName(
6409       SS, T->getTemplateName(), TL.getTemplateNameLoc());
6410   if (TemplateName.isNull())
6411     return QualType();
6412 
6413   QualType OldDeduced = T->getDeducedType();
6414   QualType NewDeduced;
6415   if (!OldDeduced.isNull()) {
6416     NewDeduced = getDerived().TransformType(OldDeduced);
6417     if (NewDeduced.isNull())
6418       return QualType();
6419   }
6420 
6421   QualType Result = getDerived().RebuildDeducedTemplateSpecializationType(
6422       TemplateName, NewDeduced);
6423   if (Result.isNull())
6424     return QualType();
6425 
6426   DeducedTemplateSpecializationTypeLoc NewTL =
6427       TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
6428   NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6429 
6430   return Result;
6431 }
6432 
6433 template<typename Derived>
6434 QualType TreeTransform<Derived>::TransformRecordType(TypeLocBuilder &TLB,
6435                                                      RecordTypeLoc TL) {
6436   const RecordType *T = TL.getTypePtr();
6437   RecordDecl *Record
6438     = cast_or_null<RecordDecl>(getDerived().TransformDecl(TL.getNameLoc(),
6439                                                           T->getDecl()));
6440   if (!Record)
6441     return QualType();
6442 
6443   QualType Result = TL.getType();
6444   if (getDerived().AlwaysRebuild() ||
6445       Record != T->getDecl()) {
6446     Result = getDerived().RebuildRecordType(Record);
6447     if (Result.isNull())
6448       return QualType();
6449   }
6450 
6451   RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
6452   NewTL.setNameLoc(TL.getNameLoc());
6453 
6454   return Result;
6455 }
6456 
6457 template<typename Derived>
6458 QualType TreeTransform<Derived>::TransformEnumType(TypeLocBuilder &TLB,
6459                                                    EnumTypeLoc TL) {
6460   const EnumType *T = TL.getTypePtr();
6461   EnumDecl *Enum
6462     = cast_or_null<EnumDecl>(getDerived().TransformDecl(TL.getNameLoc(),
6463                                                         T->getDecl()));
6464   if (!Enum)
6465     return QualType();
6466 
6467   QualType Result = TL.getType();
6468   if (getDerived().AlwaysRebuild() ||
6469       Enum != T->getDecl()) {
6470     Result = getDerived().RebuildEnumType(Enum);
6471     if (Result.isNull())
6472       return QualType();
6473   }
6474 
6475   EnumTypeLoc NewTL = TLB.push<EnumTypeLoc>(Result);
6476   NewTL.setNameLoc(TL.getNameLoc());
6477 
6478   return Result;
6479 }
6480 
6481 template<typename Derived>
6482 QualType TreeTransform<Derived>::TransformInjectedClassNameType(
6483                                          TypeLocBuilder &TLB,
6484                                          InjectedClassNameTypeLoc TL) {
6485   Decl *D = getDerived().TransformDecl(TL.getNameLoc(),
6486                                        TL.getTypePtr()->getDecl());
6487   if (!D) return QualType();
6488 
6489   QualType T = SemaRef.Context.getTypeDeclType(cast<TypeDecl>(D));
6490   TLB.pushTypeSpec(T).setNameLoc(TL.getNameLoc());
6491   return T;
6492 }
6493 
6494 template<typename Derived>
6495 QualType TreeTransform<Derived>::TransformTemplateTypeParmType(
6496                                                 TypeLocBuilder &TLB,
6497                                                 TemplateTypeParmTypeLoc TL) {
6498   return getDerived().TransformTemplateTypeParmType(
6499       TLB, TL,
6500       /*SuppressObjCLifetime=*/false);
6501 }
6502 
6503 template <typename Derived>
6504 QualType TreeTransform<Derived>::TransformTemplateTypeParmType(
6505     TypeLocBuilder &TLB, TemplateTypeParmTypeLoc TL, bool) {
6506   return TransformTypeSpecType(TLB, TL);
6507 }
6508 
6509 template<typename Derived>
6510 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmType(
6511                                          TypeLocBuilder &TLB,
6512                                          SubstTemplateTypeParmTypeLoc TL) {
6513   const SubstTemplateTypeParmType *T = TL.getTypePtr();
6514 
6515   Decl *NewReplaced =
6516       getDerived().TransformDecl(TL.getNameLoc(), T->getAssociatedDecl());
6517 
6518   // Substitute into the replacement type, which itself might involve something
6519   // that needs to be transformed. This only tends to occur with default
6520   // template arguments of template template parameters.
6521   TemporaryBase Rebase(*this, TL.getNameLoc(), DeclarationName());
6522   QualType Replacement = getDerived().TransformType(T->getReplacementType());
6523   if (Replacement.isNull())
6524     return QualType();
6525 
6526   QualType Result = SemaRef.Context.getSubstTemplateTypeParmType(
6527       Replacement, NewReplaced, T->getIndex(), T->getPackIndex());
6528 
6529   // Propagate type-source information.
6530   SubstTemplateTypeParmTypeLoc NewTL
6531     = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
6532   NewTL.setNameLoc(TL.getNameLoc());
6533   return Result;
6534 
6535 }
6536 
6537 template<typename Derived>
6538 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmPackType(
6539                                           TypeLocBuilder &TLB,
6540                                           SubstTemplateTypeParmPackTypeLoc TL) {
6541   return getDerived().TransformSubstTemplateTypeParmPackType(
6542       TLB, TL, /*SuppressObjCLifetime=*/false);
6543 }
6544 
6545 template <typename Derived>
6546 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmPackType(
6547     TypeLocBuilder &TLB, SubstTemplateTypeParmPackTypeLoc TL, bool) {
6548   return TransformTypeSpecType(TLB, TL);
6549 }
6550 
6551 template<typename Derived>
6552 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
6553                                                         TypeLocBuilder &TLB,
6554                                            TemplateSpecializationTypeLoc TL) {
6555   const TemplateSpecializationType *T = TL.getTypePtr();
6556 
6557   // The nested-name-specifier never matters in a TemplateSpecializationType,
6558   // because we can't have a dependent nested-name-specifier anyway.
6559   CXXScopeSpec SS;
6560   TemplateName Template
6561     = getDerived().TransformTemplateName(SS, T->getTemplateName(),
6562                                          TL.getTemplateNameLoc());
6563   if (Template.isNull())
6564     return QualType();
6565 
6566   return getDerived().TransformTemplateSpecializationType(TLB, TL, Template);
6567 }
6568 
6569 template<typename Derived>
6570 QualType TreeTransform<Derived>::TransformAtomicType(TypeLocBuilder &TLB,
6571                                                      AtomicTypeLoc TL) {
6572   QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
6573   if (ValueType.isNull())
6574     return QualType();
6575 
6576   QualType Result = TL.getType();
6577   if (getDerived().AlwaysRebuild() ||
6578       ValueType != TL.getValueLoc().getType()) {
6579     Result = getDerived().RebuildAtomicType(ValueType, TL.getKWLoc());
6580     if (Result.isNull())
6581       return QualType();
6582   }
6583 
6584   AtomicTypeLoc NewTL = TLB.push<AtomicTypeLoc>(Result);
6585   NewTL.setKWLoc(TL.getKWLoc());
6586   NewTL.setLParenLoc(TL.getLParenLoc());
6587   NewTL.setRParenLoc(TL.getRParenLoc());
6588 
6589   return Result;
6590 }
6591 
6592 template <typename Derived>
6593 QualType TreeTransform<Derived>::TransformPipeType(TypeLocBuilder &TLB,
6594                                                    PipeTypeLoc TL) {
6595   QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
6596   if (ValueType.isNull())
6597     return QualType();
6598 
6599   QualType Result = TL.getType();
6600   if (getDerived().AlwaysRebuild() || ValueType != TL.getValueLoc().getType()) {
6601     const PipeType *PT = Result->castAs<PipeType>();
6602     bool isReadPipe = PT->isReadOnly();
6603     Result = getDerived().RebuildPipeType(ValueType, TL.getKWLoc(), isReadPipe);
6604     if (Result.isNull())
6605       return QualType();
6606   }
6607 
6608   PipeTypeLoc NewTL = TLB.push<PipeTypeLoc>(Result);
6609   NewTL.setKWLoc(TL.getKWLoc());
6610 
6611   return Result;
6612 }
6613 
6614 template <typename Derived>
6615 QualType TreeTransform<Derived>::TransformBitIntType(TypeLocBuilder &TLB,
6616                                                      BitIntTypeLoc TL) {
6617   const BitIntType *EIT = TL.getTypePtr();
6618   QualType Result = TL.getType();
6619 
6620   if (getDerived().AlwaysRebuild()) {
6621     Result = getDerived().RebuildBitIntType(EIT->isUnsigned(),
6622                                             EIT->getNumBits(), TL.getNameLoc());
6623     if (Result.isNull())
6624       return QualType();
6625   }
6626 
6627   BitIntTypeLoc NewTL = TLB.push<BitIntTypeLoc>(Result);
6628   NewTL.setNameLoc(TL.getNameLoc());
6629   return Result;
6630 }
6631 
6632 template <typename Derived>
6633 QualType TreeTransform<Derived>::TransformDependentBitIntType(
6634     TypeLocBuilder &TLB, DependentBitIntTypeLoc TL) {
6635   const DependentBitIntType *EIT = TL.getTypePtr();
6636 
6637   EnterExpressionEvaluationContext Unevaluated(
6638       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
6639   ExprResult BitsExpr = getDerived().TransformExpr(EIT->getNumBitsExpr());
6640   BitsExpr = SemaRef.ActOnConstantExpression(BitsExpr);
6641 
6642   if (BitsExpr.isInvalid())
6643     return QualType();
6644 
6645   QualType Result = TL.getType();
6646 
6647   if (getDerived().AlwaysRebuild() || BitsExpr.get() != EIT->getNumBitsExpr()) {
6648     Result = getDerived().RebuildDependentBitIntType(
6649         EIT->isUnsigned(), BitsExpr.get(), TL.getNameLoc());
6650 
6651     if (Result.isNull())
6652       return QualType();
6653   }
6654 
6655   if (isa<DependentBitIntType>(Result)) {
6656     DependentBitIntTypeLoc NewTL = TLB.push<DependentBitIntTypeLoc>(Result);
6657     NewTL.setNameLoc(TL.getNameLoc());
6658   } else {
6659     BitIntTypeLoc NewTL = TLB.push<BitIntTypeLoc>(Result);
6660     NewTL.setNameLoc(TL.getNameLoc());
6661   }
6662   return Result;
6663 }
6664 
6665   /// Simple iterator that traverses the template arguments in a
6666   /// container that provides a \c getArgLoc() member function.
6667   ///
6668   /// This iterator is intended to be used with the iterator form of
6669   /// \c TreeTransform<Derived>::TransformTemplateArguments().
6670   template<typename ArgLocContainer>
6671   class TemplateArgumentLocContainerIterator {
6672     ArgLocContainer *Container;
6673     unsigned Index;
6674 
6675   public:
6676     typedef TemplateArgumentLoc value_type;
6677     typedef TemplateArgumentLoc reference;
6678     typedef int difference_type;
6679     typedef std::input_iterator_tag iterator_category;
6680 
6681     class pointer {
6682       TemplateArgumentLoc Arg;
6683 
6684     public:
6685       explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
6686 
6687       const TemplateArgumentLoc *operator->() const {
6688         return &Arg;
6689       }
6690     };
6691 
6692 
6693     TemplateArgumentLocContainerIterator() {}
6694 
6695     TemplateArgumentLocContainerIterator(ArgLocContainer &Container,
6696                                  unsigned Index)
6697       : Container(&Container), Index(Index) { }
6698 
6699     TemplateArgumentLocContainerIterator &operator++() {
6700       ++Index;
6701       return *this;
6702     }
6703 
6704     TemplateArgumentLocContainerIterator operator++(int) {
6705       TemplateArgumentLocContainerIterator Old(*this);
6706       ++(*this);
6707       return Old;
6708     }
6709 
6710     TemplateArgumentLoc operator*() const {
6711       return Container->getArgLoc(Index);
6712     }
6713 
6714     pointer operator->() const {
6715       return pointer(Container->getArgLoc(Index));
6716     }
6717 
6718     friend bool operator==(const TemplateArgumentLocContainerIterator &X,
6719                            const TemplateArgumentLocContainerIterator &Y) {
6720       return X.Container == Y.Container && X.Index == Y.Index;
6721     }
6722 
6723     friend bool operator!=(const TemplateArgumentLocContainerIterator &X,
6724                            const TemplateArgumentLocContainerIterator &Y) {
6725       return !(X == Y);
6726     }
6727   };
6728 
6729 template<typename Derived>
6730 QualType TreeTransform<Derived>::TransformAutoType(TypeLocBuilder &TLB,
6731                                                    AutoTypeLoc TL) {
6732   const AutoType *T = TL.getTypePtr();
6733   QualType OldDeduced = T->getDeducedType();
6734   QualType NewDeduced;
6735   if (!OldDeduced.isNull()) {
6736     NewDeduced = getDerived().TransformType(OldDeduced);
6737     if (NewDeduced.isNull())
6738       return QualType();
6739   }
6740 
6741   ConceptDecl *NewCD = nullptr;
6742   TemplateArgumentListInfo NewTemplateArgs;
6743   NestedNameSpecifierLoc NewNestedNameSpec;
6744   if (T->isConstrained()) {
6745     NewCD = cast_or_null<ConceptDecl>(getDerived().TransformDecl(
6746         TL.getConceptNameLoc(), T->getTypeConstraintConcept()));
6747 
6748     NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6749     NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6750     typedef TemplateArgumentLocContainerIterator<AutoTypeLoc> ArgIterator;
6751     if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6752                                                 ArgIterator(TL,
6753                                                             TL.getNumArgs()),
6754                                                 NewTemplateArgs))
6755       return QualType();
6756 
6757     if (TL.getNestedNameSpecifierLoc()) {
6758       NewNestedNameSpec
6759         = getDerived().TransformNestedNameSpecifierLoc(
6760             TL.getNestedNameSpecifierLoc());
6761       if (!NewNestedNameSpec)
6762         return QualType();
6763     }
6764   }
6765 
6766   QualType Result = TL.getType();
6767   if (getDerived().AlwaysRebuild() || NewDeduced != OldDeduced ||
6768       T->isDependentType() || T->isConstrained()) {
6769     // FIXME: Maybe don't rebuild if all template arguments are the same.
6770     llvm::SmallVector<TemplateArgument, 4> NewArgList;
6771     NewArgList.reserve(NewTemplateArgs.size());
6772     for (const auto &ArgLoc : NewTemplateArgs.arguments())
6773       NewArgList.push_back(ArgLoc.getArgument());
6774     Result = getDerived().RebuildAutoType(NewDeduced, T->getKeyword(), NewCD,
6775                                           NewArgList);
6776     if (Result.isNull())
6777       return QualType();
6778   }
6779 
6780   AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
6781   NewTL.setNameLoc(TL.getNameLoc());
6782   NewTL.setNestedNameSpecifierLoc(NewNestedNameSpec);
6783   NewTL.setTemplateKWLoc(TL.getTemplateKWLoc());
6784   NewTL.setConceptNameLoc(TL.getConceptNameLoc());
6785   NewTL.setFoundDecl(TL.getFoundDecl());
6786   NewTL.setLAngleLoc(TL.getLAngleLoc());
6787   NewTL.setRAngleLoc(TL.getRAngleLoc());
6788   NewTL.setRParenLoc(TL.getRParenLoc());
6789   for (unsigned I = 0; I < NewTL.getNumArgs(); ++I)
6790     NewTL.setArgLocInfo(I, NewTemplateArgs.arguments()[I].getLocInfo());
6791 
6792   return Result;
6793 }
6794 
6795 template <typename Derived>
6796 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
6797                                                         TypeLocBuilder &TLB,
6798                                            TemplateSpecializationTypeLoc TL,
6799                                                       TemplateName Template) {
6800   TemplateArgumentListInfo NewTemplateArgs;
6801   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6802   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6803   typedef TemplateArgumentLocContainerIterator<TemplateSpecializationTypeLoc>
6804     ArgIterator;
6805   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6806                                               ArgIterator(TL, TL.getNumArgs()),
6807                                               NewTemplateArgs))
6808     return QualType();
6809 
6810   // FIXME: maybe don't rebuild if all the template arguments are the same.
6811 
6812   QualType Result =
6813     getDerived().RebuildTemplateSpecializationType(Template,
6814                                                    TL.getTemplateNameLoc(),
6815                                                    NewTemplateArgs);
6816 
6817   if (!Result.isNull()) {
6818     // Specializations of template template parameters are represented as
6819     // TemplateSpecializationTypes, and substitution of type alias templates
6820     // within a dependent context can transform them into
6821     // DependentTemplateSpecializationTypes.
6822     if (isa<DependentTemplateSpecializationType>(Result)) {
6823       DependentTemplateSpecializationTypeLoc NewTL
6824         = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6825       NewTL.setElaboratedKeywordLoc(SourceLocation());
6826       NewTL.setQualifierLoc(NestedNameSpecifierLoc());
6827       NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6828       NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6829       NewTL.setLAngleLoc(TL.getLAngleLoc());
6830       NewTL.setRAngleLoc(TL.getRAngleLoc());
6831       for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6832         NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6833       return Result;
6834     }
6835 
6836     TemplateSpecializationTypeLoc NewTL
6837       = TLB.push<TemplateSpecializationTypeLoc>(Result);
6838     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6839     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6840     NewTL.setLAngleLoc(TL.getLAngleLoc());
6841     NewTL.setRAngleLoc(TL.getRAngleLoc());
6842     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6843       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6844   }
6845 
6846   return Result;
6847 }
6848 
6849 template <typename Derived>
6850 QualType TreeTransform<Derived>::TransformDependentTemplateSpecializationType(
6851                                      TypeLocBuilder &TLB,
6852                                      DependentTemplateSpecializationTypeLoc TL,
6853                                      TemplateName Template,
6854                                      CXXScopeSpec &SS) {
6855   TemplateArgumentListInfo NewTemplateArgs;
6856   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6857   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6858   typedef TemplateArgumentLocContainerIterator<
6859             DependentTemplateSpecializationTypeLoc> ArgIterator;
6860   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6861                                               ArgIterator(TL, TL.getNumArgs()),
6862                                               NewTemplateArgs))
6863     return QualType();
6864 
6865   // FIXME: maybe don't rebuild if all the template arguments are the same.
6866 
6867   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
6868     QualType Result = getSema().Context.getDependentTemplateSpecializationType(
6869         TL.getTypePtr()->getKeyword(), DTN->getQualifier(),
6870         DTN->getIdentifier(), NewTemplateArgs.arguments());
6871 
6872     DependentTemplateSpecializationTypeLoc NewTL
6873       = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6874     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6875     NewTL.setQualifierLoc(SS.getWithLocInContext(SemaRef.Context));
6876     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6877     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6878     NewTL.setLAngleLoc(TL.getLAngleLoc());
6879     NewTL.setRAngleLoc(TL.getRAngleLoc());
6880     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6881       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6882     return Result;
6883   }
6884 
6885   QualType Result
6886     = getDerived().RebuildTemplateSpecializationType(Template,
6887                                                      TL.getTemplateNameLoc(),
6888                                                      NewTemplateArgs);
6889 
6890   if (!Result.isNull()) {
6891     /// FIXME: Wrap this in an elaborated-type-specifier?
6892     TemplateSpecializationTypeLoc NewTL
6893       = TLB.push<TemplateSpecializationTypeLoc>(Result);
6894     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6895     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6896     NewTL.setLAngleLoc(TL.getLAngleLoc());
6897     NewTL.setRAngleLoc(TL.getRAngleLoc());
6898     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6899       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6900   }
6901 
6902   return Result;
6903 }
6904 
6905 template<typename Derived>
6906 QualType
6907 TreeTransform<Derived>::TransformElaboratedType(TypeLocBuilder &TLB,
6908                                                 ElaboratedTypeLoc TL) {
6909   const ElaboratedType *T = TL.getTypePtr();
6910 
6911   NestedNameSpecifierLoc QualifierLoc;
6912   // NOTE: the qualifier in an ElaboratedType is optional.
6913   if (TL.getQualifierLoc()) {
6914     QualifierLoc
6915       = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6916     if (!QualifierLoc)
6917       return QualType();
6918   }
6919 
6920   QualType NamedT = getDerived().TransformType(TLB, TL.getNamedTypeLoc());
6921   if (NamedT.isNull())
6922     return QualType();
6923 
6924   // C++0x [dcl.type.elab]p2:
6925   //   If the identifier resolves to a typedef-name or the simple-template-id
6926   //   resolves to an alias template specialization, the
6927   //   elaborated-type-specifier is ill-formed.
6928   if (T->getKeyword() != ETK_None && T->getKeyword() != ETK_Typename) {
6929     if (const TemplateSpecializationType *TST =
6930           NamedT->getAs<TemplateSpecializationType>()) {
6931       TemplateName Template = TST->getTemplateName();
6932       if (TypeAliasTemplateDecl *TAT = dyn_cast_or_null<TypeAliasTemplateDecl>(
6933               Template.getAsTemplateDecl())) {
6934         SemaRef.Diag(TL.getNamedTypeLoc().getBeginLoc(),
6935                      diag::err_tag_reference_non_tag)
6936             << TAT << Sema::NTK_TypeAliasTemplate
6937             << ElaboratedType::getTagTypeKindForKeyword(T->getKeyword());
6938         SemaRef.Diag(TAT->getLocation(), diag::note_declared_at);
6939       }
6940     }
6941   }
6942 
6943   QualType Result = TL.getType();
6944   if (getDerived().AlwaysRebuild() ||
6945       QualifierLoc != TL.getQualifierLoc() ||
6946       NamedT != T->getNamedType()) {
6947     Result = getDerived().RebuildElaboratedType(TL.getElaboratedKeywordLoc(),
6948                                                 T->getKeyword(),
6949                                                 QualifierLoc, NamedT);
6950     if (Result.isNull())
6951       return QualType();
6952   }
6953 
6954   ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
6955   NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6956   NewTL.setQualifierLoc(QualifierLoc);
6957   return Result;
6958 }
6959 
6960 template<typename Derived>
6961 QualType TreeTransform<Derived>::TransformAttributedType(
6962                                                 TypeLocBuilder &TLB,
6963                                                 AttributedTypeLoc TL) {
6964   const AttributedType *oldType = TL.getTypePtr();
6965   QualType modifiedType = getDerived().TransformType(TLB, TL.getModifiedLoc());
6966   if (modifiedType.isNull())
6967     return QualType();
6968 
6969   // oldAttr can be null if we started with a QualType rather than a TypeLoc.
6970   const Attr *oldAttr = TL.getAttr();
6971   const Attr *newAttr = oldAttr ? getDerived().TransformAttr(oldAttr) : nullptr;
6972   if (oldAttr && !newAttr)
6973     return QualType();
6974 
6975   QualType result = TL.getType();
6976 
6977   // FIXME: dependent operand expressions?
6978   if (getDerived().AlwaysRebuild() ||
6979       modifiedType != oldType->getModifiedType()) {
6980     // TODO: this is really lame; we should really be rebuilding the
6981     // equivalent type from first principles.
6982     QualType equivalentType
6983       = getDerived().TransformType(oldType->getEquivalentType());
6984     if (equivalentType.isNull())
6985       return QualType();
6986 
6987     // Check whether we can add nullability; it is only represented as
6988     // type sugar, and therefore cannot be diagnosed in any other way.
6989     if (auto nullability = oldType->getImmediateNullability()) {
6990       if (!modifiedType->canHaveNullability()) {
6991         SemaRef.Diag(TL.getAttr()->getLocation(),
6992                      diag::err_nullability_nonpointer)
6993             << DiagNullabilityKind(*nullability, false) << modifiedType;
6994         return QualType();
6995       }
6996     }
6997 
6998     result = SemaRef.Context.getAttributedType(TL.getAttrKind(),
6999                                                modifiedType,
7000                                                equivalentType);
7001   }
7002 
7003   AttributedTypeLoc newTL = TLB.push<AttributedTypeLoc>(result);
7004   newTL.setAttr(newAttr);
7005   return result;
7006 }
7007 
7008 template <typename Derived>
7009 QualType TreeTransform<Derived>::TransformBTFTagAttributedType(
7010     TypeLocBuilder &TLB, BTFTagAttributedTypeLoc TL) {
7011   // The BTFTagAttributedType is available for C only.
7012   llvm_unreachable("Unexpected TreeTransform for BTFTagAttributedType");
7013 }
7014 
7015 template<typename Derived>
7016 QualType
7017 TreeTransform<Derived>::TransformParenType(TypeLocBuilder &TLB,
7018                                            ParenTypeLoc TL) {
7019   QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
7020   if (Inner.isNull())
7021     return QualType();
7022 
7023   QualType Result = TL.getType();
7024   if (getDerived().AlwaysRebuild() ||
7025       Inner != TL.getInnerLoc().getType()) {
7026     Result = getDerived().RebuildParenType(Inner);
7027     if (Result.isNull())
7028       return QualType();
7029   }
7030 
7031   ParenTypeLoc NewTL = TLB.push<ParenTypeLoc>(Result);
7032   NewTL.setLParenLoc(TL.getLParenLoc());
7033   NewTL.setRParenLoc(TL.getRParenLoc());
7034   return Result;
7035 }
7036 
7037 template <typename Derived>
7038 QualType
7039 TreeTransform<Derived>::TransformMacroQualifiedType(TypeLocBuilder &TLB,
7040                                                     MacroQualifiedTypeLoc TL) {
7041   QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
7042   if (Inner.isNull())
7043     return QualType();
7044 
7045   QualType Result = TL.getType();
7046   if (getDerived().AlwaysRebuild() || Inner != TL.getInnerLoc().getType()) {
7047     Result =
7048         getDerived().RebuildMacroQualifiedType(Inner, TL.getMacroIdentifier());
7049     if (Result.isNull())
7050       return QualType();
7051   }
7052 
7053   MacroQualifiedTypeLoc NewTL = TLB.push<MacroQualifiedTypeLoc>(Result);
7054   NewTL.setExpansionLoc(TL.getExpansionLoc());
7055   return Result;
7056 }
7057 
7058 template<typename Derived>
7059 QualType TreeTransform<Derived>::TransformDependentNameType(
7060     TypeLocBuilder &TLB, DependentNameTypeLoc TL) {
7061   return TransformDependentNameType(TLB, TL, false);
7062 }
7063 
7064 template<typename Derived>
7065 QualType TreeTransform<Derived>::TransformDependentNameType(
7066     TypeLocBuilder &TLB, DependentNameTypeLoc TL, bool DeducedTSTContext) {
7067   const DependentNameType *T = TL.getTypePtr();
7068 
7069   NestedNameSpecifierLoc QualifierLoc
7070     = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
7071   if (!QualifierLoc)
7072     return QualType();
7073 
7074   QualType Result
7075     = getDerived().RebuildDependentNameType(T->getKeyword(),
7076                                             TL.getElaboratedKeywordLoc(),
7077                                             QualifierLoc,
7078                                             T->getIdentifier(),
7079                                             TL.getNameLoc(),
7080                                             DeducedTSTContext);
7081   if (Result.isNull())
7082     return QualType();
7083 
7084   if (const ElaboratedType* ElabT = Result->getAs<ElaboratedType>()) {
7085     QualType NamedT = ElabT->getNamedType();
7086     TLB.pushTypeSpec(NamedT).setNameLoc(TL.getNameLoc());
7087 
7088     ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
7089     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
7090     NewTL.setQualifierLoc(QualifierLoc);
7091   } else {
7092     DependentNameTypeLoc NewTL = TLB.push<DependentNameTypeLoc>(Result);
7093     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
7094     NewTL.setQualifierLoc(QualifierLoc);
7095     NewTL.setNameLoc(TL.getNameLoc());
7096   }
7097   return Result;
7098 }
7099 
7100 template<typename Derived>
7101 QualType TreeTransform<Derived>::
7102           TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
7103                                  DependentTemplateSpecializationTypeLoc TL) {
7104   NestedNameSpecifierLoc QualifierLoc;
7105   if (TL.getQualifierLoc()) {
7106     QualifierLoc
7107       = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
7108     if (!QualifierLoc)
7109       return QualType();
7110   }
7111 
7112   return getDerived()
7113            .TransformDependentTemplateSpecializationType(TLB, TL, QualifierLoc);
7114 }
7115 
7116 template<typename Derived>
7117 QualType TreeTransform<Derived>::
7118 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
7119                                    DependentTemplateSpecializationTypeLoc TL,
7120                                        NestedNameSpecifierLoc QualifierLoc) {
7121   const DependentTemplateSpecializationType *T = TL.getTypePtr();
7122 
7123   TemplateArgumentListInfo NewTemplateArgs;
7124   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
7125   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
7126 
7127   typedef TemplateArgumentLocContainerIterator<
7128   DependentTemplateSpecializationTypeLoc> ArgIterator;
7129   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
7130                                               ArgIterator(TL, TL.getNumArgs()),
7131                                               NewTemplateArgs))
7132     return QualType();
7133 
7134   QualType Result = getDerived().RebuildDependentTemplateSpecializationType(
7135       T->getKeyword(), QualifierLoc, TL.getTemplateKeywordLoc(),
7136       T->getIdentifier(), TL.getTemplateNameLoc(), NewTemplateArgs,
7137       /*AllowInjectedClassName*/ false);
7138   if (Result.isNull())
7139     return QualType();
7140 
7141   if (const ElaboratedType *ElabT = dyn_cast<ElaboratedType>(Result)) {
7142     QualType NamedT = ElabT->getNamedType();
7143 
7144     // Copy information relevant to the template specialization.
7145     TemplateSpecializationTypeLoc NamedTL
7146       = TLB.push<TemplateSpecializationTypeLoc>(NamedT);
7147     NamedTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
7148     NamedTL.setTemplateNameLoc(TL.getTemplateNameLoc());
7149     NamedTL.setLAngleLoc(TL.getLAngleLoc());
7150     NamedTL.setRAngleLoc(TL.getRAngleLoc());
7151     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
7152       NamedTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
7153 
7154     // Copy information relevant to the elaborated type.
7155     ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
7156     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
7157     NewTL.setQualifierLoc(QualifierLoc);
7158   } else if (isa<DependentTemplateSpecializationType>(Result)) {
7159     DependentTemplateSpecializationTypeLoc SpecTL
7160       = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
7161     SpecTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
7162     SpecTL.setQualifierLoc(QualifierLoc);
7163     SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
7164     SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
7165     SpecTL.setLAngleLoc(TL.getLAngleLoc());
7166     SpecTL.setRAngleLoc(TL.getRAngleLoc());
7167     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
7168       SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
7169   } else {
7170     TemplateSpecializationTypeLoc SpecTL
7171       = TLB.push<TemplateSpecializationTypeLoc>(Result);
7172     SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
7173     SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
7174     SpecTL.setLAngleLoc(TL.getLAngleLoc());
7175     SpecTL.setRAngleLoc(TL.getRAngleLoc());
7176     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
7177       SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
7178   }
7179   return Result;
7180 }
7181 
7182 template<typename Derived>
7183 QualType TreeTransform<Derived>::TransformPackExpansionType(TypeLocBuilder &TLB,
7184                                                       PackExpansionTypeLoc TL) {
7185   QualType Pattern
7186     = getDerived().TransformType(TLB, TL.getPatternLoc());
7187   if (Pattern.isNull())
7188     return QualType();
7189 
7190   QualType Result = TL.getType();
7191   if (getDerived().AlwaysRebuild() ||
7192       Pattern != TL.getPatternLoc().getType()) {
7193     Result = getDerived().RebuildPackExpansionType(Pattern,
7194                                            TL.getPatternLoc().getSourceRange(),
7195                                                    TL.getEllipsisLoc(),
7196                                            TL.getTypePtr()->getNumExpansions());
7197     if (Result.isNull())
7198       return QualType();
7199   }
7200 
7201   PackExpansionTypeLoc NewT = TLB.push<PackExpansionTypeLoc>(Result);
7202   NewT.setEllipsisLoc(TL.getEllipsisLoc());
7203   return Result;
7204 }
7205 
7206 template<typename Derived>
7207 QualType
7208 TreeTransform<Derived>::TransformObjCInterfaceType(TypeLocBuilder &TLB,
7209                                                    ObjCInterfaceTypeLoc TL) {
7210   // ObjCInterfaceType is never dependent.
7211   TLB.pushFullCopy(TL);
7212   return TL.getType();
7213 }
7214 
7215 template<typename Derived>
7216 QualType
7217 TreeTransform<Derived>::TransformObjCTypeParamType(TypeLocBuilder &TLB,
7218                                                    ObjCTypeParamTypeLoc TL) {
7219   const ObjCTypeParamType *T = TL.getTypePtr();
7220   ObjCTypeParamDecl *OTP = cast_or_null<ObjCTypeParamDecl>(
7221       getDerived().TransformDecl(T->getDecl()->getLocation(), T->getDecl()));
7222   if (!OTP)
7223     return QualType();
7224 
7225   QualType Result = TL.getType();
7226   if (getDerived().AlwaysRebuild() ||
7227       OTP != T->getDecl()) {
7228     Result = getDerived().RebuildObjCTypeParamType(
7229         OTP, TL.getProtocolLAngleLoc(),
7230         llvm::ArrayRef(TL.getTypePtr()->qual_begin(), TL.getNumProtocols()),
7231         TL.getProtocolLocs(), TL.getProtocolRAngleLoc());
7232     if (Result.isNull())
7233       return QualType();
7234   }
7235 
7236   ObjCTypeParamTypeLoc NewTL = TLB.push<ObjCTypeParamTypeLoc>(Result);
7237   if (TL.getNumProtocols()) {
7238     NewTL.setProtocolLAngleLoc(TL.getProtocolLAngleLoc());
7239     for (unsigned i = 0, n = TL.getNumProtocols(); i != n; ++i)
7240       NewTL.setProtocolLoc(i, TL.getProtocolLoc(i));
7241     NewTL.setProtocolRAngleLoc(TL.getProtocolRAngleLoc());
7242   }
7243   return Result;
7244 }
7245 
7246 template<typename Derived>
7247 QualType
7248 TreeTransform<Derived>::TransformObjCObjectType(TypeLocBuilder &TLB,
7249                                                 ObjCObjectTypeLoc TL) {
7250   // Transform base type.
7251   QualType BaseType = getDerived().TransformType(TLB, TL.getBaseLoc());
7252   if (BaseType.isNull())
7253     return QualType();
7254 
7255   bool AnyChanged = BaseType != TL.getBaseLoc().getType();
7256 
7257   // Transform type arguments.
7258   SmallVector<TypeSourceInfo *, 4> NewTypeArgInfos;
7259   for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i) {
7260     TypeSourceInfo *TypeArgInfo = TL.getTypeArgTInfo(i);
7261     TypeLoc TypeArgLoc = TypeArgInfo->getTypeLoc();
7262     QualType TypeArg = TypeArgInfo->getType();
7263     if (auto PackExpansionLoc = TypeArgLoc.getAs<PackExpansionTypeLoc>()) {
7264       AnyChanged = true;
7265 
7266       // We have a pack expansion. Instantiate it.
7267       const auto *PackExpansion = PackExpansionLoc.getType()
7268                                     ->castAs<PackExpansionType>();
7269       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
7270       SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
7271                                               Unexpanded);
7272       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
7273 
7274       // Determine whether the set of unexpanded parameter packs can
7275       // and should be expanded.
7276       TypeLoc PatternLoc = PackExpansionLoc.getPatternLoc();
7277       bool Expand = false;
7278       bool RetainExpansion = false;
7279       std::optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
7280       if (getDerived().TryExpandParameterPacks(
7281             PackExpansionLoc.getEllipsisLoc(), PatternLoc.getSourceRange(),
7282             Unexpanded, Expand, RetainExpansion, NumExpansions))
7283         return QualType();
7284 
7285       if (!Expand) {
7286         // We can't expand this pack expansion into separate arguments yet;
7287         // just substitute into the pattern and create a new pack expansion
7288         // type.
7289         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
7290 
7291         TypeLocBuilder TypeArgBuilder;
7292         TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
7293         QualType NewPatternType = getDerived().TransformType(TypeArgBuilder,
7294                                                              PatternLoc);
7295         if (NewPatternType.isNull())
7296           return QualType();
7297 
7298         QualType NewExpansionType = SemaRef.Context.getPackExpansionType(
7299                                       NewPatternType, NumExpansions);
7300         auto NewExpansionLoc = TLB.push<PackExpansionTypeLoc>(NewExpansionType);
7301         NewExpansionLoc.setEllipsisLoc(PackExpansionLoc.getEllipsisLoc());
7302         NewTypeArgInfos.push_back(
7303           TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewExpansionType));
7304         continue;
7305       }
7306 
7307       // Substitute into the pack expansion pattern for each slice of the
7308       // pack.
7309       for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
7310         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
7311 
7312         TypeLocBuilder TypeArgBuilder;
7313         TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
7314 
7315         QualType NewTypeArg = getDerived().TransformType(TypeArgBuilder,
7316                                                          PatternLoc);
7317         if (NewTypeArg.isNull())
7318           return QualType();
7319 
7320         NewTypeArgInfos.push_back(
7321           TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
7322       }
7323 
7324       continue;
7325     }
7326 
7327     TypeLocBuilder TypeArgBuilder;
7328     TypeArgBuilder.reserve(TypeArgLoc.getFullDataSize());
7329     QualType NewTypeArg =
7330         getDerived().TransformType(TypeArgBuilder, TypeArgLoc);
7331     if (NewTypeArg.isNull())
7332       return QualType();
7333 
7334     // If nothing changed, just keep the old TypeSourceInfo.
7335     if (NewTypeArg == TypeArg) {
7336       NewTypeArgInfos.push_back(TypeArgInfo);
7337       continue;
7338     }
7339 
7340     NewTypeArgInfos.push_back(
7341       TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
7342     AnyChanged = true;
7343   }
7344 
7345   QualType Result = TL.getType();
7346   if (getDerived().AlwaysRebuild() || AnyChanged) {
7347     // Rebuild the type.
7348     Result = getDerived().RebuildObjCObjectType(
7349         BaseType, TL.getBeginLoc(), TL.getTypeArgsLAngleLoc(), NewTypeArgInfos,
7350         TL.getTypeArgsRAngleLoc(), TL.getProtocolLAngleLoc(),
7351         llvm::ArrayRef(TL.getTypePtr()->qual_begin(), TL.getNumProtocols()),
7352         TL.getProtocolLocs(), TL.getProtocolRAngleLoc());
7353 
7354     if (Result.isNull())
7355       return QualType();
7356   }
7357 
7358   ObjCObjectTypeLoc NewT = TLB.push<ObjCObjectTypeLoc>(Result);
7359   NewT.setHasBaseTypeAsWritten(true);
7360   NewT.setTypeArgsLAngleLoc(TL.getTypeArgsLAngleLoc());
7361   for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i)
7362     NewT.setTypeArgTInfo(i, NewTypeArgInfos[i]);
7363   NewT.setTypeArgsRAngleLoc(TL.getTypeArgsRAngleLoc());
7364   NewT.setProtocolLAngleLoc(TL.getProtocolLAngleLoc());
7365   for (unsigned i = 0, n = TL.getNumProtocols(); i != n; ++i)
7366     NewT.setProtocolLoc(i, TL.getProtocolLoc(i));
7367   NewT.setProtocolRAngleLoc(TL.getProtocolRAngleLoc());
7368   return Result;
7369 }
7370 
7371 template<typename Derived>
7372 QualType
7373 TreeTransform<Derived>::TransformObjCObjectPointerType(TypeLocBuilder &TLB,
7374                                                ObjCObjectPointerTypeLoc TL) {
7375   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
7376   if (PointeeType.isNull())
7377     return QualType();
7378 
7379   QualType Result = TL.getType();
7380   if (getDerived().AlwaysRebuild() ||
7381       PointeeType != TL.getPointeeLoc().getType()) {
7382     Result = getDerived().RebuildObjCObjectPointerType(PointeeType,
7383                                                        TL.getStarLoc());
7384     if (Result.isNull())
7385       return QualType();
7386   }
7387 
7388   ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
7389   NewT.setStarLoc(TL.getStarLoc());
7390   return Result;
7391 }
7392 
7393 //===----------------------------------------------------------------------===//
7394 // Statement transformation
7395 //===----------------------------------------------------------------------===//
7396 template<typename Derived>
7397 StmtResult
7398 TreeTransform<Derived>::TransformNullStmt(NullStmt *S) {
7399   return S;
7400 }
7401 
7402 template<typename Derived>
7403 StmtResult
7404 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S) {
7405   return getDerived().TransformCompoundStmt(S, false);
7406 }
7407 
7408 template<typename Derived>
7409 StmtResult
7410 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S,
7411                                               bool IsStmtExpr) {
7412   Sema::CompoundScopeRAII CompoundScope(getSema());
7413 
7414   const Stmt *ExprResult = S->getStmtExprResult();
7415   bool SubStmtInvalid = false;
7416   bool SubStmtChanged = false;
7417   SmallVector<Stmt*, 8> Statements;
7418   for (auto *B : S->body()) {
7419     StmtResult Result = getDerived().TransformStmt(
7420         B, IsStmtExpr && B == ExprResult ? SDK_StmtExprResult : SDK_Discarded);
7421 
7422     if (Result.isInvalid()) {
7423       // Immediately fail if this was a DeclStmt, since it's very
7424       // likely that this will cause problems for future statements.
7425       if (isa<DeclStmt>(B))
7426         return StmtError();
7427 
7428       // Otherwise, just keep processing substatements and fail later.
7429       SubStmtInvalid = true;
7430       continue;
7431     }
7432 
7433     SubStmtChanged = SubStmtChanged || Result.get() != B;
7434     Statements.push_back(Result.getAs<Stmt>());
7435   }
7436 
7437   if (SubStmtInvalid)
7438     return StmtError();
7439 
7440   if (!getDerived().AlwaysRebuild() &&
7441       !SubStmtChanged)
7442     return S;
7443 
7444   return getDerived().RebuildCompoundStmt(S->getLBracLoc(),
7445                                           Statements,
7446                                           S->getRBracLoc(),
7447                                           IsStmtExpr);
7448 }
7449 
7450 template<typename Derived>
7451 StmtResult
7452 TreeTransform<Derived>::TransformCaseStmt(CaseStmt *S) {
7453   ExprResult LHS, RHS;
7454   {
7455     EnterExpressionEvaluationContext Unevaluated(
7456         SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
7457 
7458     // Transform the left-hand case value.
7459     LHS = getDerived().TransformExpr(S->getLHS());
7460     LHS = SemaRef.ActOnCaseExpr(S->getCaseLoc(), LHS);
7461     if (LHS.isInvalid())
7462       return StmtError();
7463 
7464     // Transform the right-hand case value (for the GNU case-range extension).
7465     RHS = getDerived().TransformExpr(S->getRHS());
7466     RHS = SemaRef.ActOnCaseExpr(S->getCaseLoc(), RHS);
7467     if (RHS.isInvalid())
7468       return StmtError();
7469   }
7470 
7471   // Build the case statement.
7472   // Case statements are always rebuilt so that they will attached to their
7473   // transformed switch statement.
7474   StmtResult Case = getDerived().RebuildCaseStmt(S->getCaseLoc(),
7475                                                        LHS.get(),
7476                                                        S->getEllipsisLoc(),
7477                                                        RHS.get(),
7478                                                        S->getColonLoc());
7479   if (Case.isInvalid())
7480     return StmtError();
7481 
7482   // Transform the statement following the case
7483   StmtResult SubStmt =
7484       getDerived().TransformStmt(S->getSubStmt());
7485   if (SubStmt.isInvalid())
7486     return StmtError();
7487 
7488   // Attach the body to the case statement
7489   return getDerived().RebuildCaseStmtBody(Case.get(), SubStmt.get());
7490 }
7491 
7492 template <typename Derived>
7493 StmtResult TreeTransform<Derived>::TransformDefaultStmt(DefaultStmt *S) {
7494   // Transform the statement following the default case
7495   StmtResult SubStmt =
7496       getDerived().TransformStmt(S->getSubStmt());
7497   if (SubStmt.isInvalid())
7498     return StmtError();
7499 
7500   // Default statements are always rebuilt
7501   return getDerived().RebuildDefaultStmt(S->getDefaultLoc(), S->getColonLoc(),
7502                                          SubStmt.get());
7503 }
7504 
7505 template<typename Derived>
7506 StmtResult
7507 TreeTransform<Derived>::TransformLabelStmt(LabelStmt *S, StmtDiscardKind SDK) {
7508   StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt(), SDK);
7509   if (SubStmt.isInvalid())
7510     return StmtError();
7511 
7512   Decl *LD = getDerived().TransformDecl(S->getDecl()->getLocation(),
7513                                         S->getDecl());
7514   if (!LD)
7515     return StmtError();
7516 
7517   // If we're transforming "in-place" (we're not creating new local
7518   // declarations), assume we're replacing the old label statement
7519   // and clear out the reference to it.
7520   if (LD == S->getDecl())
7521     S->getDecl()->setStmt(nullptr);
7522 
7523   // FIXME: Pass the real colon location in.
7524   return getDerived().RebuildLabelStmt(S->getIdentLoc(),
7525                                        cast<LabelDecl>(LD), SourceLocation(),
7526                                        SubStmt.get());
7527 }
7528 
7529 template <typename Derived>
7530 const Attr *TreeTransform<Derived>::TransformAttr(const Attr *R) {
7531   if (!R)
7532     return R;
7533 
7534   switch (R->getKind()) {
7535 // Transform attributes with a pragma spelling by calling TransformXXXAttr.
7536 #define ATTR(X)
7537 #define PRAGMA_SPELLING_ATTR(X)                                                \
7538   case attr::X:                                                                \
7539     return getDerived().Transform##X##Attr(cast<X##Attr>(R));
7540 #include "clang/Basic/AttrList.inc"
7541   default:
7542     return R;
7543   }
7544 }
7545 
7546 template <typename Derived>
7547 StmtResult
7548 TreeTransform<Derived>::TransformAttributedStmt(AttributedStmt *S,
7549                                                 StmtDiscardKind SDK) {
7550   bool AttrsChanged = false;
7551   SmallVector<const Attr *, 1> Attrs;
7552 
7553   // Visit attributes and keep track if any are transformed.
7554   for (const auto *I : S->getAttrs()) {
7555     const Attr *R = getDerived().TransformAttr(I);
7556     AttrsChanged |= (I != R);
7557     if (R)
7558       Attrs.push_back(R);
7559   }
7560 
7561   StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt(), SDK);
7562   if (SubStmt.isInvalid())
7563     return StmtError();
7564 
7565   if (SubStmt.get() == S->getSubStmt() && !AttrsChanged)
7566     return S;
7567 
7568   // If transforming the attributes failed for all of the attributes in the
7569   // statement, don't make an AttributedStmt without attributes.
7570   if (Attrs.empty())
7571     return SubStmt;
7572 
7573   return getDerived().RebuildAttributedStmt(S->getAttrLoc(), Attrs,
7574                                             SubStmt.get());
7575 }
7576 
7577 template<typename Derived>
7578 StmtResult
7579 TreeTransform<Derived>::TransformIfStmt(IfStmt *S) {
7580   // Transform the initialization statement
7581   StmtResult Init = getDerived().TransformStmt(S->getInit());
7582   if (Init.isInvalid())
7583     return StmtError();
7584 
7585   Sema::ConditionResult Cond;
7586   if (!S->isConsteval()) {
7587     // Transform the condition
7588     Cond = getDerived().TransformCondition(
7589         S->getIfLoc(), S->getConditionVariable(), S->getCond(),
7590         S->isConstexpr() ? Sema::ConditionKind::ConstexprIf
7591                          : Sema::ConditionKind::Boolean);
7592     if (Cond.isInvalid())
7593       return StmtError();
7594   }
7595 
7596   // If this is a constexpr if, determine which arm we should instantiate.
7597   std::optional<bool> ConstexprConditionValue;
7598   if (S->isConstexpr())
7599     ConstexprConditionValue = Cond.getKnownValue();
7600 
7601   // Transform the "then" branch.
7602   StmtResult Then;
7603   if (!ConstexprConditionValue || *ConstexprConditionValue) {
7604     Then = getDerived().TransformStmt(S->getThen());
7605     if (Then.isInvalid())
7606       return StmtError();
7607   } else {
7608     Then = new (getSema().Context) NullStmt(S->getThen()->getBeginLoc());
7609   }
7610 
7611   // Transform the "else" branch.
7612   StmtResult Else;
7613   if (!ConstexprConditionValue || !*ConstexprConditionValue) {
7614     Else = getDerived().TransformStmt(S->getElse());
7615     if (Else.isInvalid())
7616       return StmtError();
7617   }
7618 
7619   if (!getDerived().AlwaysRebuild() &&
7620       Init.get() == S->getInit() &&
7621       Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
7622       Then.get() == S->getThen() &&
7623       Else.get() == S->getElse())
7624     return S;
7625 
7626   return getDerived().RebuildIfStmt(
7627       S->getIfLoc(), S->getStatementKind(), S->getLParenLoc(), Cond,
7628       S->getRParenLoc(), Init.get(), Then.get(), S->getElseLoc(), Else.get());
7629 }
7630 
7631 template<typename Derived>
7632 StmtResult
7633 TreeTransform<Derived>::TransformSwitchStmt(SwitchStmt *S) {
7634   // Transform the initialization statement
7635   StmtResult Init = getDerived().TransformStmt(S->getInit());
7636   if (Init.isInvalid())
7637     return StmtError();
7638 
7639   // Transform the condition.
7640   Sema::ConditionResult Cond = getDerived().TransformCondition(
7641       S->getSwitchLoc(), S->getConditionVariable(), S->getCond(),
7642       Sema::ConditionKind::Switch);
7643   if (Cond.isInvalid())
7644     return StmtError();
7645 
7646   // Rebuild the switch statement.
7647   StmtResult Switch =
7648       getDerived().RebuildSwitchStmtStart(S->getSwitchLoc(), S->getLParenLoc(),
7649                                           Init.get(), Cond, S->getRParenLoc());
7650   if (Switch.isInvalid())
7651     return StmtError();
7652 
7653   // Transform the body of the switch statement.
7654   StmtResult Body = getDerived().TransformStmt(S->getBody());
7655   if (Body.isInvalid())
7656     return StmtError();
7657 
7658   // Complete the switch statement.
7659   return getDerived().RebuildSwitchStmtBody(S->getSwitchLoc(), Switch.get(),
7660                                             Body.get());
7661 }
7662 
7663 template<typename Derived>
7664 StmtResult
7665 TreeTransform<Derived>::TransformWhileStmt(WhileStmt *S) {
7666   // Transform the condition
7667   Sema::ConditionResult Cond = getDerived().TransformCondition(
7668       S->getWhileLoc(), S->getConditionVariable(), S->getCond(),
7669       Sema::ConditionKind::Boolean);
7670   if (Cond.isInvalid())
7671     return StmtError();
7672 
7673   // Transform the body
7674   StmtResult Body = getDerived().TransformStmt(S->getBody());
7675   if (Body.isInvalid())
7676     return StmtError();
7677 
7678   if (!getDerived().AlwaysRebuild() &&
7679       Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
7680       Body.get() == S->getBody())
7681     return Owned(S);
7682 
7683   return getDerived().RebuildWhileStmt(S->getWhileLoc(), S->getLParenLoc(),
7684                                        Cond, S->getRParenLoc(), Body.get());
7685 }
7686 
7687 template<typename Derived>
7688 StmtResult
7689 TreeTransform<Derived>::TransformDoStmt(DoStmt *S) {
7690   // Transform the body
7691   StmtResult Body = getDerived().TransformStmt(S->getBody());
7692   if (Body.isInvalid())
7693     return StmtError();
7694 
7695   // Transform the condition
7696   ExprResult Cond = getDerived().TransformExpr(S->getCond());
7697   if (Cond.isInvalid())
7698     return StmtError();
7699 
7700   if (!getDerived().AlwaysRebuild() &&
7701       Cond.get() == S->getCond() &&
7702       Body.get() == S->getBody())
7703     return S;
7704 
7705   return getDerived().RebuildDoStmt(S->getDoLoc(), Body.get(), S->getWhileLoc(),
7706                                     /*FIXME:*/S->getWhileLoc(), Cond.get(),
7707                                     S->getRParenLoc());
7708 }
7709 
7710 template<typename Derived>
7711 StmtResult
7712 TreeTransform<Derived>::TransformForStmt(ForStmt *S) {
7713   if (getSema().getLangOpts().OpenMP)
7714     getSema().startOpenMPLoop();
7715 
7716   // Transform the initialization statement
7717   StmtResult Init = getDerived().TransformStmt(S->getInit());
7718   if (Init.isInvalid())
7719     return StmtError();
7720 
7721   // In OpenMP loop region loop control variable must be captured and be
7722   // private. Perform analysis of first part (if any).
7723   if (getSema().getLangOpts().OpenMP && Init.isUsable())
7724     getSema().ActOnOpenMPLoopInitialization(S->getForLoc(), Init.get());
7725 
7726   // Transform the condition
7727   Sema::ConditionResult Cond = getDerived().TransformCondition(
7728       S->getForLoc(), S->getConditionVariable(), S->getCond(),
7729       Sema::ConditionKind::Boolean);
7730   if (Cond.isInvalid())
7731     return StmtError();
7732 
7733   // Transform the increment
7734   ExprResult Inc = getDerived().TransformExpr(S->getInc());
7735   if (Inc.isInvalid())
7736     return StmtError();
7737 
7738   Sema::FullExprArg FullInc(getSema().MakeFullDiscardedValueExpr(Inc.get()));
7739   if (S->getInc() && !FullInc.get())
7740     return StmtError();
7741 
7742   // Transform the body
7743   StmtResult Body = getDerived().TransformStmt(S->getBody());
7744   if (Body.isInvalid())
7745     return StmtError();
7746 
7747   if (!getDerived().AlwaysRebuild() &&
7748       Init.get() == S->getInit() &&
7749       Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
7750       Inc.get() == S->getInc() &&
7751       Body.get() == S->getBody())
7752     return S;
7753 
7754   return getDerived().RebuildForStmt(S->getForLoc(), S->getLParenLoc(),
7755                                      Init.get(), Cond, FullInc,
7756                                      S->getRParenLoc(), Body.get());
7757 }
7758 
7759 template<typename Derived>
7760 StmtResult
7761 TreeTransform<Derived>::TransformGotoStmt(GotoStmt *S) {
7762   Decl *LD = getDerived().TransformDecl(S->getLabel()->getLocation(),
7763                                         S->getLabel());
7764   if (!LD)
7765     return StmtError();
7766 
7767   // Goto statements must always be rebuilt, to resolve the label.
7768   return getDerived().RebuildGotoStmt(S->getGotoLoc(), S->getLabelLoc(),
7769                                       cast<LabelDecl>(LD));
7770 }
7771 
7772 template<typename Derived>
7773 StmtResult
7774 TreeTransform<Derived>::TransformIndirectGotoStmt(IndirectGotoStmt *S) {
7775   ExprResult Target = getDerived().TransformExpr(S->getTarget());
7776   if (Target.isInvalid())
7777     return StmtError();
7778   Target = SemaRef.MaybeCreateExprWithCleanups(Target.get());
7779 
7780   if (!getDerived().AlwaysRebuild() &&
7781       Target.get() == S->getTarget())
7782     return S;
7783 
7784   return getDerived().RebuildIndirectGotoStmt(S->getGotoLoc(), S->getStarLoc(),
7785                                               Target.get());
7786 }
7787 
7788 template<typename Derived>
7789 StmtResult
7790 TreeTransform<Derived>::TransformContinueStmt(ContinueStmt *S) {
7791   return S;
7792 }
7793 
7794 template<typename Derived>
7795 StmtResult
7796 TreeTransform<Derived>::TransformBreakStmt(BreakStmt *S) {
7797   return S;
7798 }
7799 
7800 template<typename Derived>
7801 StmtResult
7802 TreeTransform<Derived>::TransformReturnStmt(ReturnStmt *S) {
7803   ExprResult Result = getDerived().TransformInitializer(S->getRetValue(),
7804                                                         /*NotCopyInit*/false);
7805   if (Result.isInvalid())
7806     return StmtError();
7807 
7808   // FIXME: We always rebuild the return statement because there is no way
7809   // to tell whether the return type of the function has changed.
7810   return getDerived().RebuildReturnStmt(S->getReturnLoc(), Result.get());
7811 }
7812 
7813 template<typename Derived>
7814 StmtResult
7815 TreeTransform<Derived>::TransformDeclStmt(DeclStmt *S) {
7816   bool DeclChanged = false;
7817   SmallVector<Decl *, 4> Decls;
7818   for (auto *D : S->decls()) {
7819     Decl *Transformed = getDerived().TransformDefinition(D->getLocation(), D);
7820     if (!Transformed)
7821       return StmtError();
7822 
7823     if (Transformed != D)
7824       DeclChanged = true;
7825 
7826     Decls.push_back(Transformed);
7827   }
7828 
7829   if (!getDerived().AlwaysRebuild() && !DeclChanged)
7830     return S;
7831 
7832   return getDerived().RebuildDeclStmt(Decls, S->getBeginLoc(), S->getEndLoc());
7833 }
7834 
7835 template<typename Derived>
7836 StmtResult
7837 TreeTransform<Derived>::TransformGCCAsmStmt(GCCAsmStmt *S) {
7838 
7839   SmallVector<Expr*, 8> Constraints;
7840   SmallVector<Expr*, 8> Exprs;
7841   SmallVector<IdentifierInfo *, 4> Names;
7842 
7843   ExprResult AsmString;
7844   SmallVector<Expr*, 8> Clobbers;
7845 
7846   bool ExprsChanged = false;
7847 
7848   // Go through the outputs.
7849   for (unsigned I = 0, E = S->getNumOutputs(); I != E; ++I) {
7850     Names.push_back(S->getOutputIdentifier(I));
7851 
7852     // No need to transform the constraint literal.
7853     Constraints.push_back(S->getOutputConstraintLiteral(I));
7854 
7855     // Transform the output expr.
7856     Expr *OutputExpr = S->getOutputExpr(I);
7857     ExprResult Result = getDerived().TransformExpr(OutputExpr);
7858     if (Result.isInvalid())
7859       return StmtError();
7860 
7861     ExprsChanged |= Result.get() != OutputExpr;
7862 
7863     Exprs.push_back(Result.get());
7864   }
7865 
7866   // Go through the inputs.
7867   for (unsigned I = 0, E = S->getNumInputs(); I != E; ++I) {
7868     Names.push_back(S->getInputIdentifier(I));
7869 
7870     // No need to transform the constraint literal.
7871     Constraints.push_back(S->getInputConstraintLiteral(I));
7872 
7873     // Transform the input expr.
7874     Expr *InputExpr = S->getInputExpr(I);
7875     ExprResult Result = getDerived().TransformExpr(InputExpr);
7876     if (Result.isInvalid())
7877       return StmtError();
7878 
7879     ExprsChanged |= Result.get() != InputExpr;
7880 
7881     Exprs.push_back(Result.get());
7882   }
7883 
7884   // Go through the Labels.
7885   for (unsigned I = 0, E = S->getNumLabels(); I != E; ++I) {
7886     Names.push_back(S->getLabelIdentifier(I));
7887 
7888     ExprResult Result = getDerived().TransformExpr(S->getLabelExpr(I));
7889     if (Result.isInvalid())
7890       return StmtError();
7891     ExprsChanged |= Result.get() != S->getLabelExpr(I);
7892     Exprs.push_back(Result.get());
7893   }
7894   if (!getDerived().AlwaysRebuild() && !ExprsChanged)
7895     return S;
7896 
7897   // Go through the clobbers.
7898   for (unsigned I = 0, E = S->getNumClobbers(); I != E; ++I)
7899     Clobbers.push_back(S->getClobberStringLiteral(I));
7900 
7901   // No need to transform the asm string literal.
7902   AsmString = S->getAsmString();
7903   return getDerived().RebuildGCCAsmStmt(S->getAsmLoc(), S->isSimple(),
7904                                         S->isVolatile(), S->getNumOutputs(),
7905                                         S->getNumInputs(), Names.data(),
7906                                         Constraints, Exprs, AsmString.get(),
7907                                         Clobbers, S->getNumLabels(),
7908                                         S->getRParenLoc());
7909 }
7910 
7911 template<typename Derived>
7912 StmtResult
7913 TreeTransform<Derived>::TransformMSAsmStmt(MSAsmStmt *S) {
7914   ArrayRef<Token> AsmToks = llvm::ArrayRef(S->getAsmToks(), S->getNumAsmToks());
7915 
7916   bool HadError = false, HadChange = false;
7917 
7918   ArrayRef<Expr*> SrcExprs = S->getAllExprs();
7919   SmallVector<Expr*, 8> TransformedExprs;
7920   TransformedExprs.reserve(SrcExprs.size());
7921   for (unsigned i = 0, e = SrcExprs.size(); i != e; ++i) {
7922     ExprResult Result = getDerived().TransformExpr(SrcExprs[i]);
7923     if (!Result.isUsable()) {
7924       HadError = true;
7925     } else {
7926       HadChange |= (Result.get() != SrcExprs[i]);
7927       TransformedExprs.push_back(Result.get());
7928     }
7929   }
7930 
7931   if (HadError) return StmtError();
7932   if (!HadChange && !getDerived().AlwaysRebuild())
7933     return Owned(S);
7934 
7935   return getDerived().RebuildMSAsmStmt(S->getAsmLoc(), S->getLBraceLoc(),
7936                                        AsmToks, S->getAsmString(),
7937                                        S->getNumOutputs(), S->getNumInputs(),
7938                                        S->getAllConstraints(), S->getClobbers(),
7939                                        TransformedExprs, S->getEndLoc());
7940 }
7941 
7942 // C++ Coroutines TS
7943 
7944 template<typename Derived>
7945 StmtResult
7946 TreeTransform<Derived>::TransformCoroutineBodyStmt(CoroutineBodyStmt *S) {
7947   auto *ScopeInfo = SemaRef.getCurFunction();
7948   auto *FD = cast<FunctionDecl>(SemaRef.CurContext);
7949   assert(FD && ScopeInfo && !ScopeInfo->CoroutinePromise &&
7950          ScopeInfo->NeedsCoroutineSuspends &&
7951          ScopeInfo->CoroutineSuspends.first == nullptr &&
7952          ScopeInfo->CoroutineSuspends.second == nullptr &&
7953          "expected clean scope info");
7954 
7955   // Set that we have (possibly-invalid) suspend points before we do anything
7956   // that may fail.
7957   ScopeInfo->setNeedsCoroutineSuspends(false);
7958 
7959   // We re-build the coroutine promise object (and the coroutine parameters its
7960   // type and constructor depend on) based on the types used in our current
7961   // function. We must do so, and set it on the current FunctionScopeInfo,
7962   // before attempting to transform the other parts of the coroutine body
7963   // statement, such as the implicit suspend statements (because those
7964   // statements reference the FunctionScopeInfo::CoroutinePromise).
7965   if (!SemaRef.buildCoroutineParameterMoves(FD->getLocation()))
7966     return StmtError();
7967   auto *Promise = SemaRef.buildCoroutinePromise(FD->getLocation());
7968   if (!Promise)
7969     return StmtError();
7970   getDerived().transformedLocalDecl(S->getPromiseDecl(), {Promise});
7971   ScopeInfo->CoroutinePromise = Promise;
7972 
7973   // Transform the implicit coroutine statements constructed using dependent
7974   // types during the previous parse: initial and final suspensions, the return
7975   // object, and others. We also transform the coroutine function's body.
7976   StmtResult InitSuspend = getDerived().TransformStmt(S->getInitSuspendStmt());
7977   if (InitSuspend.isInvalid())
7978     return StmtError();
7979   StmtResult FinalSuspend =
7980       getDerived().TransformStmt(S->getFinalSuspendStmt());
7981   if (FinalSuspend.isInvalid() ||
7982       !SemaRef.checkFinalSuspendNoThrow(FinalSuspend.get()))
7983     return StmtError();
7984   ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
7985   assert(isa<Expr>(InitSuspend.get()) && isa<Expr>(FinalSuspend.get()));
7986 
7987   StmtResult BodyRes = getDerived().TransformStmt(S->getBody());
7988   if (BodyRes.isInvalid())
7989     return StmtError();
7990 
7991   CoroutineStmtBuilder Builder(SemaRef, *FD, *ScopeInfo, BodyRes.get());
7992   if (Builder.isInvalid())
7993     return StmtError();
7994 
7995   Expr *ReturnObject = S->getReturnValueInit();
7996   assert(ReturnObject && "the return object is expected to be valid");
7997   ExprResult Res = getDerived().TransformInitializer(ReturnObject,
7998                                                      /*NoCopyInit*/ false);
7999   if (Res.isInvalid())
8000     return StmtError();
8001   Builder.ReturnValue = Res.get();
8002 
8003   // If during the previous parse the coroutine still had a dependent promise
8004   // statement, we may need to build some implicit coroutine statements
8005   // (such as exception and fallthrough handlers) for the first time.
8006   if (S->hasDependentPromiseType()) {
8007     // We can only build these statements, however, if the current promise type
8008     // is not dependent.
8009     if (!Promise->getType()->isDependentType()) {
8010       assert(!S->getFallthroughHandler() && !S->getExceptionHandler() &&
8011              !S->getReturnStmtOnAllocFailure() && !S->getDeallocate() &&
8012              "these nodes should not have been built yet");
8013       if (!Builder.buildDependentStatements())
8014         return StmtError();
8015     }
8016   } else {
8017     if (auto *OnFallthrough = S->getFallthroughHandler()) {
8018       StmtResult Res = getDerived().TransformStmt(OnFallthrough);
8019       if (Res.isInvalid())
8020         return StmtError();
8021       Builder.OnFallthrough = Res.get();
8022     }
8023 
8024     if (auto *OnException = S->getExceptionHandler()) {
8025       StmtResult Res = getDerived().TransformStmt(OnException);
8026       if (Res.isInvalid())
8027         return StmtError();
8028       Builder.OnException = Res.get();
8029     }
8030 
8031     if (auto *OnAllocFailure = S->getReturnStmtOnAllocFailure()) {
8032       StmtResult Res = getDerived().TransformStmt(OnAllocFailure);
8033       if (Res.isInvalid())
8034         return StmtError();
8035       Builder.ReturnStmtOnAllocFailure = Res.get();
8036     }
8037 
8038     // Transform any additional statements we may have already built
8039     assert(S->getAllocate() && S->getDeallocate() &&
8040            "allocation and deallocation calls must already be built");
8041     ExprResult AllocRes = getDerived().TransformExpr(S->getAllocate());
8042     if (AllocRes.isInvalid())
8043       return StmtError();
8044     Builder.Allocate = AllocRes.get();
8045 
8046     ExprResult DeallocRes = getDerived().TransformExpr(S->getDeallocate());
8047     if (DeallocRes.isInvalid())
8048       return StmtError();
8049     Builder.Deallocate = DeallocRes.get();
8050 
8051     if (auto *ReturnStmt = S->getReturnStmt()) {
8052       StmtResult Res = getDerived().TransformStmt(ReturnStmt);
8053       if (Res.isInvalid())
8054         return StmtError();
8055       Builder.ReturnStmt = Res.get();
8056     }
8057   }
8058 
8059   return getDerived().RebuildCoroutineBodyStmt(Builder);
8060 }
8061 
8062 template<typename Derived>
8063 StmtResult
8064 TreeTransform<Derived>::TransformCoreturnStmt(CoreturnStmt *S) {
8065   ExprResult Result = getDerived().TransformInitializer(S->getOperand(),
8066                                                         /*NotCopyInit*/false);
8067   if (Result.isInvalid())
8068     return StmtError();
8069 
8070   // Always rebuild; we don't know if this needs to be injected into a new
8071   // context or if the promise type has changed.
8072   return getDerived().RebuildCoreturnStmt(S->getKeywordLoc(), Result.get(),
8073                                           S->isImplicit());
8074 }
8075 
8076 template <typename Derived>
8077 ExprResult TreeTransform<Derived>::TransformCoawaitExpr(CoawaitExpr *E) {
8078   ExprResult Operand = getDerived().TransformInitializer(E->getOperand(),
8079                                                          /*NotCopyInit*/ false);
8080   if (Operand.isInvalid())
8081     return ExprError();
8082 
8083   // Rebuild the common-expr from the operand rather than transforming it
8084   // separately.
8085 
8086   // FIXME: getCurScope() should not be used during template instantiation.
8087   // We should pick up the set of unqualified lookup results for operator
8088   // co_await during the initial parse.
8089   ExprResult Lookup = getSema().BuildOperatorCoawaitLookupExpr(
8090       getSema().getCurScope(), E->getKeywordLoc());
8091 
8092   // Always rebuild; we don't know if this needs to be injected into a new
8093   // context or if the promise type has changed.
8094   return getDerived().RebuildCoawaitExpr(
8095       E->getKeywordLoc(), Operand.get(),
8096       cast<UnresolvedLookupExpr>(Lookup.get()), E->isImplicit());
8097 }
8098 
8099 template <typename Derived>
8100 ExprResult
8101 TreeTransform<Derived>::TransformDependentCoawaitExpr(DependentCoawaitExpr *E) {
8102   ExprResult OperandResult = getDerived().TransformInitializer(E->getOperand(),
8103                                                         /*NotCopyInit*/ false);
8104   if (OperandResult.isInvalid())
8105     return ExprError();
8106 
8107   ExprResult LookupResult = getDerived().TransformUnresolvedLookupExpr(
8108           E->getOperatorCoawaitLookup());
8109 
8110   if (LookupResult.isInvalid())
8111     return ExprError();
8112 
8113   // Always rebuild; we don't know if this needs to be injected into a new
8114   // context or if the promise type has changed.
8115   return getDerived().RebuildDependentCoawaitExpr(
8116       E->getKeywordLoc(), OperandResult.get(),
8117       cast<UnresolvedLookupExpr>(LookupResult.get()));
8118 }
8119 
8120 template<typename Derived>
8121 ExprResult
8122 TreeTransform<Derived>::TransformCoyieldExpr(CoyieldExpr *E) {
8123   ExprResult Result = getDerived().TransformInitializer(E->getOperand(),
8124                                                         /*NotCopyInit*/false);
8125   if (Result.isInvalid())
8126     return ExprError();
8127 
8128   // Always rebuild; we don't know if this needs to be injected into a new
8129   // context or if the promise type has changed.
8130   return getDerived().RebuildCoyieldExpr(E->getKeywordLoc(), Result.get());
8131 }
8132 
8133 // Objective-C Statements.
8134 
8135 template<typename Derived>
8136 StmtResult
8137 TreeTransform<Derived>::TransformObjCAtTryStmt(ObjCAtTryStmt *S) {
8138   // Transform the body of the @try.
8139   StmtResult TryBody = getDerived().TransformStmt(S->getTryBody());
8140   if (TryBody.isInvalid())
8141     return StmtError();
8142 
8143   // Transform the @catch statements (if present).
8144   bool AnyCatchChanged = false;
8145   SmallVector<Stmt*, 8> CatchStmts;
8146   for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
8147     StmtResult Catch = getDerived().TransformStmt(S->getCatchStmt(I));
8148     if (Catch.isInvalid())
8149       return StmtError();
8150     if (Catch.get() != S->getCatchStmt(I))
8151       AnyCatchChanged = true;
8152     CatchStmts.push_back(Catch.get());
8153   }
8154 
8155   // Transform the @finally statement (if present).
8156   StmtResult Finally;
8157   if (S->getFinallyStmt()) {
8158     Finally = getDerived().TransformStmt(S->getFinallyStmt());
8159     if (Finally.isInvalid())
8160       return StmtError();
8161   }
8162 
8163   // If nothing changed, just retain this statement.
8164   if (!getDerived().AlwaysRebuild() &&
8165       TryBody.get() == S->getTryBody() &&
8166       !AnyCatchChanged &&
8167       Finally.get() == S->getFinallyStmt())
8168     return S;
8169 
8170   // Build a new statement.
8171   return getDerived().RebuildObjCAtTryStmt(S->getAtTryLoc(), TryBody.get(),
8172                                            CatchStmts, Finally.get());
8173 }
8174 
8175 template<typename Derived>
8176 StmtResult
8177 TreeTransform<Derived>::TransformObjCAtCatchStmt(ObjCAtCatchStmt *S) {
8178   // Transform the @catch parameter, if there is one.
8179   VarDecl *Var = nullptr;
8180   if (VarDecl *FromVar = S->getCatchParamDecl()) {
8181     TypeSourceInfo *TSInfo = nullptr;
8182     if (FromVar->getTypeSourceInfo()) {
8183       TSInfo = getDerived().TransformType(FromVar->getTypeSourceInfo());
8184       if (!TSInfo)
8185         return StmtError();
8186     }
8187 
8188     QualType T;
8189     if (TSInfo)
8190       T = TSInfo->getType();
8191     else {
8192       T = getDerived().TransformType(FromVar->getType());
8193       if (T.isNull())
8194         return StmtError();
8195     }
8196 
8197     Var = getDerived().RebuildObjCExceptionDecl(FromVar, TSInfo, T);
8198     if (!Var)
8199       return StmtError();
8200   }
8201 
8202   StmtResult Body = getDerived().TransformStmt(S->getCatchBody());
8203   if (Body.isInvalid())
8204     return StmtError();
8205 
8206   return getDerived().RebuildObjCAtCatchStmt(S->getAtCatchLoc(),
8207                                              S->getRParenLoc(),
8208                                              Var, Body.get());
8209 }
8210 
8211 template<typename Derived>
8212 StmtResult
8213 TreeTransform<Derived>::TransformObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
8214   // Transform the body.
8215   StmtResult Body = getDerived().TransformStmt(S->getFinallyBody());
8216   if (Body.isInvalid())
8217     return StmtError();
8218 
8219   // If nothing changed, just retain this statement.
8220   if (!getDerived().AlwaysRebuild() &&
8221       Body.get() == S->getFinallyBody())
8222     return S;
8223 
8224   // Build a new statement.
8225   return getDerived().RebuildObjCAtFinallyStmt(S->getAtFinallyLoc(),
8226                                                Body.get());
8227 }
8228 
8229 template<typename Derived>
8230 StmtResult
8231 TreeTransform<Derived>::TransformObjCAtThrowStmt(ObjCAtThrowStmt *S) {
8232   ExprResult Operand;
8233   if (S->getThrowExpr()) {
8234     Operand = getDerived().TransformExpr(S->getThrowExpr());
8235     if (Operand.isInvalid())
8236       return StmtError();
8237   }
8238 
8239   if (!getDerived().AlwaysRebuild() &&
8240       Operand.get() == S->getThrowExpr())
8241     return S;
8242 
8243   return getDerived().RebuildObjCAtThrowStmt(S->getThrowLoc(), Operand.get());
8244 }
8245 
8246 template<typename Derived>
8247 StmtResult
8248 TreeTransform<Derived>::TransformObjCAtSynchronizedStmt(
8249                                                   ObjCAtSynchronizedStmt *S) {
8250   // Transform the object we are locking.
8251   ExprResult Object = getDerived().TransformExpr(S->getSynchExpr());
8252   if (Object.isInvalid())
8253     return StmtError();
8254   Object =
8255     getDerived().RebuildObjCAtSynchronizedOperand(S->getAtSynchronizedLoc(),
8256                                                   Object.get());
8257   if (Object.isInvalid())
8258     return StmtError();
8259 
8260   // Transform the body.
8261   StmtResult Body = getDerived().TransformStmt(S->getSynchBody());
8262   if (Body.isInvalid())
8263     return StmtError();
8264 
8265   // If nothing change, just retain the current statement.
8266   if (!getDerived().AlwaysRebuild() &&
8267       Object.get() == S->getSynchExpr() &&
8268       Body.get() == S->getSynchBody())
8269     return S;
8270 
8271   // Build a new statement.
8272   return getDerived().RebuildObjCAtSynchronizedStmt(S->getAtSynchronizedLoc(),
8273                                                     Object.get(), Body.get());
8274 }
8275 
8276 template<typename Derived>
8277 StmtResult
8278 TreeTransform<Derived>::TransformObjCAutoreleasePoolStmt(
8279                                               ObjCAutoreleasePoolStmt *S) {
8280   // Transform the body.
8281   StmtResult Body = getDerived().TransformStmt(S->getSubStmt());
8282   if (Body.isInvalid())
8283     return StmtError();
8284 
8285   // If nothing changed, just retain this statement.
8286   if (!getDerived().AlwaysRebuild() &&
8287       Body.get() == S->getSubStmt())
8288     return S;
8289 
8290   // Build a new statement.
8291   return getDerived().RebuildObjCAutoreleasePoolStmt(
8292                         S->getAtLoc(), Body.get());
8293 }
8294 
8295 template<typename Derived>
8296 StmtResult
8297 TreeTransform<Derived>::TransformObjCForCollectionStmt(
8298                                                   ObjCForCollectionStmt *S) {
8299   // Transform the element statement.
8300   StmtResult Element =
8301       getDerived().TransformStmt(S->getElement(), SDK_NotDiscarded);
8302   if (Element.isInvalid())
8303     return StmtError();
8304 
8305   // Transform the collection expression.
8306   ExprResult Collection = getDerived().TransformExpr(S->getCollection());
8307   if (Collection.isInvalid())
8308     return StmtError();
8309 
8310   // Transform the body.
8311   StmtResult Body = getDerived().TransformStmt(S->getBody());
8312   if (Body.isInvalid())
8313     return StmtError();
8314 
8315   // If nothing changed, just retain this statement.
8316   if (!getDerived().AlwaysRebuild() &&
8317       Element.get() == S->getElement() &&
8318       Collection.get() == S->getCollection() &&
8319       Body.get() == S->getBody())
8320     return S;
8321 
8322   // Build a new statement.
8323   return getDerived().RebuildObjCForCollectionStmt(S->getForLoc(),
8324                                                    Element.get(),
8325                                                    Collection.get(),
8326                                                    S->getRParenLoc(),
8327                                                    Body.get());
8328 }
8329 
8330 template <typename Derived>
8331 StmtResult TreeTransform<Derived>::TransformCXXCatchStmt(CXXCatchStmt *S) {
8332   // Transform the exception declaration, if any.
8333   VarDecl *Var = nullptr;
8334   if (VarDecl *ExceptionDecl = S->getExceptionDecl()) {
8335     TypeSourceInfo *T =
8336         getDerived().TransformType(ExceptionDecl->getTypeSourceInfo());
8337     if (!T)
8338       return StmtError();
8339 
8340     Var = getDerived().RebuildExceptionDecl(
8341         ExceptionDecl, T, ExceptionDecl->getInnerLocStart(),
8342         ExceptionDecl->getLocation(), ExceptionDecl->getIdentifier());
8343     if (!Var || Var->isInvalidDecl())
8344       return StmtError();
8345   }
8346 
8347   // Transform the actual exception handler.
8348   StmtResult Handler = getDerived().TransformStmt(S->getHandlerBlock());
8349   if (Handler.isInvalid())
8350     return StmtError();
8351 
8352   if (!getDerived().AlwaysRebuild() && !Var &&
8353       Handler.get() == S->getHandlerBlock())
8354     return S;
8355 
8356   return getDerived().RebuildCXXCatchStmt(S->getCatchLoc(), Var, Handler.get());
8357 }
8358 
8359 template <typename Derived>
8360 StmtResult TreeTransform<Derived>::TransformCXXTryStmt(CXXTryStmt *S) {
8361   // Transform the try block itself.
8362   StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
8363   if (TryBlock.isInvalid())
8364     return StmtError();
8365 
8366   // Transform the handlers.
8367   bool HandlerChanged = false;
8368   SmallVector<Stmt *, 8> Handlers;
8369   for (unsigned I = 0, N = S->getNumHandlers(); I != N; ++I) {
8370     StmtResult Handler = getDerived().TransformCXXCatchStmt(S->getHandler(I));
8371     if (Handler.isInvalid())
8372       return StmtError();
8373 
8374     HandlerChanged = HandlerChanged || Handler.get() != S->getHandler(I);
8375     Handlers.push_back(Handler.getAs<Stmt>());
8376   }
8377 
8378   if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
8379       !HandlerChanged)
8380     return S;
8381 
8382   return getDerived().RebuildCXXTryStmt(S->getTryLoc(), TryBlock.get(),
8383                                         Handlers);
8384 }
8385 
8386 template<typename Derived>
8387 StmtResult
8388 TreeTransform<Derived>::TransformCXXForRangeStmt(CXXForRangeStmt *S) {
8389   StmtResult Init =
8390       S->getInit() ? getDerived().TransformStmt(S->getInit()) : StmtResult();
8391   if (Init.isInvalid())
8392     return StmtError();
8393 
8394   StmtResult Range = getDerived().TransformStmt(S->getRangeStmt());
8395   if (Range.isInvalid())
8396     return StmtError();
8397 
8398   StmtResult Begin = getDerived().TransformStmt(S->getBeginStmt());
8399   if (Begin.isInvalid())
8400     return StmtError();
8401   StmtResult End = getDerived().TransformStmt(S->getEndStmt());
8402   if (End.isInvalid())
8403     return StmtError();
8404 
8405   ExprResult Cond = getDerived().TransformExpr(S->getCond());
8406   if (Cond.isInvalid())
8407     return StmtError();
8408   if (Cond.get())
8409     Cond = SemaRef.CheckBooleanCondition(S->getColonLoc(), Cond.get());
8410   if (Cond.isInvalid())
8411     return StmtError();
8412   if (Cond.get())
8413     Cond = SemaRef.MaybeCreateExprWithCleanups(Cond.get());
8414 
8415   ExprResult Inc = getDerived().TransformExpr(S->getInc());
8416   if (Inc.isInvalid())
8417     return StmtError();
8418   if (Inc.get())
8419     Inc = SemaRef.MaybeCreateExprWithCleanups(Inc.get());
8420 
8421   StmtResult LoopVar = getDerived().TransformStmt(S->getLoopVarStmt());
8422   if (LoopVar.isInvalid())
8423     return StmtError();
8424 
8425   StmtResult NewStmt = S;
8426   if (getDerived().AlwaysRebuild() ||
8427       Init.get() != S->getInit() ||
8428       Range.get() != S->getRangeStmt() ||
8429       Begin.get() != S->getBeginStmt() ||
8430       End.get() != S->getEndStmt() ||
8431       Cond.get() != S->getCond() ||
8432       Inc.get() != S->getInc() ||
8433       LoopVar.get() != S->getLoopVarStmt()) {
8434     NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
8435                                                   S->getCoawaitLoc(), Init.get(),
8436                                                   S->getColonLoc(), Range.get(),
8437                                                   Begin.get(), End.get(),
8438                                                   Cond.get(),
8439                                                   Inc.get(), LoopVar.get(),
8440                                                   S->getRParenLoc());
8441     if (NewStmt.isInvalid() && LoopVar.get() != S->getLoopVarStmt()) {
8442       // Might not have attached any initializer to the loop variable.
8443       getSema().ActOnInitializerError(
8444           cast<DeclStmt>(LoopVar.get())->getSingleDecl());
8445       return StmtError();
8446     }
8447   }
8448 
8449   StmtResult Body = getDerived().TransformStmt(S->getBody());
8450   if (Body.isInvalid())
8451     return StmtError();
8452 
8453   // Body has changed but we didn't rebuild the for-range statement. Rebuild
8454   // it now so we have a new statement to attach the body to.
8455   if (Body.get() != S->getBody() && NewStmt.get() == S) {
8456     NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
8457                                                   S->getCoawaitLoc(), Init.get(),
8458                                                   S->getColonLoc(), Range.get(),
8459                                                   Begin.get(), End.get(),
8460                                                   Cond.get(),
8461                                                   Inc.get(), LoopVar.get(),
8462                                                   S->getRParenLoc());
8463     if (NewStmt.isInvalid())
8464       return StmtError();
8465   }
8466 
8467   if (NewStmt.get() == S)
8468     return S;
8469 
8470   return FinishCXXForRangeStmt(NewStmt.get(), Body.get());
8471 }
8472 
8473 template<typename Derived>
8474 StmtResult
8475 TreeTransform<Derived>::TransformMSDependentExistsStmt(
8476                                                     MSDependentExistsStmt *S) {
8477   // Transform the nested-name-specifier, if any.
8478   NestedNameSpecifierLoc QualifierLoc;
8479   if (S->getQualifierLoc()) {
8480     QualifierLoc
8481       = getDerived().TransformNestedNameSpecifierLoc(S->getQualifierLoc());
8482     if (!QualifierLoc)
8483       return StmtError();
8484   }
8485 
8486   // Transform the declaration name.
8487   DeclarationNameInfo NameInfo = S->getNameInfo();
8488   if (NameInfo.getName()) {
8489     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
8490     if (!NameInfo.getName())
8491       return StmtError();
8492   }
8493 
8494   // Check whether anything changed.
8495   if (!getDerived().AlwaysRebuild() &&
8496       QualifierLoc == S->getQualifierLoc() &&
8497       NameInfo.getName() == S->getNameInfo().getName())
8498     return S;
8499 
8500   // Determine whether this name exists, if we can.
8501   CXXScopeSpec SS;
8502   SS.Adopt(QualifierLoc);
8503   bool Dependent = false;
8504   switch (getSema().CheckMicrosoftIfExistsSymbol(/*S=*/nullptr, SS, NameInfo)) {
8505   case Sema::IER_Exists:
8506     if (S->isIfExists())
8507       break;
8508 
8509     return new (getSema().Context) NullStmt(S->getKeywordLoc());
8510 
8511   case Sema::IER_DoesNotExist:
8512     if (S->isIfNotExists())
8513       break;
8514 
8515     return new (getSema().Context) NullStmt(S->getKeywordLoc());
8516 
8517   case Sema::IER_Dependent:
8518     Dependent = true;
8519     break;
8520 
8521   case Sema::IER_Error:
8522     return StmtError();
8523   }
8524 
8525   // We need to continue with the instantiation, so do so now.
8526   StmtResult SubStmt = getDerived().TransformCompoundStmt(S->getSubStmt());
8527   if (SubStmt.isInvalid())
8528     return StmtError();
8529 
8530   // If we have resolved the name, just transform to the substatement.
8531   if (!Dependent)
8532     return SubStmt;
8533 
8534   // The name is still dependent, so build a dependent expression again.
8535   return getDerived().RebuildMSDependentExistsStmt(S->getKeywordLoc(),
8536                                                    S->isIfExists(),
8537                                                    QualifierLoc,
8538                                                    NameInfo,
8539                                                    SubStmt.get());
8540 }
8541 
8542 template<typename Derived>
8543 ExprResult
8544 TreeTransform<Derived>::TransformMSPropertyRefExpr(MSPropertyRefExpr *E) {
8545   NestedNameSpecifierLoc QualifierLoc;
8546   if (E->getQualifierLoc()) {
8547     QualifierLoc
8548     = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
8549     if (!QualifierLoc)
8550       return ExprError();
8551   }
8552 
8553   MSPropertyDecl *PD = cast_or_null<MSPropertyDecl>(
8554     getDerived().TransformDecl(E->getMemberLoc(), E->getPropertyDecl()));
8555   if (!PD)
8556     return ExprError();
8557 
8558   ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
8559   if (Base.isInvalid())
8560     return ExprError();
8561 
8562   return new (SemaRef.getASTContext())
8563       MSPropertyRefExpr(Base.get(), PD, E->isArrow(),
8564                         SemaRef.getASTContext().PseudoObjectTy, VK_LValue,
8565                         QualifierLoc, E->getMemberLoc());
8566 }
8567 
8568 template <typename Derived>
8569 ExprResult TreeTransform<Derived>::TransformMSPropertySubscriptExpr(
8570     MSPropertySubscriptExpr *E) {
8571   auto BaseRes = getDerived().TransformExpr(E->getBase());
8572   if (BaseRes.isInvalid())
8573     return ExprError();
8574   auto IdxRes = getDerived().TransformExpr(E->getIdx());
8575   if (IdxRes.isInvalid())
8576     return ExprError();
8577 
8578   if (!getDerived().AlwaysRebuild() &&
8579       BaseRes.get() == E->getBase() &&
8580       IdxRes.get() == E->getIdx())
8581     return E;
8582 
8583   return getDerived().RebuildArraySubscriptExpr(
8584       BaseRes.get(), SourceLocation(), IdxRes.get(), E->getRBracketLoc());
8585 }
8586 
8587 template <typename Derived>
8588 StmtResult TreeTransform<Derived>::TransformSEHTryStmt(SEHTryStmt *S) {
8589   StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
8590   if (TryBlock.isInvalid())
8591     return StmtError();
8592 
8593   StmtResult Handler = getDerived().TransformSEHHandler(S->getHandler());
8594   if (Handler.isInvalid())
8595     return StmtError();
8596 
8597   if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
8598       Handler.get() == S->getHandler())
8599     return S;
8600 
8601   return getDerived().RebuildSEHTryStmt(S->getIsCXXTry(), S->getTryLoc(),
8602                                         TryBlock.get(), Handler.get());
8603 }
8604 
8605 template <typename Derived>
8606 StmtResult TreeTransform<Derived>::TransformSEHFinallyStmt(SEHFinallyStmt *S) {
8607   StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
8608   if (Block.isInvalid())
8609     return StmtError();
8610 
8611   return getDerived().RebuildSEHFinallyStmt(S->getFinallyLoc(), Block.get());
8612 }
8613 
8614 template <typename Derived>
8615 StmtResult TreeTransform<Derived>::TransformSEHExceptStmt(SEHExceptStmt *S) {
8616   ExprResult FilterExpr = getDerived().TransformExpr(S->getFilterExpr());
8617   if (FilterExpr.isInvalid())
8618     return StmtError();
8619 
8620   StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
8621   if (Block.isInvalid())
8622     return StmtError();
8623 
8624   return getDerived().RebuildSEHExceptStmt(S->getExceptLoc(), FilterExpr.get(),
8625                                            Block.get());
8626 }
8627 
8628 template <typename Derived>
8629 StmtResult TreeTransform<Derived>::TransformSEHHandler(Stmt *Handler) {
8630   if (isa<SEHFinallyStmt>(Handler))
8631     return getDerived().TransformSEHFinallyStmt(cast<SEHFinallyStmt>(Handler));
8632   else
8633     return getDerived().TransformSEHExceptStmt(cast<SEHExceptStmt>(Handler));
8634 }
8635 
8636 template<typename Derived>
8637 StmtResult
8638 TreeTransform<Derived>::TransformSEHLeaveStmt(SEHLeaveStmt *S) {
8639   return S;
8640 }
8641 
8642 //===----------------------------------------------------------------------===//
8643 // OpenMP directive transformation
8644 //===----------------------------------------------------------------------===//
8645 
8646 template <typename Derived>
8647 StmtResult
8648 TreeTransform<Derived>::TransformOMPCanonicalLoop(OMPCanonicalLoop *L) {
8649   // OMPCanonicalLoops are eliminated during transformation, since they will be
8650   // recomputed by semantic analysis of the associated OMPLoopBasedDirective
8651   // after transformation.
8652   return getDerived().TransformStmt(L->getLoopStmt());
8653 }
8654 
8655 template <typename Derived>
8656 StmtResult TreeTransform<Derived>::TransformOMPExecutableDirective(
8657     OMPExecutableDirective *D) {
8658 
8659   // Transform the clauses
8660   llvm::SmallVector<OMPClause *, 16> TClauses;
8661   ArrayRef<OMPClause *> Clauses = D->clauses();
8662   TClauses.reserve(Clauses.size());
8663   for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
8664        I != E; ++I) {
8665     if (*I) {
8666       getDerived().getSema().StartOpenMPClause((*I)->getClauseKind());
8667       OMPClause *Clause = getDerived().TransformOMPClause(*I);
8668       getDerived().getSema().EndOpenMPClause();
8669       if (Clause)
8670         TClauses.push_back(Clause);
8671     } else {
8672       TClauses.push_back(nullptr);
8673     }
8674   }
8675   StmtResult AssociatedStmt;
8676   if (D->hasAssociatedStmt() && D->getAssociatedStmt()) {
8677     getDerived().getSema().ActOnOpenMPRegionStart(D->getDirectiveKind(),
8678                                                   /*CurScope=*/nullptr);
8679     StmtResult Body;
8680     {
8681       Sema::CompoundScopeRAII CompoundScope(getSema());
8682       Stmt *CS;
8683       if (D->getDirectiveKind() == OMPD_atomic ||
8684           D->getDirectiveKind() == OMPD_critical ||
8685           D->getDirectiveKind() == OMPD_section ||
8686           D->getDirectiveKind() == OMPD_master)
8687         CS = D->getAssociatedStmt();
8688       else
8689         CS = D->getRawStmt();
8690       Body = getDerived().TransformStmt(CS);
8691       if (Body.isUsable() && isOpenMPLoopDirective(D->getDirectiveKind()) &&
8692           getSema().getLangOpts().OpenMPIRBuilder)
8693         Body = getDerived().RebuildOMPCanonicalLoop(Body.get());
8694     }
8695     AssociatedStmt =
8696         getDerived().getSema().ActOnOpenMPRegionEnd(Body, TClauses);
8697     if (AssociatedStmt.isInvalid()) {
8698       return StmtError();
8699     }
8700   }
8701   if (TClauses.size() != Clauses.size()) {
8702     return StmtError();
8703   }
8704 
8705   // Transform directive name for 'omp critical' directive.
8706   DeclarationNameInfo DirName;
8707   if (D->getDirectiveKind() == OMPD_critical) {
8708     DirName = cast<OMPCriticalDirective>(D)->getDirectiveName();
8709     DirName = getDerived().TransformDeclarationNameInfo(DirName);
8710   }
8711   OpenMPDirectiveKind CancelRegion = OMPD_unknown;
8712   if (D->getDirectiveKind() == OMPD_cancellation_point) {
8713     CancelRegion = cast<OMPCancellationPointDirective>(D)->getCancelRegion();
8714   } else if (D->getDirectiveKind() == OMPD_cancel) {
8715     CancelRegion = cast<OMPCancelDirective>(D)->getCancelRegion();
8716   }
8717 
8718   return getDerived().RebuildOMPExecutableDirective(
8719       D->getDirectiveKind(), DirName, CancelRegion, TClauses,
8720       AssociatedStmt.get(), D->getBeginLoc(), D->getEndLoc());
8721 }
8722 
8723 template <typename Derived>
8724 StmtResult
8725 TreeTransform<Derived>::TransformOMPMetaDirective(OMPMetaDirective *D) {
8726   // TODO: Fix This
8727   SemaRef.Diag(D->getBeginLoc(), diag::err_omp_instantiation_not_supported)
8728       << getOpenMPDirectiveName(D->getDirectiveKind());
8729   return StmtError();
8730 }
8731 
8732 template <typename Derived>
8733 StmtResult
8734 TreeTransform<Derived>::TransformOMPParallelDirective(OMPParallelDirective *D) {
8735   DeclarationNameInfo DirName;
8736   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel, DirName, nullptr,
8737                                              D->getBeginLoc());
8738   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8739   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8740   return Res;
8741 }
8742 
8743 template <typename Derived>
8744 StmtResult
8745 TreeTransform<Derived>::TransformOMPSimdDirective(OMPSimdDirective *D) {
8746   DeclarationNameInfo DirName;
8747   getDerived().getSema().StartOpenMPDSABlock(OMPD_simd, DirName, nullptr,
8748                                              D->getBeginLoc());
8749   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8750   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8751   return Res;
8752 }
8753 
8754 template <typename Derived>
8755 StmtResult
8756 TreeTransform<Derived>::TransformOMPTileDirective(OMPTileDirective *D) {
8757   DeclarationNameInfo DirName;
8758   getDerived().getSema().StartOpenMPDSABlock(D->getDirectiveKind(), DirName,
8759                                              nullptr, D->getBeginLoc());
8760   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8761   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8762   return Res;
8763 }
8764 
8765 template <typename Derived>
8766 StmtResult
8767 TreeTransform<Derived>::TransformOMPUnrollDirective(OMPUnrollDirective *D) {
8768   DeclarationNameInfo DirName;
8769   getDerived().getSema().StartOpenMPDSABlock(D->getDirectiveKind(), DirName,
8770                                              nullptr, D->getBeginLoc());
8771   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8772   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8773   return Res;
8774 }
8775 
8776 template <typename Derived>
8777 StmtResult
8778 TreeTransform<Derived>::TransformOMPForDirective(OMPForDirective *D) {
8779   DeclarationNameInfo DirName;
8780   getDerived().getSema().StartOpenMPDSABlock(OMPD_for, DirName, nullptr,
8781                                              D->getBeginLoc());
8782   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8783   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8784   return Res;
8785 }
8786 
8787 template <typename Derived>
8788 StmtResult
8789 TreeTransform<Derived>::TransformOMPForSimdDirective(OMPForSimdDirective *D) {
8790   DeclarationNameInfo DirName;
8791   getDerived().getSema().StartOpenMPDSABlock(OMPD_for_simd, DirName, nullptr,
8792                                              D->getBeginLoc());
8793   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8794   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8795   return Res;
8796 }
8797 
8798 template <typename Derived>
8799 StmtResult
8800 TreeTransform<Derived>::TransformOMPSectionsDirective(OMPSectionsDirective *D) {
8801   DeclarationNameInfo DirName;
8802   getDerived().getSema().StartOpenMPDSABlock(OMPD_sections, DirName, nullptr,
8803                                              D->getBeginLoc());
8804   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8805   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8806   return Res;
8807 }
8808 
8809 template <typename Derived>
8810 StmtResult
8811 TreeTransform<Derived>::TransformOMPSectionDirective(OMPSectionDirective *D) {
8812   DeclarationNameInfo DirName;
8813   getDerived().getSema().StartOpenMPDSABlock(OMPD_section, DirName, nullptr,
8814                                              D->getBeginLoc());
8815   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8816   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8817   return Res;
8818 }
8819 
8820 template <typename Derived>
8821 StmtResult
8822 TreeTransform<Derived>::TransformOMPSingleDirective(OMPSingleDirective *D) {
8823   DeclarationNameInfo DirName;
8824   getDerived().getSema().StartOpenMPDSABlock(OMPD_single, DirName, nullptr,
8825                                              D->getBeginLoc());
8826   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8827   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8828   return Res;
8829 }
8830 
8831 template <typename Derived>
8832 StmtResult
8833 TreeTransform<Derived>::TransformOMPMasterDirective(OMPMasterDirective *D) {
8834   DeclarationNameInfo DirName;
8835   getDerived().getSema().StartOpenMPDSABlock(OMPD_master, DirName, nullptr,
8836                                              D->getBeginLoc());
8837   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8838   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8839   return Res;
8840 }
8841 
8842 template <typename Derived>
8843 StmtResult
8844 TreeTransform<Derived>::TransformOMPCriticalDirective(OMPCriticalDirective *D) {
8845   getDerived().getSema().StartOpenMPDSABlock(
8846       OMPD_critical, D->getDirectiveName(), nullptr, D->getBeginLoc());
8847   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8848   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8849   return Res;
8850 }
8851 
8852 template <typename Derived>
8853 StmtResult TreeTransform<Derived>::TransformOMPParallelForDirective(
8854     OMPParallelForDirective *D) {
8855   DeclarationNameInfo DirName;
8856   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for, DirName,
8857                                              nullptr, D->getBeginLoc());
8858   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8859   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8860   return Res;
8861 }
8862 
8863 template <typename Derived>
8864 StmtResult TreeTransform<Derived>::TransformOMPParallelForSimdDirective(
8865     OMPParallelForSimdDirective *D) {
8866   DeclarationNameInfo DirName;
8867   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for_simd, DirName,
8868                                              nullptr, D->getBeginLoc());
8869   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8870   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8871   return Res;
8872 }
8873 
8874 template <typename Derived>
8875 StmtResult TreeTransform<Derived>::TransformOMPParallelMasterDirective(
8876     OMPParallelMasterDirective *D) {
8877   DeclarationNameInfo DirName;
8878   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_master, DirName,
8879                                              nullptr, D->getBeginLoc());
8880   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8881   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8882   return Res;
8883 }
8884 
8885 template <typename Derived>
8886 StmtResult TreeTransform<Derived>::TransformOMPParallelMaskedDirective(
8887     OMPParallelMaskedDirective *D) {
8888   DeclarationNameInfo DirName;
8889   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_masked, DirName,
8890                                              nullptr, D->getBeginLoc());
8891   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8892   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8893   return Res;
8894 }
8895 
8896 template <typename Derived>
8897 StmtResult TreeTransform<Derived>::TransformOMPParallelSectionsDirective(
8898     OMPParallelSectionsDirective *D) {
8899   DeclarationNameInfo DirName;
8900   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_sections, DirName,
8901                                              nullptr, D->getBeginLoc());
8902   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8903   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8904   return Res;
8905 }
8906 
8907 template <typename Derived>
8908 StmtResult
8909 TreeTransform<Derived>::TransformOMPTaskDirective(OMPTaskDirective *D) {
8910   DeclarationNameInfo DirName;
8911   getDerived().getSema().StartOpenMPDSABlock(OMPD_task, DirName, nullptr,
8912                                              D->getBeginLoc());
8913   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8914   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8915   return Res;
8916 }
8917 
8918 template <typename Derived>
8919 StmtResult TreeTransform<Derived>::TransformOMPTaskyieldDirective(
8920     OMPTaskyieldDirective *D) {
8921   DeclarationNameInfo DirName;
8922   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskyield, DirName, nullptr,
8923                                              D->getBeginLoc());
8924   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8925   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8926   return Res;
8927 }
8928 
8929 template <typename Derived>
8930 StmtResult
8931 TreeTransform<Derived>::TransformOMPBarrierDirective(OMPBarrierDirective *D) {
8932   DeclarationNameInfo DirName;
8933   getDerived().getSema().StartOpenMPDSABlock(OMPD_barrier, DirName, nullptr,
8934                                              D->getBeginLoc());
8935   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8936   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8937   return Res;
8938 }
8939 
8940 template <typename Derived>
8941 StmtResult
8942 TreeTransform<Derived>::TransformOMPTaskwaitDirective(OMPTaskwaitDirective *D) {
8943   DeclarationNameInfo DirName;
8944   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskwait, DirName, nullptr,
8945                                              D->getBeginLoc());
8946   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8947   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8948   return Res;
8949 }
8950 
8951 template <typename Derived>
8952 StmtResult
8953 TreeTransform<Derived>::TransformOMPErrorDirective(OMPErrorDirective *D) {
8954   DeclarationNameInfo DirName;
8955   getDerived().getSema().StartOpenMPDSABlock(OMPD_error, DirName, nullptr,
8956                                              D->getBeginLoc());
8957   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8958   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8959   return Res;
8960 }
8961 
8962 template <typename Derived>
8963 StmtResult TreeTransform<Derived>::TransformOMPTaskgroupDirective(
8964     OMPTaskgroupDirective *D) {
8965   DeclarationNameInfo DirName;
8966   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskgroup, DirName, nullptr,
8967                                              D->getBeginLoc());
8968   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8969   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8970   return Res;
8971 }
8972 
8973 template <typename Derived>
8974 StmtResult
8975 TreeTransform<Derived>::TransformOMPFlushDirective(OMPFlushDirective *D) {
8976   DeclarationNameInfo DirName;
8977   getDerived().getSema().StartOpenMPDSABlock(OMPD_flush, DirName, nullptr,
8978                                              D->getBeginLoc());
8979   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8980   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8981   return Res;
8982 }
8983 
8984 template <typename Derived>
8985 StmtResult
8986 TreeTransform<Derived>::TransformOMPDepobjDirective(OMPDepobjDirective *D) {
8987   DeclarationNameInfo DirName;
8988   getDerived().getSema().StartOpenMPDSABlock(OMPD_depobj, DirName, nullptr,
8989                                              D->getBeginLoc());
8990   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8991   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8992   return Res;
8993 }
8994 
8995 template <typename Derived>
8996 StmtResult
8997 TreeTransform<Derived>::TransformOMPScanDirective(OMPScanDirective *D) {
8998   DeclarationNameInfo DirName;
8999   getDerived().getSema().StartOpenMPDSABlock(OMPD_scan, DirName, nullptr,
9000                                              D->getBeginLoc());
9001   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9002   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9003   return Res;
9004 }
9005 
9006 template <typename Derived>
9007 StmtResult
9008 TreeTransform<Derived>::TransformOMPOrderedDirective(OMPOrderedDirective *D) {
9009   DeclarationNameInfo DirName;
9010   getDerived().getSema().StartOpenMPDSABlock(OMPD_ordered, DirName, nullptr,
9011                                              D->getBeginLoc());
9012   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9013   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9014   return Res;
9015 }
9016 
9017 template <typename Derived>
9018 StmtResult
9019 TreeTransform<Derived>::TransformOMPAtomicDirective(OMPAtomicDirective *D) {
9020   DeclarationNameInfo DirName;
9021   getDerived().getSema().StartOpenMPDSABlock(OMPD_atomic, DirName, nullptr,
9022                                              D->getBeginLoc());
9023   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9024   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9025   return Res;
9026 }
9027 
9028 template <typename Derived>
9029 StmtResult
9030 TreeTransform<Derived>::TransformOMPTargetDirective(OMPTargetDirective *D) {
9031   DeclarationNameInfo DirName;
9032   getDerived().getSema().StartOpenMPDSABlock(OMPD_target, DirName, nullptr,
9033                                              D->getBeginLoc());
9034   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9035   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9036   return Res;
9037 }
9038 
9039 template <typename Derived>
9040 StmtResult TreeTransform<Derived>::TransformOMPTargetDataDirective(
9041     OMPTargetDataDirective *D) {
9042   DeclarationNameInfo DirName;
9043   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_data, DirName, nullptr,
9044                                              D->getBeginLoc());
9045   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9046   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9047   return Res;
9048 }
9049 
9050 template <typename Derived>
9051 StmtResult TreeTransform<Derived>::TransformOMPTargetEnterDataDirective(
9052     OMPTargetEnterDataDirective *D) {
9053   DeclarationNameInfo DirName;
9054   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_enter_data, DirName,
9055                                              nullptr, D->getBeginLoc());
9056   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9057   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9058   return Res;
9059 }
9060 
9061 template <typename Derived>
9062 StmtResult TreeTransform<Derived>::TransformOMPTargetExitDataDirective(
9063     OMPTargetExitDataDirective *D) {
9064   DeclarationNameInfo DirName;
9065   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_exit_data, DirName,
9066                                              nullptr, D->getBeginLoc());
9067   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9068   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9069   return Res;
9070 }
9071 
9072 template <typename Derived>
9073 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelDirective(
9074     OMPTargetParallelDirective *D) {
9075   DeclarationNameInfo DirName;
9076   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel, DirName,
9077                                              nullptr, D->getBeginLoc());
9078   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9079   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9080   return Res;
9081 }
9082 
9083 template <typename Derived>
9084 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelForDirective(
9085     OMPTargetParallelForDirective *D) {
9086   DeclarationNameInfo DirName;
9087   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel_for, DirName,
9088                                              nullptr, D->getBeginLoc());
9089   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9090   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9091   return Res;
9092 }
9093 
9094 template <typename Derived>
9095 StmtResult TreeTransform<Derived>::TransformOMPTargetUpdateDirective(
9096     OMPTargetUpdateDirective *D) {
9097   DeclarationNameInfo DirName;
9098   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_update, DirName,
9099                                              nullptr, D->getBeginLoc());
9100   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9101   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9102   return Res;
9103 }
9104 
9105 template <typename Derived>
9106 StmtResult
9107 TreeTransform<Derived>::TransformOMPTeamsDirective(OMPTeamsDirective *D) {
9108   DeclarationNameInfo DirName;
9109   getDerived().getSema().StartOpenMPDSABlock(OMPD_teams, DirName, nullptr,
9110                                              D->getBeginLoc());
9111   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9112   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9113   return Res;
9114 }
9115 
9116 template <typename Derived>
9117 StmtResult TreeTransform<Derived>::TransformOMPCancellationPointDirective(
9118     OMPCancellationPointDirective *D) {
9119   DeclarationNameInfo DirName;
9120   getDerived().getSema().StartOpenMPDSABlock(OMPD_cancellation_point, DirName,
9121                                              nullptr, D->getBeginLoc());
9122   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9123   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9124   return Res;
9125 }
9126 
9127 template <typename Derived>
9128 StmtResult
9129 TreeTransform<Derived>::TransformOMPCancelDirective(OMPCancelDirective *D) {
9130   DeclarationNameInfo DirName;
9131   getDerived().getSema().StartOpenMPDSABlock(OMPD_cancel, DirName, nullptr,
9132                                              D->getBeginLoc());
9133   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9134   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9135   return Res;
9136 }
9137 
9138 template <typename Derived>
9139 StmtResult
9140 TreeTransform<Derived>::TransformOMPTaskLoopDirective(OMPTaskLoopDirective *D) {
9141   DeclarationNameInfo DirName;
9142   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop, DirName, nullptr,
9143                                              D->getBeginLoc());
9144   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9145   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9146   return Res;
9147 }
9148 
9149 template <typename Derived>
9150 StmtResult TreeTransform<Derived>::TransformOMPTaskLoopSimdDirective(
9151     OMPTaskLoopSimdDirective *D) {
9152   DeclarationNameInfo DirName;
9153   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop_simd, DirName,
9154                                              nullptr, D->getBeginLoc());
9155   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9156   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9157   return Res;
9158 }
9159 
9160 template <typename Derived>
9161 StmtResult TreeTransform<Derived>::TransformOMPMasterTaskLoopDirective(
9162     OMPMasterTaskLoopDirective *D) {
9163   DeclarationNameInfo DirName;
9164   getDerived().getSema().StartOpenMPDSABlock(OMPD_master_taskloop, DirName,
9165                                              nullptr, D->getBeginLoc());
9166   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9167   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9168   return Res;
9169 }
9170 
9171 template <typename Derived>
9172 StmtResult TreeTransform<Derived>::TransformOMPMaskedTaskLoopDirective(
9173     OMPMaskedTaskLoopDirective *D) {
9174   DeclarationNameInfo DirName;
9175   getDerived().getSema().StartOpenMPDSABlock(OMPD_masked_taskloop, DirName,
9176                                              nullptr, D->getBeginLoc());
9177   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9178   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9179   return Res;
9180 }
9181 
9182 template <typename Derived>
9183 StmtResult TreeTransform<Derived>::TransformOMPMasterTaskLoopSimdDirective(
9184     OMPMasterTaskLoopSimdDirective *D) {
9185   DeclarationNameInfo DirName;
9186   getDerived().getSema().StartOpenMPDSABlock(OMPD_master_taskloop_simd, DirName,
9187                                              nullptr, D->getBeginLoc());
9188   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9189   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9190   return Res;
9191 }
9192 
9193 template <typename Derived>
9194 StmtResult TreeTransform<Derived>::TransformOMPMaskedTaskLoopSimdDirective(
9195     OMPMaskedTaskLoopSimdDirective *D) {
9196   DeclarationNameInfo DirName;
9197   getDerived().getSema().StartOpenMPDSABlock(OMPD_masked_taskloop_simd, DirName,
9198                                              nullptr, D->getBeginLoc());
9199   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9200   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9201   return Res;
9202 }
9203 
9204 template <typename Derived>
9205 StmtResult TreeTransform<Derived>::TransformOMPParallelMasterTaskLoopDirective(
9206     OMPParallelMasterTaskLoopDirective *D) {
9207   DeclarationNameInfo DirName;
9208   getDerived().getSema().StartOpenMPDSABlock(
9209       OMPD_parallel_master_taskloop, DirName, nullptr, D->getBeginLoc());
9210   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9211   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9212   return Res;
9213 }
9214 
9215 template <typename Derived>
9216 StmtResult TreeTransform<Derived>::TransformOMPParallelMaskedTaskLoopDirective(
9217     OMPParallelMaskedTaskLoopDirective *D) {
9218   DeclarationNameInfo DirName;
9219   getDerived().getSema().StartOpenMPDSABlock(
9220       OMPD_parallel_masked_taskloop, DirName, nullptr, D->getBeginLoc());
9221   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9222   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9223   return Res;
9224 }
9225 
9226 template <typename Derived>
9227 StmtResult
9228 TreeTransform<Derived>::TransformOMPParallelMasterTaskLoopSimdDirective(
9229     OMPParallelMasterTaskLoopSimdDirective *D) {
9230   DeclarationNameInfo DirName;
9231   getDerived().getSema().StartOpenMPDSABlock(
9232       OMPD_parallel_master_taskloop_simd, DirName, nullptr, D->getBeginLoc());
9233   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9234   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9235   return Res;
9236 }
9237 
9238 template <typename Derived>
9239 StmtResult
9240 TreeTransform<Derived>::TransformOMPParallelMaskedTaskLoopSimdDirective(
9241     OMPParallelMaskedTaskLoopSimdDirective *D) {
9242   DeclarationNameInfo DirName;
9243   getDerived().getSema().StartOpenMPDSABlock(
9244       OMPD_parallel_masked_taskloop_simd, DirName, nullptr, D->getBeginLoc());
9245   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9246   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9247   return Res;
9248 }
9249 
9250 template <typename Derived>
9251 StmtResult TreeTransform<Derived>::TransformOMPDistributeDirective(
9252     OMPDistributeDirective *D) {
9253   DeclarationNameInfo DirName;
9254   getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute, DirName, nullptr,
9255                                              D->getBeginLoc());
9256   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9257   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9258   return Res;
9259 }
9260 
9261 template <typename Derived>
9262 StmtResult TreeTransform<Derived>::TransformOMPDistributeParallelForDirective(
9263     OMPDistributeParallelForDirective *D) {
9264   DeclarationNameInfo DirName;
9265   getDerived().getSema().StartOpenMPDSABlock(
9266       OMPD_distribute_parallel_for, DirName, nullptr, D->getBeginLoc());
9267   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9268   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9269   return Res;
9270 }
9271 
9272 template <typename Derived>
9273 StmtResult
9274 TreeTransform<Derived>::TransformOMPDistributeParallelForSimdDirective(
9275     OMPDistributeParallelForSimdDirective *D) {
9276   DeclarationNameInfo DirName;
9277   getDerived().getSema().StartOpenMPDSABlock(
9278       OMPD_distribute_parallel_for_simd, DirName, nullptr, D->getBeginLoc());
9279   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9280   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9281   return Res;
9282 }
9283 
9284 template <typename Derived>
9285 StmtResult TreeTransform<Derived>::TransformOMPDistributeSimdDirective(
9286     OMPDistributeSimdDirective *D) {
9287   DeclarationNameInfo DirName;
9288   getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute_simd, DirName,
9289                                              nullptr, D->getBeginLoc());
9290   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9291   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9292   return Res;
9293 }
9294 
9295 template <typename Derived>
9296 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelForSimdDirective(
9297     OMPTargetParallelForSimdDirective *D) {
9298   DeclarationNameInfo DirName;
9299   getDerived().getSema().StartOpenMPDSABlock(
9300       OMPD_target_parallel_for_simd, DirName, nullptr, D->getBeginLoc());
9301   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9302   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9303   return Res;
9304 }
9305 
9306 template <typename Derived>
9307 StmtResult TreeTransform<Derived>::TransformOMPTargetSimdDirective(
9308     OMPTargetSimdDirective *D) {
9309   DeclarationNameInfo DirName;
9310   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_simd, DirName, nullptr,
9311                                              D->getBeginLoc());
9312   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9313   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9314   return Res;
9315 }
9316 
9317 template <typename Derived>
9318 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeDirective(
9319     OMPTeamsDistributeDirective *D) {
9320   DeclarationNameInfo DirName;
9321   getDerived().getSema().StartOpenMPDSABlock(OMPD_teams_distribute, DirName,
9322                                              nullptr, D->getBeginLoc());
9323   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9324   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9325   return Res;
9326 }
9327 
9328 template <typename Derived>
9329 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeSimdDirective(
9330     OMPTeamsDistributeSimdDirective *D) {
9331   DeclarationNameInfo DirName;
9332   getDerived().getSema().StartOpenMPDSABlock(
9333       OMPD_teams_distribute_simd, DirName, nullptr, D->getBeginLoc());
9334   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9335   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9336   return Res;
9337 }
9338 
9339 template <typename Derived>
9340 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeParallelForSimdDirective(
9341     OMPTeamsDistributeParallelForSimdDirective *D) {
9342   DeclarationNameInfo DirName;
9343   getDerived().getSema().StartOpenMPDSABlock(
9344       OMPD_teams_distribute_parallel_for_simd, DirName, nullptr,
9345       D->getBeginLoc());
9346   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9347   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9348   return Res;
9349 }
9350 
9351 template <typename Derived>
9352 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeParallelForDirective(
9353     OMPTeamsDistributeParallelForDirective *D) {
9354   DeclarationNameInfo DirName;
9355   getDerived().getSema().StartOpenMPDSABlock(
9356       OMPD_teams_distribute_parallel_for, DirName, nullptr, D->getBeginLoc());
9357   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9358   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9359   return Res;
9360 }
9361 
9362 template <typename Derived>
9363 StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsDirective(
9364     OMPTargetTeamsDirective *D) {
9365   DeclarationNameInfo DirName;
9366   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_teams, DirName,
9367                                              nullptr, D->getBeginLoc());
9368   auto Res = getDerived().TransformOMPExecutableDirective(D);
9369   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9370   return Res;
9371 }
9372 
9373 template <typename Derived>
9374 StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsDistributeDirective(
9375     OMPTargetTeamsDistributeDirective *D) {
9376   DeclarationNameInfo DirName;
9377   getDerived().getSema().StartOpenMPDSABlock(
9378       OMPD_target_teams_distribute, DirName, nullptr, D->getBeginLoc());
9379   auto Res = getDerived().TransformOMPExecutableDirective(D);
9380   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9381   return Res;
9382 }
9383 
9384 template <typename Derived>
9385 StmtResult
9386 TreeTransform<Derived>::TransformOMPTargetTeamsDistributeParallelForDirective(
9387     OMPTargetTeamsDistributeParallelForDirective *D) {
9388   DeclarationNameInfo DirName;
9389   getDerived().getSema().StartOpenMPDSABlock(
9390       OMPD_target_teams_distribute_parallel_for, DirName, nullptr,
9391       D->getBeginLoc());
9392   auto Res = getDerived().TransformOMPExecutableDirective(D);
9393   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9394   return Res;
9395 }
9396 
9397 template <typename Derived>
9398 StmtResult TreeTransform<Derived>::
9399     TransformOMPTargetTeamsDistributeParallelForSimdDirective(
9400         OMPTargetTeamsDistributeParallelForSimdDirective *D) {
9401   DeclarationNameInfo DirName;
9402   getDerived().getSema().StartOpenMPDSABlock(
9403       OMPD_target_teams_distribute_parallel_for_simd, DirName, nullptr,
9404       D->getBeginLoc());
9405   auto Res = getDerived().TransformOMPExecutableDirective(D);
9406   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9407   return Res;
9408 }
9409 
9410 template <typename Derived>
9411 StmtResult
9412 TreeTransform<Derived>::TransformOMPTargetTeamsDistributeSimdDirective(
9413     OMPTargetTeamsDistributeSimdDirective *D) {
9414   DeclarationNameInfo DirName;
9415   getDerived().getSema().StartOpenMPDSABlock(
9416       OMPD_target_teams_distribute_simd, DirName, nullptr, D->getBeginLoc());
9417   auto Res = getDerived().TransformOMPExecutableDirective(D);
9418   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9419   return Res;
9420 }
9421 
9422 template <typename Derived>
9423 StmtResult
9424 TreeTransform<Derived>::TransformOMPInteropDirective(OMPInteropDirective *D) {
9425   DeclarationNameInfo DirName;
9426   getDerived().getSema().StartOpenMPDSABlock(OMPD_interop, DirName, nullptr,
9427                                              D->getBeginLoc());
9428   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9429   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9430   return Res;
9431 }
9432 
9433 template <typename Derived>
9434 StmtResult
9435 TreeTransform<Derived>::TransformOMPDispatchDirective(OMPDispatchDirective *D) {
9436   DeclarationNameInfo DirName;
9437   getDerived().getSema().StartOpenMPDSABlock(OMPD_dispatch, DirName, nullptr,
9438                                              D->getBeginLoc());
9439   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9440   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9441   return Res;
9442 }
9443 
9444 template <typename Derived>
9445 StmtResult
9446 TreeTransform<Derived>::TransformOMPMaskedDirective(OMPMaskedDirective *D) {
9447   DeclarationNameInfo DirName;
9448   getDerived().getSema().StartOpenMPDSABlock(OMPD_masked, DirName, nullptr,
9449                                              D->getBeginLoc());
9450   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9451   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9452   return Res;
9453 }
9454 
9455 template <typename Derived>
9456 StmtResult TreeTransform<Derived>::TransformOMPGenericLoopDirective(
9457     OMPGenericLoopDirective *D) {
9458   DeclarationNameInfo DirName;
9459   getDerived().getSema().StartOpenMPDSABlock(OMPD_loop, DirName, nullptr,
9460                                              D->getBeginLoc());
9461   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9462   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9463   return Res;
9464 }
9465 
9466 template <typename Derived>
9467 StmtResult TreeTransform<Derived>::TransformOMPTeamsGenericLoopDirective(
9468     OMPTeamsGenericLoopDirective *D) {
9469   DeclarationNameInfo DirName;
9470   getDerived().getSema().StartOpenMPDSABlock(OMPD_teams_loop, DirName, nullptr,
9471                                              D->getBeginLoc());
9472   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9473   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9474   return Res;
9475 }
9476 
9477 template <typename Derived>
9478 StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsGenericLoopDirective(
9479     OMPTargetTeamsGenericLoopDirective *D) {
9480   DeclarationNameInfo DirName;
9481   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_teams_loop, DirName,
9482                                              nullptr, D->getBeginLoc());
9483   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9484   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9485   return Res;
9486 }
9487 
9488 template <typename Derived>
9489 StmtResult TreeTransform<Derived>::TransformOMPParallelGenericLoopDirective(
9490     OMPParallelGenericLoopDirective *D) {
9491   DeclarationNameInfo DirName;
9492   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_loop, DirName,
9493                                              nullptr, D->getBeginLoc());
9494   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9495   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9496   return Res;
9497 }
9498 
9499 template <typename Derived>
9500 StmtResult
9501 TreeTransform<Derived>::TransformOMPTargetParallelGenericLoopDirective(
9502     OMPTargetParallelGenericLoopDirective *D) {
9503   DeclarationNameInfo DirName;
9504   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel_loop, DirName,
9505                                              nullptr, D->getBeginLoc());
9506   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9507   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9508   return Res;
9509 }
9510 
9511 //===----------------------------------------------------------------------===//
9512 // OpenMP clause transformation
9513 //===----------------------------------------------------------------------===//
9514 template <typename Derived>
9515 OMPClause *TreeTransform<Derived>::TransformOMPIfClause(OMPIfClause *C) {
9516   ExprResult Cond = getDerived().TransformExpr(C->getCondition());
9517   if (Cond.isInvalid())
9518     return nullptr;
9519   return getDerived().RebuildOMPIfClause(
9520       C->getNameModifier(), Cond.get(), C->getBeginLoc(), C->getLParenLoc(),
9521       C->getNameModifierLoc(), C->getColonLoc(), C->getEndLoc());
9522 }
9523 
9524 template <typename Derived>
9525 OMPClause *TreeTransform<Derived>::TransformOMPFinalClause(OMPFinalClause *C) {
9526   ExprResult Cond = getDerived().TransformExpr(C->getCondition());
9527   if (Cond.isInvalid())
9528     return nullptr;
9529   return getDerived().RebuildOMPFinalClause(Cond.get(), C->getBeginLoc(),
9530                                             C->getLParenLoc(), C->getEndLoc());
9531 }
9532 
9533 template <typename Derived>
9534 OMPClause *
9535 TreeTransform<Derived>::TransformOMPNumThreadsClause(OMPNumThreadsClause *C) {
9536   ExprResult NumThreads = getDerived().TransformExpr(C->getNumThreads());
9537   if (NumThreads.isInvalid())
9538     return nullptr;
9539   return getDerived().RebuildOMPNumThreadsClause(
9540       NumThreads.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9541 }
9542 
9543 template <typename Derived>
9544 OMPClause *
9545 TreeTransform<Derived>::TransformOMPSafelenClause(OMPSafelenClause *C) {
9546   ExprResult E = getDerived().TransformExpr(C->getSafelen());
9547   if (E.isInvalid())
9548     return nullptr;
9549   return getDerived().RebuildOMPSafelenClause(
9550       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9551 }
9552 
9553 template <typename Derived>
9554 OMPClause *
9555 TreeTransform<Derived>::TransformOMPAllocatorClause(OMPAllocatorClause *C) {
9556   ExprResult E = getDerived().TransformExpr(C->getAllocator());
9557   if (E.isInvalid())
9558     return nullptr;
9559   return getDerived().RebuildOMPAllocatorClause(
9560       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9561 }
9562 
9563 template <typename Derived>
9564 OMPClause *
9565 TreeTransform<Derived>::TransformOMPSimdlenClause(OMPSimdlenClause *C) {
9566   ExprResult E = getDerived().TransformExpr(C->getSimdlen());
9567   if (E.isInvalid())
9568     return nullptr;
9569   return getDerived().RebuildOMPSimdlenClause(
9570       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9571 }
9572 
9573 template <typename Derived>
9574 OMPClause *TreeTransform<Derived>::TransformOMPSizesClause(OMPSizesClause *C) {
9575   SmallVector<Expr *, 4> TransformedSizes;
9576   TransformedSizes.reserve(C->getNumSizes());
9577   bool Changed = false;
9578   for (Expr *E : C->getSizesRefs()) {
9579     if (!E) {
9580       TransformedSizes.push_back(nullptr);
9581       continue;
9582     }
9583 
9584     ExprResult T = getDerived().TransformExpr(E);
9585     if (T.isInvalid())
9586       return nullptr;
9587     if (E != T.get())
9588       Changed = true;
9589     TransformedSizes.push_back(T.get());
9590   }
9591 
9592   if (!Changed && !getDerived().AlwaysRebuild())
9593     return C;
9594   return RebuildOMPSizesClause(TransformedSizes, C->getBeginLoc(),
9595                                C->getLParenLoc(), C->getEndLoc());
9596 }
9597 
9598 template <typename Derived>
9599 OMPClause *TreeTransform<Derived>::TransformOMPFullClause(OMPFullClause *C) {
9600   if (!getDerived().AlwaysRebuild())
9601     return C;
9602   return RebuildOMPFullClause(C->getBeginLoc(), C->getEndLoc());
9603 }
9604 
9605 template <typename Derived>
9606 OMPClause *
9607 TreeTransform<Derived>::TransformOMPPartialClause(OMPPartialClause *C) {
9608   ExprResult T = getDerived().TransformExpr(C->getFactor());
9609   if (T.isInvalid())
9610     return nullptr;
9611   Expr *Factor = T.get();
9612   bool Changed = Factor != C->getFactor();
9613 
9614   if (!Changed && !getDerived().AlwaysRebuild())
9615     return C;
9616   return RebuildOMPPartialClause(Factor, C->getBeginLoc(), C->getLParenLoc(),
9617                                  C->getEndLoc());
9618 }
9619 
9620 template <typename Derived>
9621 OMPClause *
9622 TreeTransform<Derived>::TransformOMPCollapseClause(OMPCollapseClause *C) {
9623   ExprResult E = getDerived().TransformExpr(C->getNumForLoops());
9624   if (E.isInvalid())
9625     return nullptr;
9626   return getDerived().RebuildOMPCollapseClause(
9627       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9628 }
9629 
9630 template <typename Derived>
9631 OMPClause *
9632 TreeTransform<Derived>::TransformOMPDefaultClause(OMPDefaultClause *C) {
9633   return getDerived().RebuildOMPDefaultClause(
9634       C->getDefaultKind(), C->getDefaultKindKwLoc(), C->getBeginLoc(),
9635       C->getLParenLoc(), C->getEndLoc());
9636 }
9637 
9638 template <typename Derived>
9639 OMPClause *
9640 TreeTransform<Derived>::TransformOMPProcBindClause(OMPProcBindClause *C) {
9641   return getDerived().RebuildOMPProcBindClause(
9642       C->getProcBindKind(), C->getProcBindKindKwLoc(), C->getBeginLoc(),
9643       C->getLParenLoc(), C->getEndLoc());
9644 }
9645 
9646 template <typename Derived>
9647 OMPClause *
9648 TreeTransform<Derived>::TransformOMPScheduleClause(OMPScheduleClause *C) {
9649   ExprResult E = getDerived().TransformExpr(C->getChunkSize());
9650   if (E.isInvalid())
9651     return nullptr;
9652   return getDerived().RebuildOMPScheduleClause(
9653       C->getFirstScheduleModifier(), C->getSecondScheduleModifier(),
9654       C->getScheduleKind(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
9655       C->getFirstScheduleModifierLoc(), C->getSecondScheduleModifierLoc(),
9656       C->getScheduleKindLoc(), C->getCommaLoc(), C->getEndLoc());
9657 }
9658 
9659 template <typename Derived>
9660 OMPClause *
9661 TreeTransform<Derived>::TransformOMPOrderedClause(OMPOrderedClause *C) {
9662   ExprResult E;
9663   if (auto *Num = C->getNumForLoops()) {
9664     E = getDerived().TransformExpr(Num);
9665     if (E.isInvalid())
9666       return nullptr;
9667   }
9668   return getDerived().RebuildOMPOrderedClause(C->getBeginLoc(), C->getEndLoc(),
9669                                               C->getLParenLoc(), E.get());
9670 }
9671 
9672 template <typename Derived>
9673 OMPClause *
9674 TreeTransform<Derived>::TransformOMPDetachClause(OMPDetachClause *C) {
9675   ExprResult E;
9676   if (Expr *Evt = C->getEventHandler()) {
9677     E = getDerived().TransformExpr(Evt);
9678     if (E.isInvalid())
9679       return nullptr;
9680   }
9681   return getDerived().RebuildOMPDetachClause(E.get(), C->getBeginLoc(),
9682                                              C->getLParenLoc(), C->getEndLoc());
9683 }
9684 
9685 template <typename Derived>
9686 OMPClause *
9687 TreeTransform<Derived>::TransformOMPNowaitClause(OMPNowaitClause *C) {
9688   // No need to rebuild this clause, no template-dependent parameters.
9689   return C;
9690 }
9691 
9692 template <typename Derived>
9693 OMPClause *
9694 TreeTransform<Derived>::TransformOMPUntiedClause(OMPUntiedClause *C) {
9695   // No need to rebuild this clause, no template-dependent parameters.
9696   return C;
9697 }
9698 
9699 template <typename Derived>
9700 OMPClause *
9701 TreeTransform<Derived>::TransformOMPMergeableClause(OMPMergeableClause *C) {
9702   // No need to rebuild this clause, no template-dependent parameters.
9703   return C;
9704 }
9705 
9706 template <typename Derived>
9707 OMPClause *TreeTransform<Derived>::TransformOMPReadClause(OMPReadClause *C) {
9708   // No need to rebuild this clause, no template-dependent parameters.
9709   return C;
9710 }
9711 
9712 template <typename Derived>
9713 OMPClause *TreeTransform<Derived>::TransformOMPWriteClause(OMPWriteClause *C) {
9714   // No need to rebuild this clause, no template-dependent parameters.
9715   return C;
9716 }
9717 
9718 template <typename Derived>
9719 OMPClause *
9720 TreeTransform<Derived>::TransformOMPUpdateClause(OMPUpdateClause *C) {
9721   // No need to rebuild this clause, no template-dependent parameters.
9722   return C;
9723 }
9724 
9725 template <typename Derived>
9726 OMPClause *
9727 TreeTransform<Derived>::TransformOMPCaptureClause(OMPCaptureClause *C) {
9728   // No need to rebuild this clause, no template-dependent parameters.
9729   return C;
9730 }
9731 
9732 template <typename Derived>
9733 OMPClause *
9734 TreeTransform<Derived>::TransformOMPCompareClause(OMPCompareClause *C) {
9735   // No need to rebuild this clause, no template-dependent parameters.
9736   return C;
9737 }
9738 
9739 template <typename Derived>
9740 OMPClause *
9741 TreeTransform<Derived>::TransformOMPSeqCstClause(OMPSeqCstClause *C) {
9742   // No need to rebuild this clause, no template-dependent parameters.
9743   return C;
9744 }
9745 
9746 template <typename Derived>
9747 OMPClause *
9748 TreeTransform<Derived>::TransformOMPAcqRelClause(OMPAcqRelClause *C) {
9749   // No need to rebuild this clause, no template-dependent parameters.
9750   return C;
9751 }
9752 
9753 template <typename Derived>
9754 OMPClause *
9755 TreeTransform<Derived>::TransformOMPAcquireClause(OMPAcquireClause *C) {
9756   // No need to rebuild this clause, no template-dependent parameters.
9757   return C;
9758 }
9759 
9760 template <typename Derived>
9761 OMPClause *
9762 TreeTransform<Derived>::TransformOMPReleaseClause(OMPReleaseClause *C) {
9763   // No need to rebuild this clause, no template-dependent parameters.
9764   return C;
9765 }
9766 
9767 template <typename Derived>
9768 OMPClause *
9769 TreeTransform<Derived>::TransformOMPRelaxedClause(OMPRelaxedClause *C) {
9770   // No need to rebuild this clause, no template-dependent parameters.
9771   return C;
9772 }
9773 
9774 template <typename Derived>
9775 OMPClause *
9776 TreeTransform<Derived>::TransformOMPThreadsClause(OMPThreadsClause *C) {
9777   // No need to rebuild this clause, no template-dependent parameters.
9778   return C;
9779 }
9780 
9781 template <typename Derived>
9782 OMPClause *TreeTransform<Derived>::TransformOMPSIMDClause(OMPSIMDClause *C) {
9783   // No need to rebuild this clause, no template-dependent parameters.
9784   return C;
9785 }
9786 
9787 template <typename Derived>
9788 OMPClause *
9789 TreeTransform<Derived>::TransformOMPNogroupClause(OMPNogroupClause *C) {
9790   // No need to rebuild this clause, no template-dependent parameters.
9791   return C;
9792 }
9793 
9794 template <typename Derived>
9795 OMPClause *TreeTransform<Derived>::TransformOMPInitClause(OMPInitClause *C) {
9796   ExprResult IVR = getDerived().TransformExpr(C->getInteropVar());
9797   if (IVR.isInvalid())
9798     return nullptr;
9799 
9800   OMPInteropInfo InteropInfo(C->getIsTarget(), C->getIsTargetSync());
9801   InteropInfo.PreferTypes.reserve(C->varlist_size() - 1);
9802   for (Expr *E : llvm::drop_begin(C->varlists())) {
9803     ExprResult ER = getDerived().TransformExpr(cast<Expr>(E));
9804     if (ER.isInvalid())
9805       return nullptr;
9806     InteropInfo.PreferTypes.push_back(ER.get());
9807   }
9808   return getDerived().RebuildOMPInitClause(IVR.get(), InteropInfo,
9809                                            C->getBeginLoc(), C->getLParenLoc(),
9810                                            C->getVarLoc(), C->getEndLoc());
9811 }
9812 
9813 template <typename Derived>
9814 OMPClause *TreeTransform<Derived>::TransformOMPUseClause(OMPUseClause *C) {
9815   ExprResult ER = getDerived().TransformExpr(C->getInteropVar());
9816   if (ER.isInvalid())
9817     return nullptr;
9818   return getDerived().RebuildOMPUseClause(ER.get(), C->getBeginLoc(),
9819                                           C->getLParenLoc(), C->getVarLoc(),
9820                                           C->getEndLoc());
9821 }
9822 
9823 template <typename Derived>
9824 OMPClause *
9825 TreeTransform<Derived>::TransformOMPDestroyClause(OMPDestroyClause *C) {
9826   ExprResult ER;
9827   if (Expr *IV = C->getInteropVar()) {
9828     ER = getDerived().TransformExpr(IV);
9829     if (ER.isInvalid())
9830       return nullptr;
9831   }
9832   return getDerived().RebuildOMPDestroyClause(ER.get(), C->getBeginLoc(),
9833                                               C->getLParenLoc(), C->getVarLoc(),
9834                                               C->getEndLoc());
9835 }
9836 
9837 template <typename Derived>
9838 OMPClause *
9839 TreeTransform<Derived>::TransformOMPNovariantsClause(OMPNovariantsClause *C) {
9840   ExprResult Cond = getDerived().TransformExpr(C->getCondition());
9841   if (Cond.isInvalid())
9842     return nullptr;
9843   return getDerived().RebuildOMPNovariantsClause(
9844       Cond.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9845 }
9846 
9847 template <typename Derived>
9848 OMPClause *
9849 TreeTransform<Derived>::TransformOMPNocontextClause(OMPNocontextClause *C) {
9850   ExprResult Cond = getDerived().TransformExpr(C->getCondition());
9851   if (Cond.isInvalid())
9852     return nullptr;
9853   return getDerived().RebuildOMPNocontextClause(
9854       Cond.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9855 }
9856 
9857 template <typename Derived>
9858 OMPClause *
9859 TreeTransform<Derived>::TransformOMPFilterClause(OMPFilterClause *C) {
9860   ExprResult ThreadID = getDerived().TransformExpr(C->getThreadID());
9861   if (ThreadID.isInvalid())
9862     return nullptr;
9863   return getDerived().RebuildOMPFilterClause(ThreadID.get(), C->getBeginLoc(),
9864                                              C->getLParenLoc(), C->getEndLoc());
9865 }
9866 
9867 template <typename Derived>
9868 OMPClause *TreeTransform<Derived>::TransformOMPAlignClause(OMPAlignClause *C) {
9869   ExprResult E = getDerived().TransformExpr(C->getAlignment());
9870   if (E.isInvalid())
9871     return nullptr;
9872   return getDerived().RebuildOMPAlignClause(E.get(), C->getBeginLoc(),
9873                                             C->getLParenLoc(), C->getEndLoc());
9874 }
9875 
9876 template <typename Derived>
9877 OMPClause *TreeTransform<Derived>::TransformOMPUnifiedAddressClause(
9878     OMPUnifiedAddressClause *C) {
9879   llvm_unreachable("unified_address clause cannot appear in dependent context");
9880 }
9881 
9882 template <typename Derived>
9883 OMPClause *TreeTransform<Derived>::TransformOMPUnifiedSharedMemoryClause(
9884     OMPUnifiedSharedMemoryClause *C) {
9885   llvm_unreachable(
9886       "unified_shared_memory clause cannot appear in dependent context");
9887 }
9888 
9889 template <typename Derived>
9890 OMPClause *TreeTransform<Derived>::TransformOMPReverseOffloadClause(
9891     OMPReverseOffloadClause *C) {
9892   llvm_unreachable("reverse_offload clause cannot appear in dependent context");
9893 }
9894 
9895 template <typename Derived>
9896 OMPClause *TreeTransform<Derived>::TransformOMPDynamicAllocatorsClause(
9897     OMPDynamicAllocatorsClause *C) {
9898   llvm_unreachable(
9899       "dynamic_allocators clause cannot appear in dependent context");
9900 }
9901 
9902 template <typename Derived>
9903 OMPClause *TreeTransform<Derived>::TransformOMPAtomicDefaultMemOrderClause(
9904     OMPAtomicDefaultMemOrderClause *C) {
9905   llvm_unreachable(
9906       "atomic_default_mem_order clause cannot appear in dependent context");
9907 }
9908 
9909 template <typename Derived>
9910 OMPClause *TreeTransform<Derived>::TransformOMPAtClause(OMPAtClause *C) {
9911   return getDerived().RebuildOMPAtClause(C->getAtKind(), C->getAtKindKwLoc(),
9912                                          C->getBeginLoc(), C->getLParenLoc(),
9913                                          C->getEndLoc());
9914 }
9915 
9916 template <typename Derived>
9917 OMPClause *
9918 TreeTransform<Derived>::TransformOMPSeverityClause(OMPSeverityClause *C) {
9919   return getDerived().RebuildOMPSeverityClause(
9920       C->getSeverityKind(), C->getSeverityKindKwLoc(), C->getBeginLoc(),
9921       C->getLParenLoc(), C->getEndLoc());
9922 }
9923 
9924 template <typename Derived>
9925 OMPClause *
9926 TreeTransform<Derived>::TransformOMPMessageClause(OMPMessageClause *C) {
9927   ExprResult E = getDerived().TransformExpr(C->getMessageString());
9928   if (E.isInvalid())
9929     return nullptr;
9930   return getDerived().RebuildOMPMessageClause(
9931       C->getMessageString(), C->getBeginLoc(), C->getLParenLoc(),
9932       C->getEndLoc());
9933 }
9934 
9935 template <typename Derived>
9936 OMPClause *
9937 TreeTransform<Derived>::TransformOMPPrivateClause(OMPPrivateClause *C) {
9938   llvm::SmallVector<Expr *, 16> Vars;
9939   Vars.reserve(C->varlist_size());
9940   for (auto *VE : C->varlists()) {
9941     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9942     if (EVar.isInvalid())
9943       return nullptr;
9944     Vars.push_back(EVar.get());
9945   }
9946   return getDerived().RebuildOMPPrivateClause(
9947       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9948 }
9949 
9950 template <typename Derived>
9951 OMPClause *TreeTransform<Derived>::TransformOMPFirstprivateClause(
9952     OMPFirstprivateClause *C) {
9953   llvm::SmallVector<Expr *, 16> Vars;
9954   Vars.reserve(C->varlist_size());
9955   for (auto *VE : C->varlists()) {
9956     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9957     if (EVar.isInvalid())
9958       return nullptr;
9959     Vars.push_back(EVar.get());
9960   }
9961   return getDerived().RebuildOMPFirstprivateClause(
9962       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9963 }
9964 
9965 template <typename Derived>
9966 OMPClause *
9967 TreeTransform<Derived>::TransformOMPLastprivateClause(OMPLastprivateClause *C) {
9968   llvm::SmallVector<Expr *, 16> Vars;
9969   Vars.reserve(C->varlist_size());
9970   for (auto *VE : C->varlists()) {
9971     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9972     if (EVar.isInvalid())
9973       return nullptr;
9974     Vars.push_back(EVar.get());
9975   }
9976   return getDerived().RebuildOMPLastprivateClause(
9977       Vars, C->getKind(), C->getKindLoc(), C->getColonLoc(), C->getBeginLoc(),
9978       C->getLParenLoc(), C->getEndLoc());
9979 }
9980 
9981 template <typename Derived>
9982 OMPClause *
9983 TreeTransform<Derived>::TransformOMPSharedClause(OMPSharedClause *C) {
9984   llvm::SmallVector<Expr *, 16> Vars;
9985   Vars.reserve(C->varlist_size());
9986   for (auto *VE : C->varlists()) {
9987     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9988     if (EVar.isInvalid())
9989       return nullptr;
9990     Vars.push_back(EVar.get());
9991   }
9992   return getDerived().RebuildOMPSharedClause(Vars, C->getBeginLoc(),
9993                                              C->getLParenLoc(), C->getEndLoc());
9994 }
9995 
9996 template <typename Derived>
9997 OMPClause *
9998 TreeTransform<Derived>::TransformOMPReductionClause(OMPReductionClause *C) {
9999   llvm::SmallVector<Expr *, 16> Vars;
10000   Vars.reserve(C->varlist_size());
10001   for (auto *VE : C->varlists()) {
10002     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10003     if (EVar.isInvalid())
10004       return nullptr;
10005     Vars.push_back(EVar.get());
10006   }
10007   CXXScopeSpec ReductionIdScopeSpec;
10008   ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
10009 
10010   DeclarationNameInfo NameInfo = C->getNameInfo();
10011   if (NameInfo.getName()) {
10012     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
10013     if (!NameInfo.getName())
10014       return nullptr;
10015   }
10016   // Build a list of all UDR decls with the same names ranged by the Scopes.
10017   // The Scope boundary is a duplication of the previous decl.
10018   llvm::SmallVector<Expr *, 16> UnresolvedReductions;
10019   for (auto *E : C->reduction_ops()) {
10020     // Transform all the decls.
10021     if (E) {
10022       auto *ULE = cast<UnresolvedLookupExpr>(E);
10023       UnresolvedSet<8> Decls;
10024       for (auto *D : ULE->decls()) {
10025         NamedDecl *InstD =
10026             cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
10027         Decls.addDecl(InstD, InstD->getAccess());
10028       }
10029       UnresolvedReductions.push_back(
10030        UnresolvedLookupExpr::Create(
10031           SemaRef.Context, /*NamingClass=*/nullptr,
10032           ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context),
10033           NameInfo, /*ADL=*/true, ULE->isOverloaded(),
10034           Decls.begin(), Decls.end()));
10035     } else
10036       UnresolvedReductions.push_back(nullptr);
10037   }
10038   return getDerived().RebuildOMPReductionClause(
10039       Vars, C->getModifier(), C->getBeginLoc(), C->getLParenLoc(),
10040       C->getModifierLoc(), C->getColonLoc(), C->getEndLoc(),
10041       ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
10042 }
10043 
10044 template <typename Derived>
10045 OMPClause *TreeTransform<Derived>::TransformOMPTaskReductionClause(
10046     OMPTaskReductionClause *C) {
10047   llvm::SmallVector<Expr *, 16> Vars;
10048   Vars.reserve(C->varlist_size());
10049   for (auto *VE : C->varlists()) {
10050     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10051     if (EVar.isInvalid())
10052       return nullptr;
10053     Vars.push_back(EVar.get());
10054   }
10055   CXXScopeSpec ReductionIdScopeSpec;
10056   ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
10057 
10058   DeclarationNameInfo NameInfo = C->getNameInfo();
10059   if (NameInfo.getName()) {
10060     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
10061     if (!NameInfo.getName())
10062       return nullptr;
10063   }
10064   // Build a list of all UDR decls with the same names ranged by the Scopes.
10065   // The Scope boundary is a duplication of the previous decl.
10066   llvm::SmallVector<Expr *, 16> UnresolvedReductions;
10067   for (auto *E : C->reduction_ops()) {
10068     // Transform all the decls.
10069     if (E) {
10070       auto *ULE = cast<UnresolvedLookupExpr>(E);
10071       UnresolvedSet<8> Decls;
10072       for (auto *D : ULE->decls()) {
10073         NamedDecl *InstD =
10074             cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
10075         Decls.addDecl(InstD, InstD->getAccess());
10076       }
10077       UnresolvedReductions.push_back(UnresolvedLookupExpr::Create(
10078           SemaRef.Context, /*NamingClass=*/nullptr,
10079           ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), NameInfo,
10080           /*ADL=*/true, ULE->isOverloaded(), Decls.begin(), Decls.end()));
10081     } else
10082       UnresolvedReductions.push_back(nullptr);
10083   }
10084   return getDerived().RebuildOMPTaskReductionClause(
10085       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
10086       C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
10087 }
10088 
10089 template <typename Derived>
10090 OMPClause *
10091 TreeTransform<Derived>::TransformOMPInReductionClause(OMPInReductionClause *C) {
10092   llvm::SmallVector<Expr *, 16> Vars;
10093   Vars.reserve(C->varlist_size());
10094   for (auto *VE : C->varlists()) {
10095     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10096     if (EVar.isInvalid())
10097       return nullptr;
10098     Vars.push_back(EVar.get());
10099   }
10100   CXXScopeSpec ReductionIdScopeSpec;
10101   ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
10102 
10103   DeclarationNameInfo NameInfo = C->getNameInfo();
10104   if (NameInfo.getName()) {
10105     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
10106     if (!NameInfo.getName())
10107       return nullptr;
10108   }
10109   // Build a list of all UDR decls with the same names ranged by the Scopes.
10110   // The Scope boundary is a duplication of the previous decl.
10111   llvm::SmallVector<Expr *, 16> UnresolvedReductions;
10112   for (auto *E : C->reduction_ops()) {
10113     // Transform all the decls.
10114     if (E) {
10115       auto *ULE = cast<UnresolvedLookupExpr>(E);
10116       UnresolvedSet<8> Decls;
10117       for (auto *D : ULE->decls()) {
10118         NamedDecl *InstD =
10119             cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
10120         Decls.addDecl(InstD, InstD->getAccess());
10121       }
10122       UnresolvedReductions.push_back(UnresolvedLookupExpr::Create(
10123           SemaRef.Context, /*NamingClass=*/nullptr,
10124           ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), NameInfo,
10125           /*ADL=*/true, ULE->isOverloaded(), Decls.begin(), Decls.end()));
10126     } else
10127       UnresolvedReductions.push_back(nullptr);
10128   }
10129   return getDerived().RebuildOMPInReductionClause(
10130       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
10131       C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
10132 }
10133 
10134 template <typename Derived>
10135 OMPClause *
10136 TreeTransform<Derived>::TransformOMPLinearClause(OMPLinearClause *C) {
10137   llvm::SmallVector<Expr *, 16> Vars;
10138   Vars.reserve(C->varlist_size());
10139   for (auto *VE : C->varlists()) {
10140     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10141     if (EVar.isInvalid())
10142       return nullptr;
10143     Vars.push_back(EVar.get());
10144   }
10145   ExprResult Step = getDerived().TransformExpr(C->getStep());
10146   if (Step.isInvalid())
10147     return nullptr;
10148   return getDerived().RebuildOMPLinearClause(
10149       Vars, Step.get(), C->getBeginLoc(), C->getLParenLoc(), C->getModifier(),
10150       C->getModifierLoc(), C->getColonLoc(), C->getEndLoc());
10151 }
10152 
10153 template <typename Derived>
10154 OMPClause *
10155 TreeTransform<Derived>::TransformOMPAlignedClause(OMPAlignedClause *C) {
10156   llvm::SmallVector<Expr *, 16> Vars;
10157   Vars.reserve(C->varlist_size());
10158   for (auto *VE : C->varlists()) {
10159     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10160     if (EVar.isInvalid())
10161       return nullptr;
10162     Vars.push_back(EVar.get());
10163   }
10164   ExprResult Alignment = getDerived().TransformExpr(C->getAlignment());
10165   if (Alignment.isInvalid())
10166     return nullptr;
10167   return getDerived().RebuildOMPAlignedClause(
10168       Vars, Alignment.get(), C->getBeginLoc(), C->getLParenLoc(),
10169       C->getColonLoc(), C->getEndLoc());
10170 }
10171 
10172 template <typename Derived>
10173 OMPClause *
10174 TreeTransform<Derived>::TransformOMPCopyinClause(OMPCopyinClause *C) {
10175   llvm::SmallVector<Expr *, 16> Vars;
10176   Vars.reserve(C->varlist_size());
10177   for (auto *VE : C->varlists()) {
10178     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10179     if (EVar.isInvalid())
10180       return nullptr;
10181     Vars.push_back(EVar.get());
10182   }
10183   return getDerived().RebuildOMPCopyinClause(Vars, C->getBeginLoc(),
10184                                              C->getLParenLoc(), C->getEndLoc());
10185 }
10186 
10187 template <typename Derived>
10188 OMPClause *
10189 TreeTransform<Derived>::TransformOMPCopyprivateClause(OMPCopyprivateClause *C) {
10190   llvm::SmallVector<Expr *, 16> Vars;
10191   Vars.reserve(C->varlist_size());
10192   for (auto *VE : C->varlists()) {
10193     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10194     if (EVar.isInvalid())
10195       return nullptr;
10196     Vars.push_back(EVar.get());
10197   }
10198   return getDerived().RebuildOMPCopyprivateClause(
10199       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10200 }
10201 
10202 template <typename Derived>
10203 OMPClause *TreeTransform<Derived>::TransformOMPFlushClause(OMPFlushClause *C) {
10204   llvm::SmallVector<Expr *, 16> Vars;
10205   Vars.reserve(C->varlist_size());
10206   for (auto *VE : C->varlists()) {
10207     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10208     if (EVar.isInvalid())
10209       return nullptr;
10210     Vars.push_back(EVar.get());
10211   }
10212   return getDerived().RebuildOMPFlushClause(Vars, C->getBeginLoc(),
10213                                             C->getLParenLoc(), C->getEndLoc());
10214 }
10215 
10216 template <typename Derived>
10217 OMPClause *
10218 TreeTransform<Derived>::TransformOMPDepobjClause(OMPDepobjClause *C) {
10219   ExprResult E = getDerived().TransformExpr(C->getDepobj());
10220   if (E.isInvalid())
10221     return nullptr;
10222   return getDerived().RebuildOMPDepobjClause(E.get(), C->getBeginLoc(),
10223                                              C->getLParenLoc(), C->getEndLoc());
10224 }
10225 
10226 template <typename Derived>
10227 OMPClause *
10228 TreeTransform<Derived>::TransformOMPDependClause(OMPDependClause *C) {
10229   llvm::SmallVector<Expr *, 16> Vars;
10230   Expr *DepModifier = C->getModifier();
10231   if (DepModifier) {
10232     ExprResult DepModRes = getDerived().TransformExpr(DepModifier);
10233     if (DepModRes.isInvalid())
10234       return nullptr;
10235     DepModifier = DepModRes.get();
10236   }
10237   Vars.reserve(C->varlist_size());
10238   for (auto *VE : C->varlists()) {
10239     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10240     if (EVar.isInvalid())
10241       return nullptr;
10242     Vars.push_back(EVar.get());
10243   }
10244   return getDerived().RebuildOMPDependClause(
10245       {C->getDependencyKind(), C->getDependencyLoc(), C->getColonLoc(),
10246        C->getOmpAllMemoryLoc()},
10247       DepModifier, Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10248 }
10249 
10250 template <typename Derived>
10251 OMPClause *
10252 TreeTransform<Derived>::TransformOMPDeviceClause(OMPDeviceClause *C) {
10253   ExprResult E = getDerived().TransformExpr(C->getDevice());
10254   if (E.isInvalid())
10255     return nullptr;
10256   return getDerived().RebuildOMPDeviceClause(
10257       C->getModifier(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
10258       C->getModifierLoc(), C->getEndLoc());
10259 }
10260 
10261 template <typename Derived, class T>
10262 bool transformOMPMappableExprListClause(
10263     TreeTransform<Derived> &TT, OMPMappableExprListClause<T> *C,
10264     llvm::SmallVectorImpl<Expr *> &Vars, CXXScopeSpec &MapperIdScopeSpec,
10265     DeclarationNameInfo &MapperIdInfo,
10266     llvm::SmallVectorImpl<Expr *> &UnresolvedMappers) {
10267   // Transform expressions in the list.
10268   Vars.reserve(C->varlist_size());
10269   for (auto *VE : C->varlists()) {
10270     ExprResult EVar = TT.getDerived().TransformExpr(cast<Expr>(VE));
10271     if (EVar.isInvalid())
10272       return true;
10273     Vars.push_back(EVar.get());
10274   }
10275   // Transform mapper scope specifier and identifier.
10276   NestedNameSpecifierLoc QualifierLoc;
10277   if (C->getMapperQualifierLoc()) {
10278     QualifierLoc = TT.getDerived().TransformNestedNameSpecifierLoc(
10279         C->getMapperQualifierLoc());
10280     if (!QualifierLoc)
10281       return true;
10282   }
10283   MapperIdScopeSpec.Adopt(QualifierLoc);
10284   MapperIdInfo = C->getMapperIdInfo();
10285   if (MapperIdInfo.getName()) {
10286     MapperIdInfo = TT.getDerived().TransformDeclarationNameInfo(MapperIdInfo);
10287     if (!MapperIdInfo.getName())
10288       return true;
10289   }
10290   // Build a list of all candidate OMPDeclareMapperDecls, which is provided by
10291   // the previous user-defined mapper lookup in dependent environment.
10292   for (auto *E : C->mapperlists()) {
10293     // Transform all the decls.
10294     if (E) {
10295       auto *ULE = cast<UnresolvedLookupExpr>(E);
10296       UnresolvedSet<8> Decls;
10297       for (auto *D : ULE->decls()) {
10298         NamedDecl *InstD =
10299             cast<NamedDecl>(TT.getDerived().TransformDecl(E->getExprLoc(), D));
10300         Decls.addDecl(InstD, InstD->getAccess());
10301       }
10302       UnresolvedMappers.push_back(UnresolvedLookupExpr::Create(
10303           TT.getSema().Context, /*NamingClass=*/nullptr,
10304           MapperIdScopeSpec.getWithLocInContext(TT.getSema().Context),
10305           MapperIdInfo, /*ADL=*/true, ULE->isOverloaded(), Decls.begin(),
10306           Decls.end()));
10307     } else {
10308       UnresolvedMappers.push_back(nullptr);
10309     }
10310   }
10311   return false;
10312 }
10313 
10314 template <typename Derived>
10315 OMPClause *TreeTransform<Derived>::TransformOMPMapClause(OMPMapClause *C) {
10316   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10317   llvm::SmallVector<Expr *, 16> Vars;
10318   Expr *IteratorModifier = C->getIteratorModifier();
10319   if (IteratorModifier) {
10320     ExprResult MapModRes = getDerived().TransformExpr(IteratorModifier);
10321     if (MapModRes.isInvalid())
10322       return nullptr;
10323     IteratorModifier = MapModRes.get();
10324   }
10325   CXXScopeSpec MapperIdScopeSpec;
10326   DeclarationNameInfo MapperIdInfo;
10327   llvm::SmallVector<Expr *, 16> UnresolvedMappers;
10328   if (transformOMPMappableExprListClause<Derived, OMPMapClause>(
10329           *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
10330     return nullptr;
10331   return getDerived().RebuildOMPMapClause(
10332       IteratorModifier, C->getMapTypeModifiers(), C->getMapTypeModifiersLoc(),
10333       MapperIdScopeSpec, MapperIdInfo, C->getMapType(), C->isImplicitMapType(),
10334       C->getMapLoc(), C->getColonLoc(), Vars, Locs, UnresolvedMappers);
10335 }
10336 
10337 template <typename Derived>
10338 OMPClause *
10339 TreeTransform<Derived>::TransformOMPAllocateClause(OMPAllocateClause *C) {
10340   Expr *Allocator = C->getAllocator();
10341   if (Allocator) {
10342     ExprResult AllocatorRes = getDerived().TransformExpr(Allocator);
10343     if (AllocatorRes.isInvalid())
10344       return nullptr;
10345     Allocator = AllocatorRes.get();
10346   }
10347   llvm::SmallVector<Expr *, 16> Vars;
10348   Vars.reserve(C->varlist_size());
10349   for (auto *VE : C->varlists()) {
10350     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10351     if (EVar.isInvalid())
10352       return nullptr;
10353     Vars.push_back(EVar.get());
10354   }
10355   return getDerived().RebuildOMPAllocateClause(
10356       Allocator, Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
10357       C->getEndLoc());
10358 }
10359 
10360 template <typename Derived>
10361 OMPClause *
10362 TreeTransform<Derived>::TransformOMPNumTeamsClause(OMPNumTeamsClause *C) {
10363   ExprResult E = getDerived().TransformExpr(C->getNumTeams());
10364   if (E.isInvalid())
10365     return nullptr;
10366   return getDerived().RebuildOMPNumTeamsClause(
10367       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10368 }
10369 
10370 template <typename Derived>
10371 OMPClause *
10372 TreeTransform<Derived>::TransformOMPThreadLimitClause(OMPThreadLimitClause *C) {
10373   ExprResult E = getDerived().TransformExpr(C->getThreadLimit());
10374   if (E.isInvalid())
10375     return nullptr;
10376   return getDerived().RebuildOMPThreadLimitClause(
10377       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10378 }
10379 
10380 template <typename Derived>
10381 OMPClause *
10382 TreeTransform<Derived>::TransformOMPPriorityClause(OMPPriorityClause *C) {
10383   ExprResult E = getDerived().TransformExpr(C->getPriority());
10384   if (E.isInvalid())
10385     return nullptr;
10386   return getDerived().RebuildOMPPriorityClause(
10387       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10388 }
10389 
10390 template <typename Derived>
10391 OMPClause *
10392 TreeTransform<Derived>::TransformOMPGrainsizeClause(OMPGrainsizeClause *C) {
10393   ExprResult E = getDerived().TransformExpr(C->getGrainsize());
10394   if (E.isInvalid())
10395     return nullptr;
10396   return getDerived().RebuildOMPGrainsizeClause(
10397       C->getModifier(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
10398       C->getModifierLoc(), C->getEndLoc());
10399 }
10400 
10401 template <typename Derived>
10402 OMPClause *
10403 TreeTransform<Derived>::TransformOMPNumTasksClause(OMPNumTasksClause *C) {
10404   ExprResult E = getDerived().TransformExpr(C->getNumTasks());
10405   if (E.isInvalid())
10406     return nullptr;
10407   return getDerived().RebuildOMPNumTasksClause(
10408       C->getModifier(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
10409       C->getModifierLoc(), C->getEndLoc());
10410 }
10411 
10412 template <typename Derived>
10413 OMPClause *TreeTransform<Derived>::TransformOMPHintClause(OMPHintClause *C) {
10414   ExprResult E = getDerived().TransformExpr(C->getHint());
10415   if (E.isInvalid())
10416     return nullptr;
10417   return getDerived().RebuildOMPHintClause(E.get(), C->getBeginLoc(),
10418                                            C->getLParenLoc(), C->getEndLoc());
10419 }
10420 
10421 template <typename Derived>
10422 OMPClause *TreeTransform<Derived>::TransformOMPDistScheduleClause(
10423     OMPDistScheduleClause *C) {
10424   ExprResult E = getDerived().TransformExpr(C->getChunkSize());
10425   if (E.isInvalid())
10426     return nullptr;
10427   return getDerived().RebuildOMPDistScheduleClause(
10428       C->getDistScheduleKind(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
10429       C->getDistScheduleKindLoc(), C->getCommaLoc(), C->getEndLoc());
10430 }
10431 
10432 template <typename Derived>
10433 OMPClause *
10434 TreeTransform<Derived>::TransformOMPDefaultmapClause(OMPDefaultmapClause *C) {
10435   // Rebuild Defaultmap Clause since we need to invoke the checking of
10436   // defaultmap(none:variable-category) after template initialization.
10437   return getDerived().RebuildOMPDefaultmapClause(C->getDefaultmapModifier(),
10438                                                  C->getDefaultmapKind(),
10439                                                  C->getBeginLoc(),
10440                                                  C->getLParenLoc(),
10441                                                  C->getDefaultmapModifierLoc(),
10442                                                  C->getDefaultmapKindLoc(),
10443                                                  C->getEndLoc());
10444 }
10445 
10446 template <typename Derived>
10447 OMPClause *TreeTransform<Derived>::TransformOMPToClause(OMPToClause *C) {
10448   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10449   llvm::SmallVector<Expr *, 16> Vars;
10450   CXXScopeSpec MapperIdScopeSpec;
10451   DeclarationNameInfo MapperIdInfo;
10452   llvm::SmallVector<Expr *, 16> UnresolvedMappers;
10453   if (transformOMPMappableExprListClause<Derived, OMPToClause>(
10454           *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
10455     return nullptr;
10456   return getDerived().RebuildOMPToClause(
10457       C->getMotionModifiers(), C->getMotionModifiersLoc(), MapperIdScopeSpec,
10458       MapperIdInfo, C->getColonLoc(), Vars, Locs, UnresolvedMappers);
10459 }
10460 
10461 template <typename Derived>
10462 OMPClause *TreeTransform<Derived>::TransformOMPFromClause(OMPFromClause *C) {
10463   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10464   llvm::SmallVector<Expr *, 16> Vars;
10465   CXXScopeSpec MapperIdScopeSpec;
10466   DeclarationNameInfo MapperIdInfo;
10467   llvm::SmallVector<Expr *, 16> UnresolvedMappers;
10468   if (transformOMPMappableExprListClause<Derived, OMPFromClause>(
10469           *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
10470     return nullptr;
10471   return getDerived().RebuildOMPFromClause(
10472       C->getMotionModifiers(), C->getMotionModifiersLoc(), MapperIdScopeSpec,
10473       MapperIdInfo, C->getColonLoc(), Vars, Locs, UnresolvedMappers);
10474 }
10475 
10476 template <typename Derived>
10477 OMPClause *TreeTransform<Derived>::TransformOMPUseDevicePtrClause(
10478     OMPUseDevicePtrClause *C) {
10479   llvm::SmallVector<Expr *, 16> Vars;
10480   Vars.reserve(C->varlist_size());
10481   for (auto *VE : C->varlists()) {
10482     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10483     if (EVar.isInvalid())
10484       return nullptr;
10485     Vars.push_back(EVar.get());
10486   }
10487   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10488   return getDerived().RebuildOMPUseDevicePtrClause(Vars, Locs);
10489 }
10490 
10491 template <typename Derived>
10492 OMPClause *TreeTransform<Derived>::TransformOMPUseDeviceAddrClause(
10493     OMPUseDeviceAddrClause *C) {
10494   llvm::SmallVector<Expr *, 16> Vars;
10495   Vars.reserve(C->varlist_size());
10496   for (auto *VE : C->varlists()) {
10497     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10498     if (EVar.isInvalid())
10499       return nullptr;
10500     Vars.push_back(EVar.get());
10501   }
10502   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10503   return getDerived().RebuildOMPUseDeviceAddrClause(Vars, Locs);
10504 }
10505 
10506 template <typename Derived>
10507 OMPClause *
10508 TreeTransform<Derived>::TransformOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
10509   llvm::SmallVector<Expr *, 16> Vars;
10510   Vars.reserve(C->varlist_size());
10511   for (auto *VE : C->varlists()) {
10512     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10513     if (EVar.isInvalid())
10514       return nullptr;
10515     Vars.push_back(EVar.get());
10516   }
10517   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10518   return getDerived().RebuildOMPIsDevicePtrClause(Vars, Locs);
10519 }
10520 
10521 template <typename Derived>
10522 OMPClause *TreeTransform<Derived>::TransformOMPHasDeviceAddrClause(
10523     OMPHasDeviceAddrClause *C) {
10524   llvm::SmallVector<Expr *, 16> Vars;
10525   Vars.reserve(C->varlist_size());
10526   for (auto *VE : C->varlists()) {
10527     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10528     if (EVar.isInvalid())
10529       return nullptr;
10530     Vars.push_back(EVar.get());
10531   }
10532   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10533   return getDerived().RebuildOMPHasDeviceAddrClause(Vars, Locs);
10534 }
10535 
10536 template <typename Derived>
10537 OMPClause *
10538 TreeTransform<Derived>::TransformOMPNontemporalClause(OMPNontemporalClause *C) {
10539   llvm::SmallVector<Expr *, 16> Vars;
10540   Vars.reserve(C->varlist_size());
10541   for (auto *VE : C->varlists()) {
10542     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10543     if (EVar.isInvalid())
10544       return nullptr;
10545     Vars.push_back(EVar.get());
10546   }
10547   return getDerived().RebuildOMPNontemporalClause(
10548       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10549 }
10550 
10551 template <typename Derived>
10552 OMPClause *
10553 TreeTransform<Derived>::TransformOMPInclusiveClause(OMPInclusiveClause *C) {
10554   llvm::SmallVector<Expr *, 16> Vars;
10555   Vars.reserve(C->varlist_size());
10556   for (auto *VE : C->varlists()) {
10557     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10558     if (EVar.isInvalid())
10559       return nullptr;
10560     Vars.push_back(EVar.get());
10561   }
10562   return getDerived().RebuildOMPInclusiveClause(
10563       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10564 }
10565 
10566 template <typename Derived>
10567 OMPClause *
10568 TreeTransform<Derived>::TransformOMPExclusiveClause(OMPExclusiveClause *C) {
10569   llvm::SmallVector<Expr *, 16> Vars;
10570   Vars.reserve(C->varlist_size());
10571   for (auto *VE : C->varlists()) {
10572     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10573     if (EVar.isInvalid())
10574       return nullptr;
10575     Vars.push_back(EVar.get());
10576   }
10577   return getDerived().RebuildOMPExclusiveClause(
10578       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10579 }
10580 
10581 template <typename Derived>
10582 OMPClause *TreeTransform<Derived>::TransformOMPUsesAllocatorsClause(
10583     OMPUsesAllocatorsClause *C) {
10584   SmallVector<Sema::UsesAllocatorsData, 16> Data;
10585   Data.reserve(C->getNumberOfAllocators());
10586   for (unsigned I = 0, E = C->getNumberOfAllocators(); I < E; ++I) {
10587     OMPUsesAllocatorsClause::Data D = C->getAllocatorData(I);
10588     ExprResult Allocator = getDerived().TransformExpr(D.Allocator);
10589     if (Allocator.isInvalid())
10590       continue;
10591     ExprResult AllocatorTraits;
10592     if (Expr *AT = D.AllocatorTraits) {
10593       AllocatorTraits = getDerived().TransformExpr(AT);
10594       if (AllocatorTraits.isInvalid())
10595         continue;
10596     }
10597     Sema::UsesAllocatorsData &NewD = Data.emplace_back();
10598     NewD.Allocator = Allocator.get();
10599     NewD.AllocatorTraits = AllocatorTraits.get();
10600     NewD.LParenLoc = D.LParenLoc;
10601     NewD.RParenLoc = D.RParenLoc;
10602   }
10603   return getDerived().RebuildOMPUsesAllocatorsClause(
10604       Data, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10605 }
10606 
10607 template <typename Derived>
10608 OMPClause *
10609 TreeTransform<Derived>::TransformOMPAffinityClause(OMPAffinityClause *C) {
10610   SmallVector<Expr *, 4> Locators;
10611   Locators.reserve(C->varlist_size());
10612   ExprResult ModifierRes;
10613   if (Expr *Modifier = C->getModifier()) {
10614     ModifierRes = getDerived().TransformExpr(Modifier);
10615     if (ModifierRes.isInvalid())
10616       return nullptr;
10617   }
10618   for (Expr *E : C->varlists()) {
10619     ExprResult Locator = getDerived().TransformExpr(E);
10620     if (Locator.isInvalid())
10621       continue;
10622     Locators.push_back(Locator.get());
10623   }
10624   return getDerived().RebuildOMPAffinityClause(
10625       C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(), C->getEndLoc(),
10626       ModifierRes.get(), Locators);
10627 }
10628 
10629 template <typename Derived>
10630 OMPClause *TreeTransform<Derived>::TransformOMPOrderClause(OMPOrderClause *C) {
10631   return getDerived().RebuildOMPOrderClause(
10632       C->getKind(), C->getKindKwLoc(), C->getBeginLoc(), C->getLParenLoc(),
10633       C->getEndLoc(), C->getModifier(), C->getModifierKwLoc());
10634 }
10635 
10636 template <typename Derived>
10637 OMPClause *TreeTransform<Derived>::TransformOMPBindClause(OMPBindClause *C) {
10638   return getDerived().RebuildOMPBindClause(
10639       C->getBindKind(), C->getBindKindLoc(), C->getBeginLoc(),
10640       C->getLParenLoc(), C->getEndLoc());
10641 }
10642 
10643 template <typename Derived>
10644 OMPClause *TreeTransform<Derived>::TransformOMPXDynCGroupMemClause(
10645     OMPXDynCGroupMemClause *C) {
10646   ExprResult Size = getDerived().TransformExpr(C->getSize());
10647   if (Size.isInvalid())
10648     return nullptr;
10649   return getDerived().RebuildOMPXDynCGroupMemClause(
10650       Size.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10651 }
10652 
10653 //===----------------------------------------------------------------------===//
10654 // Expression transformation
10655 //===----------------------------------------------------------------------===//
10656 template<typename Derived>
10657 ExprResult
10658 TreeTransform<Derived>::TransformConstantExpr(ConstantExpr *E) {
10659   return TransformExpr(E->getSubExpr());
10660 }
10661 
10662 template <typename Derived>
10663 ExprResult TreeTransform<Derived>::TransformSYCLUniqueStableNameExpr(
10664     SYCLUniqueStableNameExpr *E) {
10665   if (!E->isTypeDependent())
10666     return E;
10667 
10668   TypeSourceInfo *NewT = getDerived().TransformType(E->getTypeSourceInfo());
10669 
10670   if (!NewT)
10671     return ExprError();
10672 
10673   if (!getDerived().AlwaysRebuild() && E->getTypeSourceInfo() == NewT)
10674     return E;
10675 
10676   return getDerived().RebuildSYCLUniqueStableNameExpr(
10677       E->getLocation(), E->getLParenLocation(), E->getRParenLocation(), NewT);
10678 }
10679 
10680 template<typename Derived>
10681 ExprResult
10682 TreeTransform<Derived>::TransformPredefinedExpr(PredefinedExpr *E) {
10683   if (!E->isTypeDependent())
10684     return E;
10685 
10686   return getDerived().RebuildPredefinedExpr(E->getLocation(),
10687                                             E->getIdentKind());
10688 }
10689 
10690 template<typename Derived>
10691 ExprResult
10692 TreeTransform<Derived>::TransformDeclRefExpr(DeclRefExpr *E) {
10693   NestedNameSpecifierLoc QualifierLoc;
10694   if (E->getQualifierLoc()) {
10695     QualifierLoc
10696       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
10697     if (!QualifierLoc)
10698       return ExprError();
10699   }
10700 
10701   ValueDecl *ND
10702     = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getLocation(),
10703                                                          E->getDecl()));
10704   if (!ND)
10705     return ExprError();
10706 
10707   NamedDecl *Found = ND;
10708   if (E->getFoundDecl() != E->getDecl()) {
10709     Found = cast_or_null<NamedDecl>(
10710         getDerived().TransformDecl(E->getLocation(), E->getFoundDecl()));
10711     if (!Found)
10712       return ExprError();
10713   }
10714 
10715   DeclarationNameInfo NameInfo = E->getNameInfo();
10716   if (NameInfo.getName()) {
10717     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
10718     if (!NameInfo.getName())
10719       return ExprError();
10720   }
10721 
10722   if (!getDerived().AlwaysRebuild() &&
10723       QualifierLoc == E->getQualifierLoc() &&
10724       ND == E->getDecl() &&
10725       Found == E->getFoundDecl() &&
10726       NameInfo.getName() == E->getDecl()->getDeclName() &&
10727       !E->hasExplicitTemplateArgs()) {
10728 
10729     // Mark it referenced in the new context regardless.
10730     // FIXME: this is a bit instantiation-specific.
10731     SemaRef.MarkDeclRefReferenced(E);
10732 
10733     return E;
10734   }
10735 
10736   TemplateArgumentListInfo TransArgs, *TemplateArgs = nullptr;
10737   if (E->hasExplicitTemplateArgs()) {
10738     TemplateArgs = &TransArgs;
10739     TransArgs.setLAngleLoc(E->getLAngleLoc());
10740     TransArgs.setRAngleLoc(E->getRAngleLoc());
10741     if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
10742                                                 E->getNumTemplateArgs(),
10743                                                 TransArgs))
10744       return ExprError();
10745   }
10746 
10747   return getDerived().RebuildDeclRefExpr(QualifierLoc, ND, NameInfo,
10748                                          Found, TemplateArgs);
10749 }
10750 
10751 template<typename Derived>
10752 ExprResult
10753 TreeTransform<Derived>::TransformIntegerLiteral(IntegerLiteral *E) {
10754   return E;
10755 }
10756 
10757 template <typename Derived>
10758 ExprResult TreeTransform<Derived>::TransformFixedPointLiteral(
10759     FixedPointLiteral *E) {
10760   return E;
10761 }
10762 
10763 template<typename Derived>
10764 ExprResult
10765 TreeTransform<Derived>::TransformFloatingLiteral(FloatingLiteral *E) {
10766   return E;
10767 }
10768 
10769 template<typename Derived>
10770 ExprResult
10771 TreeTransform<Derived>::TransformImaginaryLiteral(ImaginaryLiteral *E) {
10772   return E;
10773 }
10774 
10775 template<typename Derived>
10776 ExprResult
10777 TreeTransform<Derived>::TransformStringLiteral(StringLiteral *E) {
10778   return E;
10779 }
10780 
10781 template<typename Derived>
10782 ExprResult
10783 TreeTransform<Derived>::TransformCharacterLiteral(CharacterLiteral *E) {
10784   return E;
10785 }
10786 
10787 template<typename Derived>
10788 ExprResult
10789 TreeTransform<Derived>::TransformUserDefinedLiteral(UserDefinedLiteral *E) {
10790   return getDerived().TransformCallExpr(E);
10791 }
10792 
10793 template<typename Derived>
10794 ExprResult
10795 TreeTransform<Derived>::TransformGenericSelectionExpr(GenericSelectionExpr *E) {
10796   ExprResult ControllingExpr =
10797     getDerived().TransformExpr(E->getControllingExpr());
10798   if (ControllingExpr.isInvalid())
10799     return ExprError();
10800 
10801   SmallVector<Expr *, 4> AssocExprs;
10802   SmallVector<TypeSourceInfo *, 4> AssocTypes;
10803   for (const GenericSelectionExpr::Association Assoc : E->associations()) {
10804     TypeSourceInfo *TSI = Assoc.getTypeSourceInfo();
10805     if (TSI) {
10806       TypeSourceInfo *AssocType = getDerived().TransformType(TSI);
10807       if (!AssocType)
10808         return ExprError();
10809       AssocTypes.push_back(AssocType);
10810     } else {
10811       AssocTypes.push_back(nullptr);
10812     }
10813 
10814     ExprResult AssocExpr =
10815         getDerived().TransformExpr(Assoc.getAssociationExpr());
10816     if (AssocExpr.isInvalid())
10817       return ExprError();
10818     AssocExprs.push_back(AssocExpr.get());
10819   }
10820 
10821   return getDerived().RebuildGenericSelectionExpr(E->getGenericLoc(),
10822                                                   E->getDefaultLoc(),
10823                                                   E->getRParenLoc(),
10824                                                   ControllingExpr.get(),
10825                                                   AssocTypes,
10826                                                   AssocExprs);
10827 }
10828 
10829 template<typename Derived>
10830 ExprResult
10831 TreeTransform<Derived>::TransformParenExpr(ParenExpr *E) {
10832   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
10833   if (SubExpr.isInvalid())
10834     return ExprError();
10835 
10836   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
10837     return E;
10838 
10839   return getDerived().RebuildParenExpr(SubExpr.get(), E->getLParen(),
10840                                        E->getRParen());
10841 }
10842 
10843 /// The operand of a unary address-of operator has special rules: it's
10844 /// allowed to refer to a non-static member of a class even if there's no 'this'
10845 /// object available.
10846 template<typename Derived>
10847 ExprResult
10848 TreeTransform<Derived>::TransformAddressOfOperand(Expr *E) {
10849   if (DependentScopeDeclRefExpr *DRE = dyn_cast<DependentScopeDeclRefExpr>(E))
10850     return getDerived().TransformDependentScopeDeclRefExpr(DRE, true, nullptr);
10851   else
10852     return getDerived().TransformExpr(E);
10853 }
10854 
10855 template<typename Derived>
10856 ExprResult
10857 TreeTransform<Derived>::TransformUnaryOperator(UnaryOperator *E) {
10858   ExprResult SubExpr;
10859   if (E->getOpcode() == UO_AddrOf)
10860     SubExpr = TransformAddressOfOperand(E->getSubExpr());
10861   else
10862     SubExpr = TransformExpr(E->getSubExpr());
10863   if (SubExpr.isInvalid())
10864     return ExprError();
10865 
10866   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
10867     return E;
10868 
10869   return getDerived().RebuildUnaryOperator(E->getOperatorLoc(),
10870                                            E->getOpcode(),
10871                                            SubExpr.get());
10872 }
10873 
10874 template<typename Derived>
10875 ExprResult
10876 TreeTransform<Derived>::TransformOffsetOfExpr(OffsetOfExpr *E) {
10877   // Transform the type.
10878   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
10879   if (!Type)
10880     return ExprError();
10881 
10882   // Transform all of the components into components similar to what the
10883   // parser uses.
10884   // FIXME: It would be slightly more efficient in the non-dependent case to
10885   // just map FieldDecls, rather than requiring the rebuilder to look for
10886   // the fields again. However, __builtin_offsetof is rare enough in
10887   // template code that we don't care.
10888   bool ExprChanged = false;
10889   typedef Sema::OffsetOfComponent Component;
10890   SmallVector<Component, 4> Components;
10891   for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
10892     const OffsetOfNode &ON = E->getComponent(I);
10893     Component Comp;
10894     Comp.isBrackets = true;
10895     Comp.LocStart = ON.getSourceRange().getBegin();
10896     Comp.LocEnd = ON.getSourceRange().getEnd();
10897     switch (ON.getKind()) {
10898     case OffsetOfNode::Array: {
10899       Expr *FromIndex = E->getIndexExpr(ON.getArrayExprIndex());
10900       ExprResult Index = getDerived().TransformExpr(FromIndex);
10901       if (Index.isInvalid())
10902         return ExprError();
10903 
10904       ExprChanged = ExprChanged || Index.get() != FromIndex;
10905       Comp.isBrackets = true;
10906       Comp.U.E = Index.get();
10907       break;
10908     }
10909 
10910     case OffsetOfNode::Field:
10911     case OffsetOfNode::Identifier:
10912       Comp.isBrackets = false;
10913       Comp.U.IdentInfo = ON.getFieldName();
10914       if (!Comp.U.IdentInfo)
10915         continue;
10916 
10917       break;
10918 
10919     case OffsetOfNode::Base:
10920       // Will be recomputed during the rebuild.
10921       continue;
10922     }
10923 
10924     Components.push_back(Comp);
10925   }
10926 
10927   // If nothing changed, retain the existing expression.
10928   if (!getDerived().AlwaysRebuild() &&
10929       Type == E->getTypeSourceInfo() &&
10930       !ExprChanged)
10931     return E;
10932 
10933   // Build a new offsetof expression.
10934   return getDerived().RebuildOffsetOfExpr(E->getOperatorLoc(), Type,
10935                                           Components, E->getRParenLoc());
10936 }
10937 
10938 template<typename Derived>
10939 ExprResult
10940 TreeTransform<Derived>::TransformOpaqueValueExpr(OpaqueValueExpr *E) {
10941   assert((!E->getSourceExpr() || getDerived().AlreadyTransformed(E->getType())) &&
10942          "opaque value expression requires transformation");
10943   return E;
10944 }
10945 
10946 template<typename Derived>
10947 ExprResult
10948 TreeTransform<Derived>::TransformTypoExpr(TypoExpr *E) {
10949   return E;
10950 }
10951 
10952 template <typename Derived>
10953 ExprResult TreeTransform<Derived>::TransformRecoveryExpr(RecoveryExpr *E) {
10954   llvm::SmallVector<Expr *, 8> Children;
10955   bool Changed = false;
10956   for (Expr *C : E->subExpressions()) {
10957     ExprResult NewC = getDerived().TransformExpr(C);
10958     if (NewC.isInvalid())
10959       return ExprError();
10960     Children.push_back(NewC.get());
10961 
10962     Changed |= NewC.get() != C;
10963   }
10964   if (!getDerived().AlwaysRebuild() && !Changed)
10965     return E;
10966   return getDerived().RebuildRecoveryExpr(E->getBeginLoc(), E->getEndLoc(),
10967                                           Children, E->getType());
10968 }
10969 
10970 template<typename Derived>
10971 ExprResult
10972 TreeTransform<Derived>::TransformPseudoObjectExpr(PseudoObjectExpr *E) {
10973   // Rebuild the syntactic form.  The original syntactic form has
10974   // opaque-value expressions in it, so strip those away and rebuild
10975   // the result.  This is a really awful way of doing this, but the
10976   // better solution (rebuilding the semantic expressions and
10977   // rebinding OVEs as necessary) doesn't work; we'd need
10978   // TreeTransform to not strip away implicit conversions.
10979   Expr *newSyntacticForm = SemaRef.recreateSyntacticForm(E);
10980   ExprResult result = getDerived().TransformExpr(newSyntacticForm);
10981   if (result.isInvalid()) return ExprError();
10982 
10983   // If that gives us a pseudo-object result back, the pseudo-object
10984   // expression must have been an lvalue-to-rvalue conversion which we
10985   // should reapply.
10986   if (result.get()->hasPlaceholderType(BuiltinType::PseudoObject))
10987     result = SemaRef.checkPseudoObjectRValue(result.get());
10988 
10989   return result;
10990 }
10991 
10992 template<typename Derived>
10993 ExprResult
10994 TreeTransform<Derived>::TransformUnaryExprOrTypeTraitExpr(
10995                                                 UnaryExprOrTypeTraitExpr *E) {
10996   if (E->isArgumentType()) {
10997     TypeSourceInfo *OldT = E->getArgumentTypeInfo();
10998 
10999     TypeSourceInfo *NewT = getDerived().TransformType(OldT);
11000     if (!NewT)
11001       return ExprError();
11002 
11003     if (!getDerived().AlwaysRebuild() && OldT == NewT)
11004       return E;
11005 
11006     return getDerived().RebuildUnaryExprOrTypeTrait(NewT, E->getOperatorLoc(),
11007                                                     E->getKind(),
11008                                                     E->getSourceRange());
11009   }
11010 
11011   // C++0x [expr.sizeof]p1:
11012   //   The operand is either an expression, which is an unevaluated operand
11013   //   [...]
11014   EnterExpressionEvaluationContext Unevaluated(
11015       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
11016       Sema::ReuseLambdaContextDecl);
11017 
11018   // Try to recover if we have something like sizeof(T::X) where X is a type.
11019   // Notably, there must be *exactly* one set of parens if X is a type.
11020   TypeSourceInfo *RecoveryTSI = nullptr;
11021   ExprResult SubExpr;
11022   auto *PE = dyn_cast<ParenExpr>(E->getArgumentExpr());
11023   if (auto *DRE =
11024           PE ? dyn_cast<DependentScopeDeclRefExpr>(PE->getSubExpr()) : nullptr)
11025     SubExpr = getDerived().TransformParenDependentScopeDeclRefExpr(
11026         PE, DRE, false, &RecoveryTSI);
11027   else
11028     SubExpr = getDerived().TransformExpr(E->getArgumentExpr());
11029 
11030   if (RecoveryTSI) {
11031     return getDerived().RebuildUnaryExprOrTypeTrait(
11032         RecoveryTSI, E->getOperatorLoc(), E->getKind(), E->getSourceRange());
11033   } else if (SubExpr.isInvalid())
11034     return ExprError();
11035 
11036   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getArgumentExpr())
11037     return E;
11038 
11039   return getDerived().RebuildUnaryExprOrTypeTrait(SubExpr.get(),
11040                                                   E->getOperatorLoc(),
11041                                                   E->getKind(),
11042                                                   E->getSourceRange());
11043 }
11044 
11045 template<typename Derived>
11046 ExprResult
11047 TreeTransform<Derived>::TransformArraySubscriptExpr(ArraySubscriptExpr *E) {
11048   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
11049   if (LHS.isInvalid())
11050     return ExprError();
11051 
11052   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
11053   if (RHS.isInvalid())
11054     return ExprError();
11055 
11056 
11057   if (!getDerived().AlwaysRebuild() &&
11058       LHS.get() == E->getLHS() &&
11059       RHS.get() == E->getRHS())
11060     return E;
11061 
11062   return getDerived().RebuildArraySubscriptExpr(
11063       LHS.get(),
11064       /*FIXME:*/ E->getLHS()->getBeginLoc(), RHS.get(), E->getRBracketLoc());
11065 }
11066 
11067 template <typename Derived>
11068 ExprResult
11069 TreeTransform<Derived>::TransformMatrixSubscriptExpr(MatrixSubscriptExpr *E) {
11070   ExprResult Base = getDerived().TransformExpr(E->getBase());
11071   if (Base.isInvalid())
11072     return ExprError();
11073 
11074   ExprResult RowIdx = getDerived().TransformExpr(E->getRowIdx());
11075   if (RowIdx.isInvalid())
11076     return ExprError();
11077 
11078   ExprResult ColumnIdx = getDerived().TransformExpr(E->getColumnIdx());
11079   if (ColumnIdx.isInvalid())
11080     return ExprError();
11081 
11082   if (!getDerived().AlwaysRebuild() && Base.get() == E->getBase() &&
11083       RowIdx.get() == E->getRowIdx() && ColumnIdx.get() == E->getColumnIdx())
11084     return E;
11085 
11086   return getDerived().RebuildMatrixSubscriptExpr(
11087       Base.get(), RowIdx.get(), ColumnIdx.get(), E->getRBracketLoc());
11088 }
11089 
11090 template <typename Derived>
11091 ExprResult
11092 TreeTransform<Derived>::TransformOMPArraySectionExpr(OMPArraySectionExpr *E) {
11093   ExprResult Base = getDerived().TransformExpr(E->getBase());
11094   if (Base.isInvalid())
11095     return ExprError();
11096 
11097   ExprResult LowerBound;
11098   if (E->getLowerBound()) {
11099     LowerBound = getDerived().TransformExpr(E->getLowerBound());
11100     if (LowerBound.isInvalid())
11101       return ExprError();
11102   }
11103 
11104   ExprResult Length;
11105   if (E->getLength()) {
11106     Length = getDerived().TransformExpr(E->getLength());
11107     if (Length.isInvalid())
11108       return ExprError();
11109   }
11110 
11111   ExprResult Stride;
11112   if (Expr *Str = E->getStride()) {
11113     Stride = getDerived().TransformExpr(Str);
11114     if (Stride.isInvalid())
11115       return ExprError();
11116   }
11117 
11118   if (!getDerived().AlwaysRebuild() && Base.get() == E->getBase() &&
11119       LowerBound.get() == E->getLowerBound() && Length.get() == E->getLength())
11120     return E;
11121 
11122   return getDerived().RebuildOMPArraySectionExpr(
11123       Base.get(), E->getBase()->getEndLoc(), LowerBound.get(),
11124       E->getColonLocFirst(), E->getColonLocSecond(), Length.get(), Stride.get(),
11125       E->getRBracketLoc());
11126 }
11127 
11128 template <typename Derived>
11129 ExprResult
11130 TreeTransform<Derived>::TransformOMPArrayShapingExpr(OMPArrayShapingExpr *E) {
11131   ExprResult Base = getDerived().TransformExpr(E->getBase());
11132   if (Base.isInvalid())
11133     return ExprError();
11134 
11135   SmallVector<Expr *, 4> Dims;
11136   bool ErrorFound = false;
11137   for (Expr *Dim : E->getDimensions()) {
11138     ExprResult DimRes = getDerived().TransformExpr(Dim);
11139     if (DimRes.isInvalid()) {
11140       ErrorFound = true;
11141       continue;
11142     }
11143     Dims.push_back(DimRes.get());
11144   }
11145 
11146   if (ErrorFound)
11147     return ExprError();
11148   return getDerived().RebuildOMPArrayShapingExpr(Base.get(), E->getLParenLoc(),
11149                                                  E->getRParenLoc(), Dims,
11150                                                  E->getBracketsRanges());
11151 }
11152 
11153 template <typename Derived>
11154 ExprResult
11155 TreeTransform<Derived>::TransformOMPIteratorExpr(OMPIteratorExpr *E) {
11156   unsigned NumIterators = E->numOfIterators();
11157   SmallVector<Sema::OMPIteratorData, 4> Data(NumIterators);
11158 
11159   bool ErrorFound = false;
11160   bool NeedToRebuild = getDerived().AlwaysRebuild();
11161   for (unsigned I = 0; I < NumIterators; ++I) {
11162     auto *D = cast<VarDecl>(E->getIteratorDecl(I));
11163     Data[I].DeclIdent = D->getIdentifier();
11164     Data[I].DeclIdentLoc = D->getLocation();
11165     if (D->getLocation() == D->getBeginLoc()) {
11166       assert(SemaRef.Context.hasSameType(D->getType(), SemaRef.Context.IntTy) &&
11167              "Implicit type must be int.");
11168     } else {
11169       TypeSourceInfo *TSI = getDerived().TransformType(D->getTypeSourceInfo());
11170       QualType DeclTy = getDerived().TransformType(D->getType());
11171       Data[I].Type = SemaRef.CreateParsedType(DeclTy, TSI);
11172     }
11173     OMPIteratorExpr::IteratorRange Range = E->getIteratorRange(I);
11174     ExprResult Begin = getDerived().TransformExpr(Range.Begin);
11175     ExprResult End = getDerived().TransformExpr(Range.End);
11176     ExprResult Step = getDerived().TransformExpr(Range.Step);
11177     ErrorFound = ErrorFound ||
11178                  !(!D->getTypeSourceInfo() || (Data[I].Type.getAsOpaquePtr() &&
11179                                                !Data[I].Type.get().isNull())) ||
11180                  Begin.isInvalid() || End.isInvalid() || Step.isInvalid();
11181     if (ErrorFound)
11182       continue;
11183     Data[I].Range.Begin = Begin.get();
11184     Data[I].Range.End = End.get();
11185     Data[I].Range.Step = Step.get();
11186     Data[I].AssignLoc = E->getAssignLoc(I);
11187     Data[I].ColonLoc = E->getColonLoc(I);
11188     Data[I].SecColonLoc = E->getSecondColonLoc(I);
11189     NeedToRebuild =
11190         NeedToRebuild ||
11191         (D->getTypeSourceInfo() && Data[I].Type.get().getTypePtrOrNull() !=
11192                                        D->getType().getTypePtrOrNull()) ||
11193         Range.Begin != Data[I].Range.Begin || Range.End != Data[I].Range.End ||
11194         Range.Step != Data[I].Range.Step;
11195   }
11196   if (ErrorFound)
11197     return ExprError();
11198   if (!NeedToRebuild)
11199     return E;
11200 
11201   ExprResult Res = getDerived().RebuildOMPIteratorExpr(
11202       E->getIteratorKwLoc(), E->getLParenLoc(), E->getRParenLoc(), Data);
11203   if (!Res.isUsable())
11204     return Res;
11205   auto *IE = cast<OMPIteratorExpr>(Res.get());
11206   for (unsigned I = 0; I < NumIterators; ++I)
11207     getDerived().transformedLocalDecl(E->getIteratorDecl(I),
11208                                       IE->getIteratorDecl(I));
11209   return Res;
11210 }
11211 
11212 template<typename Derived>
11213 ExprResult
11214 TreeTransform<Derived>::TransformCallExpr(CallExpr *E) {
11215   // Transform the callee.
11216   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
11217   if (Callee.isInvalid())
11218     return ExprError();
11219 
11220   // Transform arguments.
11221   bool ArgChanged = false;
11222   SmallVector<Expr*, 8> Args;
11223   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
11224                                   &ArgChanged))
11225     return ExprError();
11226 
11227   if (!getDerived().AlwaysRebuild() &&
11228       Callee.get() == E->getCallee() &&
11229       !ArgChanged)
11230     return SemaRef.MaybeBindToTemporary(E);
11231 
11232   // FIXME: Wrong source location information for the '('.
11233   SourceLocation FakeLParenLoc
11234     = ((Expr *)Callee.get())->getSourceRange().getBegin();
11235 
11236   Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
11237   if (E->hasStoredFPFeatures()) {
11238     FPOptionsOverride NewOverrides = E->getFPFeatures();
11239     getSema().CurFPFeatures =
11240         NewOverrides.applyOverrides(getSema().getLangOpts());
11241     getSema().FpPragmaStack.CurrentValue = NewOverrides;
11242   }
11243 
11244   return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
11245                                       Args,
11246                                       E->getRParenLoc());
11247 }
11248 
11249 template<typename Derived>
11250 ExprResult
11251 TreeTransform<Derived>::TransformMemberExpr(MemberExpr *E) {
11252   ExprResult Base = getDerived().TransformExpr(E->getBase());
11253   if (Base.isInvalid())
11254     return ExprError();
11255 
11256   NestedNameSpecifierLoc QualifierLoc;
11257   if (E->hasQualifier()) {
11258     QualifierLoc
11259       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
11260 
11261     if (!QualifierLoc)
11262       return ExprError();
11263   }
11264   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
11265 
11266   ValueDecl *Member
11267     = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getMemberLoc(),
11268                                                          E->getMemberDecl()));
11269   if (!Member)
11270     return ExprError();
11271 
11272   NamedDecl *FoundDecl = E->getFoundDecl();
11273   if (FoundDecl == E->getMemberDecl()) {
11274     FoundDecl = Member;
11275   } else {
11276     FoundDecl = cast_or_null<NamedDecl>(
11277                    getDerived().TransformDecl(E->getMemberLoc(), FoundDecl));
11278     if (!FoundDecl)
11279       return ExprError();
11280   }
11281 
11282   if (!getDerived().AlwaysRebuild() &&
11283       Base.get() == E->getBase() &&
11284       QualifierLoc == E->getQualifierLoc() &&
11285       Member == E->getMemberDecl() &&
11286       FoundDecl == E->getFoundDecl() &&
11287       !E->hasExplicitTemplateArgs()) {
11288 
11289     // Skip for member expression of (this->f), rebuilt thisi->f is needed
11290     // for Openmp where the field need to be privatizized in the case.
11291     if (!(isa<CXXThisExpr>(E->getBase()) &&
11292           getSema().isOpenMPRebuildMemberExpr(cast<ValueDecl>(Member)))) {
11293       // Mark it referenced in the new context regardless.
11294       // FIXME: this is a bit instantiation-specific.
11295       SemaRef.MarkMemberReferenced(E);
11296       return E;
11297     }
11298   }
11299 
11300   TemplateArgumentListInfo TransArgs;
11301   if (E->hasExplicitTemplateArgs()) {
11302     TransArgs.setLAngleLoc(E->getLAngleLoc());
11303     TransArgs.setRAngleLoc(E->getRAngleLoc());
11304     if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
11305                                                 E->getNumTemplateArgs(),
11306                                                 TransArgs))
11307       return ExprError();
11308   }
11309 
11310   // FIXME: Bogus source location for the operator
11311   SourceLocation FakeOperatorLoc =
11312       SemaRef.getLocForEndOfToken(E->getBase()->getSourceRange().getEnd());
11313 
11314   // FIXME: to do this check properly, we will need to preserve the
11315   // first-qualifier-in-scope here, just in case we had a dependent
11316   // base (and therefore couldn't do the check) and a
11317   // nested-name-qualifier (and therefore could do the lookup).
11318   NamedDecl *FirstQualifierInScope = nullptr;
11319   DeclarationNameInfo MemberNameInfo = E->getMemberNameInfo();
11320   if (MemberNameInfo.getName()) {
11321     MemberNameInfo = getDerived().TransformDeclarationNameInfo(MemberNameInfo);
11322     if (!MemberNameInfo.getName())
11323       return ExprError();
11324   }
11325 
11326   return getDerived().RebuildMemberExpr(Base.get(), FakeOperatorLoc,
11327                                         E->isArrow(),
11328                                         QualifierLoc,
11329                                         TemplateKWLoc,
11330                                         MemberNameInfo,
11331                                         Member,
11332                                         FoundDecl,
11333                                         (E->hasExplicitTemplateArgs()
11334                                            ? &TransArgs : nullptr),
11335                                         FirstQualifierInScope);
11336 }
11337 
11338 template<typename Derived>
11339 ExprResult
11340 TreeTransform<Derived>::TransformBinaryOperator(BinaryOperator *E) {
11341   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
11342   if (LHS.isInvalid())
11343     return ExprError();
11344 
11345   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
11346   if (RHS.isInvalid())
11347     return ExprError();
11348 
11349   if (!getDerived().AlwaysRebuild() &&
11350       LHS.get() == E->getLHS() &&
11351       RHS.get() == E->getRHS())
11352     return E;
11353 
11354   if (E->isCompoundAssignmentOp())
11355     // FPFeatures has already been established from trailing storage
11356     return getDerived().RebuildBinaryOperator(
11357         E->getOperatorLoc(), E->getOpcode(), LHS.get(), RHS.get());
11358   Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
11359   FPOptionsOverride NewOverrides(E->getFPFeatures());
11360   getSema().CurFPFeatures =
11361       NewOverrides.applyOverrides(getSema().getLangOpts());
11362   getSema().FpPragmaStack.CurrentValue = NewOverrides;
11363   return getDerived().RebuildBinaryOperator(E->getOperatorLoc(), E->getOpcode(),
11364                                             LHS.get(), RHS.get());
11365 }
11366 
11367 template <typename Derived>
11368 ExprResult TreeTransform<Derived>::TransformCXXRewrittenBinaryOperator(
11369     CXXRewrittenBinaryOperator *E) {
11370   CXXRewrittenBinaryOperator::DecomposedForm Decomp = E->getDecomposedForm();
11371 
11372   ExprResult LHS = getDerived().TransformExpr(const_cast<Expr*>(Decomp.LHS));
11373   if (LHS.isInvalid())
11374     return ExprError();
11375 
11376   ExprResult RHS = getDerived().TransformExpr(const_cast<Expr*>(Decomp.RHS));
11377   if (RHS.isInvalid())
11378     return ExprError();
11379 
11380   // Extract the already-resolved callee declarations so that we can restrict
11381   // ourselves to using them as the unqualified lookup results when rebuilding.
11382   UnresolvedSet<2> UnqualLookups;
11383   bool ChangedAnyLookups = false;
11384   Expr *PossibleBinOps[] = {E->getSemanticForm(),
11385                             const_cast<Expr *>(Decomp.InnerBinOp)};
11386   for (Expr *PossibleBinOp : PossibleBinOps) {
11387     auto *Op = dyn_cast<CXXOperatorCallExpr>(PossibleBinOp->IgnoreImplicit());
11388     if (!Op)
11389       continue;
11390     auto *Callee = dyn_cast<DeclRefExpr>(Op->getCallee()->IgnoreImplicit());
11391     if (!Callee || isa<CXXMethodDecl>(Callee->getDecl()))
11392       continue;
11393 
11394     // Transform the callee in case we built a call to a local extern
11395     // declaration.
11396     NamedDecl *Found = cast_or_null<NamedDecl>(getDerived().TransformDecl(
11397         E->getOperatorLoc(), Callee->getFoundDecl()));
11398     if (!Found)
11399       return ExprError();
11400     if (Found != Callee->getFoundDecl())
11401       ChangedAnyLookups = true;
11402     UnqualLookups.addDecl(Found);
11403   }
11404 
11405   if (!getDerived().AlwaysRebuild() && !ChangedAnyLookups &&
11406       LHS.get() == Decomp.LHS && RHS.get() == Decomp.RHS) {
11407     // Mark all functions used in the rewrite as referenced. Note that when
11408     // a < b is rewritten to (a <=> b) < 0, both the <=> and the < might be
11409     // function calls, and/or there might be a user-defined conversion sequence
11410     // applied to the operands of the <.
11411     // FIXME: this is a bit instantiation-specific.
11412     const Expr *StopAt[] = {Decomp.LHS, Decomp.RHS};
11413     SemaRef.MarkDeclarationsReferencedInExpr(E, false, StopAt);
11414     return E;
11415   }
11416 
11417   return getDerived().RebuildCXXRewrittenBinaryOperator(
11418       E->getOperatorLoc(), Decomp.Opcode, UnqualLookups, LHS.get(), RHS.get());
11419 }
11420 
11421 template<typename Derived>
11422 ExprResult
11423 TreeTransform<Derived>::TransformCompoundAssignOperator(
11424                                                       CompoundAssignOperator *E) {
11425   Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
11426   FPOptionsOverride NewOverrides(E->getFPFeatures());
11427   getSema().CurFPFeatures =
11428       NewOverrides.applyOverrides(getSema().getLangOpts());
11429   getSema().FpPragmaStack.CurrentValue = NewOverrides;
11430   return getDerived().TransformBinaryOperator(E);
11431 }
11432 
11433 template<typename Derived>
11434 ExprResult TreeTransform<Derived>::
11435 TransformBinaryConditionalOperator(BinaryConditionalOperator *e) {
11436   // Just rebuild the common and RHS expressions and see whether we
11437   // get any changes.
11438 
11439   ExprResult commonExpr = getDerived().TransformExpr(e->getCommon());
11440   if (commonExpr.isInvalid())
11441     return ExprError();
11442 
11443   ExprResult rhs = getDerived().TransformExpr(e->getFalseExpr());
11444   if (rhs.isInvalid())
11445     return ExprError();
11446 
11447   if (!getDerived().AlwaysRebuild() &&
11448       commonExpr.get() == e->getCommon() &&
11449       rhs.get() == e->getFalseExpr())
11450     return e;
11451 
11452   return getDerived().RebuildConditionalOperator(commonExpr.get(),
11453                                                  e->getQuestionLoc(),
11454                                                  nullptr,
11455                                                  e->getColonLoc(),
11456                                                  rhs.get());
11457 }
11458 
11459 template<typename Derived>
11460 ExprResult
11461 TreeTransform<Derived>::TransformConditionalOperator(ConditionalOperator *E) {
11462   ExprResult Cond = getDerived().TransformExpr(E->getCond());
11463   if (Cond.isInvalid())
11464     return ExprError();
11465 
11466   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
11467   if (LHS.isInvalid())
11468     return ExprError();
11469 
11470   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
11471   if (RHS.isInvalid())
11472     return ExprError();
11473 
11474   if (!getDerived().AlwaysRebuild() &&
11475       Cond.get() == E->getCond() &&
11476       LHS.get() == E->getLHS() &&
11477       RHS.get() == E->getRHS())
11478     return E;
11479 
11480   return getDerived().RebuildConditionalOperator(Cond.get(),
11481                                                  E->getQuestionLoc(),
11482                                                  LHS.get(),
11483                                                  E->getColonLoc(),
11484                                                  RHS.get());
11485 }
11486 
11487 template<typename Derived>
11488 ExprResult
11489 TreeTransform<Derived>::TransformImplicitCastExpr(ImplicitCastExpr *E) {
11490   // Implicit casts are eliminated during transformation, since they
11491   // will be recomputed by semantic analysis after transformation.
11492   return getDerived().TransformExpr(E->getSubExprAsWritten());
11493 }
11494 
11495 template<typename Derived>
11496 ExprResult
11497 TreeTransform<Derived>::TransformCStyleCastExpr(CStyleCastExpr *E) {
11498   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
11499   if (!Type)
11500     return ExprError();
11501 
11502   ExprResult SubExpr
11503     = getDerived().TransformExpr(E->getSubExprAsWritten());
11504   if (SubExpr.isInvalid())
11505     return ExprError();
11506 
11507   if (!getDerived().AlwaysRebuild() &&
11508       Type == E->getTypeInfoAsWritten() &&
11509       SubExpr.get() == E->getSubExpr())
11510     return E;
11511 
11512   return getDerived().RebuildCStyleCastExpr(E->getLParenLoc(),
11513                                             Type,
11514                                             E->getRParenLoc(),
11515                                             SubExpr.get());
11516 }
11517 
11518 template<typename Derived>
11519 ExprResult
11520 TreeTransform<Derived>::TransformCompoundLiteralExpr(CompoundLiteralExpr *E) {
11521   TypeSourceInfo *OldT = E->getTypeSourceInfo();
11522   TypeSourceInfo *NewT = getDerived().TransformType(OldT);
11523   if (!NewT)
11524     return ExprError();
11525 
11526   ExprResult Init = getDerived().TransformExpr(E->getInitializer());
11527   if (Init.isInvalid())
11528     return ExprError();
11529 
11530   if (!getDerived().AlwaysRebuild() &&
11531       OldT == NewT &&
11532       Init.get() == E->getInitializer())
11533     return SemaRef.MaybeBindToTemporary(E);
11534 
11535   // Note: the expression type doesn't necessarily match the
11536   // type-as-written, but that's okay, because it should always be
11537   // derivable from the initializer.
11538 
11539   return getDerived().RebuildCompoundLiteralExpr(
11540       E->getLParenLoc(), NewT,
11541       /*FIXME:*/ E->getInitializer()->getEndLoc(), Init.get());
11542 }
11543 
11544 template<typename Derived>
11545 ExprResult
11546 TreeTransform<Derived>::TransformExtVectorElementExpr(ExtVectorElementExpr *E) {
11547   ExprResult Base = getDerived().TransformExpr(E->getBase());
11548   if (Base.isInvalid())
11549     return ExprError();
11550 
11551   if (!getDerived().AlwaysRebuild() &&
11552       Base.get() == E->getBase())
11553     return E;
11554 
11555   // FIXME: Bad source location
11556   SourceLocation FakeOperatorLoc =
11557       SemaRef.getLocForEndOfToken(E->getBase()->getEndLoc());
11558   return getDerived().RebuildExtVectorElementExpr(
11559       Base.get(), FakeOperatorLoc, E->isArrow(), E->getAccessorLoc(),
11560       E->getAccessor());
11561 }
11562 
11563 template<typename Derived>
11564 ExprResult
11565 TreeTransform<Derived>::TransformInitListExpr(InitListExpr *E) {
11566   if (InitListExpr *Syntactic = E->getSyntacticForm())
11567     E = Syntactic;
11568 
11569   bool InitChanged = false;
11570 
11571   EnterExpressionEvaluationContext Context(
11572       getSema(), EnterExpressionEvaluationContext::InitList);
11573 
11574   SmallVector<Expr*, 4> Inits;
11575   if (getDerived().TransformExprs(E->getInits(), E->getNumInits(), false,
11576                                   Inits, &InitChanged))
11577     return ExprError();
11578 
11579   if (!getDerived().AlwaysRebuild() && !InitChanged) {
11580     // FIXME: Attempt to reuse the existing syntactic form of the InitListExpr
11581     // in some cases. We can't reuse it in general, because the syntactic and
11582     // semantic forms are linked, and we can't know that semantic form will
11583     // match even if the syntactic form does.
11584   }
11585 
11586   return getDerived().RebuildInitList(E->getLBraceLoc(), Inits,
11587                                       E->getRBraceLoc());
11588 }
11589 
11590 template<typename Derived>
11591 ExprResult
11592 TreeTransform<Derived>::TransformDesignatedInitExpr(DesignatedInitExpr *E) {
11593   Designation Desig;
11594 
11595   // transform the initializer value
11596   ExprResult Init = getDerived().TransformExpr(E->getInit());
11597   if (Init.isInvalid())
11598     return ExprError();
11599 
11600   // transform the designators.
11601   SmallVector<Expr*, 4> ArrayExprs;
11602   bool ExprChanged = false;
11603   for (const DesignatedInitExpr::Designator &D : E->designators()) {
11604     if (D.isFieldDesignator()) {
11605       Desig.AddDesignator(Designator::getField(D.getFieldName(),
11606                                                D.getDotLoc(),
11607                                                D.getFieldLoc()));
11608       if (D.getField()) {
11609         FieldDecl *Field = cast_or_null<FieldDecl>(
11610             getDerived().TransformDecl(D.getFieldLoc(), D.getField()));
11611         if (Field != D.getField())
11612           // Rebuild the expression when the transformed FieldDecl is
11613           // different to the already assigned FieldDecl.
11614           ExprChanged = true;
11615       } else {
11616         // Ensure that the designator expression is rebuilt when there isn't
11617         // a resolved FieldDecl in the designator as we don't want to assign
11618         // a FieldDecl to a pattern designator that will be instantiated again.
11619         ExprChanged = true;
11620       }
11621       continue;
11622     }
11623 
11624     if (D.isArrayDesignator()) {
11625       ExprResult Index = getDerived().TransformExpr(E->getArrayIndex(D));
11626       if (Index.isInvalid())
11627         return ExprError();
11628 
11629       Desig.AddDesignator(
11630           Designator::getArray(Index.get(), D.getLBracketLoc()));
11631 
11632       ExprChanged = ExprChanged || Init.get() != E->getArrayIndex(D);
11633       ArrayExprs.push_back(Index.get());
11634       continue;
11635     }
11636 
11637     assert(D.isArrayRangeDesignator() && "New kind of designator?");
11638     ExprResult Start
11639       = getDerived().TransformExpr(E->getArrayRangeStart(D));
11640     if (Start.isInvalid())
11641       return ExprError();
11642 
11643     ExprResult End = getDerived().TransformExpr(E->getArrayRangeEnd(D));
11644     if (End.isInvalid())
11645       return ExprError();
11646 
11647     Desig.AddDesignator(Designator::getArrayRange(Start.get(),
11648                                                   End.get(),
11649                                                   D.getLBracketLoc(),
11650                                                   D.getEllipsisLoc()));
11651 
11652     ExprChanged = ExprChanged || Start.get() != E->getArrayRangeStart(D) ||
11653                   End.get() != E->getArrayRangeEnd(D);
11654 
11655     ArrayExprs.push_back(Start.get());
11656     ArrayExprs.push_back(End.get());
11657   }
11658 
11659   if (!getDerived().AlwaysRebuild() &&
11660       Init.get() == E->getInit() &&
11661       !ExprChanged)
11662     return E;
11663 
11664   return getDerived().RebuildDesignatedInitExpr(Desig, ArrayExprs,
11665                                                 E->getEqualOrColonLoc(),
11666                                                 E->usesGNUSyntax(), Init.get());
11667 }
11668 
11669 // Seems that if TransformInitListExpr() only works on the syntactic form of an
11670 // InitListExpr, then a DesignatedInitUpdateExpr is not encountered.
11671 template<typename Derived>
11672 ExprResult
11673 TreeTransform<Derived>::TransformDesignatedInitUpdateExpr(
11674     DesignatedInitUpdateExpr *E) {
11675   llvm_unreachable("Unexpected DesignatedInitUpdateExpr in syntactic form of "
11676                    "initializer");
11677   return ExprError();
11678 }
11679 
11680 template<typename Derived>
11681 ExprResult
11682 TreeTransform<Derived>::TransformNoInitExpr(
11683     NoInitExpr *E) {
11684   llvm_unreachable("Unexpected NoInitExpr in syntactic form of initializer");
11685   return ExprError();
11686 }
11687 
11688 template<typename Derived>
11689 ExprResult
11690 TreeTransform<Derived>::TransformArrayInitLoopExpr(ArrayInitLoopExpr *E) {
11691   llvm_unreachable("Unexpected ArrayInitLoopExpr outside of initializer");
11692   return ExprError();
11693 }
11694 
11695 template<typename Derived>
11696 ExprResult
11697 TreeTransform<Derived>::TransformArrayInitIndexExpr(ArrayInitIndexExpr *E) {
11698   llvm_unreachable("Unexpected ArrayInitIndexExpr outside of initializer");
11699   return ExprError();
11700 }
11701 
11702 template<typename Derived>
11703 ExprResult
11704 TreeTransform<Derived>::TransformImplicitValueInitExpr(
11705                                                      ImplicitValueInitExpr *E) {
11706   TemporaryBase Rebase(*this, E->getBeginLoc(), DeclarationName());
11707 
11708   // FIXME: Will we ever have proper type location here? Will we actually
11709   // need to transform the type?
11710   QualType T = getDerived().TransformType(E->getType());
11711   if (T.isNull())
11712     return ExprError();
11713 
11714   if (!getDerived().AlwaysRebuild() &&
11715       T == E->getType())
11716     return E;
11717 
11718   return getDerived().RebuildImplicitValueInitExpr(T);
11719 }
11720 
11721 template<typename Derived>
11722 ExprResult
11723 TreeTransform<Derived>::TransformVAArgExpr(VAArgExpr *E) {
11724   TypeSourceInfo *TInfo = getDerived().TransformType(E->getWrittenTypeInfo());
11725   if (!TInfo)
11726     return ExprError();
11727 
11728   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
11729   if (SubExpr.isInvalid())
11730     return ExprError();
11731 
11732   if (!getDerived().AlwaysRebuild() &&
11733       TInfo == E->getWrittenTypeInfo() &&
11734       SubExpr.get() == E->getSubExpr())
11735     return E;
11736 
11737   return getDerived().RebuildVAArgExpr(E->getBuiltinLoc(), SubExpr.get(),
11738                                        TInfo, E->getRParenLoc());
11739 }
11740 
11741 template<typename Derived>
11742 ExprResult
11743 TreeTransform<Derived>::TransformParenListExpr(ParenListExpr *E) {
11744   bool ArgumentChanged = false;
11745   SmallVector<Expr*, 4> Inits;
11746   if (TransformExprs(E->getExprs(), E->getNumExprs(), true, Inits,
11747                      &ArgumentChanged))
11748     return ExprError();
11749 
11750   return getDerived().RebuildParenListExpr(E->getLParenLoc(),
11751                                            Inits,
11752                                            E->getRParenLoc());
11753 }
11754 
11755 /// Transform an address-of-label expression.
11756 ///
11757 /// By default, the transformation of an address-of-label expression always
11758 /// rebuilds the expression, so that the label identifier can be resolved to
11759 /// the corresponding label statement by semantic analysis.
11760 template<typename Derived>
11761 ExprResult
11762 TreeTransform<Derived>::TransformAddrLabelExpr(AddrLabelExpr *E) {
11763   Decl *LD = getDerived().TransformDecl(E->getLabel()->getLocation(),
11764                                         E->getLabel());
11765   if (!LD)
11766     return ExprError();
11767 
11768   return getDerived().RebuildAddrLabelExpr(E->getAmpAmpLoc(), E->getLabelLoc(),
11769                                            cast<LabelDecl>(LD));
11770 }
11771 
11772 template<typename Derived>
11773 ExprResult
11774 TreeTransform<Derived>::TransformStmtExpr(StmtExpr *E) {
11775   SemaRef.ActOnStartStmtExpr();
11776   StmtResult SubStmt
11777     = getDerived().TransformCompoundStmt(E->getSubStmt(), true);
11778   if (SubStmt.isInvalid()) {
11779     SemaRef.ActOnStmtExprError();
11780     return ExprError();
11781   }
11782 
11783   unsigned OldDepth = E->getTemplateDepth();
11784   unsigned NewDepth = getDerived().TransformTemplateDepth(OldDepth);
11785 
11786   if (!getDerived().AlwaysRebuild() && OldDepth == NewDepth &&
11787       SubStmt.get() == E->getSubStmt()) {
11788     // Calling this an 'error' is unintuitive, but it does the right thing.
11789     SemaRef.ActOnStmtExprError();
11790     return SemaRef.MaybeBindToTemporary(E);
11791   }
11792 
11793   return getDerived().RebuildStmtExpr(E->getLParenLoc(), SubStmt.get(),
11794                                       E->getRParenLoc(), NewDepth);
11795 }
11796 
11797 template<typename Derived>
11798 ExprResult
11799 TreeTransform<Derived>::TransformChooseExpr(ChooseExpr *E) {
11800   ExprResult Cond = getDerived().TransformExpr(E->getCond());
11801   if (Cond.isInvalid())
11802     return ExprError();
11803 
11804   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
11805   if (LHS.isInvalid())
11806     return ExprError();
11807 
11808   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
11809   if (RHS.isInvalid())
11810     return ExprError();
11811 
11812   if (!getDerived().AlwaysRebuild() &&
11813       Cond.get() == E->getCond() &&
11814       LHS.get() == E->getLHS() &&
11815       RHS.get() == E->getRHS())
11816     return E;
11817 
11818   return getDerived().RebuildChooseExpr(E->getBuiltinLoc(),
11819                                         Cond.get(), LHS.get(), RHS.get(),
11820                                         E->getRParenLoc());
11821 }
11822 
11823 template<typename Derived>
11824 ExprResult
11825 TreeTransform<Derived>::TransformGNUNullExpr(GNUNullExpr *E) {
11826   return E;
11827 }
11828 
11829 template<typename Derived>
11830 ExprResult
11831 TreeTransform<Derived>::TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11832   switch (E->getOperator()) {
11833   case OO_New:
11834   case OO_Delete:
11835   case OO_Array_New:
11836   case OO_Array_Delete:
11837     llvm_unreachable("new and delete operators cannot use CXXOperatorCallExpr");
11838 
11839   case OO_Subscript:
11840   case OO_Call: {
11841     // This is a call to an object's operator().
11842     assert(E->getNumArgs() >= 1 && "Object call is missing arguments");
11843 
11844     // Transform the object itself.
11845     ExprResult Object = getDerived().TransformExpr(E->getArg(0));
11846     if (Object.isInvalid())
11847       return ExprError();
11848 
11849     // FIXME: Poor location information
11850     SourceLocation FakeLParenLoc = SemaRef.getLocForEndOfToken(
11851         static_cast<Expr *>(Object.get())->getEndLoc());
11852 
11853     // Transform the call arguments.
11854     SmallVector<Expr*, 8> Args;
11855     if (getDerived().TransformExprs(E->getArgs() + 1, E->getNumArgs() - 1, true,
11856                                     Args))
11857       return ExprError();
11858 
11859     if (E->getOperator() == OO_Subscript)
11860       return getDerived().RebuildCxxSubscriptExpr(Object.get(), FakeLParenLoc,
11861                                                   Args, E->getEndLoc());
11862 
11863     return getDerived().RebuildCallExpr(Object.get(), FakeLParenLoc, Args,
11864                                         E->getEndLoc());
11865   }
11866 
11867 #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly)  \
11868   case OO_##Name:                                                              \
11869     break;
11870 
11871 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
11872 #include "clang/Basic/OperatorKinds.def"
11873 
11874   case OO_Conditional:
11875     llvm_unreachable("conditional operator is not actually overloadable");
11876 
11877   case OO_None:
11878   case NUM_OVERLOADED_OPERATORS:
11879     llvm_unreachable("not an overloaded operator?");
11880   }
11881 
11882   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
11883   if (Callee.isInvalid())
11884     return ExprError();
11885 
11886   ExprResult First;
11887   if (E->getOperator() == OO_Amp)
11888     First = getDerived().TransformAddressOfOperand(E->getArg(0));
11889   else
11890     First = getDerived().TransformExpr(E->getArg(0));
11891   if (First.isInvalid())
11892     return ExprError();
11893 
11894   ExprResult Second;
11895   if (E->getNumArgs() == 2) {
11896     Second = getDerived().TransformExpr(E->getArg(1));
11897     if (Second.isInvalid())
11898       return ExprError();
11899   }
11900 
11901   if (!getDerived().AlwaysRebuild() &&
11902       Callee.get() == E->getCallee() &&
11903       First.get() == E->getArg(0) &&
11904       (E->getNumArgs() != 2 || Second.get() == E->getArg(1)))
11905     return SemaRef.MaybeBindToTemporary(E);
11906 
11907   Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
11908   FPOptionsOverride NewOverrides(E->getFPFeatures());
11909   getSema().CurFPFeatures =
11910       NewOverrides.applyOverrides(getSema().getLangOpts());
11911   getSema().FpPragmaStack.CurrentValue = NewOverrides;
11912 
11913   return getDerived().RebuildCXXOperatorCallExpr(E->getOperator(),
11914                                                  E->getOperatorLoc(),
11915                                                  Callee.get(),
11916                                                  First.get(),
11917                                                  Second.get());
11918 }
11919 
11920 template<typename Derived>
11921 ExprResult
11922 TreeTransform<Derived>::TransformCXXMemberCallExpr(CXXMemberCallExpr *E) {
11923   return getDerived().TransformCallExpr(E);
11924 }
11925 
11926 template <typename Derived>
11927 ExprResult TreeTransform<Derived>::TransformSourceLocExpr(SourceLocExpr *E) {
11928   bool NeedRebuildFunc = E->getIdentKind() == SourceLocExpr::Function &&
11929                          getSema().CurContext != E->getParentContext();
11930 
11931   if (!getDerived().AlwaysRebuild() && !NeedRebuildFunc)
11932     return E;
11933 
11934   return getDerived().RebuildSourceLocExpr(E->getIdentKind(), E->getType(),
11935                                            E->getBeginLoc(), E->getEndLoc(),
11936                                            getSema().CurContext);
11937 }
11938 
11939 template<typename Derived>
11940 ExprResult
11941 TreeTransform<Derived>::TransformCUDAKernelCallExpr(CUDAKernelCallExpr *E) {
11942   // Transform the callee.
11943   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
11944   if (Callee.isInvalid())
11945     return ExprError();
11946 
11947   // Transform exec config.
11948   ExprResult EC = getDerived().TransformCallExpr(E->getConfig());
11949   if (EC.isInvalid())
11950     return ExprError();
11951 
11952   // Transform arguments.
11953   bool ArgChanged = false;
11954   SmallVector<Expr*, 8> Args;
11955   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
11956                                   &ArgChanged))
11957     return ExprError();
11958 
11959   if (!getDerived().AlwaysRebuild() &&
11960       Callee.get() == E->getCallee() &&
11961       !ArgChanged)
11962     return SemaRef.MaybeBindToTemporary(E);
11963 
11964   // FIXME: Wrong source location information for the '('.
11965   SourceLocation FakeLParenLoc
11966     = ((Expr *)Callee.get())->getSourceRange().getBegin();
11967   return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
11968                                       Args,
11969                                       E->getRParenLoc(), EC.get());
11970 }
11971 
11972 template<typename Derived>
11973 ExprResult
11974 TreeTransform<Derived>::TransformCXXNamedCastExpr(CXXNamedCastExpr *E) {
11975   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
11976   if (!Type)
11977     return ExprError();
11978 
11979   ExprResult SubExpr
11980     = getDerived().TransformExpr(E->getSubExprAsWritten());
11981   if (SubExpr.isInvalid())
11982     return ExprError();
11983 
11984   if (!getDerived().AlwaysRebuild() &&
11985       Type == E->getTypeInfoAsWritten() &&
11986       SubExpr.get() == E->getSubExpr())
11987     return E;
11988   return getDerived().RebuildCXXNamedCastExpr(
11989       E->getOperatorLoc(), E->getStmtClass(), E->getAngleBrackets().getBegin(),
11990       Type, E->getAngleBrackets().getEnd(),
11991       // FIXME. this should be '(' location
11992       E->getAngleBrackets().getEnd(), SubExpr.get(), E->getRParenLoc());
11993 }
11994 
11995 template<typename Derived>
11996 ExprResult
11997 TreeTransform<Derived>::TransformBuiltinBitCastExpr(BuiltinBitCastExpr *BCE) {
11998   TypeSourceInfo *TSI =
11999       getDerived().TransformType(BCE->getTypeInfoAsWritten());
12000   if (!TSI)
12001     return ExprError();
12002 
12003   ExprResult Sub = getDerived().TransformExpr(BCE->getSubExpr());
12004   if (Sub.isInvalid())
12005     return ExprError();
12006 
12007   return getDerived().RebuildBuiltinBitCastExpr(BCE->getBeginLoc(), TSI,
12008                                                 Sub.get(), BCE->getEndLoc());
12009 }
12010 
12011 template<typename Derived>
12012 ExprResult
12013 TreeTransform<Derived>::TransformCXXStaticCastExpr(CXXStaticCastExpr *E) {
12014   return getDerived().TransformCXXNamedCastExpr(E);
12015 }
12016 
12017 template<typename Derived>
12018 ExprResult
12019 TreeTransform<Derived>::TransformCXXDynamicCastExpr(CXXDynamicCastExpr *E) {
12020   return getDerived().TransformCXXNamedCastExpr(E);
12021 }
12022 
12023 template<typename Derived>
12024 ExprResult
12025 TreeTransform<Derived>::TransformCXXReinterpretCastExpr(
12026                                                       CXXReinterpretCastExpr *E) {
12027   return getDerived().TransformCXXNamedCastExpr(E);
12028 }
12029 
12030 template<typename Derived>
12031 ExprResult
12032 TreeTransform<Derived>::TransformCXXConstCastExpr(CXXConstCastExpr *E) {
12033   return getDerived().TransformCXXNamedCastExpr(E);
12034 }
12035 
12036 template<typename Derived>
12037 ExprResult
12038 TreeTransform<Derived>::TransformCXXAddrspaceCastExpr(CXXAddrspaceCastExpr *E) {
12039   return getDerived().TransformCXXNamedCastExpr(E);
12040 }
12041 
12042 template<typename Derived>
12043 ExprResult
12044 TreeTransform<Derived>::TransformCXXFunctionalCastExpr(
12045                                                      CXXFunctionalCastExpr *E) {
12046   TypeSourceInfo *Type =
12047       getDerived().TransformTypeWithDeducedTST(E->getTypeInfoAsWritten());
12048   if (!Type)
12049     return ExprError();
12050 
12051   ExprResult SubExpr
12052     = getDerived().TransformExpr(E->getSubExprAsWritten());
12053   if (SubExpr.isInvalid())
12054     return ExprError();
12055 
12056   if (!getDerived().AlwaysRebuild() &&
12057       Type == E->getTypeInfoAsWritten() &&
12058       SubExpr.get() == E->getSubExpr())
12059     return E;
12060 
12061   return getDerived().RebuildCXXFunctionalCastExpr(Type,
12062                                                    E->getLParenLoc(),
12063                                                    SubExpr.get(),
12064                                                    E->getRParenLoc(),
12065                                                    E->isListInitialization());
12066 }
12067 
12068 template<typename Derived>
12069 ExprResult
12070 TreeTransform<Derived>::TransformCXXTypeidExpr(CXXTypeidExpr *E) {
12071   if (E->isTypeOperand()) {
12072     TypeSourceInfo *TInfo
12073       = getDerived().TransformType(E->getTypeOperandSourceInfo());
12074     if (!TInfo)
12075       return ExprError();
12076 
12077     if (!getDerived().AlwaysRebuild() &&
12078         TInfo == E->getTypeOperandSourceInfo())
12079       return E;
12080 
12081     return getDerived().RebuildCXXTypeidExpr(E->getType(), E->getBeginLoc(),
12082                                              TInfo, E->getEndLoc());
12083   }
12084 
12085   // Typeid's operand is an unevaluated context, unless it's a polymorphic
12086   // type.  We must not unilaterally enter unevaluated context here, as then
12087   // semantic processing can re-transform an already transformed operand.
12088   Expr *Op = E->getExprOperand();
12089   auto EvalCtx = Sema::ExpressionEvaluationContext::Unevaluated;
12090   if (E->isGLValue())
12091     if (auto *RecordT = Op->getType()->getAs<RecordType>())
12092       if (cast<CXXRecordDecl>(RecordT->getDecl())->isPolymorphic())
12093         EvalCtx = SemaRef.ExprEvalContexts.back().Context;
12094 
12095   EnterExpressionEvaluationContext Unevaluated(SemaRef, EvalCtx,
12096                                                Sema::ReuseLambdaContextDecl);
12097 
12098   ExprResult SubExpr = getDerived().TransformExpr(Op);
12099   if (SubExpr.isInvalid())
12100     return ExprError();
12101 
12102   if (!getDerived().AlwaysRebuild() &&
12103       SubExpr.get() == E->getExprOperand())
12104     return E;
12105 
12106   return getDerived().RebuildCXXTypeidExpr(E->getType(), E->getBeginLoc(),
12107                                            SubExpr.get(), E->getEndLoc());
12108 }
12109 
12110 template<typename Derived>
12111 ExprResult
12112 TreeTransform<Derived>::TransformCXXUuidofExpr(CXXUuidofExpr *E) {
12113   if (E->isTypeOperand()) {
12114     TypeSourceInfo *TInfo
12115       = getDerived().TransformType(E->getTypeOperandSourceInfo());
12116     if (!TInfo)
12117       return ExprError();
12118 
12119     if (!getDerived().AlwaysRebuild() &&
12120         TInfo == E->getTypeOperandSourceInfo())
12121       return E;
12122 
12123     return getDerived().RebuildCXXUuidofExpr(E->getType(), E->getBeginLoc(),
12124                                              TInfo, E->getEndLoc());
12125   }
12126 
12127   EnterExpressionEvaluationContext Unevaluated(
12128       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
12129 
12130   ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
12131   if (SubExpr.isInvalid())
12132     return ExprError();
12133 
12134   if (!getDerived().AlwaysRebuild() &&
12135       SubExpr.get() == E->getExprOperand())
12136     return E;
12137 
12138   return getDerived().RebuildCXXUuidofExpr(E->getType(), E->getBeginLoc(),
12139                                            SubExpr.get(), E->getEndLoc());
12140 }
12141 
12142 template<typename Derived>
12143 ExprResult
12144 TreeTransform<Derived>::TransformCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
12145   return E;
12146 }
12147 
12148 template<typename Derived>
12149 ExprResult
12150 TreeTransform<Derived>::TransformCXXNullPtrLiteralExpr(
12151                                                      CXXNullPtrLiteralExpr *E) {
12152   return E;
12153 }
12154 
12155 template<typename Derived>
12156 ExprResult
12157 TreeTransform<Derived>::TransformCXXThisExpr(CXXThisExpr *E) {
12158   QualType T = getSema().getCurrentThisType();
12159 
12160   if (!getDerived().AlwaysRebuild() && T == E->getType()) {
12161     // Mark it referenced in the new context regardless.
12162     // FIXME: this is a bit instantiation-specific.
12163     getSema().MarkThisReferenced(E);
12164     return E;
12165   }
12166 
12167   return getDerived().RebuildCXXThisExpr(E->getBeginLoc(), T, E->isImplicit());
12168 }
12169 
12170 template<typename Derived>
12171 ExprResult
12172 TreeTransform<Derived>::TransformCXXThrowExpr(CXXThrowExpr *E) {
12173   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
12174   if (SubExpr.isInvalid())
12175     return ExprError();
12176 
12177   if (!getDerived().AlwaysRebuild() &&
12178       SubExpr.get() == E->getSubExpr())
12179     return E;
12180 
12181   return getDerived().RebuildCXXThrowExpr(E->getThrowLoc(), SubExpr.get(),
12182                                           E->isThrownVariableInScope());
12183 }
12184 
12185 template<typename Derived>
12186 ExprResult
12187 TreeTransform<Derived>::TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
12188   ParmVarDecl *Param = cast_or_null<ParmVarDecl>(
12189       getDerived().TransformDecl(E->getBeginLoc(), E->getParam()));
12190   if (!Param)
12191     return ExprError();
12192 
12193   ExprResult InitRes;
12194   if (E->hasRewrittenInit()) {
12195     InitRes = getDerived().TransformExpr(E->getRewrittenExpr());
12196     if (InitRes.isInvalid())
12197       return ExprError();
12198   }
12199 
12200   if (!getDerived().AlwaysRebuild() && Param == E->getParam() &&
12201       E->getUsedContext() == SemaRef.CurContext &&
12202       InitRes.get() == E->getRewrittenExpr())
12203     return E;
12204 
12205   return getDerived().RebuildCXXDefaultArgExpr(E->getUsedLocation(), Param,
12206                                                InitRes.get());
12207 }
12208 
12209 template<typename Derived>
12210 ExprResult
12211 TreeTransform<Derived>::TransformCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
12212   FieldDecl *Field = cast_or_null<FieldDecl>(
12213       getDerived().TransformDecl(E->getBeginLoc(), E->getField()));
12214   if (!Field)
12215     return ExprError();
12216 
12217   if (!getDerived().AlwaysRebuild() && Field == E->getField() &&
12218       E->getUsedContext() == SemaRef.CurContext)
12219     return E;
12220 
12221   return getDerived().RebuildCXXDefaultInitExpr(E->getExprLoc(), Field);
12222 }
12223 
12224 template<typename Derived>
12225 ExprResult
12226 TreeTransform<Derived>::TransformCXXScalarValueInitExpr(
12227                                                     CXXScalarValueInitExpr *E) {
12228   TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
12229   if (!T)
12230     return ExprError();
12231 
12232   if (!getDerived().AlwaysRebuild() &&
12233       T == E->getTypeSourceInfo())
12234     return E;
12235 
12236   return getDerived().RebuildCXXScalarValueInitExpr(T,
12237                                           /*FIXME:*/T->getTypeLoc().getEndLoc(),
12238                                                     E->getRParenLoc());
12239 }
12240 
12241 template<typename Derived>
12242 ExprResult
12243 TreeTransform<Derived>::TransformCXXNewExpr(CXXNewExpr *E) {
12244   // Transform the type that we're allocating
12245   TypeSourceInfo *AllocTypeInfo =
12246       getDerived().TransformTypeWithDeducedTST(E->getAllocatedTypeSourceInfo());
12247   if (!AllocTypeInfo)
12248     return ExprError();
12249 
12250   // Transform the size of the array we're allocating (if any).
12251   std::optional<Expr *> ArraySize;
12252   if (E->isArray()) {
12253     ExprResult NewArraySize;
12254     if (std::optional<Expr *> OldArraySize = E->getArraySize()) {
12255       NewArraySize = getDerived().TransformExpr(*OldArraySize);
12256       if (NewArraySize.isInvalid())
12257         return ExprError();
12258     }
12259     ArraySize = NewArraySize.get();
12260   }
12261 
12262   // Transform the placement arguments (if any).
12263   bool ArgumentChanged = false;
12264   SmallVector<Expr*, 8> PlacementArgs;
12265   if (getDerived().TransformExprs(E->getPlacementArgs(),
12266                                   E->getNumPlacementArgs(), true,
12267                                   PlacementArgs, &ArgumentChanged))
12268     return ExprError();
12269 
12270   // Transform the initializer (if any).
12271   Expr *OldInit = E->getInitializer();
12272   ExprResult NewInit;
12273   if (OldInit)
12274     NewInit = getDerived().TransformInitializer(OldInit, true);
12275   if (NewInit.isInvalid())
12276     return ExprError();
12277 
12278   // Transform new operator and delete operator.
12279   FunctionDecl *OperatorNew = nullptr;
12280   if (E->getOperatorNew()) {
12281     OperatorNew = cast_or_null<FunctionDecl>(
12282         getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorNew()));
12283     if (!OperatorNew)
12284       return ExprError();
12285   }
12286 
12287   FunctionDecl *OperatorDelete = nullptr;
12288   if (E->getOperatorDelete()) {
12289     OperatorDelete = cast_or_null<FunctionDecl>(
12290         getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorDelete()));
12291     if (!OperatorDelete)
12292       return ExprError();
12293   }
12294 
12295   if (!getDerived().AlwaysRebuild() &&
12296       AllocTypeInfo == E->getAllocatedTypeSourceInfo() &&
12297       ArraySize == E->getArraySize() &&
12298       NewInit.get() == OldInit &&
12299       OperatorNew == E->getOperatorNew() &&
12300       OperatorDelete == E->getOperatorDelete() &&
12301       !ArgumentChanged) {
12302     // Mark any declarations we need as referenced.
12303     // FIXME: instantiation-specific.
12304     if (OperatorNew)
12305       SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorNew);
12306     if (OperatorDelete)
12307       SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorDelete);
12308 
12309     if (E->isArray() && !E->getAllocatedType()->isDependentType()) {
12310       QualType ElementType
12311         = SemaRef.Context.getBaseElementType(E->getAllocatedType());
12312       if (const RecordType *RecordT = ElementType->getAs<RecordType>()) {
12313         CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordT->getDecl());
12314         if (CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(Record)) {
12315           SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Destructor);
12316         }
12317       }
12318     }
12319 
12320     return E;
12321   }
12322 
12323   QualType AllocType = AllocTypeInfo->getType();
12324   if (!ArraySize) {
12325     // If no array size was specified, but the new expression was
12326     // instantiated with an array type (e.g., "new T" where T is
12327     // instantiated with "int[4]"), extract the outer bound from the
12328     // array type as our array size. We do this with constant and
12329     // dependently-sized array types.
12330     const ArrayType *ArrayT = SemaRef.Context.getAsArrayType(AllocType);
12331     if (!ArrayT) {
12332       // Do nothing
12333     } else if (const ConstantArrayType *ConsArrayT
12334                                      = dyn_cast<ConstantArrayType>(ArrayT)) {
12335       ArraySize = IntegerLiteral::Create(SemaRef.Context, ConsArrayT->getSize(),
12336                                          SemaRef.Context.getSizeType(),
12337                                          /*FIXME:*/ E->getBeginLoc());
12338       AllocType = ConsArrayT->getElementType();
12339     } else if (const DependentSizedArrayType *DepArrayT
12340                               = dyn_cast<DependentSizedArrayType>(ArrayT)) {
12341       if (DepArrayT->getSizeExpr()) {
12342         ArraySize = DepArrayT->getSizeExpr();
12343         AllocType = DepArrayT->getElementType();
12344       }
12345     }
12346   }
12347 
12348   return getDerived().RebuildCXXNewExpr(
12349       E->getBeginLoc(), E->isGlobalNew(),
12350       /*FIXME:*/ E->getBeginLoc(), PlacementArgs,
12351       /*FIXME:*/ E->getBeginLoc(), E->getTypeIdParens(), AllocType,
12352       AllocTypeInfo, ArraySize, E->getDirectInitRange(), NewInit.get());
12353 }
12354 
12355 template<typename Derived>
12356 ExprResult
12357 TreeTransform<Derived>::TransformCXXDeleteExpr(CXXDeleteExpr *E) {
12358   ExprResult Operand = getDerived().TransformExpr(E->getArgument());
12359   if (Operand.isInvalid())
12360     return ExprError();
12361 
12362   // Transform the delete operator, if known.
12363   FunctionDecl *OperatorDelete = nullptr;
12364   if (E->getOperatorDelete()) {
12365     OperatorDelete = cast_or_null<FunctionDecl>(
12366         getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorDelete()));
12367     if (!OperatorDelete)
12368       return ExprError();
12369   }
12370 
12371   if (!getDerived().AlwaysRebuild() &&
12372       Operand.get() == E->getArgument() &&
12373       OperatorDelete == E->getOperatorDelete()) {
12374     // Mark any declarations we need as referenced.
12375     // FIXME: instantiation-specific.
12376     if (OperatorDelete)
12377       SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorDelete);
12378 
12379     if (!E->getArgument()->isTypeDependent()) {
12380       QualType Destroyed = SemaRef.Context.getBaseElementType(
12381                                                          E->getDestroyedType());
12382       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
12383         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
12384         SemaRef.MarkFunctionReferenced(E->getBeginLoc(),
12385                                        SemaRef.LookupDestructor(Record));
12386       }
12387     }
12388 
12389     return E;
12390   }
12391 
12392   return getDerived().RebuildCXXDeleteExpr(
12393       E->getBeginLoc(), E->isGlobalDelete(), E->isArrayForm(), Operand.get());
12394 }
12395 
12396 template<typename Derived>
12397 ExprResult
12398 TreeTransform<Derived>::TransformCXXPseudoDestructorExpr(
12399                                                      CXXPseudoDestructorExpr *E) {
12400   ExprResult Base = getDerived().TransformExpr(E->getBase());
12401   if (Base.isInvalid())
12402     return ExprError();
12403 
12404   ParsedType ObjectTypePtr;
12405   bool MayBePseudoDestructor = false;
12406   Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
12407                                               E->getOperatorLoc(),
12408                                         E->isArrow()? tok::arrow : tok::period,
12409                                               ObjectTypePtr,
12410                                               MayBePseudoDestructor);
12411   if (Base.isInvalid())
12412     return ExprError();
12413 
12414   QualType ObjectType = ObjectTypePtr.get();
12415   NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc();
12416   if (QualifierLoc) {
12417     QualifierLoc
12418       = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc, ObjectType);
12419     if (!QualifierLoc)
12420       return ExprError();
12421   }
12422   CXXScopeSpec SS;
12423   SS.Adopt(QualifierLoc);
12424 
12425   PseudoDestructorTypeStorage Destroyed;
12426   if (E->getDestroyedTypeInfo()) {
12427     TypeSourceInfo *DestroyedTypeInfo
12428       = getDerived().TransformTypeInObjectScope(E->getDestroyedTypeInfo(),
12429                                                 ObjectType, nullptr, SS);
12430     if (!DestroyedTypeInfo)
12431       return ExprError();
12432     Destroyed = DestroyedTypeInfo;
12433   } else if (!ObjectType.isNull() && ObjectType->isDependentType()) {
12434     // We aren't likely to be able to resolve the identifier down to a type
12435     // now anyway, so just retain the identifier.
12436     Destroyed = PseudoDestructorTypeStorage(E->getDestroyedTypeIdentifier(),
12437                                             E->getDestroyedTypeLoc());
12438   } else {
12439     // Look for a destructor known with the given name.
12440     ParsedType T = SemaRef.getDestructorName(E->getTildeLoc(),
12441                                               *E->getDestroyedTypeIdentifier(),
12442                                                 E->getDestroyedTypeLoc(),
12443                                                 /*Scope=*/nullptr,
12444                                                 SS, ObjectTypePtr,
12445                                                 false);
12446     if (!T)
12447       return ExprError();
12448 
12449     Destroyed
12450       = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.GetTypeFromParser(T),
12451                                                  E->getDestroyedTypeLoc());
12452   }
12453 
12454   TypeSourceInfo *ScopeTypeInfo = nullptr;
12455   if (E->getScopeTypeInfo()) {
12456     CXXScopeSpec EmptySS;
12457     ScopeTypeInfo = getDerived().TransformTypeInObjectScope(
12458                       E->getScopeTypeInfo(), ObjectType, nullptr, EmptySS);
12459     if (!ScopeTypeInfo)
12460       return ExprError();
12461   }
12462 
12463   return getDerived().RebuildCXXPseudoDestructorExpr(Base.get(),
12464                                                      E->getOperatorLoc(),
12465                                                      E->isArrow(),
12466                                                      SS,
12467                                                      ScopeTypeInfo,
12468                                                      E->getColonColonLoc(),
12469                                                      E->getTildeLoc(),
12470                                                      Destroyed);
12471 }
12472 
12473 template <typename Derived>
12474 bool TreeTransform<Derived>::TransformOverloadExprDecls(OverloadExpr *Old,
12475                                                         bool RequiresADL,
12476                                                         LookupResult &R) {
12477   // Transform all the decls.
12478   bool AllEmptyPacks = true;
12479   for (auto *OldD : Old->decls()) {
12480     Decl *InstD = getDerived().TransformDecl(Old->getNameLoc(), OldD);
12481     if (!InstD) {
12482       // Silently ignore these if a UsingShadowDecl instantiated to nothing.
12483       // This can happen because of dependent hiding.
12484       if (isa<UsingShadowDecl>(OldD))
12485         continue;
12486       else {
12487         R.clear();
12488         return true;
12489       }
12490     }
12491 
12492     // Expand using pack declarations.
12493     NamedDecl *SingleDecl = cast<NamedDecl>(InstD);
12494     ArrayRef<NamedDecl*> Decls = SingleDecl;
12495     if (auto *UPD = dyn_cast<UsingPackDecl>(InstD))
12496       Decls = UPD->expansions();
12497 
12498     // Expand using declarations.
12499     for (auto *D : Decls) {
12500       if (auto *UD = dyn_cast<UsingDecl>(D)) {
12501         for (auto *SD : UD->shadows())
12502           R.addDecl(SD);
12503       } else {
12504         R.addDecl(D);
12505       }
12506     }
12507 
12508     AllEmptyPacks &= Decls.empty();
12509   };
12510 
12511   // C++ [temp.res]/8.4.2:
12512   //   The program is ill-formed, no diagnostic required, if [...] lookup for
12513   //   a name in the template definition found a using-declaration, but the
12514   //   lookup in the corresponding scope in the instantiation odoes not find
12515   //   any declarations because the using-declaration was a pack expansion and
12516   //   the corresponding pack is empty
12517   if (AllEmptyPacks && !RequiresADL) {
12518     getSema().Diag(Old->getNameLoc(), diag::err_using_pack_expansion_empty)
12519         << isa<UnresolvedMemberExpr>(Old) << Old->getName();
12520     return true;
12521   }
12522 
12523   // Resolve a kind, but don't do any further analysis.  If it's
12524   // ambiguous, the callee needs to deal with it.
12525   R.resolveKind();
12526   return false;
12527 }
12528 
12529 template<typename Derived>
12530 ExprResult
12531 TreeTransform<Derived>::TransformUnresolvedLookupExpr(
12532                                                   UnresolvedLookupExpr *Old) {
12533   LookupResult R(SemaRef, Old->getName(), Old->getNameLoc(),
12534                  Sema::LookupOrdinaryName);
12535 
12536   // Transform the declaration set.
12537   if (TransformOverloadExprDecls(Old, Old->requiresADL(), R))
12538     return ExprError();
12539 
12540   // Rebuild the nested-name qualifier, if present.
12541   CXXScopeSpec SS;
12542   if (Old->getQualifierLoc()) {
12543     NestedNameSpecifierLoc QualifierLoc
12544       = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
12545     if (!QualifierLoc)
12546       return ExprError();
12547 
12548     SS.Adopt(QualifierLoc);
12549   }
12550 
12551   if (Old->getNamingClass()) {
12552     CXXRecordDecl *NamingClass
12553       = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
12554                                                             Old->getNameLoc(),
12555                                                         Old->getNamingClass()));
12556     if (!NamingClass) {
12557       R.clear();
12558       return ExprError();
12559     }
12560 
12561     R.setNamingClass(NamingClass);
12562   }
12563 
12564   SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
12565 
12566   // If we have neither explicit template arguments, nor the template keyword,
12567   // it's a normal declaration name or member reference.
12568   if (!Old->hasExplicitTemplateArgs() && !TemplateKWLoc.isValid()) {
12569     NamedDecl *D = R.getAsSingle<NamedDecl>();
12570     // In a C++11 unevaluated context, an UnresolvedLookupExpr might refer to an
12571     // instance member. In other contexts, BuildPossibleImplicitMemberExpr will
12572     // give a good diagnostic.
12573     if (D && D->isCXXInstanceMember()) {
12574       return SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
12575                                                      /*TemplateArgs=*/nullptr,
12576                                                      /*Scope=*/nullptr);
12577     }
12578 
12579     return getDerived().RebuildDeclarationNameExpr(SS, R, Old->requiresADL());
12580   }
12581 
12582   // If we have template arguments, rebuild them, then rebuild the
12583   // templateid expression.
12584   TemplateArgumentListInfo TransArgs(Old->getLAngleLoc(), Old->getRAngleLoc());
12585   if (Old->hasExplicitTemplateArgs() &&
12586       getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
12587                                               Old->getNumTemplateArgs(),
12588                                               TransArgs)) {
12589     R.clear();
12590     return ExprError();
12591   }
12592 
12593   return getDerived().RebuildTemplateIdExpr(SS, TemplateKWLoc, R,
12594                                             Old->requiresADL(), &TransArgs);
12595 }
12596 
12597 template<typename Derived>
12598 ExprResult
12599 TreeTransform<Derived>::TransformTypeTraitExpr(TypeTraitExpr *E) {
12600   bool ArgChanged = false;
12601   SmallVector<TypeSourceInfo *, 4> Args;
12602   for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I) {
12603     TypeSourceInfo *From = E->getArg(I);
12604     TypeLoc FromTL = From->getTypeLoc();
12605     if (!FromTL.getAs<PackExpansionTypeLoc>()) {
12606       TypeLocBuilder TLB;
12607       TLB.reserve(FromTL.getFullDataSize());
12608       QualType To = getDerived().TransformType(TLB, FromTL);
12609       if (To.isNull())
12610         return ExprError();
12611 
12612       if (To == From->getType())
12613         Args.push_back(From);
12614       else {
12615         Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
12616         ArgChanged = true;
12617       }
12618       continue;
12619     }
12620 
12621     ArgChanged = true;
12622 
12623     // We have a pack expansion. Instantiate it.
12624     PackExpansionTypeLoc ExpansionTL = FromTL.castAs<PackExpansionTypeLoc>();
12625     TypeLoc PatternTL = ExpansionTL.getPatternLoc();
12626     SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12627     SemaRef.collectUnexpandedParameterPacks(PatternTL, Unexpanded);
12628 
12629     // Determine whether the set of unexpanded parameter packs can and should
12630     // be expanded.
12631     bool Expand = true;
12632     bool RetainExpansion = false;
12633     std::optional<unsigned> OrigNumExpansions =
12634         ExpansionTL.getTypePtr()->getNumExpansions();
12635     std::optional<unsigned> NumExpansions = OrigNumExpansions;
12636     if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
12637                                              PatternTL.getSourceRange(),
12638                                              Unexpanded,
12639                                              Expand, RetainExpansion,
12640                                              NumExpansions))
12641       return ExprError();
12642 
12643     if (!Expand) {
12644       // The transform has determined that we should perform a simple
12645       // transformation on the pack expansion, producing another pack
12646       // expansion.
12647       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
12648 
12649       TypeLocBuilder TLB;
12650       TLB.reserve(From->getTypeLoc().getFullDataSize());
12651 
12652       QualType To = getDerived().TransformType(TLB, PatternTL);
12653       if (To.isNull())
12654         return ExprError();
12655 
12656       To = getDerived().RebuildPackExpansionType(To,
12657                                                  PatternTL.getSourceRange(),
12658                                                  ExpansionTL.getEllipsisLoc(),
12659                                                  NumExpansions);
12660       if (To.isNull())
12661         return ExprError();
12662 
12663       PackExpansionTypeLoc ToExpansionTL
12664         = TLB.push<PackExpansionTypeLoc>(To);
12665       ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
12666       Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
12667       continue;
12668     }
12669 
12670     // Expand the pack expansion by substituting for each argument in the
12671     // pack(s).
12672     for (unsigned I = 0; I != *NumExpansions; ++I) {
12673       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
12674       TypeLocBuilder TLB;
12675       TLB.reserve(PatternTL.getFullDataSize());
12676       QualType To = getDerived().TransformType(TLB, PatternTL);
12677       if (To.isNull())
12678         return ExprError();
12679 
12680       if (To->containsUnexpandedParameterPack()) {
12681         To = getDerived().RebuildPackExpansionType(To,
12682                                                    PatternTL.getSourceRange(),
12683                                                    ExpansionTL.getEllipsisLoc(),
12684                                                    NumExpansions);
12685         if (To.isNull())
12686           return ExprError();
12687 
12688         PackExpansionTypeLoc ToExpansionTL
12689           = TLB.push<PackExpansionTypeLoc>(To);
12690         ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
12691       }
12692 
12693       Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
12694     }
12695 
12696     if (!RetainExpansion)
12697       continue;
12698 
12699     // If we're supposed to retain a pack expansion, do so by temporarily
12700     // forgetting the partially-substituted parameter pack.
12701     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
12702 
12703     TypeLocBuilder TLB;
12704     TLB.reserve(From->getTypeLoc().getFullDataSize());
12705 
12706     QualType To = getDerived().TransformType(TLB, PatternTL);
12707     if (To.isNull())
12708       return ExprError();
12709 
12710     To = getDerived().RebuildPackExpansionType(To,
12711                                                PatternTL.getSourceRange(),
12712                                                ExpansionTL.getEllipsisLoc(),
12713                                                NumExpansions);
12714     if (To.isNull())
12715       return ExprError();
12716 
12717     PackExpansionTypeLoc ToExpansionTL
12718       = TLB.push<PackExpansionTypeLoc>(To);
12719     ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
12720     Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
12721   }
12722 
12723   if (!getDerived().AlwaysRebuild() && !ArgChanged)
12724     return E;
12725 
12726   return getDerived().RebuildTypeTrait(E->getTrait(), E->getBeginLoc(), Args,
12727                                        E->getEndLoc());
12728 }
12729 
12730 template<typename Derived>
12731 ExprResult
12732 TreeTransform<Derived>::TransformConceptSpecializationExpr(
12733                                                  ConceptSpecializationExpr *E) {
12734   const ASTTemplateArgumentListInfo *Old = E->getTemplateArgsAsWritten();
12735   TemplateArgumentListInfo TransArgs(Old->LAngleLoc, Old->RAngleLoc);
12736   if (getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
12737                                               Old->NumTemplateArgs, TransArgs))
12738     return ExprError();
12739 
12740   return getDerived().RebuildConceptSpecializationExpr(
12741       E->getNestedNameSpecifierLoc(), E->getTemplateKWLoc(),
12742       E->getConceptNameInfo(), E->getFoundDecl(), E->getNamedConcept(),
12743       &TransArgs);
12744 }
12745 
12746 template<typename Derived>
12747 ExprResult
12748 TreeTransform<Derived>::TransformRequiresExpr(RequiresExpr *E) {
12749   SmallVector<ParmVarDecl*, 4> TransParams;
12750   SmallVector<QualType, 4> TransParamTypes;
12751   Sema::ExtParameterInfoBuilder ExtParamInfos;
12752 
12753   // C++2a [expr.prim.req]p2
12754   // Expressions appearing within a requirement-body are unevaluated operands.
12755   EnterExpressionEvaluationContext Ctx(
12756       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
12757       Sema::ReuseLambdaContextDecl);
12758 
12759   RequiresExprBodyDecl *Body = RequiresExprBodyDecl::Create(
12760       getSema().Context, getSema().CurContext,
12761       E->getBody()->getBeginLoc());
12762 
12763   Sema::ContextRAII SavedContext(getSema(), Body, /*NewThisContext*/false);
12764 
12765   ExprResult TypeParamResult = getDerived().TransformRequiresTypeParams(
12766       E->getRequiresKWLoc(), E->getRBraceLoc(), E, Body,
12767       E->getLocalParameters(), TransParamTypes, TransParams, ExtParamInfos);
12768 
12769   for (ParmVarDecl *Param : TransParams)
12770     if (Param)
12771       Param->setDeclContext(Body);
12772 
12773   // On failure to transform, TransformRequiresTypeParams returns an expression
12774   // in the event that the transformation of the type params failed in some way.
12775   // It is expected that this will result in a 'not satisfied' Requires clause
12776   // when instantiating.
12777   if (!TypeParamResult.isUnset())
12778     return TypeParamResult;
12779 
12780   SmallVector<concepts::Requirement *, 4> TransReqs;
12781   if (getDerived().TransformRequiresExprRequirements(E->getRequirements(),
12782                                                      TransReqs))
12783     return ExprError();
12784 
12785   for (concepts::Requirement *Req : TransReqs) {
12786     if (auto *ER = dyn_cast<concepts::ExprRequirement>(Req)) {
12787       if (ER->getReturnTypeRequirement().isTypeConstraint()) {
12788         ER->getReturnTypeRequirement()
12789                 .getTypeConstraintTemplateParameterList()->getParam(0)
12790                 ->setDeclContext(Body);
12791       }
12792     }
12793   }
12794 
12795   return getDerived().RebuildRequiresExpr(E->getRequiresKWLoc(), Body,
12796                                           TransParams, TransReqs,
12797                                           E->getRBraceLoc());
12798 }
12799 
12800 template<typename Derived>
12801 bool TreeTransform<Derived>::TransformRequiresExprRequirements(
12802     ArrayRef<concepts::Requirement *> Reqs,
12803     SmallVectorImpl<concepts::Requirement *> &Transformed) {
12804   for (concepts::Requirement *Req : Reqs) {
12805     concepts::Requirement *TransReq = nullptr;
12806     if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Req))
12807       TransReq = getDerived().TransformTypeRequirement(TypeReq);
12808     else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Req))
12809       TransReq = getDerived().TransformExprRequirement(ExprReq);
12810     else
12811       TransReq = getDerived().TransformNestedRequirement(
12812                      cast<concepts::NestedRequirement>(Req));
12813     if (!TransReq)
12814       return true;
12815     Transformed.push_back(TransReq);
12816   }
12817   return false;
12818 }
12819 
12820 template<typename Derived>
12821 concepts::TypeRequirement *
12822 TreeTransform<Derived>::TransformTypeRequirement(
12823     concepts::TypeRequirement *Req) {
12824   if (Req->isSubstitutionFailure()) {
12825     if (getDerived().AlwaysRebuild())
12826       return getDerived().RebuildTypeRequirement(
12827               Req->getSubstitutionDiagnostic());
12828     return Req;
12829   }
12830   TypeSourceInfo *TransType = getDerived().TransformType(Req->getType());
12831   if (!TransType)
12832     return nullptr;
12833   return getDerived().RebuildTypeRequirement(TransType);
12834 }
12835 
12836 template<typename Derived>
12837 concepts::ExprRequirement *
12838 TreeTransform<Derived>::TransformExprRequirement(concepts::ExprRequirement *Req) {
12839   llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *> TransExpr;
12840   if (Req->isExprSubstitutionFailure())
12841     TransExpr = Req->getExprSubstitutionDiagnostic();
12842   else {
12843     ExprResult TransExprRes = getDerived().TransformExpr(Req->getExpr());
12844     if (TransExprRes.isUsable() && TransExprRes.get()->hasPlaceholderType())
12845       TransExprRes = SemaRef.CheckPlaceholderExpr(TransExprRes.get());
12846     if (TransExprRes.isInvalid())
12847       return nullptr;
12848     TransExpr = TransExprRes.get();
12849   }
12850 
12851   std::optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq;
12852   const auto &RetReq = Req->getReturnTypeRequirement();
12853   if (RetReq.isEmpty())
12854     TransRetReq.emplace();
12855   else if (RetReq.isSubstitutionFailure())
12856     TransRetReq.emplace(RetReq.getSubstitutionDiagnostic());
12857   else if (RetReq.isTypeConstraint()) {
12858     TemplateParameterList *OrigTPL =
12859         RetReq.getTypeConstraintTemplateParameterList();
12860     TemplateParameterList *TPL =
12861         getDerived().TransformTemplateParameterList(OrigTPL);
12862     if (!TPL)
12863       return nullptr;
12864     TransRetReq.emplace(TPL);
12865   }
12866   assert(TransRetReq && "All code paths leading here must set TransRetReq");
12867   if (Expr *E = TransExpr.dyn_cast<Expr *>())
12868     return getDerived().RebuildExprRequirement(E, Req->isSimple(),
12869                                                Req->getNoexceptLoc(),
12870                                                std::move(*TransRetReq));
12871   return getDerived().RebuildExprRequirement(
12872       TransExpr.get<concepts::Requirement::SubstitutionDiagnostic *>(),
12873       Req->isSimple(), Req->getNoexceptLoc(), std::move(*TransRetReq));
12874 }
12875 
12876 template<typename Derived>
12877 concepts::NestedRequirement *
12878 TreeTransform<Derived>::TransformNestedRequirement(
12879     concepts::NestedRequirement *Req) {
12880   if (Req->hasInvalidConstraint()) {
12881     if (getDerived().AlwaysRebuild())
12882       return getDerived().RebuildNestedRequirement(
12883           Req->getInvalidConstraintEntity(), Req->getConstraintSatisfaction());
12884     return Req;
12885   }
12886   ExprResult TransConstraint =
12887       getDerived().TransformExpr(Req->getConstraintExpr());
12888   if (TransConstraint.isInvalid())
12889     return nullptr;
12890   return getDerived().RebuildNestedRequirement(TransConstraint.get());
12891 }
12892 
12893 template<typename Derived>
12894 ExprResult
12895 TreeTransform<Derived>::TransformArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
12896   TypeSourceInfo *T = getDerived().TransformType(E->getQueriedTypeSourceInfo());
12897   if (!T)
12898     return ExprError();
12899 
12900   if (!getDerived().AlwaysRebuild() &&
12901       T == E->getQueriedTypeSourceInfo())
12902     return E;
12903 
12904   ExprResult SubExpr;
12905   {
12906     EnterExpressionEvaluationContext Unevaluated(
12907         SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
12908     SubExpr = getDerived().TransformExpr(E->getDimensionExpression());
12909     if (SubExpr.isInvalid())
12910       return ExprError();
12911 
12912     if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getDimensionExpression())
12913       return E;
12914   }
12915 
12916   return getDerived().RebuildArrayTypeTrait(E->getTrait(), E->getBeginLoc(), T,
12917                                             SubExpr.get(), E->getEndLoc());
12918 }
12919 
12920 template<typename Derived>
12921 ExprResult
12922 TreeTransform<Derived>::TransformExpressionTraitExpr(ExpressionTraitExpr *E) {
12923   ExprResult SubExpr;
12924   {
12925     EnterExpressionEvaluationContext Unevaluated(
12926         SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
12927     SubExpr = getDerived().TransformExpr(E->getQueriedExpression());
12928     if (SubExpr.isInvalid())
12929       return ExprError();
12930 
12931     if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getQueriedExpression())
12932       return E;
12933   }
12934 
12935   return getDerived().RebuildExpressionTrait(E->getTrait(), E->getBeginLoc(),
12936                                              SubExpr.get(), E->getEndLoc());
12937 }
12938 
12939 template <typename Derived>
12940 ExprResult TreeTransform<Derived>::TransformParenDependentScopeDeclRefExpr(
12941     ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool AddrTaken,
12942     TypeSourceInfo **RecoveryTSI) {
12943   ExprResult NewDRE = getDerived().TransformDependentScopeDeclRefExpr(
12944       DRE, AddrTaken, RecoveryTSI);
12945 
12946   // Propagate both errors and recovered types, which return ExprEmpty.
12947   if (!NewDRE.isUsable())
12948     return NewDRE;
12949 
12950   // We got an expr, wrap it up in parens.
12951   if (!getDerived().AlwaysRebuild() && NewDRE.get() == DRE)
12952     return PE;
12953   return getDerived().RebuildParenExpr(NewDRE.get(), PE->getLParen(),
12954                                        PE->getRParen());
12955 }
12956 
12957 template <typename Derived>
12958 ExprResult TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
12959     DependentScopeDeclRefExpr *E) {
12960   return TransformDependentScopeDeclRefExpr(E, /*IsAddressOfOperand=*/false,
12961                                             nullptr);
12962 }
12963 
12964 template <typename Derived>
12965 ExprResult TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
12966     DependentScopeDeclRefExpr *E, bool IsAddressOfOperand,
12967     TypeSourceInfo **RecoveryTSI) {
12968   assert(E->getQualifierLoc());
12969   NestedNameSpecifierLoc QualifierLoc =
12970       getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
12971   if (!QualifierLoc)
12972     return ExprError();
12973   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
12974 
12975   // TODO: If this is a conversion-function-id, verify that the
12976   // destination type name (if present) resolves the same way after
12977   // instantiation as it did in the local scope.
12978 
12979   DeclarationNameInfo NameInfo =
12980       getDerived().TransformDeclarationNameInfo(E->getNameInfo());
12981   if (!NameInfo.getName())
12982     return ExprError();
12983 
12984   if (!E->hasExplicitTemplateArgs()) {
12985     if (!getDerived().AlwaysRebuild() && QualifierLoc == E->getQualifierLoc() &&
12986         // Note: it is sufficient to compare the Name component of NameInfo:
12987         // if name has not changed, DNLoc has not changed either.
12988         NameInfo.getName() == E->getDeclName())
12989       return E;
12990 
12991     return getDerived().RebuildDependentScopeDeclRefExpr(
12992         QualifierLoc, TemplateKWLoc, NameInfo, /*TemplateArgs=*/nullptr,
12993         IsAddressOfOperand, RecoveryTSI);
12994   }
12995 
12996   TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
12997   if (getDerived().TransformTemplateArguments(
12998           E->getTemplateArgs(), E->getNumTemplateArgs(), TransArgs))
12999     return ExprError();
13000 
13001   return getDerived().RebuildDependentScopeDeclRefExpr(
13002       QualifierLoc, TemplateKWLoc, NameInfo, &TransArgs, IsAddressOfOperand,
13003       RecoveryTSI);
13004 }
13005 
13006 template<typename Derived>
13007 ExprResult
13008 TreeTransform<Derived>::TransformCXXConstructExpr(CXXConstructExpr *E) {
13009   // CXXConstructExprs other than for list-initialization and
13010   // CXXTemporaryObjectExpr are always implicit, so when we have
13011   // a 1-argument construction we just transform that argument.
13012   if (getDerived().AllowSkippingCXXConstructExpr() &&
13013       ((E->getNumArgs() == 1 ||
13014         (E->getNumArgs() > 1 && getDerived().DropCallArgument(E->getArg(1)))) &&
13015        (!getDerived().DropCallArgument(E->getArg(0))) &&
13016        !E->isListInitialization()))
13017     return getDerived().TransformInitializer(E->getArg(0),
13018                                              /*DirectInit*/ false);
13019 
13020   TemporaryBase Rebase(*this, /*FIXME*/ E->getBeginLoc(), DeclarationName());
13021 
13022   QualType T = getDerived().TransformType(E->getType());
13023   if (T.isNull())
13024     return ExprError();
13025 
13026   CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
13027       getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
13028   if (!Constructor)
13029     return ExprError();
13030 
13031   bool ArgumentChanged = false;
13032   SmallVector<Expr*, 8> Args;
13033   {
13034     EnterExpressionEvaluationContext Context(
13035         getSema(), EnterExpressionEvaluationContext::InitList,
13036         E->isListInitialization());
13037     if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
13038                                     &ArgumentChanged))
13039       return ExprError();
13040   }
13041 
13042   if (!getDerived().AlwaysRebuild() &&
13043       T == E->getType() &&
13044       Constructor == E->getConstructor() &&
13045       !ArgumentChanged) {
13046     // Mark the constructor as referenced.
13047     // FIXME: Instantiation-specific
13048     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
13049     return E;
13050   }
13051 
13052   return getDerived().RebuildCXXConstructExpr(
13053       T, /*FIXME:*/ E->getBeginLoc(), Constructor, E->isElidable(), Args,
13054       E->hadMultipleCandidates(), E->isListInitialization(),
13055       E->isStdInitListInitialization(), E->requiresZeroInitialization(),
13056       E->getConstructionKind(), E->getParenOrBraceRange());
13057 }
13058 
13059 template<typename Derived>
13060 ExprResult TreeTransform<Derived>::TransformCXXInheritedCtorInitExpr(
13061     CXXInheritedCtorInitExpr *E) {
13062   QualType T = getDerived().TransformType(E->getType());
13063   if (T.isNull())
13064     return ExprError();
13065 
13066   CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
13067       getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
13068   if (!Constructor)
13069     return ExprError();
13070 
13071   if (!getDerived().AlwaysRebuild() &&
13072       T == E->getType() &&
13073       Constructor == E->getConstructor()) {
13074     // Mark the constructor as referenced.
13075     // FIXME: Instantiation-specific
13076     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
13077     return E;
13078   }
13079 
13080   return getDerived().RebuildCXXInheritedCtorInitExpr(
13081       T, E->getLocation(), Constructor,
13082       E->constructsVBase(), E->inheritedFromVBase());
13083 }
13084 
13085 /// Transform a C++ temporary-binding expression.
13086 ///
13087 /// Since CXXBindTemporaryExpr nodes are implicitly generated, we just
13088 /// transform the subexpression and return that.
13089 template<typename Derived>
13090 ExprResult
13091 TreeTransform<Derived>::TransformCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
13092   if (auto *Dtor = E->getTemporary()->getDestructor())
13093     SemaRef.MarkFunctionReferenced(E->getBeginLoc(),
13094                                    const_cast<CXXDestructorDecl *>(Dtor));
13095   return getDerived().TransformExpr(E->getSubExpr());
13096 }
13097 
13098 /// Transform a C++ expression that contains cleanups that should
13099 /// be run after the expression is evaluated.
13100 ///
13101 /// Since ExprWithCleanups nodes are implicitly generated, we
13102 /// just transform the subexpression and return that.
13103 template<typename Derived>
13104 ExprResult
13105 TreeTransform<Derived>::TransformExprWithCleanups(ExprWithCleanups *E) {
13106   return getDerived().TransformExpr(E->getSubExpr());
13107 }
13108 
13109 template<typename Derived>
13110 ExprResult
13111 TreeTransform<Derived>::TransformCXXTemporaryObjectExpr(
13112                                                     CXXTemporaryObjectExpr *E) {
13113   TypeSourceInfo *T =
13114       getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
13115   if (!T)
13116     return ExprError();
13117 
13118   CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
13119       getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
13120   if (!Constructor)
13121     return ExprError();
13122 
13123   bool ArgumentChanged = false;
13124   SmallVector<Expr*, 8> Args;
13125   Args.reserve(E->getNumArgs());
13126   {
13127     EnterExpressionEvaluationContext Context(
13128         getSema(), EnterExpressionEvaluationContext::InitList,
13129         E->isListInitialization());
13130     if (TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
13131                        &ArgumentChanged))
13132       return ExprError();
13133   }
13134 
13135   if (!getDerived().AlwaysRebuild() &&
13136       T == E->getTypeSourceInfo() &&
13137       Constructor == E->getConstructor() &&
13138       !ArgumentChanged) {
13139     // FIXME: Instantiation-specific
13140     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
13141     return SemaRef.MaybeBindToTemporary(E);
13142   }
13143 
13144   // FIXME: We should just pass E->isListInitialization(), but we're not
13145   // prepared to handle list-initialization without a child InitListExpr.
13146   SourceLocation LParenLoc = T->getTypeLoc().getEndLoc();
13147   return getDerived().RebuildCXXTemporaryObjectExpr(
13148       T, LParenLoc, Args, E->getEndLoc(),
13149       /*ListInitialization=*/LParenLoc.isInvalid());
13150 }
13151 
13152 template<typename Derived>
13153 ExprResult
13154 TreeTransform<Derived>::TransformLambdaExpr(LambdaExpr *E) {
13155   // Transform any init-capture expressions before entering the scope of the
13156   // lambda body, because they are not semantically within that scope.
13157   typedef std::pair<ExprResult, QualType> InitCaptureInfoTy;
13158   struct TransformedInitCapture {
13159     // The location of the ... if the result is retaining a pack expansion.
13160     SourceLocation EllipsisLoc;
13161     // Zero or more expansions of the init-capture.
13162     SmallVector<InitCaptureInfoTy, 4> Expansions;
13163   };
13164   SmallVector<TransformedInitCapture, 4> InitCaptures;
13165   InitCaptures.resize(E->explicit_capture_end() - E->explicit_capture_begin());
13166   for (LambdaExpr::capture_iterator C = E->capture_begin(),
13167                                     CEnd = E->capture_end();
13168        C != CEnd; ++C) {
13169     if (!E->isInitCapture(C))
13170       continue;
13171 
13172     TransformedInitCapture &Result = InitCaptures[C - E->capture_begin()];
13173     auto *OldVD = cast<VarDecl>(C->getCapturedVar());
13174 
13175     auto SubstInitCapture = [&](SourceLocation EllipsisLoc,
13176                                 std::optional<unsigned> NumExpansions) {
13177       ExprResult NewExprInitResult = getDerived().TransformInitializer(
13178           OldVD->getInit(), OldVD->getInitStyle() == VarDecl::CallInit);
13179 
13180       if (NewExprInitResult.isInvalid()) {
13181         Result.Expansions.push_back(InitCaptureInfoTy(ExprError(), QualType()));
13182         return;
13183       }
13184       Expr *NewExprInit = NewExprInitResult.get();
13185 
13186       QualType NewInitCaptureType =
13187           getSema().buildLambdaInitCaptureInitialization(
13188               C->getLocation(), C->getCaptureKind() == LCK_ByRef,
13189               EllipsisLoc, NumExpansions, OldVD->getIdentifier(),
13190               cast<VarDecl>(C->getCapturedVar())->getInitStyle() !=
13191                   VarDecl::CInit,
13192               NewExprInit);
13193       Result.Expansions.push_back(
13194           InitCaptureInfoTy(NewExprInit, NewInitCaptureType));
13195     };
13196 
13197     // If this is an init-capture pack, consider expanding the pack now.
13198     if (OldVD->isParameterPack()) {
13199       PackExpansionTypeLoc ExpansionTL = OldVD->getTypeSourceInfo()
13200                                              ->getTypeLoc()
13201                                              .castAs<PackExpansionTypeLoc>();
13202       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13203       SemaRef.collectUnexpandedParameterPacks(OldVD->getInit(), Unexpanded);
13204 
13205       // Determine whether the set of unexpanded parameter packs can and should
13206       // be expanded.
13207       bool Expand = true;
13208       bool RetainExpansion = false;
13209       std::optional<unsigned> OrigNumExpansions =
13210           ExpansionTL.getTypePtr()->getNumExpansions();
13211       std::optional<unsigned> NumExpansions = OrigNumExpansions;
13212       if (getDerived().TryExpandParameterPacks(
13213               ExpansionTL.getEllipsisLoc(),
13214               OldVD->getInit()->getSourceRange(), Unexpanded, Expand,
13215               RetainExpansion, NumExpansions))
13216         return ExprError();
13217       if (Expand) {
13218         for (unsigned I = 0; I != *NumExpansions; ++I) {
13219           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
13220           SubstInitCapture(SourceLocation(), std::nullopt);
13221         }
13222       }
13223       if (!Expand || RetainExpansion) {
13224         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
13225         SubstInitCapture(ExpansionTL.getEllipsisLoc(), NumExpansions);
13226         Result.EllipsisLoc = ExpansionTL.getEllipsisLoc();
13227       }
13228     } else {
13229       SubstInitCapture(SourceLocation(), std::nullopt);
13230     }
13231   }
13232 
13233   LambdaScopeInfo *LSI = getSema().PushLambdaScope();
13234   Sema::FunctionScopeRAII FuncScopeCleanup(getSema());
13235 
13236   // Transform the template parameters, and add them to the current
13237   // instantiation scope. The null case is handled correctly.
13238   auto TPL = getDerived().TransformTemplateParameterList(
13239       E->getTemplateParameterList());
13240   LSI->GLTemplateParameterList = TPL;
13241 
13242   // Transform the type of the original lambda's call operator.
13243   // The transformation MUST be done in the CurrentInstantiationScope since
13244   // it introduces a mapping of the original to the newly created
13245   // transformed parameters.
13246   TypeSourceInfo *NewCallOpTSI = nullptr;
13247   {
13248     TypeSourceInfo *OldCallOpTSI = E->getCallOperator()->getTypeSourceInfo();
13249     FunctionProtoTypeLoc OldCallOpFPTL =
13250         OldCallOpTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
13251 
13252     TypeLocBuilder NewCallOpTLBuilder;
13253     SmallVector<QualType, 4> ExceptionStorage;
13254     TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
13255     QualType NewCallOpType = TransformFunctionProtoType(
13256         NewCallOpTLBuilder, OldCallOpFPTL, nullptr, Qualifiers(),
13257         [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
13258           return This->TransformExceptionSpec(OldCallOpFPTL.getBeginLoc(), ESI,
13259                                               ExceptionStorage, Changed);
13260         });
13261     if (NewCallOpType.isNull())
13262       return ExprError();
13263     NewCallOpTSI = NewCallOpTLBuilder.getTypeSourceInfo(getSema().Context,
13264                                                         NewCallOpType);
13265   }
13266 
13267   // Create the local class that will describe the lambda.
13268 
13269   // FIXME: DependencyKind below is wrong when substituting inside a templated
13270   // context that isn't a DeclContext (such as a variable template), or when
13271   // substituting an unevaluated lambda inside of a function's parameter's type
13272   // - as parameter types are not instantiated from within a function's DC. We
13273   // use evaluation contexts to distinguish the function parameter case.
13274   CXXRecordDecl::LambdaDependencyKind DependencyKind =
13275       CXXRecordDecl::LDK_Unknown;
13276   if ((getSema().isUnevaluatedContext() ||
13277        getSema().isConstantEvaluatedContext()) &&
13278       (getSema().CurContext->isFileContext() ||
13279        !getSema().CurContext->getParent()->isDependentContext()))
13280     DependencyKind = CXXRecordDecl::LDK_NeverDependent;
13281 
13282   CXXRecordDecl *OldClass = E->getLambdaClass();
13283   CXXRecordDecl *Class =
13284       getSema().createLambdaClosureType(E->getIntroducerRange(), NewCallOpTSI,
13285                                         DependencyKind, E->getCaptureDefault());
13286 
13287   getDerived().transformedLocalDecl(OldClass, {Class});
13288 
13289   std::optional<std::tuple<bool, unsigned, unsigned, Decl *>> Mangling;
13290   if (getDerived().ReplacingOriginal())
13291     Mangling = std::make_tuple(OldClass->hasKnownLambdaInternalLinkage(),
13292                                OldClass->getLambdaManglingNumber(),
13293                                OldClass->getDeviceLambdaManglingNumber(),
13294                                OldClass->getLambdaContextDecl());
13295 
13296   // Build the call operator.
13297   CXXMethodDecl *NewCallOperator = getSema().startLambdaDefinition(
13298       Class, E->getIntroducerRange(), NewCallOpTSI,
13299       E->getCallOperator()->getEndLoc(),
13300       NewCallOpTSI->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams(),
13301       E->getCallOperator()->getConstexprKind(),
13302       E->getCallOperator()->getStorageClass(),
13303       E->getCallOperator()->getTrailingRequiresClause());
13304 
13305   LSI->CallOperator = NewCallOperator;
13306 
13307   getDerived().transformAttrs(E->getCallOperator(), NewCallOperator);
13308   getDerived().transformedLocalDecl(E->getCallOperator(), {NewCallOperator});
13309 
13310   // Number the lambda for linkage purposes if necessary.
13311   getSema().handleLambdaNumbering(Class, NewCallOperator, Mangling);
13312 
13313   // Introduce the context of the call operator.
13314   Sema::ContextRAII SavedContext(getSema(), NewCallOperator,
13315                                  /*NewThisContext*/false);
13316 
13317   // Enter the scope of the lambda.
13318   getSema().buildLambdaScope(LSI, NewCallOperator,
13319                              E->getIntroducerRange(),
13320                              E->getCaptureDefault(),
13321                              E->getCaptureDefaultLoc(),
13322                              E->hasExplicitParameters(),
13323                              E->hasExplicitResultType(),
13324                              E->isMutable());
13325 
13326   bool Invalid = false;
13327 
13328   // Transform captures.
13329   for (LambdaExpr::capture_iterator C = E->capture_begin(),
13330                                  CEnd = E->capture_end();
13331        C != CEnd; ++C) {
13332     // When we hit the first implicit capture, tell Sema that we've finished
13333     // the list of explicit captures.
13334     if (C->isImplicit())
13335       break;
13336 
13337     // Capturing 'this' is trivial.
13338     if (C->capturesThis()) {
13339       getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit(),
13340                                     /*BuildAndDiagnose*/ true, nullptr,
13341                                     C->getCaptureKind() == LCK_StarThis);
13342       continue;
13343     }
13344     // Captured expression will be recaptured during captured variables
13345     // rebuilding.
13346     if (C->capturesVLAType())
13347       continue;
13348 
13349     // Rebuild init-captures, including the implied field declaration.
13350     if (E->isInitCapture(C)) {
13351       TransformedInitCapture &NewC = InitCaptures[C - E->capture_begin()];
13352 
13353       auto *OldVD = cast<VarDecl>(C->getCapturedVar());
13354       llvm::SmallVector<Decl*, 4> NewVDs;
13355 
13356       for (InitCaptureInfoTy &Info : NewC.Expansions) {
13357         ExprResult Init = Info.first;
13358         QualType InitQualType = Info.second;
13359         if (Init.isInvalid() || InitQualType.isNull()) {
13360           Invalid = true;
13361           break;
13362         }
13363         VarDecl *NewVD = getSema().createLambdaInitCaptureVarDecl(
13364             OldVD->getLocation(), InitQualType, NewC.EllipsisLoc,
13365             OldVD->getIdentifier(), OldVD->getInitStyle(), Init.get());
13366         if (!NewVD) {
13367           Invalid = true;
13368           break;
13369         }
13370         NewVDs.push_back(NewVD);
13371         getSema().addInitCapture(LSI, NewVD, C->getCaptureKind() == LCK_ByRef);
13372       }
13373 
13374       if (Invalid)
13375         break;
13376 
13377       getDerived().transformedLocalDecl(OldVD, NewVDs);
13378       continue;
13379     }
13380 
13381     assert(C->capturesVariable() && "unexpected kind of lambda capture");
13382 
13383     // Determine the capture kind for Sema.
13384     Sema::TryCaptureKind Kind
13385       = C->isImplicit()? Sema::TryCapture_Implicit
13386                        : C->getCaptureKind() == LCK_ByCopy
13387                            ? Sema::TryCapture_ExplicitByVal
13388                            : Sema::TryCapture_ExplicitByRef;
13389     SourceLocation EllipsisLoc;
13390     if (C->isPackExpansion()) {
13391       UnexpandedParameterPack Unexpanded(C->getCapturedVar(), C->getLocation());
13392       bool ShouldExpand = false;
13393       bool RetainExpansion = false;
13394       std::optional<unsigned> NumExpansions;
13395       if (getDerived().TryExpandParameterPacks(C->getEllipsisLoc(),
13396                                                C->getLocation(),
13397                                                Unexpanded,
13398                                                ShouldExpand, RetainExpansion,
13399                                                NumExpansions)) {
13400         Invalid = true;
13401         continue;
13402       }
13403 
13404       if (ShouldExpand) {
13405         // The transform has determined that we should perform an expansion;
13406         // transform and capture each of the arguments.
13407         // expansion of the pattern. Do so.
13408         auto *Pack = cast<VarDecl>(C->getCapturedVar());
13409         for (unsigned I = 0; I != *NumExpansions; ++I) {
13410           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
13411           VarDecl *CapturedVar
13412             = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
13413                                                                Pack));
13414           if (!CapturedVar) {
13415             Invalid = true;
13416             continue;
13417           }
13418 
13419           // Capture the transformed variable.
13420           getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind);
13421         }
13422 
13423         // FIXME: Retain a pack expansion if RetainExpansion is true.
13424 
13425         continue;
13426       }
13427 
13428       EllipsisLoc = C->getEllipsisLoc();
13429     }
13430 
13431     // Transform the captured variable.
13432     auto *CapturedVar = cast_or_null<ValueDecl>(
13433         getDerived().TransformDecl(C->getLocation(), C->getCapturedVar()));
13434     if (!CapturedVar || CapturedVar->isInvalidDecl()) {
13435       Invalid = true;
13436       continue;
13437     }
13438 
13439     // Capture the transformed variable.
13440     getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind,
13441                                  EllipsisLoc);
13442   }
13443   getSema().finishLambdaExplicitCaptures(LSI);
13444 
13445   // FIXME: Sema's lambda-building mechanism expects us to push an expression
13446   // evaluation context even if we're not transforming the function body.
13447   getSema().PushExpressionEvaluationContext(
13448       Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
13449 
13450   // Instantiate the body of the lambda expression.
13451   StmtResult Body =
13452       Invalid ? StmtError() : getDerived().TransformLambdaBody(E, E->getBody());
13453 
13454   // ActOnLambda* will pop the function scope for us.
13455   FuncScopeCleanup.disable();
13456 
13457   if (Body.isInvalid()) {
13458     SavedContext.pop();
13459     getSema().ActOnLambdaError(E->getBeginLoc(), /*CurScope=*/nullptr,
13460                                /*IsInstantiation=*/true);
13461     return ExprError();
13462   }
13463 
13464   // Copy the LSI before ActOnFinishFunctionBody removes it.
13465   // FIXME: This is dumb. Store the lambda information somewhere that outlives
13466   // the call operator.
13467   auto LSICopy = *LSI;
13468   getSema().ActOnFinishFunctionBody(NewCallOperator, Body.get(),
13469                                     /*IsInstantiation*/ true);
13470   SavedContext.pop();
13471 
13472   return getSema().BuildLambdaExpr(E->getBeginLoc(), Body.get()->getEndLoc(),
13473                                    &LSICopy);
13474 }
13475 
13476 template<typename Derived>
13477 StmtResult
13478 TreeTransform<Derived>::TransformLambdaBody(LambdaExpr *E, Stmt *S) {
13479   return TransformStmt(S);
13480 }
13481 
13482 template<typename Derived>
13483 StmtResult
13484 TreeTransform<Derived>::SkipLambdaBody(LambdaExpr *E, Stmt *S) {
13485   // Transform captures.
13486   for (LambdaExpr::capture_iterator C = E->capture_begin(),
13487                                  CEnd = E->capture_end();
13488        C != CEnd; ++C) {
13489     // When we hit the first implicit capture, tell Sema that we've finished
13490     // the list of explicit captures.
13491     if (!C->isImplicit())
13492       continue;
13493 
13494     // Capturing 'this' is trivial.
13495     if (C->capturesThis()) {
13496       getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit(),
13497                                     /*BuildAndDiagnose*/ true, nullptr,
13498                                     C->getCaptureKind() == LCK_StarThis);
13499       continue;
13500     }
13501     // Captured expression will be recaptured during captured variables
13502     // rebuilding.
13503     if (C->capturesVLAType())
13504       continue;
13505 
13506     assert(C->capturesVariable() && "unexpected kind of lambda capture");
13507     assert(!E->isInitCapture(C) && "implicit init-capture?");
13508 
13509     // Transform the captured variable.
13510     VarDecl *CapturedVar = cast_or_null<VarDecl>(
13511         getDerived().TransformDecl(C->getLocation(), C->getCapturedVar()));
13512     if (!CapturedVar || CapturedVar->isInvalidDecl())
13513       return StmtError();
13514 
13515     // Capture the transformed variable.
13516     getSema().tryCaptureVariable(CapturedVar, C->getLocation());
13517   }
13518 
13519   return S;
13520 }
13521 
13522 template<typename Derived>
13523 ExprResult
13524 TreeTransform<Derived>::TransformCXXUnresolvedConstructExpr(
13525                                                   CXXUnresolvedConstructExpr *E) {
13526   TypeSourceInfo *T =
13527       getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
13528   if (!T)
13529     return ExprError();
13530 
13531   bool ArgumentChanged = false;
13532   SmallVector<Expr*, 8> Args;
13533   Args.reserve(E->getNumArgs());
13534   {
13535     EnterExpressionEvaluationContext Context(
13536         getSema(), EnterExpressionEvaluationContext::InitList,
13537         E->isListInitialization());
13538     if (getDerived().TransformExprs(E->arg_begin(), E->getNumArgs(), true, Args,
13539                                     &ArgumentChanged))
13540       return ExprError();
13541   }
13542 
13543   if (!getDerived().AlwaysRebuild() &&
13544       T == E->getTypeSourceInfo() &&
13545       !ArgumentChanged)
13546     return E;
13547 
13548   // FIXME: we're faking the locations of the commas
13549   return getDerived().RebuildCXXUnresolvedConstructExpr(
13550       T, E->getLParenLoc(), Args, E->getRParenLoc(), E->isListInitialization());
13551 }
13552 
13553 template<typename Derived>
13554 ExprResult
13555 TreeTransform<Derived>::TransformCXXDependentScopeMemberExpr(
13556                                              CXXDependentScopeMemberExpr *E) {
13557   // Transform the base of the expression.
13558   ExprResult Base((Expr*) nullptr);
13559   Expr *OldBase;
13560   QualType BaseType;
13561   QualType ObjectType;
13562   if (!E->isImplicitAccess()) {
13563     OldBase = E->getBase();
13564     Base = getDerived().TransformExpr(OldBase);
13565     if (Base.isInvalid())
13566       return ExprError();
13567 
13568     // Start the member reference and compute the object's type.
13569     ParsedType ObjectTy;
13570     bool MayBePseudoDestructor = false;
13571     Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
13572                                                 E->getOperatorLoc(),
13573                                       E->isArrow()? tok::arrow : tok::period,
13574                                                 ObjectTy,
13575                                                 MayBePseudoDestructor);
13576     if (Base.isInvalid())
13577       return ExprError();
13578 
13579     ObjectType = ObjectTy.get();
13580     BaseType = ((Expr*) Base.get())->getType();
13581   } else {
13582     OldBase = nullptr;
13583     BaseType = getDerived().TransformType(E->getBaseType());
13584     ObjectType = BaseType->castAs<PointerType>()->getPointeeType();
13585   }
13586 
13587   // Transform the first part of the nested-name-specifier that qualifies
13588   // the member name.
13589   NamedDecl *FirstQualifierInScope
13590     = getDerived().TransformFirstQualifierInScope(
13591                                             E->getFirstQualifierFoundInScope(),
13592                                             E->getQualifierLoc().getBeginLoc());
13593 
13594   NestedNameSpecifierLoc QualifierLoc;
13595   if (E->getQualifier()) {
13596     QualifierLoc
13597       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc(),
13598                                                      ObjectType,
13599                                                      FirstQualifierInScope);
13600     if (!QualifierLoc)
13601       return ExprError();
13602   }
13603 
13604   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
13605 
13606   // TODO: If this is a conversion-function-id, verify that the
13607   // destination type name (if present) resolves the same way after
13608   // instantiation as it did in the local scope.
13609 
13610   DeclarationNameInfo NameInfo
13611     = getDerived().TransformDeclarationNameInfo(E->getMemberNameInfo());
13612   if (!NameInfo.getName())
13613     return ExprError();
13614 
13615   if (!E->hasExplicitTemplateArgs()) {
13616     // This is a reference to a member without an explicitly-specified
13617     // template argument list. Optimize for this common case.
13618     if (!getDerived().AlwaysRebuild() &&
13619         Base.get() == OldBase &&
13620         BaseType == E->getBaseType() &&
13621         QualifierLoc == E->getQualifierLoc() &&
13622         NameInfo.getName() == E->getMember() &&
13623         FirstQualifierInScope == E->getFirstQualifierFoundInScope())
13624       return E;
13625 
13626     return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
13627                                                        BaseType,
13628                                                        E->isArrow(),
13629                                                        E->getOperatorLoc(),
13630                                                        QualifierLoc,
13631                                                        TemplateKWLoc,
13632                                                        FirstQualifierInScope,
13633                                                        NameInfo,
13634                                                        /*TemplateArgs*/nullptr);
13635   }
13636 
13637   TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
13638   if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
13639                                               E->getNumTemplateArgs(),
13640                                               TransArgs))
13641     return ExprError();
13642 
13643   return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
13644                                                      BaseType,
13645                                                      E->isArrow(),
13646                                                      E->getOperatorLoc(),
13647                                                      QualifierLoc,
13648                                                      TemplateKWLoc,
13649                                                      FirstQualifierInScope,
13650                                                      NameInfo,
13651                                                      &TransArgs);
13652 }
13653 
13654 template <typename Derived>
13655 ExprResult TreeTransform<Derived>::TransformUnresolvedMemberExpr(
13656     UnresolvedMemberExpr *Old) {
13657   // Transform the base of the expression.
13658   ExprResult Base((Expr *)nullptr);
13659   QualType BaseType;
13660   if (!Old->isImplicitAccess()) {
13661     Base = getDerived().TransformExpr(Old->getBase());
13662     if (Base.isInvalid())
13663       return ExprError();
13664     Base =
13665         getSema().PerformMemberExprBaseConversion(Base.get(), Old->isArrow());
13666     if (Base.isInvalid())
13667       return ExprError();
13668     BaseType = Base.get()->getType();
13669   } else {
13670     BaseType = getDerived().TransformType(Old->getBaseType());
13671   }
13672 
13673   NestedNameSpecifierLoc QualifierLoc;
13674   if (Old->getQualifierLoc()) {
13675     QualifierLoc =
13676         getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
13677     if (!QualifierLoc)
13678       return ExprError();
13679   }
13680 
13681   SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
13682 
13683   LookupResult R(SemaRef, Old->getMemberNameInfo(), Sema::LookupOrdinaryName);
13684 
13685   // Transform the declaration set.
13686   if (TransformOverloadExprDecls(Old, /*RequiresADL*/ false, R))
13687     return ExprError();
13688 
13689   // Determine the naming class.
13690   if (Old->getNamingClass()) {
13691     CXXRecordDecl *NamingClass = cast_or_null<CXXRecordDecl>(
13692         getDerived().TransformDecl(Old->getMemberLoc(), Old->getNamingClass()));
13693     if (!NamingClass)
13694       return ExprError();
13695 
13696     R.setNamingClass(NamingClass);
13697   }
13698 
13699   TemplateArgumentListInfo TransArgs;
13700   if (Old->hasExplicitTemplateArgs()) {
13701     TransArgs.setLAngleLoc(Old->getLAngleLoc());
13702     TransArgs.setRAngleLoc(Old->getRAngleLoc());
13703     if (getDerived().TransformTemplateArguments(
13704             Old->getTemplateArgs(), Old->getNumTemplateArgs(), TransArgs))
13705       return ExprError();
13706   }
13707 
13708   // FIXME: to do this check properly, we will need to preserve the
13709   // first-qualifier-in-scope here, just in case we had a dependent
13710   // base (and therefore couldn't do the check) and a
13711   // nested-name-qualifier (and therefore could do the lookup).
13712   NamedDecl *FirstQualifierInScope = nullptr;
13713 
13714   return getDerived().RebuildUnresolvedMemberExpr(
13715       Base.get(), BaseType, Old->getOperatorLoc(), Old->isArrow(), QualifierLoc,
13716       TemplateKWLoc, FirstQualifierInScope, R,
13717       (Old->hasExplicitTemplateArgs() ? &TransArgs : nullptr));
13718 }
13719 
13720 template<typename Derived>
13721 ExprResult
13722 TreeTransform<Derived>::TransformCXXNoexceptExpr(CXXNoexceptExpr *E) {
13723   EnterExpressionEvaluationContext Unevaluated(
13724       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
13725   ExprResult SubExpr = getDerived().TransformExpr(E->getOperand());
13726   if (SubExpr.isInvalid())
13727     return ExprError();
13728 
13729   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getOperand())
13730     return E;
13731 
13732   return getDerived().RebuildCXXNoexceptExpr(E->getSourceRange(),SubExpr.get());
13733 }
13734 
13735 template<typename Derived>
13736 ExprResult
13737 TreeTransform<Derived>::TransformPackExpansionExpr(PackExpansionExpr *E) {
13738   ExprResult Pattern = getDerived().TransformExpr(E->getPattern());
13739   if (Pattern.isInvalid())
13740     return ExprError();
13741 
13742   if (!getDerived().AlwaysRebuild() && Pattern.get() == E->getPattern())
13743     return E;
13744 
13745   return getDerived().RebuildPackExpansion(Pattern.get(), E->getEllipsisLoc(),
13746                                            E->getNumExpansions());
13747 }
13748 
13749 template<typename Derived>
13750 ExprResult
13751 TreeTransform<Derived>::TransformSizeOfPackExpr(SizeOfPackExpr *E) {
13752   // If E is not value-dependent, then nothing will change when we transform it.
13753   // Note: This is an instantiation-centric view.
13754   if (!E->isValueDependent())
13755     return E;
13756 
13757   EnterExpressionEvaluationContext Unevaluated(
13758       getSema(), Sema::ExpressionEvaluationContext::Unevaluated);
13759 
13760   ArrayRef<TemplateArgument> PackArgs;
13761   TemplateArgument ArgStorage;
13762 
13763   // Find the argument list to transform.
13764   if (E->isPartiallySubstituted()) {
13765     PackArgs = E->getPartialArguments();
13766   } else if (E->isValueDependent()) {
13767     UnexpandedParameterPack Unexpanded(E->getPack(), E->getPackLoc());
13768     bool ShouldExpand = false;
13769     bool RetainExpansion = false;
13770     std::optional<unsigned> NumExpansions;
13771     if (getDerived().TryExpandParameterPacks(E->getOperatorLoc(), E->getPackLoc(),
13772                                              Unexpanded,
13773                                              ShouldExpand, RetainExpansion,
13774                                              NumExpansions))
13775       return ExprError();
13776 
13777     // If we need to expand the pack, build a template argument from it and
13778     // expand that.
13779     if (ShouldExpand) {
13780       auto *Pack = E->getPack();
13781       if (auto *TTPD = dyn_cast<TemplateTypeParmDecl>(Pack)) {
13782         ArgStorage = getSema().Context.getPackExpansionType(
13783             getSema().Context.getTypeDeclType(TTPD), std::nullopt);
13784       } else if (auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Pack)) {
13785         ArgStorage = TemplateArgument(TemplateName(TTPD), std::nullopt);
13786       } else {
13787         auto *VD = cast<ValueDecl>(Pack);
13788         ExprResult DRE = getSema().BuildDeclRefExpr(
13789             VD, VD->getType().getNonLValueExprType(getSema().Context),
13790             VD->getType()->isReferenceType() ? VK_LValue : VK_PRValue,
13791             E->getPackLoc());
13792         if (DRE.isInvalid())
13793           return ExprError();
13794         ArgStorage = new (getSema().Context)
13795             PackExpansionExpr(getSema().Context.DependentTy, DRE.get(),
13796                               E->getPackLoc(), std::nullopt);
13797       }
13798       PackArgs = ArgStorage;
13799     }
13800   }
13801 
13802   // If we're not expanding the pack, just transform the decl.
13803   if (!PackArgs.size()) {
13804     auto *Pack = cast_or_null<NamedDecl>(
13805         getDerived().TransformDecl(E->getPackLoc(), E->getPack()));
13806     if (!Pack)
13807       return ExprError();
13808     return getDerived().RebuildSizeOfPackExpr(
13809         E->getOperatorLoc(), Pack, E->getPackLoc(), E->getRParenLoc(),
13810         std::nullopt, std::nullopt);
13811   }
13812 
13813   // Try to compute the result without performing a partial substitution.
13814   std::optional<unsigned> Result = 0;
13815   for (const TemplateArgument &Arg : PackArgs) {
13816     if (!Arg.isPackExpansion()) {
13817       Result = *Result + 1;
13818       continue;
13819     }
13820 
13821     TemplateArgumentLoc ArgLoc;
13822     InventTemplateArgumentLoc(Arg, ArgLoc);
13823 
13824     // Find the pattern of the pack expansion.
13825     SourceLocation Ellipsis;
13826     std::optional<unsigned> OrigNumExpansions;
13827     TemplateArgumentLoc Pattern =
13828         getSema().getTemplateArgumentPackExpansionPattern(ArgLoc, Ellipsis,
13829                                                           OrigNumExpansions);
13830 
13831     // Substitute under the pack expansion. Do not expand the pack (yet).
13832     TemplateArgumentLoc OutPattern;
13833     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
13834     if (getDerived().TransformTemplateArgument(Pattern, OutPattern,
13835                                                /*Uneval*/ true))
13836       return true;
13837 
13838     // See if we can determine the number of arguments from the result.
13839     std::optional<unsigned> NumExpansions =
13840         getSema().getFullyPackExpandedSize(OutPattern.getArgument());
13841     if (!NumExpansions) {
13842       // No: we must be in an alias template expansion, and we're going to need
13843       // to actually expand the packs.
13844       Result = std::nullopt;
13845       break;
13846     }
13847 
13848     Result = *Result + *NumExpansions;
13849   }
13850 
13851   // Common case: we could determine the number of expansions without
13852   // substituting.
13853   if (Result)
13854     return getDerived().RebuildSizeOfPackExpr(
13855         E->getOperatorLoc(), E->getPack(), E->getPackLoc(), E->getRParenLoc(),
13856         *Result, std::nullopt);
13857 
13858   TemplateArgumentListInfo TransformedPackArgs(E->getPackLoc(),
13859                                                E->getPackLoc());
13860   {
13861     TemporaryBase Rebase(*this, E->getPackLoc(), getBaseEntity());
13862     typedef TemplateArgumentLocInventIterator<
13863         Derived, const TemplateArgument*> PackLocIterator;
13864     if (TransformTemplateArguments(PackLocIterator(*this, PackArgs.begin()),
13865                                    PackLocIterator(*this, PackArgs.end()),
13866                                    TransformedPackArgs, /*Uneval*/true))
13867       return ExprError();
13868   }
13869 
13870   // Check whether we managed to fully-expand the pack.
13871   // FIXME: Is it possible for us to do so and not hit the early exit path?
13872   SmallVector<TemplateArgument, 8> Args;
13873   bool PartialSubstitution = false;
13874   for (auto &Loc : TransformedPackArgs.arguments()) {
13875     Args.push_back(Loc.getArgument());
13876     if (Loc.getArgument().isPackExpansion())
13877       PartialSubstitution = true;
13878   }
13879 
13880   if (PartialSubstitution)
13881     return getDerived().RebuildSizeOfPackExpr(
13882         E->getOperatorLoc(), E->getPack(), E->getPackLoc(), E->getRParenLoc(),
13883         std::nullopt, Args);
13884 
13885   return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
13886                                             E->getPackLoc(), E->getRParenLoc(),
13887                                             Args.size(), std::nullopt);
13888 }
13889 
13890 template<typename Derived>
13891 ExprResult
13892 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmPackExpr(
13893                                           SubstNonTypeTemplateParmPackExpr *E) {
13894   // Default behavior is to do nothing with this transformation.
13895   return E;
13896 }
13897 
13898 template<typename Derived>
13899 ExprResult
13900 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmExpr(
13901                                           SubstNonTypeTemplateParmExpr *E) {
13902   // Default behavior is to do nothing with this transformation.
13903   return E;
13904 }
13905 
13906 template<typename Derived>
13907 ExprResult
13908 TreeTransform<Derived>::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
13909   // Default behavior is to do nothing with this transformation.
13910   return E;
13911 }
13912 
13913 template<typename Derived>
13914 ExprResult
13915 TreeTransform<Derived>::TransformMaterializeTemporaryExpr(
13916                                                   MaterializeTemporaryExpr *E) {
13917   return getDerived().TransformExpr(E->getSubExpr());
13918 }
13919 
13920 template<typename Derived>
13921 ExprResult
13922 TreeTransform<Derived>::TransformCXXFoldExpr(CXXFoldExpr *E) {
13923   UnresolvedLookupExpr *Callee = nullptr;
13924   if (Expr *OldCallee = E->getCallee()) {
13925     ExprResult CalleeResult = getDerived().TransformExpr(OldCallee);
13926     if (CalleeResult.isInvalid())
13927       return ExprError();
13928     Callee = cast<UnresolvedLookupExpr>(CalleeResult.get());
13929   }
13930 
13931   Expr *Pattern = E->getPattern();
13932 
13933   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13934   getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
13935   assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
13936 
13937   // Determine whether the set of unexpanded parameter packs can and should
13938   // be expanded.
13939   bool Expand = true;
13940   bool RetainExpansion = false;
13941   std::optional<unsigned> OrigNumExpansions = E->getNumExpansions(),
13942                           NumExpansions = OrigNumExpansions;
13943   if (getDerived().TryExpandParameterPacks(E->getEllipsisLoc(),
13944                                            Pattern->getSourceRange(),
13945                                            Unexpanded,
13946                                            Expand, RetainExpansion,
13947                                            NumExpansions))
13948     return true;
13949 
13950   if (!Expand) {
13951     // Do not expand any packs here, just transform and rebuild a fold
13952     // expression.
13953     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
13954 
13955     ExprResult LHS =
13956         E->getLHS() ? getDerived().TransformExpr(E->getLHS()) : ExprResult();
13957     if (LHS.isInvalid())
13958       return true;
13959 
13960     ExprResult RHS =
13961         E->getRHS() ? getDerived().TransformExpr(E->getRHS()) : ExprResult();
13962     if (RHS.isInvalid())
13963       return true;
13964 
13965     if (!getDerived().AlwaysRebuild() &&
13966         LHS.get() == E->getLHS() && RHS.get() == E->getRHS())
13967       return E;
13968 
13969     return getDerived().RebuildCXXFoldExpr(
13970         Callee, E->getBeginLoc(), LHS.get(), E->getOperator(),
13971         E->getEllipsisLoc(), RHS.get(), E->getEndLoc(), NumExpansions);
13972   }
13973 
13974   // Formally a fold expression expands to nested parenthesized expressions.
13975   // Enforce this limit to avoid creating trees so deep we can't safely traverse
13976   // them.
13977   if (NumExpansions && SemaRef.getLangOpts().BracketDepth < NumExpansions) {
13978     SemaRef.Diag(E->getEllipsisLoc(),
13979                  clang::diag::err_fold_expression_limit_exceeded)
13980         << *NumExpansions << SemaRef.getLangOpts().BracketDepth
13981         << E->getSourceRange();
13982     SemaRef.Diag(E->getEllipsisLoc(), diag::note_bracket_depth);
13983     return ExprError();
13984   }
13985 
13986   // The transform has determined that we should perform an elementwise
13987   // expansion of the pattern. Do so.
13988   ExprResult Result = getDerived().TransformExpr(E->getInit());
13989   if (Result.isInvalid())
13990     return true;
13991   bool LeftFold = E->isLeftFold();
13992 
13993   // If we're retaining an expansion for a right fold, it is the innermost
13994   // component and takes the init (if any).
13995   if (!LeftFold && RetainExpansion) {
13996     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
13997 
13998     ExprResult Out = getDerived().TransformExpr(Pattern);
13999     if (Out.isInvalid())
14000       return true;
14001 
14002     Result = getDerived().RebuildCXXFoldExpr(
14003         Callee, E->getBeginLoc(), Out.get(), E->getOperator(),
14004         E->getEllipsisLoc(), Result.get(), E->getEndLoc(), OrigNumExpansions);
14005     if (Result.isInvalid())
14006       return true;
14007   }
14008 
14009   for (unsigned I = 0; I != *NumExpansions; ++I) {
14010     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(
14011         getSema(), LeftFold ? I : *NumExpansions - I - 1);
14012     ExprResult Out = getDerived().TransformExpr(Pattern);
14013     if (Out.isInvalid())
14014       return true;
14015 
14016     if (Out.get()->containsUnexpandedParameterPack()) {
14017       // We still have a pack; retain a pack expansion for this slice.
14018       Result = getDerived().RebuildCXXFoldExpr(
14019           Callee, E->getBeginLoc(), LeftFold ? Result.get() : Out.get(),
14020           E->getOperator(), E->getEllipsisLoc(),
14021           LeftFold ? Out.get() : Result.get(), E->getEndLoc(),
14022           OrigNumExpansions);
14023     } else if (Result.isUsable()) {
14024       // We've got down to a single element; build a binary operator.
14025       Expr *LHS = LeftFold ? Result.get() : Out.get();
14026       Expr *RHS = LeftFold ? Out.get() : Result.get();
14027       if (Callee)
14028         Result = getDerived().RebuildCXXOperatorCallExpr(
14029             BinaryOperator::getOverloadedOperator(E->getOperator()),
14030             E->getEllipsisLoc(), Callee, LHS, RHS);
14031       else
14032         Result = getDerived().RebuildBinaryOperator(E->getEllipsisLoc(),
14033                                                     E->getOperator(), LHS, RHS);
14034     } else
14035       Result = Out;
14036 
14037     if (Result.isInvalid())
14038       return true;
14039   }
14040 
14041   // If we're retaining an expansion for a left fold, it is the outermost
14042   // component and takes the complete expansion so far as its init (if any).
14043   if (LeftFold && RetainExpansion) {
14044     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
14045 
14046     ExprResult Out = getDerived().TransformExpr(Pattern);
14047     if (Out.isInvalid())
14048       return true;
14049 
14050     Result = getDerived().RebuildCXXFoldExpr(
14051         Callee, E->getBeginLoc(), Result.get(), E->getOperator(),
14052         E->getEllipsisLoc(), Out.get(), E->getEndLoc(), OrigNumExpansions);
14053     if (Result.isInvalid())
14054       return true;
14055   }
14056 
14057   // If we had no init and an empty pack, and we're not retaining an expansion,
14058   // then produce a fallback value or error.
14059   if (Result.isUnset())
14060     return getDerived().RebuildEmptyCXXFoldExpr(E->getEllipsisLoc(),
14061                                                 E->getOperator());
14062 
14063   return Result;
14064 }
14065 
14066 template <typename Derived>
14067 ExprResult
14068 TreeTransform<Derived>::TransformCXXParenListInitExpr(CXXParenListInitExpr *E) {
14069   SmallVector<Expr *, 4> TransformedInits;
14070   ArrayRef<Expr *> InitExprs = E->getInitExprs();
14071   if (TransformExprs(InitExprs.data(), InitExprs.size(), true,
14072                      TransformedInits))
14073     return ExprError();
14074 
14075   return getDerived().RebuildParenListExpr(E->getBeginLoc(), TransformedInits,
14076                                            E->getEndLoc());
14077 }
14078 
14079 template<typename Derived>
14080 ExprResult
14081 TreeTransform<Derived>::TransformCXXStdInitializerListExpr(
14082     CXXStdInitializerListExpr *E) {
14083   return getDerived().TransformExpr(E->getSubExpr());
14084 }
14085 
14086 template<typename Derived>
14087 ExprResult
14088 TreeTransform<Derived>::TransformObjCStringLiteral(ObjCStringLiteral *E) {
14089   return SemaRef.MaybeBindToTemporary(E);
14090 }
14091 
14092 template<typename Derived>
14093 ExprResult
14094 TreeTransform<Derived>::TransformObjCBoolLiteralExpr(ObjCBoolLiteralExpr *E) {
14095   return E;
14096 }
14097 
14098 template<typename Derived>
14099 ExprResult
14100 TreeTransform<Derived>::TransformObjCBoxedExpr(ObjCBoxedExpr *E) {
14101   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
14102   if (SubExpr.isInvalid())
14103     return ExprError();
14104 
14105   if (!getDerived().AlwaysRebuild() &&
14106       SubExpr.get() == E->getSubExpr())
14107     return E;
14108 
14109   return getDerived().RebuildObjCBoxedExpr(E->getSourceRange(), SubExpr.get());
14110 }
14111 
14112 template<typename Derived>
14113 ExprResult
14114 TreeTransform<Derived>::TransformObjCArrayLiteral(ObjCArrayLiteral *E) {
14115   // Transform each of the elements.
14116   SmallVector<Expr *, 8> Elements;
14117   bool ArgChanged = false;
14118   if (getDerived().TransformExprs(E->getElements(), E->getNumElements(),
14119                                   /*IsCall=*/false, Elements, &ArgChanged))
14120     return ExprError();
14121 
14122   if (!getDerived().AlwaysRebuild() && !ArgChanged)
14123     return SemaRef.MaybeBindToTemporary(E);
14124 
14125   return getDerived().RebuildObjCArrayLiteral(E->getSourceRange(),
14126                                               Elements.data(),
14127                                               Elements.size());
14128 }
14129 
14130 template<typename Derived>
14131 ExprResult
14132 TreeTransform<Derived>::TransformObjCDictionaryLiteral(
14133                                                     ObjCDictionaryLiteral *E) {
14134   // Transform each of the elements.
14135   SmallVector<ObjCDictionaryElement, 8> Elements;
14136   bool ArgChanged = false;
14137   for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
14138     ObjCDictionaryElement OrigElement = E->getKeyValueElement(I);
14139 
14140     if (OrigElement.isPackExpansion()) {
14141       // This key/value element is a pack expansion.
14142       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
14143       getSema().collectUnexpandedParameterPacks(OrigElement.Key, Unexpanded);
14144       getSema().collectUnexpandedParameterPacks(OrigElement.Value, Unexpanded);
14145       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
14146 
14147       // Determine whether the set of unexpanded parameter packs can
14148       // and should be expanded.
14149       bool Expand = true;
14150       bool RetainExpansion = false;
14151       std::optional<unsigned> OrigNumExpansions = OrigElement.NumExpansions;
14152       std::optional<unsigned> NumExpansions = OrigNumExpansions;
14153       SourceRange PatternRange(OrigElement.Key->getBeginLoc(),
14154                                OrigElement.Value->getEndLoc());
14155       if (getDerived().TryExpandParameterPacks(OrigElement.EllipsisLoc,
14156                                                PatternRange, Unexpanded, Expand,
14157                                                RetainExpansion, NumExpansions))
14158         return ExprError();
14159 
14160       if (!Expand) {
14161         // The transform has determined that we should perform a simple
14162         // transformation on the pack expansion, producing another pack
14163         // expansion.
14164         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
14165         ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
14166         if (Key.isInvalid())
14167           return ExprError();
14168 
14169         if (Key.get() != OrigElement.Key)
14170           ArgChanged = true;
14171 
14172         ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
14173         if (Value.isInvalid())
14174           return ExprError();
14175 
14176         if (Value.get() != OrigElement.Value)
14177           ArgChanged = true;
14178 
14179         ObjCDictionaryElement Expansion = {
14180           Key.get(), Value.get(), OrigElement.EllipsisLoc, NumExpansions
14181         };
14182         Elements.push_back(Expansion);
14183         continue;
14184       }
14185 
14186       // Record right away that the argument was changed.  This needs
14187       // to happen even if the array expands to nothing.
14188       ArgChanged = true;
14189 
14190       // The transform has determined that we should perform an elementwise
14191       // expansion of the pattern. Do so.
14192       for (unsigned I = 0; I != *NumExpansions; ++I) {
14193         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
14194         ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
14195         if (Key.isInvalid())
14196           return ExprError();
14197 
14198         ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
14199         if (Value.isInvalid())
14200           return ExprError();
14201 
14202         ObjCDictionaryElement Element = {
14203           Key.get(), Value.get(), SourceLocation(), NumExpansions
14204         };
14205 
14206         // If any unexpanded parameter packs remain, we still have a
14207         // pack expansion.
14208         // FIXME: Can this really happen?
14209         if (Key.get()->containsUnexpandedParameterPack() ||
14210             Value.get()->containsUnexpandedParameterPack())
14211           Element.EllipsisLoc = OrigElement.EllipsisLoc;
14212 
14213         Elements.push_back(Element);
14214       }
14215 
14216       // FIXME: Retain a pack expansion if RetainExpansion is true.
14217 
14218       // We've finished with this pack expansion.
14219       continue;
14220     }
14221 
14222     // Transform and check key.
14223     ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
14224     if (Key.isInvalid())
14225       return ExprError();
14226 
14227     if (Key.get() != OrigElement.Key)
14228       ArgChanged = true;
14229 
14230     // Transform and check value.
14231     ExprResult Value
14232       = getDerived().TransformExpr(OrigElement.Value);
14233     if (Value.isInvalid())
14234       return ExprError();
14235 
14236     if (Value.get() != OrigElement.Value)
14237       ArgChanged = true;
14238 
14239     ObjCDictionaryElement Element = {Key.get(), Value.get(), SourceLocation(),
14240                                      std::nullopt};
14241     Elements.push_back(Element);
14242   }
14243 
14244   if (!getDerived().AlwaysRebuild() && !ArgChanged)
14245     return SemaRef.MaybeBindToTemporary(E);
14246 
14247   return getDerived().RebuildObjCDictionaryLiteral(E->getSourceRange(),
14248                                                    Elements);
14249 }
14250 
14251 template<typename Derived>
14252 ExprResult
14253 TreeTransform<Derived>::TransformObjCEncodeExpr(ObjCEncodeExpr *E) {
14254   TypeSourceInfo *EncodedTypeInfo
14255     = getDerived().TransformType(E->getEncodedTypeSourceInfo());
14256   if (!EncodedTypeInfo)
14257     return ExprError();
14258 
14259   if (!getDerived().AlwaysRebuild() &&
14260       EncodedTypeInfo == E->getEncodedTypeSourceInfo())
14261     return E;
14262 
14263   return getDerived().RebuildObjCEncodeExpr(E->getAtLoc(),
14264                                             EncodedTypeInfo,
14265                                             E->getRParenLoc());
14266 }
14267 
14268 template<typename Derived>
14269 ExprResult TreeTransform<Derived>::
14270 TransformObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr *E) {
14271   // This is a kind of implicit conversion, and it needs to get dropped
14272   // and recomputed for the same general reasons that ImplicitCastExprs
14273   // do, as well a more specific one: this expression is only valid when
14274   // it appears *immediately* as an argument expression.
14275   return getDerived().TransformExpr(E->getSubExpr());
14276 }
14277 
14278 template<typename Derived>
14279 ExprResult TreeTransform<Derived>::
14280 TransformObjCBridgedCastExpr(ObjCBridgedCastExpr *E) {
14281   TypeSourceInfo *TSInfo
14282     = getDerived().TransformType(E->getTypeInfoAsWritten());
14283   if (!TSInfo)
14284     return ExprError();
14285 
14286   ExprResult Result = getDerived().TransformExpr(E->getSubExpr());
14287   if (Result.isInvalid())
14288     return ExprError();
14289 
14290   if (!getDerived().AlwaysRebuild() &&
14291       TSInfo == E->getTypeInfoAsWritten() &&
14292       Result.get() == E->getSubExpr())
14293     return E;
14294 
14295   return SemaRef.BuildObjCBridgedCast(E->getLParenLoc(), E->getBridgeKind(),
14296                                       E->getBridgeKeywordLoc(), TSInfo,
14297                                       Result.get());
14298 }
14299 
14300 template <typename Derived>
14301 ExprResult TreeTransform<Derived>::TransformObjCAvailabilityCheckExpr(
14302     ObjCAvailabilityCheckExpr *E) {
14303   return E;
14304 }
14305 
14306 template<typename Derived>
14307 ExprResult
14308 TreeTransform<Derived>::TransformObjCMessageExpr(ObjCMessageExpr *E) {
14309   // Transform arguments.
14310   bool ArgChanged = false;
14311   SmallVector<Expr*, 8> Args;
14312   Args.reserve(E->getNumArgs());
14313   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), false, Args,
14314                                   &ArgChanged))
14315     return ExprError();
14316 
14317   if (E->getReceiverKind() == ObjCMessageExpr::Class) {
14318     // Class message: transform the receiver type.
14319     TypeSourceInfo *ReceiverTypeInfo
14320       = getDerived().TransformType(E->getClassReceiverTypeInfo());
14321     if (!ReceiverTypeInfo)
14322       return ExprError();
14323 
14324     // If nothing changed, just retain the existing message send.
14325     if (!getDerived().AlwaysRebuild() &&
14326         ReceiverTypeInfo == E->getClassReceiverTypeInfo() && !ArgChanged)
14327       return SemaRef.MaybeBindToTemporary(E);
14328 
14329     // Build a new class message send.
14330     SmallVector<SourceLocation, 16> SelLocs;
14331     E->getSelectorLocs(SelLocs);
14332     return getDerived().RebuildObjCMessageExpr(ReceiverTypeInfo,
14333                                                E->getSelector(),
14334                                                SelLocs,
14335                                                E->getMethodDecl(),
14336                                                E->getLeftLoc(),
14337                                                Args,
14338                                                E->getRightLoc());
14339   }
14340   else if (E->getReceiverKind() == ObjCMessageExpr::SuperClass ||
14341            E->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
14342     if (!E->getMethodDecl())
14343       return ExprError();
14344 
14345     // Build a new class message send to 'super'.
14346     SmallVector<SourceLocation, 16> SelLocs;
14347     E->getSelectorLocs(SelLocs);
14348     return getDerived().RebuildObjCMessageExpr(E->getSuperLoc(),
14349                                                E->getSelector(),
14350                                                SelLocs,
14351                                                E->getReceiverType(),
14352                                                E->getMethodDecl(),
14353                                                E->getLeftLoc(),
14354                                                Args,
14355                                                E->getRightLoc());
14356   }
14357 
14358   // Instance message: transform the receiver
14359   assert(E->getReceiverKind() == ObjCMessageExpr::Instance &&
14360          "Only class and instance messages may be instantiated");
14361   ExprResult Receiver
14362     = getDerived().TransformExpr(E->getInstanceReceiver());
14363   if (Receiver.isInvalid())
14364     return ExprError();
14365 
14366   // If nothing changed, just retain the existing message send.
14367   if (!getDerived().AlwaysRebuild() &&
14368       Receiver.get() == E->getInstanceReceiver() && !ArgChanged)
14369     return SemaRef.MaybeBindToTemporary(E);
14370 
14371   // Build a new instance message send.
14372   SmallVector<SourceLocation, 16> SelLocs;
14373   E->getSelectorLocs(SelLocs);
14374   return getDerived().RebuildObjCMessageExpr(Receiver.get(),
14375                                              E->getSelector(),
14376                                              SelLocs,
14377                                              E->getMethodDecl(),
14378                                              E->getLeftLoc(),
14379                                              Args,
14380                                              E->getRightLoc());
14381 }
14382 
14383 template<typename Derived>
14384 ExprResult
14385 TreeTransform<Derived>::TransformObjCSelectorExpr(ObjCSelectorExpr *E) {
14386   return E;
14387 }
14388 
14389 template<typename Derived>
14390 ExprResult
14391 TreeTransform<Derived>::TransformObjCProtocolExpr(ObjCProtocolExpr *E) {
14392   return E;
14393 }
14394 
14395 template<typename Derived>
14396 ExprResult
14397 TreeTransform<Derived>::TransformObjCIvarRefExpr(ObjCIvarRefExpr *E) {
14398   // Transform the base expression.
14399   ExprResult Base = getDerived().TransformExpr(E->getBase());
14400   if (Base.isInvalid())
14401     return ExprError();
14402 
14403   // We don't need to transform the ivar; it will never change.
14404 
14405   // If nothing changed, just retain the existing expression.
14406   if (!getDerived().AlwaysRebuild() &&
14407       Base.get() == E->getBase())
14408     return E;
14409 
14410   return getDerived().RebuildObjCIvarRefExpr(Base.get(), E->getDecl(),
14411                                              E->getLocation(),
14412                                              E->isArrow(), E->isFreeIvar());
14413 }
14414 
14415 template<typename Derived>
14416 ExprResult
14417 TreeTransform<Derived>::TransformObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
14418   // 'super' and types never change. Property never changes. Just
14419   // retain the existing expression.
14420   if (!E->isObjectReceiver())
14421     return E;
14422 
14423   // Transform the base expression.
14424   ExprResult Base = getDerived().TransformExpr(E->getBase());
14425   if (Base.isInvalid())
14426     return ExprError();
14427 
14428   // We don't need to transform the property; it will never change.
14429 
14430   // If nothing changed, just retain the existing expression.
14431   if (!getDerived().AlwaysRebuild() &&
14432       Base.get() == E->getBase())
14433     return E;
14434 
14435   if (E->isExplicitProperty())
14436     return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
14437                                                    E->getExplicitProperty(),
14438                                                    E->getLocation());
14439 
14440   return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
14441                                                  SemaRef.Context.PseudoObjectTy,
14442                                                  E->getImplicitPropertyGetter(),
14443                                                  E->getImplicitPropertySetter(),
14444                                                  E->getLocation());
14445 }
14446 
14447 template<typename Derived>
14448 ExprResult
14449 TreeTransform<Derived>::TransformObjCSubscriptRefExpr(ObjCSubscriptRefExpr *E) {
14450   // Transform the base expression.
14451   ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
14452   if (Base.isInvalid())
14453     return ExprError();
14454 
14455   // Transform the key expression.
14456   ExprResult Key = getDerived().TransformExpr(E->getKeyExpr());
14457   if (Key.isInvalid())
14458     return ExprError();
14459 
14460   // If nothing changed, just retain the existing expression.
14461   if (!getDerived().AlwaysRebuild() &&
14462       Key.get() == E->getKeyExpr() && Base.get() == E->getBaseExpr())
14463     return E;
14464 
14465   return getDerived().RebuildObjCSubscriptRefExpr(E->getRBracket(),
14466                                                   Base.get(), Key.get(),
14467                                                   E->getAtIndexMethodDecl(),
14468                                                   E->setAtIndexMethodDecl());
14469 }
14470 
14471 template<typename Derived>
14472 ExprResult
14473 TreeTransform<Derived>::TransformObjCIsaExpr(ObjCIsaExpr *E) {
14474   // Transform the base expression.
14475   ExprResult Base = getDerived().TransformExpr(E->getBase());
14476   if (Base.isInvalid())
14477     return ExprError();
14478 
14479   // If nothing changed, just retain the existing expression.
14480   if (!getDerived().AlwaysRebuild() &&
14481       Base.get() == E->getBase())
14482     return E;
14483 
14484   return getDerived().RebuildObjCIsaExpr(Base.get(), E->getIsaMemberLoc(),
14485                                          E->getOpLoc(),
14486                                          E->isArrow());
14487 }
14488 
14489 template<typename Derived>
14490 ExprResult
14491 TreeTransform<Derived>::TransformShuffleVectorExpr(ShuffleVectorExpr *E) {
14492   bool ArgumentChanged = false;
14493   SmallVector<Expr*, 8> SubExprs;
14494   SubExprs.reserve(E->getNumSubExprs());
14495   if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
14496                                   SubExprs, &ArgumentChanged))
14497     return ExprError();
14498 
14499   if (!getDerived().AlwaysRebuild() &&
14500       !ArgumentChanged)
14501     return E;
14502 
14503   return getDerived().RebuildShuffleVectorExpr(E->getBuiltinLoc(),
14504                                                SubExprs,
14505                                                E->getRParenLoc());
14506 }
14507 
14508 template<typename Derived>
14509 ExprResult
14510 TreeTransform<Derived>::TransformConvertVectorExpr(ConvertVectorExpr *E) {
14511   ExprResult SrcExpr = getDerived().TransformExpr(E->getSrcExpr());
14512   if (SrcExpr.isInvalid())
14513     return ExprError();
14514 
14515   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
14516   if (!Type)
14517     return ExprError();
14518 
14519   if (!getDerived().AlwaysRebuild() &&
14520       Type == E->getTypeSourceInfo() &&
14521       SrcExpr.get() == E->getSrcExpr())
14522     return E;
14523 
14524   return getDerived().RebuildConvertVectorExpr(E->getBuiltinLoc(),
14525                                                SrcExpr.get(), Type,
14526                                                E->getRParenLoc());
14527 }
14528 
14529 template<typename Derived>
14530 ExprResult
14531 TreeTransform<Derived>::TransformBlockExpr(BlockExpr *E) {
14532   BlockDecl *oldBlock = E->getBlockDecl();
14533 
14534   SemaRef.ActOnBlockStart(E->getCaretLocation(), /*Scope=*/nullptr);
14535   BlockScopeInfo *blockScope = SemaRef.getCurBlock();
14536 
14537   blockScope->TheDecl->setIsVariadic(oldBlock->isVariadic());
14538   blockScope->TheDecl->setBlockMissingReturnType(
14539                          oldBlock->blockMissingReturnType());
14540 
14541   SmallVector<ParmVarDecl*, 4> params;
14542   SmallVector<QualType, 4> paramTypes;
14543 
14544   const FunctionProtoType *exprFunctionType = E->getFunctionType();
14545 
14546   // Parameter substitution.
14547   Sema::ExtParameterInfoBuilder extParamInfos;
14548   if (getDerived().TransformFunctionTypeParams(
14549           E->getCaretLocation(), oldBlock->parameters(), nullptr,
14550           exprFunctionType->getExtParameterInfosOrNull(), paramTypes, &params,
14551           extParamInfos)) {
14552     getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
14553     return ExprError();
14554   }
14555 
14556   QualType exprResultType =
14557       getDerived().TransformType(exprFunctionType->getReturnType());
14558 
14559   auto epi = exprFunctionType->getExtProtoInfo();
14560   epi.ExtParameterInfos = extParamInfos.getPointerOrNull(paramTypes.size());
14561 
14562   QualType functionType =
14563     getDerived().RebuildFunctionProtoType(exprResultType, paramTypes, epi);
14564   blockScope->FunctionType = functionType;
14565 
14566   // Set the parameters on the block decl.
14567   if (!params.empty())
14568     blockScope->TheDecl->setParams(params);
14569 
14570   if (!oldBlock->blockMissingReturnType()) {
14571     blockScope->HasImplicitReturnType = false;
14572     blockScope->ReturnType = exprResultType;
14573   }
14574 
14575   // Transform the body
14576   StmtResult body = getDerived().TransformStmt(E->getBody());
14577   if (body.isInvalid()) {
14578     getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
14579     return ExprError();
14580   }
14581 
14582 #ifndef NDEBUG
14583   // In builds with assertions, make sure that we captured everything we
14584   // captured before.
14585   if (!SemaRef.getDiagnostics().hasErrorOccurred()) {
14586     for (const auto &I : oldBlock->captures()) {
14587       VarDecl *oldCapture = I.getVariable();
14588 
14589       // Ignore parameter packs.
14590       if (oldCapture->isParameterPack())
14591         continue;
14592 
14593       VarDecl *newCapture =
14594         cast<VarDecl>(getDerived().TransformDecl(E->getCaretLocation(),
14595                                                  oldCapture));
14596       assert(blockScope->CaptureMap.count(newCapture));
14597     }
14598     assert(oldBlock->capturesCXXThis() == blockScope->isCXXThisCaptured());
14599   }
14600 #endif
14601 
14602   return SemaRef.ActOnBlockStmtExpr(E->getCaretLocation(), body.get(),
14603                                     /*Scope=*/nullptr);
14604 }
14605 
14606 template<typename Derived>
14607 ExprResult
14608 TreeTransform<Derived>::TransformAsTypeExpr(AsTypeExpr *E) {
14609   ExprResult SrcExpr = getDerived().TransformExpr(E->getSrcExpr());
14610   if (SrcExpr.isInvalid())
14611     return ExprError();
14612 
14613   QualType Type = getDerived().TransformType(E->getType());
14614 
14615   return SemaRef.BuildAsTypeExpr(SrcExpr.get(), Type, E->getBuiltinLoc(),
14616                                  E->getRParenLoc());
14617 }
14618 
14619 template<typename Derived>
14620 ExprResult
14621 TreeTransform<Derived>::TransformAtomicExpr(AtomicExpr *E) {
14622   bool ArgumentChanged = false;
14623   SmallVector<Expr*, 8> SubExprs;
14624   SubExprs.reserve(E->getNumSubExprs());
14625   if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
14626                                   SubExprs, &ArgumentChanged))
14627     return ExprError();
14628 
14629   if (!getDerived().AlwaysRebuild() &&
14630       !ArgumentChanged)
14631     return E;
14632 
14633   return getDerived().RebuildAtomicExpr(E->getBuiltinLoc(), SubExprs,
14634                                         E->getOp(), E->getRParenLoc());
14635 }
14636 
14637 //===----------------------------------------------------------------------===//
14638 // Type reconstruction
14639 //===----------------------------------------------------------------------===//
14640 
14641 template<typename Derived>
14642 QualType TreeTransform<Derived>::RebuildPointerType(QualType PointeeType,
14643                                                     SourceLocation Star) {
14644   return SemaRef.BuildPointerType(PointeeType, Star,
14645                                   getDerived().getBaseEntity());
14646 }
14647 
14648 template<typename Derived>
14649 QualType TreeTransform<Derived>::RebuildBlockPointerType(QualType PointeeType,
14650                                                          SourceLocation Star) {
14651   return SemaRef.BuildBlockPointerType(PointeeType, Star,
14652                                        getDerived().getBaseEntity());
14653 }
14654 
14655 template<typename Derived>
14656 QualType
14657 TreeTransform<Derived>::RebuildReferenceType(QualType ReferentType,
14658                                              bool WrittenAsLValue,
14659                                              SourceLocation Sigil) {
14660   return SemaRef.BuildReferenceType(ReferentType, WrittenAsLValue,
14661                                     Sigil, getDerived().getBaseEntity());
14662 }
14663 
14664 template<typename Derived>
14665 QualType
14666 TreeTransform<Derived>::RebuildMemberPointerType(QualType PointeeType,
14667                                                  QualType ClassType,
14668                                                  SourceLocation Sigil) {
14669   return SemaRef.BuildMemberPointerType(PointeeType, ClassType, Sigil,
14670                                         getDerived().getBaseEntity());
14671 }
14672 
14673 template<typename Derived>
14674 QualType TreeTransform<Derived>::RebuildObjCTypeParamType(
14675            const ObjCTypeParamDecl *Decl,
14676            SourceLocation ProtocolLAngleLoc,
14677            ArrayRef<ObjCProtocolDecl *> Protocols,
14678            ArrayRef<SourceLocation> ProtocolLocs,
14679            SourceLocation ProtocolRAngleLoc) {
14680   return SemaRef.BuildObjCTypeParamType(Decl,
14681                                         ProtocolLAngleLoc, Protocols,
14682                                         ProtocolLocs, ProtocolRAngleLoc,
14683                                         /*FailOnError=*/true);
14684 }
14685 
14686 template<typename Derived>
14687 QualType TreeTransform<Derived>::RebuildObjCObjectType(
14688            QualType BaseType,
14689            SourceLocation Loc,
14690            SourceLocation TypeArgsLAngleLoc,
14691            ArrayRef<TypeSourceInfo *> TypeArgs,
14692            SourceLocation TypeArgsRAngleLoc,
14693            SourceLocation ProtocolLAngleLoc,
14694            ArrayRef<ObjCProtocolDecl *> Protocols,
14695            ArrayRef<SourceLocation> ProtocolLocs,
14696            SourceLocation ProtocolRAngleLoc) {
14697   return SemaRef.BuildObjCObjectType(BaseType, Loc, TypeArgsLAngleLoc, TypeArgs,
14698                                      TypeArgsRAngleLoc, ProtocolLAngleLoc,
14699                                      Protocols, ProtocolLocs, ProtocolRAngleLoc,
14700                                      /*FailOnError=*/true,
14701                                      /*Rebuilding=*/true);
14702 }
14703 
14704 template<typename Derived>
14705 QualType TreeTransform<Derived>::RebuildObjCObjectPointerType(
14706            QualType PointeeType,
14707            SourceLocation Star) {
14708   return SemaRef.Context.getObjCObjectPointerType(PointeeType);
14709 }
14710 
14711 template<typename Derived>
14712 QualType
14713 TreeTransform<Derived>::RebuildArrayType(QualType ElementType,
14714                                          ArrayType::ArraySizeModifier SizeMod,
14715                                          const llvm::APInt *Size,
14716                                          Expr *SizeExpr,
14717                                          unsigned IndexTypeQuals,
14718                                          SourceRange BracketsRange) {
14719   if (SizeExpr || !Size)
14720     return SemaRef.BuildArrayType(ElementType, SizeMod, SizeExpr,
14721                                   IndexTypeQuals, BracketsRange,
14722                                   getDerived().getBaseEntity());
14723 
14724   QualType Types[] = {
14725     SemaRef.Context.UnsignedCharTy, SemaRef.Context.UnsignedShortTy,
14726     SemaRef.Context.UnsignedIntTy, SemaRef.Context.UnsignedLongTy,
14727     SemaRef.Context.UnsignedLongLongTy, SemaRef.Context.UnsignedInt128Ty
14728   };
14729   QualType SizeType;
14730   for (const auto &T : Types)
14731     if (Size->getBitWidth() == SemaRef.Context.getIntWidth(T)) {
14732       SizeType = T;
14733       break;
14734     }
14735 
14736   // Note that we can return a VariableArrayType here in the case where
14737   // the element type was a dependent VariableArrayType.
14738   IntegerLiteral *ArraySize
14739       = IntegerLiteral::Create(SemaRef.Context, *Size, SizeType,
14740                                /*FIXME*/BracketsRange.getBegin());
14741   return SemaRef.BuildArrayType(ElementType, SizeMod, ArraySize,
14742                                 IndexTypeQuals, BracketsRange,
14743                                 getDerived().getBaseEntity());
14744 }
14745 
14746 template<typename Derived>
14747 QualType
14748 TreeTransform<Derived>::RebuildConstantArrayType(QualType ElementType,
14749                                                  ArrayType::ArraySizeModifier SizeMod,
14750                                                  const llvm::APInt &Size,
14751                                                  Expr *SizeExpr,
14752                                                  unsigned IndexTypeQuals,
14753                                                  SourceRange BracketsRange) {
14754   return getDerived().RebuildArrayType(ElementType, SizeMod, &Size, SizeExpr,
14755                                         IndexTypeQuals, BracketsRange);
14756 }
14757 
14758 template<typename Derived>
14759 QualType
14760 TreeTransform<Derived>::RebuildIncompleteArrayType(QualType ElementType,
14761                                           ArrayType::ArraySizeModifier SizeMod,
14762                                                  unsigned IndexTypeQuals,
14763                                                    SourceRange BracketsRange) {
14764   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr, nullptr,
14765                                        IndexTypeQuals, BracketsRange);
14766 }
14767 
14768 template<typename Derived>
14769 QualType
14770 TreeTransform<Derived>::RebuildVariableArrayType(QualType ElementType,
14771                                           ArrayType::ArraySizeModifier SizeMod,
14772                                                  Expr *SizeExpr,
14773                                                  unsigned IndexTypeQuals,
14774                                                  SourceRange BracketsRange) {
14775   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
14776                                        SizeExpr,
14777                                        IndexTypeQuals, BracketsRange);
14778 }
14779 
14780 template<typename Derived>
14781 QualType
14782 TreeTransform<Derived>::RebuildDependentSizedArrayType(QualType ElementType,
14783                                           ArrayType::ArraySizeModifier SizeMod,
14784                                                        Expr *SizeExpr,
14785                                                        unsigned IndexTypeQuals,
14786                                                    SourceRange BracketsRange) {
14787   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
14788                                        SizeExpr,
14789                                        IndexTypeQuals, BracketsRange);
14790 }
14791 
14792 template <typename Derived>
14793 QualType TreeTransform<Derived>::RebuildDependentAddressSpaceType(
14794     QualType PointeeType, Expr *AddrSpaceExpr, SourceLocation AttributeLoc) {
14795   return SemaRef.BuildAddressSpaceAttr(PointeeType, AddrSpaceExpr,
14796                                           AttributeLoc);
14797 }
14798 
14799 template <typename Derived>
14800 QualType
14801 TreeTransform<Derived>::RebuildVectorType(QualType ElementType,
14802                                           unsigned NumElements,
14803                                           VectorType::VectorKind VecKind) {
14804   // FIXME: semantic checking!
14805   return SemaRef.Context.getVectorType(ElementType, NumElements, VecKind);
14806 }
14807 
14808 template <typename Derived>
14809 QualType TreeTransform<Derived>::RebuildDependentVectorType(
14810     QualType ElementType, Expr *SizeExpr, SourceLocation AttributeLoc,
14811     VectorType::VectorKind VecKind) {
14812   return SemaRef.BuildVectorType(ElementType, SizeExpr, AttributeLoc);
14813 }
14814 
14815 template<typename Derived>
14816 QualType TreeTransform<Derived>::RebuildExtVectorType(QualType ElementType,
14817                                                       unsigned NumElements,
14818                                                  SourceLocation AttributeLoc) {
14819   llvm::APInt numElements(SemaRef.Context.getIntWidth(SemaRef.Context.IntTy),
14820                           NumElements, true);
14821   IntegerLiteral *VectorSize
14822     = IntegerLiteral::Create(SemaRef.Context, numElements, SemaRef.Context.IntTy,
14823                              AttributeLoc);
14824   return SemaRef.BuildExtVectorType(ElementType, VectorSize, AttributeLoc);
14825 }
14826 
14827 template<typename Derived>
14828 QualType
14829 TreeTransform<Derived>::RebuildDependentSizedExtVectorType(QualType ElementType,
14830                                                            Expr *SizeExpr,
14831                                                   SourceLocation AttributeLoc) {
14832   return SemaRef.BuildExtVectorType(ElementType, SizeExpr, AttributeLoc);
14833 }
14834 
14835 template <typename Derived>
14836 QualType TreeTransform<Derived>::RebuildConstantMatrixType(
14837     QualType ElementType, unsigned NumRows, unsigned NumColumns) {
14838   return SemaRef.Context.getConstantMatrixType(ElementType, NumRows,
14839                                                NumColumns);
14840 }
14841 
14842 template <typename Derived>
14843 QualType TreeTransform<Derived>::RebuildDependentSizedMatrixType(
14844     QualType ElementType, Expr *RowExpr, Expr *ColumnExpr,
14845     SourceLocation AttributeLoc) {
14846   return SemaRef.BuildMatrixType(ElementType, RowExpr, ColumnExpr,
14847                                  AttributeLoc);
14848 }
14849 
14850 template<typename Derived>
14851 QualType TreeTransform<Derived>::RebuildFunctionProtoType(
14852     QualType T,
14853     MutableArrayRef<QualType> ParamTypes,
14854     const FunctionProtoType::ExtProtoInfo &EPI) {
14855   return SemaRef.BuildFunctionType(T, ParamTypes,
14856                                    getDerived().getBaseLocation(),
14857                                    getDerived().getBaseEntity(),
14858                                    EPI);
14859 }
14860 
14861 template<typename Derived>
14862 QualType TreeTransform<Derived>::RebuildFunctionNoProtoType(QualType T) {
14863   return SemaRef.Context.getFunctionNoProtoType(T);
14864 }
14865 
14866 template<typename Derived>
14867 QualType TreeTransform<Derived>::RebuildUnresolvedUsingType(SourceLocation Loc,
14868                                                             Decl *D) {
14869   assert(D && "no decl found");
14870   if (D->isInvalidDecl()) return QualType();
14871 
14872   // FIXME: Doesn't account for ObjCInterfaceDecl!
14873   if (auto *UPD = dyn_cast<UsingPackDecl>(D)) {
14874     // A valid resolved using typename pack expansion decl can have multiple
14875     // UsingDecls, but they must each have exactly one type, and it must be
14876     // the same type in every case. But we must have at least one expansion!
14877     if (UPD->expansions().empty()) {
14878       getSema().Diag(Loc, diag::err_using_pack_expansion_empty)
14879           << UPD->isCXXClassMember() << UPD;
14880       return QualType();
14881     }
14882 
14883     // We might still have some unresolved types. Try to pick a resolved type
14884     // if we can. The final instantiation will check that the remaining
14885     // unresolved types instantiate to the type we pick.
14886     QualType FallbackT;
14887     QualType T;
14888     for (auto *E : UPD->expansions()) {
14889       QualType ThisT = RebuildUnresolvedUsingType(Loc, E);
14890       if (ThisT.isNull())
14891         continue;
14892       else if (ThisT->getAs<UnresolvedUsingType>())
14893         FallbackT = ThisT;
14894       else if (T.isNull())
14895         T = ThisT;
14896       else
14897         assert(getSema().Context.hasSameType(ThisT, T) &&
14898                "mismatched resolved types in using pack expansion");
14899     }
14900     return T.isNull() ? FallbackT : T;
14901   } else if (auto *Using = dyn_cast<UsingDecl>(D)) {
14902     assert(Using->hasTypename() &&
14903            "UnresolvedUsingTypenameDecl transformed to non-typename using");
14904 
14905     // A valid resolved using typename decl points to exactly one type decl.
14906     assert(++Using->shadow_begin() == Using->shadow_end());
14907 
14908     UsingShadowDecl *Shadow = *Using->shadow_begin();
14909     if (SemaRef.DiagnoseUseOfDecl(Shadow->getTargetDecl(), Loc))
14910       return QualType();
14911     return SemaRef.Context.getUsingType(
14912         Shadow, SemaRef.Context.getTypeDeclType(
14913                     cast<TypeDecl>(Shadow->getTargetDecl())));
14914   } else {
14915     assert(isa<UnresolvedUsingTypenameDecl>(D) &&
14916            "UnresolvedUsingTypenameDecl transformed to non-using decl");
14917     return SemaRef.Context.getTypeDeclType(
14918         cast<UnresolvedUsingTypenameDecl>(D));
14919   }
14920 }
14921 
14922 template <typename Derived>
14923 QualType TreeTransform<Derived>::RebuildTypeOfExprType(Expr *E, SourceLocation,
14924                                                        TypeOfKind Kind) {
14925   return SemaRef.BuildTypeofExprType(E, Kind);
14926 }
14927 
14928 template<typename Derived>
14929 QualType TreeTransform<Derived>::RebuildTypeOfType(QualType Underlying,
14930                                                    TypeOfKind Kind) {
14931   return SemaRef.Context.getTypeOfType(Underlying, Kind);
14932 }
14933 
14934 template <typename Derived>
14935 QualType TreeTransform<Derived>::RebuildDecltypeType(Expr *E, SourceLocation) {
14936   return SemaRef.BuildDecltypeType(E);
14937 }
14938 
14939 template<typename Derived>
14940 QualType TreeTransform<Derived>::RebuildUnaryTransformType(QualType BaseType,
14941                                             UnaryTransformType::UTTKind UKind,
14942                                             SourceLocation Loc) {
14943   return SemaRef.BuildUnaryTransformType(BaseType, UKind, Loc);
14944 }
14945 
14946 template<typename Derived>
14947 QualType TreeTransform<Derived>::RebuildTemplateSpecializationType(
14948                                                       TemplateName Template,
14949                                              SourceLocation TemplateNameLoc,
14950                                      TemplateArgumentListInfo &TemplateArgs) {
14951   return SemaRef.CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
14952 }
14953 
14954 template<typename Derived>
14955 QualType TreeTransform<Derived>::RebuildAtomicType(QualType ValueType,
14956                                                    SourceLocation KWLoc) {
14957   return SemaRef.BuildAtomicType(ValueType, KWLoc);
14958 }
14959 
14960 template<typename Derived>
14961 QualType TreeTransform<Derived>::RebuildPipeType(QualType ValueType,
14962                                                  SourceLocation KWLoc,
14963                                                  bool isReadPipe) {
14964   return isReadPipe ? SemaRef.BuildReadPipeType(ValueType, KWLoc)
14965                     : SemaRef.BuildWritePipeType(ValueType, KWLoc);
14966 }
14967 
14968 template <typename Derived>
14969 QualType TreeTransform<Derived>::RebuildBitIntType(bool IsUnsigned,
14970                                                    unsigned NumBits,
14971                                                    SourceLocation Loc) {
14972   llvm::APInt NumBitsAP(SemaRef.Context.getIntWidth(SemaRef.Context.IntTy),
14973                         NumBits, true);
14974   IntegerLiteral *Bits = IntegerLiteral::Create(SemaRef.Context, NumBitsAP,
14975                                                 SemaRef.Context.IntTy, Loc);
14976   return SemaRef.BuildBitIntType(IsUnsigned, Bits, Loc);
14977 }
14978 
14979 template <typename Derived>
14980 QualType TreeTransform<Derived>::RebuildDependentBitIntType(
14981     bool IsUnsigned, Expr *NumBitsExpr, SourceLocation Loc) {
14982   return SemaRef.BuildBitIntType(IsUnsigned, NumBitsExpr, Loc);
14983 }
14984 
14985 template<typename Derived>
14986 TemplateName
14987 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
14988                                             bool TemplateKW,
14989                                             TemplateDecl *Template) {
14990   return SemaRef.Context.getQualifiedTemplateName(SS.getScopeRep(), TemplateKW,
14991                                                   TemplateName(Template));
14992 }
14993 
14994 template<typename Derived>
14995 TemplateName
14996 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
14997                                             SourceLocation TemplateKWLoc,
14998                                             const IdentifierInfo &Name,
14999                                             SourceLocation NameLoc,
15000                                             QualType ObjectType,
15001                                             NamedDecl *FirstQualifierInScope,
15002                                             bool AllowInjectedClassName) {
15003   UnqualifiedId TemplateName;
15004   TemplateName.setIdentifier(&Name, NameLoc);
15005   Sema::TemplateTy Template;
15006   getSema().ActOnTemplateName(/*Scope=*/nullptr, SS, TemplateKWLoc,
15007                               TemplateName, ParsedType::make(ObjectType),
15008                               /*EnteringContext=*/false, Template,
15009                               AllowInjectedClassName);
15010   return Template.get();
15011 }
15012 
15013 template<typename Derived>
15014 TemplateName
15015 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
15016                                             SourceLocation TemplateKWLoc,
15017                                             OverloadedOperatorKind Operator,
15018                                             SourceLocation NameLoc,
15019                                             QualType ObjectType,
15020                                             bool AllowInjectedClassName) {
15021   UnqualifiedId Name;
15022   // FIXME: Bogus location information.
15023   SourceLocation SymbolLocations[3] = { NameLoc, NameLoc, NameLoc };
15024   Name.setOperatorFunctionId(NameLoc, Operator, SymbolLocations);
15025   Sema::TemplateTy Template;
15026   getSema().ActOnTemplateName(
15027       /*Scope=*/nullptr, SS, TemplateKWLoc, Name, ParsedType::make(ObjectType),
15028       /*EnteringContext=*/false, Template, AllowInjectedClassName);
15029   return Template.get();
15030 }
15031 
15032 template<typename Derived>
15033 ExprResult
15034 TreeTransform<Derived>::RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
15035                                                    SourceLocation OpLoc,
15036                                                    Expr *OrigCallee,
15037                                                    Expr *First,
15038                                                    Expr *Second) {
15039   Expr *Callee = OrigCallee->IgnoreParenCasts();
15040   bool isPostIncDec = Second && (Op == OO_PlusPlus || Op == OO_MinusMinus);
15041 
15042   if (First->getObjectKind() == OK_ObjCProperty) {
15043     BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
15044     if (BinaryOperator::isAssignmentOp(Opc))
15045       return SemaRef.checkPseudoObjectAssignment(/*Scope=*/nullptr, OpLoc, Opc,
15046                                                  First, Second);
15047     ExprResult Result = SemaRef.CheckPlaceholderExpr(First);
15048     if (Result.isInvalid())
15049       return ExprError();
15050     First = Result.get();
15051   }
15052 
15053   if (Second && Second->getObjectKind() == OK_ObjCProperty) {
15054     ExprResult Result = SemaRef.CheckPlaceholderExpr(Second);
15055     if (Result.isInvalid())
15056       return ExprError();
15057     Second = Result.get();
15058   }
15059 
15060   // Determine whether this should be a builtin operation.
15061   if (Op == OO_Subscript) {
15062     if (!First->getType()->isOverloadableType() &&
15063         !Second->getType()->isOverloadableType())
15064       return getSema().CreateBuiltinArraySubscriptExpr(
15065           First, Callee->getBeginLoc(), Second, OpLoc);
15066   } else if (Op == OO_Arrow) {
15067     // It is possible that the type refers to a RecoveryExpr created earlier
15068     // in the tree transformation.
15069     if (First->getType()->isDependentType())
15070       return ExprError();
15071     // -> is never a builtin operation.
15072     return SemaRef.BuildOverloadedArrowExpr(nullptr, First, OpLoc);
15073   } else if (Second == nullptr || isPostIncDec) {
15074     if (!First->getType()->isOverloadableType() ||
15075         (Op == OO_Amp && getSema().isQualifiedMemberAccess(First))) {
15076       // The argument is not of overloadable type, or this is an expression
15077       // of the form &Class::member, so try to create a built-in unary
15078       // operation.
15079       UnaryOperatorKind Opc
15080         = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
15081 
15082       return getSema().CreateBuiltinUnaryOp(OpLoc, Opc, First);
15083     }
15084   } else {
15085     if (!First->getType()->isOverloadableType() &&
15086         !Second->getType()->isOverloadableType()) {
15087       // Neither of the arguments is an overloadable type, so try to
15088       // create a built-in binary operation.
15089       BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
15090       ExprResult Result
15091         = SemaRef.CreateBuiltinBinOp(OpLoc, Opc, First, Second);
15092       if (Result.isInvalid())
15093         return ExprError();
15094 
15095       return Result;
15096     }
15097   }
15098 
15099   // Compute the transformed set of functions (and function templates) to be
15100   // used during overload resolution.
15101   UnresolvedSet<16> Functions;
15102   bool RequiresADL;
15103 
15104   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Callee)) {
15105     Functions.append(ULE->decls_begin(), ULE->decls_end());
15106     // If the overload could not be resolved in the template definition
15107     // (because we had a dependent argument), ADL is performed as part of
15108     // template instantiation.
15109     RequiresADL = ULE->requiresADL();
15110   } else {
15111     // If we've resolved this to a particular non-member function, just call
15112     // that function. If we resolved it to a member function,
15113     // CreateOverloaded* will find that function for us.
15114     NamedDecl *ND = cast<DeclRefExpr>(Callee)->getDecl();
15115     if (!isa<CXXMethodDecl>(ND))
15116       Functions.addDecl(ND);
15117     RequiresADL = false;
15118   }
15119 
15120   // Add any functions found via argument-dependent lookup.
15121   Expr *Args[2] = { First, Second };
15122   unsigned NumArgs = 1 + (Second != nullptr);
15123 
15124   // Create the overloaded operator invocation for unary operators.
15125   if (NumArgs == 1 || isPostIncDec) {
15126     UnaryOperatorKind Opc
15127       = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
15128     return SemaRef.CreateOverloadedUnaryOp(OpLoc, Opc, Functions, First,
15129                                            RequiresADL);
15130   }
15131 
15132   if (Op == OO_Subscript) {
15133     SourceLocation LBrace;
15134     SourceLocation RBrace;
15135 
15136     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee)) {
15137       DeclarationNameLoc NameLoc = DRE->getNameInfo().getInfo();
15138       LBrace = NameLoc.getCXXOperatorNameBeginLoc();
15139       RBrace = NameLoc.getCXXOperatorNameEndLoc();
15140     } else {
15141       LBrace = Callee->getBeginLoc();
15142       RBrace = OpLoc;
15143     }
15144 
15145     return SemaRef.CreateOverloadedArraySubscriptExpr(LBrace, RBrace,
15146                                                       First, Second);
15147   }
15148 
15149   // Create the overloaded operator invocation for binary operators.
15150   BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
15151   ExprResult Result = SemaRef.CreateOverloadedBinOp(
15152       OpLoc, Opc, Functions, Args[0], Args[1], RequiresADL);
15153   if (Result.isInvalid())
15154     return ExprError();
15155 
15156   return Result;
15157 }
15158 
15159 template<typename Derived>
15160 ExprResult
15161 TreeTransform<Derived>::RebuildCXXPseudoDestructorExpr(Expr *Base,
15162                                                      SourceLocation OperatorLoc,
15163                                                        bool isArrow,
15164                                                        CXXScopeSpec &SS,
15165                                                      TypeSourceInfo *ScopeType,
15166                                                        SourceLocation CCLoc,
15167                                                        SourceLocation TildeLoc,
15168                                         PseudoDestructorTypeStorage Destroyed) {
15169   QualType BaseType = Base->getType();
15170   if (Base->isTypeDependent() || Destroyed.getIdentifier() ||
15171       (!isArrow && !BaseType->getAs<RecordType>()) ||
15172       (isArrow && BaseType->getAs<PointerType>() &&
15173        !BaseType->castAs<PointerType>()->getPointeeType()
15174                                               ->template getAs<RecordType>())){
15175     // This pseudo-destructor expression is still a pseudo-destructor.
15176     return SemaRef.BuildPseudoDestructorExpr(
15177         Base, OperatorLoc, isArrow ? tok::arrow : tok::period, SS, ScopeType,
15178         CCLoc, TildeLoc, Destroyed);
15179   }
15180 
15181   TypeSourceInfo *DestroyedType = Destroyed.getTypeSourceInfo();
15182   DeclarationName Name(SemaRef.Context.DeclarationNames.getCXXDestructorName(
15183                  SemaRef.Context.getCanonicalType(DestroyedType->getType())));
15184   DeclarationNameInfo NameInfo(Name, Destroyed.getLocation());
15185   NameInfo.setNamedTypeInfo(DestroyedType);
15186 
15187   // The scope type is now known to be a valid nested name specifier
15188   // component. Tack it on to the end of the nested name specifier.
15189   if (ScopeType) {
15190     if (!ScopeType->getType()->getAs<TagType>()) {
15191       getSema().Diag(ScopeType->getTypeLoc().getBeginLoc(),
15192                      diag::err_expected_class_or_namespace)
15193           << ScopeType->getType() << getSema().getLangOpts().CPlusPlus;
15194       return ExprError();
15195     }
15196     SS.Extend(SemaRef.Context, SourceLocation(), ScopeType->getTypeLoc(),
15197               CCLoc);
15198   }
15199 
15200   SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
15201   return getSema().BuildMemberReferenceExpr(Base, BaseType,
15202                                             OperatorLoc, isArrow,
15203                                             SS, TemplateKWLoc,
15204                                             /*FIXME: FirstQualifier*/ nullptr,
15205                                             NameInfo,
15206                                             /*TemplateArgs*/ nullptr,
15207                                             /*S*/nullptr);
15208 }
15209 
15210 template<typename Derived>
15211 StmtResult
15212 TreeTransform<Derived>::TransformCapturedStmt(CapturedStmt *S) {
15213   SourceLocation Loc = S->getBeginLoc();
15214   CapturedDecl *CD = S->getCapturedDecl();
15215   unsigned NumParams = CD->getNumParams();
15216   unsigned ContextParamPos = CD->getContextParamPosition();
15217   SmallVector<Sema::CapturedParamNameType, 4> Params;
15218   for (unsigned I = 0; I < NumParams; ++I) {
15219     if (I != ContextParamPos) {
15220       Params.push_back(
15221              std::make_pair(
15222                   CD->getParam(I)->getName(),
15223                   getDerived().TransformType(CD->getParam(I)->getType())));
15224     } else {
15225       Params.push_back(std::make_pair(StringRef(), QualType()));
15226     }
15227   }
15228   getSema().ActOnCapturedRegionStart(Loc, /*CurScope*/nullptr,
15229                                      S->getCapturedRegionKind(), Params);
15230   StmtResult Body;
15231   {
15232     Sema::CompoundScopeRAII CompoundScope(getSema());
15233     Body = getDerived().TransformStmt(S->getCapturedStmt());
15234   }
15235 
15236   if (Body.isInvalid()) {
15237     getSema().ActOnCapturedRegionError();
15238     return StmtError();
15239   }
15240 
15241   return getSema().ActOnCapturedRegionEnd(Body.get());
15242 }
15243 
15244 } // end namespace clang
15245 
15246 #endif // LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H
15247