xref: /freebsd/contrib/llvm-project/clang/lib/Sema/TreeTransform.h (revision 1db9f3b21e39176dd5b67cf8ac378633b172463e)
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/ExprCXX.h"
23 #include "clang/AST/ExprConcepts.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/EnterExpressionEvaluationContext.h"
35 #include "clang/Sema/Lookup.h"
36 #include "clang/Sema/Ownership.h"
37 #include "clang/Sema/ParsedTemplate.h"
38 #include "clang/Sema/ScopeInfo.h"
39 #include "clang/Sema/SemaDiagnostic.h"
40 #include "clang/Sema/SemaInternal.h"
41 #include "llvm/ADT/ArrayRef.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include <algorithm>
44 #include <optional>
45 
46 using namespace llvm::omp;
47 
48 namespace clang {
49 using namespace sema;
50 
51 /// A semantic tree transformation that allows one to transform one
52 /// abstract syntax tree into another.
53 ///
54 /// A new tree transformation is defined by creating a new subclass \c X of
55 /// \c TreeTransform<X> and then overriding certain operations to provide
56 /// behavior specific to that transformation. For example, template
57 /// instantiation is implemented as a tree transformation where the
58 /// transformation of TemplateTypeParmType nodes involves substituting the
59 /// template arguments for their corresponding template parameters; a similar
60 /// transformation is performed for non-type template parameters and
61 /// template template parameters.
62 ///
63 /// This tree-transformation template uses static polymorphism to allow
64 /// subclasses to customize any of its operations. Thus, a subclass can
65 /// override any of the transformation or rebuild operators by providing an
66 /// operation with the same signature as the default implementation. The
67 /// overriding function should not be virtual.
68 ///
69 /// Semantic tree transformations are split into two stages, either of which
70 /// can be replaced by a subclass. The "transform" step transforms an AST node
71 /// or the parts of an AST node using the various transformation functions,
72 /// then passes the pieces on to the "rebuild" step, which constructs a new AST
73 /// node of the appropriate kind from the pieces. The default transformation
74 /// routines recursively transform the operands to composite AST nodes (e.g.,
75 /// the pointee type of a PointerType node) and, if any of those operand nodes
76 /// were changed by the transformation, invokes the rebuild operation to create
77 /// a new AST node.
78 ///
79 /// Subclasses can customize the transformation at various levels. The
80 /// most coarse-grained transformations involve replacing TransformType(),
81 /// TransformExpr(), TransformDecl(), TransformNestedNameSpecifierLoc(),
82 /// TransformTemplateName(), or TransformTemplateArgument() with entirely
83 /// new implementations.
84 ///
85 /// For more fine-grained transformations, subclasses can replace any of the
86 /// \c TransformXXX functions (where XXX is the name of an AST node, e.g.,
87 /// PointerType, StmtExpr) to alter the transformation. As mentioned previously,
88 /// replacing TransformTemplateTypeParmType() allows template instantiation
89 /// to substitute template arguments for their corresponding template
90 /// parameters. Additionally, subclasses can override the \c RebuildXXX
91 /// functions to control how AST nodes are rebuilt when their operands change.
92 /// By default, \c TreeTransform will invoke semantic analysis to rebuild
93 /// AST nodes. However, certain other tree transformations (e.g, cloning) may
94 /// be able to use more efficient rebuild steps.
95 ///
96 /// There are a handful of other functions that can be overridden, allowing one
97 /// to avoid traversing nodes that don't need any transformation
98 /// (\c AlreadyTransformed()), force rebuilding AST nodes even when their
99 /// operands have not changed (\c AlwaysRebuild()), and customize the
100 /// default locations and entity names used for type-checking
101 /// (\c getBaseLocation(), \c getBaseEntity()).
102 template<typename Derived>
103 class TreeTransform {
104   /// Private RAII object that helps us forget and then re-remember
105   /// the template argument corresponding to a partially-substituted parameter
106   /// pack.
107   class ForgetPartiallySubstitutedPackRAII {
108     Derived &Self;
109     TemplateArgument Old;
110 
111   public:
112     ForgetPartiallySubstitutedPackRAII(Derived &Self) : Self(Self) {
113       Old = Self.ForgetPartiallySubstitutedPack();
114     }
115 
116     ~ForgetPartiallySubstitutedPackRAII() {
117       Self.RememberPartiallySubstitutedPack(Old);
118     }
119   };
120 
121 protected:
122   Sema &SemaRef;
123 
124   /// The set of local declarations that have been transformed, for
125   /// cases where we are forced to build new declarations within the transformer
126   /// rather than in the subclass (e.g., lambda closure types).
127   llvm::DenseMap<Decl *, Decl *> TransformedLocalDecls;
128 
129 public:
130   /// Initializes a new tree transformer.
131   TreeTransform(Sema &SemaRef) : SemaRef(SemaRef) { }
132 
133   /// Retrieves a reference to the derived class.
134   Derived &getDerived() { return static_cast<Derived&>(*this); }
135 
136   /// Retrieves a reference to the derived class.
137   const Derived &getDerived() const {
138     return static_cast<const Derived&>(*this);
139   }
140 
141   static inline ExprResult Owned(Expr *E) { return E; }
142   static inline StmtResult Owned(Stmt *S) { return S; }
143 
144   /// Retrieves a reference to the semantic analysis object used for
145   /// this tree transform.
146   Sema &getSema() const { return SemaRef; }
147 
148   /// Whether the transformation should always rebuild AST nodes, even
149   /// if none of the children have changed.
150   ///
151   /// Subclasses may override this function to specify when the transformation
152   /// should rebuild all AST nodes.
153   ///
154   /// We must always rebuild all AST nodes when performing variadic template
155   /// pack expansion, in order to avoid violating the AST invariant that each
156   /// statement node appears at most once in its containing declaration.
157   bool AlwaysRebuild() { return SemaRef.ArgumentPackSubstitutionIndex != -1; }
158 
159   /// Whether the transformation is forming an expression or statement that
160   /// replaces the original. In this case, we'll reuse mangling numbers from
161   /// existing lambdas.
162   bool ReplacingOriginal() { return false; }
163 
164   /// Wether CXXConstructExpr can be skipped when they are implicit.
165   /// They will be reconstructed when used if needed.
166   /// This is useful when the user that cause rebuilding of the
167   /// CXXConstructExpr is outside of the expression at which the TreeTransform
168   /// started.
169   bool AllowSkippingCXXConstructExpr() { return true; }
170 
171   /// Returns the location of the entity being transformed, if that
172   /// information was not available elsewhere in the AST.
173   ///
174   /// By default, returns no source-location information. Subclasses can
175   /// provide an alternative implementation that provides better location
176   /// information.
177   SourceLocation getBaseLocation() { return SourceLocation(); }
178 
179   /// Returns the name of the entity being transformed, if that
180   /// information was not available elsewhere in the AST.
181   ///
182   /// By default, returns an empty name. Subclasses can provide an alternative
183   /// implementation with a more precise name.
184   DeclarationName getBaseEntity() { return DeclarationName(); }
185 
186   /// Sets the "base" location and entity when that
187   /// information is known based on another transformation.
188   ///
189   /// By default, the source location and entity are ignored. Subclasses can
190   /// override this function to provide a customized implementation.
191   void setBase(SourceLocation Loc, DeclarationName Entity) { }
192 
193   /// RAII object that temporarily sets the base location and entity
194   /// used for reporting diagnostics in types.
195   class TemporaryBase {
196     TreeTransform &Self;
197     SourceLocation OldLocation;
198     DeclarationName OldEntity;
199 
200   public:
201     TemporaryBase(TreeTransform &Self, SourceLocation Location,
202                   DeclarationName Entity) : Self(Self) {
203       OldLocation = Self.getDerived().getBaseLocation();
204       OldEntity = Self.getDerived().getBaseEntity();
205 
206       if (Location.isValid())
207         Self.getDerived().setBase(Location, Entity);
208     }
209 
210     ~TemporaryBase() {
211       Self.getDerived().setBase(OldLocation, OldEntity);
212     }
213   };
214 
215   /// Determine whether the given type \p T has already been
216   /// transformed.
217   ///
218   /// Subclasses can provide an alternative implementation of this routine
219   /// to short-circuit evaluation when it is known that a given type will
220   /// not change. For example, template instantiation need not traverse
221   /// non-dependent types.
222   bool AlreadyTransformed(QualType T) {
223     return T.isNull();
224   }
225 
226   /// Transform a template parameter depth level.
227   ///
228   /// During a transformation that transforms template parameters, this maps
229   /// an old template parameter depth to a new depth.
230   unsigned TransformTemplateDepth(unsigned Depth) {
231     return Depth;
232   }
233 
234   /// Determine whether the given call argument should be dropped, e.g.,
235   /// because it is a default argument.
236   ///
237   /// Subclasses can provide an alternative implementation of this routine to
238   /// determine which kinds of call arguments get dropped. By default,
239   /// CXXDefaultArgument nodes are dropped (prior to transformation).
240   bool DropCallArgument(Expr *E) {
241     return E->isDefaultArgument();
242   }
243 
244   /// Determine whether we should expand a pack expansion with the
245   /// given set of parameter packs into separate arguments by repeatedly
246   /// transforming the pattern.
247   ///
248   /// By default, the transformer never tries to expand pack expansions.
249   /// Subclasses can override this routine to provide different behavior.
250   ///
251   /// \param EllipsisLoc The location of the ellipsis that identifies the
252   /// pack expansion.
253   ///
254   /// \param PatternRange The source range that covers the entire pattern of
255   /// the pack expansion.
256   ///
257   /// \param Unexpanded The set of unexpanded parameter packs within the
258   /// pattern.
259   ///
260   /// \param ShouldExpand Will be set to \c true if the transformer should
261   /// expand the corresponding pack expansions into separate arguments. When
262   /// set, \c NumExpansions must also be set.
263   ///
264   /// \param RetainExpansion Whether the caller should add an unexpanded
265   /// pack expansion after all of the expanded arguments. This is used
266   /// when extending explicitly-specified template argument packs per
267   /// C++0x [temp.arg.explicit]p9.
268   ///
269   /// \param NumExpansions The number of separate arguments that will be in
270   /// the expanded form of the corresponding pack expansion. This is both an
271   /// input and an output parameter, which can be set by the caller if the
272   /// number of expansions is known a priori (e.g., due to a prior substitution)
273   /// and will be set by the callee when the number of expansions is known.
274   /// The callee must set this value when \c ShouldExpand is \c true; it may
275   /// set this value in other cases.
276   ///
277   /// \returns true if an error occurred (e.g., because the parameter packs
278   /// are to be instantiated with arguments of different lengths), false
279   /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
280   /// must be set.
281   bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
282                                SourceRange PatternRange,
283                                ArrayRef<UnexpandedParameterPack> Unexpanded,
284                                bool &ShouldExpand, bool &RetainExpansion,
285                                std::optional<unsigned> &NumExpansions) {
286     ShouldExpand = false;
287     return false;
288   }
289 
290   /// "Forget" about the partially-substituted pack template argument,
291   /// when performing an instantiation that must preserve the parameter pack
292   /// use.
293   ///
294   /// This routine is meant to be overridden by the template instantiator.
295   TemplateArgument ForgetPartiallySubstitutedPack() {
296     return TemplateArgument();
297   }
298 
299   /// "Remember" the partially-substituted pack template argument
300   /// after performing an instantiation that must preserve the parameter pack
301   /// use.
302   ///
303   /// This routine is meant to be overridden by the template instantiator.
304   void RememberPartiallySubstitutedPack(TemplateArgument Arg) { }
305 
306   /// Note to the derived class when a function parameter pack is
307   /// being expanded.
308   void ExpandingFunctionParameterPack(ParmVarDecl *Pack) { }
309 
310   /// Transforms the given type into another type.
311   ///
312   /// By default, this routine transforms a type by creating a
313   /// TypeSourceInfo for it and delegating to the appropriate
314   /// function.  This is expensive, but we don't mind, because
315   /// this method is deprecated anyway;  all users should be
316   /// switched to storing TypeSourceInfos.
317   ///
318   /// \returns the transformed type.
319   QualType TransformType(QualType T);
320 
321   /// Transforms the given type-with-location into a new
322   /// type-with-location.
323   ///
324   /// By default, this routine transforms a type by delegating to the
325   /// appropriate TransformXXXType to build a new type.  Subclasses
326   /// may override this function (to take over all type
327   /// transformations) or some set of the TransformXXXType functions
328   /// to alter the transformation.
329   TypeSourceInfo *TransformType(TypeSourceInfo *DI);
330 
331   /// Transform the given type-with-location into a new
332   /// type, collecting location information in the given builder
333   /// as necessary.
334   ///
335   QualType TransformType(TypeLocBuilder &TLB, TypeLoc TL);
336 
337   /// Transform a type that is permitted to produce a
338   /// DeducedTemplateSpecializationType.
339   ///
340   /// This is used in the (relatively rare) contexts where it is acceptable
341   /// for transformation to produce a class template type with deduced
342   /// template arguments.
343   /// @{
344   QualType TransformTypeWithDeducedTST(QualType T);
345   TypeSourceInfo *TransformTypeWithDeducedTST(TypeSourceInfo *DI);
346   /// @}
347 
348   /// The reason why the value of a statement is not discarded, if any.
349   enum StmtDiscardKind {
350     SDK_Discarded,
351     SDK_NotDiscarded,
352     SDK_StmtExprResult,
353   };
354 
355   /// Transform the given statement.
356   ///
357   /// By default, this routine transforms a statement by delegating to the
358   /// appropriate TransformXXXStmt function to transform a specific kind of
359   /// statement or the TransformExpr() function to transform an expression.
360   /// Subclasses may override this function to transform statements using some
361   /// other mechanism.
362   ///
363   /// \returns the transformed statement.
364   StmtResult TransformStmt(Stmt *S, StmtDiscardKind SDK = SDK_Discarded);
365 
366   /// Transform the given statement.
367   ///
368   /// By default, this routine transforms a statement by delegating to the
369   /// appropriate TransformOMPXXXClause function to transform a specific kind
370   /// of clause. Subclasses may override this function to transform statements
371   /// using some other mechanism.
372   ///
373   /// \returns the transformed OpenMP clause.
374   OMPClause *TransformOMPClause(OMPClause *S);
375 
376   /// Transform the given attribute.
377   ///
378   /// By default, this routine transforms a statement by delegating to the
379   /// appropriate TransformXXXAttr function to transform a specific kind
380   /// of attribute. Subclasses may override this function to transform
381   /// attributed statements/types using some other mechanism.
382   ///
383   /// \returns the transformed attribute
384   const Attr *TransformAttr(const Attr *S);
385 
386   // Transform the given statement attribute.
387   //
388   // Delegates to the appropriate TransformXXXAttr function to transform a
389   // specific kind of statement attribute. Unlike the non-statement taking
390   // version of this, this implements all attributes, not just pragmas.
391   const Attr *TransformStmtAttr(const Stmt *OrigS, const Stmt *InstS,
392                                 const Attr *A);
393 
394   // Transform the specified attribute.
395   //
396   // Subclasses should override the transformation of attributes with a pragma
397   // spelling to transform expressions stored within the attribute.
398   //
399   // \returns the transformed attribute.
400 #define ATTR(X)                                                                \
401   const X##Attr *Transform##X##Attr(const X##Attr *R) { return R; }
402 #include "clang/Basic/AttrList.inc"
403 
404   // Transform the specified attribute.
405   //
406   // Subclasses should override the transformation of attributes to do
407   // transformation and checking of statement attributes. By default, this
408   // delegates to the non-statement taking version.
409   //
410   // \returns the transformed attribute.
411 #define ATTR(X)                                                                \
412   const X##Attr *TransformStmt##X##Attr(const Stmt *, const Stmt *,            \
413                                         const X##Attr *A) {                    \
414     return getDerived().Transform##X##Attr(A);                                 \
415   }
416 #include "clang/Basic/AttrList.inc"
417 
418   /// Transform the given expression.
419   ///
420   /// By default, this routine transforms an expression by delegating to the
421   /// appropriate TransformXXXExpr function to build a new expression.
422   /// Subclasses may override this function to transform expressions using some
423   /// other mechanism.
424   ///
425   /// \returns the transformed expression.
426   ExprResult TransformExpr(Expr *E);
427 
428   /// Transform the given initializer.
429   ///
430   /// By default, this routine transforms an initializer by stripping off the
431   /// semantic nodes added by initialization, then passing the result to
432   /// TransformExpr or TransformExprs.
433   ///
434   /// \returns the transformed initializer.
435   ExprResult TransformInitializer(Expr *Init, bool NotCopyInit);
436 
437   /// Transform the given list of expressions.
438   ///
439   /// This routine transforms a list of expressions by invoking
440   /// \c TransformExpr() for each subexpression. However, it also provides
441   /// support for variadic templates by expanding any pack expansions (if the
442   /// derived class permits such expansion) along the way. When pack expansions
443   /// are present, the number of outputs may not equal the number of inputs.
444   ///
445   /// \param Inputs The set of expressions to be transformed.
446   ///
447   /// \param NumInputs The number of expressions in \c Inputs.
448   ///
449   /// \param IsCall If \c true, then this transform is being performed on
450   /// function-call arguments, and any arguments that should be dropped, will
451   /// be.
452   ///
453   /// \param Outputs The transformed input expressions will be added to this
454   /// vector.
455   ///
456   /// \param ArgChanged If non-NULL, will be set \c true if any argument changed
457   /// due to transformation.
458   ///
459   /// \returns true if an error occurred, false otherwise.
460   bool TransformExprs(Expr *const *Inputs, unsigned NumInputs, bool IsCall,
461                       SmallVectorImpl<Expr *> &Outputs,
462                       bool *ArgChanged = nullptr);
463 
464   /// Transform the given declaration, which is referenced from a type
465   /// or expression.
466   ///
467   /// By default, acts as the identity function on declarations, unless the
468   /// transformer has had to transform the declaration itself. Subclasses
469   /// may override this function to provide alternate behavior.
470   Decl *TransformDecl(SourceLocation Loc, Decl *D) {
471     llvm::DenseMap<Decl *, Decl *>::iterator Known
472       = TransformedLocalDecls.find(D);
473     if (Known != TransformedLocalDecls.end())
474       return Known->second;
475 
476     return D;
477   }
478 
479   /// Transform the specified condition.
480   ///
481   /// By default, this transforms the variable and expression and rebuilds
482   /// the condition.
483   Sema::ConditionResult TransformCondition(SourceLocation Loc, VarDecl *Var,
484                                            Expr *Expr,
485                                            Sema::ConditionKind Kind);
486 
487   /// Transform the attributes associated with the given declaration and
488   /// place them on the new declaration.
489   ///
490   /// By default, this operation does nothing. Subclasses may override this
491   /// behavior to transform attributes.
492   void transformAttrs(Decl *Old, Decl *New) { }
493 
494   /// Note that a local declaration has been transformed by this
495   /// transformer.
496   ///
497   /// Local declarations are typically transformed via a call to
498   /// TransformDefinition. However, in some cases (e.g., lambda expressions),
499   /// the transformer itself has to transform the declarations. This routine
500   /// can be overridden by a subclass that keeps track of such mappings.
501   void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> New) {
502     assert(New.size() == 1 &&
503            "must override transformedLocalDecl if performing pack expansion");
504     TransformedLocalDecls[Old] = New.front();
505   }
506 
507   /// Transform the definition of the given declaration.
508   ///
509   /// By default, invokes TransformDecl() to transform the declaration.
510   /// Subclasses may override this function to provide alternate behavior.
511   Decl *TransformDefinition(SourceLocation Loc, Decl *D) {
512     return getDerived().TransformDecl(Loc, D);
513   }
514 
515   /// Transform the given declaration, which was the first part of a
516   /// nested-name-specifier in a member access expression.
517   ///
518   /// This specific declaration transformation only applies to the first
519   /// identifier in a nested-name-specifier of a member access expression, e.g.,
520   /// the \c T in \c x->T::member
521   ///
522   /// By default, invokes TransformDecl() to transform the declaration.
523   /// Subclasses may override this function to provide alternate behavior.
524   NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc) {
525     return cast_or_null<NamedDecl>(getDerived().TransformDecl(Loc, D));
526   }
527 
528   /// Transform the set of declarations in an OverloadExpr.
529   bool TransformOverloadExprDecls(OverloadExpr *Old, bool RequiresADL,
530                                   LookupResult &R);
531 
532   /// Transform the given nested-name-specifier with source-location
533   /// information.
534   ///
535   /// By default, transforms all of the types and declarations within the
536   /// nested-name-specifier. Subclasses may override this function to provide
537   /// alternate behavior.
538   NestedNameSpecifierLoc
539   TransformNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
540                                   QualType ObjectType = QualType(),
541                                   NamedDecl *FirstQualifierInScope = nullptr);
542 
543   /// Transform the given declaration name.
544   ///
545   /// By default, transforms the types of conversion function, constructor,
546   /// and destructor names and then (if needed) rebuilds the declaration name.
547   /// Identifiers and selectors are returned unmodified. Subclasses may
548   /// override this function to provide alternate behavior.
549   DeclarationNameInfo
550   TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo);
551 
552   bool TransformRequiresExprRequirements(
553       ArrayRef<concepts::Requirement *> Reqs,
554       llvm::SmallVectorImpl<concepts::Requirement *> &Transformed);
555   concepts::TypeRequirement *
556   TransformTypeRequirement(concepts::TypeRequirement *Req);
557   concepts::ExprRequirement *
558   TransformExprRequirement(concepts::ExprRequirement *Req);
559   concepts::NestedRequirement *
560   TransformNestedRequirement(concepts::NestedRequirement *Req);
561 
562   /// Transform the given template name.
563   ///
564   /// \param SS The nested-name-specifier that qualifies the template
565   /// name. This nested-name-specifier must already have been transformed.
566   ///
567   /// \param Name The template name to transform.
568   ///
569   /// \param NameLoc The source location of the template name.
570   ///
571   /// \param ObjectType If we're translating a template name within a member
572   /// access expression, this is the type of the object whose member template
573   /// is being referenced.
574   ///
575   /// \param FirstQualifierInScope If the first part of a nested-name-specifier
576   /// also refers to a name within the current (lexical) scope, this is the
577   /// declaration it refers to.
578   ///
579   /// By default, transforms the template name by transforming the declarations
580   /// and nested-name-specifiers that occur within the template name.
581   /// Subclasses may override this function to provide alternate behavior.
582   TemplateName
583   TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
584                         SourceLocation NameLoc,
585                         QualType ObjectType = QualType(),
586                         NamedDecl *FirstQualifierInScope = nullptr,
587                         bool AllowInjectedClassName = false);
588 
589   /// Transform the given template argument.
590   ///
591   /// By default, this operation transforms the type, expression, or
592   /// declaration stored within the template argument and constructs a
593   /// new template argument from the transformed result. Subclasses may
594   /// override this function to provide alternate behavior.
595   ///
596   /// Returns true if there was an error.
597   bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
598                                  TemplateArgumentLoc &Output,
599                                  bool Uneval = false);
600 
601   /// Transform the given set of template arguments.
602   ///
603   /// By default, this operation transforms all of the template arguments
604   /// in the input set using \c TransformTemplateArgument(), and appends
605   /// the transformed arguments to the output list.
606   ///
607   /// Note that this overload of \c TransformTemplateArguments() is merely
608   /// a convenience function. Subclasses that wish to override this behavior
609   /// should override the iterator-based member template version.
610   ///
611   /// \param Inputs The set of template arguments to be transformed.
612   ///
613   /// \param NumInputs The number of template arguments in \p Inputs.
614   ///
615   /// \param Outputs The set of transformed template arguments output by this
616   /// routine.
617   ///
618   /// Returns true if an error occurred.
619   bool TransformTemplateArguments(const TemplateArgumentLoc *Inputs,
620                                   unsigned NumInputs,
621                                   TemplateArgumentListInfo &Outputs,
622                                   bool Uneval = false) {
623     return TransformTemplateArguments(Inputs, Inputs + NumInputs, Outputs,
624                                       Uneval);
625   }
626 
627   /// Transform the given set of template arguments.
628   ///
629   /// By default, this operation transforms all of the template arguments
630   /// in the input set using \c TransformTemplateArgument(), and appends
631   /// the transformed arguments to the output list.
632   ///
633   /// \param First An iterator to the first template argument.
634   ///
635   /// \param Last An iterator one step past the last template argument.
636   ///
637   /// \param Outputs The set of transformed template arguments output by this
638   /// routine.
639   ///
640   /// Returns true if an error occurred.
641   template<typename InputIterator>
642   bool TransformTemplateArguments(InputIterator First,
643                                   InputIterator Last,
644                                   TemplateArgumentListInfo &Outputs,
645                                   bool Uneval = false);
646 
647   /// Fakes up a TemplateArgumentLoc for a given TemplateArgument.
648   void InventTemplateArgumentLoc(const TemplateArgument &Arg,
649                                  TemplateArgumentLoc &ArgLoc);
650 
651   /// Fakes up a TypeSourceInfo for a type.
652   TypeSourceInfo *InventTypeSourceInfo(QualType T) {
653     return SemaRef.Context.getTrivialTypeSourceInfo(T,
654                        getDerived().getBaseLocation());
655   }
656 
657 #define ABSTRACT_TYPELOC(CLASS, PARENT)
658 #define TYPELOC(CLASS, PARENT)                                   \
659   QualType Transform##CLASS##Type(TypeLocBuilder &TLB, CLASS##TypeLoc T);
660 #include "clang/AST/TypeLocNodes.def"
661 
662   QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
663                                          TemplateTypeParmTypeLoc TL,
664                                          bool SuppressObjCLifetime);
665   QualType
666   TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
667                                          SubstTemplateTypeParmPackTypeLoc TL,
668                                          bool SuppressObjCLifetime);
669 
670   template<typename Fn>
671   QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
672                                       FunctionProtoTypeLoc TL,
673                                       CXXRecordDecl *ThisContext,
674                                       Qualifiers ThisTypeQuals,
675                                       Fn TransformExceptionSpec);
676 
677   template <typename Fn>
678   QualType TransformAttributedType(TypeLocBuilder &TLB, AttributedTypeLoc TL,
679                                    Fn TransformModifiedType);
680 
681   bool TransformExceptionSpec(SourceLocation Loc,
682                               FunctionProtoType::ExceptionSpecInfo &ESI,
683                               SmallVectorImpl<QualType> &Exceptions,
684                               bool &Changed);
685 
686   StmtResult TransformSEHHandler(Stmt *Handler);
687 
688   QualType
689   TransformTemplateSpecializationType(TypeLocBuilder &TLB,
690                                       TemplateSpecializationTypeLoc TL,
691                                       TemplateName Template);
692 
693   QualType
694   TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
695                                       DependentTemplateSpecializationTypeLoc TL,
696                                                TemplateName Template,
697                                                CXXScopeSpec &SS);
698 
699   QualType TransformDependentTemplateSpecializationType(
700       TypeLocBuilder &TLB, DependentTemplateSpecializationTypeLoc TL,
701       NestedNameSpecifierLoc QualifierLoc);
702 
703   /// Transforms the parameters of a function type into the
704   /// given vectors.
705   ///
706   /// The result vectors should be kept in sync; null entries in the
707   /// variables vector are acceptable.
708   ///
709   /// LastParamTransformed, if non-null, will be set to the index of the last
710   /// parameter on which transfromation was started. In the event of an error,
711   /// this will contain the parameter which failed to instantiate.
712   ///
713   /// Return true on error.
714   bool TransformFunctionTypeParams(
715       SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
716       const QualType *ParamTypes,
717       const FunctionProtoType::ExtParameterInfo *ParamInfos,
718       SmallVectorImpl<QualType> &PTypes, SmallVectorImpl<ParmVarDecl *> *PVars,
719       Sema::ExtParameterInfoBuilder &PInfos, unsigned *LastParamTransformed);
720 
721   bool TransformFunctionTypeParams(
722       SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
723       const QualType *ParamTypes,
724       const FunctionProtoType::ExtParameterInfo *ParamInfos,
725       SmallVectorImpl<QualType> &PTypes, SmallVectorImpl<ParmVarDecl *> *PVars,
726       Sema::ExtParameterInfoBuilder &PInfos) {
727     return getDerived().TransformFunctionTypeParams(
728         Loc, Params, ParamTypes, ParamInfos, PTypes, PVars, PInfos, nullptr);
729   }
730 
731   /// Transforms the parameters of a requires expresison into the given vectors.
732   ///
733   /// The result vectors should be kept in sync; null entries in the
734   /// variables vector are acceptable.
735   ///
736   /// Returns an unset ExprResult on success.  Returns an ExprResult the 'not
737   /// satisfied' RequiresExpr if subsitution failed, OR an ExprError, both of
738   /// which are cases where transformation shouldn't continue.
739   ExprResult TransformRequiresTypeParams(
740       SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
741       RequiresExprBodyDecl *Body, ArrayRef<ParmVarDecl *> Params,
742       SmallVectorImpl<QualType> &PTypes,
743       SmallVectorImpl<ParmVarDecl *> &TransParams,
744       Sema::ExtParameterInfoBuilder &PInfos) {
745     if (getDerived().TransformFunctionTypeParams(
746             KWLoc, Params, /*ParamTypes=*/nullptr,
747             /*ParamInfos=*/nullptr, PTypes, &TransParams, PInfos))
748       return ExprError();
749 
750     return ExprResult{};
751   }
752 
753   /// Transforms a single function-type parameter.  Return null
754   /// on error.
755   ///
756   /// \param indexAdjustment - A number to add to the parameter's
757   ///   scope index;  can be negative
758   ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
759                                           int indexAdjustment,
760                                           std::optional<unsigned> NumExpansions,
761                                           bool ExpectParameterPack);
762 
763   /// Transform the body of a lambda-expression.
764   StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body);
765   /// Alternative implementation of TransformLambdaBody that skips transforming
766   /// the body.
767   StmtResult SkipLambdaBody(LambdaExpr *E, Stmt *Body);
768 
769   QualType TransformReferenceType(TypeLocBuilder &TLB, ReferenceTypeLoc TL);
770 
771   StmtResult TransformCompoundStmt(CompoundStmt *S, bool IsStmtExpr);
772   ExprResult TransformCXXNamedCastExpr(CXXNamedCastExpr *E);
773 
774   TemplateParameterList *TransformTemplateParameterList(
775         TemplateParameterList *TPL) {
776     return TPL;
777   }
778 
779   ExprResult TransformAddressOfOperand(Expr *E);
780 
781   ExprResult TransformDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E,
782                                                 bool IsAddressOfOperand,
783                                                 TypeSourceInfo **RecoveryTSI);
784 
785   ExprResult TransformParenDependentScopeDeclRefExpr(
786       ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool IsAddressOfOperand,
787       TypeSourceInfo **RecoveryTSI);
788 
789   StmtResult TransformOMPExecutableDirective(OMPExecutableDirective *S);
790 
791 // FIXME: We use LLVM_ATTRIBUTE_NOINLINE because inlining causes a ridiculous
792 // amount of stack usage with clang.
793 #define STMT(Node, Parent)                        \
794   LLVM_ATTRIBUTE_NOINLINE \
795   StmtResult Transform##Node(Node *S);
796 #define VALUESTMT(Node, Parent)                   \
797   LLVM_ATTRIBUTE_NOINLINE \
798   StmtResult Transform##Node(Node *S, StmtDiscardKind SDK);
799 #define EXPR(Node, Parent)                        \
800   LLVM_ATTRIBUTE_NOINLINE \
801   ExprResult Transform##Node(Node *E);
802 #define ABSTRACT_STMT(Stmt)
803 #include "clang/AST/StmtNodes.inc"
804 
805 #define GEN_CLANG_CLAUSE_CLASS
806 #define CLAUSE_CLASS(Enum, Str, Class)                                         \
807   LLVM_ATTRIBUTE_NOINLINE                                                      \
808   OMPClause *Transform##Class(Class *S);
809 #include "llvm/Frontend/OpenMP/OMP.inc"
810 
811   /// Build a new qualified type given its unqualified type and type location.
812   ///
813   /// By default, this routine adds type qualifiers only to types that can
814   /// have qualifiers, and silently suppresses those qualifiers that are not
815   /// permitted. Subclasses may override this routine to provide different
816   /// behavior.
817   QualType RebuildQualifiedType(QualType T, QualifiedTypeLoc TL);
818 
819   /// Build a new pointer type given its pointee type.
820   ///
821   /// By default, performs semantic analysis when building the pointer type.
822   /// Subclasses may override this routine to provide different behavior.
823   QualType RebuildPointerType(QualType PointeeType, SourceLocation Sigil);
824 
825   /// Build a new block pointer type given its pointee type.
826   ///
827   /// By default, performs semantic analysis when building the block pointer
828   /// type. Subclasses may override this routine to provide different behavior.
829   QualType RebuildBlockPointerType(QualType PointeeType, SourceLocation Sigil);
830 
831   /// Build a new reference type given the type it references.
832   ///
833   /// By default, performs semantic analysis when building the
834   /// reference type. Subclasses may override this routine to provide
835   /// different behavior.
836   ///
837   /// \param LValue whether the type was written with an lvalue sigil
838   /// or an rvalue sigil.
839   QualType RebuildReferenceType(QualType ReferentType,
840                                 bool LValue,
841                                 SourceLocation Sigil);
842 
843   /// Build a new member pointer type given the pointee type and the
844   /// class type it refers into.
845   ///
846   /// By default, performs semantic analysis when building the member pointer
847   /// type. Subclasses may override this routine to provide different behavior.
848   QualType RebuildMemberPointerType(QualType PointeeType, QualType ClassType,
849                                     SourceLocation Sigil);
850 
851   QualType RebuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
852                                     SourceLocation ProtocolLAngleLoc,
853                                     ArrayRef<ObjCProtocolDecl *> Protocols,
854                                     ArrayRef<SourceLocation> ProtocolLocs,
855                                     SourceLocation ProtocolRAngleLoc);
856 
857   /// Build an Objective-C object type.
858   ///
859   /// By default, performs semantic analysis when building the object type.
860   /// Subclasses may override this routine to provide different behavior.
861   QualType RebuildObjCObjectType(QualType BaseType,
862                                  SourceLocation Loc,
863                                  SourceLocation TypeArgsLAngleLoc,
864                                  ArrayRef<TypeSourceInfo *> TypeArgs,
865                                  SourceLocation TypeArgsRAngleLoc,
866                                  SourceLocation ProtocolLAngleLoc,
867                                  ArrayRef<ObjCProtocolDecl *> Protocols,
868                                  ArrayRef<SourceLocation> ProtocolLocs,
869                                  SourceLocation ProtocolRAngleLoc);
870 
871   /// Build a new Objective-C object pointer type given the pointee type.
872   ///
873   /// By default, directly builds the pointer type, with no additional semantic
874   /// analysis.
875   QualType RebuildObjCObjectPointerType(QualType PointeeType,
876                                         SourceLocation Star);
877 
878   /// Build a new array type given the element type, size
879   /// modifier, size of the array (if known), size expression, and index type
880   /// qualifiers.
881   ///
882   /// By default, performs semantic analysis when building the array type.
883   /// Subclasses may override this routine to provide different behavior.
884   /// Also by default, all of the other Rebuild*Array
885   QualType RebuildArrayType(QualType ElementType, ArraySizeModifier SizeMod,
886                             const llvm::APInt *Size, Expr *SizeExpr,
887                             unsigned IndexTypeQuals, SourceRange BracketsRange);
888 
889   /// Build a new constant array type given the element type, size
890   /// modifier, (known) size of the array, and index type qualifiers.
891   ///
892   /// By default, performs semantic analysis when building the array type.
893   /// Subclasses may override this routine to provide different behavior.
894   QualType RebuildConstantArrayType(QualType ElementType,
895                                     ArraySizeModifier SizeMod,
896                                     const llvm::APInt &Size, Expr *SizeExpr,
897                                     unsigned IndexTypeQuals,
898                                     SourceRange BracketsRange);
899 
900   /// Build a new incomplete array type given the element type, size
901   /// modifier, and index type qualifiers.
902   ///
903   /// By default, performs semantic analysis when building the array type.
904   /// Subclasses may override this routine to provide different behavior.
905   QualType RebuildIncompleteArrayType(QualType ElementType,
906                                       ArraySizeModifier SizeMod,
907                                       unsigned IndexTypeQuals,
908                                       SourceRange BracketsRange);
909 
910   /// Build a new variable-length array type given the element type,
911   /// size modifier, size expression, and index type qualifiers.
912   ///
913   /// By default, performs semantic analysis when building the array type.
914   /// Subclasses may override this routine to provide different behavior.
915   QualType RebuildVariableArrayType(QualType ElementType,
916                                     ArraySizeModifier SizeMod, Expr *SizeExpr,
917                                     unsigned IndexTypeQuals,
918                                     SourceRange BracketsRange);
919 
920   /// Build a new dependent-sized array type given the element type,
921   /// size modifier, size expression, and index type qualifiers.
922   ///
923   /// By default, performs semantic analysis when building the array type.
924   /// Subclasses may override this routine to provide different behavior.
925   QualType RebuildDependentSizedArrayType(QualType ElementType,
926                                           ArraySizeModifier SizeMod,
927                                           Expr *SizeExpr,
928                                           unsigned IndexTypeQuals,
929                                           SourceRange BracketsRange);
930 
931   /// Build a new vector type given the element type and
932   /// number of elements.
933   ///
934   /// By default, performs semantic analysis when building the vector type.
935   /// Subclasses may override this routine to provide different behavior.
936   QualType RebuildVectorType(QualType ElementType, unsigned NumElements,
937                              VectorKind VecKind);
938 
939   /// Build a new potentially dependently-sized extended vector type
940   /// given the element type and number of elements.
941   ///
942   /// By default, performs semantic analysis when building the vector type.
943   /// Subclasses may override this routine to provide different behavior.
944   QualType RebuildDependentVectorType(QualType ElementType, Expr *SizeExpr,
945                                       SourceLocation AttributeLoc, VectorKind);
946 
947   /// Build a new extended vector type given the element type and
948   /// number of elements.
949   ///
950   /// By default, performs semantic analysis when building the vector type.
951   /// Subclasses may override this routine to provide different behavior.
952   QualType RebuildExtVectorType(QualType ElementType, unsigned NumElements,
953                                 SourceLocation AttributeLoc);
954 
955   /// Build a new potentially dependently-sized extended vector type
956   /// given the element type and number of elements.
957   ///
958   /// By default, performs semantic analysis when building the vector type.
959   /// Subclasses may override this routine to provide different behavior.
960   QualType RebuildDependentSizedExtVectorType(QualType ElementType,
961                                               Expr *SizeExpr,
962                                               SourceLocation AttributeLoc);
963 
964   /// Build a new matrix type given the element type and dimensions.
965   QualType RebuildConstantMatrixType(QualType ElementType, unsigned NumRows,
966                                      unsigned NumColumns);
967 
968   /// Build a new matrix type given the type and dependently-defined
969   /// dimensions.
970   QualType RebuildDependentSizedMatrixType(QualType ElementType, Expr *RowExpr,
971                                            Expr *ColumnExpr,
972                                            SourceLocation AttributeLoc);
973 
974   /// Build a new DependentAddressSpaceType or return the pointee
975   /// type variable with the correct address space (retrieved from
976   /// AddrSpaceExpr) applied to it. The former will be returned in cases
977   /// where the address space remains dependent.
978   ///
979   /// By default, performs semantic analysis when building the type with address
980   /// space applied. Subclasses may override this routine to provide different
981   /// behavior.
982   QualType RebuildDependentAddressSpaceType(QualType PointeeType,
983                                             Expr *AddrSpaceExpr,
984                                             SourceLocation AttributeLoc);
985 
986   /// Build a new function type.
987   ///
988   /// By default, performs semantic analysis when building the function type.
989   /// Subclasses may override this routine to provide different behavior.
990   QualType RebuildFunctionProtoType(QualType T,
991                                     MutableArrayRef<QualType> ParamTypes,
992                                     const FunctionProtoType::ExtProtoInfo &EPI);
993 
994   /// Build a new unprototyped function type.
995   QualType RebuildFunctionNoProtoType(QualType ResultType);
996 
997   /// Rebuild an unresolved typename type, given the decl that
998   /// the UnresolvedUsingTypenameDecl was transformed to.
999   QualType RebuildUnresolvedUsingType(SourceLocation NameLoc, Decl *D);
1000 
1001   /// Build a new type found via an alias.
1002   QualType RebuildUsingType(UsingShadowDecl *Found, QualType Underlying) {
1003     return SemaRef.Context.getUsingType(Found, Underlying);
1004   }
1005 
1006   /// Build a new typedef type.
1007   QualType RebuildTypedefType(TypedefNameDecl *Typedef) {
1008     return SemaRef.Context.getTypeDeclType(Typedef);
1009   }
1010 
1011   /// Build a new MacroDefined type.
1012   QualType RebuildMacroQualifiedType(QualType T,
1013                                      const IdentifierInfo *MacroII) {
1014     return SemaRef.Context.getMacroQualifiedType(T, MacroII);
1015   }
1016 
1017   /// Build a new class/struct/union type.
1018   QualType RebuildRecordType(RecordDecl *Record) {
1019     return SemaRef.Context.getTypeDeclType(Record);
1020   }
1021 
1022   /// Build a new Enum type.
1023   QualType RebuildEnumType(EnumDecl *Enum) {
1024     return SemaRef.Context.getTypeDeclType(Enum);
1025   }
1026 
1027   /// Build a new typeof(expr) type.
1028   ///
1029   /// By default, performs semantic analysis when building the typeof type.
1030   /// Subclasses may override this routine to provide different behavior.
1031   QualType RebuildTypeOfExprType(Expr *Underlying, SourceLocation Loc,
1032                                  TypeOfKind Kind);
1033 
1034   /// Build a new typeof(type) type.
1035   ///
1036   /// By default, builds a new TypeOfType with the given underlying type.
1037   QualType RebuildTypeOfType(QualType Underlying, TypeOfKind Kind);
1038 
1039   /// Build a new unary transform type.
1040   QualType RebuildUnaryTransformType(QualType BaseType,
1041                                      UnaryTransformType::UTTKind UKind,
1042                                      SourceLocation Loc);
1043 
1044   /// Build a new C++11 decltype type.
1045   ///
1046   /// By default, performs semantic analysis when building the decltype type.
1047   /// Subclasses may override this routine to provide different behavior.
1048   QualType RebuildDecltypeType(Expr *Underlying, SourceLocation Loc);
1049 
1050   /// Build a new C++11 auto type.
1051   ///
1052   /// By default, builds a new AutoType with the given deduced type.
1053   QualType RebuildAutoType(QualType Deduced, AutoTypeKeyword Keyword,
1054                            ConceptDecl *TypeConstraintConcept,
1055                            ArrayRef<TemplateArgument> TypeConstraintArgs) {
1056     // Note, IsDependent is always false here: we implicitly convert an 'auto'
1057     // which has been deduced to a dependent type into an undeduced 'auto', so
1058     // that we'll retry deduction after the transformation.
1059     return SemaRef.Context.getAutoType(Deduced, Keyword,
1060                                        /*IsDependent*/ false, /*IsPack=*/false,
1061                                        TypeConstraintConcept,
1062                                        TypeConstraintArgs);
1063   }
1064 
1065   /// By default, builds a new DeducedTemplateSpecializationType with the given
1066   /// deduced type.
1067   QualType RebuildDeducedTemplateSpecializationType(TemplateName Template,
1068       QualType Deduced) {
1069     return SemaRef.Context.getDeducedTemplateSpecializationType(
1070         Template, Deduced, /*IsDependent*/ false);
1071   }
1072 
1073   /// Build a new template specialization type.
1074   ///
1075   /// By default, performs semantic analysis when building the template
1076   /// specialization type. Subclasses may override this routine to provide
1077   /// different behavior.
1078   QualType RebuildTemplateSpecializationType(TemplateName Template,
1079                                              SourceLocation TemplateLoc,
1080                                              TemplateArgumentListInfo &Args);
1081 
1082   /// Build a new parenthesized type.
1083   ///
1084   /// By default, builds a new ParenType type from the inner type.
1085   /// Subclasses may override this routine to provide different behavior.
1086   QualType RebuildParenType(QualType InnerType) {
1087     return SemaRef.BuildParenType(InnerType);
1088   }
1089 
1090   /// Build a new qualified name type.
1091   ///
1092   /// By default, builds a new ElaboratedType type from the keyword,
1093   /// the nested-name-specifier and the named type.
1094   /// Subclasses may override this routine to provide different behavior.
1095   QualType RebuildElaboratedType(SourceLocation KeywordLoc,
1096                                  ElaboratedTypeKeyword Keyword,
1097                                  NestedNameSpecifierLoc QualifierLoc,
1098                                  QualType Named) {
1099     return SemaRef.Context.getElaboratedType(Keyword,
1100                                          QualifierLoc.getNestedNameSpecifier(),
1101                                              Named);
1102   }
1103 
1104   /// Build a new typename type that refers to a template-id.
1105   ///
1106   /// By default, builds a new DependentNameType type from the
1107   /// nested-name-specifier and the given type. Subclasses may override
1108   /// this routine to provide different behavior.
1109   QualType RebuildDependentTemplateSpecializationType(
1110                                           ElaboratedTypeKeyword Keyword,
1111                                           NestedNameSpecifierLoc QualifierLoc,
1112                                           SourceLocation TemplateKWLoc,
1113                                           const IdentifierInfo *Name,
1114                                           SourceLocation NameLoc,
1115                                           TemplateArgumentListInfo &Args,
1116                                           bool AllowInjectedClassName) {
1117     // Rebuild the template name.
1118     // TODO: avoid TemplateName abstraction
1119     CXXScopeSpec SS;
1120     SS.Adopt(QualifierLoc);
1121     TemplateName InstName = getDerived().RebuildTemplateName(
1122         SS, TemplateKWLoc, *Name, NameLoc, QualType(), nullptr,
1123         AllowInjectedClassName);
1124 
1125     if (InstName.isNull())
1126       return QualType();
1127 
1128     // If it's still dependent, make a dependent specialization.
1129     if (InstName.getAsDependentTemplateName())
1130       return SemaRef.Context.getDependentTemplateSpecializationType(
1131           Keyword, QualifierLoc.getNestedNameSpecifier(), Name,
1132           Args.arguments());
1133 
1134     // Otherwise, make an elaborated type wrapping a non-dependent
1135     // specialization.
1136     QualType T =
1137         getDerived().RebuildTemplateSpecializationType(InstName, NameLoc, Args);
1138     if (T.isNull())
1139       return QualType();
1140     return SemaRef.Context.getElaboratedType(
1141         Keyword, QualifierLoc.getNestedNameSpecifier(), T);
1142   }
1143 
1144   /// Build a new typename type that refers to an identifier.
1145   ///
1146   /// By default, performs semantic analysis when building the typename type
1147   /// (or elaborated type). Subclasses may override this routine to provide
1148   /// different behavior.
1149   QualType RebuildDependentNameType(ElaboratedTypeKeyword Keyword,
1150                                     SourceLocation KeywordLoc,
1151                                     NestedNameSpecifierLoc QualifierLoc,
1152                                     const IdentifierInfo *Id,
1153                                     SourceLocation IdLoc,
1154                                     bool DeducedTSTContext) {
1155     CXXScopeSpec SS;
1156     SS.Adopt(QualifierLoc);
1157 
1158     if (QualifierLoc.getNestedNameSpecifier()->isDependent()) {
1159       // If the name is still dependent, just build a new dependent name type.
1160       if (!SemaRef.computeDeclContext(SS))
1161         return SemaRef.Context.getDependentNameType(Keyword,
1162                                           QualifierLoc.getNestedNameSpecifier(),
1163                                                     Id);
1164     }
1165 
1166     if (Keyword == ElaboratedTypeKeyword::None ||
1167         Keyword == ElaboratedTypeKeyword::Typename) {
1168       return SemaRef.CheckTypenameType(Keyword, KeywordLoc, QualifierLoc,
1169                                        *Id, IdLoc, DeducedTSTContext);
1170     }
1171 
1172     TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
1173 
1174     // We had a dependent elaborated-type-specifier that has been transformed
1175     // into a non-dependent elaborated-type-specifier. Find the tag we're
1176     // referring to.
1177     LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1178     DeclContext *DC = SemaRef.computeDeclContext(SS, false);
1179     if (!DC)
1180       return QualType();
1181 
1182     if (SemaRef.RequireCompleteDeclContext(SS, DC))
1183       return QualType();
1184 
1185     TagDecl *Tag = nullptr;
1186     SemaRef.LookupQualifiedName(Result, DC);
1187     switch (Result.getResultKind()) {
1188       case LookupResult::NotFound:
1189       case LookupResult::NotFoundInCurrentInstantiation:
1190         break;
1191 
1192       case LookupResult::Found:
1193         Tag = Result.getAsSingle<TagDecl>();
1194         break;
1195 
1196       case LookupResult::FoundOverloaded:
1197       case LookupResult::FoundUnresolvedValue:
1198         llvm_unreachable("Tag lookup cannot find non-tags");
1199 
1200       case LookupResult::Ambiguous:
1201         // Let the LookupResult structure handle ambiguities.
1202         return QualType();
1203     }
1204 
1205     if (!Tag) {
1206       // Check where the name exists but isn't a tag type and use that to emit
1207       // better diagnostics.
1208       LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1209       SemaRef.LookupQualifiedName(Result, DC);
1210       switch (Result.getResultKind()) {
1211         case LookupResult::Found:
1212         case LookupResult::FoundOverloaded:
1213         case LookupResult::FoundUnresolvedValue: {
1214           NamedDecl *SomeDecl = Result.getRepresentativeDecl();
1215           Sema::NonTagKind NTK = SemaRef.getNonTagTypeDeclKind(SomeDecl, Kind);
1216           SemaRef.Diag(IdLoc, diag::err_tag_reference_non_tag)
1217               << SomeDecl << NTK << llvm::to_underlying(Kind);
1218           SemaRef.Diag(SomeDecl->getLocation(), diag::note_declared_at);
1219           break;
1220         }
1221         default:
1222           SemaRef.Diag(IdLoc, diag::err_not_tag_in_scope)
1223               << llvm::to_underlying(Kind) << Id << DC
1224               << QualifierLoc.getSourceRange();
1225           break;
1226       }
1227       return QualType();
1228     }
1229 
1230     if (!SemaRef.isAcceptableTagRedeclaration(Tag, Kind, /*isDefinition*/false,
1231                                               IdLoc, Id)) {
1232       SemaRef.Diag(KeywordLoc, diag::err_use_with_wrong_tag) << Id;
1233       SemaRef.Diag(Tag->getLocation(), diag::note_previous_use);
1234       return QualType();
1235     }
1236 
1237     // Build the elaborated-type-specifier type.
1238     QualType T = SemaRef.Context.getTypeDeclType(Tag);
1239     return SemaRef.Context.getElaboratedType(Keyword,
1240                                          QualifierLoc.getNestedNameSpecifier(),
1241                                              T);
1242   }
1243 
1244   /// Build a new pack expansion type.
1245   ///
1246   /// By default, builds a new PackExpansionType type from the given pattern.
1247   /// Subclasses may override this routine to provide different behavior.
1248   QualType RebuildPackExpansionType(QualType Pattern, SourceRange PatternRange,
1249                                     SourceLocation EllipsisLoc,
1250                                     std::optional<unsigned> NumExpansions) {
1251     return getSema().CheckPackExpansion(Pattern, PatternRange, EllipsisLoc,
1252                                         NumExpansions);
1253   }
1254 
1255   /// Build a new atomic type given its value type.
1256   ///
1257   /// By default, performs semantic analysis when building the atomic type.
1258   /// Subclasses may override this routine to provide different behavior.
1259   QualType RebuildAtomicType(QualType ValueType, SourceLocation KWLoc);
1260 
1261   /// Build a new pipe type given its value type.
1262   QualType RebuildPipeType(QualType ValueType, SourceLocation KWLoc,
1263                            bool isReadPipe);
1264 
1265   /// Build a bit-precise int given its value type.
1266   QualType RebuildBitIntType(bool IsUnsigned, unsigned NumBits,
1267                              SourceLocation Loc);
1268 
1269   /// Build a dependent bit-precise int given its value type.
1270   QualType RebuildDependentBitIntType(bool IsUnsigned, Expr *NumBitsExpr,
1271                                       SourceLocation Loc);
1272 
1273   /// Build a new template name given a nested name specifier, a flag
1274   /// indicating whether the "template" keyword was provided, and the template
1275   /// that the template name refers to.
1276   ///
1277   /// By default, builds the new template name directly. Subclasses may override
1278   /// this routine to provide different behavior.
1279   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1280                                    bool TemplateKW,
1281                                    TemplateDecl *Template);
1282 
1283   /// Build a new template name given a nested name specifier and the
1284   /// name that is referred to as a template.
1285   ///
1286   /// By default, performs semantic analysis to determine whether the name can
1287   /// be resolved to a specific template, then builds the appropriate kind of
1288   /// template name. Subclasses may override this routine to provide different
1289   /// behavior.
1290   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1291                                    SourceLocation TemplateKWLoc,
1292                                    const IdentifierInfo &Name,
1293                                    SourceLocation NameLoc, QualType ObjectType,
1294                                    NamedDecl *FirstQualifierInScope,
1295                                    bool AllowInjectedClassName);
1296 
1297   /// Build a new template name given a nested name specifier and the
1298   /// overloaded operator name that is referred to as a template.
1299   ///
1300   /// By default, performs semantic analysis to determine whether the name can
1301   /// be resolved to a specific template, then builds the appropriate kind of
1302   /// template name. Subclasses may override this routine to provide different
1303   /// behavior.
1304   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1305                                    SourceLocation TemplateKWLoc,
1306                                    OverloadedOperatorKind Operator,
1307                                    SourceLocation NameLoc, QualType ObjectType,
1308                                    bool AllowInjectedClassName);
1309 
1310   /// Build a new template name given a template template parameter pack
1311   /// and the
1312   ///
1313   /// By default, performs semantic analysis to determine whether the name can
1314   /// be resolved to a specific template, then builds the appropriate kind of
1315   /// template name. Subclasses may override this routine to provide different
1316   /// behavior.
1317   TemplateName RebuildTemplateName(const TemplateArgument &ArgPack,
1318                                    Decl *AssociatedDecl, unsigned Index,
1319                                    bool Final) {
1320     return getSema().Context.getSubstTemplateTemplateParmPack(
1321         ArgPack, AssociatedDecl, Index, Final);
1322   }
1323 
1324   /// Build a new compound statement.
1325   ///
1326   /// By default, performs semantic analysis to build the new statement.
1327   /// Subclasses may override this routine to provide different behavior.
1328   StmtResult RebuildCompoundStmt(SourceLocation LBraceLoc,
1329                                        MultiStmtArg Statements,
1330                                        SourceLocation RBraceLoc,
1331                                        bool IsStmtExpr) {
1332     return getSema().ActOnCompoundStmt(LBraceLoc, RBraceLoc, Statements,
1333                                        IsStmtExpr);
1334   }
1335 
1336   /// Build a new case statement.
1337   ///
1338   /// By default, performs semantic analysis to build the new statement.
1339   /// Subclasses may override this routine to provide different behavior.
1340   StmtResult RebuildCaseStmt(SourceLocation CaseLoc,
1341                                    Expr *LHS,
1342                                    SourceLocation EllipsisLoc,
1343                                    Expr *RHS,
1344                                    SourceLocation ColonLoc) {
1345     return getSema().ActOnCaseStmt(CaseLoc, LHS, EllipsisLoc, RHS,
1346                                    ColonLoc);
1347   }
1348 
1349   /// Attach the body to a new case statement.
1350   ///
1351   /// By default, performs semantic analysis to build the new statement.
1352   /// Subclasses may override this routine to provide different behavior.
1353   StmtResult RebuildCaseStmtBody(Stmt *S, Stmt *Body) {
1354     getSema().ActOnCaseStmtBody(S, Body);
1355     return S;
1356   }
1357 
1358   /// Build a new default statement.
1359   ///
1360   /// By default, performs semantic analysis to build the new statement.
1361   /// Subclasses may override this routine to provide different behavior.
1362   StmtResult RebuildDefaultStmt(SourceLocation DefaultLoc,
1363                                       SourceLocation ColonLoc,
1364                                       Stmt *SubStmt) {
1365     return getSema().ActOnDefaultStmt(DefaultLoc, ColonLoc, SubStmt,
1366                                       /*CurScope=*/nullptr);
1367   }
1368 
1369   /// Build a new label statement.
1370   ///
1371   /// By default, performs semantic analysis to build the new statement.
1372   /// Subclasses may override this routine to provide different behavior.
1373   StmtResult RebuildLabelStmt(SourceLocation IdentLoc, LabelDecl *L,
1374                               SourceLocation ColonLoc, Stmt *SubStmt) {
1375     return SemaRef.ActOnLabelStmt(IdentLoc, L, ColonLoc, SubStmt);
1376   }
1377 
1378   /// Build a new attributed statement.
1379   ///
1380   /// By default, performs semantic analysis to build the new statement.
1381   /// Subclasses may override this routine to provide different behavior.
1382   StmtResult RebuildAttributedStmt(SourceLocation AttrLoc,
1383                                    ArrayRef<const Attr *> Attrs,
1384                                    Stmt *SubStmt) {
1385     if (SemaRef.CheckRebuiltStmtAttributes(Attrs))
1386       return StmtError();
1387     return SemaRef.BuildAttributedStmt(AttrLoc, Attrs, SubStmt);
1388   }
1389 
1390   /// Build a new "if" statement.
1391   ///
1392   /// By default, performs semantic analysis to build the new statement.
1393   /// Subclasses may override this routine to provide different behavior.
1394   StmtResult RebuildIfStmt(SourceLocation IfLoc, IfStatementKind Kind,
1395                            SourceLocation LParenLoc, Sema::ConditionResult Cond,
1396                            SourceLocation RParenLoc, Stmt *Init, Stmt *Then,
1397                            SourceLocation ElseLoc, Stmt *Else) {
1398     return getSema().ActOnIfStmt(IfLoc, Kind, LParenLoc, Init, Cond, RParenLoc,
1399                                  Then, ElseLoc, Else);
1400   }
1401 
1402   /// Start building a new switch statement.
1403   ///
1404   /// By default, performs semantic analysis to build the new statement.
1405   /// Subclasses may override this routine to provide different behavior.
1406   StmtResult RebuildSwitchStmtStart(SourceLocation SwitchLoc,
1407                                     SourceLocation LParenLoc, Stmt *Init,
1408                                     Sema::ConditionResult Cond,
1409                                     SourceLocation RParenLoc) {
1410     return getSema().ActOnStartOfSwitchStmt(SwitchLoc, LParenLoc, Init, Cond,
1411                                             RParenLoc);
1412   }
1413 
1414   /// Attach the body to the switch statement.
1415   ///
1416   /// By default, performs semantic analysis to build the new statement.
1417   /// Subclasses may override this routine to provide different behavior.
1418   StmtResult RebuildSwitchStmtBody(SourceLocation SwitchLoc,
1419                                    Stmt *Switch, Stmt *Body) {
1420     return getSema().ActOnFinishSwitchStmt(SwitchLoc, Switch, Body);
1421   }
1422 
1423   /// Build a new while statement.
1424   ///
1425   /// By default, performs semantic analysis to build the new statement.
1426   /// Subclasses may override this routine to provide different behavior.
1427   StmtResult RebuildWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc,
1428                               Sema::ConditionResult Cond,
1429                               SourceLocation RParenLoc, Stmt *Body) {
1430     return getSema().ActOnWhileStmt(WhileLoc, LParenLoc, Cond, RParenLoc, Body);
1431   }
1432 
1433   /// Build a new do-while statement.
1434   ///
1435   /// By default, performs semantic analysis to build the new statement.
1436   /// Subclasses may override this routine to provide different behavior.
1437   StmtResult RebuildDoStmt(SourceLocation DoLoc, Stmt *Body,
1438                            SourceLocation WhileLoc, SourceLocation LParenLoc,
1439                            Expr *Cond, SourceLocation RParenLoc) {
1440     return getSema().ActOnDoStmt(DoLoc, Body, WhileLoc, LParenLoc,
1441                                  Cond, RParenLoc);
1442   }
1443 
1444   /// Build a new for statement.
1445   ///
1446   /// By default, performs semantic analysis to build the new statement.
1447   /// Subclasses may override this routine to provide different behavior.
1448   StmtResult RebuildForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1449                             Stmt *Init, Sema::ConditionResult Cond,
1450                             Sema::FullExprArg Inc, SourceLocation RParenLoc,
1451                             Stmt *Body) {
1452     return getSema().ActOnForStmt(ForLoc, LParenLoc, Init, Cond,
1453                                   Inc, RParenLoc, Body);
1454   }
1455 
1456   /// Build a new goto statement.
1457   ///
1458   /// By default, performs semantic analysis to build the new statement.
1459   /// Subclasses may override this routine to provide different behavior.
1460   StmtResult RebuildGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
1461                              LabelDecl *Label) {
1462     return getSema().ActOnGotoStmt(GotoLoc, LabelLoc, Label);
1463   }
1464 
1465   /// Build a new indirect goto statement.
1466   ///
1467   /// By default, performs semantic analysis to build the new statement.
1468   /// Subclasses may override this routine to provide different behavior.
1469   StmtResult RebuildIndirectGotoStmt(SourceLocation GotoLoc,
1470                                      SourceLocation StarLoc,
1471                                      Expr *Target) {
1472     return getSema().ActOnIndirectGotoStmt(GotoLoc, StarLoc, Target);
1473   }
1474 
1475   /// Build a new return statement.
1476   ///
1477   /// By default, performs semantic analysis to build the new statement.
1478   /// Subclasses may override this routine to provide different behavior.
1479   StmtResult RebuildReturnStmt(SourceLocation ReturnLoc, Expr *Result) {
1480     return getSema().BuildReturnStmt(ReturnLoc, Result);
1481   }
1482 
1483   /// Build a new declaration statement.
1484   ///
1485   /// By default, performs semantic analysis to build the new statement.
1486   /// Subclasses may override this routine to provide different behavior.
1487   StmtResult RebuildDeclStmt(MutableArrayRef<Decl *> Decls,
1488                              SourceLocation StartLoc, SourceLocation EndLoc) {
1489     Sema::DeclGroupPtrTy DG = getSema().BuildDeclaratorGroup(Decls);
1490     return getSema().ActOnDeclStmt(DG, StartLoc, EndLoc);
1491   }
1492 
1493   /// Build a new inline asm statement.
1494   ///
1495   /// By default, performs semantic analysis to build the new statement.
1496   /// Subclasses may override this routine to provide different behavior.
1497   StmtResult RebuildGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
1498                                bool IsVolatile, unsigned NumOutputs,
1499                                unsigned NumInputs, IdentifierInfo **Names,
1500                                MultiExprArg Constraints, MultiExprArg Exprs,
1501                                Expr *AsmString, MultiExprArg Clobbers,
1502                                unsigned NumLabels,
1503                                SourceLocation RParenLoc) {
1504     return getSema().ActOnGCCAsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs,
1505                                      NumInputs, Names, Constraints, Exprs,
1506                                      AsmString, Clobbers, NumLabels, RParenLoc);
1507   }
1508 
1509   /// Build a new MS style inline asm statement.
1510   ///
1511   /// By default, performs semantic analysis to build the new statement.
1512   /// Subclasses may override this routine to provide different behavior.
1513   StmtResult RebuildMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
1514                               ArrayRef<Token> AsmToks,
1515                               StringRef AsmString,
1516                               unsigned NumOutputs, unsigned NumInputs,
1517                               ArrayRef<StringRef> Constraints,
1518                               ArrayRef<StringRef> Clobbers,
1519                               ArrayRef<Expr*> Exprs,
1520                               SourceLocation EndLoc) {
1521     return getSema().ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmString,
1522                                     NumOutputs, NumInputs,
1523                                     Constraints, Clobbers, Exprs, EndLoc);
1524   }
1525 
1526   /// Build a new co_return statement.
1527   ///
1528   /// By default, performs semantic analysis to build the new statement.
1529   /// Subclasses may override this routine to provide different behavior.
1530   StmtResult RebuildCoreturnStmt(SourceLocation CoreturnLoc, Expr *Result,
1531                                  bool IsImplicit) {
1532     return getSema().BuildCoreturnStmt(CoreturnLoc, Result, IsImplicit);
1533   }
1534 
1535   /// Build a new co_await expression.
1536   ///
1537   /// By default, performs semantic analysis to build the new expression.
1538   /// Subclasses may override this routine to provide different behavior.
1539   ExprResult RebuildCoawaitExpr(SourceLocation CoawaitLoc, Expr *Operand,
1540                                 UnresolvedLookupExpr *OpCoawaitLookup,
1541                                 bool IsImplicit) {
1542     // This function rebuilds a coawait-expr given its operator.
1543     // For an explicit coawait-expr, the rebuild involves the full set
1544     // of transformations performed by BuildUnresolvedCoawaitExpr(),
1545     // including calling await_transform().
1546     // For an implicit coawait-expr, we need to rebuild the "operator
1547     // coawait" but not await_transform(), so use BuildResolvedCoawaitExpr().
1548     // This mirrors how the implicit CoawaitExpr is originally created
1549     // in Sema::ActOnCoroutineBodyStart().
1550     if (IsImplicit) {
1551       ExprResult Suspend = getSema().BuildOperatorCoawaitCall(
1552           CoawaitLoc, Operand, OpCoawaitLookup);
1553       if (Suspend.isInvalid())
1554         return ExprError();
1555       return getSema().BuildResolvedCoawaitExpr(CoawaitLoc, Operand,
1556                                                 Suspend.get(), true);
1557     }
1558 
1559     return getSema().BuildUnresolvedCoawaitExpr(CoawaitLoc, Operand,
1560                                                 OpCoawaitLookup);
1561   }
1562 
1563   /// Build a new co_await expression.
1564   ///
1565   /// By default, performs semantic analysis to build the new expression.
1566   /// Subclasses may override this routine to provide different behavior.
1567   ExprResult RebuildDependentCoawaitExpr(SourceLocation CoawaitLoc,
1568                                          Expr *Result,
1569                                          UnresolvedLookupExpr *Lookup) {
1570     return getSema().BuildUnresolvedCoawaitExpr(CoawaitLoc, Result, Lookup);
1571   }
1572 
1573   /// Build a new co_yield expression.
1574   ///
1575   /// By default, performs semantic analysis to build the new expression.
1576   /// Subclasses may override this routine to provide different behavior.
1577   ExprResult RebuildCoyieldExpr(SourceLocation CoyieldLoc, Expr *Result) {
1578     return getSema().BuildCoyieldExpr(CoyieldLoc, Result);
1579   }
1580 
1581   StmtResult RebuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1582     return getSema().BuildCoroutineBodyStmt(Args);
1583   }
1584 
1585   /// Build a new Objective-C \@try statement.
1586   ///
1587   /// By default, performs semantic analysis to build the new statement.
1588   /// Subclasses may override this routine to provide different behavior.
1589   StmtResult RebuildObjCAtTryStmt(SourceLocation AtLoc,
1590                                         Stmt *TryBody,
1591                                         MultiStmtArg CatchStmts,
1592                                         Stmt *Finally) {
1593     return getSema().ActOnObjCAtTryStmt(AtLoc, TryBody, CatchStmts,
1594                                         Finally);
1595   }
1596 
1597   /// Rebuild an Objective-C exception declaration.
1598   ///
1599   /// By default, performs semantic analysis to build the new declaration.
1600   /// Subclasses may override this routine to provide different behavior.
1601   VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1602                                     TypeSourceInfo *TInfo, QualType T) {
1603     return getSema().BuildObjCExceptionDecl(TInfo, T,
1604                                             ExceptionDecl->getInnerLocStart(),
1605                                             ExceptionDecl->getLocation(),
1606                                             ExceptionDecl->getIdentifier());
1607   }
1608 
1609   /// Build a new Objective-C \@catch statement.
1610   ///
1611   /// By default, performs semantic analysis to build the new statement.
1612   /// Subclasses may override this routine to provide different behavior.
1613   StmtResult RebuildObjCAtCatchStmt(SourceLocation AtLoc,
1614                                           SourceLocation RParenLoc,
1615                                           VarDecl *Var,
1616                                           Stmt *Body) {
1617     return getSema().ActOnObjCAtCatchStmt(AtLoc, RParenLoc,
1618                                           Var, Body);
1619   }
1620 
1621   /// Build a new Objective-C \@finally statement.
1622   ///
1623   /// By default, performs semantic analysis to build the new statement.
1624   /// Subclasses may override this routine to provide different behavior.
1625   StmtResult RebuildObjCAtFinallyStmt(SourceLocation AtLoc,
1626                                             Stmt *Body) {
1627     return getSema().ActOnObjCAtFinallyStmt(AtLoc, Body);
1628   }
1629 
1630   /// Build a new Objective-C \@throw statement.
1631   ///
1632   /// By default, performs semantic analysis to build the new statement.
1633   /// Subclasses may override this routine to provide different behavior.
1634   StmtResult RebuildObjCAtThrowStmt(SourceLocation AtLoc,
1635                                           Expr *Operand) {
1636     return getSema().BuildObjCAtThrowStmt(AtLoc, Operand);
1637   }
1638 
1639   /// Build a new OpenMP Canonical loop.
1640   ///
1641   /// Ensures that the outermost loop in @p LoopStmt is wrapped by a
1642   /// OMPCanonicalLoop.
1643   StmtResult RebuildOMPCanonicalLoop(Stmt *LoopStmt) {
1644     return getSema().ActOnOpenMPCanonicalLoop(LoopStmt);
1645   }
1646 
1647   /// Build a new OpenMP executable directive.
1648   ///
1649   /// By default, performs semantic analysis to build the new statement.
1650   /// Subclasses may override this routine to provide different behavior.
1651   StmtResult RebuildOMPExecutableDirective(
1652       OpenMPDirectiveKind Kind, DeclarationNameInfo DirName,
1653       OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
1654       Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc,
1655       OpenMPDirectiveKind PrevMappedDirective = OMPD_unknown) {
1656 
1657     return getSema().ActOnOpenMPExecutableDirective(
1658         Kind, DirName, CancelRegion, Clauses, AStmt, StartLoc, EndLoc,
1659         PrevMappedDirective);
1660   }
1661 
1662   /// Build a new OpenMP 'if' 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 *RebuildOMPIfClause(OpenMPDirectiveKind NameModifier,
1667                                 Expr *Condition, SourceLocation StartLoc,
1668                                 SourceLocation LParenLoc,
1669                                 SourceLocation NameModifierLoc,
1670                                 SourceLocation ColonLoc,
1671                                 SourceLocation EndLoc) {
1672     return getSema().ActOnOpenMPIfClause(NameModifier, Condition, StartLoc,
1673                                          LParenLoc, NameModifierLoc, ColonLoc,
1674                                          EndLoc);
1675   }
1676 
1677   /// Build a new OpenMP 'final' clause.
1678   ///
1679   /// By default, performs semantic analysis to build the new OpenMP clause.
1680   /// Subclasses may override this routine to provide different behavior.
1681   OMPClause *RebuildOMPFinalClause(Expr *Condition, SourceLocation StartLoc,
1682                                    SourceLocation LParenLoc,
1683                                    SourceLocation EndLoc) {
1684     return getSema().ActOnOpenMPFinalClause(Condition, StartLoc, LParenLoc,
1685                                             EndLoc);
1686   }
1687 
1688   /// Build a new OpenMP 'num_threads' clause.
1689   ///
1690   /// By default, performs semantic analysis to build the new OpenMP clause.
1691   /// Subclasses may override this routine to provide different behavior.
1692   OMPClause *RebuildOMPNumThreadsClause(Expr *NumThreads,
1693                                         SourceLocation StartLoc,
1694                                         SourceLocation LParenLoc,
1695                                         SourceLocation EndLoc) {
1696     return getSema().ActOnOpenMPNumThreadsClause(NumThreads, StartLoc,
1697                                                  LParenLoc, EndLoc);
1698   }
1699 
1700   /// Build a new OpenMP 'safelen' clause.
1701   ///
1702   /// By default, performs semantic analysis to build the new OpenMP clause.
1703   /// Subclasses may override this routine to provide different behavior.
1704   OMPClause *RebuildOMPSafelenClause(Expr *Len, SourceLocation StartLoc,
1705                                      SourceLocation LParenLoc,
1706                                      SourceLocation EndLoc) {
1707     return getSema().ActOnOpenMPSafelenClause(Len, StartLoc, LParenLoc, EndLoc);
1708   }
1709 
1710   /// Build a new OpenMP 'simdlen' clause.
1711   ///
1712   /// By default, performs semantic analysis to build the new OpenMP clause.
1713   /// Subclasses may override this routine to provide different behavior.
1714   OMPClause *RebuildOMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
1715                                      SourceLocation LParenLoc,
1716                                      SourceLocation EndLoc) {
1717     return getSema().ActOnOpenMPSimdlenClause(Len, StartLoc, LParenLoc, EndLoc);
1718   }
1719 
1720   OMPClause *RebuildOMPSizesClause(ArrayRef<Expr *> Sizes,
1721                                    SourceLocation StartLoc,
1722                                    SourceLocation LParenLoc,
1723                                    SourceLocation EndLoc) {
1724     return getSema().ActOnOpenMPSizesClause(Sizes, StartLoc, LParenLoc, EndLoc);
1725   }
1726 
1727   /// Build a new OpenMP 'full' clause.
1728   OMPClause *RebuildOMPFullClause(SourceLocation StartLoc,
1729                                   SourceLocation EndLoc) {
1730     return getSema().ActOnOpenMPFullClause(StartLoc, EndLoc);
1731   }
1732 
1733   /// Build a new OpenMP 'partial' clause.
1734   OMPClause *RebuildOMPPartialClause(Expr *Factor, SourceLocation StartLoc,
1735                                      SourceLocation LParenLoc,
1736                                      SourceLocation EndLoc) {
1737     return getSema().ActOnOpenMPPartialClause(Factor, StartLoc, LParenLoc,
1738                                               EndLoc);
1739   }
1740 
1741   /// Build a new OpenMP 'allocator' clause.
1742   ///
1743   /// By default, performs semantic analysis to build the new OpenMP clause.
1744   /// Subclasses may override this routine to provide different behavior.
1745   OMPClause *RebuildOMPAllocatorClause(Expr *A, SourceLocation StartLoc,
1746                                        SourceLocation LParenLoc,
1747                                        SourceLocation EndLoc) {
1748     return getSema().ActOnOpenMPAllocatorClause(A, StartLoc, LParenLoc, EndLoc);
1749   }
1750 
1751   /// Build a new OpenMP 'collapse' clause.
1752   ///
1753   /// By default, performs semantic analysis to build the new OpenMP clause.
1754   /// Subclasses may override this routine to provide different behavior.
1755   OMPClause *RebuildOMPCollapseClause(Expr *Num, SourceLocation StartLoc,
1756                                       SourceLocation LParenLoc,
1757                                       SourceLocation EndLoc) {
1758     return getSema().ActOnOpenMPCollapseClause(Num, StartLoc, LParenLoc,
1759                                                EndLoc);
1760   }
1761 
1762   /// Build a new OpenMP 'default' clause.
1763   ///
1764   /// By default, performs semantic analysis to build the new OpenMP clause.
1765   /// Subclasses may override this routine to provide different behavior.
1766   OMPClause *RebuildOMPDefaultClause(DefaultKind Kind, SourceLocation KindKwLoc,
1767                                      SourceLocation StartLoc,
1768                                      SourceLocation LParenLoc,
1769                                      SourceLocation EndLoc) {
1770     return getSema().ActOnOpenMPDefaultClause(Kind, KindKwLoc,
1771                                               StartLoc, LParenLoc, EndLoc);
1772   }
1773 
1774   /// Build a new OpenMP 'proc_bind' clause.
1775   ///
1776   /// By default, performs semantic analysis to build the new OpenMP clause.
1777   /// Subclasses may override this routine to provide different behavior.
1778   OMPClause *RebuildOMPProcBindClause(ProcBindKind Kind,
1779                                       SourceLocation KindKwLoc,
1780                                       SourceLocation StartLoc,
1781                                       SourceLocation LParenLoc,
1782                                       SourceLocation EndLoc) {
1783     return getSema().ActOnOpenMPProcBindClause(Kind, KindKwLoc,
1784                                                StartLoc, LParenLoc, EndLoc);
1785   }
1786 
1787   /// Build a new OpenMP 'schedule' clause.
1788   ///
1789   /// By default, performs semantic analysis to build the new OpenMP clause.
1790   /// Subclasses may override this routine to provide different behavior.
1791   OMPClause *RebuildOMPScheduleClause(
1792       OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
1793       OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
1794       SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
1795       SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
1796     return getSema().ActOnOpenMPScheduleClause(
1797         M1, M2, Kind, ChunkSize, StartLoc, LParenLoc, M1Loc, M2Loc, KindLoc,
1798         CommaLoc, EndLoc);
1799   }
1800 
1801   /// Build a new OpenMP 'ordered' clause.
1802   ///
1803   /// By default, performs semantic analysis to build the new OpenMP clause.
1804   /// Subclasses may override this routine to provide different behavior.
1805   OMPClause *RebuildOMPOrderedClause(SourceLocation StartLoc,
1806                                      SourceLocation EndLoc,
1807                                      SourceLocation LParenLoc, Expr *Num) {
1808     return getSema().ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Num);
1809   }
1810 
1811   /// Build a new OpenMP 'private' clause.
1812   ///
1813   /// By default, performs semantic analysis to build the new OpenMP clause.
1814   /// Subclasses may override this routine to provide different behavior.
1815   OMPClause *RebuildOMPPrivateClause(ArrayRef<Expr *> VarList,
1816                                      SourceLocation StartLoc,
1817                                      SourceLocation LParenLoc,
1818                                      SourceLocation EndLoc) {
1819     return getSema().ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc,
1820                                               EndLoc);
1821   }
1822 
1823   /// Build a new OpenMP 'firstprivate' clause.
1824   ///
1825   /// By default, performs semantic analysis to build the new OpenMP clause.
1826   /// Subclasses may override this routine to provide different behavior.
1827   OMPClause *RebuildOMPFirstprivateClause(ArrayRef<Expr *> VarList,
1828                                           SourceLocation StartLoc,
1829                                           SourceLocation LParenLoc,
1830                                           SourceLocation EndLoc) {
1831     return getSema().ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc,
1832                                                    EndLoc);
1833   }
1834 
1835   /// Build a new OpenMP 'lastprivate' clause.
1836   ///
1837   /// By default, performs semantic analysis to build the new OpenMP clause.
1838   /// Subclasses may override this routine to provide different behavior.
1839   OMPClause *RebuildOMPLastprivateClause(ArrayRef<Expr *> VarList,
1840                                          OpenMPLastprivateModifier LPKind,
1841                                          SourceLocation LPKindLoc,
1842                                          SourceLocation ColonLoc,
1843                                          SourceLocation StartLoc,
1844                                          SourceLocation LParenLoc,
1845                                          SourceLocation EndLoc) {
1846     return getSema().ActOnOpenMPLastprivateClause(
1847         VarList, LPKind, LPKindLoc, ColonLoc, StartLoc, LParenLoc, EndLoc);
1848   }
1849 
1850   /// Build a new OpenMP 'shared' clause.
1851   ///
1852   /// By default, performs semantic analysis to build the new OpenMP clause.
1853   /// Subclasses may override this routine to provide different behavior.
1854   OMPClause *RebuildOMPSharedClause(ArrayRef<Expr *> VarList,
1855                                     SourceLocation StartLoc,
1856                                     SourceLocation LParenLoc,
1857                                     SourceLocation EndLoc) {
1858     return getSema().ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc,
1859                                              EndLoc);
1860   }
1861 
1862   /// Build a new OpenMP 'reduction' clause.
1863   ///
1864   /// By default, performs semantic analysis to build the new statement.
1865   /// Subclasses may override this routine to provide different behavior.
1866   OMPClause *RebuildOMPReductionClause(
1867       ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier,
1868       SourceLocation StartLoc, SourceLocation LParenLoc,
1869       SourceLocation ModifierLoc, SourceLocation ColonLoc,
1870       SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
1871       const DeclarationNameInfo &ReductionId,
1872       ArrayRef<Expr *> UnresolvedReductions) {
1873     return getSema().ActOnOpenMPReductionClause(
1874         VarList, Modifier, StartLoc, LParenLoc, ModifierLoc, ColonLoc, EndLoc,
1875         ReductionIdScopeSpec, ReductionId, UnresolvedReductions);
1876   }
1877 
1878   /// Build a new OpenMP 'task_reduction' clause.
1879   ///
1880   /// By default, performs semantic analysis to build the new statement.
1881   /// Subclasses may override this routine to provide different behavior.
1882   OMPClause *RebuildOMPTaskReductionClause(
1883       ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1884       SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
1885       CXXScopeSpec &ReductionIdScopeSpec,
1886       const DeclarationNameInfo &ReductionId,
1887       ArrayRef<Expr *> UnresolvedReductions) {
1888     return getSema().ActOnOpenMPTaskReductionClause(
1889         VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1890         ReductionId, UnresolvedReductions);
1891   }
1892 
1893   /// Build a new OpenMP 'in_reduction' clause.
1894   ///
1895   /// By default, performs semantic analysis to build the new statement.
1896   /// Subclasses may override this routine to provide different behavior.
1897   OMPClause *
1898   RebuildOMPInReductionClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1899                               SourceLocation LParenLoc, SourceLocation ColonLoc,
1900                               SourceLocation EndLoc,
1901                               CXXScopeSpec &ReductionIdScopeSpec,
1902                               const DeclarationNameInfo &ReductionId,
1903                               ArrayRef<Expr *> UnresolvedReductions) {
1904     return getSema().ActOnOpenMPInReductionClause(
1905         VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1906         ReductionId, UnresolvedReductions);
1907   }
1908 
1909   /// Build a new OpenMP 'linear' clause.
1910   ///
1911   /// By default, performs semantic analysis to build the new OpenMP clause.
1912   /// Subclasses may override this routine to provide different behavior.
1913   OMPClause *RebuildOMPLinearClause(
1914       ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
1915       SourceLocation LParenLoc, OpenMPLinearClauseKind Modifier,
1916       SourceLocation ModifierLoc, SourceLocation ColonLoc,
1917       SourceLocation StepModifierLoc, SourceLocation EndLoc) {
1918     return getSema().ActOnOpenMPLinearClause(VarList, Step, StartLoc, LParenLoc,
1919                                              Modifier, ModifierLoc, ColonLoc,
1920                                              StepModifierLoc, EndLoc);
1921   }
1922 
1923   /// Build a new OpenMP 'aligned' clause.
1924   ///
1925   /// By default, performs semantic analysis to build the new OpenMP clause.
1926   /// Subclasses may override this routine to provide different behavior.
1927   OMPClause *RebuildOMPAlignedClause(ArrayRef<Expr *> VarList, Expr *Alignment,
1928                                      SourceLocation StartLoc,
1929                                      SourceLocation LParenLoc,
1930                                      SourceLocation ColonLoc,
1931                                      SourceLocation EndLoc) {
1932     return getSema().ActOnOpenMPAlignedClause(VarList, Alignment, StartLoc,
1933                                               LParenLoc, ColonLoc, EndLoc);
1934   }
1935 
1936   /// Build a new OpenMP 'copyin' 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 *RebuildOMPCopyinClause(ArrayRef<Expr *> VarList,
1941                                     SourceLocation StartLoc,
1942                                     SourceLocation LParenLoc,
1943                                     SourceLocation EndLoc) {
1944     return getSema().ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc,
1945                                              EndLoc);
1946   }
1947 
1948   /// Build a new OpenMP 'copyprivate' 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 *RebuildOMPCopyprivateClause(ArrayRef<Expr *> VarList,
1953                                          SourceLocation StartLoc,
1954                                          SourceLocation LParenLoc,
1955                                          SourceLocation EndLoc) {
1956     return getSema().ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc,
1957                                                   EndLoc);
1958   }
1959 
1960   /// Build a new OpenMP 'flush' pseudo clause.
1961   ///
1962   /// By default, performs semantic analysis to build the new OpenMP clause.
1963   /// Subclasses may override this routine to provide different behavior.
1964   OMPClause *RebuildOMPFlushClause(ArrayRef<Expr *> VarList,
1965                                    SourceLocation StartLoc,
1966                                    SourceLocation LParenLoc,
1967                                    SourceLocation EndLoc) {
1968     return getSema().ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc,
1969                                             EndLoc);
1970   }
1971 
1972   /// Build a new OpenMP 'depobj' pseudo clause.
1973   ///
1974   /// By default, performs semantic analysis to build the new OpenMP clause.
1975   /// Subclasses may override this routine to provide different behavior.
1976   OMPClause *RebuildOMPDepobjClause(Expr *Depobj, SourceLocation StartLoc,
1977                                     SourceLocation LParenLoc,
1978                                     SourceLocation EndLoc) {
1979     return getSema().ActOnOpenMPDepobjClause(Depobj, StartLoc, LParenLoc,
1980                                              EndLoc);
1981   }
1982 
1983   /// Build a new OpenMP 'depend' pseudo clause.
1984   ///
1985   /// By default, performs semantic analysis to build the new OpenMP clause.
1986   /// Subclasses may override this routine to provide different behavior.
1987   OMPClause *RebuildOMPDependClause(OMPDependClause::DependDataTy Data,
1988                                     Expr *DepModifier, ArrayRef<Expr *> VarList,
1989                                     SourceLocation StartLoc,
1990                                     SourceLocation LParenLoc,
1991                                     SourceLocation EndLoc) {
1992     return getSema().ActOnOpenMPDependClause(Data, DepModifier, VarList,
1993                                              StartLoc, LParenLoc, EndLoc);
1994   }
1995 
1996   /// Build a new OpenMP 'device' clause.
1997   ///
1998   /// By default, performs semantic analysis to build the new statement.
1999   /// Subclasses may override this routine to provide different behavior.
2000   OMPClause *RebuildOMPDeviceClause(OpenMPDeviceClauseModifier Modifier,
2001                                     Expr *Device, SourceLocation StartLoc,
2002                                     SourceLocation LParenLoc,
2003                                     SourceLocation ModifierLoc,
2004                                     SourceLocation EndLoc) {
2005     return getSema().ActOnOpenMPDeviceClause(Modifier, Device, StartLoc,
2006                                              LParenLoc, ModifierLoc, EndLoc);
2007   }
2008 
2009   /// Build a new OpenMP 'map' clause.
2010   ///
2011   /// By default, performs semantic analysis to build the new OpenMP clause.
2012   /// Subclasses may override this routine to provide different behavior.
2013   OMPClause *RebuildOMPMapClause(
2014       Expr *IteratorModifier, ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
2015       ArrayRef<SourceLocation> MapTypeModifiersLoc,
2016       CXXScopeSpec MapperIdScopeSpec, DeclarationNameInfo MapperId,
2017       OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
2018       SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
2019       const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
2020     return getSema().ActOnOpenMPMapClause(
2021         IteratorModifier, MapTypeModifiers, MapTypeModifiersLoc,
2022         MapperIdScopeSpec, MapperId, MapType, IsMapTypeImplicit, MapLoc,
2023         ColonLoc, VarList, Locs,
2024         /*NoDiagnose=*/false, UnresolvedMappers);
2025   }
2026 
2027   /// Build a new OpenMP 'allocate' clause.
2028   ///
2029   /// By default, performs semantic analysis to build the new OpenMP clause.
2030   /// Subclasses may override this routine to provide different behavior.
2031   OMPClause *RebuildOMPAllocateClause(Expr *Allocate, ArrayRef<Expr *> VarList,
2032                                       SourceLocation StartLoc,
2033                                       SourceLocation LParenLoc,
2034                                       SourceLocation ColonLoc,
2035                                       SourceLocation EndLoc) {
2036     return getSema().ActOnOpenMPAllocateClause(Allocate, VarList, StartLoc,
2037                                                LParenLoc, ColonLoc, EndLoc);
2038   }
2039 
2040   /// Build a new OpenMP 'num_teams' clause.
2041   ///
2042   /// By default, performs semantic analysis to build the new statement.
2043   /// Subclasses may override this routine to provide different behavior.
2044   OMPClause *RebuildOMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
2045                                       SourceLocation LParenLoc,
2046                                       SourceLocation EndLoc) {
2047     return getSema().ActOnOpenMPNumTeamsClause(NumTeams, StartLoc, LParenLoc,
2048                                                EndLoc);
2049   }
2050 
2051   /// Build a new OpenMP 'thread_limit' clause.
2052   ///
2053   /// By default, performs semantic analysis to build the new statement.
2054   /// Subclasses may override this routine to provide different behavior.
2055   OMPClause *RebuildOMPThreadLimitClause(Expr *ThreadLimit,
2056                                          SourceLocation StartLoc,
2057                                          SourceLocation LParenLoc,
2058                                          SourceLocation EndLoc) {
2059     return getSema().ActOnOpenMPThreadLimitClause(ThreadLimit, StartLoc,
2060                                                   LParenLoc, EndLoc);
2061   }
2062 
2063   /// Build a new OpenMP 'priority' 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 *RebuildOMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
2068                                       SourceLocation LParenLoc,
2069                                       SourceLocation EndLoc) {
2070     return getSema().ActOnOpenMPPriorityClause(Priority, StartLoc, LParenLoc,
2071                                                EndLoc);
2072   }
2073 
2074   /// Build a new OpenMP 'grainsize' clause.
2075   ///
2076   /// By default, performs semantic analysis to build the new statement.
2077   /// Subclasses may override this routine to provide different behavior.
2078   OMPClause *RebuildOMPGrainsizeClause(OpenMPGrainsizeClauseModifier Modifier,
2079                                        Expr *Device, SourceLocation StartLoc,
2080                                        SourceLocation LParenLoc,
2081                                        SourceLocation ModifierLoc,
2082                                        SourceLocation EndLoc) {
2083     return getSema().ActOnOpenMPGrainsizeClause(Modifier, Device, StartLoc,
2084                                                 LParenLoc, ModifierLoc, EndLoc);
2085   }
2086 
2087   /// Build a new OpenMP 'num_tasks' clause.
2088   ///
2089   /// By default, performs semantic analysis to build the new statement.
2090   /// Subclasses may override this routine to provide different behavior.
2091   OMPClause *RebuildOMPNumTasksClause(OpenMPNumTasksClauseModifier Modifier,
2092                                       Expr *NumTasks, SourceLocation StartLoc,
2093                                       SourceLocation LParenLoc,
2094                                       SourceLocation ModifierLoc,
2095                                       SourceLocation EndLoc) {
2096     return getSema().ActOnOpenMPNumTasksClause(Modifier, NumTasks, StartLoc,
2097                                                LParenLoc, ModifierLoc, EndLoc);
2098   }
2099 
2100   /// Build a new OpenMP 'hint' clause.
2101   ///
2102   /// By default, performs semantic analysis to build the new statement.
2103   /// Subclasses may override this routine to provide different behavior.
2104   OMPClause *RebuildOMPHintClause(Expr *Hint, SourceLocation StartLoc,
2105                                   SourceLocation LParenLoc,
2106                                   SourceLocation EndLoc) {
2107     return getSema().ActOnOpenMPHintClause(Hint, StartLoc, LParenLoc, EndLoc);
2108   }
2109 
2110   /// Build a new OpenMP 'detach' clause.
2111   ///
2112   /// By default, performs semantic analysis to build the new statement.
2113   /// Subclasses may override this routine to provide different behavior.
2114   OMPClause *RebuildOMPDetachClause(Expr *Evt, SourceLocation StartLoc,
2115                                     SourceLocation LParenLoc,
2116                                     SourceLocation EndLoc) {
2117     return getSema().ActOnOpenMPDetachClause(Evt, StartLoc, LParenLoc, EndLoc);
2118   }
2119 
2120   /// Build a new OpenMP 'dist_schedule' clause.
2121   ///
2122   /// By default, performs semantic analysis to build the new OpenMP clause.
2123   /// Subclasses may override this routine to provide different behavior.
2124   OMPClause *
2125   RebuildOMPDistScheduleClause(OpenMPDistScheduleClauseKind Kind,
2126                                Expr *ChunkSize, SourceLocation StartLoc,
2127                                SourceLocation LParenLoc, SourceLocation KindLoc,
2128                                SourceLocation CommaLoc, SourceLocation EndLoc) {
2129     return getSema().ActOnOpenMPDistScheduleClause(
2130         Kind, ChunkSize, StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc);
2131   }
2132 
2133   /// Build a new OpenMP 'to' clause.
2134   ///
2135   /// By default, performs semantic analysis to build the new statement.
2136   /// Subclasses may override this routine to provide different behavior.
2137   OMPClause *
2138   RebuildOMPToClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
2139                      ArrayRef<SourceLocation> MotionModifiersLoc,
2140                      CXXScopeSpec &MapperIdScopeSpec,
2141                      DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
2142                      ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
2143                      ArrayRef<Expr *> UnresolvedMappers) {
2144     return getSema().ActOnOpenMPToClause(MotionModifiers, MotionModifiersLoc,
2145                                          MapperIdScopeSpec, MapperId, ColonLoc,
2146                                          VarList, Locs, UnresolvedMappers);
2147   }
2148 
2149   /// Build a new OpenMP 'from' clause.
2150   ///
2151   /// By default, performs semantic analysis to build the new statement.
2152   /// Subclasses may override this routine to provide different behavior.
2153   OMPClause *
2154   RebuildOMPFromClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
2155                        ArrayRef<SourceLocation> MotionModifiersLoc,
2156                        CXXScopeSpec &MapperIdScopeSpec,
2157                        DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
2158                        ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
2159                        ArrayRef<Expr *> UnresolvedMappers) {
2160     return getSema().ActOnOpenMPFromClause(
2161         MotionModifiers, MotionModifiersLoc, MapperIdScopeSpec, MapperId,
2162         ColonLoc, VarList, Locs, UnresolvedMappers);
2163   }
2164 
2165   /// Build a new OpenMP 'use_device_ptr' clause.
2166   ///
2167   /// By default, performs semantic analysis to build the new OpenMP clause.
2168   /// Subclasses may override this routine to provide different behavior.
2169   OMPClause *RebuildOMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
2170                                           const OMPVarListLocTy &Locs) {
2171     return getSema().ActOnOpenMPUseDevicePtrClause(VarList, Locs);
2172   }
2173 
2174   /// Build a new OpenMP 'use_device_addr' clause.
2175   ///
2176   /// By default, performs semantic analysis to build the new OpenMP clause.
2177   /// Subclasses may override this routine to provide different behavior.
2178   OMPClause *RebuildOMPUseDeviceAddrClause(ArrayRef<Expr *> VarList,
2179                                            const OMPVarListLocTy &Locs) {
2180     return getSema().ActOnOpenMPUseDeviceAddrClause(VarList, Locs);
2181   }
2182 
2183   /// Build a new OpenMP 'is_device_ptr' clause.
2184   ///
2185   /// By default, performs semantic analysis to build the new OpenMP clause.
2186   /// Subclasses may override this routine to provide different behavior.
2187   OMPClause *RebuildOMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
2188                                          const OMPVarListLocTy &Locs) {
2189     return getSema().ActOnOpenMPIsDevicePtrClause(VarList, Locs);
2190   }
2191 
2192   /// Build a new OpenMP 'has_device_addr' 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 *RebuildOMPHasDeviceAddrClause(ArrayRef<Expr *> VarList,
2197                                            const OMPVarListLocTy &Locs) {
2198     return getSema().ActOnOpenMPHasDeviceAddrClause(VarList, Locs);
2199   }
2200 
2201   /// Build a new OpenMP 'defaultmap' clause.
2202   ///
2203   /// By default, performs semantic analysis to build the new OpenMP clause.
2204   /// Subclasses may override this routine to provide different behavior.
2205   OMPClause *RebuildOMPDefaultmapClause(OpenMPDefaultmapClauseModifier M,
2206                                         OpenMPDefaultmapClauseKind Kind,
2207                                         SourceLocation StartLoc,
2208                                         SourceLocation LParenLoc,
2209                                         SourceLocation MLoc,
2210                                         SourceLocation KindLoc,
2211                                         SourceLocation EndLoc) {
2212     return getSema().ActOnOpenMPDefaultmapClause(M, Kind, StartLoc, LParenLoc,
2213                                                  MLoc, KindLoc, EndLoc);
2214   }
2215 
2216   /// Build a new OpenMP 'nontemporal' 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 *RebuildOMPNontemporalClause(ArrayRef<Expr *> VarList,
2221                                          SourceLocation StartLoc,
2222                                          SourceLocation LParenLoc,
2223                                          SourceLocation EndLoc) {
2224     return getSema().ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc,
2225                                                   EndLoc);
2226   }
2227 
2228   /// Build a new OpenMP 'inclusive' 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 *RebuildOMPInclusiveClause(ArrayRef<Expr *> VarList,
2233                                        SourceLocation StartLoc,
2234                                        SourceLocation LParenLoc,
2235                                        SourceLocation EndLoc) {
2236     return getSema().ActOnOpenMPInclusiveClause(VarList, StartLoc, LParenLoc,
2237                                                 EndLoc);
2238   }
2239 
2240   /// Build a new OpenMP 'exclusive' clause.
2241   ///
2242   /// By default, performs semantic analysis to build the new OpenMP clause.
2243   /// Subclasses may override this routine to provide different behavior.
2244   OMPClause *RebuildOMPExclusiveClause(ArrayRef<Expr *> VarList,
2245                                        SourceLocation StartLoc,
2246                                        SourceLocation LParenLoc,
2247                                        SourceLocation EndLoc) {
2248     return getSema().ActOnOpenMPExclusiveClause(VarList, StartLoc, LParenLoc,
2249                                                 EndLoc);
2250   }
2251 
2252   /// Build a new OpenMP 'uses_allocators' 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 *RebuildOMPUsesAllocatorsClause(
2257       ArrayRef<Sema::UsesAllocatorsData> Data, SourceLocation StartLoc,
2258       SourceLocation LParenLoc, SourceLocation EndLoc) {
2259     return getSema().ActOnOpenMPUsesAllocatorClause(StartLoc, LParenLoc, EndLoc,
2260                                                     Data);
2261   }
2262 
2263   /// Build a new OpenMP 'affinity' clause.
2264   ///
2265   /// By default, performs semantic analysis to build the new OpenMP clause.
2266   /// Subclasses may override this routine to provide different behavior.
2267   OMPClause *RebuildOMPAffinityClause(SourceLocation StartLoc,
2268                                       SourceLocation LParenLoc,
2269                                       SourceLocation ColonLoc,
2270                                       SourceLocation EndLoc, Expr *Modifier,
2271                                       ArrayRef<Expr *> Locators) {
2272     return getSema().ActOnOpenMPAffinityClause(StartLoc, LParenLoc, ColonLoc,
2273                                                EndLoc, Modifier, Locators);
2274   }
2275 
2276   /// Build a new OpenMP 'order' clause.
2277   ///
2278   /// By default, performs semantic analysis to build the new OpenMP clause.
2279   /// Subclasses may override this routine to provide different behavior.
2280   OMPClause *RebuildOMPOrderClause(
2281       OpenMPOrderClauseKind Kind, SourceLocation KindKwLoc,
2282       SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc,
2283       OpenMPOrderClauseModifier Modifier, SourceLocation ModifierKwLoc) {
2284     return getSema().ActOnOpenMPOrderClause(Modifier, Kind, StartLoc, LParenLoc,
2285                                             ModifierKwLoc, KindKwLoc, EndLoc);
2286   }
2287 
2288   /// Build a new OpenMP 'init' 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 *RebuildOMPInitClause(Expr *InteropVar, OMPInteropInfo &InteropInfo,
2293                                   SourceLocation StartLoc,
2294                                   SourceLocation LParenLoc,
2295                                   SourceLocation VarLoc,
2296                                   SourceLocation EndLoc) {
2297     return getSema().ActOnOpenMPInitClause(InteropVar, InteropInfo, StartLoc,
2298                                            LParenLoc, VarLoc, EndLoc);
2299   }
2300 
2301   /// Build a new OpenMP 'use' clause.
2302   ///
2303   /// By default, performs semantic analysis to build the new OpenMP clause.
2304   /// Subclasses may override this routine to provide different behavior.
2305   OMPClause *RebuildOMPUseClause(Expr *InteropVar, SourceLocation StartLoc,
2306                                  SourceLocation LParenLoc,
2307                                  SourceLocation VarLoc, SourceLocation EndLoc) {
2308     return getSema().ActOnOpenMPUseClause(InteropVar, StartLoc, LParenLoc,
2309                                           VarLoc, EndLoc);
2310   }
2311 
2312   /// Build a new OpenMP 'destroy' 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 *RebuildOMPDestroyClause(Expr *InteropVar, SourceLocation StartLoc,
2317                                      SourceLocation LParenLoc,
2318                                      SourceLocation VarLoc,
2319                                      SourceLocation EndLoc) {
2320     return getSema().ActOnOpenMPDestroyClause(InteropVar, StartLoc, LParenLoc,
2321                                               VarLoc, EndLoc);
2322   }
2323 
2324   /// Build a new OpenMP 'novariants' clause.
2325   ///
2326   /// By default, performs semantic analysis to build the new OpenMP clause.
2327   /// Subclasses may override this routine to provide different behavior.
2328   OMPClause *RebuildOMPNovariantsClause(Expr *Condition,
2329                                         SourceLocation StartLoc,
2330                                         SourceLocation LParenLoc,
2331                                         SourceLocation EndLoc) {
2332     return getSema().ActOnOpenMPNovariantsClause(Condition, StartLoc, LParenLoc,
2333                                                  EndLoc);
2334   }
2335 
2336   /// Build a new OpenMP 'nocontext' clause.
2337   ///
2338   /// By default, performs semantic analysis to build the new OpenMP clause.
2339   /// Subclasses may override this routine to provide different behavior.
2340   OMPClause *RebuildOMPNocontextClause(Expr *Condition, SourceLocation StartLoc,
2341                                        SourceLocation LParenLoc,
2342                                        SourceLocation EndLoc) {
2343     return getSema().ActOnOpenMPNocontextClause(Condition, StartLoc, LParenLoc,
2344                                                 EndLoc);
2345   }
2346 
2347   /// Build a new OpenMP 'filter' 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 *RebuildOMPFilterClause(Expr *ThreadID, SourceLocation StartLoc,
2352                                     SourceLocation LParenLoc,
2353                                     SourceLocation EndLoc) {
2354     return getSema().ActOnOpenMPFilterClause(ThreadID, StartLoc, LParenLoc,
2355                                              EndLoc);
2356   }
2357 
2358   /// Build a new OpenMP 'bind' 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 *RebuildOMPBindClause(OpenMPBindClauseKind Kind,
2363                                   SourceLocation KindLoc,
2364                                   SourceLocation StartLoc,
2365                                   SourceLocation LParenLoc,
2366                                   SourceLocation EndLoc) {
2367     return getSema().ActOnOpenMPBindClause(Kind, KindLoc, StartLoc, LParenLoc,
2368                                            EndLoc);
2369   }
2370 
2371   /// Build a new OpenMP 'ompx_dyn_cgroup_mem' clause.
2372   ///
2373   /// By default, performs semantic analysis to build the new OpenMP clause.
2374   /// Subclasses may override this routine to provide different behavior.
2375   OMPClause *RebuildOMPXDynCGroupMemClause(Expr *Size, SourceLocation StartLoc,
2376                                            SourceLocation LParenLoc,
2377                                            SourceLocation EndLoc) {
2378     return getSema().ActOnOpenMPXDynCGroupMemClause(Size, StartLoc, LParenLoc,
2379                                                     EndLoc);
2380   }
2381 
2382   /// Build a new OpenMP 'ompx_attribute' clause.
2383   ///
2384   /// By default, performs semantic analysis to build the new OpenMP clause.
2385   /// Subclasses may override this routine to provide different behavior.
2386   OMPClause *RebuildOMPXAttributeClause(ArrayRef<const Attr *> Attrs,
2387                                         SourceLocation StartLoc,
2388                                         SourceLocation LParenLoc,
2389                                         SourceLocation EndLoc) {
2390     return getSema().ActOnOpenMPXAttributeClause(Attrs, StartLoc, LParenLoc,
2391                                                  EndLoc);
2392   }
2393 
2394   /// Build a new OpenMP 'ompx_bare' clause.
2395   ///
2396   /// By default, performs semantic analysis to build the new OpenMP clause.
2397   /// Subclasses may override this routine to provide different behavior.
2398   OMPClause *RebuildOMPXBareClause(SourceLocation StartLoc,
2399                                    SourceLocation EndLoc) {
2400     return getSema().ActOnOpenMPXBareClause(StartLoc, EndLoc);
2401   }
2402 
2403   /// Build a new OpenMP 'align' clause.
2404   ///
2405   /// By default, performs semantic analysis to build the new OpenMP clause.
2406   /// Subclasses may override this routine to provide different behavior.
2407   OMPClause *RebuildOMPAlignClause(Expr *A, SourceLocation StartLoc,
2408                                    SourceLocation LParenLoc,
2409                                    SourceLocation EndLoc) {
2410     return getSema().ActOnOpenMPAlignClause(A, StartLoc, LParenLoc, EndLoc);
2411   }
2412 
2413   /// Build a new OpenMP 'at' clause.
2414   ///
2415   /// By default, performs semantic analysis to build the new OpenMP clause.
2416   /// Subclasses may override this routine to provide different behavior.
2417   OMPClause *RebuildOMPAtClause(OpenMPAtClauseKind Kind, SourceLocation KwLoc,
2418                                 SourceLocation StartLoc,
2419                                 SourceLocation LParenLoc,
2420                                 SourceLocation EndLoc) {
2421     return getSema().ActOnOpenMPAtClause(Kind, KwLoc, StartLoc, LParenLoc,
2422                                          EndLoc);
2423   }
2424 
2425   /// Build a new OpenMP 'severity' clause.
2426   ///
2427   /// By default, performs semantic analysis to build the new OpenMP clause.
2428   /// Subclasses may override this routine to provide different behavior.
2429   OMPClause *RebuildOMPSeverityClause(OpenMPSeverityClauseKind Kind,
2430                                       SourceLocation KwLoc,
2431                                       SourceLocation StartLoc,
2432                                       SourceLocation LParenLoc,
2433                                       SourceLocation EndLoc) {
2434     return getSema().ActOnOpenMPSeverityClause(Kind, KwLoc, StartLoc, LParenLoc,
2435                                                EndLoc);
2436   }
2437 
2438   /// Build a new OpenMP 'message' clause.
2439   ///
2440   /// By default, performs semantic analysis to build the new OpenMP clause.
2441   /// Subclasses may override this routine to provide different behavior.
2442   OMPClause *RebuildOMPMessageClause(Expr *MS, SourceLocation StartLoc,
2443                                      SourceLocation LParenLoc,
2444                                      SourceLocation EndLoc) {
2445     return getSema().ActOnOpenMPMessageClause(MS, StartLoc, LParenLoc, EndLoc);
2446   }
2447 
2448   /// Build a new OpenMP 'doacross' clause.
2449   ///
2450   /// By default, performs semantic analysis to build the new OpenMP clause.
2451   /// Subclasses may override this routine to provide different behavior.
2452   OMPClause *
2453   RebuildOMPDoacrossClause(OpenMPDoacrossClauseModifier DepType,
2454                            SourceLocation DepLoc, SourceLocation ColonLoc,
2455                            ArrayRef<Expr *> VarList, SourceLocation StartLoc,
2456                            SourceLocation LParenLoc, SourceLocation EndLoc) {
2457     return getSema().ActOnOpenMPDoacrossClause(
2458         DepType, DepLoc, ColonLoc, VarList, StartLoc, LParenLoc, EndLoc);
2459   }
2460 
2461   /// Rebuild the operand to an Objective-C \@synchronized statement.
2462   ///
2463   /// By default, performs semantic analysis to build the new statement.
2464   /// Subclasses may override this routine to provide different behavior.
2465   ExprResult RebuildObjCAtSynchronizedOperand(SourceLocation atLoc,
2466                                               Expr *object) {
2467     return getSema().ActOnObjCAtSynchronizedOperand(atLoc, object);
2468   }
2469 
2470   /// Build a new Objective-C \@synchronized statement.
2471   ///
2472   /// By default, performs semantic analysis to build the new statement.
2473   /// Subclasses may override this routine to provide different behavior.
2474   StmtResult RebuildObjCAtSynchronizedStmt(SourceLocation AtLoc,
2475                                            Expr *Object, Stmt *Body) {
2476     return getSema().ActOnObjCAtSynchronizedStmt(AtLoc, Object, Body);
2477   }
2478 
2479   /// Build a new Objective-C \@autoreleasepool statement.
2480   ///
2481   /// By default, performs semantic analysis to build the new statement.
2482   /// Subclasses may override this routine to provide different behavior.
2483   StmtResult RebuildObjCAutoreleasePoolStmt(SourceLocation AtLoc,
2484                                             Stmt *Body) {
2485     return getSema().ActOnObjCAutoreleasePoolStmt(AtLoc, Body);
2486   }
2487 
2488   /// Build a new Objective-C fast enumeration statement.
2489   ///
2490   /// By default, performs semantic analysis to build the new statement.
2491   /// Subclasses may override this routine to provide different behavior.
2492   StmtResult RebuildObjCForCollectionStmt(SourceLocation ForLoc,
2493                                           Stmt *Element,
2494                                           Expr *Collection,
2495                                           SourceLocation RParenLoc,
2496                                           Stmt *Body) {
2497     StmtResult ForEachStmt = getSema().ActOnObjCForCollectionStmt(ForLoc,
2498                                                 Element,
2499                                                 Collection,
2500                                                 RParenLoc);
2501     if (ForEachStmt.isInvalid())
2502       return StmtError();
2503 
2504     return getSema().FinishObjCForCollectionStmt(ForEachStmt.get(), Body);
2505   }
2506 
2507   /// Build a new C++ exception declaration.
2508   ///
2509   /// By default, performs semantic analysis to build the new decaration.
2510   /// Subclasses may override this routine to provide different behavior.
2511   VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
2512                                 TypeSourceInfo *Declarator,
2513                                 SourceLocation StartLoc,
2514                                 SourceLocation IdLoc,
2515                                 IdentifierInfo *Id) {
2516     VarDecl *Var = getSema().BuildExceptionDeclaration(nullptr, Declarator,
2517                                                        StartLoc, IdLoc, Id);
2518     if (Var)
2519       getSema().CurContext->addDecl(Var);
2520     return Var;
2521   }
2522 
2523   /// Build a new C++ catch statement.
2524   ///
2525   /// By default, performs semantic analysis to build the new statement.
2526   /// Subclasses may override this routine to provide different behavior.
2527   StmtResult RebuildCXXCatchStmt(SourceLocation CatchLoc,
2528                                  VarDecl *ExceptionDecl,
2529                                  Stmt *Handler) {
2530     return Owned(new (getSema().Context) CXXCatchStmt(CatchLoc, ExceptionDecl,
2531                                                       Handler));
2532   }
2533 
2534   /// Build a new C++ try statement.
2535   ///
2536   /// By default, performs semantic analysis to build the new statement.
2537   /// Subclasses may override this routine to provide different behavior.
2538   StmtResult RebuildCXXTryStmt(SourceLocation TryLoc, Stmt *TryBlock,
2539                                ArrayRef<Stmt *> Handlers) {
2540     return getSema().ActOnCXXTryBlock(TryLoc, TryBlock, Handlers);
2541   }
2542 
2543   /// Build a new C++0x range-based for statement.
2544   ///
2545   /// By default, performs semantic analysis to build the new statement.
2546   /// Subclasses may override this routine to provide different behavior.
2547   StmtResult RebuildCXXForRangeStmt(SourceLocation ForLoc,
2548                                     SourceLocation CoawaitLoc, Stmt *Init,
2549                                     SourceLocation ColonLoc, Stmt *Range,
2550                                     Stmt *Begin, Stmt *End, Expr *Cond,
2551                                     Expr *Inc, Stmt *LoopVar,
2552                                     SourceLocation RParenLoc) {
2553     // If we've just learned that the range is actually an Objective-C
2554     // collection, treat this as an Objective-C fast enumeration loop.
2555     if (DeclStmt *RangeStmt = dyn_cast<DeclStmt>(Range)) {
2556       if (RangeStmt->isSingleDecl()) {
2557         if (VarDecl *RangeVar = dyn_cast<VarDecl>(RangeStmt->getSingleDecl())) {
2558           if (RangeVar->isInvalidDecl())
2559             return StmtError();
2560 
2561           Expr *RangeExpr = RangeVar->getInit();
2562           if (!RangeExpr->isTypeDependent() &&
2563               RangeExpr->getType()->isObjCObjectPointerType()) {
2564             // FIXME: Support init-statements in Objective-C++20 ranged for
2565             // statement.
2566             if (Init) {
2567               return SemaRef.Diag(Init->getBeginLoc(),
2568                                   diag::err_objc_for_range_init_stmt)
2569                          << Init->getSourceRange();
2570             }
2571             return getSema().ActOnObjCForCollectionStmt(ForLoc, LoopVar,
2572                                                         RangeExpr, RParenLoc);
2573           }
2574         }
2575       }
2576     }
2577 
2578     return getSema().BuildCXXForRangeStmt(ForLoc, CoawaitLoc, Init, ColonLoc,
2579                                           Range, Begin, End, Cond, Inc, LoopVar,
2580                                           RParenLoc, Sema::BFRK_Rebuild);
2581   }
2582 
2583   /// Build a new C++0x range-based for statement.
2584   ///
2585   /// By default, performs semantic analysis to build the new statement.
2586   /// Subclasses may override this routine to provide different behavior.
2587   StmtResult RebuildMSDependentExistsStmt(SourceLocation KeywordLoc,
2588                                           bool IsIfExists,
2589                                           NestedNameSpecifierLoc QualifierLoc,
2590                                           DeclarationNameInfo NameInfo,
2591                                           Stmt *Nested) {
2592     return getSema().BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
2593                                                 QualifierLoc, NameInfo, Nested);
2594   }
2595 
2596   /// Attach body to a C++0x range-based for statement.
2597   ///
2598   /// By default, performs semantic analysis to finish the new statement.
2599   /// Subclasses may override this routine to provide different behavior.
2600   StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body) {
2601     return getSema().FinishCXXForRangeStmt(ForRange, Body);
2602   }
2603 
2604   StmtResult RebuildSEHTryStmt(bool IsCXXTry, SourceLocation TryLoc,
2605                                Stmt *TryBlock, Stmt *Handler) {
2606     return getSema().ActOnSEHTryBlock(IsCXXTry, TryLoc, TryBlock, Handler);
2607   }
2608 
2609   StmtResult RebuildSEHExceptStmt(SourceLocation Loc, Expr *FilterExpr,
2610                                   Stmt *Block) {
2611     return getSema().ActOnSEHExceptBlock(Loc, FilterExpr, Block);
2612   }
2613 
2614   StmtResult RebuildSEHFinallyStmt(SourceLocation Loc, Stmt *Block) {
2615     return SEHFinallyStmt::Create(getSema().getASTContext(), Loc, Block);
2616   }
2617 
2618   ExprResult RebuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
2619                                              SourceLocation LParen,
2620                                              SourceLocation RParen,
2621                                              TypeSourceInfo *TSI) {
2622     return getSema().BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI);
2623   }
2624 
2625   /// Build a new predefined expression.
2626   ///
2627   /// By default, performs semantic analysis to build the new expression.
2628   /// Subclasses may override this routine to provide different behavior.
2629   ExprResult RebuildPredefinedExpr(SourceLocation Loc, PredefinedIdentKind IK) {
2630     return getSema().BuildPredefinedExpr(Loc, IK);
2631   }
2632 
2633   /// Build a new expression that references a declaration.
2634   ///
2635   /// By default, performs semantic analysis to build the new expression.
2636   /// Subclasses may override this routine to provide different behavior.
2637   ExprResult RebuildDeclarationNameExpr(const CXXScopeSpec &SS,
2638                                         LookupResult &R,
2639                                         bool RequiresADL) {
2640     return getSema().BuildDeclarationNameExpr(SS, R, RequiresADL);
2641   }
2642 
2643 
2644   /// Build a new expression that references a declaration.
2645   ///
2646   /// By default, performs semantic analysis to build the new expression.
2647   /// Subclasses may override this routine to provide different behavior.
2648   ExprResult RebuildDeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
2649                                 ValueDecl *VD,
2650                                 const DeclarationNameInfo &NameInfo,
2651                                 NamedDecl *Found,
2652                                 TemplateArgumentListInfo *TemplateArgs) {
2653     CXXScopeSpec SS;
2654     SS.Adopt(QualifierLoc);
2655     return getSema().BuildDeclarationNameExpr(SS, NameInfo, VD, Found,
2656                                               TemplateArgs);
2657   }
2658 
2659   /// Build a new expression in parentheses.
2660   ///
2661   /// By default, performs semantic analysis to build the new expression.
2662   /// Subclasses may override this routine to provide different behavior.
2663   ExprResult RebuildParenExpr(Expr *SubExpr, SourceLocation LParen,
2664                                     SourceLocation RParen) {
2665     return getSema().ActOnParenExpr(LParen, RParen, SubExpr);
2666   }
2667 
2668   /// Build a new pseudo-destructor expression.
2669   ///
2670   /// By default, performs semantic analysis to build the new expression.
2671   /// Subclasses may override this routine to provide different behavior.
2672   ExprResult RebuildCXXPseudoDestructorExpr(Expr *Base,
2673                                             SourceLocation OperatorLoc,
2674                                             bool isArrow,
2675                                             CXXScopeSpec &SS,
2676                                             TypeSourceInfo *ScopeType,
2677                                             SourceLocation CCLoc,
2678                                             SourceLocation TildeLoc,
2679                                         PseudoDestructorTypeStorage Destroyed);
2680 
2681   /// Build a new unary operator expression.
2682   ///
2683   /// By default, performs semantic analysis to build the new expression.
2684   /// Subclasses may override this routine to provide different behavior.
2685   ExprResult RebuildUnaryOperator(SourceLocation OpLoc,
2686                                         UnaryOperatorKind Opc,
2687                                         Expr *SubExpr) {
2688     return getSema().BuildUnaryOp(/*Scope=*/nullptr, OpLoc, Opc, SubExpr);
2689   }
2690 
2691   /// Build a new builtin offsetof expression.
2692   ///
2693   /// By default, performs semantic analysis to build the new expression.
2694   /// Subclasses may override this routine to provide different behavior.
2695   ExprResult RebuildOffsetOfExpr(SourceLocation OperatorLoc,
2696                                  TypeSourceInfo *Type,
2697                                  ArrayRef<Sema::OffsetOfComponent> Components,
2698                                  SourceLocation RParenLoc) {
2699     return getSema().BuildBuiltinOffsetOf(OperatorLoc, Type, Components,
2700                                           RParenLoc);
2701   }
2702 
2703   /// Build a new sizeof, alignof or vec_step expression with a
2704   /// type argument.
2705   ///
2706   /// By default, performs semantic analysis to build the new expression.
2707   /// Subclasses may override this routine to provide different behavior.
2708   ExprResult RebuildUnaryExprOrTypeTrait(TypeSourceInfo *TInfo,
2709                                          SourceLocation OpLoc,
2710                                          UnaryExprOrTypeTrait ExprKind,
2711                                          SourceRange R) {
2712     return getSema().CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R);
2713   }
2714 
2715   /// Build a new sizeof, alignof or vec step expression with an
2716   /// expression argument.
2717   ///
2718   /// By default, performs semantic analysis to build the new expression.
2719   /// Subclasses may override this routine to provide different behavior.
2720   ExprResult RebuildUnaryExprOrTypeTrait(Expr *SubExpr, SourceLocation OpLoc,
2721                                          UnaryExprOrTypeTrait ExprKind,
2722                                          SourceRange R) {
2723     ExprResult Result
2724       = getSema().CreateUnaryExprOrTypeTraitExpr(SubExpr, OpLoc, ExprKind);
2725     if (Result.isInvalid())
2726       return ExprError();
2727 
2728     return Result;
2729   }
2730 
2731   /// Build a new array subscript expression.
2732   ///
2733   /// By default, performs semantic analysis to build the new expression.
2734   /// Subclasses may override this routine to provide different behavior.
2735   ExprResult RebuildArraySubscriptExpr(Expr *LHS,
2736                                              SourceLocation LBracketLoc,
2737                                              Expr *RHS,
2738                                              SourceLocation RBracketLoc) {
2739     return getSema().ActOnArraySubscriptExpr(/*Scope=*/nullptr, LHS,
2740                                              LBracketLoc, RHS,
2741                                              RBracketLoc);
2742   }
2743 
2744   /// Build a new matrix subscript expression.
2745   ///
2746   /// By default, performs semantic analysis to build the new expression.
2747   /// Subclasses may override this routine to provide different behavior.
2748   ExprResult RebuildMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
2749                                         Expr *ColumnIdx,
2750                                         SourceLocation RBracketLoc) {
2751     return getSema().CreateBuiltinMatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
2752                                                       RBracketLoc);
2753   }
2754 
2755   /// Build a new array section 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 RebuildOMPArraySectionExpr(Expr *Base, SourceLocation LBracketLoc,
2760                                         Expr *LowerBound,
2761                                         SourceLocation ColonLocFirst,
2762                                         SourceLocation ColonLocSecond,
2763                                         Expr *Length, Expr *Stride,
2764                                         SourceLocation RBracketLoc) {
2765     return getSema().ActOnOMPArraySectionExpr(Base, LBracketLoc, LowerBound,
2766                                               ColonLocFirst, ColonLocSecond,
2767                                               Length, Stride, RBracketLoc);
2768   }
2769 
2770   /// Build a new array shaping expression.
2771   ///
2772   /// By default, performs semantic analysis to build the new expression.
2773   /// Subclasses may override this routine to provide different behavior.
2774   ExprResult RebuildOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
2775                                         SourceLocation RParenLoc,
2776                                         ArrayRef<Expr *> Dims,
2777                                         ArrayRef<SourceRange> BracketsRanges) {
2778     return getSema().ActOnOMPArrayShapingExpr(Base, LParenLoc, RParenLoc, Dims,
2779                                               BracketsRanges);
2780   }
2781 
2782   /// Build a new iterator expression.
2783   ///
2784   /// By default, performs semantic analysis to build the new expression.
2785   /// Subclasses may override this routine to provide different behavior.
2786   ExprResult RebuildOMPIteratorExpr(
2787       SourceLocation IteratorKwLoc, SourceLocation LLoc, SourceLocation RLoc,
2788       ArrayRef<Sema::OMPIteratorData> Data) {
2789     return getSema().ActOnOMPIteratorExpr(/*Scope=*/nullptr, IteratorKwLoc,
2790                                           LLoc, RLoc, Data);
2791   }
2792 
2793   /// Build a new call expression.
2794   ///
2795   /// By default, performs semantic analysis to build the new expression.
2796   /// Subclasses may override this routine to provide different behavior.
2797   ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
2798                                    MultiExprArg Args,
2799                                    SourceLocation RParenLoc,
2800                                    Expr *ExecConfig = nullptr) {
2801     return getSema().ActOnCallExpr(
2802         /*Scope=*/nullptr, Callee, LParenLoc, Args, RParenLoc, ExecConfig);
2803   }
2804 
2805   ExprResult RebuildCxxSubscriptExpr(Expr *Callee, SourceLocation LParenLoc,
2806                                      MultiExprArg Args,
2807                                      SourceLocation RParenLoc) {
2808     return getSema().ActOnArraySubscriptExpr(
2809         /*Scope=*/nullptr, Callee, LParenLoc, Args, RParenLoc);
2810   }
2811 
2812   /// Build a new member access expression.
2813   ///
2814   /// By default, performs semantic analysis to build the new expression.
2815   /// Subclasses may override this routine to provide different behavior.
2816   ExprResult RebuildMemberExpr(Expr *Base, SourceLocation OpLoc,
2817                                bool isArrow,
2818                                NestedNameSpecifierLoc QualifierLoc,
2819                                SourceLocation TemplateKWLoc,
2820                                const DeclarationNameInfo &MemberNameInfo,
2821                                ValueDecl *Member,
2822                                NamedDecl *FoundDecl,
2823                         const TemplateArgumentListInfo *ExplicitTemplateArgs,
2824                                NamedDecl *FirstQualifierInScope) {
2825     ExprResult BaseResult = getSema().PerformMemberExprBaseConversion(Base,
2826                                                                       isArrow);
2827     if (!Member->getDeclName()) {
2828       // We have a reference to an unnamed field.  This is always the
2829       // base of an anonymous struct/union member access, i.e. the
2830       // field is always of record type.
2831       assert(Member->getType()->isRecordType() &&
2832              "unnamed member not of record type?");
2833 
2834       BaseResult =
2835         getSema().PerformObjectMemberConversion(BaseResult.get(),
2836                                                 QualifierLoc.getNestedNameSpecifier(),
2837                                                 FoundDecl, Member);
2838       if (BaseResult.isInvalid())
2839         return ExprError();
2840       Base = BaseResult.get();
2841 
2842       CXXScopeSpec EmptySS;
2843       return getSema().BuildFieldReferenceExpr(
2844           Base, isArrow, OpLoc, EmptySS, cast<FieldDecl>(Member),
2845           DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()), MemberNameInfo);
2846     }
2847 
2848     CXXScopeSpec SS;
2849     SS.Adopt(QualifierLoc);
2850 
2851     Base = BaseResult.get();
2852     QualType BaseType = Base->getType();
2853 
2854     if (isArrow && !BaseType->isPointerType())
2855       return ExprError();
2856 
2857     // FIXME: this involves duplicating earlier analysis in a lot of
2858     // cases; we should avoid this when possible.
2859     LookupResult R(getSema(), MemberNameInfo, Sema::LookupMemberName);
2860     R.addDecl(FoundDecl);
2861     R.resolveKind();
2862 
2863     if (getSema().isUnevaluatedContext() && Base->isImplicitCXXThis() &&
2864         isa<FieldDecl, IndirectFieldDecl, MSPropertyDecl>(Member)) {
2865       if (auto *ThisClass = cast<CXXThisExpr>(Base)
2866                                 ->getType()
2867                                 ->getPointeeType()
2868                                 ->getAsCXXRecordDecl()) {
2869         auto *Class = cast<CXXRecordDecl>(Member->getDeclContext());
2870         // In unevaluated contexts, an expression supposed to be a member access
2871         // might reference a member in an unrelated class.
2872         if (!ThisClass->Equals(Class) && !ThisClass->isDerivedFrom(Class))
2873           return getSema().BuildDeclRefExpr(Member, Member->getType(),
2874                                             VK_LValue, Member->getLocation());
2875       }
2876     }
2877 
2878     return getSema().BuildMemberReferenceExpr(Base, BaseType, OpLoc, isArrow,
2879                                               SS, TemplateKWLoc,
2880                                               FirstQualifierInScope,
2881                                               R, ExplicitTemplateArgs,
2882                                               /*S*/nullptr);
2883   }
2884 
2885   /// Build a new binary operator expression.
2886   ///
2887   /// By default, performs semantic analysis to build the new expression.
2888   /// Subclasses may override this routine to provide different behavior.
2889   ExprResult RebuildBinaryOperator(SourceLocation OpLoc,
2890                                          BinaryOperatorKind Opc,
2891                                          Expr *LHS, Expr *RHS) {
2892     return getSema().BuildBinOp(/*Scope=*/nullptr, OpLoc, Opc, LHS, RHS);
2893   }
2894 
2895   /// Build a new rewritten operator expression.
2896   ///
2897   /// By default, performs semantic analysis to build the new expression.
2898   /// Subclasses may override this routine to provide different behavior.
2899   ExprResult RebuildCXXRewrittenBinaryOperator(
2900       SourceLocation OpLoc, BinaryOperatorKind Opcode,
2901       const UnresolvedSetImpl &UnqualLookups, Expr *LHS, Expr *RHS) {
2902     return getSema().CreateOverloadedBinOp(OpLoc, Opcode, UnqualLookups, LHS,
2903                                            RHS, /*RequiresADL*/false);
2904   }
2905 
2906   /// Build a new conditional operator expression.
2907   ///
2908   /// By default, performs semantic analysis to build the new expression.
2909   /// Subclasses may override this routine to provide different behavior.
2910   ExprResult RebuildConditionalOperator(Expr *Cond,
2911                                         SourceLocation QuestionLoc,
2912                                         Expr *LHS,
2913                                         SourceLocation ColonLoc,
2914                                         Expr *RHS) {
2915     return getSema().ActOnConditionalOp(QuestionLoc, ColonLoc, Cond,
2916                                         LHS, RHS);
2917   }
2918 
2919   /// Build a new C-style cast expression.
2920   ///
2921   /// By default, performs semantic analysis to build the new expression.
2922   /// Subclasses may override this routine to provide different behavior.
2923   ExprResult RebuildCStyleCastExpr(SourceLocation LParenLoc,
2924                                          TypeSourceInfo *TInfo,
2925                                          SourceLocation RParenLoc,
2926                                          Expr *SubExpr) {
2927     return getSema().BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc,
2928                                          SubExpr);
2929   }
2930 
2931   /// Build a new compound literal expression.
2932   ///
2933   /// By default, performs semantic analysis to build the new expression.
2934   /// Subclasses may override this routine to provide different behavior.
2935   ExprResult RebuildCompoundLiteralExpr(SourceLocation LParenLoc,
2936                                               TypeSourceInfo *TInfo,
2937                                               SourceLocation RParenLoc,
2938                                               Expr *Init) {
2939     return getSema().BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc,
2940                                               Init);
2941   }
2942 
2943   /// Build a new extended vector element access expression.
2944   ///
2945   /// By default, performs semantic analysis to build the new expression.
2946   /// Subclasses may override this routine to provide different behavior.
2947   ExprResult RebuildExtVectorElementExpr(Expr *Base, SourceLocation OpLoc,
2948                                          bool IsArrow,
2949                                          SourceLocation AccessorLoc,
2950                                          IdentifierInfo &Accessor) {
2951 
2952     CXXScopeSpec SS;
2953     DeclarationNameInfo NameInfo(&Accessor, AccessorLoc);
2954     return getSema().BuildMemberReferenceExpr(
2955         Base, Base->getType(), OpLoc, IsArrow, SS, SourceLocation(),
2956         /*FirstQualifierInScope*/ nullptr, NameInfo,
2957         /* TemplateArgs */ nullptr,
2958         /*S*/ nullptr);
2959   }
2960 
2961   /// Build a new initializer list expression.
2962   ///
2963   /// By default, performs semantic analysis to build the new expression.
2964   /// Subclasses may override this routine to provide different behavior.
2965   ExprResult RebuildInitList(SourceLocation LBraceLoc,
2966                              MultiExprArg Inits,
2967                              SourceLocation RBraceLoc) {
2968     return SemaRef.BuildInitList(LBraceLoc, Inits, RBraceLoc);
2969   }
2970 
2971   /// Build a new designated initializer expression.
2972   ///
2973   /// By default, performs semantic analysis to build the new expression.
2974   /// Subclasses may override this routine to provide different behavior.
2975   ExprResult RebuildDesignatedInitExpr(Designation &Desig,
2976                                              MultiExprArg ArrayExprs,
2977                                              SourceLocation EqualOrColonLoc,
2978                                              bool GNUSyntax,
2979                                              Expr *Init) {
2980     ExprResult Result
2981       = SemaRef.ActOnDesignatedInitializer(Desig, EqualOrColonLoc, GNUSyntax,
2982                                            Init);
2983     if (Result.isInvalid())
2984       return ExprError();
2985 
2986     return Result;
2987   }
2988 
2989   /// Build a new value-initialized expression.
2990   ///
2991   /// By default, builds the implicit value initialization without performing
2992   /// any semantic analysis. Subclasses may override this routine to provide
2993   /// different behavior.
2994   ExprResult RebuildImplicitValueInitExpr(QualType T) {
2995     return new (SemaRef.Context) ImplicitValueInitExpr(T);
2996   }
2997 
2998   /// Build a new \c va_arg expression.
2999   ///
3000   /// By default, performs semantic analysis to build the new expression.
3001   /// Subclasses may override this routine to provide different behavior.
3002   ExprResult RebuildVAArgExpr(SourceLocation BuiltinLoc,
3003                                     Expr *SubExpr, TypeSourceInfo *TInfo,
3004                                     SourceLocation RParenLoc) {
3005     return getSema().BuildVAArgExpr(BuiltinLoc,
3006                                     SubExpr, TInfo,
3007                                     RParenLoc);
3008   }
3009 
3010   /// Build a new expression list in parentheses.
3011   ///
3012   /// By default, performs semantic analysis to build the new expression.
3013   /// Subclasses may override this routine to provide different behavior.
3014   ExprResult RebuildParenListExpr(SourceLocation LParenLoc,
3015                                   MultiExprArg SubExprs,
3016                                   SourceLocation RParenLoc) {
3017     return getSema().ActOnParenListExpr(LParenLoc, RParenLoc, SubExprs);
3018   }
3019 
3020   /// Build a new address-of-label expression.
3021   ///
3022   /// By default, performs semantic analysis, using the name of the label
3023   /// rather than attempting to map the label statement itself.
3024   /// Subclasses may override this routine to provide different behavior.
3025   ExprResult RebuildAddrLabelExpr(SourceLocation AmpAmpLoc,
3026                                   SourceLocation LabelLoc, LabelDecl *Label) {
3027     return getSema().ActOnAddrLabel(AmpAmpLoc, LabelLoc, Label);
3028   }
3029 
3030   /// Build a new GNU statement expression.
3031   ///
3032   /// By default, performs semantic analysis to build the new expression.
3033   /// Subclasses may override this routine to provide different behavior.
3034   ExprResult RebuildStmtExpr(SourceLocation LParenLoc, Stmt *SubStmt,
3035                              SourceLocation RParenLoc, unsigned TemplateDepth) {
3036     return getSema().BuildStmtExpr(LParenLoc, SubStmt, RParenLoc,
3037                                    TemplateDepth);
3038   }
3039 
3040   /// Build a new __builtin_choose_expr expression.
3041   ///
3042   /// By default, performs semantic analysis to build the new expression.
3043   /// Subclasses may override this routine to provide different behavior.
3044   ExprResult RebuildChooseExpr(SourceLocation BuiltinLoc,
3045                                      Expr *Cond, Expr *LHS, Expr *RHS,
3046                                      SourceLocation RParenLoc) {
3047     return SemaRef.ActOnChooseExpr(BuiltinLoc,
3048                                    Cond, LHS, RHS,
3049                                    RParenLoc);
3050   }
3051 
3052   /// Build a new generic selection expression with an expression predicate.
3053   ///
3054   /// By default, performs semantic analysis to build the new expression.
3055   /// Subclasses may override this routine to provide different behavior.
3056   ExprResult RebuildGenericSelectionExpr(SourceLocation KeyLoc,
3057                                          SourceLocation DefaultLoc,
3058                                          SourceLocation RParenLoc,
3059                                          Expr *ControllingExpr,
3060                                          ArrayRef<TypeSourceInfo *> Types,
3061                                          ArrayRef<Expr *> Exprs) {
3062     return getSema().CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
3063                                                 /*PredicateIsExpr=*/true,
3064                                                 ControllingExpr, Types, Exprs);
3065   }
3066 
3067   /// Build a new generic selection expression with a type predicate.
3068   ///
3069   /// By default, performs semantic analysis to build the new expression.
3070   /// Subclasses may override this routine to provide different behavior.
3071   ExprResult RebuildGenericSelectionExpr(SourceLocation KeyLoc,
3072                                          SourceLocation DefaultLoc,
3073                                          SourceLocation RParenLoc,
3074                                          TypeSourceInfo *ControllingType,
3075                                          ArrayRef<TypeSourceInfo *> Types,
3076                                          ArrayRef<Expr *> Exprs) {
3077     return getSema().CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
3078                                                 /*PredicateIsExpr=*/false,
3079                                                 ControllingType, Types, Exprs);
3080   }
3081 
3082   /// Build a new overloaded operator call expression.
3083   ///
3084   /// By default, performs semantic analysis to build the new expression.
3085   /// The semantic analysis provides the behavior of template instantiation,
3086   /// copying with transformations that turn what looks like an overloaded
3087   /// operator call into a use of a builtin operator, performing
3088   /// argument-dependent lookup, etc. Subclasses may override this routine to
3089   /// provide different behavior.
3090   ExprResult RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
3091                                         SourceLocation OpLoc,
3092                                         SourceLocation CalleeLoc,
3093                                         bool RequiresADL,
3094                                         const UnresolvedSetImpl &Functions,
3095                                         Expr *First, Expr *Second);
3096 
3097   /// Build a new C++ "named" cast expression, such as static_cast or
3098   /// reinterpret_cast.
3099   ///
3100   /// By default, this routine dispatches to one of the more-specific routines
3101   /// for a particular named case, e.g., RebuildCXXStaticCastExpr().
3102   /// Subclasses may override this routine to provide different behavior.
3103   ExprResult RebuildCXXNamedCastExpr(SourceLocation OpLoc,
3104                                            Stmt::StmtClass Class,
3105                                            SourceLocation LAngleLoc,
3106                                            TypeSourceInfo *TInfo,
3107                                            SourceLocation RAngleLoc,
3108                                            SourceLocation LParenLoc,
3109                                            Expr *SubExpr,
3110                                            SourceLocation RParenLoc) {
3111     switch (Class) {
3112     case Stmt::CXXStaticCastExprClass:
3113       return getDerived().RebuildCXXStaticCastExpr(OpLoc, LAngleLoc, TInfo,
3114                                                    RAngleLoc, LParenLoc,
3115                                                    SubExpr, RParenLoc);
3116 
3117     case Stmt::CXXDynamicCastExprClass:
3118       return getDerived().RebuildCXXDynamicCastExpr(OpLoc, LAngleLoc, TInfo,
3119                                                     RAngleLoc, LParenLoc,
3120                                                     SubExpr, RParenLoc);
3121 
3122     case Stmt::CXXReinterpretCastExprClass:
3123       return getDerived().RebuildCXXReinterpretCastExpr(OpLoc, LAngleLoc, TInfo,
3124                                                         RAngleLoc, LParenLoc,
3125                                                         SubExpr,
3126                                                         RParenLoc);
3127 
3128     case Stmt::CXXConstCastExprClass:
3129       return getDerived().RebuildCXXConstCastExpr(OpLoc, LAngleLoc, TInfo,
3130                                                    RAngleLoc, LParenLoc,
3131                                                    SubExpr, RParenLoc);
3132 
3133     case Stmt::CXXAddrspaceCastExprClass:
3134       return getDerived().RebuildCXXAddrspaceCastExpr(
3135           OpLoc, LAngleLoc, TInfo, RAngleLoc, LParenLoc, SubExpr, RParenLoc);
3136 
3137     default:
3138       llvm_unreachable("Invalid C++ named cast");
3139     }
3140   }
3141 
3142   /// Build a new C++ static_cast expression.
3143   ///
3144   /// By default, performs semantic analysis to build the new expression.
3145   /// Subclasses may override this routine to provide different behavior.
3146   ExprResult RebuildCXXStaticCastExpr(SourceLocation OpLoc,
3147                                             SourceLocation LAngleLoc,
3148                                             TypeSourceInfo *TInfo,
3149                                             SourceLocation RAngleLoc,
3150                                             SourceLocation LParenLoc,
3151                                             Expr *SubExpr,
3152                                             SourceLocation RParenLoc) {
3153     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_static_cast,
3154                                        TInfo, SubExpr,
3155                                        SourceRange(LAngleLoc, RAngleLoc),
3156                                        SourceRange(LParenLoc, RParenLoc));
3157   }
3158 
3159   /// Build a new C++ dynamic_cast expression.
3160   ///
3161   /// By default, performs semantic analysis to build the new expression.
3162   /// Subclasses may override this routine to provide different behavior.
3163   ExprResult RebuildCXXDynamicCastExpr(SourceLocation OpLoc,
3164                                              SourceLocation LAngleLoc,
3165                                              TypeSourceInfo *TInfo,
3166                                              SourceLocation RAngleLoc,
3167                                              SourceLocation LParenLoc,
3168                                              Expr *SubExpr,
3169                                              SourceLocation RParenLoc) {
3170     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_dynamic_cast,
3171                                        TInfo, SubExpr,
3172                                        SourceRange(LAngleLoc, RAngleLoc),
3173                                        SourceRange(LParenLoc, RParenLoc));
3174   }
3175 
3176   /// Build a new C++ reinterpret_cast expression.
3177   ///
3178   /// By default, performs semantic analysis to build the new expression.
3179   /// Subclasses may override this routine to provide different behavior.
3180   ExprResult RebuildCXXReinterpretCastExpr(SourceLocation OpLoc,
3181                                                  SourceLocation LAngleLoc,
3182                                                  TypeSourceInfo *TInfo,
3183                                                  SourceLocation RAngleLoc,
3184                                                  SourceLocation LParenLoc,
3185                                                  Expr *SubExpr,
3186                                                  SourceLocation RParenLoc) {
3187     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_reinterpret_cast,
3188                                        TInfo, SubExpr,
3189                                        SourceRange(LAngleLoc, RAngleLoc),
3190                                        SourceRange(LParenLoc, RParenLoc));
3191   }
3192 
3193   /// Build a new C++ const_cast expression.
3194   ///
3195   /// By default, performs semantic analysis to build the new expression.
3196   /// Subclasses may override this routine to provide different behavior.
3197   ExprResult RebuildCXXConstCastExpr(SourceLocation OpLoc,
3198                                            SourceLocation LAngleLoc,
3199                                            TypeSourceInfo *TInfo,
3200                                            SourceLocation RAngleLoc,
3201                                            SourceLocation LParenLoc,
3202                                            Expr *SubExpr,
3203                                            SourceLocation RParenLoc) {
3204     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_const_cast,
3205                                        TInfo, SubExpr,
3206                                        SourceRange(LAngleLoc, RAngleLoc),
3207                                        SourceRange(LParenLoc, RParenLoc));
3208   }
3209 
3210   ExprResult
3211   RebuildCXXAddrspaceCastExpr(SourceLocation OpLoc, SourceLocation LAngleLoc,
3212                               TypeSourceInfo *TInfo, SourceLocation RAngleLoc,
3213                               SourceLocation LParenLoc, Expr *SubExpr,
3214                               SourceLocation RParenLoc) {
3215     return getSema().BuildCXXNamedCast(
3216         OpLoc, tok::kw_addrspace_cast, TInfo, SubExpr,
3217         SourceRange(LAngleLoc, RAngleLoc), SourceRange(LParenLoc, RParenLoc));
3218   }
3219 
3220   /// Build a new C++ functional-style cast expression.
3221   ///
3222   /// By default, performs semantic analysis to build the new expression.
3223   /// Subclasses may override this routine to provide different behavior.
3224   ExprResult RebuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
3225                                           SourceLocation LParenLoc,
3226                                           Expr *Sub,
3227                                           SourceLocation RParenLoc,
3228                                           bool ListInitialization) {
3229     // If Sub is a ParenListExpr, then Sub is the syntatic form of a
3230     // CXXParenListInitExpr. Pass its expanded arguments so that the
3231     // CXXParenListInitExpr can be rebuilt.
3232     if (auto *PLE = dyn_cast<ParenListExpr>(Sub))
3233       return getSema().BuildCXXTypeConstructExpr(
3234           TInfo, LParenLoc, MultiExprArg(PLE->getExprs(), PLE->getNumExprs()),
3235           RParenLoc, ListInitialization);
3236     return getSema().BuildCXXTypeConstructExpr(TInfo, LParenLoc,
3237                                                MultiExprArg(&Sub, 1), RParenLoc,
3238                                                ListInitialization);
3239   }
3240 
3241   /// Build a new C++ __builtin_bit_cast expression.
3242   ///
3243   /// By default, performs semantic analysis to build the new expression.
3244   /// Subclasses may override this routine to provide different behavior.
3245   ExprResult RebuildBuiltinBitCastExpr(SourceLocation KWLoc,
3246                                        TypeSourceInfo *TSI, Expr *Sub,
3247                                        SourceLocation RParenLoc) {
3248     return getSema().BuildBuiltinBitCastExpr(KWLoc, TSI, Sub, RParenLoc);
3249   }
3250 
3251   /// Build a new C++ typeid(type) expression.
3252   ///
3253   /// By default, performs semantic analysis to build the new expression.
3254   /// Subclasses may override this routine to provide different behavior.
3255   ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
3256                                         SourceLocation TypeidLoc,
3257                                         TypeSourceInfo *Operand,
3258                                         SourceLocation RParenLoc) {
3259     return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
3260                                     RParenLoc);
3261   }
3262 
3263 
3264   /// Build a new C++ typeid(expr) expression.
3265   ///
3266   /// By default, performs semantic analysis to build the new expression.
3267   /// Subclasses may override this routine to provide different behavior.
3268   ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
3269                                         SourceLocation TypeidLoc,
3270                                         Expr *Operand,
3271                                         SourceLocation RParenLoc) {
3272     return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
3273                                     RParenLoc);
3274   }
3275 
3276   /// Build a new C++ __uuidof(type) expression.
3277   ///
3278   /// By default, performs semantic analysis to build the new expression.
3279   /// Subclasses may override this routine to provide different behavior.
3280   ExprResult RebuildCXXUuidofExpr(QualType Type, SourceLocation TypeidLoc,
3281                                   TypeSourceInfo *Operand,
3282                                   SourceLocation RParenLoc) {
3283     return getSema().BuildCXXUuidof(Type, TypeidLoc, Operand, RParenLoc);
3284   }
3285 
3286   /// Build a new C++ __uuidof(expr) expression.
3287   ///
3288   /// By default, performs semantic analysis to build the new expression.
3289   /// Subclasses may override this routine to provide different behavior.
3290   ExprResult RebuildCXXUuidofExpr(QualType Type, SourceLocation TypeidLoc,
3291                                   Expr *Operand, SourceLocation RParenLoc) {
3292     return getSema().BuildCXXUuidof(Type, TypeidLoc, Operand, RParenLoc);
3293   }
3294 
3295   /// Build a new C++ "this" expression.
3296   ///
3297   /// By default, builds a new "this" expression without performing any
3298   /// semantic analysis. Subclasses may override this routine to provide
3299   /// different behavior.
3300   ExprResult RebuildCXXThisExpr(SourceLocation ThisLoc,
3301                                 QualType ThisType,
3302                                 bool isImplicit) {
3303     return getSema().BuildCXXThisExpr(ThisLoc, ThisType, isImplicit);
3304   }
3305 
3306   /// Build a new C++ throw 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 RebuildCXXThrowExpr(SourceLocation ThrowLoc, Expr *Sub,
3311                                  bool IsThrownVariableInScope) {
3312     return getSema().BuildCXXThrow(ThrowLoc, Sub, IsThrownVariableInScope);
3313   }
3314 
3315   /// Build a new C++ default-argument expression.
3316   ///
3317   /// By default, builds a new default-argument expression, which does not
3318   /// require any semantic analysis. Subclasses may override this routine to
3319   /// provide different behavior.
3320   ExprResult RebuildCXXDefaultArgExpr(SourceLocation Loc, ParmVarDecl *Param,
3321                                       Expr *RewrittenExpr) {
3322     return CXXDefaultArgExpr::Create(getSema().Context, Loc, Param,
3323                                      RewrittenExpr, getSema().CurContext);
3324   }
3325 
3326   /// Build a new C++11 default-initialization expression.
3327   ///
3328   /// By default, builds a new default field initialization expression, which
3329   /// does not require any semantic analysis. Subclasses may override this
3330   /// routine to provide different behavior.
3331   ExprResult RebuildCXXDefaultInitExpr(SourceLocation Loc,
3332                                        FieldDecl *Field) {
3333     return getSema().BuildCXXDefaultInitExpr(Loc, Field);
3334   }
3335 
3336   /// Build a new C++ zero-initialization expression.
3337   ///
3338   /// By default, performs semantic analysis to build the new expression.
3339   /// Subclasses may override this routine to provide different behavior.
3340   ExprResult RebuildCXXScalarValueInitExpr(TypeSourceInfo *TSInfo,
3341                                            SourceLocation LParenLoc,
3342                                            SourceLocation RParenLoc) {
3343     return getSema().BuildCXXTypeConstructExpr(TSInfo, LParenLoc, std::nullopt,
3344                                                RParenLoc,
3345                                                /*ListInitialization=*/false);
3346   }
3347 
3348   /// Build a new C++ "new" expression.
3349   ///
3350   /// By default, performs semantic analysis to build the new expression.
3351   /// Subclasses may override this routine to provide different behavior.
3352   ExprResult RebuildCXXNewExpr(SourceLocation StartLoc, bool UseGlobal,
3353                                SourceLocation PlacementLParen,
3354                                MultiExprArg PlacementArgs,
3355                                SourceLocation PlacementRParen,
3356                                SourceRange TypeIdParens, QualType AllocatedType,
3357                                TypeSourceInfo *AllocatedTypeInfo,
3358                                std::optional<Expr *> ArraySize,
3359                                SourceRange DirectInitRange, Expr *Initializer) {
3360     return getSema().BuildCXXNew(StartLoc, UseGlobal,
3361                                  PlacementLParen,
3362                                  PlacementArgs,
3363                                  PlacementRParen,
3364                                  TypeIdParens,
3365                                  AllocatedType,
3366                                  AllocatedTypeInfo,
3367                                  ArraySize,
3368                                  DirectInitRange,
3369                                  Initializer);
3370   }
3371 
3372   /// Build a new C++ "delete" expression.
3373   ///
3374   /// By default, performs semantic analysis to build the new expression.
3375   /// Subclasses may override this routine to provide different behavior.
3376   ExprResult RebuildCXXDeleteExpr(SourceLocation StartLoc,
3377                                         bool IsGlobalDelete,
3378                                         bool IsArrayForm,
3379                                         Expr *Operand) {
3380     return getSema().ActOnCXXDelete(StartLoc, IsGlobalDelete, IsArrayForm,
3381                                     Operand);
3382   }
3383 
3384   /// Build a new type trait expression.
3385   ///
3386   /// By default, performs semantic analysis to build the new expression.
3387   /// Subclasses may override this routine to provide different behavior.
3388   ExprResult RebuildTypeTrait(TypeTrait Trait,
3389                               SourceLocation StartLoc,
3390                               ArrayRef<TypeSourceInfo *> Args,
3391                               SourceLocation RParenLoc) {
3392     return getSema().BuildTypeTrait(Trait, StartLoc, Args, RParenLoc);
3393   }
3394 
3395   /// Build a new array type trait expression.
3396   ///
3397   /// By default, performs semantic analysis to build the new expression.
3398   /// Subclasses may override this routine to provide different behavior.
3399   ExprResult RebuildArrayTypeTrait(ArrayTypeTrait Trait,
3400                                    SourceLocation StartLoc,
3401                                    TypeSourceInfo *TSInfo,
3402                                    Expr *DimExpr,
3403                                    SourceLocation RParenLoc) {
3404     return getSema().BuildArrayTypeTrait(Trait, StartLoc, TSInfo, DimExpr, RParenLoc);
3405   }
3406 
3407   /// Build a new expression trait expression.
3408   ///
3409   /// By default, performs semantic analysis to build the new expression.
3410   /// Subclasses may override this routine to provide different behavior.
3411   ExprResult RebuildExpressionTrait(ExpressionTrait Trait,
3412                                    SourceLocation StartLoc,
3413                                    Expr *Queried,
3414                                    SourceLocation RParenLoc) {
3415     return getSema().BuildExpressionTrait(Trait, StartLoc, Queried, RParenLoc);
3416   }
3417 
3418   /// Build a new (previously unresolved) declaration reference
3419   /// expression.
3420   ///
3421   /// By default, performs semantic analysis to build the new expression.
3422   /// Subclasses may override this routine to provide different behavior.
3423   ExprResult RebuildDependentScopeDeclRefExpr(
3424                                           NestedNameSpecifierLoc QualifierLoc,
3425                                           SourceLocation TemplateKWLoc,
3426                                        const DeclarationNameInfo &NameInfo,
3427                               const TemplateArgumentListInfo *TemplateArgs,
3428                                           bool IsAddressOfOperand,
3429                                           TypeSourceInfo **RecoveryTSI) {
3430     CXXScopeSpec SS;
3431     SS.Adopt(QualifierLoc);
3432 
3433     if (TemplateArgs || TemplateKWLoc.isValid())
3434       return getSema().BuildQualifiedTemplateIdExpr(SS, TemplateKWLoc, NameInfo,
3435                                                     TemplateArgs);
3436 
3437     return getSema().BuildQualifiedDeclarationNameExpr(
3438         SS, NameInfo, IsAddressOfOperand, /*S*/nullptr, RecoveryTSI);
3439   }
3440 
3441   /// Build a new template-id expression.
3442   ///
3443   /// By default, performs semantic analysis to build the new expression.
3444   /// Subclasses may override this routine to provide different behavior.
3445   ExprResult RebuildTemplateIdExpr(const CXXScopeSpec &SS,
3446                                    SourceLocation TemplateKWLoc,
3447                                    LookupResult &R,
3448                                    bool RequiresADL,
3449                               const TemplateArgumentListInfo *TemplateArgs) {
3450     return getSema().BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL,
3451                                          TemplateArgs);
3452   }
3453 
3454   /// Build a new object-construction expression.
3455   ///
3456   /// By default, performs semantic analysis to build the new expression.
3457   /// Subclasses may override this routine to provide different behavior.
3458   ExprResult RebuildCXXConstructExpr(
3459       QualType T, SourceLocation Loc, CXXConstructorDecl *Constructor,
3460       bool IsElidable, MultiExprArg Args, bool HadMultipleCandidates,
3461       bool ListInitialization, bool StdInitListInitialization,
3462       bool RequiresZeroInit, CXXConstructionKind ConstructKind,
3463       SourceRange ParenRange) {
3464     // Reconstruct the constructor we originally found, which might be
3465     // different if this is a call to an inherited constructor.
3466     CXXConstructorDecl *FoundCtor = Constructor;
3467     if (Constructor->isInheritingConstructor())
3468       FoundCtor = Constructor->getInheritedConstructor().getConstructor();
3469 
3470     SmallVector<Expr *, 8> ConvertedArgs;
3471     if (getSema().CompleteConstructorCall(FoundCtor, T, Args, Loc,
3472                                           ConvertedArgs))
3473       return ExprError();
3474 
3475     return getSema().BuildCXXConstructExpr(Loc, T, Constructor,
3476                                            IsElidable,
3477                                            ConvertedArgs,
3478                                            HadMultipleCandidates,
3479                                            ListInitialization,
3480                                            StdInitListInitialization,
3481                                            RequiresZeroInit, ConstructKind,
3482                                            ParenRange);
3483   }
3484 
3485   /// Build a new implicit construction via inherited constructor
3486   /// expression.
3487   ExprResult RebuildCXXInheritedCtorInitExpr(QualType T, SourceLocation Loc,
3488                                              CXXConstructorDecl *Constructor,
3489                                              bool ConstructsVBase,
3490                                              bool InheritedFromVBase) {
3491     return new (getSema().Context) CXXInheritedCtorInitExpr(
3492         Loc, T, Constructor, ConstructsVBase, InheritedFromVBase);
3493   }
3494 
3495   /// Build a new object-construction expression.
3496   ///
3497   /// By default, performs semantic analysis to build the new expression.
3498   /// Subclasses may override this routine to provide different behavior.
3499   ExprResult RebuildCXXTemporaryObjectExpr(TypeSourceInfo *TSInfo,
3500                                            SourceLocation LParenOrBraceLoc,
3501                                            MultiExprArg Args,
3502                                            SourceLocation RParenOrBraceLoc,
3503                                            bool ListInitialization) {
3504     return getSema().BuildCXXTypeConstructExpr(
3505         TSInfo, LParenOrBraceLoc, Args, RParenOrBraceLoc, ListInitialization);
3506   }
3507 
3508   /// Build a new object-construction expression.
3509   ///
3510   /// By default, performs semantic analysis to build the new expression.
3511   /// Subclasses may override this routine to provide different behavior.
3512   ExprResult RebuildCXXUnresolvedConstructExpr(TypeSourceInfo *TSInfo,
3513                                                SourceLocation LParenLoc,
3514                                                MultiExprArg Args,
3515                                                SourceLocation RParenLoc,
3516                                                bool ListInitialization) {
3517     return getSema().BuildCXXTypeConstructExpr(TSInfo, LParenLoc, Args,
3518                                                RParenLoc, ListInitialization);
3519   }
3520 
3521   /// Build a new member reference expression.
3522   ///
3523   /// By default, performs semantic analysis to build the new expression.
3524   /// Subclasses may override this routine to provide different behavior.
3525   ExprResult RebuildCXXDependentScopeMemberExpr(Expr *BaseE,
3526                                                 QualType BaseType,
3527                                                 bool IsArrow,
3528                                                 SourceLocation OperatorLoc,
3529                                           NestedNameSpecifierLoc QualifierLoc,
3530                                                 SourceLocation TemplateKWLoc,
3531                                             NamedDecl *FirstQualifierInScope,
3532                                    const DeclarationNameInfo &MemberNameInfo,
3533                               const TemplateArgumentListInfo *TemplateArgs) {
3534     CXXScopeSpec SS;
3535     SS.Adopt(QualifierLoc);
3536 
3537     return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
3538                                             OperatorLoc, IsArrow,
3539                                             SS, TemplateKWLoc,
3540                                             FirstQualifierInScope,
3541                                             MemberNameInfo,
3542                                             TemplateArgs, /*S*/nullptr);
3543   }
3544 
3545   /// Build a new member reference expression.
3546   ///
3547   /// By default, performs semantic analysis to build the new expression.
3548   /// Subclasses may override this routine to provide different behavior.
3549   ExprResult RebuildUnresolvedMemberExpr(Expr *BaseE, QualType BaseType,
3550                                          SourceLocation OperatorLoc,
3551                                          bool IsArrow,
3552                                          NestedNameSpecifierLoc QualifierLoc,
3553                                          SourceLocation TemplateKWLoc,
3554                                          NamedDecl *FirstQualifierInScope,
3555                                          LookupResult &R,
3556                                 const TemplateArgumentListInfo *TemplateArgs) {
3557     CXXScopeSpec SS;
3558     SS.Adopt(QualifierLoc);
3559 
3560     return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
3561                                             OperatorLoc, IsArrow,
3562                                             SS, TemplateKWLoc,
3563                                             FirstQualifierInScope,
3564                                             R, TemplateArgs, /*S*/nullptr);
3565   }
3566 
3567   /// Build a new noexcept expression.
3568   ///
3569   /// By default, performs semantic analysis to build the new expression.
3570   /// Subclasses may override this routine to provide different behavior.
3571   ExprResult RebuildCXXNoexceptExpr(SourceRange Range, Expr *Arg) {
3572     return SemaRef.BuildCXXNoexceptExpr(Range.getBegin(), Arg, Range.getEnd());
3573   }
3574 
3575   /// Build a new expression to compute the length of a parameter pack.
3576   ExprResult RebuildSizeOfPackExpr(SourceLocation OperatorLoc, NamedDecl *Pack,
3577                                    SourceLocation PackLoc,
3578                                    SourceLocation RParenLoc,
3579                                    std::optional<unsigned> Length,
3580                                    ArrayRef<TemplateArgument> PartialArgs) {
3581     return SizeOfPackExpr::Create(SemaRef.Context, OperatorLoc, Pack, PackLoc,
3582                                   RParenLoc, Length, PartialArgs);
3583   }
3584 
3585   /// Build a new expression representing a call to a source location
3586   ///  builtin.
3587   ///
3588   /// By default, performs semantic analysis to build the new expression.
3589   /// Subclasses may override this routine to provide different behavior.
3590   ExprResult RebuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy,
3591                                   SourceLocation BuiltinLoc,
3592                                   SourceLocation RPLoc,
3593                                   DeclContext *ParentContext) {
3594     return getSema().BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc,
3595                                         ParentContext);
3596   }
3597 
3598   /// Build a new Objective-C boxed expression.
3599   ///
3600   /// By default, performs semantic analysis to build the new expression.
3601   /// Subclasses may override this routine to provide different behavior.
3602   ExprResult RebuildConceptSpecializationExpr(NestedNameSpecifierLoc NNS,
3603       SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo,
3604       NamedDecl *FoundDecl, ConceptDecl *NamedConcept,
3605       TemplateArgumentListInfo *TALI) {
3606     CXXScopeSpec SS;
3607     SS.Adopt(NNS);
3608     ExprResult Result = getSema().CheckConceptTemplateId(SS, TemplateKWLoc,
3609                                                          ConceptNameInfo,
3610                                                          FoundDecl,
3611                                                          NamedConcept, TALI);
3612     if (Result.isInvalid())
3613       return ExprError();
3614     return Result;
3615   }
3616 
3617   /// \brief Build a new requires expression.
3618   ///
3619   /// By default, performs semantic analysis to build the new expression.
3620   /// Subclasses may override this routine to provide different behavior.
3621   ExprResult RebuildRequiresExpr(SourceLocation RequiresKWLoc,
3622                                  RequiresExprBodyDecl *Body,
3623                                  SourceLocation LParenLoc,
3624                                  ArrayRef<ParmVarDecl *> LocalParameters,
3625                                  SourceLocation RParenLoc,
3626                                  ArrayRef<concepts::Requirement *> Requirements,
3627                                  SourceLocation ClosingBraceLoc) {
3628     return RequiresExpr::Create(SemaRef.Context, RequiresKWLoc, Body, LParenLoc,
3629                                 LocalParameters, RParenLoc, Requirements,
3630                                 ClosingBraceLoc);
3631   }
3632 
3633   concepts::TypeRequirement *
3634   RebuildTypeRequirement(
3635       concepts::Requirement::SubstitutionDiagnostic *SubstDiag) {
3636     return SemaRef.BuildTypeRequirement(SubstDiag);
3637   }
3638 
3639   concepts::TypeRequirement *RebuildTypeRequirement(TypeSourceInfo *T) {
3640     return SemaRef.BuildTypeRequirement(T);
3641   }
3642 
3643   concepts::ExprRequirement *
3644   RebuildExprRequirement(
3645       concepts::Requirement::SubstitutionDiagnostic *SubstDiag, bool IsSimple,
3646       SourceLocation NoexceptLoc,
3647       concepts::ExprRequirement::ReturnTypeRequirement Ret) {
3648     return SemaRef.BuildExprRequirement(SubstDiag, IsSimple, NoexceptLoc,
3649                                         std::move(Ret));
3650   }
3651 
3652   concepts::ExprRequirement *
3653   RebuildExprRequirement(Expr *E, bool IsSimple, SourceLocation NoexceptLoc,
3654                          concepts::ExprRequirement::ReturnTypeRequirement Ret) {
3655     return SemaRef.BuildExprRequirement(E, IsSimple, NoexceptLoc,
3656                                         std::move(Ret));
3657   }
3658 
3659   concepts::NestedRequirement *
3660   RebuildNestedRequirement(StringRef InvalidConstraintEntity,
3661                            const ASTConstraintSatisfaction &Satisfaction) {
3662     return SemaRef.BuildNestedRequirement(InvalidConstraintEntity,
3663                                           Satisfaction);
3664   }
3665 
3666   concepts::NestedRequirement *RebuildNestedRequirement(Expr *Constraint) {
3667     return SemaRef.BuildNestedRequirement(Constraint);
3668   }
3669 
3670   /// \brief Build a new Objective-C boxed expression.
3671   ///
3672   /// By default, performs semantic analysis to build the new expression.
3673   /// Subclasses may override this routine to provide different behavior.
3674   ExprResult RebuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
3675     return getSema().BuildObjCBoxedExpr(SR, ValueExpr);
3676   }
3677 
3678   /// Build a new Objective-C array literal.
3679   ///
3680   /// By default, performs semantic analysis to build the new expression.
3681   /// Subclasses may override this routine to provide different behavior.
3682   ExprResult RebuildObjCArrayLiteral(SourceRange Range,
3683                                      Expr **Elements, unsigned NumElements) {
3684     return getSema().BuildObjCArrayLiteral(Range,
3685                                            MultiExprArg(Elements, NumElements));
3686   }
3687 
3688   ExprResult RebuildObjCSubscriptRefExpr(SourceLocation RB,
3689                                          Expr *Base, Expr *Key,
3690                                          ObjCMethodDecl *getterMethod,
3691                                          ObjCMethodDecl *setterMethod) {
3692     return  getSema().BuildObjCSubscriptExpression(RB, Base, Key,
3693                                                    getterMethod, setterMethod);
3694   }
3695 
3696   /// Build a new Objective-C dictionary literal.
3697   ///
3698   /// By default, performs semantic analysis to build the new expression.
3699   /// Subclasses may override this routine to provide different behavior.
3700   ExprResult RebuildObjCDictionaryLiteral(SourceRange Range,
3701                               MutableArrayRef<ObjCDictionaryElement> Elements) {
3702     return getSema().BuildObjCDictionaryLiteral(Range, Elements);
3703   }
3704 
3705   /// Build a new Objective-C \@encode expression.
3706   ///
3707   /// By default, performs semantic analysis to build the new expression.
3708   /// Subclasses may override this routine to provide different behavior.
3709   ExprResult RebuildObjCEncodeExpr(SourceLocation AtLoc,
3710                                          TypeSourceInfo *EncodeTypeInfo,
3711                                          SourceLocation RParenLoc) {
3712     return SemaRef.BuildObjCEncodeExpression(AtLoc, EncodeTypeInfo, RParenLoc);
3713   }
3714 
3715   /// Build a new Objective-C class message.
3716   ExprResult RebuildObjCMessageExpr(TypeSourceInfo *ReceiverTypeInfo,
3717                                           Selector Sel,
3718                                           ArrayRef<SourceLocation> SelectorLocs,
3719                                           ObjCMethodDecl *Method,
3720                                           SourceLocation LBracLoc,
3721                                           MultiExprArg Args,
3722                                           SourceLocation RBracLoc) {
3723     return SemaRef.BuildClassMessage(ReceiverTypeInfo,
3724                                      ReceiverTypeInfo->getType(),
3725                                      /*SuperLoc=*/SourceLocation(),
3726                                      Sel, Method, LBracLoc, SelectorLocs,
3727                                      RBracLoc, Args);
3728   }
3729 
3730   /// Build a new Objective-C instance message.
3731   ExprResult RebuildObjCMessageExpr(Expr *Receiver,
3732                                           Selector Sel,
3733                                           ArrayRef<SourceLocation> SelectorLocs,
3734                                           ObjCMethodDecl *Method,
3735                                           SourceLocation LBracLoc,
3736                                           MultiExprArg Args,
3737                                           SourceLocation RBracLoc) {
3738     return SemaRef.BuildInstanceMessage(Receiver,
3739                                         Receiver->getType(),
3740                                         /*SuperLoc=*/SourceLocation(),
3741                                         Sel, Method, LBracLoc, SelectorLocs,
3742                                         RBracLoc, Args);
3743   }
3744 
3745   /// Build a new Objective-C instance/class message to 'super'.
3746   ExprResult RebuildObjCMessageExpr(SourceLocation SuperLoc,
3747                                     Selector Sel,
3748                                     ArrayRef<SourceLocation> SelectorLocs,
3749                                     QualType SuperType,
3750                                     ObjCMethodDecl *Method,
3751                                     SourceLocation LBracLoc,
3752                                     MultiExprArg Args,
3753                                     SourceLocation RBracLoc) {
3754     return Method->isInstanceMethod() ? SemaRef.BuildInstanceMessage(nullptr,
3755                                           SuperType,
3756                                           SuperLoc,
3757                                           Sel, Method, LBracLoc, SelectorLocs,
3758                                           RBracLoc, Args)
3759                                       : SemaRef.BuildClassMessage(nullptr,
3760                                           SuperType,
3761                                           SuperLoc,
3762                                           Sel, Method, LBracLoc, SelectorLocs,
3763                                           RBracLoc, Args);
3764 
3765 
3766   }
3767 
3768   /// Build a new Objective-C ivar reference expression.
3769   ///
3770   /// By default, performs semantic analysis to build the new expression.
3771   /// Subclasses may override this routine to provide different behavior.
3772   ExprResult RebuildObjCIvarRefExpr(Expr *BaseArg, ObjCIvarDecl *Ivar,
3773                                           SourceLocation IvarLoc,
3774                                           bool IsArrow, bool IsFreeIvar) {
3775     CXXScopeSpec SS;
3776     DeclarationNameInfo NameInfo(Ivar->getDeclName(), IvarLoc);
3777     ExprResult Result = getSema().BuildMemberReferenceExpr(
3778         BaseArg, BaseArg->getType(),
3779         /*FIXME:*/ IvarLoc, IsArrow, SS, SourceLocation(),
3780         /*FirstQualifierInScope=*/nullptr, NameInfo,
3781         /*TemplateArgs=*/nullptr,
3782         /*S=*/nullptr);
3783     if (IsFreeIvar && Result.isUsable())
3784       cast<ObjCIvarRefExpr>(Result.get())->setIsFreeIvar(IsFreeIvar);
3785     return Result;
3786   }
3787 
3788   /// Build a new Objective-C property reference expression.
3789   ///
3790   /// By default, performs semantic analysis to build the new expression.
3791   /// Subclasses may override this routine to provide different behavior.
3792   ExprResult RebuildObjCPropertyRefExpr(Expr *BaseArg,
3793                                         ObjCPropertyDecl *Property,
3794                                         SourceLocation PropertyLoc) {
3795     CXXScopeSpec SS;
3796     DeclarationNameInfo NameInfo(Property->getDeclName(), PropertyLoc);
3797     return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3798                                               /*FIXME:*/PropertyLoc,
3799                                               /*IsArrow=*/false,
3800                                               SS, SourceLocation(),
3801                                               /*FirstQualifierInScope=*/nullptr,
3802                                               NameInfo,
3803                                               /*TemplateArgs=*/nullptr,
3804                                               /*S=*/nullptr);
3805   }
3806 
3807   /// Build a new Objective-C property reference expression.
3808   ///
3809   /// By default, performs semantic analysis to build the new expression.
3810   /// Subclasses may override this routine to provide different behavior.
3811   ExprResult RebuildObjCPropertyRefExpr(Expr *Base, QualType T,
3812                                         ObjCMethodDecl *Getter,
3813                                         ObjCMethodDecl *Setter,
3814                                         SourceLocation PropertyLoc) {
3815     // Since these expressions can only be value-dependent, we do not
3816     // need to perform semantic analysis again.
3817     return Owned(
3818       new (getSema().Context) ObjCPropertyRefExpr(Getter, Setter, T,
3819                                                   VK_LValue, OK_ObjCProperty,
3820                                                   PropertyLoc, Base));
3821   }
3822 
3823   /// Build a new Objective-C "isa" expression.
3824   ///
3825   /// By default, performs semantic analysis to build the new expression.
3826   /// Subclasses may override this routine to provide different behavior.
3827   ExprResult RebuildObjCIsaExpr(Expr *BaseArg, SourceLocation IsaLoc,
3828                                 SourceLocation OpLoc, bool IsArrow) {
3829     CXXScopeSpec SS;
3830     DeclarationNameInfo NameInfo(&getSema().Context.Idents.get("isa"), IsaLoc);
3831     return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3832                                               OpLoc, IsArrow,
3833                                               SS, SourceLocation(),
3834                                               /*FirstQualifierInScope=*/nullptr,
3835                                               NameInfo,
3836                                               /*TemplateArgs=*/nullptr,
3837                                               /*S=*/nullptr);
3838   }
3839 
3840   /// Build a new shuffle vector expression.
3841   ///
3842   /// By default, performs semantic analysis to build the new expression.
3843   /// Subclasses may override this routine to provide different behavior.
3844   ExprResult RebuildShuffleVectorExpr(SourceLocation BuiltinLoc,
3845                                       MultiExprArg SubExprs,
3846                                       SourceLocation RParenLoc) {
3847     // Find the declaration for __builtin_shufflevector
3848     const IdentifierInfo &Name
3849       = SemaRef.Context.Idents.get("__builtin_shufflevector");
3850     TranslationUnitDecl *TUDecl = SemaRef.Context.getTranslationUnitDecl();
3851     DeclContext::lookup_result Lookup = TUDecl->lookup(DeclarationName(&Name));
3852     assert(!Lookup.empty() && "No __builtin_shufflevector?");
3853 
3854     // Build a reference to the __builtin_shufflevector builtin
3855     FunctionDecl *Builtin = cast<FunctionDecl>(Lookup.front());
3856     Expr *Callee = new (SemaRef.Context)
3857         DeclRefExpr(SemaRef.Context, Builtin, false,
3858                     SemaRef.Context.BuiltinFnTy, VK_PRValue, BuiltinLoc);
3859     QualType CalleePtrTy = SemaRef.Context.getPointerType(Builtin->getType());
3860     Callee = SemaRef.ImpCastExprToType(Callee, CalleePtrTy,
3861                                        CK_BuiltinFnToFnPtr).get();
3862 
3863     // Build the CallExpr
3864     ExprResult TheCall = CallExpr::Create(
3865         SemaRef.Context, Callee, SubExprs, Builtin->getCallResultType(),
3866         Expr::getValueKindForType(Builtin->getReturnType()), RParenLoc,
3867         FPOptionsOverride());
3868 
3869     // Type-check the __builtin_shufflevector expression.
3870     return SemaRef.SemaBuiltinShuffleVector(cast<CallExpr>(TheCall.get()));
3871   }
3872 
3873   /// Build a new convert vector expression.
3874   ExprResult RebuildConvertVectorExpr(SourceLocation BuiltinLoc,
3875                                       Expr *SrcExpr, TypeSourceInfo *DstTInfo,
3876                                       SourceLocation RParenLoc) {
3877     return SemaRef.SemaConvertVectorExpr(SrcExpr, DstTInfo,
3878                                          BuiltinLoc, RParenLoc);
3879   }
3880 
3881   /// Build a new template argument pack expansion.
3882   ///
3883   /// By default, performs semantic analysis to build a new pack expansion
3884   /// for a template argument. Subclasses may override this routine to provide
3885   /// different behavior.
3886   TemplateArgumentLoc
3887   RebuildPackExpansion(TemplateArgumentLoc Pattern, SourceLocation EllipsisLoc,
3888                        std::optional<unsigned> NumExpansions) {
3889     switch (Pattern.getArgument().getKind()) {
3890     case TemplateArgument::Expression: {
3891       ExprResult Result
3892         = getSema().CheckPackExpansion(Pattern.getSourceExpression(),
3893                                        EllipsisLoc, NumExpansions);
3894       if (Result.isInvalid())
3895         return TemplateArgumentLoc();
3896 
3897       return TemplateArgumentLoc(Result.get(), Result.get());
3898     }
3899 
3900     case TemplateArgument::Template:
3901       return TemplateArgumentLoc(
3902           SemaRef.Context,
3903           TemplateArgument(Pattern.getArgument().getAsTemplate(),
3904                            NumExpansions),
3905           Pattern.getTemplateQualifierLoc(), Pattern.getTemplateNameLoc(),
3906           EllipsisLoc);
3907 
3908     case TemplateArgument::Null:
3909     case TemplateArgument::Integral:
3910     case TemplateArgument::Declaration:
3911     case TemplateArgument::Pack:
3912     case TemplateArgument::TemplateExpansion:
3913     case TemplateArgument::NullPtr:
3914       llvm_unreachable("Pack expansion pattern has no parameter packs");
3915 
3916     case TemplateArgument::Type:
3917       if (TypeSourceInfo *Expansion
3918             = getSema().CheckPackExpansion(Pattern.getTypeSourceInfo(),
3919                                            EllipsisLoc,
3920                                            NumExpansions))
3921         return TemplateArgumentLoc(TemplateArgument(Expansion->getType()),
3922                                    Expansion);
3923       break;
3924     }
3925 
3926     return TemplateArgumentLoc();
3927   }
3928 
3929   /// Build a new expression pack expansion.
3930   ///
3931   /// By default, performs semantic analysis to build a new pack expansion
3932   /// for an expression. Subclasses may override this routine to provide
3933   /// different behavior.
3934   ExprResult RebuildPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
3935                                   std::optional<unsigned> NumExpansions) {
3936     return getSema().CheckPackExpansion(Pattern, EllipsisLoc, NumExpansions);
3937   }
3938 
3939   /// Build a new C++1z fold-expression.
3940   ///
3941   /// By default, performs semantic analysis in order to build a new fold
3942   /// expression.
3943   ExprResult RebuildCXXFoldExpr(UnresolvedLookupExpr *ULE,
3944                                 SourceLocation LParenLoc, Expr *LHS,
3945                                 BinaryOperatorKind Operator,
3946                                 SourceLocation EllipsisLoc, Expr *RHS,
3947                                 SourceLocation RParenLoc,
3948                                 std::optional<unsigned> NumExpansions) {
3949     return getSema().BuildCXXFoldExpr(ULE, LParenLoc, LHS, Operator,
3950                                       EllipsisLoc, RHS, RParenLoc,
3951                                       NumExpansions);
3952   }
3953 
3954   /// Build an empty C++1z fold-expression with the given operator.
3955   ///
3956   /// By default, produces the fallback value for the fold-expression, or
3957   /// produce an error if there is no fallback value.
3958   ExprResult RebuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
3959                                      BinaryOperatorKind Operator) {
3960     return getSema().BuildEmptyCXXFoldExpr(EllipsisLoc, Operator);
3961   }
3962 
3963   /// Build a new atomic operation expression.
3964   ///
3965   /// By default, performs semantic analysis to build the new expression.
3966   /// Subclasses may override this routine to provide different behavior.
3967   ExprResult RebuildAtomicExpr(SourceLocation BuiltinLoc, MultiExprArg SubExprs,
3968                                AtomicExpr::AtomicOp Op,
3969                                SourceLocation RParenLoc) {
3970     // Use this for all of the locations, since we don't know the difference
3971     // between the call and the expr at this point.
3972     SourceRange Range{BuiltinLoc, RParenLoc};
3973     return getSema().BuildAtomicExpr(Range, Range, RParenLoc, SubExprs, Op,
3974                                      Sema::AtomicArgumentOrder::AST);
3975   }
3976 
3977   ExprResult RebuildRecoveryExpr(SourceLocation BeginLoc, SourceLocation EndLoc,
3978                                  ArrayRef<Expr *> SubExprs, QualType Type) {
3979     return getSema().CreateRecoveryExpr(BeginLoc, EndLoc, SubExprs, Type);
3980   }
3981 
3982 private:
3983   TypeLoc TransformTypeInObjectScope(TypeLoc TL,
3984                                      QualType ObjectType,
3985                                      NamedDecl *FirstQualifierInScope,
3986                                      CXXScopeSpec &SS);
3987 
3988   TypeSourceInfo *TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
3989                                              QualType ObjectType,
3990                                              NamedDecl *FirstQualifierInScope,
3991                                              CXXScopeSpec &SS);
3992 
3993   TypeSourceInfo *TransformTSIInObjectScope(TypeLoc TL, QualType ObjectType,
3994                                             NamedDecl *FirstQualifierInScope,
3995                                             CXXScopeSpec &SS);
3996 
3997   QualType TransformDependentNameType(TypeLocBuilder &TLB,
3998                                       DependentNameTypeLoc TL,
3999                                       bool DeducibleTSTContext);
4000 };
4001 
4002 template <typename Derived>
4003 StmtResult TreeTransform<Derived>::TransformStmt(Stmt *S, StmtDiscardKind SDK) {
4004   if (!S)
4005     return S;
4006 
4007   switch (S->getStmtClass()) {
4008   case Stmt::NoStmtClass: break;
4009 
4010   // Transform individual statement nodes
4011   // Pass SDK into statements that can produce a value
4012 #define STMT(Node, Parent)                                              \
4013   case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(S));
4014 #define VALUESTMT(Node, Parent)                                         \
4015   case Stmt::Node##Class:                                               \
4016     return getDerived().Transform##Node(cast<Node>(S), SDK);
4017 #define ABSTRACT_STMT(Node)
4018 #define EXPR(Node, Parent)
4019 #include "clang/AST/StmtNodes.inc"
4020 
4021   // Transform expressions by calling TransformExpr.
4022 #define STMT(Node, Parent)
4023 #define ABSTRACT_STMT(Stmt)
4024 #define EXPR(Node, Parent) case Stmt::Node##Class:
4025 #include "clang/AST/StmtNodes.inc"
4026     {
4027       ExprResult E = getDerived().TransformExpr(cast<Expr>(S));
4028 
4029       if (SDK == SDK_StmtExprResult)
4030         E = getSema().ActOnStmtExprResult(E);
4031       return getSema().ActOnExprStmt(E, SDK == SDK_Discarded);
4032     }
4033   }
4034 
4035   return S;
4036 }
4037 
4038 template<typename Derived>
4039 OMPClause *TreeTransform<Derived>::TransformOMPClause(OMPClause *S) {
4040   if (!S)
4041     return S;
4042 
4043   switch (S->getClauseKind()) {
4044   default: break;
4045   // Transform individual clause nodes
4046 #define GEN_CLANG_CLAUSE_CLASS
4047 #define CLAUSE_CLASS(Enum, Str, Class)                                         \
4048   case Enum:                                                                   \
4049     return getDerived().Transform##Class(cast<Class>(S));
4050 #include "llvm/Frontend/OpenMP/OMP.inc"
4051   }
4052 
4053   return S;
4054 }
4055 
4056 
4057 template<typename Derived>
4058 ExprResult TreeTransform<Derived>::TransformExpr(Expr *E) {
4059   if (!E)
4060     return E;
4061 
4062   switch (E->getStmtClass()) {
4063     case Stmt::NoStmtClass: break;
4064 #define STMT(Node, Parent) case Stmt::Node##Class: break;
4065 #define ABSTRACT_STMT(Stmt)
4066 #define EXPR(Node, Parent)                                              \
4067     case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(E));
4068 #include "clang/AST/StmtNodes.inc"
4069   }
4070 
4071   return E;
4072 }
4073 
4074 template<typename Derived>
4075 ExprResult TreeTransform<Derived>::TransformInitializer(Expr *Init,
4076                                                         bool NotCopyInit) {
4077   // Initializers are instantiated like expressions, except that various outer
4078   // layers are stripped.
4079   if (!Init)
4080     return Init;
4081 
4082   if (auto *FE = dyn_cast<FullExpr>(Init))
4083     Init = FE->getSubExpr();
4084 
4085   if (auto *AIL = dyn_cast<ArrayInitLoopExpr>(Init)) {
4086     OpaqueValueExpr *OVE = AIL->getCommonExpr();
4087     Init = OVE->getSourceExpr();
4088   }
4089 
4090   if (MaterializeTemporaryExpr *MTE = dyn_cast<MaterializeTemporaryExpr>(Init))
4091     Init = MTE->getSubExpr();
4092 
4093   while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
4094     Init = Binder->getSubExpr();
4095 
4096   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
4097     Init = ICE->getSubExprAsWritten();
4098 
4099   if (CXXStdInitializerListExpr *ILE =
4100           dyn_cast<CXXStdInitializerListExpr>(Init))
4101     return TransformInitializer(ILE->getSubExpr(), NotCopyInit);
4102 
4103   // If this is copy-initialization, we only need to reconstruct
4104   // InitListExprs. Other forms of copy-initialization will be a no-op if
4105   // the initializer is already the right type.
4106   CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init);
4107   if (!NotCopyInit && !(Construct && Construct->isListInitialization()))
4108     return getDerived().TransformExpr(Init);
4109 
4110   // Revert value-initialization back to empty parens.
4111   if (CXXScalarValueInitExpr *VIE = dyn_cast<CXXScalarValueInitExpr>(Init)) {
4112     SourceRange Parens = VIE->getSourceRange();
4113     return getDerived().RebuildParenListExpr(Parens.getBegin(), std::nullopt,
4114                                              Parens.getEnd());
4115   }
4116 
4117   // FIXME: We shouldn't build ImplicitValueInitExprs for direct-initialization.
4118   if (isa<ImplicitValueInitExpr>(Init))
4119     return getDerived().RebuildParenListExpr(SourceLocation(), std::nullopt,
4120                                              SourceLocation());
4121 
4122   // Revert initialization by constructor back to a parenthesized or braced list
4123   // of expressions. Any other form of initializer can just be reused directly.
4124   if (!Construct || isa<CXXTemporaryObjectExpr>(Construct))
4125     return getDerived().TransformExpr(Init);
4126 
4127   // If the initialization implicitly converted an initializer list to a
4128   // std::initializer_list object, unwrap the std::initializer_list too.
4129   if (Construct && Construct->isStdInitListInitialization())
4130     return TransformInitializer(Construct->getArg(0), NotCopyInit);
4131 
4132   // Enter a list-init context if this was list initialization.
4133   EnterExpressionEvaluationContext Context(
4134       getSema(), EnterExpressionEvaluationContext::InitList,
4135       Construct->isListInitialization());
4136 
4137   SmallVector<Expr*, 8> NewArgs;
4138   bool ArgChanged = false;
4139   if (getDerived().TransformExprs(Construct->getArgs(), Construct->getNumArgs(),
4140                                   /*IsCall*/true, NewArgs, &ArgChanged))
4141     return ExprError();
4142 
4143   // If this was list initialization, revert to syntactic list form.
4144   if (Construct->isListInitialization())
4145     return getDerived().RebuildInitList(Construct->getBeginLoc(), NewArgs,
4146                                         Construct->getEndLoc());
4147 
4148   // Build a ParenListExpr to represent anything else.
4149   SourceRange Parens = Construct->getParenOrBraceRange();
4150   if (Parens.isInvalid()) {
4151     // This was a variable declaration's initialization for which no initializer
4152     // was specified.
4153     assert(NewArgs.empty() &&
4154            "no parens or braces but have direct init with arguments?");
4155     return ExprEmpty();
4156   }
4157   return getDerived().RebuildParenListExpr(Parens.getBegin(), NewArgs,
4158                                            Parens.getEnd());
4159 }
4160 
4161 template<typename Derived>
4162 bool TreeTransform<Derived>::TransformExprs(Expr *const *Inputs,
4163                                             unsigned NumInputs,
4164                                             bool IsCall,
4165                                       SmallVectorImpl<Expr *> &Outputs,
4166                                             bool *ArgChanged) {
4167   for (unsigned I = 0; I != NumInputs; ++I) {
4168     // If requested, drop call arguments that need to be dropped.
4169     if (IsCall && getDerived().DropCallArgument(Inputs[I])) {
4170       if (ArgChanged)
4171         *ArgChanged = true;
4172 
4173       break;
4174     }
4175 
4176     if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Inputs[I])) {
4177       Expr *Pattern = Expansion->getPattern();
4178 
4179       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4180       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
4181       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
4182 
4183       // Determine whether the set of unexpanded parameter packs can and should
4184       // be expanded.
4185       bool Expand = true;
4186       bool RetainExpansion = false;
4187       std::optional<unsigned> OrigNumExpansions = Expansion->getNumExpansions();
4188       std::optional<unsigned> NumExpansions = OrigNumExpansions;
4189       if (getDerived().TryExpandParameterPacks(Expansion->getEllipsisLoc(),
4190                                                Pattern->getSourceRange(),
4191                                                Unexpanded,
4192                                                Expand, RetainExpansion,
4193                                                NumExpansions))
4194         return true;
4195 
4196       if (!Expand) {
4197         // The transform has determined that we should perform a simple
4198         // transformation on the pack expansion, producing another pack
4199         // expansion.
4200         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4201         ExprResult OutPattern = getDerived().TransformExpr(Pattern);
4202         if (OutPattern.isInvalid())
4203           return true;
4204 
4205         ExprResult Out = getDerived().RebuildPackExpansion(OutPattern.get(),
4206                                                 Expansion->getEllipsisLoc(),
4207                                                            NumExpansions);
4208         if (Out.isInvalid())
4209           return true;
4210 
4211         if (ArgChanged)
4212           *ArgChanged = true;
4213         Outputs.push_back(Out.get());
4214         continue;
4215       }
4216 
4217       // Record right away that the argument was changed.  This needs
4218       // to happen even if the array expands to nothing.
4219       if (ArgChanged) *ArgChanged = true;
4220 
4221       // The transform has determined that we should perform an elementwise
4222       // expansion of the pattern. Do so.
4223       for (unsigned I = 0; I != *NumExpansions; ++I) {
4224         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
4225         ExprResult Out = getDerived().TransformExpr(Pattern);
4226         if (Out.isInvalid())
4227           return true;
4228 
4229         if (Out.get()->containsUnexpandedParameterPack()) {
4230           Out = getDerived().RebuildPackExpansion(
4231               Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
4232           if (Out.isInvalid())
4233             return true;
4234         }
4235 
4236         Outputs.push_back(Out.get());
4237       }
4238 
4239       // If we're supposed to retain a pack expansion, do so by temporarily
4240       // forgetting the partially-substituted parameter pack.
4241       if (RetainExpansion) {
4242         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
4243 
4244         ExprResult Out = getDerived().TransformExpr(Pattern);
4245         if (Out.isInvalid())
4246           return true;
4247 
4248         Out = getDerived().RebuildPackExpansion(
4249             Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
4250         if (Out.isInvalid())
4251           return true;
4252 
4253         Outputs.push_back(Out.get());
4254       }
4255 
4256       continue;
4257     }
4258 
4259     ExprResult Result =
4260       IsCall ? getDerived().TransformInitializer(Inputs[I], /*DirectInit*/false)
4261              : getDerived().TransformExpr(Inputs[I]);
4262     if (Result.isInvalid())
4263       return true;
4264 
4265     if (Result.get() != Inputs[I] && ArgChanged)
4266       *ArgChanged = true;
4267 
4268     Outputs.push_back(Result.get());
4269   }
4270 
4271   return false;
4272 }
4273 
4274 template <typename Derived>
4275 Sema::ConditionResult TreeTransform<Derived>::TransformCondition(
4276     SourceLocation Loc, VarDecl *Var, Expr *Expr, Sema::ConditionKind Kind) {
4277   if (Var) {
4278     VarDecl *ConditionVar = cast_or_null<VarDecl>(
4279         getDerived().TransformDefinition(Var->getLocation(), Var));
4280 
4281     if (!ConditionVar)
4282       return Sema::ConditionError();
4283 
4284     return getSema().ActOnConditionVariable(ConditionVar, Loc, Kind);
4285   }
4286 
4287   if (Expr) {
4288     ExprResult CondExpr = getDerived().TransformExpr(Expr);
4289 
4290     if (CondExpr.isInvalid())
4291       return Sema::ConditionError();
4292 
4293     return getSema().ActOnCondition(nullptr, Loc, CondExpr.get(), Kind,
4294                                     /*MissingOK=*/true);
4295   }
4296 
4297   return Sema::ConditionResult();
4298 }
4299 
4300 template <typename Derived>
4301 NestedNameSpecifierLoc TreeTransform<Derived>::TransformNestedNameSpecifierLoc(
4302     NestedNameSpecifierLoc NNS, QualType ObjectType,
4303     NamedDecl *FirstQualifierInScope) {
4304   SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
4305 
4306   auto insertNNS = [&Qualifiers](NestedNameSpecifierLoc NNS) {
4307     for (NestedNameSpecifierLoc Qualifier = NNS; Qualifier;
4308          Qualifier = Qualifier.getPrefix())
4309       Qualifiers.push_back(Qualifier);
4310   };
4311   insertNNS(NNS);
4312 
4313   CXXScopeSpec SS;
4314   while (!Qualifiers.empty()) {
4315     NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
4316     NestedNameSpecifier *QNNS = Q.getNestedNameSpecifier();
4317 
4318     switch (QNNS->getKind()) {
4319     case NestedNameSpecifier::Identifier: {
4320       Sema::NestedNameSpecInfo IdInfo(QNNS->getAsIdentifier(),
4321                                       Q.getLocalBeginLoc(), Q.getLocalEndLoc(),
4322                                       ObjectType);
4323       if (SemaRef.BuildCXXNestedNameSpecifier(/*Scope=*/nullptr, IdInfo, false,
4324                                               SS, FirstQualifierInScope, false))
4325         return NestedNameSpecifierLoc();
4326       break;
4327     }
4328 
4329     case NestedNameSpecifier::Namespace: {
4330       NamespaceDecl *NS =
4331           cast_or_null<NamespaceDecl>(getDerived().TransformDecl(
4332               Q.getLocalBeginLoc(), QNNS->getAsNamespace()));
4333       SS.Extend(SemaRef.Context, NS, Q.getLocalBeginLoc(), Q.getLocalEndLoc());
4334       break;
4335     }
4336 
4337     case NestedNameSpecifier::NamespaceAlias: {
4338       NamespaceAliasDecl *Alias =
4339           cast_or_null<NamespaceAliasDecl>(getDerived().TransformDecl(
4340               Q.getLocalBeginLoc(), QNNS->getAsNamespaceAlias()));
4341       SS.Extend(SemaRef.Context, Alias, Q.getLocalBeginLoc(),
4342                 Q.getLocalEndLoc());
4343       break;
4344     }
4345 
4346     case NestedNameSpecifier::Global:
4347       // There is no meaningful transformation that one could perform on the
4348       // global scope.
4349       SS.MakeGlobal(SemaRef.Context, Q.getBeginLoc());
4350       break;
4351 
4352     case NestedNameSpecifier::Super: {
4353       CXXRecordDecl *RD =
4354           cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
4355               SourceLocation(), QNNS->getAsRecordDecl()));
4356       SS.MakeSuper(SemaRef.Context, RD, Q.getBeginLoc(), Q.getEndLoc());
4357       break;
4358     }
4359 
4360     case NestedNameSpecifier::TypeSpecWithTemplate:
4361     case NestedNameSpecifier::TypeSpec: {
4362       TypeLoc TL = TransformTypeInObjectScope(Q.getTypeLoc(), ObjectType,
4363                                               FirstQualifierInScope, SS);
4364 
4365       if (!TL)
4366         return NestedNameSpecifierLoc();
4367 
4368       QualType T = TL.getType();
4369       if (T->isDependentType() || T->isRecordType() ||
4370           (SemaRef.getLangOpts().CPlusPlus11 && T->isEnumeralType())) {
4371         if (T->isEnumeralType())
4372           SemaRef.Diag(TL.getBeginLoc(),
4373                        diag::warn_cxx98_compat_enum_nested_name_spec);
4374 
4375         if (const auto ETL = TL.getAs<ElaboratedTypeLoc>()) {
4376           SS.Adopt(ETL.getQualifierLoc());
4377           TL = ETL.getNamedTypeLoc();
4378         }
4379         SS.Extend(SemaRef.Context, /*FIXME:*/ SourceLocation(), TL,
4380                   Q.getLocalEndLoc());
4381         break;
4382       }
4383       // If the nested-name-specifier is an invalid type def, don't emit an
4384       // error because a previous error should have already been emitted.
4385       TypedefTypeLoc TTL = TL.getAsAdjusted<TypedefTypeLoc>();
4386       if (!TTL || !TTL.getTypedefNameDecl()->isInvalidDecl()) {
4387         SemaRef.Diag(TL.getBeginLoc(), diag::err_nested_name_spec_non_tag)
4388             << T << SS.getRange();
4389       }
4390       return NestedNameSpecifierLoc();
4391     }
4392     }
4393 
4394     // The qualifier-in-scope and object type only apply to the leftmost entity.
4395     FirstQualifierInScope = nullptr;
4396     ObjectType = QualType();
4397   }
4398 
4399   // Don't rebuild the nested-name-specifier if we don't have to.
4400   if (SS.getScopeRep() == NNS.getNestedNameSpecifier() &&
4401       !getDerived().AlwaysRebuild())
4402     return NNS;
4403 
4404   // If we can re-use the source-location data from the original
4405   // nested-name-specifier, do so.
4406   if (SS.location_size() == NNS.getDataLength() &&
4407       memcmp(SS.location_data(), NNS.getOpaqueData(), SS.location_size()) == 0)
4408     return NestedNameSpecifierLoc(SS.getScopeRep(), NNS.getOpaqueData());
4409 
4410   // Allocate new nested-name-specifier location information.
4411   return SS.getWithLocInContext(SemaRef.Context);
4412 }
4413 
4414 template<typename Derived>
4415 DeclarationNameInfo
4416 TreeTransform<Derived>
4417 ::TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo) {
4418   DeclarationName Name = NameInfo.getName();
4419   if (!Name)
4420     return DeclarationNameInfo();
4421 
4422   switch (Name.getNameKind()) {
4423   case DeclarationName::Identifier:
4424   case DeclarationName::ObjCZeroArgSelector:
4425   case DeclarationName::ObjCOneArgSelector:
4426   case DeclarationName::ObjCMultiArgSelector:
4427   case DeclarationName::CXXOperatorName:
4428   case DeclarationName::CXXLiteralOperatorName:
4429   case DeclarationName::CXXUsingDirective:
4430     return NameInfo;
4431 
4432   case DeclarationName::CXXDeductionGuideName: {
4433     TemplateDecl *OldTemplate = Name.getCXXDeductionGuideTemplate();
4434     TemplateDecl *NewTemplate = cast_or_null<TemplateDecl>(
4435         getDerived().TransformDecl(NameInfo.getLoc(), OldTemplate));
4436     if (!NewTemplate)
4437       return DeclarationNameInfo();
4438 
4439     DeclarationNameInfo NewNameInfo(NameInfo);
4440     NewNameInfo.setName(
4441         SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(NewTemplate));
4442     return NewNameInfo;
4443   }
4444 
4445   case DeclarationName::CXXConstructorName:
4446   case DeclarationName::CXXDestructorName:
4447   case DeclarationName::CXXConversionFunctionName: {
4448     TypeSourceInfo *NewTInfo;
4449     CanQualType NewCanTy;
4450     if (TypeSourceInfo *OldTInfo = NameInfo.getNamedTypeInfo()) {
4451       NewTInfo = getDerived().TransformType(OldTInfo);
4452       if (!NewTInfo)
4453         return DeclarationNameInfo();
4454       NewCanTy = SemaRef.Context.getCanonicalType(NewTInfo->getType());
4455     }
4456     else {
4457       NewTInfo = nullptr;
4458       TemporaryBase Rebase(*this, NameInfo.getLoc(), Name);
4459       QualType NewT = getDerived().TransformType(Name.getCXXNameType());
4460       if (NewT.isNull())
4461         return DeclarationNameInfo();
4462       NewCanTy = SemaRef.Context.getCanonicalType(NewT);
4463     }
4464 
4465     DeclarationName NewName
4466       = SemaRef.Context.DeclarationNames.getCXXSpecialName(Name.getNameKind(),
4467                                                            NewCanTy);
4468     DeclarationNameInfo NewNameInfo(NameInfo);
4469     NewNameInfo.setName(NewName);
4470     NewNameInfo.setNamedTypeInfo(NewTInfo);
4471     return NewNameInfo;
4472   }
4473   }
4474 
4475   llvm_unreachable("Unknown name kind.");
4476 }
4477 
4478 template<typename Derived>
4479 TemplateName
4480 TreeTransform<Derived>::TransformTemplateName(CXXScopeSpec &SS,
4481                                               TemplateName Name,
4482                                               SourceLocation NameLoc,
4483                                               QualType ObjectType,
4484                                               NamedDecl *FirstQualifierInScope,
4485                                               bool AllowInjectedClassName) {
4486   if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) {
4487     TemplateDecl *Template = QTN->getUnderlyingTemplate().getAsTemplateDecl();
4488     assert(Template && "qualified template name must refer to a template");
4489 
4490     TemplateDecl *TransTemplate
4491       = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
4492                                                               Template));
4493     if (!TransTemplate)
4494       return TemplateName();
4495 
4496     if (!getDerived().AlwaysRebuild() &&
4497         SS.getScopeRep() == QTN->getQualifier() &&
4498         TransTemplate == Template)
4499       return Name;
4500 
4501     return getDerived().RebuildTemplateName(SS, QTN->hasTemplateKeyword(),
4502                                             TransTemplate);
4503   }
4504 
4505   if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
4506     if (SS.getScopeRep()) {
4507       // These apply to the scope specifier, not the template.
4508       ObjectType = QualType();
4509       FirstQualifierInScope = nullptr;
4510     }
4511 
4512     if (!getDerived().AlwaysRebuild() &&
4513         SS.getScopeRep() == DTN->getQualifier() &&
4514         ObjectType.isNull())
4515       return Name;
4516 
4517     // FIXME: Preserve the location of the "template" keyword.
4518     SourceLocation TemplateKWLoc = NameLoc;
4519 
4520     if (DTN->isIdentifier()) {
4521       return getDerived().RebuildTemplateName(SS,
4522                                               TemplateKWLoc,
4523                                               *DTN->getIdentifier(),
4524                                               NameLoc,
4525                                               ObjectType,
4526                                               FirstQualifierInScope,
4527                                               AllowInjectedClassName);
4528     }
4529 
4530     return getDerived().RebuildTemplateName(SS, TemplateKWLoc,
4531                                             DTN->getOperator(), NameLoc,
4532                                             ObjectType, AllowInjectedClassName);
4533   }
4534 
4535   if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4536     TemplateDecl *TransTemplate
4537       = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
4538                                                               Template));
4539     if (!TransTemplate)
4540       return TemplateName();
4541 
4542     if (!getDerived().AlwaysRebuild() &&
4543         TransTemplate == Template)
4544       return Name;
4545 
4546     return TemplateName(TransTemplate);
4547   }
4548 
4549   if (SubstTemplateTemplateParmPackStorage *SubstPack
4550       = Name.getAsSubstTemplateTemplateParmPack()) {
4551     return getDerived().RebuildTemplateName(
4552         SubstPack->getArgumentPack(), SubstPack->getAssociatedDecl(),
4553         SubstPack->getIndex(), SubstPack->getFinal());
4554   }
4555 
4556   // These should be getting filtered out before they reach the AST.
4557   llvm_unreachable("overloaded function decl survived to here");
4558 }
4559 
4560 template<typename Derived>
4561 void TreeTransform<Derived>::InventTemplateArgumentLoc(
4562                                          const TemplateArgument &Arg,
4563                                          TemplateArgumentLoc &Output) {
4564   Output = getSema().getTrivialTemplateArgumentLoc(
4565       Arg, QualType(), getDerived().getBaseLocation());
4566 }
4567 
4568 template <typename Derived>
4569 bool TreeTransform<Derived>::TransformTemplateArgument(
4570     const TemplateArgumentLoc &Input, TemplateArgumentLoc &Output,
4571     bool Uneval) {
4572   const TemplateArgument &Arg = Input.getArgument();
4573   switch (Arg.getKind()) {
4574   case TemplateArgument::Null:
4575   case TemplateArgument::Pack:
4576     llvm_unreachable("Unexpected TemplateArgument");
4577 
4578   case TemplateArgument::Integral:
4579   case TemplateArgument::NullPtr:
4580   case TemplateArgument::Declaration: {
4581     // Transform a resolved template argument straight to a resolved template
4582     // argument. We get here when substituting into an already-substituted
4583     // template type argument during concept satisfaction checking.
4584     QualType T = Arg.getNonTypeTemplateArgumentType();
4585     QualType NewT = getDerived().TransformType(T);
4586     if (NewT.isNull())
4587       return true;
4588 
4589     ValueDecl *D = Arg.getKind() == TemplateArgument::Declaration
4590                        ? Arg.getAsDecl()
4591                        : nullptr;
4592     ValueDecl *NewD = D ? cast_or_null<ValueDecl>(getDerived().TransformDecl(
4593                               getDerived().getBaseLocation(), D))
4594                         : nullptr;
4595     if (D && !NewD)
4596       return true;
4597 
4598     if (NewT == T && D == NewD)
4599       Output = Input;
4600     else if (Arg.getKind() == TemplateArgument::Integral)
4601       Output = TemplateArgumentLoc(
4602           TemplateArgument(getSema().Context, Arg.getAsIntegral(), NewT),
4603           TemplateArgumentLocInfo());
4604     else if (Arg.getKind() == TemplateArgument::NullPtr)
4605       Output = TemplateArgumentLoc(TemplateArgument(NewT, /*IsNullPtr=*/true),
4606                                    TemplateArgumentLocInfo());
4607     else
4608       Output = TemplateArgumentLoc(TemplateArgument(NewD, NewT),
4609                                    TemplateArgumentLocInfo());
4610 
4611     return false;
4612   }
4613 
4614   case TemplateArgument::Type: {
4615     TypeSourceInfo *DI = Input.getTypeSourceInfo();
4616     if (!DI)
4617       DI = InventTypeSourceInfo(Input.getArgument().getAsType());
4618 
4619     DI = getDerived().TransformType(DI);
4620     if (!DI)
4621       return true;
4622 
4623     Output = TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4624     return false;
4625   }
4626 
4627   case TemplateArgument::Template: {
4628     NestedNameSpecifierLoc QualifierLoc = Input.getTemplateQualifierLoc();
4629     if (QualifierLoc) {
4630       QualifierLoc = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc);
4631       if (!QualifierLoc)
4632         return true;
4633     }
4634 
4635     CXXScopeSpec SS;
4636     SS.Adopt(QualifierLoc);
4637     TemplateName Template = getDerived().TransformTemplateName(
4638         SS, Arg.getAsTemplate(), Input.getTemplateNameLoc());
4639     if (Template.isNull())
4640       return true;
4641 
4642     Output = TemplateArgumentLoc(SemaRef.Context, TemplateArgument(Template),
4643                                  QualifierLoc, Input.getTemplateNameLoc());
4644     return false;
4645   }
4646 
4647   case TemplateArgument::TemplateExpansion:
4648     llvm_unreachable("Caller should expand pack expansions");
4649 
4650   case TemplateArgument::Expression: {
4651     // Template argument expressions are constant expressions.
4652     EnterExpressionEvaluationContext Unevaluated(
4653         getSema(),
4654         Uneval ? Sema::ExpressionEvaluationContext::Unevaluated
4655                : Sema::ExpressionEvaluationContext::ConstantEvaluated,
4656         Sema::ReuseLambdaContextDecl, /*ExprContext=*/
4657         Sema::ExpressionEvaluationContextRecord::EK_TemplateArgument);
4658 
4659     Expr *InputExpr = Input.getSourceExpression();
4660     if (!InputExpr)
4661       InputExpr = Input.getArgument().getAsExpr();
4662 
4663     ExprResult E = getDerived().TransformExpr(InputExpr);
4664     E = SemaRef.ActOnConstantExpression(E);
4665     if (E.isInvalid())
4666       return true;
4667     Output = TemplateArgumentLoc(TemplateArgument(E.get()), E.get());
4668     return false;
4669   }
4670   }
4671 
4672   // Work around bogus GCC warning
4673   return true;
4674 }
4675 
4676 /// Iterator adaptor that invents template argument location information
4677 /// for each of the template arguments in its underlying iterator.
4678 template<typename Derived, typename InputIterator>
4679 class TemplateArgumentLocInventIterator {
4680   TreeTransform<Derived> &Self;
4681   InputIterator Iter;
4682 
4683 public:
4684   typedef TemplateArgumentLoc value_type;
4685   typedef TemplateArgumentLoc reference;
4686   typedef typename std::iterator_traits<InputIterator>::difference_type
4687     difference_type;
4688   typedef std::input_iterator_tag iterator_category;
4689 
4690   class pointer {
4691     TemplateArgumentLoc Arg;
4692 
4693   public:
4694     explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
4695 
4696     const TemplateArgumentLoc *operator->() const { return &Arg; }
4697   };
4698 
4699   TemplateArgumentLocInventIterator() { }
4700 
4701   explicit TemplateArgumentLocInventIterator(TreeTransform<Derived> &Self,
4702                                              InputIterator Iter)
4703     : Self(Self), Iter(Iter) { }
4704 
4705   TemplateArgumentLocInventIterator &operator++() {
4706     ++Iter;
4707     return *this;
4708   }
4709 
4710   TemplateArgumentLocInventIterator operator++(int) {
4711     TemplateArgumentLocInventIterator Old(*this);
4712     ++(*this);
4713     return Old;
4714   }
4715 
4716   reference operator*() const {
4717     TemplateArgumentLoc Result;
4718     Self.InventTemplateArgumentLoc(*Iter, Result);
4719     return Result;
4720   }
4721 
4722   pointer operator->() const { return pointer(**this); }
4723 
4724   friend bool operator==(const TemplateArgumentLocInventIterator &X,
4725                          const TemplateArgumentLocInventIterator &Y) {
4726     return X.Iter == Y.Iter;
4727   }
4728 
4729   friend bool operator!=(const TemplateArgumentLocInventIterator &X,
4730                          const TemplateArgumentLocInventIterator &Y) {
4731     return X.Iter != Y.Iter;
4732   }
4733 };
4734 
4735 template<typename Derived>
4736 template<typename InputIterator>
4737 bool TreeTransform<Derived>::TransformTemplateArguments(
4738     InputIterator First, InputIterator Last, TemplateArgumentListInfo &Outputs,
4739     bool Uneval) {
4740   for (; First != Last; ++First) {
4741     TemplateArgumentLoc Out;
4742     TemplateArgumentLoc In = *First;
4743 
4744     if (In.getArgument().getKind() == TemplateArgument::Pack) {
4745       // Unpack argument packs, which we translate them into separate
4746       // arguments.
4747       // FIXME: We could do much better if we could guarantee that the
4748       // TemplateArgumentLocInfo for the pack expansion would be usable for
4749       // all of the template arguments in the argument pack.
4750       typedef TemplateArgumentLocInventIterator<Derived,
4751                                                 TemplateArgument::pack_iterator>
4752         PackLocIterator;
4753       if (TransformTemplateArguments(PackLocIterator(*this,
4754                                                  In.getArgument().pack_begin()),
4755                                      PackLocIterator(*this,
4756                                                    In.getArgument().pack_end()),
4757                                      Outputs, Uneval))
4758         return true;
4759 
4760       continue;
4761     }
4762 
4763     if (In.getArgument().isPackExpansion()) {
4764       // We have a pack expansion, for which we will be substituting into
4765       // the pattern.
4766       SourceLocation Ellipsis;
4767       std::optional<unsigned> OrigNumExpansions;
4768       TemplateArgumentLoc Pattern
4769         = getSema().getTemplateArgumentPackExpansionPattern(
4770               In, Ellipsis, OrigNumExpansions);
4771 
4772       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4773       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
4774       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
4775 
4776       // Determine whether the set of unexpanded parameter packs can and should
4777       // be expanded.
4778       bool Expand = true;
4779       bool RetainExpansion = false;
4780       std::optional<unsigned> NumExpansions = OrigNumExpansions;
4781       if (getDerived().TryExpandParameterPacks(Ellipsis,
4782                                                Pattern.getSourceRange(),
4783                                                Unexpanded,
4784                                                Expand,
4785                                                RetainExpansion,
4786                                                NumExpansions))
4787         return true;
4788 
4789       if (!Expand) {
4790         // The transform has determined that we should perform a simple
4791         // transformation on the pack expansion, producing another pack
4792         // expansion.
4793         TemplateArgumentLoc OutPattern;
4794         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4795         if (getDerived().TransformTemplateArgument(Pattern, OutPattern, Uneval))
4796           return true;
4797 
4798         Out = getDerived().RebuildPackExpansion(OutPattern, Ellipsis,
4799                                                 NumExpansions);
4800         if (Out.getArgument().isNull())
4801           return true;
4802 
4803         Outputs.addArgument(Out);
4804         continue;
4805       }
4806 
4807       // The transform has determined that we should perform an elementwise
4808       // expansion of the pattern. Do so.
4809       for (unsigned I = 0; I != *NumExpansions; ++I) {
4810         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
4811 
4812         if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4813           return true;
4814 
4815         if (Out.getArgument().containsUnexpandedParameterPack()) {
4816           Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4817                                                   OrigNumExpansions);
4818           if (Out.getArgument().isNull())
4819             return true;
4820         }
4821 
4822         Outputs.addArgument(Out);
4823       }
4824 
4825       // If we're supposed to retain a pack expansion, do so by temporarily
4826       // forgetting the partially-substituted parameter pack.
4827       if (RetainExpansion) {
4828         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
4829 
4830         if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4831           return true;
4832 
4833         Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4834                                                 OrigNumExpansions);
4835         if (Out.getArgument().isNull())
4836           return true;
4837 
4838         Outputs.addArgument(Out);
4839       }
4840 
4841       continue;
4842     }
4843 
4844     // The simple case:
4845     if (getDerived().TransformTemplateArgument(In, Out, Uneval))
4846       return true;
4847 
4848     Outputs.addArgument(Out);
4849   }
4850 
4851   return false;
4852 
4853 }
4854 
4855 //===----------------------------------------------------------------------===//
4856 // Type transformation
4857 //===----------------------------------------------------------------------===//
4858 
4859 template<typename Derived>
4860 QualType TreeTransform<Derived>::TransformType(QualType T) {
4861   if (getDerived().AlreadyTransformed(T))
4862     return T;
4863 
4864   // Temporary workaround.  All of these transformations should
4865   // eventually turn into transformations on TypeLocs.
4866   TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4867                                                 getDerived().getBaseLocation());
4868 
4869   TypeSourceInfo *NewDI = getDerived().TransformType(DI);
4870 
4871   if (!NewDI)
4872     return QualType();
4873 
4874   return NewDI->getType();
4875 }
4876 
4877 template<typename Derived>
4878 TypeSourceInfo *TreeTransform<Derived>::TransformType(TypeSourceInfo *DI) {
4879   // Refine the base location to the type's location.
4880   TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4881                        getDerived().getBaseEntity());
4882   if (getDerived().AlreadyTransformed(DI->getType()))
4883     return DI;
4884 
4885   TypeLocBuilder TLB;
4886 
4887   TypeLoc TL = DI->getTypeLoc();
4888   TLB.reserve(TL.getFullDataSize());
4889 
4890   QualType Result = getDerived().TransformType(TLB, TL);
4891   if (Result.isNull())
4892     return nullptr;
4893 
4894   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4895 }
4896 
4897 template<typename Derived>
4898 QualType
4899 TreeTransform<Derived>::TransformType(TypeLocBuilder &TLB, TypeLoc T) {
4900   switch (T.getTypeLocClass()) {
4901 #define ABSTRACT_TYPELOC(CLASS, PARENT)
4902 #define TYPELOC(CLASS, PARENT)                                                 \
4903   case TypeLoc::CLASS:                                                         \
4904     return getDerived().Transform##CLASS##Type(TLB,                            \
4905                                                T.castAs<CLASS##TypeLoc>());
4906 #include "clang/AST/TypeLocNodes.def"
4907   }
4908 
4909   llvm_unreachable("unhandled type loc!");
4910 }
4911 
4912 template<typename Derived>
4913 QualType TreeTransform<Derived>::TransformTypeWithDeducedTST(QualType T) {
4914   if (!isa<DependentNameType>(T))
4915     return TransformType(T);
4916 
4917   if (getDerived().AlreadyTransformed(T))
4918     return T;
4919   TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4920                                                 getDerived().getBaseLocation());
4921   TypeSourceInfo *NewDI = getDerived().TransformTypeWithDeducedTST(DI);
4922   return NewDI ? NewDI->getType() : QualType();
4923 }
4924 
4925 template<typename Derived>
4926 TypeSourceInfo *
4927 TreeTransform<Derived>::TransformTypeWithDeducedTST(TypeSourceInfo *DI) {
4928   if (!isa<DependentNameType>(DI->getType()))
4929     return TransformType(DI);
4930 
4931   // Refine the base location to the type's location.
4932   TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4933                        getDerived().getBaseEntity());
4934   if (getDerived().AlreadyTransformed(DI->getType()))
4935     return DI;
4936 
4937   TypeLocBuilder TLB;
4938 
4939   TypeLoc TL = DI->getTypeLoc();
4940   TLB.reserve(TL.getFullDataSize());
4941 
4942   auto QTL = TL.getAs<QualifiedTypeLoc>();
4943   if (QTL)
4944     TL = QTL.getUnqualifiedLoc();
4945 
4946   auto DNTL = TL.castAs<DependentNameTypeLoc>();
4947 
4948   QualType Result = getDerived().TransformDependentNameType(
4949       TLB, DNTL, /*DeducedTSTContext*/true);
4950   if (Result.isNull())
4951     return nullptr;
4952 
4953   if (QTL) {
4954     Result = getDerived().RebuildQualifiedType(Result, QTL);
4955     if (Result.isNull())
4956       return nullptr;
4957     TLB.TypeWasModifiedSafely(Result);
4958   }
4959 
4960   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4961 }
4962 
4963 template<typename Derived>
4964 QualType
4965 TreeTransform<Derived>::TransformQualifiedType(TypeLocBuilder &TLB,
4966                                                QualifiedTypeLoc T) {
4967   QualType Result;
4968   TypeLoc UnqualTL = T.getUnqualifiedLoc();
4969   auto SuppressObjCLifetime =
4970       T.getType().getLocalQualifiers().hasObjCLifetime();
4971   if (auto TTP = UnqualTL.getAs<TemplateTypeParmTypeLoc>()) {
4972     Result = getDerived().TransformTemplateTypeParmType(TLB, TTP,
4973                                                         SuppressObjCLifetime);
4974   } else if (auto STTP = UnqualTL.getAs<SubstTemplateTypeParmPackTypeLoc>()) {
4975     Result = getDerived().TransformSubstTemplateTypeParmPackType(
4976         TLB, STTP, SuppressObjCLifetime);
4977   } else {
4978     Result = getDerived().TransformType(TLB, UnqualTL);
4979   }
4980 
4981   if (Result.isNull())
4982     return QualType();
4983 
4984   Result = getDerived().RebuildQualifiedType(Result, T);
4985 
4986   if (Result.isNull())
4987     return QualType();
4988 
4989   // RebuildQualifiedType might have updated the type, but not in a way
4990   // that invalidates the TypeLoc. (There's no location information for
4991   // qualifiers.)
4992   TLB.TypeWasModifiedSafely(Result);
4993 
4994   return Result;
4995 }
4996 
4997 template <typename Derived>
4998 QualType TreeTransform<Derived>::RebuildQualifiedType(QualType T,
4999                                                       QualifiedTypeLoc TL) {
5000 
5001   SourceLocation Loc = TL.getBeginLoc();
5002   Qualifiers Quals = TL.getType().getLocalQualifiers();
5003 
5004   if ((T.getAddressSpace() != LangAS::Default &&
5005        Quals.getAddressSpace() != LangAS::Default) &&
5006       T.getAddressSpace() != Quals.getAddressSpace()) {
5007     SemaRef.Diag(Loc, diag::err_address_space_mismatch_templ_inst)
5008         << TL.getType() << T;
5009     return QualType();
5010   }
5011 
5012   // C++ [dcl.fct]p7:
5013   //   [When] adding cv-qualifications on top of the function type [...] the
5014   //   cv-qualifiers are ignored.
5015   if (T->isFunctionType()) {
5016     T = SemaRef.getASTContext().getAddrSpaceQualType(T,
5017                                                      Quals.getAddressSpace());
5018     return T;
5019   }
5020 
5021   // C++ [dcl.ref]p1:
5022   //   when the cv-qualifiers are introduced through the use of a typedef-name
5023   //   or decltype-specifier [...] the cv-qualifiers are ignored.
5024   // Note that [dcl.ref]p1 lists all cases in which cv-qualifiers can be
5025   // applied to a reference type.
5026   if (T->isReferenceType()) {
5027     // The only qualifier that applies to a reference type is restrict.
5028     if (!Quals.hasRestrict())
5029       return T;
5030     Quals = Qualifiers::fromCVRMask(Qualifiers::Restrict);
5031   }
5032 
5033   // Suppress Objective-C lifetime qualifiers if they don't make sense for the
5034   // resulting type.
5035   if (Quals.hasObjCLifetime()) {
5036     if (!T->isObjCLifetimeType() && !T->isDependentType())
5037       Quals.removeObjCLifetime();
5038     else if (T.getObjCLifetime()) {
5039       // Objective-C ARC:
5040       //   A lifetime qualifier applied to a substituted template parameter
5041       //   overrides the lifetime qualifier from the template argument.
5042       const AutoType *AutoTy;
5043       if ((AutoTy = dyn_cast<AutoType>(T)) && AutoTy->isDeduced()) {
5044         // 'auto' types behave the same way as template parameters.
5045         QualType Deduced = AutoTy->getDeducedType();
5046         Qualifiers Qs = Deduced.getQualifiers();
5047         Qs.removeObjCLifetime();
5048         Deduced =
5049             SemaRef.Context.getQualifiedType(Deduced.getUnqualifiedType(), Qs);
5050         T = SemaRef.Context.getAutoType(Deduced, AutoTy->getKeyword(),
5051                                         AutoTy->isDependentType(),
5052                                         /*isPack=*/false,
5053                                         AutoTy->getTypeConstraintConcept(),
5054                                         AutoTy->getTypeConstraintArguments());
5055       } else {
5056         // Otherwise, complain about the addition of a qualifier to an
5057         // already-qualified type.
5058         // FIXME: Why is this check not in Sema::BuildQualifiedType?
5059         SemaRef.Diag(Loc, diag::err_attr_objc_ownership_redundant) << T;
5060         Quals.removeObjCLifetime();
5061       }
5062     }
5063   }
5064 
5065   return SemaRef.BuildQualifiedType(T, Loc, Quals);
5066 }
5067 
5068 template<typename Derived>
5069 TypeLoc
5070 TreeTransform<Derived>::TransformTypeInObjectScope(TypeLoc TL,
5071                                                    QualType ObjectType,
5072                                                    NamedDecl *UnqualLookup,
5073                                                    CXXScopeSpec &SS) {
5074   if (getDerived().AlreadyTransformed(TL.getType()))
5075     return TL;
5076 
5077   TypeSourceInfo *TSI =
5078       TransformTSIInObjectScope(TL, ObjectType, UnqualLookup, SS);
5079   if (TSI)
5080     return TSI->getTypeLoc();
5081   return TypeLoc();
5082 }
5083 
5084 template<typename Derived>
5085 TypeSourceInfo *
5086 TreeTransform<Derived>::TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
5087                                                    QualType ObjectType,
5088                                                    NamedDecl *UnqualLookup,
5089                                                    CXXScopeSpec &SS) {
5090   if (getDerived().AlreadyTransformed(TSInfo->getType()))
5091     return TSInfo;
5092 
5093   return TransformTSIInObjectScope(TSInfo->getTypeLoc(), ObjectType,
5094                                    UnqualLookup, SS);
5095 }
5096 
5097 template <typename Derived>
5098 TypeSourceInfo *TreeTransform<Derived>::TransformTSIInObjectScope(
5099     TypeLoc TL, QualType ObjectType, NamedDecl *UnqualLookup,
5100     CXXScopeSpec &SS) {
5101   QualType T = TL.getType();
5102   assert(!getDerived().AlreadyTransformed(T));
5103 
5104   TypeLocBuilder TLB;
5105   QualType Result;
5106 
5107   if (isa<TemplateSpecializationType>(T)) {
5108     TemplateSpecializationTypeLoc SpecTL =
5109         TL.castAs<TemplateSpecializationTypeLoc>();
5110 
5111     TemplateName Template = getDerived().TransformTemplateName(
5112         SS, SpecTL.getTypePtr()->getTemplateName(), SpecTL.getTemplateNameLoc(),
5113         ObjectType, UnqualLookup, /*AllowInjectedClassName*/true);
5114     if (Template.isNull())
5115       return nullptr;
5116 
5117     Result = getDerived().TransformTemplateSpecializationType(TLB, SpecTL,
5118                                                               Template);
5119   } else if (isa<DependentTemplateSpecializationType>(T)) {
5120     DependentTemplateSpecializationTypeLoc SpecTL =
5121         TL.castAs<DependentTemplateSpecializationTypeLoc>();
5122 
5123     TemplateName Template
5124       = getDerived().RebuildTemplateName(SS,
5125                                          SpecTL.getTemplateKeywordLoc(),
5126                                          *SpecTL.getTypePtr()->getIdentifier(),
5127                                          SpecTL.getTemplateNameLoc(),
5128                                          ObjectType, UnqualLookup,
5129                                          /*AllowInjectedClassName*/true);
5130     if (Template.isNull())
5131       return nullptr;
5132 
5133     Result = getDerived().TransformDependentTemplateSpecializationType(TLB,
5134                                                                        SpecTL,
5135                                                                        Template,
5136                                                                        SS);
5137   } else {
5138     // Nothing special needs to be done for these.
5139     Result = getDerived().TransformType(TLB, TL);
5140   }
5141 
5142   if (Result.isNull())
5143     return nullptr;
5144 
5145   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
5146 }
5147 
5148 template <class TyLoc> static inline
5149 QualType TransformTypeSpecType(TypeLocBuilder &TLB, TyLoc T) {
5150   TyLoc NewT = TLB.push<TyLoc>(T.getType());
5151   NewT.setNameLoc(T.getNameLoc());
5152   return T.getType();
5153 }
5154 
5155 template<typename Derived>
5156 QualType TreeTransform<Derived>::TransformBuiltinType(TypeLocBuilder &TLB,
5157                                                       BuiltinTypeLoc T) {
5158   BuiltinTypeLoc NewT = TLB.push<BuiltinTypeLoc>(T.getType());
5159   NewT.setBuiltinLoc(T.getBuiltinLoc());
5160   if (T.needsExtraLocalData())
5161     NewT.getWrittenBuiltinSpecs() = T.getWrittenBuiltinSpecs();
5162   return T.getType();
5163 }
5164 
5165 template<typename Derived>
5166 QualType TreeTransform<Derived>::TransformComplexType(TypeLocBuilder &TLB,
5167                                                       ComplexTypeLoc T) {
5168   // FIXME: recurse?
5169   return TransformTypeSpecType(TLB, T);
5170 }
5171 
5172 template <typename Derived>
5173 QualType TreeTransform<Derived>::TransformAdjustedType(TypeLocBuilder &TLB,
5174                                                        AdjustedTypeLoc TL) {
5175   // Adjustments applied during transformation are handled elsewhere.
5176   return getDerived().TransformType(TLB, TL.getOriginalLoc());
5177 }
5178 
5179 template<typename Derived>
5180 QualType TreeTransform<Derived>::TransformDecayedType(TypeLocBuilder &TLB,
5181                                                       DecayedTypeLoc TL) {
5182   QualType OriginalType = getDerived().TransformType(TLB, TL.getOriginalLoc());
5183   if (OriginalType.isNull())
5184     return QualType();
5185 
5186   QualType Result = TL.getType();
5187   if (getDerived().AlwaysRebuild() ||
5188       OriginalType != TL.getOriginalLoc().getType())
5189     Result = SemaRef.Context.getDecayedType(OriginalType);
5190   TLB.push<DecayedTypeLoc>(Result);
5191   // Nothing to set for DecayedTypeLoc.
5192   return Result;
5193 }
5194 
5195 template<typename Derived>
5196 QualType TreeTransform<Derived>::TransformPointerType(TypeLocBuilder &TLB,
5197                                                       PointerTypeLoc TL) {
5198   QualType PointeeType
5199     = getDerived().TransformType(TLB, TL.getPointeeLoc());
5200   if (PointeeType.isNull())
5201     return QualType();
5202 
5203   QualType Result = TL.getType();
5204   if (PointeeType->getAs<ObjCObjectType>()) {
5205     // A dependent pointer type 'T *' has is being transformed such
5206     // that an Objective-C class type is being replaced for 'T'. The
5207     // resulting pointer type is an ObjCObjectPointerType, not a
5208     // PointerType.
5209     Result = SemaRef.Context.getObjCObjectPointerType(PointeeType);
5210 
5211     ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
5212     NewT.setStarLoc(TL.getStarLoc());
5213     return Result;
5214   }
5215 
5216   if (getDerived().AlwaysRebuild() ||
5217       PointeeType != TL.getPointeeLoc().getType()) {
5218     Result = getDerived().RebuildPointerType(PointeeType, TL.getSigilLoc());
5219     if (Result.isNull())
5220       return QualType();
5221   }
5222 
5223   // Objective-C ARC can add lifetime qualifiers to the type that we're
5224   // pointing to.
5225   TLB.TypeWasModifiedSafely(Result->getPointeeType());
5226 
5227   PointerTypeLoc NewT = TLB.push<PointerTypeLoc>(Result);
5228   NewT.setSigilLoc(TL.getSigilLoc());
5229   return Result;
5230 }
5231 
5232 template<typename Derived>
5233 QualType
5234 TreeTransform<Derived>::TransformBlockPointerType(TypeLocBuilder &TLB,
5235                                                   BlockPointerTypeLoc TL) {
5236   QualType PointeeType
5237     = getDerived().TransformType(TLB, TL.getPointeeLoc());
5238   if (PointeeType.isNull())
5239     return QualType();
5240 
5241   QualType Result = TL.getType();
5242   if (getDerived().AlwaysRebuild() ||
5243       PointeeType != TL.getPointeeLoc().getType()) {
5244     Result = getDerived().RebuildBlockPointerType(PointeeType,
5245                                                   TL.getSigilLoc());
5246     if (Result.isNull())
5247       return QualType();
5248   }
5249 
5250   BlockPointerTypeLoc NewT = TLB.push<BlockPointerTypeLoc>(Result);
5251   NewT.setSigilLoc(TL.getSigilLoc());
5252   return Result;
5253 }
5254 
5255 /// Transforms a reference type.  Note that somewhat paradoxically we
5256 /// don't care whether the type itself is an l-value type or an r-value
5257 /// type;  we only care if the type was *written* as an l-value type
5258 /// or an r-value type.
5259 template<typename Derived>
5260 QualType
5261 TreeTransform<Derived>::TransformReferenceType(TypeLocBuilder &TLB,
5262                                                ReferenceTypeLoc TL) {
5263   const ReferenceType *T = TL.getTypePtr();
5264 
5265   // Note that this works with the pointee-as-written.
5266   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
5267   if (PointeeType.isNull())
5268     return QualType();
5269 
5270   QualType Result = TL.getType();
5271   if (getDerived().AlwaysRebuild() ||
5272       PointeeType != T->getPointeeTypeAsWritten()) {
5273     Result = getDerived().RebuildReferenceType(PointeeType,
5274                                                T->isSpelledAsLValue(),
5275                                                TL.getSigilLoc());
5276     if (Result.isNull())
5277       return QualType();
5278   }
5279 
5280   // Objective-C ARC can add lifetime qualifiers to the type that we're
5281   // referring to.
5282   TLB.TypeWasModifiedSafely(
5283       Result->castAs<ReferenceType>()->getPointeeTypeAsWritten());
5284 
5285   // r-value references can be rebuilt as l-value references.
5286   ReferenceTypeLoc NewTL;
5287   if (isa<LValueReferenceType>(Result))
5288     NewTL = TLB.push<LValueReferenceTypeLoc>(Result);
5289   else
5290     NewTL = TLB.push<RValueReferenceTypeLoc>(Result);
5291   NewTL.setSigilLoc(TL.getSigilLoc());
5292 
5293   return Result;
5294 }
5295 
5296 template<typename Derived>
5297 QualType
5298 TreeTransform<Derived>::TransformLValueReferenceType(TypeLocBuilder &TLB,
5299                                                  LValueReferenceTypeLoc TL) {
5300   return TransformReferenceType(TLB, TL);
5301 }
5302 
5303 template<typename Derived>
5304 QualType
5305 TreeTransform<Derived>::TransformRValueReferenceType(TypeLocBuilder &TLB,
5306                                                  RValueReferenceTypeLoc TL) {
5307   return TransformReferenceType(TLB, TL);
5308 }
5309 
5310 template<typename Derived>
5311 QualType
5312 TreeTransform<Derived>::TransformMemberPointerType(TypeLocBuilder &TLB,
5313                                                    MemberPointerTypeLoc TL) {
5314   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
5315   if (PointeeType.isNull())
5316     return QualType();
5317 
5318   TypeSourceInfo* OldClsTInfo = TL.getClassTInfo();
5319   TypeSourceInfo *NewClsTInfo = nullptr;
5320   if (OldClsTInfo) {
5321     NewClsTInfo = getDerived().TransformType(OldClsTInfo);
5322     if (!NewClsTInfo)
5323       return QualType();
5324   }
5325 
5326   const MemberPointerType *T = TL.getTypePtr();
5327   QualType OldClsType = QualType(T->getClass(), 0);
5328   QualType NewClsType;
5329   if (NewClsTInfo)
5330     NewClsType = NewClsTInfo->getType();
5331   else {
5332     NewClsType = getDerived().TransformType(OldClsType);
5333     if (NewClsType.isNull())
5334       return QualType();
5335   }
5336 
5337   QualType Result = TL.getType();
5338   if (getDerived().AlwaysRebuild() ||
5339       PointeeType != T->getPointeeType() ||
5340       NewClsType != OldClsType) {
5341     Result = getDerived().RebuildMemberPointerType(PointeeType, NewClsType,
5342                                                    TL.getStarLoc());
5343     if (Result.isNull())
5344       return QualType();
5345   }
5346 
5347   // If we had to adjust the pointee type when building a member pointer, make
5348   // sure to push TypeLoc info for it.
5349   const MemberPointerType *MPT = Result->getAs<MemberPointerType>();
5350   if (MPT && PointeeType != MPT->getPointeeType()) {
5351     assert(isa<AdjustedType>(MPT->getPointeeType()));
5352     TLB.push<AdjustedTypeLoc>(MPT->getPointeeType());
5353   }
5354 
5355   MemberPointerTypeLoc NewTL = TLB.push<MemberPointerTypeLoc>(Result);
5356   NewTL.setSigilLoc(TL.getSigilLoc());
5357   NewTL.setClassTInfo(NewClsTInfo);
5358 
5359   return Result;
5360 }
5361 
5362 template<typename Derived>
5363 QualType
5364 TreeTransform<Derived>::TransformConstantArrayType(TypeLocBuilder &TLB,
5365                                                    ConstantArrayTypeLoc TL) {
5366   const ConstantArrayType *T = TL.getTypePtr();
5367   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5368   if (ElementType.isNull())
5369     return QualType();
5370 
5371   // Prefer the expression from the TypeLoc;  the other may have been uniqued.
5372   Expr *OldSize = TL.getSizeExpr();
5373   if (!OldSize)
5374     OldSize = const_cast<Expr*>(T->getSizeExpr());
5375   Expr *NewSize = nullptr;
5376   if (OldSize) {
5377     EnterExpressionEvaluationContext Unevaluated(
5378         SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5379     NewSize = getDerived().TransformExpr(OldSize).template getAs<Expr>();
5380     NewSize = SemaRef.ActOnConstantExpression(NewSize).get();
5381   }
5382 
5383   QualType Result = TL.getType();
5384   if (getDerived().AlwaysRebuild() ||
5385       ElementType != T->getElementType() ||
5386       (T->getSizeExpr() && NewSize != OldSize)) {
5387     Result = getDerived().RebuildConstantArrayType(ElementType,
5388                                                    T->getSizeModifier(),
5389                                                    T->getSize(), NewSize,
5390                                              T->getIndexTypeCVRQualifiers(),
5391                                                    TL.getBracketsRange());
5392     if (Result.isNull())
5393       return QualType();
5394   }
5395 
5396   // We might have either a ConstantArrayType or a VariableArrayType now:
5397   // a ConstantArrayType is allowed to have an element type which is a
5398   // VariableArrayType if the type is dependent.  Fortunately, all array
5399   // types have the same location layout.
5400   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
5401   NewTL.setLBracketLoc(TL.getLBracketLoc());
5402   NewTL.setRBracketLoc(TL.getRBracketLoc());
5403   NewTL.setSizeExpr(NewSize);
5404 
5405   return Result;
5406 }
5407 
5408 template<typename Derived>
5409 QualType TreeTransform<Derived>::TransformIncompleteArrayType(
5410                                               TypeLocBuilder &TLB,
5411                                               IncompleteArrayTypeLoc TL) {
5412   const IncompleteArrayType *T = TL.getTypePtr();
5413   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5414   if (ElementType.isNull())
5415     return QualType();
5416 
5417   QualType Result = TL.getType();
5418   if (getDerived().AlwaysRebuild() ||
5419       ElementType != T->getElementType()) {
5420     Result = getDerived().RebuildIncompleteArrayType(ElementType,
5421                                                      T->getSizeModifier(),
5422                                            T->getIndexTypeCVRQualifiers(),
5423                                                      TL.getBracketsRange());
5424     if (Result.isNull())
5425       return QualType();
5426   }
5427 
5428   IncompleteArrayTypeLoc NewTL = TLB.push<IncompleteArrayTypeLoc>(Result);
5429   NewTL.setLBracketLoc(TL.getLBracketLoc());
5430   NewTL.setRBracketLoc(TL.getRBracketLoc());
5431   NewTL.setSizeExpr(nullptr);
5432 
5433   return Result;
5434 }
5435 
5436 template<typename Derived>
5437 QualType
5438 TreeTransform<Derived>::TransformVariableArrayType(TypeLocBuilder &TLB,
5439                                                    VariableArrayTypeLoc TL) {
5440   const VariableArrayType *T = TL.getTypePtr();
5441   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5442   if (ElementType.isNull())
5443     return QualType();
5444 
5445   ExprResult SizeResult;
5446   {
5447     EnterExpressionEvaluationContext Context(
5448         SemaRef, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
5449     SizeResult = getDerived().TransformExpr(T->getSizeExpr());
5450   }
5451   if (SizeResult.isInvalid())
5452     return QualType();
5453   SizeResult =
5454       SemaRef.ActOnFinishFullExpr(SizeResult.get(), /*DiscardedValue*/ false);
5455   if (SizeResult.isInvalid())
5456     return QualType();
5457 
5458   Expr *Size = SizeResult.get();
5459 
5460   QualType Result = TL.getType();
5461   if (getDerived().AlwaysRebuild() ||
5462       ElementType != T->getElementType() ||
5463       Size != T->getSizeExpr()) {
5464     Result = getDerived().RebuildVariableArrayType(ElementType,
5465                                                    T->getSizeModifier(),
5466                                                    Size,
5467                                              T->getIndexTypeCVRQualifiers(),
5468                                                    TL.getBracketsRange());
5469     if (Result.isNull())
5470       return QualType();
5471   }
5472 
5473   // We might have constant size array now, but fortunately it has the same
5474   // location layout.
5475   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
5476   NewTL.setLBracketLoc(TL.getLBracketLoc());
5477   NewTL.setRBracketLoc(TL.getRBracketLoc());
5478   NewTL.setSizeExpr(Size);
5479 
5480   return Result;
5481 }
5482 
5483 template<typename Derived>
5484 QualType
5485 TreeTransform<Derived>::TransformDependentSizedArrayType(TypeLocBuilder &TLB,
5486                                              DependentSizedArrayTypeLoc TL) {
5487   const DependentSizedArrayType *T = TL.getTypePtr();
5488   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5489   if (ElementType.isNull())
5490     return QualType();
5491 
5492   // Array bounds are constant expressions.
5493   EnterExpressionEvaluationContext Unevaluated(
5494       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5495 
5496   // If we have a VLA then it won't be a constant.
5497   SemaRef.ExprEvalContexts.back().InConditionallyConstantEvaluateContext = true;
5498 
5499   // Prefer the expression from the TypeLoc;  the other may have been uniqued.
5500   Expr *origSize = TL.getSizeExpr();
5501   if (!origSize) origSize = T->getSizeExpr();
5502 
5503   ExprResult sizeResult
5504     = getDerived().TransformExpr(origSize);
5505   sizeResult = SemaRef.ActOnConstantExpression(sizeResult);
5506   if (sizeResult.isInvalid())
5507     return QualType();
5508 
5509   Expr *size = sizeResult.get();
5510 
5511   QualType Result = TL.getType();
5512   if (getDerived().AlwaysRebuild() ||
5513       ElementType != T->getElementType() ||
5514       size != origSize) {
5515     Result = getDerived().RebuildDependentSizedArrayType(ElementType,
5516                                                          T->getSizeModifier(),
5517                                                          size,
5518                                                 T->getIndexTypeCVRQualifiers(),
5519                                                         TL.getBracketsRange());
5520     if (Result.isNull())
5521       return QualType();
5522   }
5523 
5524   // We might have any sort of array type now, but fortunately they
5525   // all have the same location layout.
5526   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
5527   NewTL.setLBracketLoc(TL.getLBracketLoc());
5528   NewTL.setRBracketLoc(TL.getRBracketLoc());
5529   NewTL.setSizeExpr(size);
5530 
5531   return Result;
5532 }
5533 
5534 template <typename Derived>
5535 QualType TreeTransform<Derived>::TransformDependentVectorType(
5536     TypeLocBuilder &TLB, DependentVectorTypeLoc TL) {
5537   const DependentVectorType *T = TL.getTypePtr();
5538   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5539   if (ElementType.isNull())
5540     return QualType();
5541 
5542   EnterExpressionEvaluationContext Unevaluated(
5543       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5544 
5545   ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
5546   Size = SemaRef.ActOnConstantExpression(Size);
5547   if (Size.isInvalid())
5548     return QualType();
5549 
5550   QualType Result = TL.getType();
5551   if (getDerived().AlwaysRebuild() || ElementType != T->getElementType() ||
5552       Size.get() != T->getSizeExpr()) {
5553     Result = getDerived().RebuildDependentVectorType(
5554         ElementType, Size.get(), T->getAttributeLoc(), T->getVectorKind());
5555     if (Result.isNull())
5556       return QualType();
5557   }
5558 
5559   // Result might be dependent or not.
5560   if (isa<DependentVectorType>(Result)) {
5561     DependentVectorTypeLoc NewTL =
5562         TLB.push<DependentVectorTypeLoc>(Result);
5563     NewTL.setNameLoc(TL.getNameLoc());
5564   } else {
5565     VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
5566     NewTL.setNameLoc(TL.getNameLoc());
5567   }
5568 
5569   return Result;
5570 }
5571 
5572 template<typename Derived>
5573 QualType TreeTransform<Derived>::TransformDependentSizedExtVectorType(
5574                                       TypeLocBuilder &TLB,
5575                                       DependentSizedExtVectorTypeLoc TL) {
5576   const DependentSizedExtVectorType *T = TL.getTypePtr();
5577 
5578   // FIXME: ext vector locs should be nested
5579   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5580   if (ElementType.isNull())
5581     return QualType();
5582 
5583   // Vector sizes are constant expressions.
5584   EnterExpressionEvaluationContext Unevaluated(
5585       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5586 
5587   ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
5588   Size = SemaRef.ActOnConstantExpression(Size);
5589   if (Size.isInvalid())
5590     return QualType();
5591 
5592   QualType Result = TL.getType();
5593   if (getDerived().AlwaysRebuild() ||
5594       ElementType != T->getElementType() ||
5595       Size.get() != T->getSizeExpr()) {
5596     Result = getDerived().RebuildDependentSizedExtVectorType(ElementType,
5597                                                              Size.get(),
5598                                                          T->getAttributeLoc());
5599     if (Result.isNull())
5600       return QualType();
5601   }
5602 
5603   // Result might be dependent or not.
5604   if (isa<DependentSizedExtVectorType>(Result)) {
5605     DependentSizedExtVectorTypeLoc NewTL
5606       = TLB.push<DependentSizedExtVectorTypeLoc>(Result);
5607     NewTL.setNameLoc(TL.getNameLoc());
5608   } else {
5609     ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
5610     NewTL.setNameLoc(TL.getNameLoc());
5611   }
5612 
5613   return Result;
5614 }
5615 
5616 template <typename Derived>
5617 QualType
5618 TreeTransform<Derived>::TransformConstantMatrixType(TypeLocBuilder &TLB,
5619                                                     ConstantMatrixTypeLoc TL) {
5620   const ConstantMatrixType *T = TL.getTypePtr();
5621   QualType ElementType = getDerived().TransformType(T->getElementType());
5622   if (ElementType.isNull())
5623     return QualType();
5624 
5625   QualType Result = TL.getType();
5626   if (getDerived().AlwaysRebuild() || ElementType != T->getElementType()) {
5627     Result = getDerived().RebuildConstantMatrixType(
5628         ElementType, T->getNumRows(), T->getNumColumns());
5629     if (Result.isNull())
5630       return QualType();
5631   }
5632 
5633   ConstantMatrixTypeLoc NewTL = TLB.push<ConstantMatrixTypeLoc>(Result);
5634   NewTL.setAttrNameLoc(TL.getAttrNameLoc());
5635   NewTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5636   NewTL.setAttrRowOperand(TL.getAttrRowOperand());
5637   NewTL.setAttrColumnOperand(TL.getAttrColumnOperand());
5638 
5639   return Result;
5640 }
5641 
5642 template <typename Derived>
5643 QualType TreeTransform<Derived>::TransformDependentSizedMatrixType(
5644     TypeLocBuilder &TLB, DependentSizedMatrixTypeLoc TL) {
5645   const DependentSizedMatrixType *T = TL.getTypePtr();
5646 
5647   QualType ElementType = getDerived().TransformType(T->getElementType());
5648   if (ElementType.isNull()) {
5649     return QualType();
5650   }
5651 
5652   // Matrix dimensions are constant expressions.
5653   EnterExpressionEvaluationContext Unevaluated(
5654       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5655 
5656   Expr *origRows = TL.getAttrRowOperand();
5657   if (!origRows)
5658     origRows = T->getRowExpr();
5659   Expr *origColumns = TL.getAttrColumnOperand();
5660   if (!origColumns)
5661     origColumns = T->getColumnExpr();
5662 
5663   ExprResult rowResult = getDerived().TransformExpr(origRows);
5664   rowResult = SemaRef.ActOnConstantExpression(rowResult);
5665   if (rowResult.isInvalid())
5666     return QualType();
5667 
5668   ExprResult columnResult = getDerived().TransformExpr(origColumns);
5669   columnResult = SemaRef.ActOnConstantExpression(columnResult);
5670   if (columnResult.isInvalid())
5671     return QualType();
5672 
5673   Expr *rows = rowResult.get();
5674   Expr *columns = columnResult.get();
5675 
5676   QualType Result = TL.getType();
5677   if (getDerived().AlwaysRebuild() || ElementType != T->getElementType() ||
5678       rows != origRows || columns != origColumns) {
5679     Result = getDerived().RebuildDependentSizedMatrixType(
5680         ElementType, rows, columns, T->getAttributeLoc());
5681 
5682     if (Result.isNull())
5683       return QualType();
5684   }
5685 
5686   // We might have any sort of matrix type now, but fortunately they
5687   // all have the same location layout.
5688   MatrixTypeLoc NewTL = TLB.push<MatrixTypeLoc>(Result);
5689   NewTL.setAttrNameLoc(TL.getAttrNameLoc());
5690   NewTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5691   NewTL.setAttrRowOperand(rows);
5692   NewTL.setAttrColumnOperand(columns);
5693   return Result;
5694 }
5695 
5696 template <typename Derived>
5697 QualType TreeTransform<Derived>::TransformDependentAddressSpaceType(
5698     TypeLocBuilder &TLB, DependentAddressSpaceTypeLoc TL) {
5699   const DependentAddressSpaceType *T = TL.getTypePtr();
5700 
5701   QualType pointeeType = getDerived().TransformType(T->getPointeeType());
5702 
5703   if (pointeeType.isNull())
5704     return QualType();
5705 
5706   // Address spaces are constant expressions.
5707   EnterExpressionEvaluationContext Unevaluated(
5708       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5709 
5710   ExprResult AddrSpace = getDerived().TransformExpr(T->getAddrSpaceExpr());
5711   AddrSpace = SemaRef.ActOnConstantExpression(AddrSpace);
5712   if (AddrSpace.isInvalid())
5713     return QualType();
5714 
5715   QualType Result = TL.getType();
5716   if (getDerived().AlwaysRebuild() || pointeeType != T->getPointeeType() ||
5717       AddrSpace.get() != T->getAddrSpaceExpr()) {
5718     Result = getDerived().RebuildDependentAddressSpaceType(
5719         pointeeType, AddrSpace.get(), T->getAttributeLoc());
5720     if (Result.isNull())
5721       return QualType();
5722   }
5723 
5724   // Result might be dependent or not.
5725   if (isa<DependentAddressSpaceType>(Result)) {
5726     DependentAddressSpaceTypeLoc NewTL =
5727         TLB.push<DependentAddressSpaceTypeLoc>(Result);
5728 
5729     NewTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5730     NewTL.setAttrExprOperand(TL.getAttrExprOperand());
5731     NewTL.setAttrNameLoc(TL.getAttrNameLoc());
5732 
5733   } else {
5734     TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(
5735         Result, getDerived().getBaseLocation());
5736     TransformType(TLB, DI->getTypeLoc());
5737   }
5738 
5739   return Result;
5740 }
5741 
5742 template <typename Derived>
5743 QualType TreeTransform<Derived>::TransformVectorType(TypeLocBuilder &TLB,
5744                                                      VectorTypeLoc TL) {
5745   const VectorType *T = TL.getTypePtr();
5746   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5747   if (ElementType.isNull())
5748     return QualType();
5749 
5750   QualType Result = TL.getType();
5751   if (getDerived().AlwaysRebuild() ||
5752       ElementType != T->getElementType()) {
5753     Result = getDerived().RebuildVectorType(ElementType, T->getNumElements(),
5754                                             T->getVectorKind());
5755     if (Result.isNull())
5756       return QualType();
5757   }
5758 
5759   VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
5760   NewTL.setNameLoc(TL.getNameLoc());
5761 
5762   return Result;
5763 }
5764 
5765 template<typename Derived>
5766 QualType TreeTransform<Derived>::TransformExtVectorType(TypeLocBuilder &TLB,
5767                                                         ExtVectorTypeLoc TL) {
5768   const VectorType *T = TL.getTypePtr();
5769   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5770   if (ElementType.isNull())
5771     return QualType();
5772 
5773   QualType Result = TL.getType();
5774   if (getDerived().AlwaysRebuild() ||
5775       ElementType != T->getElementType()) {
5776     Result = getDerived().RebuildExtVectorType(ElementType,
5777                                                T->getNumElements(),
5778                                                /*FIXME*/ SourceLocation());
5779     if (Result.isNull())
5780       return QualType();
5781   }
5782 
5783   ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
5784   NewTL.setNameLoc(TL.getNameLoc());
5785 
5786   return Result;
5787 }
5788 
5789 template <typename Derived>
5790 ParmVarDecl *TreeTransform<Derived>::TransformFunctionTypeParam(
5791     ParmVarDecl *OldParm, int indexAdjustment,
5792     std::optional<unsigned> NumExpansions, bool ExpectParameterPack) {
5793   TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
5794   TypeSourceInfo *NewDI = nullptr;
5795 
5796   if (NumExpansions && isa<PackExpansionType>(OldDI->getType())) {
5797     // If we're substituting into a pack expansion type and we know the
5798     // length we want to expand to, just substitute for the pattern.
5799     TypeLoc OldTL = OldDI->getTypeLoc();
5800     PackExpansionTypeLoc OldExpansionTL = OldTL.castAs<PackExpansionTypeLoc>();
5801 
5802     TypeLocBuilder TLB;
5803     TypeLoc NewTL = OldDI->getTypeLoc();
5804     TLB.reserve(NewTL.getFullDataSize());
5805 
5806     QualType Result = getDerived().TransformType(TLB,
5807                                                OldExpansionTL.getPatternLoc());
5808     if (Result.isNull())
5809       return nullptr;
5810 
5811     Result = RebuildPackExpansionType(Result,
5812                                 OldExpansionTL.getPatternLoc().getSourceRange(),
5813                                       OldExpansionTL.getEllipsisLoc(),
5814                                       NumExpansions);
5815     if (Result.isNull())
5816       return nullptr;
5817 
5818     PackExpansionTypeLoc NewExpansionTL
5819       = TLB.push<PackExpansionTypeLoc>(Result);
5820     NewExpansionTL.setEllipsisLoc(OldExpansionTL.getEllipsisLoc());
5821     NewDI = TLB.getTypeSourceInfo(SemaRef.Context, Result);
5822   } else
5823     NewDI = getDerived().TransformType(OldDI);
5824   if (!NewDI)
5825     return nullptr;
5826 
5827   if (NewDI == OldDI && indexAdjustment == 0)
5828     return OldParm;
5829 
5830   ParmVarDecl *newParm = ParmVarDecl::Create(SemaRef.Context,
5831                                              OldParm->getDeclContext(),
5832                                              OldParm->getInnerLocStart(),
5833                                              OldParm->getLocation(),
5834                                              OldParm->getIdentifier(),
5835                                              NewDI->getType(),
5836                                              NewDI,
5837                                              OldParm->getStorageClass(),
5838                                              /* DefArg */ nullptr);
5839   newParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
5840                         OldParm->getFunctionScopeIndex() + indexAdjustment);
5841   transformedLocalDecl(OldParm, {newParm});
5842   return newParm;
5843 }
5844 
5845 template <typename Derived>
5846 bool TreeTransform<Derived>::TransformFunctionTypeParams(
5847     SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
5848     const QualType *ParamTypes,
5849     const FunctionProtoType::ExtParameterInfo *ParamInfos,
5850     SmallVectorImpl<QualType> &OutParamTypes,
5851     SmallVectorImpl<ParmVarDecl *> *PVars,
5852     Sema::ExtParameterInfoBuilder &PInfos,
5853     unsigned *LastParamTransformed) {
5854   int indexAdjustment = 0;
5855 
5856   unsigned NumParams = Params.size();
5857   for (unsigned i = 0; i != NumParams; ++i) {
5858     if (LastParamTransformed)
5859       *LastParamTransformed = i;
5860     if (ParmVarDecl *OldParm = Params[i]) {
5861       assert(OldParm->getFunctionScopeIndex() == i);
5862 
5863       std::optional<unsigned> NumExpansions;
5864       ParmVarDecl *NewParm = nullptr;
5865       if (OldParm->isParameterPack()) {
5866         // We have a function parameter pack that may need to be expanded.
5867         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5868 
5869         // Find the parameter packs that could be expanded.
5870         TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc();
5871         PackExpansionTypeLoc ExpansionTL = TL.castAs<PackExpansionTypeLoc>();
5872         TypeLoc Pattern = ExpansionTL.getPatternLoc();
5873         SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
5874 
5875         // Determine whether we should expand the parameter packs.
5876         bool ShouldExpand = false;
5877         bool RetainExpansion = false;
5878         std::optional<unsigned> OrigNumExpansions;
5879         if (Unexpanded.size() > 0) {
5880           OrigNumExpansions = ExpansionTL.getTypePtr()->getNumExpansions();
5881           NumExpansions = OrigNumExpansions;
5882           if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
5883                                                    Pattern.getSourceRange(),
5884                                                    Unexpanded,
5885                                                    ShouldExpand,
5886                                                    RetainExpansion,
5887                                                    NumExpansions)) {
5888             return true;
5889           }
5890         } else {
5891 #ifndef NDEBUG
5892           const AutoType *AT =
5893               Pattern.getType().getTypePtr()->getContainedAutoType();
5894           assert((AT && (!AT->isDeduced() || AT->getDeducedType().isNull())) &&
5895                  "Could not find parameter packs or undeduced auto type!");
5896 #endif
5897         }
5898 
5899         if (ShouldExpand) {
5900           // Expand the function parameter pack into multiple, separate
5901           // parameters.
5902           getDerived().ExpandingFunctionParameterPack(OldParm);
5903           for (unsigned I = 0; I != *NumExpansions; ++I) {
5904             Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
5905             ParmVarDecl *NewParm
5906               = getDerived().TransformFunctionTypeParam(OldParm,
5907                                                         indexAdjustment++,
5908                                                         OrigNumExpansions,
5909                                                 /*ExpectParameterPack=*/false);
5910             if (!NewParm)
5911               return true;
5912 
5913             if (ParamInfos)
5914               PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5915             OutParamTypes.push_back(NewParm->getType());
5916             if (PVars)
5917               PVars->push_back(NewParm);
5918           }
5919 
5920           // If we're supposed to retain a pack expansion, do so by temporarily
5921           // forgetting the partially-substituted parameter pack.
5922           if (RetainExpansion) {
5923             ForgetPartiallySubstitutedPackRAII Forget(getDerived());
5924             ParmVarDecl *NewParm
5925               = getDerived().TransformFunctionTypeParam(OldParm,
5926                                                         indexAdjustment++,
5927                                                         OrigNumExpansions,
5928                                                 /*ExpectParameterPack=*/false);
5929             if (!NewParm)
5930               return true;
5931 
5932             if (ParamInfos)
5933               PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5934             OutParamTypes.push_back(NewParm->getType());
5935             if (PVars)
5936               PVars->push_back(NewParm);
5937           }
5938 
5939           // The next parameter should have the same adjustment as the
5940           // last thing we pushed, but we post-incremented indexAdjustment
5941           // on every push.  Also, if we push nothing, the adjustment should
5942           // go down by one.
5943           indexAdjustment--;
5944 
5945           // We're done with the pack expansion.
5946           continue;
5947         }
5948 
5949         // We'll substitute the parameter now without expanding the pack
5950         // expansion.
5951         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5952         NewParm = getDerived().TransformFunctionTypeParam(OldParm,
5953                                                           indexAdjustment,
5954                                                           NumExpansions,
5955                                                   /*ExpectParameterPack=*/true);
5956         assert(NewParm->isParameterPack() &&
5957                "Parameter pack no longer a parameter pack after "
5958                "transformation.");
5959       } else {
5960         NewParm = getDerived().TransformFunctionTypeParam(
5961             OldParm, indexAdjustment, std::nullopt,
5962             /*ExpectParameterPack=*/false);
5963       }
5964 
5965       if (!NewParm)
5966         return true;
5967 
5968       if (ParamInfos)
5969         PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5970       OutParamTypes.push_back(NewParm->getType());
5971       if (PVars)
5972         PVars->push_back(NewParm);
5973       continue;
5974     }
5975 
5976     // Deal with the possibility that we don't have a parameter
5977     // declaration for this parameter.
5978     assert(ParamTypes);
5979     QualType OldType = ParamTypes[i];
5980     bool IsPackExpansion = false;
5981     std::optional<unsigned> NumExpansions;
5982     QualType NewType;
5983     if (const PackExpansionType *Expansion
5984                                        = dyn_cast<PackExpansionType>(OldType)) {
5985       // We have a function parameter pack that may need to be expanded.
5986       QualType Pattern = Expansion->getPattern();
5987       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5988       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
5989 
5990       // Determine whether we should expand the parameter packs.
5991       bool ShouldExpand = false;
5992       bool RetainExpansion = false;
5993       if (getDerived().TryExpandParameterPacks(Loc, SourceRange(),
5994                                                Unexpanded,
5995                                                ShouldExpand,
5996                                                RetainExpansion,
5997                                                NumExpansions)) {
5998         return true;
5999       }
6000 
6001       if (ShouldExpand) {
6002         // Expand the function parameter pack into multiple, separate
6003         // parameters.
6004         for (unsigned I = 0; I != *NumExpansions; ++I) {
6005           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
6006           QualType NewType = getDerived().TransformType(Pattern);
6007           if (NewType.isNull())
6008             return true;
6009 
6010           if (NewType->containsUnexpandedParameterPack()) {
6011             NewType = getSema().getASTContext().getPackExpansionType(
6012                 NewType, std::nullopt);
6013 
6014             if (NewType.isNull())
6015               return true;
6016           }
6017 
6018           if (ParamInfos)
6019             PInfos.set(OutParamTypes.size(), ParamInfos[i]);
6020           OutParamTypes.push_back(NewType);
6021           if (PVars)
6022             PVars->push_back(nullptr);
6023         }
6024 
6025         // We're done with the pack expansion.
6026         continue;
6027       }
6028 
6029       // If we're supposed to retain a pack expansion, do so by temporarily
6030       // forgetting the partially-substituted parameter pack.
6031       if (RetainExpansion) {
6032         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
6033         QualType NewType = getDerived().TransformType(Pattern);
6034         if (NewType.isNull())
6035           return true;
6036 
6037         if (ParamInfos)
6038           PInfos.set(OutParamTypes.size(), ParamInfos[i]);
6039         OutParamTypes.push_back(NewType);
6040         if (PVars)
6041           PVars->push_back(nullptr);
6042       }
6043 
6044       // We'll substitute the parameter now without expanding the pack
6045       // expansion.
6046       OldType = Expansion->getPattern();
6047       IsPackExpansion = true;
6048       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
6049       NewType = getDerived().TransformType(OldType);
6050     } else {
6051       NewType = getDerived().TransformType(OldType);
6052     }
6053 
6054     if (NewType.isNull())
6055       return true;
6056 
6057     if (IsPackExpansion)
6058       NewType = getSema().Context.getPackExpansionType(NewType,
6059                                                        NumExpansions);
6060 
6061     if (ParamInfos)
6062       PInfos.set(OutParamTypes.size(), ParamInfos[i]);
6063     OutParamTypes.push_back(NewType);
6064     if (PVars)
6065       PVars->push_back(nullptr);
6066   }
6067 
6068 #ifndef NDEBUG
6069   if (PVars) {
6070     for (unsigned i = 0, e = PVars->size(); i != e; ++i)
6071       if (ParmVarDecl *parm = (*PVars)[i])
6072         assert(parm->getFunctionScopeIndex() == i);
6073   }
6074 #endif
6075 
6076   return false;
6077 }
6078 
6079 template<typename Derived>
6080 QualType
6081 TreeTransform<Derived>::TransformFunctionProtoType(TypeLocBuilder &TLB,
6082                                                    FunctionProtoTypeLoc TL) {
6083   SmallVector<QualType, 4> ExceptionStorage;
6084   TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
6085   return getDerived().TransformFunctionProtoType(
6086       TLB, TL, nullptr, Qualifiers(),
6087       [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
6088         return This->getDerived().TransformExceptionSpec(
6089             TL.getBeginLoc(), ESI, ExceptionStorage, Changed);
6090       });
6091 }
6092 
6093 template<typename Derived> template<typename Fn>
6094 QualType TreeTransform<Derived>::TransformFunctionProtoType(
6095     TypeLocBuilder &TLB, FunctionProtoTypeLoc TL, CXXRecordDecl *ThisContext,
6096     Qualifiers ThisTypeQuals, Fn TransformExceptionSpec) {
6097 
6098   // Transform the parameters and return type.
6099   //
6100   // We are required to instantiate the params and return type in source order.
6101   // When the function has a trailing return type, we instantiate the
6102   // parameters before the return type,  since the return type can then refer
6103   // to the parameters themselves (via decltype, sizeof, etc.).
6104   //
6105   SmallVector<QualType, 4> ParamTypes;
6106   SmallVector<ParmVarDecl*, 4> ParamDecls;
6107   Sema::ExtParameterInfoBuilder ExtParamInfos;
6108   const FunctionProtoType *T = TL.getTypePtr();
6109 
6110   QualType ResultType;
6111 
6112   if (T->hasTrailingReturn()) {
6113     if (getDerived().TransformFunctionTypeParams(
6114             TL.getBeginLoc(), TL.getParams(),
6115             TL.getTypePtr()->param_type_begin(),
6116             T->getExtParameterInfosOrNull(),
6117             ParamTypes, &ParamDecls, ExtParamInfos))
6118       return QualType();
6119 
6120     {
6121       // C++11 [expr.prim.general]p3:
6122       //   If a declaration declares a member function or member function
6123       //   template of a class X, the expression this is a prvalue of type
6124       //   "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
6125       //   and the end of the function-definition, member-declarator, or
6126       //   declarator.
6127       Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals);
6128 
6129       ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
6130       if (ResultType.isNull())
6131         return QualType();
6132     }
6133   }
6134   else {
6135     ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
6136     if (ResultType.isNull())
6137       return QualType();
6138 
6139     if (getDerived().TransformFunctionTypeParams(
6140             TL.getBeginLoc(), TL.getParams(),
6141             TL.getTypePtr()->param_type_begin(),
6142             T->getExtParameterInfosOrNull(),
6143             ParamTypes, &ParamDecls, ExtParamInfos))
6144       return QualType();
6145   }
6146 
6147   FunctionProtoType::ExtProtoInfo EPI = T->getExtProtoInfo();
6148 
6149   bool EPIChanged = false;
6150   if (TransformExceptionSpec(EPI.ExceptionSpec, EPIChanged))
6151     return QualType();
6152 
6153   // Handle extended parameter information.
6154   if (auto NewExtParamInfos =
6155         ExtParamInfos.getPointerOrNull(ParamTypes.size())) {
6156     if (!EPI.ExtParameterInfos ||
6157         llvm::ArrayRef(EPI.ExtParameterInfos, TL.getNumParams()) !=
6158             llvm::ArrayRef(NewExtParamInfos, ParamTypes.size())) {
6159       EPIChanged = true;
6160     }
6161     EPI.ExtParameterInfos = NewExtParamInfos;
6162   } else if (EPI.ExtParameterInfos) {
6163     EPIChanged = true;
6164     EPI.ExtParameterInfos = nullptr;
6165   }
6166 
6167   QualType Result = TL.getType();
6168   if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType() ||
6169       T->getParamTypes() != llvm::ArrayRef(ParamTypes) || EPIChanged) {
6170     Result = getDerived().RebuildFunctionProtoType(ResultType, ParamTypes, EPI);
6171     if (Result.isNull())
6172       return QualType();
6173   }
6174 
6175   FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
6176   NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
6177   NewTL.setLParenLoc(TL.getLParenLoc());
6178   NewTL.setRParenLoc(TL.getRParenLoc());
6179   NewTL.setExceptionSpecRange(TL.getExceptionSpecRange());
6180   NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
6181   for (unsigned i = 0, e = NewTL.getNumParams(); i != e; ++i)
6182     NewTL.setParam(i, ParamDecls[i]);
6183 
6184   return Result;
6185 }
6186 
6187 template<typename Derived>
6188 bool TreeTransform<Derived>::TransformExceptionSpec(
6189     SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI,
6190     SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
6191   assert(ESI.Type != EST_Uninstantiated && ESI.Type != EST_Unevaluated);
6192 
6193   // Instantiate a dynamic noexcept expression, if any.
6194   if (isComputedNoexcept(ESI.Type)) {
6195     EnterExpressionEvaluationContext Unevaluated(
6196         getSema(), Sema::ExpressionEvaluationContext::ConstantEvaluated);
6197     ExprResult NoexceptExpr = getDerived().TransformExpr(ESI.NoexceptExpr);
6198     if (NoexceptExpr.isInvalid())
6199       return true;
6200 
6201     ExceptionSpecificationType EST = ESI.Type;
6202     NoexceptExpr =
6203         getSema().ActOnNoexceptSpec(NoexceptExpr.get(), EST);
6204     if (NoexceptExpr.isInvalid())
6205       return true;
6206 
6207     if (ESI.NoexceptExpr != NoexceptExpr.get() || EST != ESI.Type)
6208       Changed = true;
6209     ESI.NoexceptExpr = NoexceptExpr.get();
6210     ESI.Type = EST;
6211   }
6212 
6213   if (ESI.Type != EST_Dynamic)
6214     return false;
6215 
6216   // Instantiate a dynamic exception specification's type.
6217   for (QualType T : ESI.Exceptions) {
6218     if (const PackExpansionType *PackExpansion =
6219             T->getAs<PackExpansionType>()) {
6220       Changed = true;
6221 
6222       // We have a pack expansion. Instantiate it.
6223       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
6224       SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
6225                                               Unexpanded);
6226       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
6227 
6228       // Determine whether the set of unexpanded parameter packs can and
6229       // should
6230       // be expanded.
6231       bool Expand = false;
6232       bool RetainExpansion = false;
6233       std::optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
6234       // FIXME: Track the location of the ellipsis (and track source location
6235       // information for the types in the exception specification in general).
6236       if (getDerived().TryExpandParameterPacks(
6237               Loc, SourceRange(), Unexpanded, Expand,
6238               RetainExpansion, NumExpansions))
6239         return true;
6240 
6241       if (!Expand) {
6242         // We can't expand this pack expansion into separate arguments yet;
6243         // just substitute into the pattern and create a new pack expansion
6244         // type.
6245         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
6246         QualType U = getDerived().TransformType(PackExpansion->getPattern());
6247         if (U.isNull())
6248           return true;
6249 
6250         U = SemaRef.Context.getPackExpansionType(U, NumExpansions);
6251         Exceptions.push_back(U);
6252         continue;
6253       }
6254 
6255       // Substitute into the pack expansion pattern for each slice of the
6256       // pack.
6257       for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
6258         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
6259 
6260         QualType U = getDerived().TransformType(PackExpansion->getPattern());
6261         if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
6262           return true;
6263 
6264         Exceptions.push_back(U);
6265       }
6266     } else {
6267       QualType U = getDerived().TransformType(T);
6268       if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
6269         return true;
6270       if (T != U)
6271         Changed = true;
6272 
6273       Exceptions.push_back(U);
6274     }
6275   }
6276 
6277   ESI.Exceptions = Exceptions;
6278   if (ESI.Exceptions.empty())
6279     ESI.Type = EST_DynamicNone;
6280   return false;
6281 }
6282 
6283 template<typename Derived>
6284 QualType TreeTransform<Derived>::TransformFunctionNoProtoType(
6285                                                  TypeLocBuilder &TLB,
6286                                                  FunctionNoProtoTypeLoc TL) {
6287   const FunctionNoProtoType *T = TL.getTypePtr();
6288   QualType ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
6289   if (ResultType.isNull())
6290     return QualType();
6291 
6292   QualType Result = TL.getType();
6293   if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType())
6294     Result = getDerived().RebuildFunctionNoProtoType(ResultType);
6295 
6296   FunctionNoProtoTypeLoc NewTL = TLB.push<FunctionNoProtoTypeLoc>(Result);
6297   NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
6298   NewTL.setLParenLoc(TL.getLParenLoc());
6299   NewTL.setRParenLoc(TL.getRParenLoc());
6300   NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
6301 
6302   return Result;
6303 }
6304 
6305 template <typename Derived>
6306 QualType TreeTransform<Derived>::TransformUnresolvedUsingType(
6307     TypeLocBuilder &TLB, UnresolvedUsingTypeLoc TL) {
6308   const UnresolvedUsingType *T = TL.getTypePtr();
6309   Decl *D = getDerived().TransformDecl(TL.getNameLoc(), T->getDecl());
6310   if (!D)
6311     return QualType();
6312 
6313   QualType Result = TL.getType();
6314   if (getDerived().AlwaysRebuild() || D != T->getDecl()) {
6315     Result = getDerived().RebuildUnresolvedUsingType(TL.getNameLoc(), D);
6316     if (Result.isNull())
6317       return QualType();
6318   }
6319 
6320   // We might get an arbitrary type spec type back.  We should at
6321   // least always get a type spec type, though.
6322   TypeSpecTypeLoc NewTL = TLB.pushTypeSpec(Result);
6323   NewTL.setNameLoc(TL.getNameLoc());
6324 
6325   return Result;
6326 }
6327 
6328 template <typename Derived>
6329 QualType TreeTransform<Derived>::TransformUsingType(TypeLocBuilder &TLB,
6330                                                     UsingTypeLoc TL) {
6331   const UsingType *T = TL.getTypePtr();
6332 
6333   auto *Found = cast_or_null<UsingShadowDecl>(getDerived().TransformDecl(
6334       TL.getLocalSourceRange().getBegin(), T->getFoundDecl()));
6335   if (!Found)
6336     return QualType();
6337 
6338   QualType Underlying = getDerived().TransformType(T->desugar());
6339   if (Underlying.isNull())
6340     return QualType();
6341 
6342   QualType Result = TL.getType();
6343   if (getDerived().AlwaysRebuild() || Found != T->getFoundDecl() ||
6344       Underlying != T->getUnderlyingType()) {
6345     Result = getDerived().RebuildUsingType(Found, Underlying);
6346     if (Result.isNull())
6347       return QualType();
6348   }
6349 
6350   TLB.pushTypeSpec(Result).setNameLoc(TL.getNameLoc());
6351   return Result;
6352 }
6353 
6354 template<typename Derived>
6355 QualType TreeTransform<Derived>::TransformTypedefType(TypeLocBuilder &TLB,
6356                                                       TypedefTypeLoc TL) {
6357   const TypedefType *T = TL.getTypePtr();
6358   TypedefNameDecl *Typedef
6359     = cast_or_null<TypedefNameDecl>(getDerived().TransformDecl(TL.getNameLoc(),
6360                                                                T->getDecl()));
6361   if (!Typedef)
6362     return QualType();
6363 
6364   QualType Result = TL.getType();
6365   if (getDerived().AlwaysRebuild() ||
6366       Typedef != T->getDecl()) {
6367     Result = getDerived().RebuildTypedefType(Typedef);
6368     if (Result.isNull())
6369       return QualType();
6370   }
6371 
6372   TypedefTypeLoc NewTL = TLB.push<TypedefTypeLoc>(Result);
6373   NewTL.setNameLoc(TL.getNameLoc());
6374 
6375   return Result;
6376 }
6377 
6378 template<typename Derived>
6379 QualType TreeTransform<Derived>::TransformTypeOfExprType(TypeLocBuilder &TLB,
6380                                                       TypeOfExprTypeLoc TL) {
6381   // typeof expressions are not potentially evaluated contexts
6382   EnterExpressionEvaluationContext Unevaluated(
6383       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
6384       Sema::ReuseLambdaContextDecl);
6385 
6386   ExprResult E = getDerived().TransformExpr(TL.getUnderlyingExpr());
6387   if (E.isInvalid())
6388     return QualType();
6389 
6390   E = SemaRef.HandleExprEvaluationContextForTypeof(E.get());
6391   if (E.isInvalid())
6392     return QualType();
6393 
6394   QualType Result = TL.getType();
6395   TypeOfKind Kind = Result->getAs<TypeOfExprType>()->getKind();
6396   if (getDerived().AlwaysRebuild() || E.get() != TL.getUnderlyingExpr()) {
6397     Result =
6398         getDerived().RebuildTypeOfExprType(E.get(), TL.getTypeofLoc(), Kind);
6399     if (Result.isNull())
6400       return QualType();
6401   }
6402 
6403   TypeOfExprTypeLoc NewTL = TLB.push<TypeOfExprTypeLoc>(Result);
6404   NewTL.setTypeofLoc(TL.getTypeofLoc());
6405   NewTL.setLParenLoc(TL.getLParenLoc());
6406   NewTL.setRParenLoc(TL.getRParenLoc());
6407 
6408   return Result;
6409 }
6410 
6411 template<typename Derived>
6412 QualType TreeTransform<Derived>::TransformTypeOfType(TypeLocBuilder &TLB,
6413                                                      TypeOfTypeLoc TL) {
6414   TypeSourceInfo* Old_Under_TI = TL.getUnmodifiedTInfo();
6415   TypeSourceInfo* New_Under_TI = getDerived().TransformType(Old_Under_TI);
6416   if (!New_Under_TI)
6417     return QualType();
6418 
6419   QualType Result = TL.getType();
6420   TypeOfKind Kind = Result->getAs<TypeOfType>()->getKind();
6421   if (getDerived().AlwaysRebuild() || New_Under_TI != Old_Under_TI) {
6422     Result = getDerived().RebuildTypeOfType(New_Under_TI->getType(), Kind);
6423     if (Result.isNull())
6424       return QualType();
6425   }
6426 
6427   TypeOfTypeLoc NewTL = TLB.push<TypeOfTypeLoc>(Result);
6428   NewTL.setTypeofLoc(TL.getTypeofLoc());
6429   NewTL.setLParenLoc(TL.getLParenLoc());
6430   NewTL.setRParenLoc(TL.getRParenLoc());
6431   NewTL.setUnmodifiedTInfo(New_Under_TI);
6432 
6433   return Result;
6434 }
6435 
6436 template<typename Derived>
6437 QualType TreeTransform<Derived>::TransformDecltypeType(TypeLocBuilder &TLB,
6438                                                        DecltypeTypeLoc TL) {
6439   const DecltypeType *T = TL.getTypePtr();
6440 
6441   // decltype expressions are not potentially evaluated contexts
6442   EnterExpressionEvaluationContext Unevaluated(
6443       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated, nullptr,
6444       Sema::ExpressionEvaluationContextRecord::EK_Decltype);
6445 
6446   ExprResult E = getDerived().TransformExpr(T->getUnderlyingExpr());
6447   if (E.isInvalid())
6448     return QualType();
6449 
6450   E = getSema().ActOnDecltypeExpression(E.get());
6451   if (E.isInvalid())
6452     return QualType();
6453 
6454   QualType Result = TL.getType();
6455   if (getDerived().AlwaysRebuild() ||
6456       E.get() != T->getUnderlyingExpr()) {
6457     Result = getDerived().RebuildDecltypeType(E.get(), TL.getDecltypeLoc());
6458     if (Result.isNull())
6459       return QualType();
6460   }
6461   else E.get();
6462 
6463   DecltypeTypeLoc NewTL = TLB.push<DecltypeTypeLoc>(Result);
6464   NewTL.setDecltypeLoc(TL.getDecltypeLoc());
6465   NewTL.setRParenLoc(TL.getRParenLoc());
6466   return Result;
6467 }
6468 
6469 template<typename Derived>
6470 QualType TreeTransform<Derived>::TransformUnaryTransformType(
6471                                                             TypeLocBuilder &TLB,
6472                                                      UnaryTransformTypeLoc TL) {
6473   QualType Result = TL.getType();
6474   if (Result->isDependentType()) {
6475     const UnaryTransformType *T = TL.getTypePtr();
6476     QualType NewBase =
6477       getDerived().TransformType(TL.getUnderlyingTInfo())->getType();
6478     Result = getDerived().RebuildUnaryTransformType(NewBase,
6479                                                     T->getUTTKind(),
6480                                                     TL.getKWLoc());
6481     if (Result.isNull())
6482       return QualType();
6483   }
6484 
6485   UnaryTransformTypeLoc NewTL = TLB.push<UnaryTransformTypeLoc>(Result);
6486   NewTL.setKWLoc(TL.getKWLoc());
6487   NewTL.setParensRange(TL.getParensRange());
6488   NewTL.setUnderlyingTInfo(TL.getUnderlyingTInfo());
6489   return Result;
6490 }
6491 
6492 template<typename Derived>
6493 QualType TreeTransform<Derived>::TransformDeducedTemplateSpecializationType(
6494     TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) {
6495   const DeducedTemplateSpecializationType *T = TL.getTypePtr();
6496 
6497   CXXScopeSpec SS;
6498   TemplateName TemplateName = getDerived().TransformTemplateName(
6499       SS, T->getTemplateName(), TL.getTemplateNameLoc());
6500   if (TemplateName.isNull())
6501     return QualType();
6502 
6503   QualType OldDeduced = T->getDeducedType();
6504   QualType NewDeduced;
6505   if (!OldDeduced.isNull()) {
6506     NewDeduced = getDerived().TransformType(OldDeduced);
6507     if (NewDeduced.isNull())
6508       return QualType();
6509   }
6510 
6511   QualType Result = getDerived().RebuildDeducedTemplateSpecializationType(
6512       TemplateName, NewDeduced);
6513   if (Result.isNull())
6514     return QualType();
6515 
6516   DeducedTemplateSpecializationTypeLoc NewTL =
6517       TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
6518   NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6519 
6520   return Result;
6521 }
6522 
6523 template<typename Derived>
6524 QualType TreeTransform<Derived>::TransformRecordType(TypeLocBuilder &TLB,
6525                                                      RecordTypeLoc TL) {
6526   const RecordType *T = TL.getTypePtr();
6527   RecordDecl *Record
6528     = cast_or_null<RecordDecl>(getDerived().TransformDecl(TL.getNameLoc(),
6529                                                           T->getDecl()));
6530   if (!Record)
6531     return QualType();
6532 
6533   QualType Result = TL.getType();
6534   if (getDerived().AlwaysRebuild() ||
6535       Record != T->getDecl()) {
6536     Result = getDerived().RebuildRecordType(Record);
6537     if (Result.isNull())
6538       return QualType();
6539   }
6540 
6541   RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
6542   NewTL.setNameLoc(TL.getNameLoc());
6543 
6544   return Result;
6545 }
6546 
6547 template<typename Derived>
6548 QualType TreeTransform<Derived>::TransformEnumType(TypeLocBuilder &TLB,
6549                                                    EnumTypeLoc TL) {
6550   const EnumType *T = TL.getTypePtr();
6551   EnumDecl *Enum
6552     = cast_or_null<EnumDecl>(getDerived().TransformDecl(TL.getNameLoc(),
6553                                                         T->getDecl()));
6554   if (!Enum)
6555     return QualType();
6556 
6557   QualType Result = TL.getType();
6558   if (getDerived().AlwaysRebuild() ||
6559       Enum != T->getDecl()) {
6560     Result = getDerived().RebuildEnumType(Enum);
6561     if (Result.isNull())
6562       return QualType();
6563   }
6564 
6565   EnumTypeLoc NewTL = TLB.push<EnumTypeLoc>(Result);
6566   NewTL.setNameLoc(TL.getNameLoc());
6567 
6568   return Result;
6569 }
6570 
6571 template<typename Derived>
6572 QualType TreeTransform<Derived>::TransformInjectedClassNameType(
6573                                          TypeLocBuilder &TLB,
6574                                          InjectedClassNameTypeLoc TL) {
6575   Decl *D = getDerived().TransformDecl(TL.getNameLoc(),
6576                                        TL.getTypePtr()->getDecl());
6577   if (!D) return QualType();
6578 
6579   QualType T = SemaRef.Context.getTypeDeclType(cast<TypeDecl>(D));
6580   TLB.pushTypeSpec(T).setNameLoc(TL.getNameLoc());
6581   return T;
6582 }
6583 
6584 template<typename Derived>
6585 QualType TreeTransform<Derived>::TransformTemplateTypeParmType(
6586                                                 TypeLocBuilder &TLB,
6587                                                 TemplateTypeParmTypeLoc TL) {
6588   return getDerived().TransformTemplateTypeParmType(
6589       TLB, TL,
6590       /*SuppressObjCLifetime=*/false);
6591 }
6592 
6593 template <typename Derived>
6594 QualType TreeTransform<Derived>::TransformTemplateTypeParmType(
6595     TypeLocBuilder &TLB, TemplateTypeParmTypeLoc TL, bool) {
6596   return TransformTypeSpecType(TLB, TL);
6597 }
6598 
6599 template<typename Derived>
6600 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmType(
6601                                          TypeLocBuilder &TLB,
6602                                          SubstTemplateTypeParmTypeLoc TL) {
6603   const SubstTemplateTypeParmType *T = TL.getTypePtr();
6604 
6605   Decl *NewReplaced =
6606       getDerived().TransformDecl(TL.getNameLoc(), T->getAssociatedDecl());
6607 
6608   // Substitute into the replacement type, which itself might involve something
6609   // that needs to be transformed. This only tends to occur with default
6610   // template arguments of template template parameters.
6611   TemporaryBase Rebase(*this, TL.getNameLoc(), DeclarationName());
6612   QualType Replacement = getDerived().TransformType(T->getReplacementType());
6613   if (Replacement.isNull())
6614     return QualType();
6615 
6616   QualType Result = SemaRef.Context.getSubstTemplateTypeParmType(
6617       Replacement, NewReplaced, T->getIndex(), T->getPackIndex());
6618 
6619   // Propagate type-source information.
6620   SubstTemplateTypeParmTypeLoc NewTL
6621     = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
6622   NewTL.setNameLoc(TL.getNameLoc());
6623   return Result;
6624 
6625 }
6626 
6627 template<typename Derived>
6628 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmPackType(
6629                                           TypeLocBuilder &TLB,
6630                                           SubstTemplateTypeParmPackTypeLoc TL) {
6631   return getDerived().TransformSubstTemplateTypeParmPackType(
6632       TLB, TL, /*SuppressObjCLifetime=*/false);
6633 }
6634 
6635 template <typename Derived>
6636 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmPackType(
6637     TypeLocBuilder &TLB, SubstTemplateTypeParmPackTypeLoc TL, bool) {
6638   return TransformTypeSpecType(TLB, TL);
6639 }
6640 
6641 template<typename Derived>
6642 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
6643                                                         TypeLocBuilder &TLB,
6644                                            TemplateSpecializationTypeLoc TL) {
6645   const TemplateSpecializationType *T = TL.getTypePtr();
6646 
6647   // The nested-name-specifier never matters in a TemplateSpecializationType,
6648   // because we can't have a dependent nested-name-specifier anyway.
6649   CXXScopeSpec SS;
6650   TemplateName Template
6651     = getDerived().TransformTemplateName(SS, T->getTemplateName(),
6652                                          TL.getTemplateNameLoc());
6653   if (Template.isNull())
6654     return QualType();
6655 
6656   return getDerived().TransformTemplateSpecializationType(TLB, TL, Template);
6657 }
6658 
6659 template<typename Derived>
6660 QualType TreeTransform<Derived>::TransformAtomicType(TypeLocBuilder &TLB,
6661                                                      AtomicTypeLoc TL) {
6662   QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
6663   if (ValueType.isNull())
6664     return QualType();
6665 
6666   QualType Result = TL.getType();
6667   if (getDerived().AlwaysRebuild() ||
6668       ValueType != TL.getValueLoc().getType()) {
6669     Result = getDerived().RebuildAtomicType(ValueType, TL.getKWLoc());
6670     if (Result.isNull())
6671       return QualType();
6672   }
6673 
6674   AtomicTypeLoc NewTL = TLB.push<AtomicTypeLoc>(Result);
6675   NewTL.setKWLoc(TL.getKWLoc());
6676   NewTL.setLParenLoc(TL.getLParenLoc());
6677   NewTL.setRParenLoc(TL.getRParenLoc());
6678 
6679   return Result;
6680 }
6681 
6682 template <typename Derived>
6683 QualType TreeTransform<Derived>::TransformPipeType(TypeLocBuilder &TLB,
6684                                                    PipeTypeLoc TL) {
6685   QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
6686   if (ValueType.isNull())
6687     return QualType();
6688 
6689   QualType Result = TL.getType();
6690   if (getDerived().AlwaysRebuild() || ValueType != TL.getValueLoc().getType()) {
6691     const PipeType *PT = Result->castAs<PipeType>();
6692     bool isReadPipe = PT->isReadOnly();
6693     Result = getDerived().RebuildPipeType(ValueType, TL.getKWLoc(), isReadPipe);
6694     if (Result.isNull())
6695       return QualType();
6696   }
6697 
6698   PipeTypeLoc NewTL = TLB.push<PipeTypeLoc>(Result);
6699   NewTL.setKWLoc(TL.getKWLoc());
6700 
6701   return Result;
6702 }
6703 
6704 template <typename Derived>
6705 QualType TreeTransform<Derived>::TransformBitIntType(TypeLocBuilder &TLB,
6706                                                      BitIntTypeLoc TL) {
6707   const BitIntType *EIT = TL.getTypePtr();
6708   QualType Result = TL.getType();
6709 
6710   if (getDerived().AlwaysRebuild()) {
6711     Result = getDerived().RebuildBitIntType(EIT->isUnsigned(),
6712                                             EIT->getNumBits(), TL.getNameLoc());
6713     if (Result.isNull())
6714       return QualType();
6715   }
6716 
6717   BitIntTypeLoc NewTL = TLB.push<BitIntTypeLoc>(Result);
6718   NewTL.setNameLoc(TL.getNameLoc());
6719   return Result;
6720 }
6721 
6722 template <typename Derived>
6723 QualType TreeTransform<Derived>::TransformDependentBitIntType(
6724     TypeLocBuilder &TLB, DependentBitIntTypeLoc TL) {
6725   const DependentBitIntType *EIT = TL.getTypePtr();
6726 
6727   EnterExpressionEvaluationContext Unevaluated(
6728       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
6729   ExprResult BitsExpr = getDerived().TransformExpr(EIT->getNumBitsExpr());
6730   BitsExpr = SemaRef.ActOnConstantExpression(BitsExpr);
6731 
6732   if (BitsExpr.isInvalid())
6733     return QualType();
6734 
6735   QualType Result = TL.getType();
6736 
6737   if (getDerived().AlwaysRebuild() || BitsExpr.get() != EIT->getNumBitsExpr()) {
6738     Result = getDerived().RebuildDependentBitIntType(
6739         EIT->isUnsigned(), BitsExpr.get(), TL.getNameLoc());
6740 
6741     if (Result.isNull())
6742       return QualType();
6743   }
6744 
6745   if (isa<DependentBitIntType>(Result)) {
6746     DependentBitIntTypeLoc NewTL = TLB.push<DependentBitIntTypeLoc>(Result);
6747     NewTL.setNameLoc(TL.getNameLoc());
6748   } else {
6749     BitIntTypeLoc NewTL = TLB.push<BitIntTypeLoc>(Result);
6750     NewTL.setNameLoc(TL.getNameLoc());
6751   }
6752   return Result;
6753 }
6754 
6755   /// Simple iterator that traverses the template arguments in a
6756   /// container that provides a \c getArgLoc() member function.
6757   ///
6758   /// This iterator is intended to be used with the iterator form of
6759   /// \c TreeTransform<Derived>::TransformTemplateArguments().
6760   template<typename ArgLocContainer>
6761   class TemplateArgumentLocContainerIterator {
6762     ArgLocContainer *Container;
6763     unsigned Index;
6764 
6765   public:
6766     typedef TemplateArgumentLoc value_type;
6767     typedef TemplateArgumentLoc reference;
6768     typedef int difference_type;
6769     typedef std::input_iterator_tag iterator_category;
6770 
6771     class pointer {
6772       TemplateArgumentLoc Arg;
6773 
6774     public:
6775       explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
6776 
6777       const TemplateArgumentLoc *operator->() const {
6778         return &Arg;
6779       }
6780     };
6781 
6782 
6783     TemplateArgumentLocContainerIterator() {}
6784 
6785     TemplateArgumentLocContainerIterator(ArgLocContainer &Container,
6786                                  unsigned Index)
6787       : Container(&Container), Index(Index) { }
6788 
6789     TemplateArgumentLocContainerIterator &operator++() {
6790       ++Index;
6791       return *this;
6792     }
6793 
6794     TemplateArgumentLocContainerIterator operator++(int) {
6795       TemplateArgumentLocContainerIterator Old(*this);
6796       ++(*this);
6797       return Old;
6798     }
6799 
6800     TemplateArgumentLoc operator*() const {
6801       return Container->getArgLoc(Index);
6802     }
6803 
6804     pointer operator->() const {
6805       return pointer(Container->getArgLoc(Index));
6806     }
6807 
6808     friend bool operator==(const TemplateArgumentLocContainerIterator &X,
6809                            const TemplateArgumentLocContainerIterator &Y) {
6810       return X.Container == Y.Container && X.Index == Y.Index;
6811     }
6812 
6813     friend bool operator!=(const TemplateArgumentLocContainerIterator &X,
6814                            const TemplateArgumentLocContainerIterator &Y) {
6815       return !(X == Y);
6816     }
6817   };
6818 
6819 template<typename Derived>
6820 QualType TreeTransform<Derived>::TransformAutoType(TypeLocBuilder &TLB,
6821                                                    AutoTypeLoc TL) {
6822   const AutoType *T = TL.getTypePtr();
6823   QualType OldDeduced = T->getDeducedType();
6824   QualType NewDeduced;
6825   if (!OldDeduced.isNull()) {
6826     NewDeduced = getDerived().TransformType(OldDeduced);
6827     if (NewDeduced.isNull())
6828       return QualType();
6829   }
6830 
6831   ConceptDecl *NewCD = nullptr;
6832   TemplateArgumentListInfo NewTemplateArgs;
6833   NestedNameSpecifierLoc NewNestedNameSpec;
6834   if (T->isConstrained()) {
6835     assert(TL.getConceptReference());
6836     NewCD = cast_or_null<ConceptDecl>(getDerived().TransformDecl(
6837         TL.getConceptNameLoc(), T->getTypeConstraintConcept()));
6838 
6839     NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6840     NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6841     typedef TemplateArgumentLocContainerIterator<AutoTypeLoc> ArgIterator;
6842     if (getDerived().TransformTemplateArguments(
6843             ArgIterator(TL, 0), ArgIterator(TL, TL.getNumArgs()),
6844             NewTemplateArgs))
6845       return QualType();
6846 
6847     if (TL.getNestedNameSpecifierLoc()) {
6848       NewNestedNameSpec
6849         = getDerived().TransformNestedNameSpecifierLoc(
6850             TL.getNestedNameSpecifierLoc());
6851       if (!NewNestedNameSpec)
6852         return QualType();
6853     }
6854   }
6855 
6856   QualType Result = TL.getType();
6857   if (getDerived().AlwaysRebuild() || NewDeduced != OldDeduced ||
6858       T->isDependentType() || T->isConstrained()) {
6859     // FIXME: Maybe don't rebuild if all template arguments are the same.
6860     llvm::SmallVector<TemplateArgument, 4> NewArgList;
6861     NewArgList.reserve(NewTemplateArgs.size());
6862     for (const auto &ArgLoc : NewTemplateArgs.arguments())
6863       NewArgList.push_back(ArgLoc.getArgument());
6864     Result = getDerived().RebuildAutoType(NewDeduced, T->getKeyword(), NewCD,
6865                                           NewArgList);
6866     if (Result.isNull())
6867       return QualType();
6868   }
6869 
6870   AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
6871   NewTL.setNameLoc(TL.getNameLoc());
6872   NewTL.setRParenLoc(TL.getRParenLoc());
6873   NewTL.setConceptReference(nullptr);
6874 
6875   if (T->isConstrained()) {
6876     DeclarationNameInfo DNI = DeclarationNameInfo(
6877         TL.getTypePtr()->getTypeConstraintConcept()->getDeclName(),
6878         TL.getConceptNameLoc(),
6879         TL.getTypePtr()->getTypeConstraintConcept()->getDeclName());
6880     auto *CR = ConceptReference::Create(
6881         SemaRef.Context, NewNestedNameSpec, TL.getTemplateKWLoc(), DNI,
6882         TL.getFoundDecl(), TL.getTypePtr()->getTypeConstraintConcept(),
6883         ASTTemplateArgumentListInfo::Create(SemaRef.Context, NewTemplateArgs));
6884     NewTL.setConceptReference(CR);
6885   }
6886 
6887   return Result;
6888 }
6889 
6890 template <typename Derived>
6891 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
6892                                                         TypeLocBuilder &TLB,
6893                                            TemplateSpecializationTypeLoc TL,
6894                                                       TemplateName Template) {
6895   TemplateArgumentListInfo NewTemplateArgs;
6896   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6897   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6898   typedef TemplateArgumentLocContainerIterator<TemplateSpecializationTypeLoc>
6899     ArgIterator;
6900   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6901                                               ArgIterator(TL, TL.getNumArgs()),
6902                                               NewTemplateArgs))
6903     return QualType();
6904 
6905   // FIXME: maybe don't rebuild if all the template arguments are the same.
6906 
6907   QualType Result =
6908     getDerived().RebuildTemplateSpecializationType(Template,
6909                                                    TL.getTemplateNameLoc(),
6910                                                    NewTemplateArgs);
6911 
6912   if (!Result.isNull()) {
6913     // Specializations of template template parameters are represented as
6914     // TemplateSpecializationTypes, and substitution of type alias templates
6915     // within a dependent context can transform them into
6916     // DependentTemplateSpecializationTypes.
6917     if (isa<DependentTemplateSpecializationType>(Result)) {
6918       DependentTemplateSpecializationTypeLoc NewTL
6919         = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6920       NewTL.setElaboratedKeywordLoc(SourceLocation());
6921       NewTL.setQualifierLoc(NestedNameSpecifierLoc());
6922       NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6923       NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6924       NewTL.setLAngleLoc(TL.getLAngleLoc());
6925       NewTL.setRAngleLoc(TL.getRAngleLoc());
6926       for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6927         NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6928       return Result;
6929     }
6930 
6931     TemplateSpecializationTypeLoc NewTL
6932       = TLB.push<TemplateSpecializationTypeLoc>(Result);
6933     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6934     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6935     NewTL.setLAngleLoc(TL.getLAngleLoc());
6936     NewTL.setRAngleLoc(TL.getRAngleLoc());
6937     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6938       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6939   }
6940 
6941   return Result;
6942 }
6943 
6944 template <typename Derived>
6945 QualType TreeTransform<Derived>::TransformDependentTemplateSpecializationType(
6946                                      TypeLocBuilder &TLB,
6947                                      DependentTemplateSpecializationTypeLoc TL,
6948                                      TemplateName Template,
6949                                      CXXScopeSpec &SS) {
6950   TemplateArgumentListInfo NewTemplateArgs;
6951   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6952   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6953   typedef TemplateArgumentLocContainerIterator<
6954             DependentTemplateSpecializationTypeLoc> ArgIterator;
6955   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6956                                               ArgIterator(TL, TL.getNumArgs()),
6957                                               NewTemplateArgs))
6958     return QualType();
6959 
6960   // FIXME: maybe don't rebuild if all the template arguments are the same.
6961 
6962   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
6963     QualType Result = getSema().Context.getDependentTemplateSpecializationType(
6964         TL.getTypePtr()->getKeyword(), DTN->getQualifier(),
6965         DTN->getIdentifier(), NewTemplateArgs.arguments());
6966 
6967     DependentTemplateSpecializationTypeLoc NewTL
6968       = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6969     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6970     NewTL.setQualifierLoc(SS.getWithLocInContext(SemaRef.Context));
6971     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6972     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6973     NewTL.setLAngleLoc(TL.getLAngleLoc());
6974     NewTL.setRAngleLoc(TL.getRAngleLoc());
6975     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6976       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6977     return Result;
6978   }
6979 
6980   QualType Result
6981     = getDerived().RebuildTemplateSpecializationType(Template,
6982                                                      TL.getTemplateNameLoc(),
6983                                                      NewTemplateArgs);
6984 
6985   if (!Result.isNull()) {
6986     /// FIXME: Wrap this in an elaborated-type-specifier?
6987     TemplateSpecializationTypeLoc NewTL
6988       = TLB.push<TemplateSpecializationTypeLoc>(Result);
6989     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6990     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6991     NewTL.setLAngleLoc(TL.getLAngleLoc());
6992     NewTL.setRAngleLoc(TL.getRAngleLoc());
6993     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6994       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6995   }
6996 
6997   return Result;
6998 }
6999 
7000 template<typename Derived>
7001 QualType
7002 TreeTransform<Derived>::TransformElaboratedType(TypeLocBuilder &TLB,
7003                                                 ElaboratedTypeLoc TL) {
7004   const ElaboratedType *T = TL.getTypePtr();
7005 
7006   NestedNameSpecifierLoc QualifierLoc;
7007   // NOTE: the qualifier in an ElaboratedType is optional.
7008   if (TL.getQualifierLoc()) {
7009     QualifierLoc
7010       = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
7011     if (!QualifierLoc)
7012       return QualType();
7013   }
7014 
7015   QualType NamedT = getDerived().TransformType(TLB, TL.getNamedTypeLoc());
7016   if (NamedT.isNull())
7017     return QualType();
7018 
7019   // C++0x [dcl.type.elab]p2:
7020   //   If the identifier resolves to a typedef-name or the simple-template-id
7021   //   resolves to an alias template specialization, the
7022   //   elaborated-type-specifier is ill-formed.
7023   if (T->getKeyword() != ElaboratedTypeKeyword::None &&
7024       T->getKeyword() != ElaboratedTypeKeyword::Typename) {
7025     if (const TemplateSpecializationType *TST =
7026           NamedT->getAs<TemplateSpecializationType>()) {
7027       TemplateName Template = TST->getTemplateName();
7028       if (TypeAliasTemplateDecl *TAT = dyn_cast_or_null<TypeAliasTemplateDecl>(
7029               Template.getAsTemplateDecl())) {
7030         SemaRef.Diag(TL.getNamedTypeLoc().getBeginLoc(),
7031                      diag::err_tag_reference_non_tag)
7032             << TAT << Sema::NTK_TypeAliasTemplate
7033             << llvm::to_underlying(
7034                    ElaboratedType::getTagTypeKindForKeyword(T->getKeyword()));
7035         SemaRef.Diag(TAT->getLocation(), diag::note_declared_at);
7036       }
7037     }
7038   }
7039 
7040   QualType Result = TL.getType();
7041   if (getDerived().AlwaysRebuild() ||
7042       QualifierLoc != TL.getQualifierLoc() ||
7043       NamedT != T->getNamedType()) {
7044     Result = getDerived().RebuildElaboratedType(TL.getElaboratedKeywordLoc(),
7045                                                 T->getKeyword(),
7046                                                 QualifierLoc, NamedT);
7047     if (Result.isNull())
7048       return QualType();
7049   }
7050 
7051   ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
7052   NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
7053   NewTL.setQualifierLoc(QualifierLoc);
7054   return Result;
7055 }
7056 
7057 template <typename Derived>
7058 template <typename Fn>
7059 QualType TreeTransform<Derived>::TransformAttributedType(
7060     TypeLocBuilder &TLB, AttributedTypeLoc TL, Fn TransformModifiedTypeFn) {
7061   const AttributedType *oldType = TL.getTypePtr();
7062   QualType modifiedType = TransformModifiedTypeFn(TLB, TL.getModifiedLoc());
7063   if (modifiedType.isNull())
7064     return QualType();
7065 
7066   // oldAttr can be null if we started with a QualType rather than a TypeLoc.
7067   const Attr *oldAttr = TL.getAttr();
7068   const Attr *newAttr = oldAttr ? getDerived().TransformAttr(oldAttr) : nullptr;
7069   if (oldAttr && !newAttr)
7070     return QualType();
7071 
7072   QualType result = TL.getType();
7073 
7074   // FIXME: dependent operand expressions?
7075   if (getDerived().AlwaysRebuild() ||
7076       modifiedType != oldType->getModifiedType()) {
7077     // TODO: this is really lame; we should really be rebuilding the
7078     // equivalent type from first principles.
7079     QualType equivalentType
7080       = getDerived().TransformType(oldType->getEquivalentType());
7081     if (equivalentType.isNull())
7082       return QualType();
7083 
7084     // Check whether we can add nullability; it is only represented as
7085     // type sugar, and therefore cannot be diagnosed in any other way.
7086     if (auto nullability = oldType->getImmediateNullability()) {
7087       if (!modifiedType->canHaveNullability()) {
7088         SemaRef.Diag((TL.getAttr() ? TL.getAttr()->getLocation()
7089                                    : TL.getModifiedLoc().getBeginLoc()),
7090                      diag::err_nullability_nonpointer)
7091             << DiagNullabilityKind(*nullability, false) << modifiedType;
7092         return QualType();
7093       }
7094     }
7095 
7096     result = SemaRef.Context.getAttributedType(TL.getAttrKind(),
7097                                                modifiedType,
7098                                                equivalentType);
7099   }
7100 
7101   AttributedTypeLoc newTL = TLB.push<AttributedTypeLoc>(result);
7102   newTL.setAttr(newAttr);
7103   return result;
7104 }
7105 
7106 template <typename Derived>
7107 QualType TreeTransform<Derived>::TransformAttributedType(TypeLocBuilder &TLB,
7108                                                          AttributedTypeLoc TL) {
7109   return getDerived().TransformAttributedType(
7110       TLB, TL, [&](TypeLocBuilder &TLB, TypeLoc ModifiedLoc) -> QualType {
7111         return getDerived().TransformType(TLB, ModifiedLoc);
7112       });
7113 }
7114 
7115 template <typename Derived>
7116 QualType TreeTransform<Derived>::TransformBTFTagAttributedType(
7117     TypeLocBuilder &TLB, BTFTagAttributedTypeLoc TL) {
7118   // The BTFTagAttributedType is available for C only.
7119   llvm_unreachable("Unexpected TreeTransform for BTFTagAttributedType");
7120 }
7121 
7122 template<typename Derived>
7123 QualType
7124 TreeTransform<Derived>::TransformParenType(TypeLocBuilder &TLB,
7125                                            ParenTypeLoc TL) {
7126   QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
7127   if (Inner.isNull())
7128     return QualType();
7129 
7130   QualType Result = TL.getType();
7131   if (getDerived().AlwaysRebuild() ||
7132       Inner != TL.getInnerLoc().getType()) {
7133     Result = getDerived().RebuildParenType(Inner);
7134     if (Result.isNull())
7135       return QualType();
7136   }
7137 
7138   ParenTypeLoc NewTL = TLB.push<ParenTypeLoc>(Result);
7139   NewTL.setLParenLoc(TL.getLParenLoc());
7140   NewTL.setRParenLoc(TL.getRParenLoc());
7141   return Result;
7142 }
7143 
7144 template <typename Derived>
7145 QualType
7146 TreeTransform<Derived>::TransformMacroQualifiedType(TypeLocBuilder &TLB,
7147                                                     MacroQualifiedTypeLoc TL) {
7148   QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
7149   if (Inner.isNull())
7150     return QualType();
7151 
7152   QualType Result = TL.getType();
7153   if (getDerived().AlwaysRebuild() || Inner != TL.getInnerLoc().getType()) {
7154     Result =
7155         getDerived().RebuildMacroQualifiedType(Inner, TL.getMacroIdentifier());
7156     if (Result.isNull())
7157       return QualType();
7158   }
7159 
7160   MacroQualifiedTypeLoc NewTL = TLB.push<MacroQualifiedTypeLoc>(Result);
7161   NewTL.setExpansionLoc(TL.getExpansionLoc());
7162   return Result;
7163 }
7164 
7165 template<typename Derived>
7166 QualType TreeTransform<Derived>::TransformDependentNameType(
7167     TypeLocBuilder &TLB, DependentNameTypeLoc TL) {
7168   return TransformDependentNameType(TLB, TL, false);
7169 }
7170 
7171 template<typename Derived>
7172 QualType TreeTransform<Derived>::TransformDependentNameType(
7173     TypeLocBuilder &TLB, DependentNameTypeLoc TL, bool DeducedTSTContext) {
7174   const DependentNameType *T = TL.getTypePtr();
7175 
7176   NestedNameSpecifierLoc QualifierLoc
7177     = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
7178   if (!QualifierLoc)
7179     return QualType();
7180 
7181   QualType Result
7182     = getDerived().RebuildDependentNameType(T->getKeyword(),
7183                                             TL.getElaboratedKeywordLoc(),
7184                                             QualifierLoc,
7185                                             T->getIdentifier(),
7186                                             TL.getNameLoc(),
7187                                             DeducedTSTContext);
7188   if (Result.isNull())
7189     return QualType();
7190 
7191   if (const ElaboratedType* ElabT = Result->getAs<ElaboratedType>()) {
7192     QualType NamedT = ElabT->getNamedType();
7193     TLB.pushTypeSpec(NamedT).setNameLoc(TL.getNameLoc());
7194 
7195     ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
7196     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
7197     NewTL.setQualifierLoc(QualifierLoc);
7198   } else {
7199     DependentNameTypeLoc NewTL = TLB.push<DependentNameTypeLoc>(Result);
7200     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
7201     NewTL.setQualifierLoc(QualifierLoc);
7202     NewTL.setNameLoc(TL.getNameLoc());
7203   }
7204   return Result;
7205 }
7206 
7207 template<typename Derived>
7208 QualType TreeTransform<Derived>::
7209           TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
7210                                  DependentTemplateSpecializationTypeLoc TL) {
7211   NestedNameSpecifierLoc QualifierLoc;
7212   if (TL.getQualifierLoc()) {
7213     QualifierLoc
7214       = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
7215     if (!QualifierLoc)
7216       return QualType();
7217   }
7218 
7219   return getDerived()
7220            .TransformDependentTemplateSpecializationType(TLB, TL, QualifierLoc);
7221 }
7222 
7223 template<typename Derived>
7224 QualType TreeTransform<Derived>::
7225 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
7226                                    DependentTemplateSpecializationTypeLoc TL,
7227                                        NestedNameSpecifierLoc QualifierLoc) {
7228   const DependentTemplateSpecializationType *T = TL.getTypePtr();
7229 
7230   TemplateArgumentListInfo NewTemplateArgs;
7231   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
7232   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
7233 
7234   typedef TemplateArgumentLocContainerIterator<
7235   DependentTemplateSpecializationTypeLoc> ArgIterator;
7236   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
7237                                               ArgIterator(TL, TL.getNumArgs()),
7238                                               NewTemplateArgs))
7239     return QualType();
7240 
7241   QualType Result = getDerived().RebuildDependentTemplateSpecializationType(
7242       T->getKeyword(), QualifierLoc, TL.getTemplateKeywordLoc(),
7243       T->getIdentifier(), TL.getTemplateNameLoc(), NewTemplateArgs,
7244       /*AllowInjectedClassName*/ false);
7245   if (Result.isNull())
7246     return QualType();
7247 
7248   if (const ElaboratedType *ElabT = dyn_cast<ElaboratedType>(Result)) {
7249     QualType NamedT = ElabT->getNamedType();
7250 
7251     // Copy information relevant to the template specialization.
7252     TemplateSpecializationTypeLoc NamedTL
7253       = TLB.push<TemplateSpecializationTypeLoc>(NamedT);
7254     NamedTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
7255     NamedTL.setTemplateNameLoc(TL.getTemplateNameLoc());
7256     NamedTL.setLAngleLoc(TL.getLAngleLoc());
7257     NamedTL.setRAngleLoc(TL.getRAngleLoc());
7258     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
7259       NamedTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
7260 
7261     // Copy information relevant to the elaborated type.
7262     ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
7263     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
7264     NewTL.setQualifierLoc(QualifierLoc);
7265   } else if (isa<DependentTemplateSpecializationType>(Result)) {
7266     DependentTemplateSpecializationTypeLoc SpecTL
7267       = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
7268     SpecTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
7269     SpecTL.setQualifierLoc(QualifierLoc);
7270     SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
7271     SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
7272     SpecTL.setLAngleLoc(TL.getLAngleLoc());
7273     SpecTL.setRAngleLoc(TL.getRAngleLoc());
7274     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
7275       SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
7276   } else {
7277     TemplateSpecializationTypeLoc SpecTL
7278       = TLB.push<TemplateSpecializationTypeLoc>(Result);
7279     SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
7280     SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
7281     SpecTL.setLAngleLoc(TL.getLAngleLoc());
7282     SpecTL.setRAngleLoc(TL.getRAngleLoc());
7283     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
7284       SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
7285   }
7286   return Result;
7287 }
7288 
7289 template<typename Derived>
7290 QualType TreeTransform<Derived>::TransformPackExpansionType(TypeLocBuilder &TLB,
7291                                                       PackExpansionTypeLoc TL) {
7292   QualType Pattern
7293     = getDerived().TransformType(TLB, TL.getPatternLoc());
7294   if (Pattern.isNull())
7295     return QualType();
7296 
7297   QualType Result = TL.getType();
7298   if (getDerived().AlwaysRebuild() ||
7299       Pattern != TL.getPatternLoc().getType()) {
7300     Result = getDerived().RebuildPackExpansionType(Pattern,
7301                                            TL.getPatternLoc().getSourceRange(),
7302                                                    TL.getEllipsisLoc(),
7303                                            TL.getTypePtr()->getNumExpansions());
7304     if (Result.isNull())
7305       return QualType();
7306   }
7307 
7308   PackExpansionTypeLoc NewT = TLB.push<PackExpansionTypeLoc>(Result);
7309   NewT.setEllipsisLoc(TL.getEllipsisLoc());
7310   return Result;
7311 }
7312 
7313 template<typename Derived>
7314 QualType
7315 TreeTransform<Derived>::TransformObjCInterfaceType(TypeLocBuilder &TLB,
7316                                                    ObjCInterfaceTypeLoc TL) {
7317   // ObjCInterfaceType is never dependent.
7318   TLB.pushFullCopy(TL);
7319   return TL.getType();
7320 }
7321 
7322 template<typename Derived>
7323 QualType
7324 TreeTransform<Derived>::TransformObjCTypeParamType(TypeLocBuilder &TLB,
7325                                                    ObjCTypeParamTypeLoc TL) {
7326   const ObjCTypeParamType *T = TL.getTypePtr();
7327   ObjCTypeParamDecl *OTP = cast_or_null<ObjCTypeParamDecl>(
7328       getDerived().TransformDecl(T->getDecl()->getLocation(), T->getDecl()));
7329   if (!OTP)
7330     return QualType();
7331 
7332   QualType Result = TL.getType();
7333   if (getDerived().AlwaysRebuild() ||
7334       OTP != T->getDecl()) {
7335     Result = getDerived().RebuildObjCTypeParamType(
7336         OTP, TL.getProtocolLAngleLoc(),
7337         llvm::ArrayRef(TL.getTypePtr()->qual_begin(), TL.getNumProtocols()),
7338         TL.getProtocolLocs(), TL.getProtocolRAngleLoc());
7339     if (Result.isNull())
7340       return QualType();
7341   }
7342 
7343   ObjCTypeParamTypeLoc NewTL = TLB.push<ObjCTypeParamTypeLoc>(Result);
7344   if (TL.getNumProtocols()) {
7345     NewTL.setProtocolLAngleLoc(TL.getProtocolLAngleLoc());
7346     for (unsigned i = 0, n = TL.getNumProtocols(); i != n; ++i)
7347       NewTL.setProtocolLoc(i, TL.getProtocolLoc(i));
7348     NewTL.setProtocolRAngleLoc(TL.getProtocolRAngleLoc());
7349   }
7350   return Result;
7351 }
7352 
7353 template<typename Derived>
7354 QualType
7355 TreeTransform<Derived>::TransformObjCObjectType(TypeLocBuilder &TLB,
7356                                                 ObjCObjectTypeLoc TL) {
7357   // Transform base type.
7358   QualType BaseType = getDerived().TransformType(TLB, TL.getBaseLoc());
7359   if (BaseType.isNull())
7360     return QualType();
7361 
7362   bool AnyChanged = BaseType != TL.getBaseLoc().getType();
7363 
7364   // Transform type arguments.
7365   SmallVector<TypeSourceInfo *, 4> NewTypeArgInfos;
7366   for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i) {
7367     TypeSourceInfo *TypeArgInfo = TL.getTypeArgTInfo(i);
7368     TypeLoc TypeArgLoc = TypeArgInfo->getTypeLoc();
7369     QualType TypeArg = TypeArgInfo->getType();
7370     if (auto PackExpansionLoc = TypeArgLoc.getAs<PackExpansionTypeLoc>()) {
7371       AnyChanged = true;
7372 
7373       // We have a pack expansion. Instantiate it.
7374       const auto *PackExpansion = PackExpansionLoc.getType()
7375                                     ->castAs<PackExpansionType>();
7376       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
7377       SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
7378                                               Unexpanded);
7379       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
7380 
7381       // Determine whether the set of unexpanded parameter packs can
7382       // and should be expanded.
7383       TypeLoc PatternLoc = PackExpansionLoc.getPatternLoc();
7384       bool Expand = false;
7385       bool RetainExpansion = false;
7386       std::optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
7387       if (getDerived().TryExpandParameterPacks(
7388             PackExpansionLoc.getEllipsisLoc(), PatternLoc.getSourceRange(),
7389             Unexpanded, Expand, RetainExpansion, NumExpansions))
7390         return QualType();
7391 
7392       if (!Expand) {
7393         // We can't expand this pack expansion into separate arguments yet;
7394         // just substitute into the pattern and create a new pack expansion
7395         // type.
7396         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
7397 
7398         TypeLocBuilder TypeArgBuilder;
7399         TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
7400         QualType NewPatternType = getDerived().TransformType(TypeArgBuilder,
7401                                                              PatternLoc);
7402         if (NewPatternType.isNull())
7403           return QualType();
7404 
7405         QualType NewExpansionType = SemaRef.Context.getPackExpansionType(
7406                                       NewPatternType, NumExpansions);
7407         auto NewExpansionLoc = TLB.push<PackExpansionTypeLoc>(NewExpansionType);
7408         NewExpansionLoc.setEllipsisLoc(PackExpansionLoc.getEllipsisLoc());
7409         NewTypeArgInfos.push_back(
7410           TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewExpansionType));
7411         continue;
7412       }
7413 
7414       // Substitute into the pack expansion pattern for each slice of the
7415       // pack.
7416       for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
7417         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
7418 
7419         TypeLocBuilder TypeArgBuilder;
7420         TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
7421 
7422         QualType NewTypeArg = getDerived().TransformType(TypeArgBuilder,
7423                                                          PatternLoc);
7424         if (NewTypeArg.isNull())
7425           return QualType();
7426 
7427         NewTypeArgInfos.push_back(
7428           TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
7429       }
7430 
7431       continue;
7432     }
7433 
7434     TypeLocBuilder TypeArgBuilder;
7435     TypeArgBuilder.reserve(TypeArgLoc.getFullDataSize());
7436     QualType NewTypeArg =
7437         getDerived().TransformType(TypeArgBuilder, TypeArgLoc);
7438     if (NewTypeArg.isNull())
7439       return QualType();
7440 
7441     // If nothing changed, just keep the old TypeSourceInfo.
7442     if (NewTypeArg == TypeArg) {
7443       NewTypeArgInfos.push_back(TypeArgInfo);
7444       continue;
7445     }
7446 
7447     NewTypeArgInfos.push_back(
7448       TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
7449     AnyChanged = true;
7450   }
7451 
7452   QualType Result = TL.getType();
7453   if (getDerived().AlwaysRebuild() || AnyChanged) {
7454     // Rebuild the type.
7455     Result = getDerived().RebuildObjCObjectType(
7456         BaseType, TL.getBeginLoc(), TL.getTypeArgsLAngleLoc(), NewTypeArgInfos,
7457         TL.getTypeArgsRAngleLoc(), TL.getProtocolLAngleLoc(),
7458         llvm::ArrayRef(TL.getTypePtr()->qual_begin(), TL.getNumProtocols()),
7459         TL.getProtocolLocs(), TL.getProtocolRAngleLoc());
7460 
7461     if (Result.isNull())
7462       return QualType();
7463   }
7464 
7465   ObjCObjectTypeLoc NewT = TLB.push<ObjCObjectTypeLoc>(Result);
7466   NewT.setHasBaseTypeAsWritten(true);
7467   NewT.setTypeArgsLAngleLoc(TL.getTypeArgsLAngleLoc());
7468   for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i)
7469     NewT.setTypeArgTInfo(i, NewTypeArgInfos[i]);
7470   NewT.setTypeArgsRAngleLoc(TL.getTypeArgsRAngleLoc());
7471   NewT.setProtocolLAngleLoc(TL.getProtocolLAngleLoc());
7472   for (unsigned i = 0, n = TL.getNumProtocols(); i != n; ++i)
7473     NewT.setProtocolLoc(i, TL.getProtocolLoc(i));
7474   NewT.setProtocolRAngleLoc(TL.getProtocolRAngleLoc());
7475   return Result;
7476 }
7477 
7478 template<typename Derived>
7479 QualType
7480 TreeTransform<Derived>::TransformObjCObjectPointerType(TypeLocBuilder &TLB,
7481                                                ObjCObjectPointerTypeLoc TL) {
7482   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
7483   if (PointeeType.isNull())
7484     return QualType();
7485 
7486   QualType Result = TL.getType();
7487   if (getDerived().AlwaysRebuild() ||
7488       PointeeType != TL.getPointeeLoc().getType()) {
7489     Result = getDerived().RebuildObjCObjectPointerType(PointeeType,
7490                                                        TL.getStarLoc());
7491     if (Result.isNull())
7492       return QualType();
7493   }
7494 
7495   ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
7496   NewT.setStarLoc(TL.getStarLoc());
7497   return Result;
7498 }
7499 
7500 //===----------------------------------------------------------------------===//
7501 // Statement transformation
7502 //===----------------------------------------------------------------------===//
7503 template<typename Derived>
7504 StmtResult
7505 TreeTransform<Derived>::TransformNullStmt(NullStmt *S) {
7506   return S;
7507 }
7508 
7509 template<typename Derived>
7510 StmtResult
7511 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S) {
7512   return getDerived().TransformCompoundStmt(S, false);
7513 }
7514 
7515 template<typename Derived>
7516 StmtResult
7517 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S,
7518                                               bool IsStmtExpr) {
7519   Sema::CompoundScopeRAII CompoundScope(getSema());
7520   Sema::FPFeaturesStateRAII FPSave(getSema());
7521   if (S->hasStoredFPFeatures())
7522     getSema().resetFPOptions(
7523         S->getStoredFPFeatures().applyOverrides(getSema().getLangOpts()));
7524 
7525   const Stmt *ExprResult = S->getStmtExprResult();
7526   bool SubStmtInvalid = false;
7527   bool SubStmtChanged = false;
7528   SmallVector<Stmt*, 8> Statements;
7529   for (auto *B : S->body()) {
7530     StmtResult Result = getDerived().TransformStmt(
7531         B, IsStmtExpr && B == ExprResult ? SDK_StmtExprResult : SDK_Discarded);
7532 
7533     if (Result.isInvalid()) {
7534       // Immediately fail if this was a DeclStmt, since it's very
7535       // likely that this will cause problems for future statements.
7536       if (isa<DeclStmt>(B))
7537         return StmtError();
7538 
7539       // Otherwise, just keep processing substatements and fail later.
7540       SubStmtInvalid = true;
7541       continue;
7542     }
7543 
7544     SubStmtChanged = SubStmtChanged || Result.get() != B;
7545     Statements.push_back(Result.getAs<Stmt>());
7546   }
7547 
7548   if (SubStmtInvalid)
7549     return StmtError();
7550 
7551   if (!getDerived().AlwaysRebuild() &&
7552       !SubStmtChanged)
7553     return S;
7554 
7555   return getDerived().RebuildCompoundStmt(S->getLBracLoc(),
7556                                           Statements,
7557                                           S->getRBracLoc(),
7558                                           IsStmtExpr);
7559 }
7560 
7561 template<typename Derived>
7562 StmtResult
7563 TreeTransform<Derived>::TransformCaseStmt(CaseStmt *S) {
7564   ExprResult LHS, RHS;
7565   {
7566     EnterExpressionEvaluationContext Unevaluated(
7567         SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
7568 
7569     // Transform the left-hand case value.
7570     LHS = getDerived().TransformExpr(S->getLHS());
7571     LHS = SemaRef.ActOnCaseExpr(S->getCaseLoc(), LHS);
7572     if (LHS.isInvalid())
7573       return StmtError();
7574 
7575     // Transform the right-hand case value (for the GNU case-range extension).
7576     RHS = getDerived().TransformExpr(S->getRHS());
7577     RHS = SemaRef.ActOnCaseExpr(S->getCaseLoc(), RHS);
7578     if (RHS.isInvalid())
7579       return StmtError();
7580   }
7581 
7582   // Build the case statement.
7583   // Case statements are always rebuilt so that they will attached to their
7584   // transformed switch statement.
7585   StmtResult Case = getDerived().RebuildCaseStmt(S->getCaseLoc(),
7586                                                        LHS.get(),
7587                                                        S->getEllipsisLoc(),
7588                                                        RHS.get(),
7589                                                        S->getColonLoc());
7590   if (Case.isInvalid())
7591     return StmtError();
7592 
7593   // Transform the statement following the case
7594   StmtResult SubStmt =
7595       getDerived().TransformStmt(S->getSubStmt());
7596   if (SubStmt.isInvalid())
7597     return StmtError();
7598 
7599   // Attach the body to the case statement
7600   return getDerived().RebuildCaseStmtBody(Case.get(), SubStmt.get());
7601 }
7602 
7603 template <typename Derived>
7604 StmtResult TreeTransform<Derived>::TransformDefaultStmt(DefaultStmt *S) {
7605   // Transform the statement following the default case
7606   StmtResult SubStmt =
7607       getDerived().TransformStmt(S->getSubStmt());
7608   if (SubStmt.isInvalid())
7609     return StmtError();
7610 
7611   // Default statements are always rebuilt
7612   return getDerived().RebuildDefaultStmt(S->getDefaultLoc(), S->getColonLoc(),
7613                                          SubStmt.get());
7614 }
7615 
7616 template<typename Derived>
7617 StmtResult
7618 TreeTransform<Derived>::TransformLabelStmt(LabelStmt *S, StmtDiscardKind SDK) {
7619   StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt(), SDK);
7620   if (SubStmt.isInvalid())
7621     return StmtError();
7622 
7623   Decl *LD = getDerived().TransformDecl(S->getDecl()->getLocation(),
7624                                         S->getDecl());
7625   if (!LD)
7626     return StmtError();
7627 
7628   // If we're transforming "in-place" (we're not creating new local
7629   // declarations), assume we're replacing the old label statement
7630   // and clear out the reference to it.
7631   if (LD == S->getDecl())
7632     S->getDecl()->setStmt(nullptr);
7633 
7634   // FIXME: Pass the real colon location in.
7635   return getDerived().RebuildLabelStmt(S->getIdentLoc(),
7636                                        cast<LabelDecl>(LD), SourceLocation(),
7637                                        SubStmt.get());
7638 }
7639 
7640 template <typename Derived>
7641 const Attr *TreeTransform<Derived>::TransformAttr(const Attr *R) {
7642   if (!R)
7643     return R;
7644 
7645   switch (R->getKind()) {
7646 // Transform attributes by calling TransformXXXAttr.
7647 #define ATTR(X)                                                                \
7648   case attr::X:                                                                \
7649     return getDerived().Transform##X##Attr(cast<X##Attr>(R));
7650 #include "clang/Basic/AttrList.inc"
7651   }
7652   return R;
7653 }
7654 
7655 template <typename Derived>
7656 const Attr *TreeTransform<Derived>::TransformStmtAttr(const Stmt *OrigS,
7657                                                       const Stmt *InstS,
7658                                                       const Attr *R) {
7659   if (!R)
7660     return R;
7661 
7662   switch (R->getKind()) {
7663 // Transform attributes by calling TransformStmtXXXAttr.
7664 #define ATTR(X)                                                                \
7665   case attr::X:                                                                \
7666     return getDerived().TransformStmt##X##Attr(OrigS, InstS, cast<X##Attr>(R));
7667 #include "clang/Basic/AttrList.inc"
7668   }
7669   return TransformAttr(R);
7670 }
7671 
7672 template <typename Derived>
7673 StmtResult
7674 TreeTransform<Derived>::TransformAttributedStmt(AttributedStmt *S,
7675                                                 StmtDiscardKind SDK) {
7676   StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt(), SDK);
7677   if (SubStmt.isInvalid())
7678     return StmtError();
7679 
7680   bool AttrsChanged = false;
7681   SmallVector<const Attr *, 1> Attrs;
7682 
7683   // Visit attributes and keep track if any are transformed.
7684   for (const auto *I : S->getAttrs()) {
7685     const Attr *R =
7686         getDerived().TransformStmtAttr(S->getSubStmt(), SubStmt.get(), I);
7687     AttrsChanged |= (I != R);
7688     if (R)
7689       Attrs.push_back(R);
7690   }
7691 
7692   if (SubStmt.get() == S->getSubStmt() && !AttrsChanged)
7693     return S;
7694 
7695   // If transforming the attributes failed for all of the attributes in the
7696   // statement, don't make an AttributedStmt without attributes.
7697   if (Attrs.empty())
7698     return SubStmt;
7699 
7700   return getDerived().RebuildAttributedStmt(S->getAttrLoc(), Attrs,
7701                                             SubStmt.get());
7702 }
7703 
7704 template<typename Derived>
7705 StmtResult
7706 TreeTransform<Derived>::TransformIfStmt(IfStmt *S) {
7707   // Transform the initialization statement
7708   StmtResult Init = getDerived().TransformStmt(S->getInit());
7709   if (Init.isInvalid())
7710     return StmtError();
7711 
7712   Sema::ConditionResult Cond;
7713   if (!S->isConsteval()) {
7714     // Transform the condition
7715     Cond = getDerived().TransformCondition(
7716         S->getIfLoc(), S->getConditionVariable(), S->getCond(),
7717         S->isConstexpr() ? Sema::ConditionKind::ConstexprIf
7718                          : Sema::ConditionKind::Boolean);
7719     if (Cond.isInvalid())
7720       return StmtError();
7721   }
7722 
7723   // If this is a constexpr if, determine which arm we should instantiate.
7724   std::optional<bool> ConstexprConditionValue;
7725   if (S->isConstexpr())
7726     ConstexprConditionValue = Cond.getKnownValue();
7727 
7728   // Transform the "then" branch.
7729   StmtResult Then;
7730   if (!ConstexprConditionValue || *ConstexprConditionValue) {
7731     Then = getDerived().TransformStmt(S->getThen());
7732     if (Then.isInvalid())
7733       return StmtError();
7734   } else {
7735     Then = new (getSema().Context) NullStmt(S->getThen()->getBeginLoc());
7736   }
7737 
7738   // Transform the "else" branch.
7739   StmtResult Else;
7740   if (!ConstexprConditionValue || !*ConstexprConditionValue) {
7741     Else = getDerived().TransformStmt(S->getElse());
7742     if (Else.isInvalid())
7743       return StmtError();
7744   }
7745 
7746   if (!getDerived().AlwaysRebuild() &&
7747       Init.get() == S->getInit() &&
7748       Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
7749       Then.get() == S->getThen() &&
7750       Else.get() == S->getElse())
7751     return S;
7752 
7753   return getDerived().RebuildIfStmt(
7754       S->getIfLoc(), S->getStatementKind(), S->getLParenLoc(), Cond,
7755       S->getRParenLoc(), Init.get(), Then.get(), S->getElseLoc(), Else.get());
7756 }
7757 
7758 template<typename Derived>
7759 StmtResult
7760 TreeTransform<Derived>::TransformSwitchStmt(SwitchStmt *S) {
7761   // Transform the initialization statement
7762   StmtResult Init = getDerived().TransformStmt(S->getInit());
7763   if (Init.isInvalid())
7764     return StmtError();
7765 
7766   // Transform the condition.
7767   Sema::ConditionResult Cond = getDerived().TransformCondition(
7768       S->getSwitchLoc(), S->getConditionVariable(), S->getCond(),
7769       Sema::ConditionKind::Switch);
7770   if (Cond.isInvalid())
7771     return StmtError();
7772 
7773   // Rebuild the switch statement.
7774   StmtResult Switch =
7775       getDerived().RebuildSwitchStmtStart(S->getSwitchLoc(), S->getLParenLoc(),
7776                                           Init.get(), Cond, S->getRParenLoc());
7777   if (Switch.isInvalid())
7778     return StmtError();
7779 
7780   // Transform the body of the switch statement.
7781   StmtResult Body = getDerived().TransformStmt(S->getBody());
7782   if (Body.isInvalid())
7783     return StmtError();
7784 
7785   // Complete the switch statement.
7786   return getDerived().RebuildSwitchStmtBody(S->getSwitchLoc(), Switch.get(),
7787                                             Body.get());
7788 }
7789 
7790 template<typename Derived>
7791 StmtResult
7792 TreeTransform<Derived>::TransformWhileStmt(WhileStmt *S) {
7793   // Transform the condition
7794   Sema::ConditionResult Cond = getDerived().TransformCondition(
7795       S->getWhileLoc(), S->getConditionVariable(), S->getCond(),
7796       Sema::ConditionKind::Boolean);
7797   if (Cond.isInvalid())
7798     return StmtError();
7799 
7800   // Transform the body
7801   StmtResult Body = getDerived().TransformStmt(S->getBody());
7802   if (Body.isInvalid())
7803     return StmtError();
7804 
7805   if (!getDerived().AlwaysRebuild() &&
7806       Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
7807       Body.get() == S->getBody())
7808     return Owned(S);
7809 
7810   return getDerived().RebuildWhileStmt(S->getWhileLoc(), S->getLParenLoc(),
7811                                        Cond, S->getRParenLoc(), Body.get());
7812 }
7813 
7814 template<typename Derived>
7815 StmtResult
7816 TreeTransform<Derived>::TransformDoStmt(DoStmt *S) {
7817   // Transform the body
7818   StmtResult Body = getDerived().TransformStmt(S->getBody());
7819   if (Body.isInvalid())
7820     return StmtError();
7821 
7822   // Transform the condition
7823   ExprResult Cond = getDerived().TransformExpr(S->getCond());
7824   if (Cond.isInvalid())
7825     return StmtError();
7826 
7827   if (!getDerived().AlwaysRebuild() &&
7828       Cond.get() == S->getCond() &&
7829       Body.get() == S->getBody())
7830     return S;
7831 
7832   return getDerived().RebuildDoStmt(S->getDoLoc(), Body.get(), S->getWhileLoc(),
7833                                     /*FIXME:*/S->getWhileLoc(), Cond.get(),
7834                                     S->getRParenLoc());
7835 }
7836 
7837 template<typename Derived>
7838 StmtResult
7839 TreeTransform<Derived>::TransformForStmt(ForStmt *S) {
7840   if (getSema().getLangOpts().OpenMP)
7841     getSema().startOpenMPLoop();
7842 
7843   // Transform the initialization statement
7844   StmtResult Init = getDerived().TransformStmt(S->getInit());
7845   if (Init.isInvalid())
7846     return StmtError();
7847 
7848   // In OpenMP loop region loop control variable must be captured and be
7849   // private. Perform analysis of first part (if any).
7850   if (getSema().getLangOpts().OpenMP && Init.isUsable())
7851     getSema().ActOnOpenMPLoopInitialization(S->getForLoc(), Init.get());
7852 
7853   // Transform the condition
7854   Sema::ConditionResult Cond = getDerived().TransformCondition(
7855       S->getForLoc(), S->getConditionVariable(), S->getCond(),
7856       Sema::ConditionKind::Boolean);
7857   if (Cond.isInvalid())
7858     return StmtError();
7859 
7860   // Transform the increment
7861   ExprResult Inc = getDerived().TransformExpr(S->getInc());
7862   if (Inc.isInvalid())
7863     return StmtError();
7864 
7865   Sema::FullExprArg FullInc(getSema().MakeFullDiscardedValueExpr(Inc.get()));
7866   if (S->getInc() && !FullInc.get())
7867     return StmtError();
7868 
7869   // Transform the body
7870   StmtResult Body = getDerived().TransformStmt(S->getBody());
7871   if (Body.isInvalid())
7872     return StmtError();
7873 
7874   if (!getDerived().AlwaysRebuild() &&
7875       Init.get() == S->getInit() &&
7876       Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
7877       Inc.get() == S->getInc() &&
7878       Body.get() == S->getBody())
7879     return S;
7880 
7881   return getDerived().RebuildForStmt(S->getForLoc(), S->getLParenLoc(),
7882                                      Init.get(), Cond, FullInc,
7883                                      S->getRParenLoc(), Body.get());
7884 }
7885 
7886 template<typename Derived>
7887 StmtResult
7888 TreeTransform<Derived>::TransformGotoStmt(GotoStmt *S) {
7889   Decl *LD = getDerived().TransformDecl(S->getLabel()->getLocation(),
7890                                         S->getLabel());
7891   if (!LD)
7892     return StmtError();
7893 
7894   // Goto statements must always be rebuilt, to resolve the label.
7895   return getDerived().RebuildGotoStmt(S->getGotoLoc(), S->getLabelLoc(),
7896                                       cast<LabelDecl>(LD));
7897 }
7898 
7899 template<typename Derived>
7900 StmtResult
7901 TreeTransform<Derived>::TransformIndirectGotoStmt(IndirectGotoStmt *S) {
7902   ExprResult Target = getDerived().TransformExpr(S->getTarget());
7903   if (Target.isInvalid())
7904     return StmtError();
7905   Target = SemaRef.MaybeCreateExprWithCleanups(Target.get());
7906 
7907   if (!getDerived().AlwaysRebuild() &&
7908       Target.get() == S->getTarget())
7909     return S;
7910 
7911   return getDerived().RebuildIndirectGotoStmt(S->getGotoLoc(), S->getStarLoc(),
7912                                               Target.get());
7913 }
7914 
7915 template<typename Derived>
7916 StmtResult
7917 TreeTransform<Derived>::TransformContinueStmt(ContinueStmt *S) {
7918   return S;
7919 }
7920 
7921 template<typename Derived>
7922 StmtResult
7923 TreeTransform<Derived>::TransformBreakStmt(BreakStmt *S) {
7924   return S;
7925 }
7926 
7927 template<typename Derived>
7928 StmtResult
7929 TreeTransform<Derived>::TransformReturnStmt(ReturnStmt *S) {
7930   ExprResult Result = getDerived().TransformInitializer(S->getRetValue(),
7931                                                         /*NotCopyInit*/false);
7932   if (Result.isInvalid())
7933     return StmtError();
7934 
7935   // FIXME: We always rebuild the return statement because there is no way
7936   // to tell whether the return type of the function has changed.
7937   return getDerived().RebuildReturnStmt(S->getReturnLoc(), Result.get());
7938 }
7939 
7940 template<typename Derived>
7941 StmtResult
7942 TreeTransform<Derived>::TransformDeclStmt(DeclStmt *S) {
7943   bool DeclChanged = false;
7944   SmallVector<Decl *, 4> Decls;
7945   for (auto *D : S->decls()) {
7946     Decl *Transformed = getDerived().TransformDefinition(D->getLocation(), D);
7947     if (!Transformed)
7948       return StmtError();
7949 
7950     if (Transformed != D)
7951       DeclChanged = true;
7952 
7953     Decls.push_back(Transformed);
7954   }
7955 
7956   if (!getDerived().AlwaysRebuild() && !DeclChanged)
7957     return S;
7958 
7959   return getDerived().RebuildDeclStmt(Decls, S->getBeginLoc(), S->getEndLoc());
7960 }
7961 
7962 template<typename Derived>
7963 StmtResult
7964 TreeTransform<Derived>::TransformGCCAsmStmt(GCCAsmStmt *S) {
7965 
7966   SmallVector<Expr*, 8> Constraints;
7967   SmallVector<Expr*, 8> Exprs;
7968   SmallVector<IdentifierInfo *, 4> Names;
7969 
7970   ExprResult AsmString;
7971   SmallVector<Expr*, 8> Clobbers;
7972 
7973   bool ExprsChanged = false;
7974 
7975   // Go through the outputs.
7976   for (unsigned I = 0, E = S->getNumOutputs(); I != E; ++I) {
7977     Names.push_back(S->getOutputIdentifier(I));
7978 
7979     // No need to transform the constraint literal.
7980     Constraints.push_back(S->getOutputConstraintLiteral(I));
7981 
7982     // Transform the output expr.
7983     Expr *OutputExpr = S->getOutputExpr(I);
7984     ExprResult Result = getDerived().TransformExpr(OutputExpr);
7985     if (Result.isInvalid())
7986       return StmtError();
7987 
7988     ExprsChanged |= Result.get() != OutputExpr;
7989 
7990     Exprs.push_back(Result.get());
7991   }
7992 
7993   // Go through the inputs.
7994   for (unsigned I = 0, E = S->getNumInputs(); I != E; ++I) {
7995     Names.push_back(S->getInputIdentifier(I));
7996 
7997     // No need to transform the constraint literal.
7998     Constraints.push_back(S->getInputConstraintLiteral(I));
7999 
8000     // Transform the input expr.
8001     Expr *InputExpr = S->getInputExpr(I);
8002     ExprResult Result = getDerived().TransformExpr(InputExpr);
8003     if (Result.isInvalid())
8004       return StmtError();
8005 
8006     ExprsChanged |= Result.get() != InputExpr;
8007 
8008     Exprs.push_back(Result.get());
8009   }
8010 
8011   // Go through the Labels.
8012   for (unsigned I = 0, E = S->getNumLabels(); I != E; ++I) {
8013     Names.push_back(S->getLabelIdentifier(I));
8014 
8015     ExprResult Result = getDerived().TransformExpr(S->getLabelExpr(I));
8016     if (Result.isInvalid())
8017       return StmtError();
8018     ExprsChanged |= Result.get() != S->getLabelExpr(I);
8019     Exprs.push_back(Result.get());
8020   }
8021   if (!getDerived().AlwaysRebuild() && !ExprsChanged)
8022     return S;
8023 
8024   // Go through the clobbers.
8025   for (unsigned I = 0, E = S->getNumClobbers(); I != E; ++I)
8026     Clobbers.push_back(S->getClobberStringLiteral(I));
8027 
8028   // No need to transform the asm string literal.
8029   AsmString = S->getAsmString();
8030   return getDerived().RebuildGCCAsmStmt(S->getAsmLoc(), S->isSimple(),
8031                                         S->isVolatile(), S->getNumOutputs(),
8032                                         S->getNumInputs(), Names.data(),
8033                                         Constraints, Exprs, AsmString.get(),
8034                                         Clobbers, S->getNumLabels(),
8035                                         S->getRParenLoc());
8036 }
8037 
8038 template<typename Derived>
8039 StmtResult
8040 TreeTransform<Derived>::TransformMSAsmStmt(MSAsmStmt *S) {
8041   ArrayRef<Token> AsmToks = llvm::ArrayRef(S->getAsmToks(), S->getNumAsmToks());
8042 
8043   bool HadError = false, HadChange = false;
8044 
8045   ArrayRef<Expr*> SrcExprs = S->getAllExprs();
8046   SmallVector<Expr*, 8> TransformedExprs;
8047   TransformedExprs.reserve(SrcExprs.size());
8048   for (unsigned i = 0, e = SrcExprs.size(); i != e; ++i) {
8049     ExprResult Result = getDerived().TransformExpr(SrcExprs[i]);
8050     if (!Result.isUsable()) {
8051       HadError = true;
8052     } else {
8053       HadChange |= (Result.get() != SrcExprs[i]);
8054       TransformedExprs.push_back(Result.get());
8055     }
8056   }
8057 
8058   if (HadError) return StmtError();
8059   if (!HadChange && !getDerived().AlwaysRebuild())
8060     return Owned(S);
8061 
8062   return getDerived().RebuildMSAsmStmt(S->getAsmLoc(), S->getLBraceLoc(),
8063                                        AsmToks, S->getAsmString(),
8064                                        S->getNumOutputs(), S->getNumInputs(),
8065                                        S->getAllConstraints(), S->getClobbers(),
8066                                        TransformedExprs, S->getEndLoc());
8067 }
8068 
8069 // C++ Coroutines
8070 template<typename Derived>
8071 StmtResult
8072 TreeTransform<Derived>::TransformCoroutineBodyStmt(CoroutineBodyStmt *S) {
8073   auto *ScopeInfo = SemaRef.getCurFunction();
8074   auto *FD = cast<FunctionDecl>(SemaRef.CurContext);
8075   assert(FD && ScopeInfo && !ScopeInfo->CoroutinePromise &&
8076          ScopeInfo->NeedsCoroutineSuspends &&
8077          ScopeInfo->CoroutineSuspends.first == nullptr &&
8078          ScopeInfo->CoroutineSuspends.second == nullptr &&
8079          "expected clean scope info");
8080 
8081   // Set that we have (possibly-invalid) suspend points before we do anything
8082   // that may fail.
8083   ScopeInfo->setNeedsCoroutineSuspends(false);
8084 
8085   // We re-build the coroutine promise object (and the coroutine parameters its
8086   // type and constructor depend on) based on the types used in our current
8087   // function. We must do so, and set it on the current FunctionScopeInfo,
8088   // before attempting to transform the other parts of the coroutine body
8089   // statement, such as the implicit suspend statements (because those
8090   // statements reference the FunctionScopeInfo::CoroutinePromise).
8091   if (!SemaRef.buildCoroutineParameterMoves(FD->getLocation()))
8092     return StmtError();
8093   auto *Promise = SemaRef.buildCoroutinePromise(FD->getLocation());
8094   if (!Promise)
8095     return StmtError();
8096   getDerived().transformedLocalDecl(S->getPromiseDecl(), {Promise});
8097   ScopeInfo->CoroutinePromise = Promise;
8098 
8099   // Transform the implicit coroutine statements constructed using dependent
8100   // types during the previous parse: initial and final suspensions, the return
8101   // object, and others. We also transform the coroutine function's body.
8102   StmtResult InitSuspend = getDerived().TransformStmt(S->getInitSuspendStmt());
8103   if (InitSuspend.isInvalid())
8104     return StmtError();
8105   StmtResult FinalSuspend =
8106       getDerived().TransformStmt(S->getFinalSuspendStmt());
8107   if (FinalSuspend.isInvalid() ||
8108       !SemaRef.checkFinalSuspendNoThrow(FinalSuspend.get()))
8109     return StmtError();
8110   ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
8111   assert(isa<Expr>(InitSuspend.get()) && isa<Expr>(FinalSuspend.get()));
8112 
8113   StmtResult BodyRes = getDerived().TransformStmt(S->getBody());
8114   if (BodyRes.isInvalid())
8115     return StmtError();
8116 
8117   CoroutineStmtBuilder Builder(SemaRef, *FD, *ScopeInfo, BodyRes.get());
8118   if (Builder.isInvalid())
8119     return StmtError();
8120 
8121   Expr *ReturnObject = S->getReturnValueInit();
8122   assert(ReturnObject && "the return object is expected to be valid");
8123   ExprResult Res = getDerived().TransformInitializer(ReturnObject,
8124                                                      /*NoCopyInit*/ false);
8125   if (Res.isInvalid())
8126     return StmtError();
8127   Builder.ReturnValue = Res.get();
8128 
8129   // If during the previous parse the coroutine still had a dependent promise
8130   // statement, we may need to build some implicit coroutine statements
8131   // (such as exception and fallthrough handlers) for the first time.
8132   if (S->hasDependentPromiseType()) {
8133     // We can only build these statements, however, if the current promise type
8134     // is not dependent.
8135     if (!Promise->getType()->isDependentType()) {
8136       assert(!S->getFallthroughHandler() && !S->getExceptionHandler() &&
8137              !S->getReturnStmtOnAllocFailure() && !S->getDeallocate() &&
8138              "these nodes should not have been built yet");
8139       if (!Builder.buildDependentStatements())
8140         return StmtError();
8141     }
8142   } else {
8143     if (auto *OnFallthrough = S->getFallthroughHandler()) {
8144       StmtResult Res = getDerived().TransformStmt(OnFallthrough);
8145       if (Res.isInvalid())
8146         return StmtError();
8147       Builder.OnFallthrough = Res.get();
8148     }
8149 
8150     if (auto *OnException = S->getExceptionHandler()) {
8151       StmtResult Res = getDerived().TransformStmt(OnException);
8152       if (Res.isInvalid())
8153         return StmtError();
8154       Builder.OnException = Res.get();
8155     }
8156 
8157     if (auto *OnAllocFailure = S->getReturnStmtOnAllocFailure()) {
8158       StmtResult Res = getDerived().TransformStmt(OnAllocFailure);
8159       if (Res.isInvalid())
8160         return StmtError();
8161       Builder.ReturnStmtOnAllocFailure = Res.get();
8162     }
8163 
8164     // Transform any additional statements we may have already built
8165     assert(S->getAllocate() && S->getDeallocate() &&
8166            "allocation and deallocation calls must already be built");
8167     ExprResult AllocRes = getDerived().TransformExpr(S->getAllocate());
8168     if (AllocRes.isInvalid())
8169       return StmtError();
8170     Builder.Allocate = AllocRes.get();
8171 
8172     ExprResult DeallocRes = getDerived().TransformExpr(S->getDeallocate());
8173     if (DeallocRes.isInvalid())
8174       return StmtError();
8175     Builder.Deallocate = DeallocRes.get();
8176 
8177     if (auto *ResultDecl = S->getResultDecl()) {
8178       StmtResult Res = getDerived().TransformStmt(ResultDecl);
8179       if (Res.isInvalid())
8180         return StmtError();
8181       Builder.ResultDecl = Res.get();
8182     }
8183 
8184     if (auto *ReturnStmt = S->getReturnStmt()) {
8185       StmtResult Res = getDerived().TransformStmt(ReturnStmt);
8186       if (Res.isInvalid())
8187         return StmtError();
8188       Builder.ReturnStmt = Res.get();
8189     }
8190   }
8191 
8192   return getDerived().RebuildCoroutineBodyStmt(Builder);
8193 }
8194 
8195 template<typename Derived>
8196 StmtResult
8197 TreeTransform<Derived>::TransformCoreturnStmt(CoreturnStmt *S) {
8198   ExprResult Result = getDerived().TransformInitializer(S->getOperand(),
8199                                                         /*NotCopyInit*/false);
8200   if (Result.isInvalid())
8201     return StmtError();
8202 
8203   // Always rebuild; we don't know if this needs to be injected into a new
8204   // context or if the promise type has changed.
8205   return getDerived().RebuildCoreturnStmt(S->getKeywordLoc(), Result.get(),
8206                                           S->isImplicit());
8207 }
8208 
8209 template <typename Derived>
8210 ExprResult TreeTransform<Derived>::TransformCoawaitExpr(CoawaitExpr *E) {
8211   ExprResult Operand = getDerived().TransformInitializer(E->getOperand(),
8212                                                          /*NotCopyInit*/ false);
8213   if (Operand.isInvalid())
8214     return ExprError();
8215 
8216   // Rebuild the common-expr from the operand rather than transforming it
8217   // separately.
8218 
8219   // FIXME: getCurScope() should not be used during template instantiation.
8220   // We should pick up the set of unqualified lookup results for operator
8221   // co_await during the initial parse.
8222   ExprResult Lookup = getSema().BuildOperatorCoawaitLookupExpr(
8223       getSema().getCurScope(), E->getKeywordLoc());
8224 
8225   // Always rebuild; we don't know if this needs to be injected into a new
8226   // context or if the promise type has changed.
8227   return getDerived().RebuildCoawaitExpr(
8228       E->getKeywordLoc(), Operand.get(),
8229       cast<UnresolvedLookupExpr>(Lookup.get()), E->isImplicit());
8230 }
8231 
8232 template <typename Derived>
8233 ExprResult
8234 TreeTransform<Derived>::TransformDependentCoawaitExpr(DependentCoawaitExpr *E) {
8235   ExprResult OperandResult = getDerived().TransformInitializer(E->getOperand(),
8236                                                         /*NotCopyInit*/ false);
8237   if (OperandResult.isInvalid())
8238     return ExprError();
8239 
8240   ExprResult LookupResult = getDerived().TransformUnresolvedLookupExpr(
8241           E->getOperatorCoawaitLookup());
8242 
8243   if (LookupResult.isInvalid())
8244     return ExprError();
8245 
8246   // Always rebuild; we don't know if this needs to be injected into a new
8247   // context or if the promise type has changed.
8248   return getDerived().RebuildDependentCoawaitExpr(
8249       E->getKeywordLoc(), OperandResult.get(),
8250       cast<UnresolvedLookupExpr>(LookupResult.get()));
8251 }
8252 
8253 template<typename Derived>
8254 ExprResult
8255 TreeTransform<Derived>::TransformCoyieldExpr(CoyieldExpr *E) {
8256   ExprResult Result = getDerived().TransformInitializer(E->getOperand(),
8257                                                         /*NotCopyInit*/false);
8258   if (Result.isInvalid())
8259     return ExprError();
8260 
8261   // Always rebuild; we don't know if this needs to be injected into a new
8262   // context or if the promise type has changed.
8263   return getDerived().RebuildCoyieldExpr(E->getKeywordLoc(), Result.get());
8264 }
8265 
8266 // Objective-C Statements.
8267 
8268 template<typename Derived>
8269 StmtResult
8270 TreeTransform<Derived>::TransformObjCAtTryStmt(ObjCAtTryStmt *S) {
8271   // Transform the body of the @try.
8272   StmtResult TryBody = getDerived().TransformStmt(S->getTryBody());
8273   if (TryBody.isInvalid())
8274     return StmtError();
8275 
8276   // Transform the @catch statements (if present).
8277   bool AnyCatchChanged = false;
8278   SmallVector<Stmt*, 8> CatchStmts;
8279   for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
8280     StmtResult Catch = getDerived().TransformStmt(S->getCatchStmt(I));
8281     if (Catch.isInvalid())
8282       return StmtError();
8283     if (Catch.get() != S->getCatchStmt(I))
8284       AnyCatchChanged = true;
8285     CatchStmts.push_back(Catch.get());
8286   }
8287 
8288   // Transform the @finally statement (if present).
8289   StmtResult Finally;
8290   if (S->getFinallyStmt()) {
8291     Finally = getDerived().TransformStmt(S->getFinallyStmt());
8292     if (Finally.isInvalid())
8293       return StmtError();
8294   }
8295 
8296   // If nothing changed, just retain this statement.
8297   if (!getDerived().AlwaysRebuild() &&
8298       TryBody.get() == S->getTryBody() &&
8299       !AnyCatchChanged &&
8300       Finally.get() == S->getFinallyStmt())
8301     return S;
8302 
8303   // Build a new statement.
8304   return getDerived().RebuildObjCAtTryStmt(S->getAtTryLoc(), TryBody.get(),
8305                                            CatchStmts, Finally.get());
8306 }
8307 
8308 template<typename Derived>
8309 StmtResult
8310 TreeTransform<Derived>::TransformObjCAtCatchStmt(ObjCAtCatchStmt *S) {
8311   // Transform the @catch parameter, if there is one.
8312   VarDecl *Var = nullptr;
8313   if (VarDecl *FromVar = S->getCatchParamDecl()) {
8314     TypeSourceInfo *TSInfo = nullptr;
8315     if (FromVar->getTypeSourceInfo()) {
8316       TSInfo = getDerived().TransformType(FromVar->getTypeSourceInfo());
8317       if (!TSInfo)
8318         return StmtError();
8319     }
8320 
8321     QualType T;
8322     if (TSInfo)
8323       T = TSInfo->getType();
8324     else {
8325       T = getDerived().TransformType(FromVar->getType());
8326       if (T.isNull())
8327         return StmtError();
8328     }
8329 
8330     Var = getDerived().RebuildObjCExceptionDecl(FromVar, TSInfo, T);
8331     if (!Var)
8332       return StmtError();
8333   }
8334 
8335   StmtResult Body = getDerived().TransformStmt(S->getCatchBody());
8336   if (Body.isInvalid())
8337     return StmtError();
8338 
8339   return getDerived().RebuildObjCAtCatchStmt(S->getAtCatchLoc(),
8340                                              S->getRParenLoc(),
8341                                              Var, Body.get());
8342 }
8343 
8344 template<typename Derived>
8345 StmtResult
8346 TreeTransform<Derived>::TransformObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
8347   // Transform the body.
8348   StmtResult Body = getDerived().TransformStmt(S->getFinallyBody());
8349   if (Body.isInvalid())
8350     return StmtError();
8351 
8352   // If nothing changed, just retain this statement.
8353   if (!getDerived().AlwaysRebuild() &&
8354       Body.get() == S->getFinallyBody())
8355     return S;
8356 
8357   // Build a new statement.
8358   return getDerived().RebuildObjCAtFinallyStmt(S->getAtFinallyLoc(),
8359                                                Body.get());
8360 }
8361 
8362 template<typename Derived>
8363 StmtResult
8364 TreeTransform<Derived>::TransformObjCAtThrowStmt(ObjCAtThrowStmt *S) {
8365   ExprResult Operand;
8366   if (S->getThrowExpr()) {
8367     Operand = getDerived().TransformExpr(S->getThrowExpr());
8368     if (Operand.isInvalid())
8369       return StmtError();
8370   }
8371 
8372   if (!getDerived().AlwaysRebuild() &&
8373       Operand.get() == S->getThrowExpr())
8374     return S;
8375 
8376   return getDerived().RebuildObjCAtThrowStmt(S->getThrowLoc(), Operand.get());
8377 }
8378 
8379 template<typename Derived>
8380 StmtResult
8381 TreeTransform<Derived>::TransformObjCAtSynchronizedStmt(
8382                                                   ObjCAtSynchronizedStmt *S) {
8383   // Transform the object we are locking.
8384   ExprResult Object = getDerived().TransformExpr(S->getSynchExpr());
8385   if (Object.isInvalid())
8386     return StmtError();
8387   Object =
8388     getDerived().RebuildObjCAtSynchronizedOperand(S->getAtSynchronizedLoc(),
8389                                                   Object.get());
8390   if (Object.isInvalid())
8391     return StmtError();
8392 
8393   // Transform the body.
8394   StmtResult Body = getDerived().TransformStmt(S->getSynchBody());
8395   if (Body.isInvalid())
8396     return StmtError();
8397 
8398   // If nothing change, just retain the current statement.
8399   if (!getDerived().AlwaysRebuild() &&
8400       Object.get() == S->getSynchExpr() &&
8401       Body.get() == S->getSynchBody())
8402     return S;
8403 
8404   // Build a new statement.
8405   return getDerived().RebuildObjCAtSynchronizedStmt(S->getAtSynchronizedLoc(),
8406                                                     Object.get(), Body.get());
8407 }
8408 
8409 template<typename Derived>
8410 StmtResult
8411 TreeTransform<Derived>::TransformObjCAutoreleasePoolStmt(
8412                                               ObjCAutoreleasePoolStmt *S) {
8413   // Transform the body.
8414   StmtResult Body = getDerived().TransformStmt(S->getSubStmt());
8415   if (Body.isInvalid())
8416     return StmtError();
8417 
8418   // If nothing changed, just retain this statement.
8419   if (!getDerived().AlwaysRebuild() &&
8420       Body.get() == S->getSubStmt())
8421     return S;
8422 
8423   // Build a new statement.
8424   return getDerived().RebuildObjCAutoreleasePoolStmt(
8425                         S->getAtLoc(), Body.get());
8426 }
8427 
8428 template<typename Derived>
8429 StmtResult
8430 TreeTransform<Derived>::TransformObjCForCollectionStmt(
8431                                                   ObjCForCollectionStmt *S) {
8432   // Transform the element statement.
8433   StmtResult Element =
8434       getDerived().TransformStmt(S->getElement(), SDK_NotDiscarded);
8435   if (Element.isInvalid())
8436     return StmtError();
8437 
8438   // Transform the collection expression.
8439   ExprResult Collection = getDerived().TransformExpr(S->getCollection());
8440   if (Collection.isInvalid())
8441     return StmtError();
8442 
8443   // Transform the body.
8444   StmtResult Body = getDerived().TransformStmt(S->getBody());
8445   if (Body.isInvalid())
8446     return StmtError();
8447 
8448   // If nothing changed, just retain this statement.
8449   if (!getDerived().AlwaysRebuild() &&
8450       Element.get() == S->getElement() &&
8451       Collection.get() == S->getCollection() &&
8452       Body.get() == S->getBody())
8453     return S;
8454 
8455   // Build a new statement.
8456   return getDerived().RebuildObjCForCollectionStmt(S->getForLoc(),
8457                                                    Element.get(),
8458                                                    Collection.get(),
8459                                                    S->getRParenLoc(),
8460                                                    Body.get());
8461 }
8462 
8463 template <typename Derived>
8464 StmtResult TreeTransform<Derived>::TransformCXXCatchStmt(CXXCatchStmt *S) {
8465   // Transform the exception declaration, if any.
8466   VarDecl *Var = nullptr;
8467   if (VarDecl *ExceptionDecl = S->getExceptionDecl()) {
8468     TypeSourceInfo *T =
8469         getDerived().TransformType(ExceptionDecl->getTypeSourceInfo());
8470     if (!T)
8471       return StmtError();
8472 
8473     Var = getDerived().RebuildExceptionDecl(
8474         ExceptionDecl, T, ExceptionDecl->getInnerLocStart(),
8475         ExceptionDecl->getLocation(), ExceptionDecl->getIdentifier());
8476     if (!Var || Var->isInvalidDecl())
8477       return StmtError();
8478   }
8479 
8480   // Transform the actual exception handler.
8481   StmtResult Handler = getDerived().TransformStmt(S->getHandlerBlock());
8482   if (Handler.isInvalid())
8483     return StmtError();
8484 
8485   if (!getDerived().AlwaysRebuild() && !Var &&
8486       Handler.get() == S->getHandlerBlock())
8487     return S;
8488 
8489   return getDerived().RebuildCXXCatchStmt(S->getCatchLoc(), Var, Handler.get());
8490 }
8491 
8492 template <typename Derived>
8493 StmtResult TreeTransform<Derived>::TransformCXXTryStmt(CXXTryStmt *S) {
8494   // Transform the try block itself.
8495   StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
8496   if (TryBlock.isInvalid())
8497     return StmtError();
8498 
8499   // Transform the handlers.
8500   bool HandlerChanged = false;
8501   SmallVector<Stmt *, 8> Handlers;
8502   for (unsigned I = 0, N = S->getNumHandlers(); I != N; ++I) {
8503     StmtResult Handler = getDerived().TransformCXXCatchStmt(S->getHandler(I));
8504     if (Handler.isInvalid())
8505       return StmtError();
8506 
8507     HandlerChanged = HandlerChanged || Handler.get() != S->getHandler(I);
8508     Handlers.push_back(Handler.getAs<Stmt>());
8509   }
8510 
8511   if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
8512       !HandlerChanged)
8513     return S;
8514 
8515   return getDerived().RebuildCXXTryStmt(S->getTryLoc(), TryBlock.get(),
8516                                         Handlers);
8517 }
8518 
8519 template<typename Derived>
8520 StmtResult
8521 TreeTransform<Derived>::TransformCXXForRangeStmt(CXXForRangeStmt *S) {
8522   StmtResult Init =
8523       S->getInit() ? getDerived().TransformStmt(S->getInit()) : StmtResult();
8524   if (Init.isInvalid())
8525     return StmtError();
8526 
8527   StmtResult Range = getDerived().TransformStmt(S->getRangeStmt());
8528   if (Range.isInvalid())
8529     return StmtError();
8530 
8531   StmtResult Begin = getDerived().TransformStmt(S->getBeginStmt());
8532   if (Begin.isInvalid())
8533     return StmtError();
8534   StmtResult End = getDerived().TransformStmt(S->getEndStmt());
8535   if (End.isInvalid())
8536     return StmtError();
8537 
8538   ExprResult Cond = getDerived().TransformExpr(S->getCond());
8539   if (Cond.isInvalid())
8540     return StmtError();
8541   if (Cond.get())
8542     Cond = SemaRef.CheckBooleanCondition(S->getColonLoc(), Cond.get());
8543   if (Cond.isInvalid())
8544     return StmtError();
8545   if (Cond.get())
8546     Cond = SemaRef.MaybeCreateExprWithCleanups(Cond.get());
8547 
8548   ExprResult Inc = getDerived().TransformExpr(S->getInc());
8549   if (Inc.isInvalid())
8550     return StmtError();
8551   if (Inc.get())
8552     Inc = SemaRef.MaybeCreateExprWithCleanups(Inc.get());
8553 
8554   StmtResult LoopVar = getDerived().TransformStmt(S->getLoopVarStmt());
8555   if (LoopVar.isInvalid())
8556     return StmtError();
8557 
8558   StmtResult NewStmt = S;
8559   if (getDerived().AlwaysRebuild() ||
8560       Init.get() != S->getInit() ||
8561       Range.get() != S->getRangeStmt() ||
8562       Begin.get() != S->getBeginStmt() ||
8563       End.get() != S->getEndStmt() ||
8564       Cond.get() != S->getCond() ||
8565       Inc.get() != S->getInc() ||
8566       LoopVar.get() != S->getLoopVarStmt()) {
8567     NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
8568                                                   S->getCoawaitLoc(), Init.get(),
8569                                                   S->getColonLoc(), Range.get(),
8570                                                   Begin.get(), End.get(),
8571                                                   Cond.get(),
8572                                                   Inc.get(), LoopVar.get(),
8573                                                   S->getRParenLoc());
8574     if (NewStmt.isInvalid() && LoopVar.get() != S->getLoopVarStmt()) {
8575       // Might not have attached any initializer to the loop variable.
8576       getSema().ActOnInitializerError(
8577           cast<DeclStmt>(LoopVar.get())->getSingleDecl());
8578       return StmtError();
8579     }
8580   }
8581 
8582   StmtResult Body = getDerived().TransformStmt(S->getBody());
8583   if (Body.isInvalid())
8584     return StmtError();
8585 
8586   // Body has changed but we didn't rebuild the for-range statement. Rebuild
8587   // it now so we have a new statement to attach the body to.
8588   if (Body.get() != S->getBody() && NewStmt.get() == S) {
8589     NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
8590                                                   S->getCoawaitLoc(), Init.get(),
8591                                                   S->getColonLoc(), Range.get(),
8592                                                   Begin.get(), End.get(),
8593                                                   Cond.get(),
8594                                                   Inc.get(), LoopVar.get(),
8595                                                   S->getRParenLoc());
8596     if (NewStmt.isInvalid())
8597       return StmtError();
8598   }
8599 
8600   if (NewStmt.get() == S)
8601     return S;
8602 
8603   return FinishCXXForRangeStmt(NewStmt.get(), Body.get());
8604 }
8605 
8606 template<typename Derived>
8607 StmtResult
8608 TreeTransform<Derived>::TransformMSDependentExistsStmt(
8609                                                     MSDependentExistsStmt *S) {
8610   // Transform the nested-name-specifier, if any.
8611   NestedNameSpecifierLoc QualifierLoc;
8612   if (S->getQualifierLoc()) {
8613     QualifierLoc
8614       = getDerived().TransformNestedNameSpecifierLoc(S->getQualifierLoc());
8615     if (!QualifierLoc)
8616       return StmtError();
8617   }
8618 
8619   // Transform the declaration name.
8620   DeclarationNameInfo NameInfo = S->getNameInfo();
8621   if (NameInfo.getName()) {
8622     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
8623     if (!NameInfo.getName())
8624       return StmtError();
8625   }
8626 
8627   // Check whether anything changed.
8628   if (!getDerived().AlwaysRebuild() &&
8629       QualifierLoc == S->getQualifierLoc() &&
8630       NameInfo.getName() == S->getNameInfo().getName())
8631     return S;
8632 
8633   // Determine whether this name exists, if we can.
8634   CXXScopeSpec SS;
8635   SS.Adopt(QualifierLoc);
8636   bool Dependent = false;
8637   switch (getSema().CheckMicrosoftIfExistsSymbol(/*S=*/nullptr, SS, NameInfo)) {
8638   case Sema::IER_Exists:
8639     if (S->isIfExists())
8640       break;
8641 
8642     return new (getSema().Context) NullStmt(S->getKeywordLoc());
8643 
8644   case Sema::IER_DoesNotExist:
8645     if (S->isIfNotExists())
8646       break;
8647 
8648     return new (getSema().Context) NullStmt(S->getKeywordLoc());
8649 
8650   case Sema::IER_Dependent:
8651     Dependent = true;
8652     break;
8653 
8654   case Sema::IER_Error:
8655     return StmtError();
8656   }
8657 
8658   // We need to continue with the instantiation, so do so now.
8659   StmtResult SubStmt = getDerived().TransformCompoundStmt(S->getSubStmt());
8660   if (SubStmt.isInvalid())
8661     return StmtError();
8662 
8663   // If we have resolved the name, just transform to the substatement.
8664   if (!Dependent)
8665     return SubStmt;
8666 
8667   // The name is still dependent, so build a dependent expression again.
8668   return getDerived().RebuildMSDependentExistsStmt(S->getKeywordLoc(),
8669                                                    S->isIfExists(),
8670                                                    QualifierLoc,
8671                                                    NameInfo,
8672                                                    SubStmt.get());
8673 }
8674 
8675 template<typename Derived>
8676 ExprResult
8677 TreeTransform<Derived>::TransformMSPropertyRefExpr(MSPropertyRefExpr *E) {
8678   NestedNameSpecifierLoc QualifierLoc;
8679   if (E->getQualifierLoc()) {
8680     QualifierLoc
8681     = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
8682     if (!QualifierLoc)
8683       return ExprError();
8684   }
8685 
8686   MSPropertyDecl *PD = cast_or_null<MSPropertyDecl>(
8687     getDerived().TransformDecl(E->getMemberLoc(), E->getPropertyDecl()));
8688   if (!PD)
8689     return ExprError();
8690 
8691   ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
8692   if (Base.isInvalid())
8693     return ExprError();
8694 
8695   return new (SemaRef.getASTContext())
8696       MSPropertyRefExpr(Base.get(), PD, E->isArrow(),
8697                         SemaRef.getASTContext().PseudoObjectTy, VK_LValue,
8698                         QualifierLoc, E->getMemberLoc());
8699 }
8700 
8701 template <typename Derived>
8702 ExprResult TreeTransform<Derived>::TransformMSPropertySubscriptExpr(
8703     MSPropertySubscriptExpr *E) {
8704   auto BaseRes = getDerived().TransformExpr(E->getBase());
8705   if (BaseRes.isInvalid())
8706     return ExprError();
8707   auto IdxRes = getDerived().TransformExpr(E->getIdx());
8708   if (IdxRes.isInvalid())
8709     return ExprError();
8710 
8711   if (!getDerived().AlwaysRebuild() &&
8712       BaseRes.get() == E->getBase() &&
8713       IdxRes.get() == E->getIdx())
8714     return E;
8715 
8716   return getDerived().RebuildArraySubscriptExpr(
8717       BaseRes.get(), SourceLocation(), IdxRes.get(), E->getRBracketLoc());
8718 }
8719 
8720 template <typename Derived>
8721 StmtResult TreeTransform<Derived>::TransformSEHTryStmt(SEHTryStmt *S) {
8722   StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
8723   if (TryBlock.isInvalid())
8724     return StmtError();
8725 
8726   StmtResult Handler = getDerived().TransformSEHHandler(S->getHandler());
8727   if (Handler.isInvalid())
8728     return StmtError();
8729 
8730   if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
8731       Handler.get() == S->getHandler())
8732     return S;
8733 
8734   return getDerived().RebuildSEHTryStmt(S->getIsCXXTry(), S->getTryLoc(),
8735                                         TryBlock.get(), Handler.get());
8736 }
8737 
8738 template <typename Derived>
8739 StmtResult TreeTransform<Derived>::TransformSEHFinallyStmt(SEHFinallyStmt *S) {
8740   StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
8741   if (Block.isInvalid())
8742     return StmtError();
8743 
8744   return getDerived().RebuildSEHFinallyStmt(S->getFinallyLoc(), Block.get());
8745 }
8746 
8747 template <typename Derived>
8748 StmtResult TreeTransform<Derived>::TransformSEHExceptStmt(SEHExceptStmt *S) {
8749   ExprResult FilterExpr = getDerived().TransformExpr(S->getFilterExpr());
8750   if (FilterExpr.isInvalid())
8751     return StmtError();
8752 
8753   StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
8754   if (Block.isInvalid())
8755     return StmtError();
8756 
8757   return getDerived().RebuildSEHExceptStmt(S->getExceptLoc(), FilterExpr.get(),
8758                                            Block.get());
8759 }
8760 
8761 template <typename Derived>
8762 StmtResult TreeTransform<Derived>::TransformSEHHandler(Stmt *Handler) {
8763   if (isa<SEHFinallyStmt>(Handler))
8764     return getDerived().TransformSEHFinallyStmt(cast<SEHFinallyStmt>(Handler));
8765   else
8766     return getDerived().TransformSEHExceptStmt(cast<SEHExceptStmt>(Handler));
8767 }
8768 
8769 template<typename Derived>
8770 StmtResult
8771 TreeTransform<Derived>::TransformSEHLeaveStmt(SEHLeaveStmt *S) {
8772   return S;
8773 }
8774 
8775 //===----------------------------------------------------------------------===//
8776 // OpenMP directive transformation
8777 //===----------------------------------------------------------------------===//
8778 
8779 template <typename Derived>
8780 StmtResult
8781 TreeTransform<Derived>::TransformOMPCanonicalLoop(OMPCanonicalLoop *L) {
8782   // OMPCanonicalLoops are eliminated during transformation, since they will be
8783   // recomputed by semantic analysis of the associated OMPLoopBasedDirective
8784   // after transformation.
8785   return getDerived().TransformStmt(L->getLoopStmt());
8786 }
8787 
8788 template <typename Derived>
8789 StmtResult TreeTransform<Derived>::TransformOMPExecutableDirective(
8790     OMPExecutableDirective *D) {
8791 
8792   // Transform the clauses
8793   llvm::SmallVector<OMPClause *, 16> TClauses;
8794   ArrayRef<OMPClause *> Clauses = D->clauses();
8795   TClauses.reserve(Clauses.size());
8796   for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
8797        I != E; ++I) {
8798     if (*I) {
8799       getDerived().getSema().StartOpenMPClause((*I)->getClauseKind());
8800       OMPClause *Clause = getDerived().TransformOMPClause(*I);
8801       getDerived().getSema().EndOpenMPClause();
8802       if (Clause)
8803         TClauses.push_back(Clause);
8804     } else {
8805       TClauses.push_back(nullptr);
8806     }
8807   }
8808   StmtResult AssociatedStmt;
8809   if (D->hasAssociatedStmt() && D->getAssociatedStmt()) {
8810     getDerived().getSema().ActOnOpenMPRegionStart(D->getDirectiveKind(),
8811                                                   /*CurScope=*/nullptr);
8812     StmtResult Body;
8813     {
8814       Sema::CompoundScopeRAII CompoundScope(getSema());
8815       Stmt *CS;
8816       if (D->getDirectiveKind() == OMPD_atomic ||
8817           D->getDirectiveKind() == OMPD_critical ||
8818           D->getDirectiveKind() == OMPD_section ||
8819           D->getDirectiveKind() == OMPD_master)
8820         CS = D->getAssociatedStmt();
8821       else
8822         CS = D->getRawStmt();
8823       Body = getDerived().TransformStmt(CS);
8824       if (Body.isUsable() && isOpenMPLoopDirective(D->getDirectiveKind()) &&
8825           getSema().getLangOpts().OpenMPIRBuilder)
8826         Body = getDerived().RebuildOMPCanonicalLoop(Body.get());
8827     }
8828     AssociatedStmt =
8829         getDerived().getSema().ActOnOpenMPRegionEnd(Body, TClauses);
8830     if (AssociatedStmt.isInvalid()) {
8831       return StmtError();
8832     }
8833   }
8834   if (TClauses.size() != Clauses.size()) {
8835     return StmtError();
8836   }
8837 
8838   // Transform directive name for 'omp critical' directive.
8839   DeclarationNameInfo DirName;
8840   if (D->getDirectiveKind() == OMPD_critical) {
8841     DirName = cast<OMPCriticalDirective>(D)->getDirectiveName();
8842     DirName = getDerived().TransformDeclarationNameInfo(DirName);
8843   }
8844   OpenMPDirectiveKind CancelRegion = OMPD_unknown;
8845   if (D->getDirectiveKind() == OMPD_cancellation_point) {
8846     CancelRegion = cast<OMPCancellationPointDirective>(D)->getCancelRegion();
8847   } else if (D->getDirectiveKind() == OMPD_cancel) {
8848     CancelRegion = cast<OMPCancelDirective>(D)->getCancelRegion();
8849   }
8850 
8851   return getDerived().RebuildOMPExecutableDirective(
8852       D->getDirectiveKind(), DirName, CancelRegion, TClauses,
8853       AssociatedStmt.get(), D->getBeginLoc(), D->getEndLoc(),
8854       D->getMappedDirective());
8855 }
8856 
8857 template <typename Derived>
8858 StmtResult
8859 TreeTransform<Derived>::TransformOMPMetaDirective(OMPMetaDirective *D) {
8860   // TODO: Fix This
8861   SemaRef.Diag(D->getBeginLoc(), diag::err_omp_instantiation_not_supported)
8862       << getOpenMPDirectiveName(D->getDirectiveKind());
8863   return StmtError();
8864 }
8865 
8866 template <typename Derived>
8867 StmtResult
8868 TreeTransform<Derived>::TransformOMPParallelDirective(OMPParallelDirective *D) {
8869   DeclarationNameInfo DirName;
8870   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel, DirName, nullptr,
8871                                              D->getBeginLoc());
8872   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8873   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8874   return Res;
8875 }
8876 
8877 template <typename Derived>
8878 StmtResult
8879 TreeTransform<Derived>::TransformOMPSimdDirective(OMPSimdDirective *D) {
8880   DeclarationNameInfo DirName;
8881   getDerived().getSema().StartOpenMPDSABlock(OMPD_simd, DirName, nullptr,
8882                                              D->getBeginLoc());
8883   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8884   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8885   return Res;
8886 }
8887 
8888 template <typename Derived>
8889 StmtResult
8890 TreeTransform<Derived>::TransformOMPTileDirective(OMPTileDirective *D) {
8891   DeclarationNameInfo DirName;
8892   getDerived().getSema().StartOpenMPDSABlock(D->getDirectiveKind(), DirName,
8893                                              nullptr, D->getBeginLoc());
8894   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8895   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8896   return Res;
8897 }
8898 
8899 template <typename Derived>
8900 StmtResult
8901 TreeTransform<Derived>::TransformOMPUnrollDirective(OMPUnrollDirective *D) {
8902   DeclarationNameInfo DirName;
8903   getDerived().getSema().StartOpenMPDSABlock(D->getDirectiveKind(), DirName,
8904                                              nullptr, D->getBeginLoc());
8905   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8906   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8907   return Res;
8908 }
8909 
8910 template <typename Derived>
8911 StmtResult
8912 TreeTransform<Derived>::TransformOMPForDirective(OMPForDirective *D) {
8913   DeclarationNameInfo DirName;
8914   getDerived().getSema().StartOpenMPDSABlock(OMPD_for, DirName, nullptr,
8915                                              D->getBeginLoc());
8916   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8917   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8918   return Res;
8919 }
8920 
8921 template <typename Derived>
8922 StmtResult
8923 TreeTransform<Derived>::TransformOMPForSimdDirective(OMPForSimdDirective *D) {
8924   DeclarationNameInfo DirName;
8925   getDerived().getSema().StartOpenMPDSABlock(OMPD_for_simd, DirName, nullptr,
8926                                              D->getBeginLoc());
8927   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8928   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8929   return Res;
8930 }
8931 
8932 template <typename Derived>
8933 StmtResult
8934 TreeTransform<Derived>::TransformOMPSectionsDirective(OMPSectionsDirective *D) {
8935   DeclarationNameInfo DirName;
8936   getDerived().getSema().StartOpenMPDSABlock(OMPD_sections, DirName, nullptr,
8937                                              D->getBeginLoc());
8938   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8939   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8940   return Res;
8941 }
8942 
8943 template <typename Derived>
8944 StmtResult
8945 TreeTransform<Derived>::TransformOMPSectionDirective(OMPSectionDirective *D) {
8946   DeclarationNameInfo DirName;
8947   getDerived().getSema().StartOpenMPDSABlock(OMPD_section, DirName, nullptr,
8948                                              D->getBeginLoc());
8949   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8950   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8951   return Res;
8952 }
8953 
8954 template <typename Derived>
8955 StmtResult
8956 TreeTransform<Derived>::TransformOMPScopeDirective(OMPScopeDirective *D) {
8957   DeclarationNameInfo DirName;
8958   getDerived().getSema().StartOpenMPDSABlock(OMPD_scope, DirName, nullptr,
8959                                              D->getBeginLoc());
8960   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8961   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8962   return Res;
8963 }
8964 
8965 template <typename Derived>
8966 StmtResult
8967 TreeTransform<Derived>::TransformOMPSingleDirective(OMPSingleDirective *D) {
8968   DeclarationNameInfo DirName;
8969   getDerived().getSema().StartOpenMPDSABlock(OMPD_single, DirName, nullptr,
8970                                              D->getBeginLoc());
8971   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8972   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8973   return Res;
8974 }
8975 
8976 template <typename Derived>
8977 StmtResult
8978 TreeTransform<Derived>::TransformOMPMasterDirective(OMPMasterDirective *D) {
8979   DeclarationNameInfo DirName;
8980   getDerived().getSema().StartOpenMPDSABlock(OMPD_master, DirName, nullptr,
8981                                              D->getBeginLoc());
8982   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8983   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8984   return Res;
8985 }
8986 
8987 template <typename Derived>
8988 StmtResult
8989 TreeTransform<Derived>::TransformOMPCriticalDirective(OMPCriticalDirective *D) {
8990   getDerived().getSema().StartOpenMPDSABlock(
8991       OMPD_critical, D->getDirectiveName(), nullptr, D->getBeginLoc());
8992   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8993   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8994   return Res;
8995 }
8996 
8997 template <typename Derived>
8998 StmtResult TreeTransform<Derived>::TransformOMPParallelForDirective(
8999     OMPParallelForDirective *D) {
9000   DeclarationNameInfo DirName;
9001   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for, DirName,
9002                                              nullptr, D->getBeginLoc());
9003   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9004   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9005   return Res;
9006 }
9007 
9008 template <typename Derived>
9009 StmtResult TreeTransform<Derived>::TransformOMPParallelForSimdDirective(
9010     OMPParallelForSimdDirective *D) {
9011   DeclarationNameInfo DirName;
9012   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for_simd, DirName,
9013                                              nullptr, D->getBeginLoc());
9014   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9015   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9016   return Res;
9017 }
9018 
9019 template <typename Derived>
9020 StmtResult TreeTransform<Derived>::TransformOMPParallelMasterDirective(
9021     OMPParallelMasterDirective *D) {
9022   DeclarationNameInfo DirName;
9023   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_master, DirName,
9024                                              nullptr, D->getBeginLoc());
9025   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9026   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9027   return Res;
9028 }
9029 
9030 template <typename Derived>
9031 StmtResult TreeTransform<Derived>::TransformOMPParallelMaskedDirective(
9032     OMPParallelMaskedDirective *D) {
9033   DeclarationNameInfo DirName;
9034   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_masked, DirName,
9035                                              nullptr, D->getBeginLoc());
9036   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9037   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9038   return Res;
9039 }
9040 
9041 template <typename Derived>
9042 StmtResult TreeTransform<Derived>::TransformOMPParallelSectionsDirective(
9043     OMPParallelSectionsDirective *D) {
9044   DeclarationNameInfo DirName;
9045   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_sections, DirName,
9046                                              nullptr, D->getBeginLoc());
9047   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9048   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9049   return Res;
9050 }
9051 
9052 template <typename Derived>
9053 StmtResult
9054 TreeTransform<Derived>::TransformOMPTaskDirective(OMPTaskDirective *D) {
9055   DeclarationNameInfo DirName;
9056   getDerived().getSema().StartOpenMPDSABlock(OMPD_task, DirName, nullptr,
9057                                              D->getBeginLoc());
9058   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9059   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9060   return Res;
9061 }
9062 
9063 template <typename Derived>
9064 StmtResult TreeTransform<Derived>::TransformOMPTaskyieldDirective(
9065     OMPTaskyieldDirective *D) {
9066   DeclarationNameInfo DirName;
9067   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskyield, DirName, nullptr,
9068                                              D->getBeginLoc());
9069   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9070   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9071   return Res;
9072 }
9073 
9074 template <typename Derived>
9075 StmtResult
9076 TreeTransform<Derived>::TransformOMPBarrierDirective(OMPBarrierDirective *D) {
9077   DeclarationNameInfo DirName;
9078   getDerived().getSema().StartOpenMPDSABlock(OMPD_barrier, DirName, nullptr,
9079                                              D->getBeginLoc());
9080   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9081   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9082   return Res;
9083 }
9084 
9085 template <typename Derived>
9086 StmtResult
9087 TreeTransform<Derived>::TransformOMPTaskwaitDirective(OMPTaskwaitDirective *D) {
9088   DeclarationNameInfo DirName;
9089   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskwait, DirName, nullptr,
9090                                              D->getBeginLoc());
9091   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9092   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9093   return Res;
9094 }
9095 
9096 template <typename Derived>
9097 StmtResult
9098 TreeTransform<Derived>::TransformOMPErrorDirective(OMPErrorDirective *D) {
9099   DeclarationNameInfo DirName;
9100   getDerived().getSema().StartOpenMPDSABlock(OMPD_error, DirName, nullptr,
9101                                              D->getBeginLoc());
9102   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9103   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9104   return Res;
9105 }
9106 
9107 template <typename Derived>
9108 StmtResult TreeTransform<Derived>::TransformOMPTaskgroupDirective(
9109     OMPTaskgroupDirective *D) {
9110   DeclarationNameInfo DirName;
9111   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskgroup, DirName, nullptr,
9112                                              D->getBeginLoc());
9113   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9114   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9115   return Res;
9116 }
9117 
9118 template <typename Derived>
9119 StmtResult
9120 TreeTransform<Derived>::TransformOMPFlushDirective(OMPFlushDirective *D) {
9121   DeclarationNameInfo DirName;
9122   getDerived().getSema().StartOpenMPDSABlock(OMPD_flush, DirName, nullptr,
9123                                              D->getBeginLoc());
9124   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9125   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9126   return Res;
9127 }
9128 
9129 template <typename Derived>
9130 StmtResult
9131 TreeTransform<Derived>::TransformOMPDepobjDirective(OMPDepobjDirective *D) {
9132   DeclarationNameInfo DirName;
9133   getDerived().getSema().StartOpenMPDSABlock(OMPD_depobj, DirName, nullptr,
9134                                              D->getBeginLoc());
9135   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9136   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9137   return Res;
9138 }
9139 
9140 template <typename Derived>
9141 StmtResult
9142 TreeTransform<Derived>::TransformOMPScanDirective(OMPScanDirective *D) {
9143   DeclarationNameInfo DirName;
9144   getDerived().getSema().StartOpenMPDSABlock(OMPD_scan, DirName, nullptr,
9145                                              D->getBeginLoc());
9146   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9147   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9148   return Res;
9149 }
9150 
9151 template <typename Derived>
9152 StmtResult
9153 TreeTransform<Derived>::TransformOMPOrderedDirective(OMPOrderedDirective *D) {
9154   DeclarationNameInfo DirName;
9155   getDerived().getSema().StartOpenMPDSABlock(OMPD_ordered, DirName, nullptr,
9156                                              D->getBeginLoc());
9157   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9158   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9159   return Res;
9160 }
9161 
9162 template <typename Derived>
9163 StmtResult
9164 TreeTransform<Derived>::TransformOMPAtomicDirective(OMPAtomicDirective *D) {
9165   DeclarationNameInfo DirName;
9166   getDerived().getSema().StartOpenMPDSABlock(OMPD_atomic, DirName, nullptr,
9167                                              D->getBeginLoc());
9168   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9169   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9170   return Res;
9171 }
9172 
9173 template <typename Derived>
9174 StmtResult
9175 TreeTransform<Derived>::TransformOMPTargetDirective(OMPTargetDirective *D) {
9176   DeclarationNameInfo DirName;
9177   getDerived().getSema().StartOpenMPDSABlock(OMPD_target, DirName, nullptr,
9178                                              D->getBeginLoc());
9179   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9180   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9181   return Res;
9182 }
9183 
9184 template <typename Derived>
9185 StmtResult TreeTransform<Derived>::TransformOMPTargetDataDirective(
9186     OMPTargetDataDirective *D) {
9187   DeclarationNameInfo DirName;
9188   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_data, DirName, nullptr,
9189                                              D->getBeginLoc());
9190   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9191   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9192   return Res;
9193 }
9194 
9195 template <typename Derived>
9196 StmtResult TreeTransform<Derived>::TransformOMPTargetEnterDataDirective(
9197     OMPTargetEnterDataDirective *D) {
9198   DeclarationNameInfo DirName;
9199   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_enter_data, DirName,
9200                                              nullptr, D->getBeginLoc());
9201   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9202   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9203   return Res;
9204 }
9205 
9206 template <typename Derived>
9207 StmtResult TreeTransform<Derived>::TransformOMPTargetExitDataDirective(
9208     OMPTargetExitDataDirective *D) {
9209   DeclarationNameInfo DirName;
9210   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_exit_data, DirName,
9211                                              nullptr, D->getBeginLoc());
9212   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9213   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9214   return Res;
9215 }
9216 
9217 template <typename Derived>
9218 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelDirective(
9219     OMPTargetParallelDirective *D) {
9220   DeclarationNameInfo DirName;
9221   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel, DirName,
9222                                              nullptr, D->getBeginLoc());
9223   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9224   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9225   return Res;
9226 }
9227 
9228 template <typename Derived>
9229 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelForDirective(
9230     OMPTargetParallelForDirective *D) {
9231   DeclarationNameInfo DirName;
9232   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel_for, DirName,
9233                                              nullptr, D->getBeginLoc());
9234   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9235   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9236   return Res;
9237 }
9238 
9239 template <typename Derived>
9240 StmtResult TreeTransform<Derived>::TransformOMPTargetUpdateDirective(
9241     OMPTargetUpdateDirective *D) {
9242   DeclarationNameInfo DirName;
9243   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_update, DirName,
9244                                              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
9252 TreeTransform<Derived>::TransformOMPTeamsDirective(OMPTeamsDirective *D) {
9253   DeclarationNameInfo DirName;
9254   getDerived().getSema().StartOpenMPDSABlock(OMPD_teams, 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>::TransformOMPCancellationPointDirective(
9263     OMPCancellationPointDirective *D) {
9264   DeclarationNameInfo DirName;
9265   getDerived().getSema().StartOpenMPDSABlock(OMPD_cancellation_point, DirName,
9266                                              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>::TransformOMPCancelDirective(OMPCancelDirective *D) {
9275   DeclarationNameInfo DirName;
9276   getDerived().getSema().StartOpenMPDSABlock(OMPD_cancel, DirName, nullptr,
9277                                              D->getBeginLoc());
9278   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9279   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9280   return Res;
9281 }
9282 
9283 template <typename Derived>
9284 StmtResult
9285 TreeTransform<Derived>::TransformOMPTaskLoopDirective(OMPTaskLoopDirective *D) {
9286   DeclarationNameInfo DirName;
9287   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop, DirName, nullptr,
9288                                              D->getBeginLoc());
9289   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9290   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9291   return Res;
9292 }
9293 
9294 template <typename Derived>
9295 StmtResult TreeTransform<Derived>::TransformOMPTaskLoopSimdDirective(
9296     OMPTaskLoopSimdDirective *D) {
9297   DeclarationNameInfo DirName;
9298   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop_simd, DirName,
9299                                              nullptr, D->getBeginLoc());
9300   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9301   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9302   return Res;
9303 }
9304 
9305 template <typename Derived>
9306 StmtResult TreeTransform<Derived>::TransformOMPMasterTaskLoopDirective(
9307     OMPMasterTaskLoopDirective *D) {
9308   DeclarationNameInfo DirName;
9309   getDerived().getSema().StartOpenMPDSABlock(OMPD_master_taskloop, DirName,
9310                                              nullptr, D->getBeginLoc());
9311   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9312   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9313   return Res;
9314 }
9315 
9316 template <typename Derived>
9317 StmtResult TreeTransform<Derived>::TransformOMPMaskedTaskLoopDirective(
9318     OMPMaskedTaskLoopDirective *D) {
9319   DeclarationNameInfo DirName;
9320   getDerived().getSema().StartOpenMPDSABlock(OMPD_masked_taskloop, DirName,
9321                                              nullptr, D->getBeginLoc());
9322   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9323   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9324   return Res;
9325 }
9326 
9327 template <typename Derived>
9328 StmtResult TreeTransform<Derived>::TransformOMPMasterTaskLoopSimdDirective(
9329     OMPMasterTaskLoopSimdDirective *D) {
9330   DeclarationNameInfo DirName;
9331   getDerived().getSema().StartOpenMPDSABlock(OMPD_master_taskloop_simd, DirName,
9332                                              nullptr, D->getBeginLoc());
9333   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9334   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9335   return Res;
9336 }
9337 
9338 template <typename Derived>
9339 StmtResult TreeTransform<Derived>::TransformOMPMaskedTaskLoopSimdDirective(
9340     OMPMaskedTaskLoopSimdDirective *D) {
9341   DeclarationNameInfo DirName;
9342   getDerived().getSema().StartOpenMPDSABlock(OMPD_masked_taskloop_simd, DirName,
9343                                              nullptr, D->getBeginLoc());
9344   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9345   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9346   return Res;
9347 }
9348 
9349 template <typename Derived>
9350 StmtResult TreeTransform<Derived>::TransformOMPParallelMasterTaskLoopDirective(
9351     OMPParallelMasterTaskLoopDirective *D) {
9352   DeclarationNameInfo DirName;
9353   getDerived().getSema().StartOpenMPDSABlock(
9354       OMPD_parallel_master_taskloop, DirName, nullptr, D->getBeginLoc());
9355   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9356   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9357   return Res;
9358 }
9359 
9360 template <typename Derived>
9361 StmtResult TreeTransform<Derived>::TransformOMPParallelMaskedTaskLoopDirective(
9362     OMPParallelMaskedTaskLoopDirective *D) {
9363   DeclarationNameInfo DirName;
9364   getDerived().getSema().StartOpenMPDSABlock(
9365       OMPD_parallel_masked_taskloop, DirName, nullptr, D->getBeginLoc());
9366   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9367   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9368   return Res;
9369 }
9370 
9371 template <typename Derived>
9372 StmtResult
9373 TreeTransform<Derived>::TransformOMPParallelMasterTaskLoopSimdDirective(
9374     OMPParallelMasterTaskLoopSimdDirective *D) {
9375   DeclarationNameInfo DirName;
9376   getDerived().getSema().StartOpenMPDSABlock(
9377       OMPD_parallel_master_taskloop_simd, DirName, nullptr, D->getBeginLoc());
9378   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9379   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9380   return Res;
9381 }
9382 
9383 template <typename Derived>
9384 StmtResult
9385 TreeTransform<Derived>::TransformOMPParallelMaskedTaskLoopSimdDirective(
9386     OMPParallelMaskedTaskLoopSimdDirective *D) {
9387   DeclarationNameInfo DirName;
9388   getDerived().getSema().StartOpenMPDSABlock(
9389       OMPD_parallel_masked_taskloop_simd, DirName, nullptr, D->getBeginLoc());
9390   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9391   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9392   return Res;
9393 }
9394 
9395 template <typename Derived>
9396 StmtResult TreeTransform<Derived>::TransformOMPDistributeDirective(
9397     OMPDistributeDirective *D) {
9398   DeclarationNameInfo DirName;
9399   getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute, DirName, nullptr,
9400                                              D->getBeginLoc());
9401   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9402   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9403   return Res;
9404 }
9405 
9406 template <typename Derived>
9407 StmtResult TreeTransform<Derived>::TransformOMPDistributeParallelForDirective(
9408     OMPDistributeParallelForDirective *D) {
9409   DeclarationNameInfo DirName;
9410   getDerived().getSema().StartOpenMPDSABlock(
9411       OMPD_distribute_parallel_for, DirName, nullptr, D->getBeginLoc());
9412   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9413   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9414   return Res;
9415 }
9416 
9417 template <typename Derived>
9418 StmtResult
9419 TreeTransform<Derived>::TransformOMPDistributeParallelForSimdDirective(
9420     OMPDistributeParallelForSimdDirective *D) {
9421   DeclarationNameInfo DirName;
9422   getDerived().getSema().StartOpenMPDSABlock(
9423       OMPD_distribute_parallel_for_simd, DirName, nullptr, D->getBeginLoc());
9424   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9425   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9426   return Res;
9427 }
9428 
9429 template <typename Derived>
9430 StmtResult TreeTransform<Derived>::TransformOMPDistributeSimdDirective(
9431     OMPDistributeSimdDirective *D) {
9432   DeclarationNameInfo DirName;
9433   getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute_simd, DirName,
9434                                              nullptr, D->getBeginLoc());
9435   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9436   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9437   return Res;
9438 }
9439 
9440 template <typename Derived>
9441 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelForSimdDirective(
9442     OMPTargetParallelForSimdDirective *D) {
9443   DeclarationNameInfo DirName;
9444   getDerived().getSema().StartOpenMPDSABlock(
9445       OMPD_target_parallel_for_simd, DirName, nullptr, D->getBeginLoc());
9446   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9447   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9448   return Res;
9449 }
9450 
9451 template <typename Derived>
9452 StmtResult TreeTransform<Derived>::TransformOMPTargetSimdDirective(
9453     OMPTargetSimdDirective *D) {
9454   DeclarationNameInfo DirName;
9455   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_simd, DirName, nullptr,
9456                                              D->getBeginLoc());
9457   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9458   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9459   return Res;
9460 }
9461 
9462 template <typename Derived>
9463 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeDirective(
9464     OMPTeamsDistributeDirective *D) {
9465   DeclarationNameInfo DirName;
9466   getDerived().getSema().StartOpenMPDSABlock(OMPD_teams_distribute, DirName,
9467                                              nullptr, D->getBeginLoc());
9468   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9469   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9470   return Res;
9471 }
9472 
9473 template <typename Derived>
9474 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeSimdDirective(
9475     OMPTeamsDistributeSimdDirective *D) {
9476   DeclarationNameInfo DirName;
9477   getDerived().getSema().StartOpenMPDSABlock(
9478       OMPD_teams_distribute_simd, DirName, nullptr, D->getBeginLoc());
9479   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9480   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9481   return Res;
9482 }
9483 
9484 template <typename Derived>
9485 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeParallelForSimdDirective(
9486     OMPTeamsDistributeParallelForSimdDirective *D) {
9487   DeclarationNameInfo DirName;
9488   getDerived().getSema().StartOpenMPDSABlock(
9489       OMPD_teams_distribute_parallel_for_simd, DirName, nullptr,
9490       D->getBeginLoc());
9491   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9492   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9493   return Res;
9494 }
9495 
9496 template <typename Derived>
9497 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeParallelForDirective(
9498     OMPTeamsDistributeParallelForDirective *D) {
9499   DeclarationNameInfo DirName;
9500   getDerived().getSema().StartOpenMPDSABlock(
9501       OMPD_teams_distribute_parallel_for, DirName, nullptr, D->getBeginLoc());
9502   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9503   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9504   return Res;
9505 }
9506 
9507 template <typename Derived>
9508 StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsDirective(
9509     OMPTargetTeamsDirective *D) {
9510   DeclarationNameInfo DirName;
9511   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_teams, DirName,
9512                                              nullptr, D->getBeginLoc());
9513   auto Res = getDerived().TransformOMPExecutableDirective(D);
9514   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9515   return Res;
9516 }
9517 
9518 template <typename Derived>
9519 StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsDistributeDirective(
9520     OMPTargetTeamsDistributeDirective *D) {
9521   DeclarationNameInfo DirName;
9522   getDerived().getSema().StartOpenMPDSABlock(
9523       OMPD_target_teams_distribute, DirName, nullptr, D->getBeginLoc());
9524   auto Res = getDerived().TransformOMPExecutableDirective(D);
9525   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9526   return Res;
9527 }
9528 
9529 template <typename Derived>
9530 StmtResult
9531 TreeTransform<Derived>::TransformOMPTargetTeamsDistributeParallelForDirective(
9532     OMPTargetTeamsDistributeParallelForDirective *D) {
9533   DeclarationNameInfo DirName;
9534   getDerived().getSema().StartOpenMPDSABlock(
9535       OMPD_target_teams_distribute_parallel_for, DirName, nullptr,
9536       D->getBeginLoc());
9537   auto Res = getDerived().TransformOMPExecutableDirective(D);
9538   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9539   return Res;
9540 }
9541 
9542 template <typename Derived>
9543 StmtResult TreeTransform<Derived>::
9544     TransformOMPTargetTeamsDistributeParallelForSimdDirective(
9545         OMPTargetTeamsDistributeParallelForSimdDirective *D) {
9546   DeclarationNameInfo DirName;
9547   getDerived().getSema().StartOpenMPDSABlock(
9548       OMPD_target_teams_distribute_parallel_for_simd, DirName, nullptr,
9549       D->getBeginLoc());
9550   auto Res = getDerived().TransformOMPExecutableDirective(D);
9551   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9552   return Res;
9553 }
9554 
9555 template <typename Derived>
9556 StmtResult
9557 TreeTransform<Derived>::TransformOMPTargetTeamsDistributeSimdDirective(
9558     OMPTargetTeamsDistributeSimdDirective *D) {
9559   DeclarationNameInfo DirName;
9560   getDerived().getSema().StartOpenMPDSABlock(
9561       OMPD_target_teams_distribute_simd, DirName, nullptr, D->getBeginLoc());
9562   auto Res = getDerived().TransformOMPExecutableDirective(D);
9563   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9564   return Res;
9565 }
9566 
9567 template <typename Derived>
9568 StmtResult
9569 TreeTransform<Derived>::TransformOMPInteropDirective(OMPInteropDirective *D) {
9570   DeclarationNameInfo DirName;
9571   getDerived().getSema().StartOpenMPDSABlock(OMPD_interop, DirName, nullptr,
9572                                              D->getBeginLoc());
9573   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9574   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9575   return Res;
9576 }
9577 
9578 template <typename Derived>
9579 StmtResult
9580 TreeTransform<Derived>::TransformOMPDispatchDirective(OMPDispatchDirective *D) {
9581   DeclarationNameInfo DirName;
9582   getDerived().getSema().StartOpenMPDSABlock(OMPD_dispatch, DirName, nullptr,
9583                                              D->getBeginLoc());
9584   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9585   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9586   return Res;
9587 }
9588 
9589 template <typename Derived>
9590 StmtResult
9591 TreeTransform<Derived>::TransformOMPMaskedDirective(OMPMaskedDirective *D) {
9592   DeclarationNameInfo DirName;
9593   getDerived().getSema().StartOpenMPDSABlock(OMPD_masked, DirName, nullptr,
9594                                              D->getBeginLoc());
9595   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9596   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9597   return Res;
9598 }
9599 
9600 template <typename Derived>
9601 StmtResult TreeTransform<Derived>::TransformOMPGenericLoopDirective(
9602     OMPGenericLoopDirective *D) {
9603   DeclarationNameInfo DirName;
9604   getDerived().getSema().StartOpenMPDSABlock(OMPD_loop, DirName, nullptr,
9605                                              D->getBeginLoc());
9606   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9607   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9608   return Res;
9609 }
9610 
9611 template <typename Derived>
9612 StmtResult TreeTransform<Derived>::TransformOMPTeamsGenericLoopDirective(
9613     OMPTeamsGenericLoopDirective *D) {
9614   DeclarationNameInfo DirName;
9615   getDerived().getSema().StartOpenMPDSABlock(OMPD_teams_loop, DirName, nullptr,
9616                                              D->getBeginLoc());
9617   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9618   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9619   return Res;
9620 }
9621 
9622 template <typename Derived>
9623 StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsGenericLoopDirective(
9624     OMPTargetTeamsGenericLoopDirective *D) {
9625   DeclarationNameInfo DirName;
9626   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_teams_loop, DirName,
9627                                              nullptr, D->getBeginLoc());
9628   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9629   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9630   return Res;
9631 }
9632 
9633 template <typename Derived>
9634 StmtResult TreeTransform<Derived>::TransformOMPParallelGenericLoopDirective(
9635     OMPParallelGenericLoopDirective *D) {
9636   DeclarationNameInfo DirName;
9637   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_loop, DirName,
9638                                              nullptr, D->getBeginLoc());
9639   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9640   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9641   return Res;
9642 }
9643 
9644 template <typename Derived>
9645 StmtResult
9646 TreeTransform<Derived>::TransformOMPTargetParallelGenericLoopDirective(
9647     OMPTargetParallelGenericLoopDirective *D) {
9648   DeclarationNameInfo DirName;
9649   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel_loop, DirName,
9650                                              nullptr, D->getBeginLoc());
9651   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9652   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9653   return Res;
9654 }
9655 
9656 //===----------------------------------------------------------------------===//
9657 // OpenMP clause transformation
9658 //===----------------------------------------------------------------------===//
9659 template <typename Derived>
9660 OMPClause *TreeTransform<Derived>::TransformOMPIfClause(OMPIfClause *C) {
9661   ExprResult Cond = getDerived().TransformExpr(C->getCondition());
9662   if (Cond.isInvalid())
9663     return nullptr;
9664   return getDerived().RebuildOMPIfClause(
9665       C->getNameModifier(), Cond.get(), C->getBeginLoc(), C->getLParenLoc(),
9666       C->getNameModifierLoc(), C->getColonLoc(), C->getEndLoc());
9667 }
9668 
9669 template <typename Derived>
9670 OMPClause *TreeTransform<Derived>::TransformOMPFinalClause(OMPFinalClause *C) {
9671   ExprResult Cond = getDerived().TransformExpr(C->getCondition());
9672   if (Cond.isInvalid())
9673     return nullptr;
9674   return getDerived().RebuildOMPFinalClause(Cond.get(), C->getBeginLoc(),
9675                                             C->getLParenLoc(), C->getEndLoc());
9676 }
9677 
9678 template <typename Derived>
9679 OMPClause *
9680 TreeTransform<Derived>::TransformOMPNumThreadsClause(OMPNumThreadsClause *C) {
9681   ExprResult NumThreads = getDerived().TransformExpr(C->getNumThreads());
9682   if (NumThreads.isInvalid())
9683     return nullptr;
9684   return getDerived().RebuildOMPNumThreadsClause(
9685       NumThreads.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9686 }
9687 
9688 template <typename Derived>
9689 OMPClause *
9690 TreeTransform<Derived>::TransformOMPSafelenClause(OMPSafelenClause *C) {
9691   ExprResult E = getDerived().TransformExpr(C->getSafelen());
9692   if (E.isInvalid())
9693     return nullptr;
9694   return getDerived().RebuildOMPSafelenClause(
9695       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9696 }
9697 
9698 template <typename Derived>
9699 OMPClause *
9700 TreeTransform<Derived>::TransformOMPAllocatorClause(OMPAllocatorClause *C) {
9701   ExprResult E = getDerived().TransformExpr(C->getAllocator());
9702   if (E.isInvalid())
9703     return nullptr;
9704   return getDerived().RebuildOMPAllocatorClause(
9705       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9706 }
9707 
9708 template <typename Derived>
9709 OMPClause *
9710 TreeTransform<Derived>::TransformOMPSimdlenClause(OMPSimdlenClause *C) {
9711   ExprResult E = getDerived().TransformExpr(C->getSimdlen());
9712   if (E.isInvalid())
9713     return nullptr;
9714   return getDerived().RebuildOMPSimdlenClause(
9715       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9716 }
9717 
9718 template <typename Derived>
9719 OMPClause *TreeTransform<Derived>::TransformOMPSizesClause(OMPSizesClause *C) {
9720   SmallVector<Expr *, 4> TransformedSizes;
9721   TransformedSizes.reserve(C->getNumSizes());
9722   bool Changed = false;
9723   for (Expr *E : C->getSizesRefs()) {
9724     if (!E) {
9725       TransformedSizes.push_back(nullptr);
9726       continue;
9727     }
9728 
9729     ExprResult T = getDerived().TransformExpr(E);
9730     if (T.isInvalid())
9731       return nullptr;
9732     if (E != T.get())
9733       Changed = true;
9734     TransformedSizes.push_back(T.get());
9735   }
9736 
9737   if (!Changed && !getDerived().AlwaysRebuild())
9738     return C;
9739   return RebuildOMPSizesClause(TransformedSizes, C->getBeginLoc(),
9740                                C->getLParenLoc(), C->getEndLoc());
9741 }
9742 
9743 template <typename Derived>
9744 OMPClause *TreeTransform<Derived>::TransformOMPFullClause(OMPFullClause *C) {
9745   if (!getDerived().AlwaysRebuild())
9746     return C;
9747   return RebuildOMPFullClause(C->getBeginLoc(), C->getEndLoc());
9748 }
9749 
9750 template <typename Derived>
9751 OMPClause *
9752 TreeTransform<Derived>::TransformOMPPartialClause(OMPPartialClause *C) {
9753   ExprResult T = getDerived().TransformExpr(C->getFactor());
9754   if (T.isInvalid())
9755     return nullptr;
9756   Expr *Factor = T.get();
9757   bool Changed = Factor != C->getFactor();
9758 
9759   if (!Changed && !getDerived().AlwaysRebuild())
9760     return C;
9761   return RebuildOMPPartialClause(Factor, C->getBeginLoc(), C->getLParenLoc(),
9762                                  C->getEndLoc());
9763 }
9764 
9765 template <typename Derived>
9766 OMPClause *
9767 TreeTransform<Derived>::TransformOMPCollapseClause(OMPCollapseClause *C) {
9768   ExprResult E = getDerived().TransformExpr(C->getNumForLoops());
9769   if (E.isInvalid())
9770     return nullptr;
9771   return getDerived().RebuildOMPCollapseClause(
9772       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9773 }
9774 
9775 template <typename Derived>
9776 OMPClause *
9777 TreeTransform<Derived>::TransformOMPDefaultClause(OMPDefaultClause *C) {
9778   return getDerived().RebuildOMPDefaultClause(
9779       C->getDefaultKind(), C->getDefaultKindKwLoc(), C->getBeginLoc(),
9780       C->getLParenLoc(), C->getEndLoc());
9781 }
9782 
9783 template <typename Derived>
9784 OMPClause *
9785 TreeTransform<Derived>::TransformOMPProcBindClause(OMPProcBindClause *C) {
9786   return getDerived().RebuildOMPProcBindClause(
9787       C->getProcBindKind(), C->getProcBindKindKwLoc(), C->getBeginLoc(),
9788       C->getLParenLoc(), C->getEndLoc());
9789 }
9790 
9791 template <typename Derived>
9792 OMPClause *
9793 TreeTransform<Derived>::TransformOMPScheduleClause(OMPScheduleClause *C) {
9794   ExprResult E = getDerived().TransformExpr(C->getChunkSize());
9795   if (E.isInvalid())
9796     return nullptr;
9797   return getDerived().RebuildOMPScheduleClause(
9798       C->getFirstScheduleModifier(), C->getSecondScheduleModifier(),
9799       C->getScheduleKind(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
9800       C->getFirstScheduleModifierLoc(), C->getSecondScheduleModifierLoc(),
9801       C->getScheduleKindLoc(), C->getCommaLoc(), C->getEndLoc());
9802 }
9803 
9804 template <typename Derived>
9805 OMPClause *
9806 TreeTransform<Derived>::TransformOMPOrderedClause(OMPOrderedClause *C) {
9807   ExprResult E;
9808   if (auto *Num = C->getNumForLoops()) {
9809     E = getDerived().TransformExpr(Num);
9810     if (E.isInvalid())
9811       return nullptr;
9812   }
9813   return getDerived().RebuildOMPOrderedClause(C->getBeginLoc(), C->getEndLoc(),
9814                                               C->getLParenLoc(), E.get());
9815 }
9816 
9817 template <typename Derived>
9818 OMPClause *
9819 TreeTransform<Derived>::TransformOMPDetachClause(OMPDetachClause *C) {
9820   ExprResult E;
9821   if (Expr *Evt = C->getEventHandler()) {
9822     E = getDerived().TransformExpr(Evt);
9823     if (E.isInvalid())
9824       return nullptr;
9825   }
9826   return getDerived().RebuildOMPDetachClause(E.get(), C->getBeginLoc(),
9827                                              C->getLParenLoc(), C->getEndLoc());
9828 }
9829 
9830 template <typename Derived>
9831 OMPClause *
9832 TreeTransform<Derived>::TransformOMPNowaitClause(OMPNowaitClause *C) {
9833   // No need to rebuild this clause, no template-dependent parameters.
9834   return C;
9835 }
9836 
9837 template <typename Derived>
9838 OMPClause *
9839 TreeTransform<Derived>::TransformOMPUntiedClause(OMPUntiedClause *C) {
9840   // No need to rebuild this clause, no template-dependent parameters.
9841   return C;
9842 }
9843 
9844 template <typename Derived>
9845 OMPClause *
9846 TreeTransform<Derived>::TransformOMPMergeableClause(OMPMergeableClause *C) {
9847   // No need to rebuild this clause, no template-dependent parameters.
9848   return C;
9849 }
9850 
9851 template <typename Derived>
9852 OMPClause *TreeTransform<Derived>::TransformOMPReadClause(OMPReadClause *C) {
9853   // No need to rebuild this clause, no template-dependent parameters.
9854   return C;
9855 }
9856 
9857 template <typename Derived>
9858 OMPClause *TreeTransform<Derived>::TransformOMPWriteClause(OMPWriteClause *C) {
9859   // No need to rebuild this clause, no template-dependent parameters.
9860   return C;
9861 }
9862 
9863 template <typename Derived>
9864 OMPClause *
9865 TreeTransform<Derived>::TransformOMPUpdateClause(OMPUpdateClause *C) {
9866   // No need to rebuild this clause, no template-dependent parameters.
9867   return C;
9868 }
9869 
9870 template <typename Derived>
9871 OMPClause *
9872 TreeTransform<Derived>::TransformOMPCaptureClause(OMPCaptureClause *C) {
9873   // No need to rebuild this clause, no template-dependent parameters.
9874   return C;
9875 }
9876 
9877 template <typename Derived>
9878 OMPClause *
9879 TreeTransform<Derived>::TransformOMPCompareClause(OMPCompareClause *C) {
9880   // No need to rebuild this clause, no template-dependent parameters.
9881   return C;
9882 }
9883 
9884 template <typename Derived>
9885 OMPClause *TreeTransform<Derived>::TransformOMPFailClause(OMPFailClause *C) {
9886   // No need to rebuild this clause, no template-dependent parameters.
9887   return C;
9888 }
9889 
9890 template <typename Derived>
9891 OMPClause *
9892 TreeTransform<Derived>::TransformOMPSeqCstClause(OMPSeqCstClause *C) {
9893   // No need to rebuild this clause, no template-dependent parameters.
9894   return C;
9895 }
9896 
9897 template <typename Derived>
9898 OMPClause *
9899 TreeTransform<Derived>::TransformOMPAcqRelClause(OMPAcqRelClause *C) {
9900   // No need to rebuild this clause, no template-dependent parameters.
9901   return C;
9902 }
9903 
9904 template <typename Derived>
9905 OMPClause *
9906 TreeTransform<Derived>::TransformOMPAcquireClause(OMPAcquireClause *C) {
9907   // No need to rebuild this clause, no template-dependent parameters.
9908   return C;
9909 }
9910 
9911 template <typename Derived>
9912 OMPClause *
9913 TreeTransform<Derived>::TransformOMPReleaseClause(OMPReleaseClause *C) {
9914   // No need to rebuild this clause, no template-dependent parameters.
9915   return C;
9916 }
9917 
9918 template <typename Derived>
9919 OMPClause *
9920 TreeTransform<Derived>::TransformOMPRelaxedClause(OMPRelaxedClause *C) {
9921   // No need to rebuild this clause, no template-dependent parameters.
9922   return C;
9923 }
9924 
9925 template <typename Derived>
9926 OMPClause *
9927 TreeTransform<Derived>::TransformOMPThreadsClause(OMPThreadsClause *C) {
9928   // No need to rebuild this clause, no template-dependent parameters.
9929   return C;
9930 }
9931 
9932 template <typename Derived>
9933 OMPClause *TreeTransform<Derived>::TransformOMPSIMDClause(OMPSIMDClause *C) {
9934   // No need to rebuild this clause, no template-dependent parameters.
9935   return C;
9936 }
9937 
9938 template <typename Derived>
9939 OMPClause *
9940 TreeTransform<Derived>::TransformOMPNogroupClause(OMPNogroupClause *C) {
9941   // No need to rebuild this clause, no template-dependent parameters.
9942   return C;
9943 }
9944 
9945 template <typename Derived>
9946 OMPClause *TreeTransform<Derived>::TransformOMPInitClause(OMPInitClause *C) {
9947   ExprResult IVR = getDerived().TransformExpr(C->getInteropVar());
9948   if (IVR.isInvalid())
9949     return nullptr;
9950 
9951   OMPInteropInfo InteropInfo(C->getIsTarget(), C->getIsTargetSync());
9952   InteropInfo.PreferTypes.reserve(C->varlist_size() - 1);
9953   for (Expr *E : llvm::drop_begin(C->varlists())) {
9954     ExprResult ER = getDerived().TransformExpr(cast<Expr>(E));
9955     if (ER.isInvalid())
9956       return nullptr;
9957     InteropInfo.PreferTypes.push_back(ER.get());
9958   }
9959   return getDerived().RebuildOMPInitClause(IVR.get(), InteropInfo,
9960                                            C->getBeginLoc(), C->getLParenLoc(),
9961                                            C->getVarLoc(), C->getEndLoc());
9962 }
9963 
9964 template <typename Derived>
9965 OMPClause *TreeTransform<Derived>::TransformOMPUseClause(OMPUseClause *C) {
9966   ExprResult ER = getDerived().TransformExpr(C->getInteropVar());
9967   if (ER.isInvalid())
9968     return nullptr;
9969   return getDerived().RebuildOMPUseClause(ER.get(), C->getBeginLoc(),
9970                                           C->getLParenLoc(), C->getVarLoc(),
9971                                           C->getEndLoc());
9972 }
9973 
9974 template <typename Derived>
9975 OMPClause *
9976 TreeTransform<Derived>::TransformOMPDestroyClause(OMPDestroyClause *C) {
9977   ExprResult ER;
9978   if (Expr *IV = C->getInteropVar()) {
9979     ER = getDerived().TransformExpr(IV);
9980     if (ER.isInvalid())
9981       return nullptr;
9982   }
9983   return getDerived().RebuildOMPDestroyClause(ER.get(), C->getBeginLoc(),
9984                                               C->getLParenLoc(), C->getVarLoc(),
9985                                               C->getEndLoc());
9986 }
9987 
9988 template <typename Derived>
9989 OMPClause *
9990 TreeTransform<Derived>::TransformOMPNovariantsClause(OMPNovariantsClause *C) {
9991   ExprResult Cond = getDerived().TransformExpr(C->getCondition());
9992   if (Cond.isInvalid())
9993     return nullptr;
9994   return getDerived().RebuildOMPNovariantsClause(
9995       Cond.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9996 }
9997 
9998 template <typename Derived>
9999 OMPClause *
10000 TreeTransform<Derived>::TransformOMPNocontextClause(OMPNocontextClause *C) {
10001   ExprResult Cond = getDerived().TransformExpr(C->getCondition());
10002   if (Cond.isInvalid())
10003     return nullptr;
10004   return getDerived().RebuildOMPNocontextClause(
10005       Cond.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10006 }
10007 
10008 template <typename Derived>
10009 OMPClause *
10010 TreeTransform<Derived>::TransformOMPFilterClause(OMPFilterClause *C) {
10011   ExprResult ThreadID = getDerived().TransformExpr(C->getThreadID());
10012   if (ThreadID.isInvalid())
10013     return nullptr;
10014   return getDerived().RebuildOMPFilterClause(ThreadID.get(), C->getBeginLoc(),
10015                                              C->getLParenLoc(), C->getEndLoc());
10016 }
10017 
10018 template <typename Derived>
10019 OMPClause *TreeTransform<Derived>::TransformOMPAlignClause(OMPAlignClause *C) {
10020   ExprResult E = getDerived().TransformExpr(C->getAlignment());
10021   if (E.isInvalid())
10022     return nullptr;
10023   return getDerived().RebuildOMPAlignClause(E.get(), C->getBeginLoc(),
10024                                             C->getLParenLoc(), C->getEndLoc());
10025 }
10026 
10027 template <typename Derived>
10028 OMPClause *TreeTransform<Derived>::TransformOMPUnifiedAddressClause(
10029     OMPUnifiedAddressClause *C) {
10030   llvm_unreachable("unified_address clause cannot appear in dependent context");
10031 }
10032 
10033 template <typename Derived>
10034 OMPClause *TreeTransform<Derived>::TransformOMPUnifiedSharedMemoryClause(
10035     OMPUnifiedSharedMemoryClause *C) {
10036   llvm_unreachable(
10037       "unified_shared_memory clause cannot appear in dependent context");
10038 }
10039 
10040 template <typename Derived>
10041 OMPClause *TreeTransform<Derived>::TransformOMPReverseOffloadClause(
10042     OMPReverseOffloadClause *C) {
10043   llvm_unreachable("reverse_offload clause cannot appear in dependent context");
10044 }
10045 
10046 template <typename Derived>
10047 OMPClause *TreeTransform<Derived>::TransformOMPDynamicAllocatorsClause(
10048     OMPDynamicAllocatorsClause *C) {
10049   llvm_unreachable(
10050       "dynamic_allocators clause cannot appear in dependent context");
10051 }
10052 
10053 template <typename Derived>
10054 OMPClause *TreeTransform<Derived>::TransformOMPAtomicDefaultMemOrderClause(
10055     OMPAtomicDefaultMemOrderClause *C) {
10056   llvm_unreachable(
10057       "atomic_default_mem_order clause cannot appear in dependent context");
10058 }
10059 
10060 template <typename Derived>
10061 OMPClause *TreeTransform<Derived>::TransformOMPAtClause(OMPAtClause *C) {
10062   return getDerived().RebuildOMPAtClause(C->getAtKind(), C->getAtKindKwLoc(),
10063                                          C->getBeginLoc(), C->getLParenLoc(),
10064                                          C->getEndLoc());
10065 }
10066 
10067 template <typename Derived>
10068 OMPClause *
10069 TreeTransform<Derived>::TransformOMPSeverityClause(OMPSeverityClause *C) {
10070   return getDerived().RebuildOMPSeverityClause(
10071       C->getSeverityKind(), C->getSeverityKindKwLoc(), C->getBeginLoc(),
10072       C->getLParenLoc(), C->getEndLoc());
10073 }
10074 
10075 template <typename Derived>
10076 OMPClause *
10077 TreeTransform<Derived>::TransformOMPMessageClause(OMPMessageClause *C) {
10078   ExprResult E = getDerived().TransformExpr(C->getMessageString());
10079   if (E.isInvalid())
10080     return nullptr;
10081   return getDerived().RebuildOMPMessageClause(
10082       C->getMessageString(), C->getBeginLoc(), C->getLParenLoc(),
10083       C->getEndLoc());
10084 }
10085 
10086 template <typename Derived>
10087 OMPClause *
10088 TreeTransform<Derived>::TransformOMPPrivateClause(OMPPrivateClause *C) {
10089   llvm::SmallVector<Expr *, 16> Vars;
10090   Vars.reserve(C->varlist_size());
10091   for (auto *VE : C->varlists()) {
10092     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10093     if (EVar.isInvalid())
10094       return nullptr;
10095     Vars.push_back(EVar.get());
10096   }
10097   return getDerived().RebuildOMPPrivateClause(
10098       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10099 }
10100 
10101 template <typename Derived>
10102 OMPClause *TreeTransform<Derived>::TransformOMPFirstprivateClause(
10103     OMPFirstprivateClause *C) {
10104   llvm::SmallVector<Expr *, 16> Vars;
10105   Vars.reserve(C->varlist_size());
10106   for (auto *VE : C->varlists()) {
10107     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10108     if (EVar.isInvalid())
10109       return nullptr;
10110     Vars.push_back(EVar.get());
10111   }
10112   return getDerived().RebuildOMPFirstprivateClause(
10113       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10114 }
10115 
10116 template <typename Derived>
10117 OMPClause *
10118 TreeTransform<Derived>::TransformOMPLastprivateClause(OMPLastprivateClause *C) {
10119   llvm::SmallVector<Expr *, 16> Vars;
10120   Vars.reserve(C->varlist_size());
10121   for (auto *VE : C->varlists()) {
10122     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10123     if (EVar.isInvalid())
10124       return nullptr;
10125     Vars.push_back(EVar.get());
10126   }
10127   return getDerived().RebuildOMPLastprivateClause(
10128       Vars, C->getKind(), C->getKindLoc(), C->getColonLoc(), C->getBeginLoc(),
10129       C->getLParenLoc(), C->getEndLoc());
10130 }
10131 
10132 template <typename Derived>
10133 OMPClause *
10134 TreeTransform<Derived>::TransformOMPSharedClause(OMPSharedClause *C) {
10135   llvm::SmallVector<Expr *, 16> Vars;
10136   Vars.reserve(C->varlist_size());
10137   for (auto *VE : C->varlists()) {
10138     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10139     if (EVar.isInvalid())
10140       return nullptr;
10141     Vars.push_back(EVar.get());
10142   }
10143   return getDerived().RebuildOMPSharedClause(Vars, C->getBeginLoc(),
10144                                              C->getLParenLoc(), C->getEndLoc());
10145 }
10146 
10147 template <typename Derived>
10148 OMPClause *
10149 TreeTransform<Derived>::TransformOMPReductionClause(OMPReductionClause *C) {
10150   llvm::SmallVector<Expr *, 16> Vars;
10151   Vars.reserve(C->varlist_size());
10152   for (auto *VE : C->varlists()) {
10153     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10154     if (EVar.isInvalid())
10155       return nullptr;
10156     Vars.push_back(EVar.get());
10157   }
10158   CXXScopeSpec ReductionIdScopeSpec;
10159   ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
10160 
10161   DeclarationNameInfo NameInfo = C->getNameInfo();
10162   if (NameInfo.getName()) {
10163     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
10164     if (!NameInfo.getName())
10165       return nullptr;
10166   }
10167   // Build a list of all UDR decls with the same names ranged by the Scopes.
10168   // The Scope boundary is a duplication of the previous decl.
10169   llvm::SmallVector<Expr *, 16> UnresolvedReductions;
10170   for (auto *E : C->reduction_ops()) {
10171     // Transform all the decls.
10172     if (E) {
10173       auto *ULE = cast<UnresolvedLookupExpr>(E);
10174       UnresolvedSet<8> Decls;
10175       for (auto *D : ULE->decls()) {
10176         NamedDecl *InstD =
10177             cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
10178         Decls.addDecl(InstD, InstD->getAccess());
10179       }
10180       UnresolvedReductions.push_back(
10181        UnresolvedLookupExpr::Create(
10182           SemaRef.Context, /*NamingClass=*/nullptr,
10183           ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context),
10184           NameInfo, /*ADL=*/true, ULE->isOverloaded(),
10185           Decls.begin(), Decls.end()));
10186     } else
10187       UnresolvedReductions.push_back(nullptr);
10188   }
10189   return getDerived().RebuildOMPReductionClause(
10190       Vars, C->getModifier(), C->getBeginLoc(), C->getLParenLoc(),
10191       C->getModifierLoc(), C->getColonLoc(), C->getEndLoc(),
10192       ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
10193 }
10194 
10195 template <typename Derived>
10196 OMPClause *TreeTransform<Derived>::TransformOMPTaskReductionClause(
10197     OMPTaskReductionClause *C) {
10198   llvm::SmallVector<Expr *, 16> Vars;
10199   Vars.reserve(C->varlist_size());
10200   for (auto *VE : C->varlists()) {
10201     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10202     if (EVar.isInvalid())
10203       return nullptr;
10204     Vars.push_back(EVar.get());
10205   }
10206   CXXScopeSpec ReductionIdScopeSpec;
10207   ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
10208 
10209   DeclarationNameInfo NameInfo = C->getNameInfo();
10210   if (NameInfo.getName()) {
10211     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
10212     if (!NameInfo.getName())
10213       return nullptr;
10214   }
10215   // Build a list of all UDR decls with the same names ranged by the Scopes.
10216   // The Scope boundary is a duplication of the previous decl.
10217   llvm::SmallVector<Expr *, 16> UnresolvedReductions;
10218   for (auto *E : C->reduction_ops()) {
10219     // Transform all the decls.
10220     if (E) {
10221       auto *ULE = cast<UnresolvedLookupExpr>(E);
10222       UnresolvedSet<8> Decls;
10223       for (auto *D : ULE->decls()) {
10224         NamedDecl *InstD =
10225             cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
10226         Decls.addDecl(InstD, InstD->getAccess());
10227       }
10228       UnresolvedReductions.push_back(UnresolvedLookupExpr::Create(
10229           SemaRef.Context, /*NamingClass=*/nullptr,
10230           ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), NameInfo,
10231           /*ADL=*/true, ULE->isOverloaded(), Decls.begin(), Decls.end()));
10232     } else
10233       UnresolvedReductions.push_back(nullptr);
10234   }
10235   return getDerived().RebuildOMPTaskReductionClause(
10236       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
10237       C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
10238 }
10239 
10240 template <typename Derived>
10241 OMPClause *
10242 TreeTransform<Derived>::TransformOMPInReductionClause(OMPInReductionClause *C) {
10243   llvm::SmallVector<Expr *, 16> Vars;
10244   Vars.reserve(C->varlist_size());
10245   for (auto *VE : C->varlists()) {
10246     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10247     if (EVar.isInvalid())
10248       return nullptr;
10249     Vars.push_back(EVar.get());
10250   }
10251   CXXScopeSpec ReductionIdScopeSpec;
10252   ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
10253 
10254   DeclarationNameInfo NameInfo = C->getNameInfo();
10255   if (NameInfo.getName()) {
10256     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
10257     if (!NameInfo.getName())
10258       return nullptr;
10259   }
10260   // Build a list of all UDR decls with the same names ranged by the Scopes.
10261   // The Scope boundary is a duplication of the previous decl.
10262   llvm::SmallVector<Expr *, 16> UnresolvedReductions;
10263   for (auto *E : C->reduction_ops()) {
10264     // Transform all the decls.
10265     if (E) {
10266       auto *ULE = cast<UnresolvedLookupExpr>(E);
10267       UnresolvedSet<8> Decls;
10268       for (auto *D : ULE->decls()) {
10269         NamedDecl *InstD =
10270             cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
10271         Decls.addDecl(InstD, InstD->getAccess());
10272       }
10273       UnresolvedReductions.push_back(UnresolvedLookupExpr::Create(
10274           SemaRef.Context, /*NamingClass=*/nullptr,
10275           ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), NameInfo,
10276           /*ADL=*/true, ULE->isOverloaded(), Decls.begin(), Decls.end()));
10277     } else
10278       UnresolvedReductions.push_back(nullptr);
10279   }
10280   return getDerived().RebuildOMPInReductionClause(
10281       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
10282       C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
10283 }
10284 
10285 template <typename Derived>
10286 OMPClause *
10287 TreeTransform<Derived>::TransformOMPLinearClause(OMPLinearClause *C) {
10288   llvm::SmallVector<Expr *, 16> Vars;
10289   Vars.reserve(C->varlist_size());
10290   for (auto *VE : C->varlists()) {
10291     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10292     if (EVar.isInvalid())
10293       return nullptr;
10294     Vars.push_back(EVar.get());
10295   }
10296   ExprResult Step = getDerived().TransformExpr(C->getStep());
10297   if (Step.isInvalid())
10298     return nullptr;
10299   return getDerived().RebuildOMPLinearClause(
10300       Vars, Step.get(), C->getBeginLoc(), C->getLParenLoc(), C->getModifier(),
10301       C->getModifierLoc(), C->getColonLoc(), C->getStepModifierLoc(),
10302       C->getEndLoc());
10303 }
10304 
10305 template <typename Derived>
10306 OMPClause *
10307 TreeTransform<Derived>::TransformOMPAlignedClause(OMPAlignedClause *C) {
10308   llvm::SmallVector<Expr *, 16> Vars;
10309   Vars.reserve(C->varlist_size());
10310   for (auto *VE : C->varlists()) {
10311     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10312     if (EVar.isInvalid())
10313       return nullptr;
10314     Vars.push_back(EVar.get());
10315   }
10316   ExprResult Alignment = getDerived().TransformExpr(C->getAlignment());
10317   if (Alignment.isInvalid())
10318     return nullptr;
10319   return getDerived().RebuildOMPAlignedClause(
10320       Vars, Alignment.get(), C->getBeginLoc(), C->getLParenLoc(),
10321       C->getColonLoc(), C->getEndLoc());
10322 }
10323 
10324 template <typename Derived>
10325 OMPClause *
10326 TreeTransform<Derived>::TransformOMPCopyinClause(OMPCopyinClause *C) {
10327   llvm::SmallVector<Expr *, 16> Vars;
10328   Vars.reserve(C->varlist_size());
10329   for (auto *VE : C->varlists()) {
10330     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10331     if (EVar.isInvalid())
10332       return nullptr;
10333     Vars.push_back(EVar.get());
10334   }
10335   return getDerived().RebuildOMPCopyinClause(Vars, C->getBeginLoc(),
10336                                              C->getLParenLoc(), C->getEndLoc());
10337 }
10338 
10339 template <typename Derived>
10340 OMPClause *
10341 TreeTransform<Derived>::TransformOMPCopyprivateClause(OMPCopyprivateClause *C) {
10342   llvm::SmallVector<Expr *, 16> Vars;
10343   Vars.reserve(C->varlist_size());
10344   for (auto *VE : C->varlists()) {
10345     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10346     if (EVar.isInvalid())
10347       return nullptr;
10348     Vars.push_back(EVar.get());
10349   }
10350   return getDerived().RebuildOMPCopyprivateClause(
10351       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10352 }
10353 
10354 template <typename Derived>
10355 OMPClause *TreeTransform<Derived>::TransformOMPFlushClause(OMPFlushClause *C) {
10356   llvm::SmallVector<Expr *, 16> Vars;
10357   Vars.reserve(C->varlist_size());
10358   for (auto *VE : C->varlists()) {
10359     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10360     if (EVar.isInvalid())
10361       return nullptr;
10362     Vars.push_back(EVar.get());
10363   }
10364   return getDerived().RebuildOMPFlushClause(Vars, C->getBeginLoc(),
10365                                             C->getLParenLoc(), C->getEndLoc());
10366 }
10367 
10368 template <typename Derived>
10369 OMPClause *
10370 TreeTransform<Derived>::TransformOMPDepobjClause(OMPDepobjClause *C) {
10371   ExprResult E = getDerived().TransformExpr(C->getDepobj());
10372   if (E.isInvalid())
10373     return nullptr;
10374   return getDerived().RebuildOMPDepobjClause(E.get(), C->getBeginLoc(),
10375                                              C->getLParenLoc(), C->getEndLoc());
10376 }
10377 
10378 template <typename Derived>
10379 OMPClause *
10380 TreeTransform<Derived>::TransformOMPDependClause(OMPDependClause *C) {
10381   llvm::SmallVector<Expr *, 16> Vars;
10382   Expr *DepModifier = C->getModifier();
10383   if (DepModifier) {
10384     ExprResult DepModRes = getDerived().TransformExpr(DepModifier);
10385     if (DepModRes.isInvalid())
10386       return nullptr;
10387     DepModifier = DepModRes.get();
10388   }
10389   Vars.reserve(C->varlist_size());
10390   for (auto *VE : C->varlists()) {
10391     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10392     if (EVar.isInvalid())
10393       return nullptr;
10394     Vars.push_back(EVar.get());
10395   }
10396   return getDerived().RebuildOMPDependClause(
10397       {C->getDependencyKind(), C->getDependencyLoc(), C->getColonLoc(),
10398        C->getOmpAllMemoryLoc()},
10399       DepModifier, Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10400 }
10401 
10402 template <typename Derived>
10403 OMPClause *
10404 TreeTransform<Derived>::TransformOMPDeviceClause(OMPDeviceClause *C) {
10405   ExprResult E = getDerived().TransformExpr(C->getDevice());
10406   if (E.isInvalid())
10407     return nullptr;
10408   return getDerived().RebuildOMPDeviceClause(
10409       C->getModifier(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
10410       C->getModifierLoc(), C->getEndLoc());
10411 }
10412 
10413 template <typename Derived, class T>
10414 bool transformOMPMappableExprListClause(
10415     TreeTransform<Derived> &TT, OMPMappableExprListClause<T> *C,
10416     llvm::SmallVectorImpl<Expr *> &Vars, CXXScopeSpec &MapperIdScopeSpec,
10417     DeclarationNameInfo &MapperIdInfo,
10418     llvm::SmallVectorImpl<Expr *> &UnresolvedMappers) {
10419   // Transform expressions in the list.
10420   Vars.reserve(C->varlist_size());
10421   for (auto *VE : C->varlists()) {
10422     ExprResult EVar = TT.getDerived().TransformExpr(cast<Expr>(VE));
10423     if (EVar.isInvalid())
10424       return true;
10425     Vars.push_back(EVar.get());
10426   }
10427   // Transform mapper scope specifier and identifier.
10428   NestedNameSpecifierLoc QualifierLoc;
10429   if (C->getMapperQualifierLoc()) {
10430     QualifierLoc = TT.getDerived().TransformNestedNameSpecifierLoc(
10431         C->getMapperQualifierLoc());
10432     if (!QualifierLoc)
10433       return true;
10434   }
10435   MapperIdScopeSpec.Adopt(QualifierLoc);
10436   MapperIdInfo = C->getMapperIdInfo();
10437   if (MapperIdInfo.getName()) {
10438     MapperIdInfo = TT.getDerived().TransformDeclarationNameInfo(MapperIdInfo);
10439     if (!MapperIdInfo.getName())
10440       return true;
10441   }
10442   // Build a list of all candidate OMPDeclareMapperDecls, which is provided by
10443   // the previous user-defined mapper lookup in dependent environment.
10444   for (auto *E : C->mapperlists()) {
10445     // Transform all the decls.
10446     if (E) {
10447       auto *ULE = cast<UnresolvedLookupExpr>(E);
10448       UnresolvedSet<8> Decls;
10449       for (auto *D : ULE->decls()) {
10450         NamedDecl *InstD =
10451             cast<NamedDecl>(TT.getDerived().TransformDecl(E->getExprLoc(), D));
10452         Decls.addDecl(InstD, InstD->getAccess());
10453       }
10454       UnresolvedMappers.push_back(UnresolvedLookupExpr::Create(
10455           TT.getSema().Context, /*NamingClass=*/nullptr,
10456           MapperIdScopeSpec.getWithLocInContext(TT.getSema().Context),
10457           MapperIdInfo, /*ADL=*/true, ULE->isOverloaded(), Decls.begin(),
10458           Decls.end()));
10459     } else {
10460       UnresolvedMappers.push_back(nullptr);
10461     }
10462   }
10463   return false;
10464 }
10465 
10466 template <typename Derived>
10467 OMPClause *TreeTransform<Derived>::TransformOMPMapClause(OMPMapClause *C) {
10468   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10469   llvm::SmallVector<Expr *, 16> Vars;
10470   Expr *IteratorModifier = C->getIteratorModifier();
10471   if (IteratorModifier) {
10472     ExprResult MapModRes = getDerived().TransformExpr(IteratorModifier);
10473     if (MapModRes.isInvalid())
10474       return nullptr;
10475     IteratorModifier = MapModRes.get();
10476   }
10477   CXXScopeSpec MapperIdScopeSpec;
10478   DeclarationNameInfo MapperIdInfo;
10479   llvm::SmallVector<Expr *, 16> UnresolvedMappers;
10480   if (transformOMPMappableExprListClause<Derived, OMPMapClause>(
10481           *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
10482     return nullptr;
10483   return getDerived().RebuildOMPMapClause(
10484       IteratorModifier, C->getMapTypeModifiers(), C->getMapTypeModifiersLoc(),
10485       MapperIdScopeSpec, MapperIdInfo, C->getMapType(), C->isImplicitMapType(),
10486       C->getMapLoc(), C->getColonLoc(), Vars, Locs, UnresolvedMappers);
10487 }
10488 
10489 template <typename Derived>
10490 OMPClause *
10491 TreeTransform<Derived>::TransformOMPAllocateClause(OMPAllocateClause *C) {
10492   Expr *Allocator = C->getAllocator();
10493   if (Allocator) {
10494     ExprResult AllocatorRes = getDerived().TransformExpr(Allocator);
10495     if (AllocatorRes.isInvalid())
10496       return nullptr;
10497     Allocator = AllocatorRes.get();
10498   }
10499   llvm::SmallVector<Expr *, 16> Vars;
10500   Vars.reserve(C->varlist_size());
10501   for (auto *VE : C->varlists()) {
10502     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10503     if (EVar.isInvalid())
10504       return nullptr;
10505     Vars.push_back(EVar.get());
10506   }
10507   return getDerived().RebuildOMPAllocateClause(
10508       Allocator, Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
10509       C->getEndLoc());
10510 }
10511 
10512 template <typename Derived>
10513 OMPClause *
10514 TreeTransform<Derived>::TransformOMPNumTeamsClause(OMPNumTeamsClause *C) {
10515   ExprResult E = getDerived().TransformExpr(C->getNumTeams());
10516   if (E.isInvalid())
10517     return nullptr;
10518   return getDerived().RebuildOMPNumTeamsClause(
10519       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10520 }
10521 
10522 template <typename Derived>
10523 OMPClause *
10524 TreeTransform<Derived>::TransformOMPThreadLimitClause(OMPThreadLimitClause *C) {
10525   ExprResult E = getDerived().TransformExpr(C->getThreadLimit());
10526   if (E.isInvalid())
10527     return nullptr;
10528   return getDerived().RebuildOMPThreadLimitClause(
10529       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10530 }
10531 
10532 template <typename Derived>
10533 OMPClause *
10534 TreeTransform<Derived>::TransformOMPPriorityClause(OMPPriorityClause *C) {
10535   ExprResult E = getDerived().TransformExpr(C->getPriority());
10536   if (E.isInvalid())
10537     return nullptr;
10538   return getDerived().RebuildOMPPriorityClause(
10539       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10540 }
10541 
10542 template <typename Derived>
10543 OMPClause *
10544 TreeTransform<Derived>::TransformOMPGrainsizeClause(OMPGrainsizeClause *C) {
10545   ExprResult E = getDerived().TransformExpr(C->getGrainsize());
10546   if (E.isInvalid())
10547     return nullptr;
10548   return getDerived().RebuildOMPGrainsizeClause(
10549       C->getModifier(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
10550       C->getModifierLoc(), C->getEndLoc());
10551 }
10552 
10553 template <typename Derived>
10554 OMPClause *
10555 TreeTransform<Derived>::TransformOMPNumTasksClause(OMPNumTasksClause *C) {
10556   ExprResult E = getDerived().TransformExpr(C->getNumTasks());
10557   if (E.isInvalid())
10558     return nullptr;
10559   return getDerived().RebuildOMPNumTasksClause(
10560       C->getModifier(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
10561       C->getModifierLoc(), C->getEndLoc());
10562 }
10563 
10564 template <typename Derived>
10565 OMPClause *TreeTransform<Derived>::TransformOMPHintClause(OMPHintClause *C) {
10566   ExprResult E = getDerived().TransformExpr(C->getHint());
10567   if (E.isInvalid())
10568     return nullptr;
10569   return getDerived().RebuildOMPHintClause(E.get(), C->getBeginLoc(),
10570                                            C->getLParenLoc(), C->getEndLoc());
10571 }
10572 
10573 template <typename Derived>
10574 OMPClause *TreeTransform<Derived>::TransformOMPDistScheduleClause(
10575     OMPDistScheduleClause *C) {
10576   ExprResult E = getDerived().TransformExpr(C->getChunkSize());
10577   if (E.isInvalid())
10578     return nullptr;
10579   return getDerived().RebuildOMPDistScheduleClause(
10580       C->getDistScheduleKind(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
10581       C->getDistScheduleKindLoc(), C->getCommaLoc(), C->getEndLoc());
10582 }
10583 
10584 template <typename Derived>
10585 OMPClause *
10586 TreeTransform<Derived>::TransformOMPDefaultmapClause(OMPDefaultmapClause *C) {
10587   // Rebuild Defaultmap Clause since we need to invoke the checking of
10588   // defaultmap(none:variable-category) after template initialization.
10589   return getDerived().RebuildOMPDefaultmapClause(C->getDefaultmapModifier(),
10590                                                  C->getDefaultmapKind(),
10591                                                  C->getBeginLoc(),
10592                                                  C->getLParenLoc(),
10593                                                  C->getDefaultmapModifierLoc(),
10594                                                  C->getDefaultmapKindLoc(),
10595                                                  C->getEndLoc());
10596 }
10597 
10598 template <typename Derived>
10599 OMPClause *TreeTransform<Derived>::TransformOMPToClause(OMPToClause *C) {
10600   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10601   llvm::SmallVector<Expr *, 16> Vars;
10602   CXXScopeSpec MapperIdScopeSpec;
10603   DeclarationNameInfo MapperIdInfo;
10604   llvm::SmallVector<Expr *, 16> UnresolvedMappers;
10605   if (transformOMPMappableExprListClause<Derived, OMPToClause>(
10606           *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
10607     return nullptr;
10608   return getDerived().RebuildOMPToClause(
10609       C->getMotionModifiers(), C->getMotionModifiersLoc(), MapperIdScopeSpec,
10610       MapperIdInfo, C->getColonLoc(), Vars, Locs, UnresolvedMappers);
10611 }
10612 
10613 template <typename Derived>
10614 OMPClause *TreeTransform<Derived>::TransformOMPFromClause(OMPFromClause *C) {
10615   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10616   llvm::SmallVector<Expr *, 16> Vars;
10617   CXXScopeSpec MapperIdScopeSpec;
10618   DeclarationNameInfo MapperIdInfo;
10619   llvm::SmallVector<Expr *, 16> UnresolvedMappers;
10620   if (transformOMPMappableExprListClause<Derived, OMPFromClause>(
10621           *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
10622     return nullptr;
10623   return getDerived().RebuildOMPFromClause(
10624       C->getMotionModifiers(), C->getMotionModifiersLoc(), MapperIdScopeSpec,
10625       MapperIdInfo, C->getColonLoc(), Vars, Locs, UnresolvedMappers);
10626 }
10627 
10628 template <typename Derived>
10629 OMPClause *TreeTransform<Derived>::TransformOMPUseDevicePtrClause(
10630     OMPUseDevicePtrClause *C) {
10631   llvm::SmallVector<Expr *, 16> Vars;
10632   Vars.reserve(C->varlist_size());
10633   for (auto *VE : C->varlists()) {
10634     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10635     if (EVar.isInvalid())
10636       return nullptr;
10637     Vars.push_back(EVar.get());
10638   }
10639   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10640   return getDerived().RebuildOMPUseDevicePtrClause(Vars, Locs);
10641 }
10642 
10643 template <typename Derived>
10644 OMPClause *TreeTransform<Derived>::TransformOMPUseDeviceAddrClause(
10645     OMPUseDeviceAddrClause *C) {
10646   llvm::SmallVector<Expr *, 16> Vars;
10647   Vars.reserve(C->varlist_size());
10648   for (auto *VE : C->varlists()) {
10649     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10650     if (EVar.isInvalid())
10651       return nullptr;
10652     Vars.push_back(EVar.get());
10653   }
10654   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10655   return getDerived().RebuildOMPUseDeviceAddrClause(Vars, Locs);
10656 }
10657 
10658 template <typename Derived>
10659 OMPClause *
10660 TreeTransform<Derived>::TransformOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
10661   llvm::SmallVector<Expr *, 16> Vars;
10662   Vars.reserve(C->varlist_size());
10663   for (auto *VE : C->varlists()) {
10664     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10665     if (EVar.isInvalid())
10666       return nullptr;
10667     Vars.push_back(EVar.get());
10668   }
10669   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10670   return getDerived().RebuildOMPIsDevicePtrClause(Vars, Locs);
10671 }
10672 
10673 template <typename Derived>
10674 OMPClause *TreeTransform<Derived>::TransformOMPHasDeviceAddrClause(
10675     OMPHasDeviceAddrClause *C) {
10676   llvm::SmallVector<Expr *, 16> Vars;
10677   Vars.reserve(C->varlist_size());
10678   for (auto *VE : C->varlists()) {
10679     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10680     if (EVar.isInvalid())
10681       return nullptr;
10682     Vars.push_back(EVar.get());
10683   }
10684   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10685   return getDerived().RebuildOMPHasDeviceAddrClause(Vars, Locs);
10686 }
10687 
10688 template <typename Derived>
10689 OMPClause *
10690 TreeTransform<Derived>::TransformOMPNontemporalClause(OMPNontemporalClause *C) {
10691   llvm::SmallVector<Expr *, 16> Vars;
10692   Vars.reserve(C->varlist_size());
10693   for (auto *VE : C->varlists()) {
10694     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10695     if (EVar.isInvalid())
10696       return nullptr;
10697     Vars.push_back(EVar.get());
10698   }
10699   return getDerived().RebuildOMPNontemporalClause(
10700       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10701 }
10702 
10703 template <typename Derived>
10704 OMPClause *
10705 TreeTransform<Derived>::TransformOMPInclusiveClause(OMPInclusiveClause *C) {
10706   llvm::SmallVector<Expr *, 16> Vars;
10707   Vars.reserve(C->varlist_size());
10708   for (auto *VE : C->varlists()) {
10709     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10710     if (EVar.isInvalid())
10711       return nullptr;
10712     Vars.push_back(EVar.get());
10713   }
10714   return getDerived().RebuildOMPInclusiveClause(
10715       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10716 }
10717 
10718 template <typename Derived>
10719 OMPClause *
10720 TreeTransform<Derived>::TransformOMPExclusiveClause(OMPExclusiveClause *C) {
10721   llvm::SmallVector<Expr *, 16> Vars;
10722   Vars.reserve(C->varlist_size());
10723   for (auto *VE : C->varlists()) {
10724     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10725     if (EVar.isInvalid())
10726       return nullptr;
10727     Vars.push_back(EVar.get());
10728   }
10729   return getDerived().RebuildOMPExclusiveClause(
10730       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10731 }
10732 
10733 template <typename Derived>
10734 OMPClause *TreeTransform<Derived>::TransformOMPUsesAllocatorsClause(
10735     OMPUsesAllocatorsClause *C) {
10736   SmallVector<Sema::UsesAllocatorsData, 16> Data;
10737   Data.reserve(C->getNumberOfAllocators());
10738   for (unsigned I = 0, E = C->getNumberOfAllocators(); I < E; ++I) {
10739     OMPUsesAllocatorsClause::Data D = C->getAllocatorData(I);
10740     ExprResult Allocator = getDerived().TransformExpr(D.Allocator);
10741     if (Allocator.isInvalid())
10742       continue;
10743     ExprResult AllocatorTraits;
10744     if (Expr *AT = D.AllocatorTraits) {
10745       AllocatorTraits = getDerived().TransformExpr(AT);
10746       if (AllocatorTraits.isInvalid())
10747         continue;
10748     }
10749     Sema::UsesAllocatorsData &NewD = Data.emplace_back();
10750     NewD.Allocator = Allocator.get();
10751     NewD.AllocatorTraits = AllocatorTraits.get();
10752     NewD.LParenLoc = D.LParenLoc;
10753     NewD.RParenLoc = D.RParenLoc;
10754   }
10755   return getDerived().RebuildOMPUsesAllocatorsClause(
10756       Data, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10757 }
10758 
10759 template <typename Derived>
10760 OMPClause *
10761 TreeTransform<Derived>::TransformOMPAffinityClause(OMPAffinityClause *C) {
10762   SmallVector<Expr *, 4> Locators;
10763   Locators.reserve(C->varlist_size());
10764   ExprResult ModifierRes;
10765   if (Expr *Modifier = C->getModifier()) {
10766     ModifierRes = getDerived().TransformExpr(Modifier);
10767     if (ModifierRes.isInvalid())
10768       return nullptr;
10769   }
10770   for (Expr *E : C->varlists()) {
10771     ExprResult Locator = getDerived().TransformExpr(E);
10772     if (Locator.isInvalid())
10773       continue;
10774     Locators.push_back(Locator.get());
10775   }
10776   return getDerived().RebuildOMPAffinityClause(
10777       C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(), C->getEndLoc(),
10778       ModifierRes.get(), Locators);
10779 }
10780 
10781 template <typename Derived>
10782 OMPClause *TreeTransform<Derived>::TransformOMPOrderClause(OMPOrderClause *C) {
10783   return getDerived().RebuildOMPOrderClause(
10784       C->getKind(), C->getKindKwLoc(), C->getBeginLoc(), C->getLParenLoc(),
10785       C->getEndLoc(), C->getModifier(), C->getModifierKwLoc());
10786 }
10787 
10788 template <typename Derived>
10789 OMPClause *TreeTransform<Derived>::TransformOMPBindClause(OMPBindClause *C) {
10790   return getDerived().RebuildOMPBindClause(
10791       C->getBindKind(), C->getBindKindLoc(), C->getBeginLoc(),
10792       C->getLParenLoc(), C->getEndLoc());
10793 }
10794 
10795 template <typename Derived>
10796 OMPClause *TreeTransform<Derived>::TransformOMPXDynCGroupMemClause(
10797     OMPXDynCGroupMemClause *C) {
10798   ExprResult Size = getDerived().TransformExpr(C->getSize());
10799   if (Size.isInvalid())
10800     return nullptr;
10801   return getDerived().RebuildOMPXDynCGroupMemClause(
10802       Size.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10803 }
10804 
10805 template <typename Derived>
10806 OMPClause *
10807 TreeTransform<Derived>::TransformOMPDoacrossClause(OMPDoacrossClause *C) {
10808   llvm::SmallVector<Expr *, 16> Vars;
10809   Vars.reserve(C->varlist_size());
10810   for (auto *VE : C->varlists()) {
10811     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10812     if (EVar.isInvalid())
10813       return nullptr;
10814     Vars.push_back(EVar.get());
10815   }
10816   return getDerived().RebuildOMPDoacrossClause(
10817       C->getDependenceType(), C->getDependenceLoc(), C->getColonLoc(), Vars,
10818       C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10819 }
10820 
10821 template <typename Derived>
10822 OMPClause *
10823 TreeTransform<Derived>::TransformOMPXAttributeClause(OMPXAttributeClause *C) {
10824   SmallVector<const Attr *> NewAttrs;
10825   for (auto *A : C->getAttrs())
10826     NewAttrs.push_back(getDerived().TransformAttr(A));
10827   return getDerived().RebuildOMPXAttributeClause(
10828       NewAttrs, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10829 }
10830 
10831 template <typename Derived>
10832 OMPClause *TreeTransform<Derived>::TransformOMPXBareClause(OMPXBareClause *C) {
10833   return getDerived().RebuildOMPXBareClause(C->getBeginLoc(), C->getEndLoc());
10834 }
10835 
10836 //===----------------------------------------------------------------------===//
10837 // Expression transformation
10838 //===----------------------------------------------------------------------===//
10839 template<typename Derived>
10840 ExprResult
10841 TreeTransform<Derived>::TransformConstantExpr(ConstantExpr *E) {
10842   return TransformExpr(E->getSubExpr());
10843 }
10844 
10845 template <typename Derived>
10846 ExprResult TreeTransform<Derived>::TransformSYCLUniqueStableNameExpr(
10847     SYCLUniqueStableNameExpr *E) {
10848   if (!E->isTypeDependent())
10849     return E;
10850 
10851   TypeSourceInfo *NewT = getDerived().TransformType(E->getTypeSourceInfo());
10852 
10853   if (!NewT)
10854     return ExprError();
10855 
10856   if (!getDerived().AlwaysRebuild() && E->getTypeSourceInfo() == NewT)
10857     return E;
10858 
10859   return getDerived().RebuildSYCLUniqueStableNameExpr(
10860       E->getLocation(), E->getLParenLocation(), E->getRParenLocation(), NewT);
10861 }
10862 
10863 template<typename Derived>
10864 ExprResult
10865 TreeTransform<Derived>::TransformPredefinedExpr(PredefinedExpr *E) {
10866   if (!E->isTypeDependent())
10867     return E;
10868 
10869   return getDerived().RebuildPredefinedExpr(E->getLocation(),
10870                                             E->getIdentKind());
10871 }
10872 
10873 template<typename Derived>
10874 ExprResult
10875 TreeTransform<Derived>::TransformDeclRefExpr(DeclRefExpr *E) {
10876   NestedNameSpecifierLoc QualifierLoc;
10877   if (E->getQualifierLoc()) {
10878     QualifierLoc
10879       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
10880     if (!QualifierLoc)
10881       return ExprError();
10882   }
10883 
10884   ValueDecl *ND
10885     = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getLocation(),
10886                                                          E->getDecl()));
10887   if (!ND)
10888     return ExprError();
10889 
10890   NamedDecl *Found = ND;
10891   if (E->getFoundDecl() != E->getDecl()) {
10892     Found = cast_or_null<NamedDecl>(
10893         getDerived().TransformDecl(E->getLocation(), E->getFoundDecl()));
10894     if (!Found)
10895       return ExprError();
10896   }
10897 
10898   DeclarationNameInfo NameInfo = E->getNameInfo();
10899   if (NameInfo.getName()) {
10900     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
10901     if (!NameInfo.getName())
10902       return ExprError();
10903   }
10904 
10905   if (!getDerived().AlwaysRebuild() &&
10906       QualifierLoc == E->getQualifierLoc() &&
10907       ND == E->getDecl() &&
10908       Found == E->getFoundDecl() &&
10909       NameInfo.getName() == E->getDecl()->getDeclName() &&
10910       !E->hasExplicitTemplateArgs()) {
10911 
10912     // Mark it referenced in the new context regardless.
10913     // FIXME: this is a bit instantiation-specific.
10914     SemaRef.MarkDeclRefReferenced(E);
10915 
10916     return E;
10917   }
10918 
10919   TemplateArgumentListInfo TransArgs, *TemplateArgs = nullptr;
10920   if (E->hasExplicitTemplateArgs()) {
10921     TemplateArgs = &TransArgs;
10922     TransArgs.setLAngleLoc(E->getLAngleLoc());
10923     TransArgs.setRAngleLoc(E->getRAngleLoc());
10924     if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
10925                                                 E->getNumTemplateArgs(),
10926                                                 TransArgs))
10927       return ExprError();
10928   }
10929 
10930   return getDerived().RebuildDeclRefExpr(QualifierLoc, ND, NameInfo,
10931                                          Found, TemplateArgs);
10932 }
10933 
10934 template<typename Derived>
10935 ExprResult
10936 TreeTransform<Derived>::TransformIntegerLiteral(IntegerLiteral *E) {
10937   return E;
10938 }
10939 
10940 template <typename Derived>
10941 ExprResult TreeTransform<Derived>::TransformFixedPointLiteral(
10942     FixedPointLiteral *E) {
10943   return E;
10944 }
10945 
10946 template<typename Derived>
10947 ExprResult
10948 TreeTransform<Derived>::TransformFloatingLiteral(FloatingLiteral *E) {
10949   return E;
10950 }
10951 
10952 template<typename Derived>
10953 ExprResult
10954 TreeTransform<Derived>::TransformImaginaryLiteral(ImaginaryLiteral *E) {
10955   return E;
10956 }
10957 
10958 template<typename Derived>
10959 ExprResult
10960 TreeTransform<Derived>::TransformStringLiteral(StringLiteral *E) {
10961   return E;
10962 }
10963 
10964 template<typename Derived>
10965 ExprResult
10966 TreeTransform<Derived>::TransformCharacterLiteral(CharacterLiteral *E) {
10967   return E;
10968 }
10969 
10970 template<typename Derived>
10971 ExprResult
10972 TreeTransform<Derived>::TransformUserDefinedLiteral(UserDefinedLiteral *E) {
10973   return getDerived().TransformCallExpr(E);
10974 }
10975 
10976 template<typename Derived>
10977 ExprResult
10978 TreeTransform<Derived>::TransformGenericSelectionExpr(GenericSelectionExpr *E) {
10979   ExprResult ControllingExpr;
10980   TypeSourceInfo *ControllingType = nullptr;
10981   if (E->isExprPredicate())
10982     ControllingExpr = getDerived().TransformExpr(E->getControllingExpr());
10983   else
10984     ControllingType = getDerived().TransformType(E->getControllingType());
10985 
10986   if (ControllingExpr.isInvalid() && !ControllingType)
10987     return ExprError();
10988 
10989   SmallVector<Expr *, 4> AssocExprs;
10990   SmallVector<TypeSourceInfo *, 4> AssocTypes;
10991   for (const GenericSelectionExpr::Association Assoc : E->associations()) {
10992     TypeSourceInfo *TSI = Assoc.getTypeSourceInfo();
10993     if (TSI) {
10994       TypeSourceInfo *AssocType = getDerived().TransformType(TSI);
10995       if (!AssocType)
10996         return ExprError();
10997       AssocTypes.push_back(AssocType);
10998     } else {
10999       AssocTypes.push_back(nullptr);
11000     }
11001 
11002     ExprResult AssocExpr =
11003         getDerived().TransformExpr(Assoc.getAssociationExpr());
11004     if (AssocExpr.isInvalid())
11005       return ExprError();
11006     AssocExprs.push_back(AssocExpr.get());
11007   }
11008 
11009   if (!ControllingType)
11010   return getDerived().RebuildGenericSelectionExpr(E->getGenericLoc(),
11011                                                   E->getDefaultLoc(),
11012                                                   E->getRParenLoc(),
11013                                                   ControllingExpr.get(),
11014                                                   AssocTypes,
11015                                                   AssocExprs);
11016   return getDerived().RebuildGenericSelectionExpr(
11017       E->getGenericLoc(), E->getDefaultLoc(), E->getRParenLoc(),
11018       ControllingType, AssocTypes, AssocExprs);
11019 }
11020 
11021 template<typename Derived>
11022 ExprResult
11023 TreeTransform<Derived>::TransformParenExpr(ParenExpr *E) {
11024   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
11025   if (SubExpr.isInvalid())
11026     return ExprError();
11027 
11028   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
11029     return E;
11030 
11031   return getDerived().RebuildParenExpr(SubExpr.get(), E->getLParen(),
11032                                        E->getRParen());
11033 }
11034 
11035 /// The operand of a unary address-of operator has special rules: it's
11036 /// allowed to refer to a non-static member of a class even if there's no 'this'
11037 /// object available.
11038 template<typename Derived>
11039 ExprResult
11040 TreeTransform<Derived>::TransformAddressOfOperand(Expr *E) {
11041   if (DependentScopeDeclRefExpr *DRE = dyn_cast<DependentScopeDeclRefExpr>(E))
11042     return getDerived().TransformDependentScopeDeclRefExpr(DRE, true, nullptr);
11043   else
11044     return getDerived().TransformExpr(E);
11045 }
11046 
11047 template<typename Derived>
11048 ExprResult
11049 TreeTransform<Derived>::TransformUnaryOperator(UnaryOperator *E) {
11050   ExprResult SubExpr;
11051   if (E->getOpcode() == UO_AddrOf)
11052     SubExpr = TransformAddressOfOperand(E->getSubExpr());
11053   else
11054     SubExpr = TransformExpr(E->getSubExpr());
11055   if (SubExpr.isInvalid())
11056     return ExprError();
11057 
11058   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
11059     return E;
11060 
11061   return getDerived().RebuildUnaryOperator(E->getOperatorLoc(),
11062                                            E->getOpcode(),
11063                                            SubExpr.get());
11064 }
11065 
11066 template<typename Derived>
11067 ExprResult
11068 TreeTransform<Derived>::TransformOffsetOfExpr(OffsetOfExpr *E) {
11069   // Transform the type.
11070   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
11071   if (!Type)
11072     return ExprError();
11073 
11074   // Transform all of the components into components similar to what the
11075   // parser uses.
11076   // FIXME: It would be slightly more efficient in the non-dependent case to
11077   // just map FieldDecls, rather than requiring the rebuilder to look for
11078   // the fields again. However, __builtin_offsetof is rare enough in
11079   // template code that we don't care.
11080   bool ExprChanged = false;
11081   typedef Sema::OffsetOfComponent Component;
11082   SmallVector<Component, 4> Components;
11083   for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
11084     const OffsetOfNode &ON = E->getComponent(I);
11085     Component Comp;
11086     Comp.isBrackets = true;
11087     Comp.LocStart = ON.getSourceRange().getBegin();
11088     Comp.LocEnd = ON.getSourceRange().getEnd();
11089     switch (ON.getKind()) {
11090     case OffsetOfNode::Array: {
11091       Expr *FromIndex = E->getIndexExpr(ON.getArrayExprIndex());
11092       ExprResult Index = getDerived().TransformExpr(FromIndex);
11093       if (Index.isInvalid())
11094         return ExprError();
11095 
11096       ExprChanged = ExprChanged || Index.get() != FromIndex;
11097       Comp.isBrackets = true;
11098       Comp.U.E = Index.get();
11099       break;
11100     }
11101 
11102     case OffsetOfNode::Field:
11103     case OffsetOfNode::Identifier:
11104       Comp.isBrackets = false;
11105       Comp.U.IdentInfo = ON.getFieldName();
11106       if (!Comp.U.IdentInfo)
11107         continue;
11108 
11109       break;
11110 
11111     case OffsetOfNode::Base:
11112       // Will be recomputed during the rebuild.
11113       continue;
11114     }
11115 
11116     Components.push_back(Comp);
11117   }
11118 
11119   // If nothing changed, retain the existing expression.
11120   if (!getDerived().AlwaysRebuild() &&
11121       Type == E->getTypeSourceInfo() &&
11122       !ExprChanged)
11123     return E;
11124 
11125   // Build a new offsetof expression.
11126   return getDerived().RebuildOffsetOfExpr(E->getOperatorLoc(), Type,
11127                                           Components, E->getRParenLoc());
11128 }
11129 
11130 template<typename Derived>
11131 ExprResult
11132 TreeTransform<Derived>::TransformOpaqueValueExpr(OpaqueValueExpr *E) {
11133   assert((!E->getSourceExpr() || getDerived().AlreadyTransformed(E->getType())) &&
11134          "opaque value expression requires transformation");
11135   return E;
11136 }
11137 
11138 template<typename Derived>
11139 ExprResult
11140 TreeTransform<Derived>::TransformTypoExpr(TypoExpr *E) {
11141   return E;
11142 }
11143 
11144 template <typename Derived>
11145 ExprResult TreeTransform<Derived>::TransformRecoveryExpr(RecoveryExpr *E) {
11146   llvm::SmallVector<Expr *, 8> Children;
11147   bool Changed = false;
11148   for (Expr *C : E->subExpressions()) {
11149     ExprResult NewC = getDerived().TransformExpr(C);
11150     if (NewC.isInvalid())
11151       return ExprError();
11152     Children.push_back(NewC.get());
11153 
11154     Changed |= NewC.get() != C;
11155   }
11156   if (!getDerived().AlwaysRebuild() && !Changed)
11157     return E;
11158   return getDerived().RebuildRecoveryExpr(E->getBeginLoc(), E->getEndLoc(),
11159                                           Children, E->getType());
11160 }
11161 
11162 template<typename Derived>
11163 ExprResult
11164 TreeTransform<Derived>::TransformPseudoObjectExpr(PseudoObjectExpr *E) {
11165   // Rebuild the syntactic form.  The original syntactic form has
11166   // opaque-value expressions in it, so strip those away and rebuild
11167   // the result.  This is a really awful way of doing this, but the
11168   // better solution (rebuilding the semantic expressions and
11169   // rebinding OVEs as necessary) doesn't work; we'd need
11170   // TreeTransform to not strip away implicit conversions.
11171   Expr *newSyntacticForm = SemaRef.recreateSyntacticForm(E);
11172   ExprResult result = getDerived().TransformExpr(newSyntacticForm);
11173   if (result.isInvalid()) return ExprError();
11174 
11175   // If that gives us a pseudo-object result back, the pseudo-object
11176   // expression must have been an lvalue-to-rvalue conversion which we
11177   // should reapply.
11178   if (result.get()->hasPlaceholderType(BuiltinType::PseudoObject))
11179     result = SemaRef.checkPseudoObjectRValue(result.get());
11180 
11181   return result;
11182 }
11183 
11184 template<typename Derived>
11185 ExprResult
11186 TreeTransform<Derived>::TransformUnaryExprOrTypeTraitExpr(
11187                                                 UnaryExprOrTypeTraitExpr *E) {
11188   if (E->isArgumentType()) {
11189     TypeSourceInfo *OldT = E->getArgumentTypeInfo();
11190 
11191     TypeSourceInfo *NewT = getDerived().TransformType(OldT);
11192     if (!NewT)
11193       return ExprError();
11194 
11195     if (!getDerived().AlwaysRebuild() && OldT == NewT)
11196       return E;
11197 
11198     return getDerived().RebuildUnaryExprOrTypeTrait(NewT, E->getOperatorLoc(),
11199                                                     E->getKind(),
11200                                                     E->getSourceRange());
11201   }
11202 
11203   // C++0x [expr.sizeof]p1:
11204   //   The operand is either an expression, which is an unevaluated operand
11205   //   [...]
11206   EnterExpressionEvaluationContext Unevaluated(
11207       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
11208       Sema::ReuseLambdaContextDecl);
11209 
11210   // Try to recover if we have something like sizeof(T::X) where X is a type.
11211   // Notably, there must be *exactly* one set of parens if X is a type.
11212   TypeSourceInfo *RecoveryTSI = nullptr;
11213   ExprResult SubExpr;
11214   auto *PE = dyn_cast<ParenExpr>(E->getArgumentExpr());
11215   if (auto *DRE =
11216           PE ? dyn_cast<DependentScopeDeclRefExpr>(PE->getSubExpr()) : nullptr)
11217     SubExpr = getDerived().TransformParenDependentScopeDeclRefExpr(
11218         PE, DRE, false, &RecoveryTSI);
11219   else
11220     SubExpr = getDerived().TransformExpr(E->getArgumentExpr());
11221 
11222   if (RecoveryTSI) {
11223     return getDerived().RebuildUnaryExprOrTypeTrait(
11224         RecoveryTSI, E->getOperatorLoc(), E->getKind(), E->getSourceRange());
11225   } else if (SubExpr.isInvalid())
11226     return ExprError();
11227 
11228   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getArgumentExpr())
11229     return E;
11230 
11231   return getDerived().RebuildUnaryExprOrTypeTrait(SubExpr.get(),
11232                                                   E->getOperatorLoc(),
11233                                                   E->getKind(),
11234                                                   E->getSourceRange());
11235 }
11236 
11237 template<typename Derived>
11238 ExprResult
11239 TreeTransform<Derived>::TransformArraySubscriptExpr(ArraySubscriptExpr *E) {
11240   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
11241   if (LHS.isInvalid())
11242     return ExprError();
11243 
11244   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
11245   if (RHS.isInvalid())
11246     return ExprError();
11247 
11248 
11249   if (!getDerived().AlwaysRebuild() &&
11250       LHS.get() == E->getLHS() &&
11251       RHS.get() == E->getRHS())
11252     return E;
11253 
11254   return getDerived().RebuildArraySubscriptExpr(
11255       LHS.get(),
11256       /*FIXME:*/ E->getLHS()->getBeginLoc(), RHS.get(), E->getRBracketLoc());
11257 }
11258 
11259 template <typename Derived>
11260 ExprResult
11261 TreeTransform<Derived>::TransformMatrixSubscriptExpr(MatrixSubscriptExpr *E) {
11262   ExprResult Base = getDerived().TransformExpr(E->getBase());
11263   if (Base.isInvalid())
11264     return ExprError();
11265 
11266   ExprResult RowIdx = getDerived().TransformExpr(E->getRowIdx());
11267   if (RowIdx.isInvalid())
11268     return ExprError();
11269 
11270   ExprResult ColumnIdx = getDerived().TransformExpr(E->getColumnIdx());
11271   if (ColumnIdx.isInvalid())
11272     return ExprError();
11273 
11274   if (!getDerived().AlwaysRebuild() && Base.get() == E->getBase() &&
11275       RowIdx.get() == E->getRowIdx() && ColumnIdx.get() == E->getColumnIdx())
11276     return E;
11277 
11278   return getDerived().RebuildMatrixSubscriptExpr(
11279       Base.get(), RowIdx.get(), ColumnIdx.get(), E->getRBracketLoc());
11280 }
11281 
11282 template <typename Derived>
11283 ExprResult
11284 TreeTransform<Derived>::TransformOMPArraySectionExpr(OMPArraySectionExpr *E) {
11285   ExprResult Base = getDerived().TransformExpr(E->getBase());
11286   if (Base.isInvalid())
11287     return ExprError();
11288 
11289   ExprResult LowerBound;
11290   if (E->getLowerBound()) {
11291     LowerBound = getDerived().TransformExpr(E->getLowerBound());
11292     if (LowerBound.isInvalid())
11293       return ExprError();
11294   }
11295 
11296   ExprResult Length;
11297   if (E->getLength()) {
11298     Length = getDerived().TransformExpr(E->getLength());
11299     if (Length.isInvalid())
11300       return ExprError();
11301   }
11302 
11303   ExprResult Stride;
11304   if (Expr *Str = E->getStride()) {
11305     Stride = getDerived().TransformExpr(Str);
11306     if (Stride.isInvalid())
11307       return ExprError();
11308   }
11309 
11310   if (!getDerived().AlwaysRebuild() && Base.get() == E->getBase() &&
11311       LowerBound.get() == E->getLowerBound() && Length.get() == E->getLength())
11312     return E;
11313 
11314   return getDerived().RebuildOMPArraySectionExpr(
11315       Base.get(), E->getBase()->getEndLoc(), LowerBound.get(),
11316       E->getColonLocFirst(), E->getColonLocSecond(), Length.get(), Stride.get(),
11317       E->getRBracketLoc());
11318 }
11319 
11320 template <typename Derived>
11321 ExprResult
11322 TreeTransform<Derived>::TransformOMPArrayShapingExpr(OMPArrayShapingExpr *E) {
11323   ExprResult Base = getDerived().TransformExpr(E->getBase());
11324   if (Base.isInvalid())
11325     return ExprError();
11326 
11327   SmallVector<Expr *, 4> Dims;
11328   bool ErrorFound = false;
11329   for (Expr *Dim : E->getDimensions()) {
11330     ExprResult DimRes = getDerived().TransformExpr(Dim);
11331     if (DimRes.isInvalid()) {
11332       ErrorFound = true;
11333       continue;
11334     }
11335     Dims.push_back(DimRes.get());
11336   }
11337 
11338   if (ErrorFound)
11339     return ExprError();
11340   return getDerived().RebuildOMPArrayShapingExpr(Base.get(), E->getLParenLoc(),
11341                                                  E->getRParenLoc(), Dims,
11342                                                  E->getBracketsRanges());
11343 }
11344 
11345 template <typename Derived>
11346 ExprResult
11347 TreeTransform<Derived>::TransformOMPIteratorExpr(OMPIteratorExpr *E) {
11348   unsigned NumIterators = E->numOfIterators();
11349   SmallVector<Sema::OMPIteratorData, 4> Data(NumIterators);
11350 
11351   bool ErrorFound = false;
11352   bool NeedToRebuild = getDerived().AlwaysRebuild();
11353   for (unsigned I = 0; I < NumIterators; ++I) {
11354     auto *D = cast<VarDecl>(E->getIteratorDecl(I));
11355     Data[I].DeclIdent = D->getIdentifier();
11356     Data[I].DeclIdentLoc = D->getLocation();
11357     if (D->getLocation() == D->getBeginLoc()) {
11358       assert(SemaRef.Context.hasSameType(D->getType(), SemaRef.Context.IntTy) &&
11359              "Implicit type must be int.");
11360     } else {
11361       TypeSourceInfo *TSI = getDerived().TransformType(D->getTypeSourceInfo());
11362       QualType DeclTy = getDerived().TransformType(D->getType());
11363       Data[I].Type = SemaRef.CreateParsedType(DeclTy, TSI);
11364     }
11365     OMPIteratorExpr::IteratorRange Range = E->getIteratorRange(I);
11366     ExprResult Begin = getDerived().TransformExpr(Range.Begin);
11367     ExprResult End = getDerived().TransformExpr(Range.End);
11368     ExprResult Step = getDerived().TransformExpr(Range.Step);
11369     ErrorFound = ErrorFound ||
11370                  !(!D->getTypeSourceInfo() || (Data[I].Type.getAsOpaquePtr() &&
11371                                                !Data[I].Type.get().isNull())) ||
11372                  Begin.isInvalid() || End.isInvalid() || Step.isInvalid();
11373     if (ErrorFound)
11374       continue;
11375     Data[I].Range.Begin = Begin.get();
11376     Data[I].Range.End = End.get();
11377     Data[I].Range.Step = Step.get();
11378     Data[I].AssignLoc = E->getAssignLoc(I);
11379     Data[I].ColonLoc = E->getColonLoc(I);
11380     Data[I].SecColonLoc = E->getSecondColonLoc(I);
11381     NeedToRebuild =
11382         NeedToRebuild ||
11383         (D->getTypeSourceInfo() && Data[I].Type.get().getTypePtrOrNull() !=
11384                                        D->getType().getTypePtrOrNull()) ||
11385         Range.Begin != Data[I].Range.Begin || Range.End != Data[I].Range.End ||
11386         Range.Step != Data[I].Range.Step;
11387   }
11388   if (ErrorFound)
11389     return ExprError();
11390   if (!NeedToRebuild)
11391     return E;
11392 
11393   ExprResult Res = getDerived().RebuildOMPIteratorExpr(
11394       E->getIteratorKwLoc(), E->getLParenLoc(), E->getRParenLoc(), Data);
11395   if (!Res.isUsable())
11396     return Res;
11397   auto *IE = cast<OMPIteratorExpr>(Res.get());
11398   for (unsigned I = 0; I < NumIterators; ++I)
11399     getDerived().transformedLocalDecl(E->getIteratorDecl(I),
11400                                       IE->getIteratorDecl(I));
11401   return Res;
11402 }
11403 
11404 template<typename Derived>
11405 ExprResult
11406 TreeTransform<Derived>::TransformCallExpr(CallExpr *E) {
11407   // Transform the callee.
11408   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
11409   if (Callee.isInvalid())
11410     return ExprError();
11411 
11412   // Transform arguments.
11413   bool ArgChanged = false;
11414   SmallVector<Expr*, 8> Args;
11415   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
11416                                   &ArgChanged))
11417     return ExprError();
11418 
11419   if (!getDerived().AlwaysRebuild() &&
11420       Callee.get() == E->getCallee() &&
11421       !ArgChanged)
11422     return SemaRef.MaybeBindToTemporary(E);
11423 
11424   // FIXME: Wrong source location information for the '('.
11425   SourceLocation FakeLParenLoc
11426     = ((Expr *)Callee.get())->getSourceRange().getBegin();
11427 
11428   Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
11429   if (E->hasStoredFPFeatures()) {
11430     FPOptionsOverride NewOverrides = E->getFPFeatures();
11431     getSema().CurFPFeatures =
11432         NewOverrides.applyOverrides(getSema().getLangOpts());
11433     getSema().FpPragmaStack.CurrentValue = NewOverrides;
11434   }
11435 
11436   return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
11437                                       Args,
11438                                       E->getRParenLoc());
11439 }
11440 
11441 template<typename Derived>
11442 ExprResult
11443 TreeTransform<Derived>::TransformMemberExpr(MemberExpr *E) {
11444   ExprResult Base = getDerived().TransformExpr(E->getBase());
11445   if (Base.isInvalid())
11446     return ExprError();
11447 
11448   NestedNameSpecifierLoc QualifierLoc;
11449   if (E->hasQualifier()) {
11450     QualifierLoc
11451       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
11452 
11453     if (!QualifierLoc)
11454       return ExprError();
11455   }
11456   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
11457 
11458   ValueDecl *Member
11459     = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getMemberLoc(),
11460                                                          E->getMemberDecl()));
11461   if (!Member)
11462     return ExprError();
11463 
11464   NamedDecl *FoundDecl = E->getFoundDecl();
11465   if (FoundDecl == E->getMemberDecl()) {
11466     FoundDecl = Member;
11467   } else {
11468     FoundDecl = cast_or_null<NamedDecl>(
11469                    getDerived().TransformDecl(E->getMemberLoc(), FoundDecl));
11470     if (!FoundDecl)
11471       return ExprError();
11472   }
11473 
11474   if (!getDerived().AlwaysRebuild() &&
11475       Base.get() == E->getBase() &&
11476       QualifierLoc == E->getQualifierLoc() &&
11477       Member == E->getMemberDecl() &&
11478       FoundDecl == E->getFoundDecl() &&
11479       !E->hasExplicitTemplateArgs()) {
11480 
11481     // Skip for member expression of (this->f), rebuilt thisi->f is needed
11482     // for Openmp where the field need to be privatizized in the case.
11483     if (!(isa<CXXThisExpr>(E->getBase()) &&
11484           getSema().isOpenMPRebuildMemberExpr(cast<ValueDecl>(Member)))) {
11485       // Mark it referenced in the new context regardless.
11486       // FIXME: this is a bit instantiation-specific.
11487       SemaRef.MarkMemberReferenced(E);
11488       return E;
11489     }
11490   }
11491 
11492   TemplateArgumentListInfo TransArgs;
11493   if (E->hasExplicitTemplateArgs()) {
11494     TransArgs.setLAngleLoc(E->getLAngleLoc());
11495     TransArgs.setRAngleLoc(E->getRAngleLoc());
11496     if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
11497                                                 E->getNumTemplateArgs(),
11498                                                 TransArgs))
11499       return ExprError();
11500   }
11501 
11502   // FIXME: Bogus source location for the operator
11503   SourceLocation FakeOperatorLoc =
11504       SemaRef.getLocForEndOfToken(E->getBase()->getSourceRange().getEnd());
11505 
11506   // FIXME: to do this check properly, we will need to preserve the
11507   // first-qualifier-in-scope here, just in case we had a dependent
11508   // base (and therefore couldn't do the check) and a
11509   // nested-name-qualifier (and therefore could do the lookup).
11510   NamedDecl *FirstQualifierInScope = nullptr;
11511   DeclarationNameInfo MemberNameInfo = E->getMemberNameInfo();
11512   if (MemberNameInfo.getName()) {
11513     MemberNameInfo = getDerived().TransformDeclarationNameInfo(MemberNameInfo);
11514     if (!MemberNameInfo.getName())
11515       return ExprError();
11516   }
11517 
11518   return getDerived().RebuildMemberExpr(Base.get(), FakeOperatorLoc,
11519                                         E->isArrow(),
11520                                         QualifierLoc,
11521                                         TemplateKWLoc,
11522                                         MemberNameInfo,
11523                                         Member,
11524                                         FoundDecl,
11525                                         (E->hasExplicitTemplateArgs()
11526                                            ? &TransArgs : nullptr),
11527                                         FirstQualifierInScope);
11528 }
11529 
11530 template<typename Derived>
11531 ExprResult
11532 TreeTransform<Derived>::TransformBinaryOperator(BinaryOperator *E) {
11533   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
11534   if (LHS.isInvalid())
11535     return ExprError();
11536 
11537   ExprResult RHS =
11538       getDerived().TransformInitializer(E->getRHS(), /*NotCopyInit=*/false);
11539   if (RHS.isInvalid())
11540     return ExprError();
11541 
11542   if (!getDerived().AlwaysRebuild() &&
11543       LHS.get() == E->getLHS() &&
11544       RHS.get() == E->getRHS())
11545     return E;
11546 
11547   if (E->isCompoundAssignmentOp())
11548     // FPFeatures has already been established from trailing storage
11549     return getDerived().RebuildBinaryOperator(
11550         E->getOperatorLoc(), E->getOpcode(), LHS.get(), RHS.get());
11551   Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
11552   FPOptionsOverride NewOverrides(E->getFPFeatures());
11553   getSema().CurFPFeatures =
11554       NewOverrides.applyOverrides(getSema().getLangOpts());
11555   getSema().FpPragmaStack.CurrentValue = NewOverrides;
11556   return getDerived().RebuildBinaryOperator(E->getOperatorLoc(), E->getOpcode(),
11557                                             LHS.get(), RHS.get());
11558 }
11559 
11560 template <typename Derived>
11561 ExprResult TreeTransform<Derived>::TransformCXXRewrittenBinaryOperator(
11562     CXXRewrittenBinaryOperator *E) {
11563   CXXRewrittenBinaryOperator::DecomposedForm Decomp = E->getDecomposedForm();
11564 
11565   ExprResult LHS = getDerived().TransformExpr(const_cast<Expr*>(Decomp.LHS));
11566   if (LHS.isInvalid())
11567     return ExprError();
11568 
11569   ExprResult RHS = getDerived().TransformExpr(const_cast<Expr*>(Decomp.RHS));
11570   if (RHS.isInvalid())
11571     return ExprError();
11572 
11573   // Extract the already-resolved callee declarations so that we can restrict
11574   // ourselves to using them as the unqualified lookup results when rebuilding.
11575   UnresolvedSet<2> UnqualLookups;
11576   bool ChangedAnyLookups = false;
11577   Expr *PossibleBinOps[] = {E->getSemanticForm(),
11578                             const_cast<Expr *>(Decomp.InnerBinOp)};
11579   for (Expr *PossibleBinOp : PossibleBinOps) {
11580     auto *Op = dyn_cast<CXXOperatorCallExpr>(PossibleBinOp->IgnoreImplicit());
11581     if (!Op)
11582       continue;
11583     auto *Callee = dyn_cast<DeclRefExpr>(Op->getCallee()->IgnoreImplicit());
11584     if (!Callee || isa<CXXMethodDecl>(Callee->getDecl()))
11585       continue;
11586 
11587     // Transform the callee in case we built a call to a local extern
11588     // declaration.
11589     NamedDecl *Found = cast_or_null<NamedDecl>(getDerived().TransformDecl(
11590         E->getOperatorLoc(), Callee->getFoundDecl()));
11591     if (!Found)
11592       return ExprError();
11593     if (Found != Callee->getFoundDecl())
11594       ChangedAnyLookups = true;
11595     UnqualLookups.addDecl(Found);
11596   }
11597 
11598   if (!getDerived().AlwaysRebuild() && !ChangedAnyLookups &&
11599       LHS.get() == Decomp.LHS && RHS.get() == Decomp.RHS) {
11600     // Mark all functions used in the rewrite as referenced. Note that when
11601     // a < b is rewritten to (a <=> b) < 0, both the <=> and the < might be
11602     // function calls, and/or there might be a user-defined conversion sequence
11603     // applied to the operands of the <.
11604     // FIXME: this is a bit instantiation-specific.
11605     const Expr *StopAt[] = {Decomp.LHS, Decomp.RHS};
11606     SemaRef.MarkDeclarationsReferencedInExpr(E, false, StopAt);
11607     return E;
11608   }
11609 
11610   return getDerived().RebuildCXXRewrittenBinaryOperator(
11611       E->getOperatorLoc(), Decomp.Opcode, UnqualLookups, LHS.get(), RHS.get());
11612 }
11613 
11614 template<typename Derived>
11615 ExprResult
11616 TreeTransform<Derived>::TransformCompoundAssignOperator(
11617                                                       CompoundAssignOperator *E) {
11618   Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
11619   FPOptionsOverride NewOverrides(E->getFPFeatures());
11620   getSema().CurFPFeatures =
11621       NewOverrides.applyOverrides(getSema().getLangOpts());
11622   getSema().FpPragmaStack.CurrentValue = NewOverrides;
11623   return getDerived().TransformBinaryOperator(E);
11624 }
11625 
11626 template<typename Derived>
11627 ExprResult TreeTransform<Derived>::
11628 TransformBinaryConditionalOperator(BinaryConditionalOperator *e) {
11629   // Just rebuild the common and RHS expressions and see whether we
11630   // get any changes.
11631 
11632   ExprResult commonExpr = getDerived().TransformExpr(e->getCommon());
11633   if (commonExpr.isInvalid())
11634     return ExprError();
11635 
11636   ExprResult rhs = getDerived().TransformExpr(e->getFalseExpr());
11637   if (rhs.isInvalid())
11638     return ExprError();
11639 
11640   if (!getDerived().AlwaysRebuild() &&
11641       commonExpr.get() == e->getCommon() &&
11642       rhs.get() == e->getFalseExpr())
11643     return e;
11644 
11645   return getDerived().RebuildConditionalOperator(commonExpr.get(),
11646                                                  e->getQuestionLoc(),
11647                                                  nullptr,
11648                                                  e->getColonLoc(),
11649                                                  rhs.get());
11650 }
11651 
11652 template<typename Derived>
11653 ExprResult
11654 TreeTransform<Derived>::TransformConditionalOperator(ConditionalOperator *E) {
11655   ExprResult Cond = getDerived().TransformExpr(E->getCond());
11656   if (Cond.isInvalid())
11657     return ExprError();
11658 
11659   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
11660   if (LHS.isInvalid())
11661     return ExprError();
11662 
11663   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
11664   if (RHS.isInvalid())
11665     return ExprError();
11666 
11667   if (!getDerived().AlwaysRebuild() &&
11668       Cond.get() == E->getCond() &&
11669       LHS.get() == E->getLHS() &&
11670       RHS.get() == E->getRHS())
11671     return E;
11672 
11673   return getDerived().RebuildConditionalOperator(Cond.get(),
11674                                                  E->getQuestionLoc(),
11675                                                  LHS.get(),
11676                                                  E->getColonLoc(),
11677                                                  RHS.get());
11678 }
11679 
11680 template<typename Derived>
11681 ExprResult
11682 TreeTransform<Derived>::TransformImplicitCastExpr(ImplicitCastExpr *E) {
11683   // Implicit casts are eliminated during transformation, since they
11684   // will be recomputed by semantic analysis after transformation.
11685   return getDerived().TransformExpr(E->getSubExprAsWritten());
11686 }
11687 
11688 template<typename Derived>
11689 ExprResult
11690 TreeTransform<Derived>::TransformCStyleCastExpr(CStyleCastExpr *E) {
11691   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
11692   if (!Type)
11693     return ExprError();
11694 
11695   ExprResult SubExpr
11696     = getDerived().TransformExpr(E->getSubExprAsWritten());
11697   if (SubExpr.isInvalid())
11698     return ExprError();
11699 
11700   if (!getDerived().AlwaysRebuild() &&
11701       Type == E->getTypeInfoAsWritten() &&
11702       SubExpr.get() == E->getSubExpr())
11703     return E;
11704 
11705   return getDerived().RebuildCStyleCastExpr(E->getLParenLoc(),
11706                                             Type,
11707                                             E->getRParenLoc(),
11708                                             SubExpr.get());
11709 }
11710 
11711 template<typename Derived>
11712 ExprResult
11713 TreeTransform<Derived>::TransformCompoundLiteralExpr(CompoundLiteralExpr *E) {
11714   TypeSourceInfo *OldT = E->getTypeSourceInfo();
11715   TypeSourceInfo *NewT = getDerived().TransformType(OldT);
11716   if (!NewT)
11717     return ExprError();
11718 
11719   ExprResult Init = getDerived().TransformExpr(E->getInitializer());
11720   if (Init.isInvalid())
11721     return ExprError();
11722 
11723   if (!getDerived().AlwaysRebuild() &&
11724       OldT == NewT &&
11725       Init.get() == E->getInitializer())
11726     return SemaRef.MaybeBindToTemporary(E);
11727 
11728   // Note: the expression type doesn't necessarily match the
11729   // type-as-written, but that's okay, because it should always be
11730   // derivable from the initializer.
11731 
11732   return getDerived().RebuildCompoundLiteralExpr(
11733       E->getLParenLoc(), NewT,
11734       /*FIXME:*/ E->getInitializer()->getEndLoc(), Init.get());
11735 }
11736 
11737 template<typename Derived>
11738 ExprResult
11739 TreeTransform<Derived>::TransformExtVectorElementExpr(ExtVectorElementExpr *E) {
11740   ExprResult Base = getDerived().TransformExpr(E->getBase());
11741   if (Base.isInvalid())
11742     return ExprError();
11743 
11744   if (!getDerived().AlwaysRebuild() &&
11745       Base.get() == E->getBase())
11746     return E;
11747 
11748   // FIXME: Bad source location
11749   SourceLocation FakeOperatorLoc =
11750       SemaRef.getLocForEndOfToken(E->getBase()->getEndLoc());
11751   return getDerived().RebuildExtVectorElementExpr(
11752       Base.get(), FakeOperatorLoc, E->isArrow(), E->getAccessorLoc(),
11753       E->getAccessor());
11754 }
11755 
11756 template<typename Derived>
11757 ExprResult
11758 TreeTransform<Derived>::TransformInitListExpr(InitListExpr *E) {
11759   if (InitListExpr *Syntactic = E->getSyntacticForm())
11760     E = Syntactic;
11761 
11762   bool InitChanged = false;
11763 
11764   EnterExpressionEvaluationContext Context(
11765       getSema(), EnterExpressionEvaluationContext::InitList);
11766 
11767   SmallVector<Expr*, 4> Inits;
11768   if (getDerived().TransformExprs(E->getInits(), E->getNumInits(), false,
11769                                   Inits, &InitChanged))
11770     return ExprError();
11771 
11772   if (!getDerived().AlwaysRebuild() && !InitChanged) {
11773     // FIXME: Attempt to reuse the existing syntactic form of the InitListExpr
11774     // in some cases. We can't reuse it in general, because the syntactic and
11775     // semantic forms are linked, and we can't know that semantic form will
11776     // match even if the syntactic form does.
11777   }
11778 
11779   return getDerived().RebuildInitList(E->getLBraceLoc(), Inits,
11780                                       E->getRBraceLoc());
11781 }
11782 
11783 template<typename Derived>
11784 ExprResult
11785 TreeTransform<Derived>::TransformDesignatedInitExpr(DesignatedInitExpr *E) {
11786   Designation Desig;
11787 
11788   // transform the initializer value
11789   ExprResult Init = getDerived().TransformExpr(E->getInit());
11790   if (Init.isInvalid())
11791     return ExprError();
11792 
11793   // transform the designators.
11794   SmallVector<Expr*, 4> ArrayExprs;
11795   bool ExprChanged = false;
11796   for (const DesignatedInitExpr::Designator &D : E->designators()) {
11797     if (D.isFieldDesignator()) {
11798       if (D.getFieldDecl()) {
11799         FieldDecl *Field = cast_or_null<FieldDecl>(
11800             getDerived().TransformDecl(D.getFieldLoc(), D.getFieldDecl()));
11801         if (Field != D.getFieldDecl())
11802           // Rebuild the expression when the transformed FieldDecl is
11803           // different to the already assigned FieldDecl.
11804           ExprChanged = true;
11805         if (Field->isAnonymousStructOrUnion())
11806           continue;
11807       } else {
11808         // Ensure that the designator expression is rebuilt when there isn't
11809         // a resolved FieldDecl in the designator as we don't want to assign
11810         // a FieldDecl to a pattern designator that will be instantiated again.
11811         ExprChanged = true;
11812       }
11813       Desig.AddDesignator(Designator::CreateFieldDesignator(
11814           D.getFieldName(), D.getDotLoc(), D.getFieldLoc()));
11815       continue;
11816     }
11817 
11818     if (D.isArrayDesignator()) {
11819       ExprResult Index = getDerived().TransformExpr(E->getArrayIndex(D));
11820       if (Index.isInvalid())
11821         return ExprError();
11822 
11823       Desig.AddDesignator(
11824           Designator::CreateArrayDesignator(Index.get(), D.getLBracketLoc()));
11825 
11826       ExprChanged = ExprChanged || Init.get() != E->getArrayIndex(D);
11827       ArrayExprs.push_back(Index.get());
11828       continue;
11829     }
11830 
11831     assert(D.isArrayRangeDesignator() && "New kind of designator?");
11832     ExprResult Start
11833       = getDerived().TransformExpr(E->getArrayRangeStart(D));
11834     if (Start.isInvalid())
11835       return ExprError();
11836 
11837     ExprResult End = getDerived().TransformExpr(E->getArrayRangeEnd(D));
11838     if (End.isInvalid())
11839       return ExprError();
11840 
11841     Desig.AddDesignator(Designator::CreateArrayRangeDesignator(
11842         Start.get(), End.get(), D.getLBracketLoc(), D.getEllipsisLoc()));
11843 
11844     ExprChanged = ExprChanged || Start.get() != E->getArrayRangeStart(D) ||
11845                   End.get() != E->getArrayRangeEnd(D);
11846 
11847     ArrayExprs.push_back(Start.get());
11848     ArrayExprs.push_back(End.get());
11849   }
11850 
11851   if (!getDerived().AlwaysRebuild() &&
11852       Init.get() == E->getInit() &&
11853       !ExprChanged)
11854     return E;
11855 
11856   return getDerived().RebuildDesignatedInitExpr(Desig, ArrayExprs,
11857                                                 E->getEqualOrColonLoc(),
11858                                                 E->usesGNUSyntax(), Init.get());
11859 }
11860 
11861 // Seems that if TransformInitListExpr() only works on the syntactic form of an
11862 // InitListExpr, then a DesignatedInitUpdateExpr is not encountered.
11863 template<typename Derived>
11864 ExprResult
11865 TreeTransform<Derived>::TransformDesignatedInitUpdateExpr(
11866     DesignatedInitUpdateExpr *E) {
11867   llvm_unreachable("Unexpected DesignatedInitUpdateExpr in syntactic form of "
11868                    "initializer");
11869   return ExprError();
11870 }
11871 
11872 template<typename Derived>
11873 ExprResult
11874 TreeTransform<Derived>::TransformNoInitExpr(
11875     NoInitExpr *E) {
11876   llvm_unreachable("Unexpected NoInitExpr in syntactic form of initializer");
11877   return ExprError();
11878 }
11879 
11880 template<typename Derived>
11881 ExprResult
11882 TreeTransform<Derived>::TransformArrayInitLoopExpr(ArrayInitLoopExpr *E) {
11883   llvm_unreachable("Unexpected ArrayInitLoopExpr outside of initializer");
11884   return ExprError();
11885 }
11886 
11887 template<typename Derived>
11888 ExprResult
11889 TreeTransform<Derived>::TransformArrayInitIndexExpr(ArrayInitIndexExpr *E) {
11890   llvm_unreachable("Unexpected ArrayInitIndexExpr outside of initializer");
11891   return ExprError();
11892 }
11893 
11894 template<typename Derived>
11895 ExprResult
11896 TreeTransform<Derived>::TransformImplicitValueInitExpr(
11897                                                      ImplicitValueInitExpr *E) {
11898   TemporaryBase Rebase(*this, E->getBeginLoc(), DeclarationName());
11899 
11900   // FIXME: Will we ever have proper type location here? Will we actually
11901   // need to transform the type?
11902   QualType T = getDerived().TransformType(E->getType());
11903   if (T.isNull())
11904     return ExprError();
11905 
11906   if (!getDerived().AlwaysRebuild() &&
11907       T == E->getType())
11908     return E;
11909 
11910   return getDerived().RebuildImplicitValueInitExpr(T);
11911 }
11912 
11913 template<typename Derived>
11914 ExprResult
11915 TreeTransform<Derived>::TransformVAArgExpr(VAArgExpr *E) {
11916   TypeSourceInfo *TInfo = getDerived().TransformType(E->getWrittenTypeInfo());
11917   if (!TInfo)
11918     return ExprError();
11919 
11920   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
11921   if (SubExpr.isInvalid())
11922     return ExprError();
11923 
11924   if (!getDerived().AlwaysRebuild() &&
11925       TInfo == E->getWrittenTypeInfo() &&
11926       SubExpr.get() == E->getSubExpr())
11927     return E;
11928 
11929   return getDerived().RebuildVAArgExpr(E->getBuiltinLoc(), SubExpr.get(),
11930                                        TInfo, E->getRParenLoc());
11931 }
11932 
11933 template<typename Derived>
11934 ExprResult
11935 TreeTransform<Derived>::TransformParenListExpr(ParenListExpr *E) {
11936   bool ArgumentChanged = false;
11937   SmallVector<Expr*, 4> Inits;
11938   if (TransformExprs(E->getExprs(), E->getNumExprs(), true, Inits,
11939                      &ArgumentChanged))
11940     return ExprError();
11941 
11942   return getDerived().RebuildParenListExpr(E->getLParenLoc(),
11943                                            Inits,
11944                                            E->getRParenLoc());
11945 }
11946 
11947 /// Transform an address-of-label expression.
11948 ///
11949 /// By default, the transformation of an address-of-label expression always
11950 /// rebuilds the expression, so that the label identifier can be resolved to
11951 /// the corresponding label statement by semantic analysis.
11952 template<typename Derived>
11953 ExprResult
11954 TreeTransform<Derived>::TransformAddrLabelExpr(AddrLabelExpr *E) {
11955   Decl *LD = getDerived().TransformDecl(E->getLabel()->getLocation(),
11956                                         E->getLabel());
11957   if (!LD)
11958     return ExprError();
11959 
11960   return getDerived().RebuildAddrLabelExpr(E->getAmpAmpLoc(), E->getLabelLoc(),
11961                                            cast<LabelDecl>(LD));
11962 }
11963 
11964 template<typename Derived>
11965 ExprResult
11966 TreeTransform<Derived>::TransformStmtExpr(StmtExpr *E) {
11967   SemaRef.ActOnStartStmtExpr();
11968   StmtResult SubStmt
11969     = getDerived().TransformCompoundStmt(E->getSubStmt(), true);
11970   if (SubStmt.isInvalid()) {
11971     SemaRef.ActOnStmtExprError();
11972     return ExprError();
11973   }
11974 
11975   unsigned OldDepth = E->getTemplateDepth();
11976   unsigned NewDepth = getDerived().TransformTemplateDepth(OldDepth);
11977 
11978   if (!getDerived().AlwaysRebuild() && OldDepth == NewDepth &&
11979       SubStmt.get() == E->getSubStmt()) {
11980     // Calling this an 'error' is unintuitive, but it does the right thing.
11981     SemaRef.ActOnStmtExprError();
11982     return SemaRef.MaybeBindToTemporary(E);
11983   }
11984 
11985   return getDerived().RebuildStmtExpr(E->getLParenLoc(), SubStmt.get(),
11986                                       E->getRParenLoc(), NewDepth);
11987 }
11988 
11989 template<typename Derived>
11990 ExprResult
11991 TreeTransform<Derived>::TransformChooseExpr(ChooseExpr *E) {
11992   ExprResult Cond = getDerived().TransformExpr(E->getCond());
11993   if (Cond.isInvalid())
11994     return ExprError();
11995 
11996   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
11997   if (LHS.isInvalid())
11998     return ExprError();
11999 
12000   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
12001   if (RHS.isInvalid())
12002     return ExprError();
12003 
12004   if (!getDerived().AlwaysRebuild() &&
12005       Cond.get() == E->getCond() &&
12006       LHS.get() == E->getLHS() &&
12007       RHS.get() == E->getRHS())
12008     return E;
12009 
12010   return getDerived().RebuildChooseExpr(E->getBuiltinLoc(),
12011                                         Cond.get(), LHS.get(), RHS.get(),
12012                                         E->getRParenLoc());
12013 }
12014 
12015 template<typename Derived>
12016 ExprResult
12017 TreeTransform<Derived>::TransformGNUNullExpr(GNUNullExpr *E) {
12018   return E;
12019 }
12020 
12021 template<typename Derived>
12022 ExprResult
12023 TreeTransform<Derived>::TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
12024   switch (E->getOperator()) {
12025   case OO_New:
12026   case OO_Delete:
12027   case OO_Array_New:
12028   case OO_Array_Delete:
12029     llvm_unreachable("new and delete operators cannot use CXXOperatorCallExpr");
12030 
12031   case OO_Subscript:
12032   case OO_Call: {
12033     // This is a call to an object's operator().
12034     assert(E->getNumArgs() >= 1 && "Object call is missing arguments");
12035 
12036     // Transform the object itself.
12037     ExprResult Object = getDerived().TransformExpr(E->getArg(0));
12038     if (Object.isInvalid())
12039       return ExprError();
12040 
12041     // FIXME: Poor location information
12042     SourceLocation FakeLParenLoc = SemaRef.getLocForEndOfToken(
12043         static_cast<Expr *>(Object.get())->getEndLoc());
12044 
12045     // Transform the call arguments.
12046     SmallVector<Expr*, 8> Args;
12047     if (getDerived().TransformExprs(E->getArgs() + 1, E->getNumArgs() - 1, true,
12048                                     Args))
12049       return ExprError();
12050 
12051     if (E->getOperator() == OO_Subscript)
12052       return getDerived().RebuildCxxSubscriptExpr(Object.get(), FakeLParenLoc,
12053                                                   Args, E->getEndLoc());
12054 
12055     return getDerived().RebuildCallExpr(Object.get(), FakeLParenLoc, Args,
12056                                         E->getEndLoc());
12057   }
12058 
12059 #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly)  \
12060   case OO_##Name:                                                              \
12061     break;
12062 
12063 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
12064 #include "clang/Basic/OperatorKinds.def"
12065 
12066   case OO_Conditional:
12067     llvm_unreachable("conditional operator is not actually overloadable");
12068 
12069   case OO_None:
12070   case NUM_OVERLOADED_OPERATORS:
12071     llvm_unreachable("not an overloaded operator?");
12072   }
12073 
12074   ExprResult First;
12075   if (E->getOperator() == OO_Amp)
12076     First = getDerived().TransformAddressOfOperand(E->getArg(0));
12077   else
12078     First = getDerived().TransformExpr(E->getArg(0));
12079   if (First.isInvalid())
12080     return ExprError();
12081 
12082   ExprResult Second;
12083   if (E->getNumArgs() == 2) {
12084     Second =
12085         getDerived().TransformInitializer(E->getArg(1), /*NotCopyInit=*/false);
12086     if (Second.isInvalid())
12087       return ExprError();
12088   }
12089 
12090   Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
12091   FPOptionsOverride NewOverrides(E->getFPFeatures());
12092   getSema().CurFPFeatures =
12093       NewOverrides.applyOverrides(getSema().getLangOpts());
12094   getSema().FpPragmaStack.CurrentValue = NewOverrides;
12095 
12096   Expr *Callee = E->getCallee();
12097   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Callee)) {
12098     LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
12099                    Sema::LookupOrdinaryName);
12100     if (getDerived().TransformOverloadExprDecls(ULE, ULE->requiresADL(), R))
12101       return ExprError();
12102 
12103     return getDerived().RebuildCXXOperatorCallExpr(
12104         E->getOperator(), E->getOperatorLoc(), Callee->getBeginLoc(),
12105         ULE->requiresADL(), R.asUnresolvedSet(), First.get(), Second.get());
12106   }
12107 
12108   UnresolvedSet<1> Functions;
12109   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
12110     Callee = ICE->getSubExprAsWritten();
12111   NamedDecl *DR = cast<DeclRefExpr>(Callee)->getDecl();
12112   ValueDecl *VD = cast_or_null<ValueDecl>(
12113       getDerived().TransformDecl(DR->getLocation(), DR));
12114   if (!VD)
12115     return ExprError();
12116 
12117   if (!isa<CXXMethodDecl>(VD))
12118     Functions.addDecl(VD);
12119 
12120   return getDerived().RebuildCXXOperatorCallExpr(
12121       E->getOperator(), E->getOperatorLoc(), Callee->getBeginLoc(),
12122       /*RequiresADL=*/false, Functions, First.get(), Second.get());
12123 }
12124 
12125 template<typename Derived>
12126 ExprResult
12127 TreeTransform<Derived>::TransformCXXMemberCallExpr(CXXMemberCallExpr *E) {
12128   return getDerived().TransformCallExpr(E);
12129 }
12130 
12131 template <typename Derived>
12132 ExprResult TreeTransform<Derived>::TransformSourceLocExpr(SourceLocExpr *E) {
12133   bool NeedRebuildFunc = E->getIdentKind() == SourceLocIdentKind::Function &&
12134                          getSema().CurContext != E->getParentContext();
12135 
12136   if (!getDerived().AlwaysRebuild() && !NeedRebuildFunc)
12137     return E;
12138 
12139   return getDerived().RebuildSourceLocExpr(E->getIdentKind(), E->getType(),
12140                                            E->getBeginLoc(), E->getEndLoc(),
12141                                            getSema().CurContext);
12142 }
12143 
12144 template<typename Derived>
12145 ExprResult
12146 TreeTransform<Derived>::TransformCUDAKernelCallExpr(CUDAKernelCallExpr *E) {
12147   // Transform the callee.
12148   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
12149   if (Callee.isInvalid())
12150     return ExprError();
12151 
12152   // Transform exec config.
12153   ExprResult EC = getDerived().TransformCallExpr(E->getConfig());
12154   if (EC.isInvalid())
12155     return ExprError();
12156 
12157   // Transform arguments.
12158   bool ArgChanged = false;
12159   SmallVector<Expr*, 8> Args;
12160   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
12161                                   &ArgChanged))
12162     return ExprError();
12163 
12164   if (!getDerived().AlwaysRebuild() &&
12165       Callee.get() == E->getCallee() &&
12166       !ArgChanged)
12167     return SemaRef.MaybeBindToTemporary(E);
12168 
12169   // FIXME: Wrong source location information for the '('.
12170   SourceLocation FakeLParenLoc
12171     = ((Expr *)Callee.get())->getSourceRange().getBegin();
12172   return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
12173                                       Args,
12174                                       E->getRParenLoc(), EC.get());
12175 }
12176 
12177 template<typename Derived>
12178 ExprResult
12179 TreeTransform<Derived>::TransformCXXNamedCastExpr(CXXNamedCastExpr *E) {
12180   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
12181   if (!Type)
12182     return ExprError();
12183 
12184   ExprResult SubExpr
12185     = getDerived().TransformExpr(E->getSubExprAsWritten());
12186   if (SubExpr.isInvalid())
12187     return ExprError();
12188 
12189   if (!getDerived().AlwaysRebuild() &&
12190       Type == E->getTypeInfoAsWritten() &&
12191       SubExpr.get() == E->getSubExpr())
12192     return E;
12193   return getDerived().RebuildCXXNamedCastExpr(
12194       E->getOperatorLoc(), E->getStmtClass(), E->getAngleBrackets().getBegin(),
12195       Type, E->getAngleBrackets().getEnd(),
12196       // FIXME. this should be '(' location
12197       E->getAngleBrackets().getEnd(), SubExpr.get(), E->getRParenLoc());
12198 }
12199 
12200 template<typename Derived>
12201 ExprResult
12202 TreeTransform<Derived>::TransformBuiltinBitCastExpr(BuiltinBitCastExpr *BCE) {
12203   TypeSourceInfo *TSI =
12204       getDerived().TransformType(BCE->getTypeInfoAsWritten());
12205   if (!TSI)
12206     return ExprError();
12207 
12208   ExprResult Sub = getDerived().TransformExpr(BCE->getSubExpr());
12209   if (Sub.isInvalid())
12210     return ExprError();
12211 
12212   return getDerived().RebuildBuiltinBitCastExpr(BCE->getBeginLoc(), TSI,
12213                                                 Sub.get(), BCE->getEndLoc());
12214 }
12215 
12216 template<typename Derived>
12217 ExprResult
12218 TreeTransform<Derived>::TransformCXXStaticCastExpr(CXXStaticCastExpr *E) {
12219   return getDerived().TransformCXXNamedCastExpr(E);
12220 }
12221 
12222 template<typename Derived>
12223 ExprResult
12224 TreeTransform<Derived>::TransformCXXDynamicCastExpr(CXXDynamicCastExpr *E) {
12225   return getDerived().TransformCXXNamedCastExpr(E);
12226 }
12227 
12228 template<typename Derived>
12229 ExprResult
12230 TreeTransform<Derived>::TransformCXXReinterpretCastExpr(
12231                                                       CXXReinterpretCastExpr *E) {
12232   return getDerived().TransformCXXNamedCastExpr(E);
12233 }
12234 
12235 template<typename Derived>
12236 ExprResult
12237 TreeTransform<Derived>::TransformCXXConstCastExpr(CXXConstCastExpr *E) {
12238   return getDerived().TransformCXXNamedCastExpr(E);
12239 }
12240 
12241 template<typename Derived>
12242 ExprResult
12243 TreeTransform<Derived>::TransformCXXAddrspaceCastExpr(CXXAddrspaceCastExpr *E) {
12244   return getDerived().TransformCXXNamedCastExpr(E);
12245 }
12246 
12247 template<typename Derived>
12248 ExprResult
12249 TreeTransform<Derived>::TransformCXXFunctionalCastExpr(
12250                                                      CXXFunctionalCastExpr *E) {
12251   TypeSourceInfo *Type =
12252       getDerived().TransformTypeWithDeducedTST(E->getTypeInfoAsWritten());
12253   if (!Type)
12254     return ExprError();
12255 
12256   ExprResult SubExpr
12257     = getDerived().TransformExpr(E->getSubExprAsWritten());
12258   if (SubExpr.isInvalid())
12259     return ExprError();
12260 
12261   if (!getDerived().AlwaysRebuild() &&
12262       Type == E->getTypeInfoAsWritten() &&
12263       SubExpr.get() == E->getSubExpr())
12264     return E;
12265 
12266   return getDerived().RebuildCXXFunctionalCastExpr(Type,
12267                                                    E->getLParenLoc(),
12268                                                    SubExpr.get(),
12269                                                    E->getRParenLoc(),
12270                                                    E->isListInitialization());
12271 }
12272 
12273 template<typename Derived>
12274 ExprResult
12275 TreeTransform<Derived>::TransformCXXTypeidExpr(CXXTypeidExpr *E) {
12276   if (E->isTypeOperand()) {
12277     TypeSourceInfo *TInfo
12278       = getDerived().TransformType(E->getTypeOperandSourceInfo());
12279     if (!TInfo)
12280       return ExprError();
12281 
12282     if (!getDerived().AlwaysRebuild() &&
12283         TInfo == E->getTypeOperandSourceInfo())
12284       return E;
12285 
12286     return getDerived().RebuildCXXTypeidExpr(E->getType(), E->getBeginLoc(),
12287                                              TInfo, E->getEndLoc());
12288   }
12289 
12290   // Typeid's operand is an unevaluated context, unless it's a polymorphic
12291   // type.  We must not unilaterally enter unevaluated context here, as then
12292   // semantic processing can re-transform an already transformed operand.
12293   Expr *Op = E->getExprOperand();
12294   auto EvalCtx = Sema::ExpressionEvaluationContext::Unevaluated;
12295   if (E->isGLValue())
12296     if (auto *RecordT = Op->getType()->getAs<RecordType>())
12297       if (cast<CXXRecordDecl>(RecordT->getDecl())->isPolymorphic())
12298         EvalCtx = SemaRef.ExprEvalContexts.back().Context;
12299 
12300   EnterExpressionEvaluationContext Unevaluated(SemaRef, EvalCtx,
12301                                                Sema::ReuseLambdaContextDecl);
12302 
12303   ExprResult SubExpr = getDerived().TransformExpr(Op);
12304   if (SubExpr.isInvalid())
12305     return ExprError();
12306 
12307   if (!getDerived().AlwaysRebuild() &&
12308       SubExpr.get() == E->getExprOperand())
12309     return E;
12310 
12311   return getDerived().RebuildCXXTypeidExpr(E->getType(), E->getBeginLoc(),
12312                                            SubExpr.get(), E->getEndLoc());
12313 }
12314 
12315 template<typename Derived>
12316 ExprResult
12317 TreeTransform<Derived>::TransformCXXUuidofExpr(CXXUuidofExpr *E) {
12318   if (E->isTypeOperand()) {
12319     TypeSourceInfo *TInfo
12320       = getDerived().TransformType(E->getTypeOperandSourceInfo());
12321     if (!TInfo)
12322       return ExprError();
12323 
12324     if (!getDerived().AlwaysRebuild() &&
12325         TInfo == E->getTypeOperandSourceInfo())
12326       return E;
12327 
12328     return getDerived().RebuildCXXUuidofExpr(E->getType(), E->getBeginLoc(),
12329                                              TInfo, E->getEndLoc());
12330   }
12331 
12332   EnterExpressionEvaluationContext Unevaluated(
12333       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
12334 
12335   ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
12336   if (SubExpr.isInvalid())
12337     return ExprError();
12338 
12339   if (!getDerived().AlwaysRebuild() &&
12340       SubExpr.get() == E->getExprOperand())
12341     return E;
12342 
12343   return getDerived().RebuildCXXUuidofExpr(E->getType(), E->getBeginLoc(),
12344                                            SubExpr.get(), E->getEndLoc());
12345 }
12346 
12347 template<typename Derived>
12348 ExprResult
12349 TreeTransform<Derived>::TransformCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
12350   return E;
12351 }
12352 
12353 template<typename Derived>
12354 ExprResult
12355 TreeTransform<Derived>::TransformCXXNullPtrLiteralExpr(
12356                                                      CXXNullPtrLiteralExpr *E) {
12357   return E;
12358 }
12359 
12360 template<typename Derived>
12361 ExprResult
12362 TreeTransform<Derived>::TransformCXXThisExpr(CXXThisExpr *E) {
12363 
12364   // In lambdas, the qualifiers of the type depends of where in
12365   // the call operator `this` appear, and we do not have a good way to
12366   // rebuild this information, so we transform the type.
12367   //
12368   // In other contexts, the type of `this` may be overrided
12369   // for type deduction, so we need to recompute it.
12370   QualType T = getSema().getCurLambda() ?
12371                    getDerived().TransformType(E->getType())
12372                  : getSema().getCurrentThisType();
12373 
12374   if (!getDerived().AlwaysRebuild() && T == E->getType()) {
12375     // Mark it referenced in the new context regardless.
12376     // FIXME: this is a bit instantiation-specific.
12377     getSema().MarkThisReferenced(E);
12378     return E;
12379   }
12380 
12381   return getDerived().RebuildCXXThisExpr(E->getBeginLoc(), T, E->isImplicit());
12382 }
12383 
12384 template<typename Derived>
12385 ExprResult
12386 TreeTransform<Derived>::TransformCXXThrowExpr(CXXThrowExpr *E) {
12387   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
12388   if (SubExpr.isInvalid())
12389     return ExprError();
12390 
12391   if (!getDerived().AlwaysRebuild() &&
12392       SubExpr.get() == E->getSubExpr())
12393     return E;
12394 
12395   return getDerived().RebuildCXXThrowExpr(E->getThrowLoc(), SubExpr.get(),
12396                                           E->isThrownVariableInScope());
12397 }
12398 
12399 template<typename Derived>
12400 ExprResult
12401 TreeTransform<Derived>::TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
12402   ParmVarDecl *Param = cast_or_null<ParmVarDecl>(
12403       getDerived().TransformDecl(E->getBeginLoc(), E->getParam()));
12404   if (!Param)
12405     return ExprError();
12406 
12407   ExprResult InitRes;
12408   if (E->hasRewrittenInit()) {
12409     InitRes = getDerived().TransformExpr(E->getRewrittenExpr());
12410     if (InitRes.isInvalid())
12411       return ExprError();
12412   }
12413 
12414   if (!getDerived().AlwaysRebuild() && Param == E->getParam() &&
12415       E->getUsedContext() == SemaRef.CurContext &&
12416       InitRes.get() == E->getRewrittenExpr())
12417     return E;
12418 
12419   return getDerived().RebuildCXXDefaultArgExpr(E->getUsedLocation(), Param,
12420                                                InitRes.get());
12421 }
12422 
12423 template<typename Derived>
12424 ExprResult
12425 TreeTransform<Derived>::TransformCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
12426   FieldDecl *Field = cast_or_null<FieldDecl>(
12427       getDerived().TransformDecl(E->getBeginLoc(), E->getField()));
12428   if (!Field)
12429     return ExprError();
12430 
12431   if (!getDerived().AlwaysRebuild() && Field == E->getField() &&
12432       E->getUsedContext() == SemaRef.CurContext)
12433     return E;
12434 
12435   return getDerived().RebuildCXXDefaultInitExpr(E->getExprLoc(), Field);
12436 }
12437 
12438 template<typename Derived>
12439 ExprResult
12440 TreeTransform<Derived>::TransformCXXScalarValueInitExpr(
12441                                                     CXXScalarValueInitExpr *E) {
12442   TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
12443   if (!T)
12444     return ExprError();
12445 
12446   if (!getDerived().AlwaysRebuild() &&
12447       T == E->getTypeSourceInfo())
12448     return E;
12449 
12450   return getDerived().RebuildCXXScalarValueInitExpr(T,
12451                                           /*FIXME:*/T->getTypeLoc().getEndLoc(),
12452                                                     E->getRParenLoc());
12453 }
12454 
12455 template<typename Derived>
12456 ExprResult
12457 TreeTransform<Derived>::TransformCXXNewExpr(CXXNewExpr *E) {
12458   // Transform the type that we're allocating
12459   TypeSourceInfo *AllocTypeInfo =
12460       getDerived().TransformTypeWithDeducedTST(E->getAllocatedTypeSourceInfo());
12461   if (!AllocTypeInfo)
12462     return ExprError();
12463 
12464   // Transform the size of the array we're allocating (if any).
12465   std::optional<Expr *> ArraySize;
12466   if (E->isArray()) {
12467     ExprResult NewArraySize;
12468     if (std::optional<Expr *> OldArraySize = E->getArraySize()) {
12469       NewArraySize = getDerived().TransformExpr(*OldArraySize);
12470       if (NewArraySize.isInvalid())
12471         return ExprError();
12472     }
12473     ArraySize = NewArraySize.get();
12474   }
12475 
12476   // Transform the placement arguments (if any).
12477   bool ArgumentChanged = false;
12478   SmallVector<Expr*, 8> PlacementArgs;
12479   if (getDerived().TransformExprs(E->getPlacementArgs(),
12480                                   E->getNumPlacementArgs(), true,
12481                                   PlacementArgs, &ArgumentChanged))
12482     return ExprError();
12483 
12484   // Transform the initializer (if any).
12485   Expr *OldInit = E->getInitializer();
12486   ExprResult NewInit;
12487   if (OldInit)
12488     NewInit = getDerived().TransformInitializer(OldInit, true);
12489   if (NewInit.isInvalid())
12490     return ExprError();
12491 
12492   // Transform new operator and delete operator.
12493   FunctionDecl *OperatorNew = nullptr;
12494   if (E->getOperatorNew()) {
12495     OperatorNew = cast_or_null<FunctionDecl>(
12496         getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorNew()));
12497     if (!OperatorNew)
12498       return ExprError();
12499   }
12500 
12501   FunctionDecl *OperatorDelete = nullptr;
12502   if (E->getOperatorDelete()) {
12503     OperatorDelete = cast_or_null<FunctionDecl>(
12504         getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorDelete()));
12505     if (!OperatorDelete)
12506       return ExprError();
12507   }
12508 
12509   if (!getDerived().AlwaysRebuild() &&
12510       AllocTypeInfo == E->getAllocatedTypeSourceInfo() &&
12511       ArraySize == E->getArraySize() &&
12512       NewInit.get() == OldInit &&
12513       OperatorNew == E->getOperatorNew() &&
12514       OperatorDelete == E->getOperatorDelete() &&
12515       !ArgumentChanged) {
12516     // Mark any declarations we need as referenced.
12517     // FIXME: instantiation-specific.
12518     if (OperatorNew)
12519       SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorNew);
12520     if (OperatorDelete)
12521       SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorDelete);
12522 
12523     if (E->isArray() && !E->getAllocatedType()->isDependentType()) {
12524       QualType ElementType
12525         = SemaRef.Context.getBaseElementType(E->getAllocatedType());
12526       if (const RecordType *RecordT = ElementType->getAs<RecordType>()) {
12527         CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordT->getDecl());
12528         if (CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(Record)) {
12529           SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Destructor);
12530         }
12531       }
12532     }
12533 
12534     return E;
12535   }
12536 
12537   QualType AllocType = AllocTypeInfo->getType();
12538   if (!ArraySize) {
12539     // If no array size was specified, but the new expression was
12540     // instantiated with an array type (e.g., "new T" where T is
12541     // instantiated with "int[4]"), extract the outer bound from the
12542     // array type as our array size. We do this with constant and
12543     // dependently-sized array types.
12544     const ArrayType *ArrayT = SemaRef.Context.getAsArrayType(AllocType);
12545     if (!ArrayT) {
12546       // Do nothing
12547     } else if (const ConstantArrayType *ConsArrayT
12548                                      = dyn_cast<ConstantArrayType>(ArrayT)) {
12549       ArraySize = IntegerLiteral::Create(SemaRef.Context, ConsArrayT->getSize(),
12550                                          SemaRef.Context.getSizeType(),
12551                                          /*FIXME:*/ E->getBeginLoc());
12552       AllocType = ConsArrayT->getElementType();
12553     } else if (const DependentSizedArrayType *DepArrayT
12554                               = dyn_cast<DependentSizedArrayType>(ArrayT)) {
12555       if (DepArrayT->getSizeExpr()) {
12556         ArraySize = DepArrayT->getSizeExpr();
12557         AllocType = DepArrayT->getElementType();
12558       }
12559     }
12560   }
12561 
12562   return getDerived().RebuildCXXNewExpr(
12563       E->getBeginLoc(), E->isGlobalNew(),
12564       /*FIXME:*/ E->getBeginLoc(), PlacementArgs,
12565       /*FIXME:*/ E->getBeginLoc(), E->getTypeIdParens(), AllocType,
12566       AllocTypeInfo, ArraySize, E->getDirectInitRange(), NewInit.get());
12567 }
12568 
12569 template<typename Derived>
12570 ExprResult
12571 TreeTransform<Derived>::TransformCXXDeleteExpr(CXXDeleteExpr *E) {
12572   ExprResult Operand = getDerived().TransformExpr(E->getArgument());
12573   if (Operand.isInvalid())
12574     return ExprError();
12575 
12576   // Transform the delete operator, if known.
12577   FunctionDecl *OperatorDelete = nullptr;
12578   if (E->getOperatorDelete()) {
12579     OperatorDelete = cast_or_null<FunctionDecl>(
12580         getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorDelete()));
12581     if (!OperatorDelete)
12582       return ExprError();
12583   }
12584 
12585   if (!getDerived().AlwaysRebuild() &&
12586       Operand.get() == E->getArgument() &&
12587       OperatorDelete == E->getOperatorDelete()) {
12588     // Mark any declarations we need as referenced.
12589     // FIXME: instantiation-specific.
12590     if (OperatorDelete)
12591       SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorDelete);
12592 
12593     if (!E->getArgument()->isTypeDependent()) {
12594       QualType Destroyed = SemaRef.Context.getBaseElementType(
12595                                                          E->getDestroyedType());
12596       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
12597         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
12598         SemaRef.MarkFunctionReferenced(E->getBeginLoc(),
12599                                        SemaRef.LookupDestructor(Record));
12600       }
12601     }
12602 
12603     return E;
12604   }
12605 
12606   return getDerived().RebuildCXXDeleteExpr(
12607       E->getBeginLoc(), E->isGlobalDelete(), E->isArrayForm(), Operand.get());
12608 }
12609 
12610 template<typename Derived>
12611 ExprResult
12612 TreeTransform<Derived>::TransformCXXPseudoDestructorExpr(
12613                                                      CXXPseudoDestructorExpr *E) {
12614   ExprResult Base = getDerived().TransformExpr(E->getBase());
12615   if (Base.isInvalid())
12616     return ExprError();
12617 
12618   ParsedType ObjectTypePtr;
12619   bool MayBePseudoDestructor = false;
12620   Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
12621                                               E->getOperatorLoc(),
12622                                         E->isArrow()? tok::arrow : tok::period,
12623                                               ObjectTypePtr,
12624                                               MayBePseudoDestructor);
12625   if (Base.isInvalid())
12626     return ExprError();
12627 
12628   QualType ObjectType = ObjectTypePtr.get();
12629   NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc();
12630   if (QualifierLoc) {
12631     QualifierLoc
12632       = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc, ObjectType);
12633     if (!QualifierLoc)
12634       return ExprError();
12635   }
12636   CXXScopeSpec SS;
12637   SS.Adopt(QualifierLoc);
12638 
12639   PseudoDestructorTypeStorage Destroyed;
12640   if (E->getDestroyedTypeInfo()) {
12641     TypeSourceInfo *DestroyedTypeInfo
12642       = getDerived().TransformTypeInObjectScope(E->getDestroyedTypeInfo(),
12643                                                 ObjectType, nullptr, SS);
12644     if (!DestroyedTypeInfo)
12645       return ExprError();
12646     Destroyed = DestroyedTypeInfo;
12647   } else if (!ObjectType.isNull() && ObjectType->isDependentType()) {
12648     // We aren't likely to be able to resolve the identifier down to a type
12649     // now anyway, so just retain the identifier.
12650     Destroyed = PseudoDestructorTypeStorage(E->getDestroyedTypeIdentifier(),
12651                                             E->getDestroyedTypeLoc());
12652   } else {
12653     // Look for a destructor known with the given name.
12654     ParsedType T = SemaRef.getDestructorName(
12655         *E->getDestroyedTypeIdentifier(), E->getDestroyedTypeLoc(),
12656         /*Scope=*/nullptr, SS, ObjectTypePtr, false);
12657     if (!T)
12658       return ExprError();
12659 
12660     Destroyed
12661       = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.GetTypeFromParser(T),
12662                                                  E->getDestroyedTypeLoc());
12663   }
12664 
12665   TypeSourceInfo *ScopeTypeInfo = nullptr;
12666   if (E->getScopeTypeInfo()) {
12667     CXXScopeSpec EmptySS;
12668     ScopeTypeInfo = getDerived().TransformTypeInObjectScope(
12669                       E->getScopeTypeInfo(), ObjectType, nullptr, EmptySS);
12670     if (!ScopeTypeInfo)
12671       return ExprError();
12672   }
12673 
12674   return getDerived().RebuildCXXPseudoDestructorExpr(Base.get(),
12675                                                      E->getOperatorLoc(),
12676                                                      E->isArrow(),
12677                                                      SS,
12678                                                      ScopeTypeInfo,
12679                                                      E->getColonColonLoc(),
12680                                                      E->getTildeLoc(),
12681                                                      Destroyed);
12682 }
12683 
12684 template <typename Derived>
12685 bool TreeTransform<Derived>::TransformOverloadExprDecls(OverloadExpr *Old,
12686                                                         bool RequiresADL,
12687                                                         LookupResult &R) {
12688   // Transform all the decls.
12689   bool AllEmptyPacks = true;
12690   for (auto *OldD : Old->decls()) {
12691     Decl *InstD = getDerived().TransformDecl(Old->getNameLoc(), OldD);
12692     if (!InstD) {
12693       // Silently ignore these if a UsingShadowDecl instantiated to nothing.
12694       // This can happen because of dependent hiding.
12695       if (isa<UsingShadowDecl>(OldD))
12696         continue;
12697       else {
12698         R.clear();
12699         return true;
12700       }
12701     }
12702 
12703     // Expand using pack declarations.
12704     NamedDecl *SingleDecl = cast<NamedDecl>(InstD);
12705     ArrayRef<NamedDecl*> Decls = SingleDecl;
12706     if (auto *UPD = dyn_cast<UsingPackDecl>(InstD))
12707       Decls = UPD->expansions();
12708 
12709     // Expand using declarations.
12710     for (auto *D : Decls) {
12711       if (auto *UD = dyn_cast<UsingDecl>(D)) {
12712         for (auto *SD : UD->shadows())
12713           R.addDecl(SD);
12714       } else {
12715         R.addDecl(D);
12716       }
12717     }
12718 
12719     AllEmptyPacks &= Decls.empty();
12720   };
12721 
12722   // C++ [temp.res]/8.4.2:
12723   //   The program is ill-formed, no diagnostic required, if [...] lookup for
12724   //   a name in the template definition found a using-declaration, but the
12725   //   lookup in the corresponding scope in the instantiation odoes not find
12726   //   any declarations because the using-declaration was a pack expansion and
12727   //   the corresponding pack is empty
12728   if (AllEmptyPacks && !RequiresADL) {
12729     getSema().Diag(Old->getNameLoc(), diag::err_using_pack_expansion_empty)
12730         << isa<UnresolvedMemberExpr>(Old) << Old->getName();
12731     return true;
12732   }
12733 
12734   // Resolve a kind, but don't do any further analysis.  If it's
12735   // ambiguous, the callee needs to deal with it.
12736   R.resolveKind();
12737   return false;
12738 }
12739 
12740 template<typename Derived>
12741 ExprResult
12742 TreeTransform<Derived>::TransformUnresolvedLookupExpr(
12743                                                   UnresolvedLookupExpr *Old) {
12744   LookupResult R(SemaRef, Old->getName(), Old->getNameLoc(),
12745                  Sema::LookupOrdinaryName);
12746 
12747   // Transform the declaration set.
12748   if (TransformOverloadExprDecls(Old, Old->requiresADL(), R))
12749     return ExprError();
12750 
12751   // Rebuild the nested-name qualifier, if present.
12752   CXXScopeSpec SS;
12753   if (Old->getQualifierLoc()) {
12754     NestedNameSpecifierLoc QualifierLoc
12755       = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
12756     if (!QualifierLoc)
12757       return ExprError();
12758 
12759     SS.Adopt(QualifierLoc);
12760   }
12761 
12762   if (Old->getNamingClass()) {
12763     CXXRecordDecl *NamingClass
12764       = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
12765                                                             Old->getNameLoc(),
12766                                                         Old->getNamingClass()));
12767     if (!NamingClass) {
12768       R.clear();
12769       return ExprError();
12770     }
12771 
12772     R.setNamingClass(NamingClass);
12773   }
12774 
12775   SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
12776 
12777   // If we have neither explicit template arguments, nor the template keyword,
12778   // it's a normal declaration name or member reference.
12779   if (!Old->hasExplicitTemplateArgs() && !TemplateKWLoc.isValid()) {
12780     NamedDecl *D = R.getAsSingle<NamedDecl>();
12781     // In a C++11 unevaluated context, an UnresolvedLookupExpr might refer to an
12782     // instance member. In other contexts, BuildPossibleImplicitMemberExpr will
12783     // give a good diagnostic.
12784     if (D && D->isCXXInstanceMember()) {
12785       return SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
12786                                                      /*TemplateArgs=*/nullptr,
12787                                                      /*Scope=*/nullptr);
12788     }
12789 
12790     return getDerived().RebuildDeclarationNameExpr(SS, R, Old->requiresADL());
12791   }
12792 
12793   // If we have template arguments, rebuild them, then rebuild the
12794   // templateid expression.
12795   TemplateArgumentListInfo TransArgs(Old->getLAngleLoc(), Old->getRAngleLoc());
12796   if (Old->hasExplicitTemplateArgs() &&
12797       getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
12798                                               Old->getNumTemplateArgs(),
12799                                               TransArgs)) {
12800     R.clear();
12801     return ExprError();
12802   }
12803 
12804   return getDerived().RebuildTemplateIdExpr(SS, TemplateKWLoc, R,
12805                                             Old->requiresADL(), &TransArgs);
12806 }
12807 
12808 template<typename Derived>
12809 ExprResult
12810 TreeTransform<Derived>::TransformTypeTraitExpr(TypeTraitExpr *E) {
12811   bool ArgChanged = false;
12812   SmallVector<TypeSourceInfo *, 4> Args;
12813   for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I) {
12814     TypeSourceInfo *From = E->getArg(I);
12815     TypeLoc FromTL = From->getTypeLoc();
12816     if (!FromTL.getAs<PackExpansionTypeLoc>()) {
12817       TypeLocBuilder TLB;
12818       TLB.reserve(FromTL.getFullDataSize());
12819       QualType To = getDerived().TransformType(TLB, FromTL);
12820       if (To.isNull())
12821         return ExprError();
12822 
12823       if (To == From->getType())
12824         Args.push_back(From);
12825       else {
12826         Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
12827         ArgChanged = true;
12828       }
12829       continue;
12830     }
12831 
12832     ArgChanged = true;
12833 
12834     // We have a pack expansion. Instantiate it.
12835     PackExpansionTypeLoc ExpansionTL = FromTL.castAs<PackExpansionTypeLoc>();
12836     TypeLoc PatternTL = ExpansionTL.getPatternLoc();
12837     SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12838     SemaRef.collectUnexpandedParameterPacks(PatternTL, Unexpanded);
12839 
12840     // Determine whether the set of unexpanded parameter packs can and should
12841     // be expanded.
12842     bool Expand = true;
12843     bool RetainExpansion = false;
12844     std::optional<unsigned> OrigNumExpansions =
12845         ExpansionTL.getTypePtr()->getNumExpansions();
12846     std::optional<unsigned> NumExpansions = OrigNumExpansions;
12847     if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
12848                                              PatternTL.getSourceRange(),
12849                                              Unexpanded,
12850                                              Expand, RetainExpansion,
12851                                              NumExpansions))
12852       return ExprError();
12853 
12854     if (!Expand) {
12855       // The transform has determined that we should perform a simple
12856       // transformation on the pack expansion, producing another pack
12857       // expansion.
12858       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
12859 
12860       TypeLocBuilder TLB;
12861       TLB.reserve(From->getTypeLoc().getFullDataSize());
12862 
12863       QualType To = getDerived().TransformType(TLB, PatternTL);
12864       if (To.isNull())
12865         return ExprError();
12866 
12867       To = getDerived().RebuildPackExpansionType(To,
12868                                                  PatternTL.getSourceRange(),
12869                                                  ExpansionTL.getEllipsisLoc(),
12870                                                  NumExpansions);
12871       if (To.isNull())
12872         return ExprError();
12873 
12874       PackExpansionTypeLoc ToExpansionTL
12875         = TLB.push<PackExpansionTypeLoc>(To);
12876       ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
12877       Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
12878       continue;
12879     }
12880 
12881     // Expand the pack expansion by substituting for each argument in the
12882     // pack(s).
12883     for (unsigned I = 0; I != *NumExpansions; ++I) {
12884       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
12885       TypeLocBuilder TLB;
12886       TLB.reserve(PatternTL.getFullDataSize());
12887       QualType To = getDerived().TransformType(TLB, PatternTL);
12888       if (To.isNull())
12889         return ExprError();
12890 
12891       if (To->containsUnexpandedParameterPack()) {
12892         To = getDerived().RebuildPackExpansionType(To,
12893                                                    PatternTL.getSourceRange(),
12894                                                    ExpansionTL.getEllipsisLoc(),
12895                                                    NumExpansions);
12896         if (To.isNull())
12897           return ExprError();
12898 
12899         PackExpansionTypeLoc ToExpansionTL
12900           = TLB.push<PackExpansionTypeLoc>(To);
12901         ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
12902       }
12903 
12904       Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
12905     }
12906 
12907     if (!RetainExpansion)
12908       continue;
12909 
12910     // If we're supposed to retain a pack expansion, do so by temporarily
12911     // forgetting the partially-substituted parameter pack.
12912     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
12913 
12914     TypeLocBuilder TLB;
12915     TLB.reserve(From->getTypeLoc().getFullDataSize());
12916 
12917     QualType To = getDerived().TransformType(TLB, PatternTL);
12918     if (To.isNull())
12919       return ExprError();
12920 
12921     To = getDerived().RebuildPackExpansionType(To,
12922                                                PatternTL.getSourceRange(),
12923                                                ExpansionTL.getEllipsisLoc(),
12924                                                NumExpansions);
12925     if (To.isNull())
12926       return ExprError();
12927 
12928     PackExpansionTypeLoc ToExpansionTL
12929       = TLB.push<PackExpansionTypeLoc>(To);
12930     ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
12931     Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
12932   }
12933 
12934   if (!getDerived().AlwaysRebuild() && !ArgChanged)
12935     return E;
12936 
12937   return getDerived().RebuildTypeTrait(E->getTrait(), E->getBeginLoc(), Args,
12938                                        E->getEndLoc());
12939 }
12940 
12941 template<typename Derived>
12942 ExprResult
12943 TreeTransform<Derived>::TransformConceptSpecializationExpr(
12944                                                  ConceptSpecializationExpr *E) {
12945   const ASTTemplateArgumentListInfo *Old = E->getTemplateArgsAsWritten();
12946   TemplateArgumentListInfo TransArgs(Old->LAngleLoc, Old->RAngleLoc);
12947   if (getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
12948                                               Old->NumTemplateArgs, TransArgs))
12949     return ExprError();
12950 
12951   return getDerived().RebuildConceptSpecializationExpr(
12952       E->getNestedNameSpecifierLoc(), E->getTemplateKWLoc(),
12953       E->getConceptNameInfo(), E->getFoundDecl(), E->getNamedConcept(),
12954       &TransArgs);
12955 }
12956 
12957 template<typename Derived>
12958 ExprResult
12959 TreeTransform<Derived>::TransformRequiresExpr(RequiresExpr *E) {
12960   SmallVector<ParmVarDecl*, 4> TransParams;
12961   SmallVector<QualType, 4> TransParamTypes;
12962   Sema::ExtParameterInfoBuilder ExtParamInfos;
12963 
12964   // C++2a [expr.prim.req]p2
12965   // Expressions appearing within a requirement-body are unevaluated operands.
12966   EnterExpressionEvaluationContext Ctx(
12967       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
12968       Sema::ReuseLambdaContextDecl);
12969 
12970   RequiresExprBodyDecl *Body = RequiresExprBodyDecl::Create(
12971       getSema().Context, getSema().CurContext,
12972       E->getBody()->getBeginLoc());
12973 
12974   Sema::ContextRAII SavedContext(getSema(), Body, /*NewThisContext*/false);
12975 
12976   ExprResult TypeParamResult = getDerived().TransformRequiresTypeParams(
12977       E->getRequiresKWLoc(), E->getRBraceLoc(), E, Body,
12978       E->getLocalParameters(), TransParamTypes, TransParams, ExtParamInfos);
12979 
12980   for (ParmVarDecl *Param : TransParams)
12981     if (Param)
12982       Param->setDeclContext(Body);
12983 
12984   // On failure to transform, TransformRequiresTypeParams returns an expression
12985   // in the event that the transformation of the type params failed in some way.
12986   // It is expected that this will result in a 'not satisfied' Requires clause
12987   // when instantiating.
12988   if (!TypeParamResult.isUnset())
12989     return TypeParamResult;
12990 
12991   SmallVector<concepts::Requirement *, 4> TransReqs;
12992   if (getDerived().TransformRequiresExprRequirements(E->getRequirements(),
12993                                                      TransReqs))
12994     return ExprError();
12995 
12996   for (concepts::Requirement *Req : TransReqs) {
12997     if (auto *ER = dyn_cast<concepts::ExprRequirement>(Req)) {
12998       if (ER->getReturnTypeRequirement().isTypeConstraint()) {
12999         ER->getReturnTypeRequirement()
13000                 .getTypeConstraintTemplateParameterList()->getParam(0)
13001                 ->setDeclContext(Body);
13002       }
13003     }
13004   }
13005 
13006   return getDerived().RebuildRequiresExpr(
13007       E->getRequiresKWLoc(), Body, E->getLParenLoc(), TransParams,
13008       E->getRParenLoc(), TransReqs, E->getRBraceLoc());
13009 }
13010 
13011 template<typename Derived>
13012 bool TreeTransform<Derived>::TransformRequiresExprRequirements(
13013     ArrayRef<concepts::Requirement *> Reqs,
13014     SmallVectorImpl<concepts::Requirement *> &Transformed) {
13015   for (concepts::Requirement *Req : Reqs) {
13016     concepts::Requirement *TransReq = nullptr;
13017     if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Req))
13018       TransReq = getDerived().TransformTypeRequirement(TypeReq);
13019     else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Req))
13020       TransReq = getDerived().TransformExprRequirement(ExprReq);
13021     else
13022       TransReq = getDerived().TransformNestedRequirement(
13023                      cast<concepts::NestedRequirement>(Req));
13024     if (!TransReq)
13025       return true;
13026     Transformed.push_back(TransReq);
13027   }
13028   return false;
13029 }
13030 
13031 template<typename Derived>
13032 concepts::TypeRequirement *
13033 TreeTransform<Derived>::TransformTypeRequirement(
13034     concepts::TypeRequirement *Req) {
13035   if (Req->isSubstitutionFailure()) {
13036     if (getDerived().AlwaysRebuild())
13037       return getDerived().RebuildTypeRequirement(
13038               Req->getSubstitutionDiagnostic());
13039     return Req;
13040   }
13041   TypeSourceInfo *TransType = getDerived().TransformType(Req->getType());
13042   if (!TransType)
13043     return nullptr;
13044   return getDerived().RebuildTypeRequirement(TransType);
13045 }
13046 
13047 template<typename Derived>
13048 concepts::ExprRequirement *
13049 TreeTransform<Derived>::TransformExprRequirement(concepts::ExprRequirement *Req) {
13050   llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *> TransExpr;
13051   if (Req->isExprSubstitutionFailure())
13052     TransExpr = Req->getExprSubstitutionDiagnostic();
13053   else {
13054     ExprResult TransExprRes = getDerived().TransformExpr(Req->getExpr());
13055     if (TransExprRes.isUsable() && TransExprRes.get()->hasPlaceholderType())
13056       TransExprRes = SemaRef.CheckPlaceholderExpr(TransExprRes.get());
13057     if (TransExprRes.isInvalid())
13058       return nullptr;
13059     TransExpr = TransExprRes.get();
13060   }
13061 
13062   std::optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq;
13063   const auto &RetReq = Req->getReturnTypeRequirement();
13064   if (RetReq.isEmpty())
13065     TransRetReq.emplace();
13066   else if (RetReq.isSubstitutionFailure())
13067     TransRetReq.emplace(RetReq.getSubstitutionDiagnostic());
13068   else if (RetReq.isTypeConstraint()) {
13069     TemplateParameterList *OrigTPL =
13070         RetReq.getTypeConstraintTemplateParameterList();
13071     TemplateParameterList *TPL =
13072         getDerived().TransformTemplateParameterList(OrigTPL);
13073     if (!TPL)
13074       return nullptr;
13075     TransRetReq.emplace(TPL);
13076   }
13077   assert(TransRetReq && "All code paths leading here must set TransRetReq");
13078   if (Expr *E = TransExpr.dyn_cast<Expr *>())
13079     return getDerived().RebuildExprRequirement(E, Req->isSimple(),
13080                                                Req->getNoexceptLoc(),
13081                                                std::move(*TransRetReq));
13082   return getDerived().RebuildExprRequirement(
13083       TransExpr.get<concepts::Requirement::SubstitutionDiagnostic *>(),
13084       Req->isSimple(), Req->getNoexceptLoc(), std::move(*TransRetReq));
13085 }
13086 
13087 template<typename Derived>
13088 concepts::NestedRequirement *
13089 TreeTransform<Derived>::TransformNestedRequirement(
13090     concepts::NestedRequirement *Req) {
13091   if (Req->hasInvalidConstraint()) {
13092     if (getDerived().AlwaysRebuild())
13093       return getDerived().RebuildNestedRequirement(
13094           Req->getInvalidConstraintEntity(), Req->getConstraintSatisfaction());
13095     return Req;
13096   }
13097   ExprResult TransConstraint =
13098       getDerived().TransformExpr(Req->getConstraintExpr());
13099   if (TransConstraint.isInvalid())
13100     return nullptr;
13101   return getDerived().RebuildNestedRequirement(TransConstraint.get());
13102 }
13103 
13104 template<typename Derived>
13105 ExprResult
13106 TreeTransform<Derived>::TransformArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
13107   TypeSourceInfo *T = getDerived().TransformType(E->getQueriedTypeSourceInfo());
13108   if (!T)
13109     return ExprError();
13110 
13111   if (!getDerived().AlwaysRebuild() &&
13112       T == E->getQueriedTypeSourceInfo())
13113     return E;
13114 
13115   ExprResult SubExpr;
13116   {
13117     EnterExpressionEvaluationContext Unevaluated(
13118         SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
13119     SubExpr = getDerived().TransformExpr(E->getDimensionExpression());
13120     if (SubExpr.isInvalid())
13121       return ExprError();
13122 
13123     if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getDimensionExpression())
13124       return E;
13125   }
13126 
13127   return getDerived().RebuildArrayTypeTrait(E->getTrait(), E->getBeginLoc(), T,
13128                                             SubExpr.get(), E->getEndLoc());
13129 }
13130 
13131 template<typename Derived>
13132 ExprResult
13133 TreeTransform<Derived>::TransformExpressionTraitExpr(ExpressionTraitExpr *E) {
13134   ExprResult SubExpr;
13135   {
13136     EnterExpressionEvaluationContext Unevaluated(
13137         SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
13138     SubExpr = getDerived().TransformExpr(E->getQueriedExpression());
13139     if (SubExpr.isInvalid())
13140       return ExprError();
13141 
13142     if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getQueriedExpression())
13143       return E;
13144   }
13145 
13146   return getDerived().RebuildExpressionTrait(E->getTrait(), E->getBeginLoc(),
13147                                              SubExpr.get(), E->getEndLoc());
13148 }
13149 
13150 template <typename Derived>
13151 ExprResult TreeTransform<Derived>::TransformParenDependentScopeDeclRefExpr(
13152     ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool AddrTaken,
13153     TypeSourceInfo **RecoveryTSI) {
13154   ExprResult NewDRE = getDerived().TransformDependentScopeDeclRefExpr(
13155       DRE, AddrTaken, RecoveryTSI);
13156 
13157   // Propagate both errors and recovered types, which return ExprEmpty.
13158   if (!NewDRE.isUsable())
13159     return NewDRE;
13160 
13161   // We got an expr, wrap it up in parens.
13162   if (!getDerived().AlwaysRebuild() && NewDRE.get() == DRE)
13163     return PE;
13164   return getDerived().RebuildParenExpr(NewDRE.get(), PE->getLParen(),
13165                                        PE->getRParen());
13166 }
13167 
13168 template <typename Derived>
13169 ExprResult TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
13170     DependentScopeDeclRefExpr *E) {
13171   return TransformDependentScopeDeclRefExpr(E, /*IsAddressOfOperand=*/false,
13172                                             nullptr);
13173 }
13174 
13175 template <typename Derived>
13176 ExprResult TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
13177     DependentScopeDeclRefExpr *E, bool IsAddressOfOperand,
13178     TypeSourceInfo **RecoveryTSI) {
13179   assert(E->getQualifierLoc());
13180   NestedNameSpecifierLoc QualifierLoc =
13181       getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
13182   if (!QualifierLoc)
13183     return ExprError();
13184   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
13185 
13186   // TODO: If this is a conversion-function-id, verify that the
13187   // destination type name (if present) resolves the same way after
13188   // instantiation as it did in the local scope.
13189 
13190   DeclarationNameInfo NameInfo =
13191       getDerived().TransformDeclarationNameInfo(E->getNameInfo());
13192   if (!NameInfo.getName())
13193     return ExprError();
13194 
13195   if (!E->hasExplicitTemplateArgs()) {
13196     if (!getDerived().AlwaysRebuild() && QualifierLoc == E->getQualifierLoc() &&
13197         // Note: it is sufficient to compare the Name component of NameInfo:
13198         // if name has not changed, DNLoc has not changed either.
13199         NameInfo.getName() == E->getDeclName())
13200       return E;
13201 
13202     return getDerived().RebuildDependentScopeDeclRefExpr(
13203         QualifierLoc, TemplateKWLoc, NameInfo, /*TemplateArgs=*/nullptr,
13204         IsAddressOfOperand, RecoveryTSI);
13205   }
13206 
13207   TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
13208   if (getDerived().TransformTemplateArguments(
13209           E->getTemplateArgs(), E->getNumTemplateArgs(), TransArgs))
13210     return ExprError();
13211 
13212   return getDerived().RebuildDependentScopeDeclRefExpr(
13213       QualifierLoc, TemplateKWLoc, NameInfo, &TransArgs, IsAddressOfOperand,
13214       RecoveryTSI);
13215 }
13216 
13217 template<typename Derived>
13218 ExprResult
13219 TreeTransform<Derived>::TransformCXXConstructExpr(CXXConstructExpr *E) {
13220   // CXXConstructExprs other than for list-initialization and
13221   // CXXTemporaryObjectExpr are always implicit, so when we have
13222   // a 1-argument construction we just transform that argument.
13223   if (getDerived().AllowSkippingCXXConstructExpr() &&
13224       ((E->getNumArgs() == 1 ||
13225         (E->getNumArgs() > 1 && getDerived().DropCallArgument(E->getArg(1)))) &&
13226        (!getDerived().DropCallArgument(E->getArg(0))) &&
13227        !E->isListInitialization()))
13228     return getDerived().TransformInitializer(E->getArg(0),
13229                                              /*DirectInit*/ false);
13230 
13231   TemporaryBase Rebase(*this, /*FIXME*/ E->getBeginLoc(), DeclarationName());
13232 
13233   QualType T = getDerived().TransformType(E->getType());
13234   if (T.isNull())
13235     return ExprError();
13236 
13237   CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
13238       getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
13239   if (!Constructor)
13240     return ExprError();
13241 
13242   bool ArgumentChanged = false;
13243   SmallVector<Expr*, 8> Args;
13244   {
13245     EnterExpressionEvaluationContext Context(
13246         getSema(), EnterExpressionEvaluationContext::InitList,
13247         E->isListInitialization());
13248     if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
13249                                     &ArgumentChanged))
13250       return ExprError();
13251   }
13252 
13253   if (!getDerived().AlwaysRebuild() &&
13254       T == E->getType() &&
13255       Constructor == E->getConstructor() &&
13256       !ArgumentChanged) {
13257     // Mark the constructor as referenced.
13258     // FIXME: Instantiation-specific
13259     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
13260     return E;
13261   }
13262 
13263   return getDerived().RebuildCXXConstructExpr(
13264       T, /*FIXME:*/ E->getBeginLoc(), Constructor, E->isElidable(), Args,
13265       E->hadMultipleCandidates(), E->isListInitialization(),
13266       E->isStdInitListInitialization(), E->requiresZeroInitialization(),
13267       E->getConstructionKind(), E->getParenOrBraceRange());
13268 }
13269 
13270 template<typename Derived>
13271 ExprResult TreeTransform<Derived>::TransformCXXInheritedCtorInitExpr(
13272     CXXInheritedCtorInitExpr *E) {
13273   QualType T = getDerived().TransformType(E->getType());
13274   if (T.isNull())
13275     return ExprError();
13276 
13277   CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
13278       getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
13279   if (!Constructor)
13280     return ExprError();
13281 
13282   if (!getDerived().AlwaysRebuild() &&
13283       T == E->getType() &&
13284       Constructor == E->getConstructor()) {
13285     // Mark the constructor as referenced.
13286     // FIXME: Instantiation-specific
13287     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
13288     return E;
13289   }
13290 
13291   return getDerived().RebuildCXXInheritedCtorInitExpr(
13292       T, E->getLocation(), Constructor,
13293       E->constructsVBase(), E->inheritedFromVBase());
13294 }
13295 
13296 /// Transform a C++ temporary-binding expression.
13297 ///
13298 /// Since CXXBindTemporaryExpr nodes are implicitly generated, we just
13299 /// transform the subexpression and return that.
13300 template<typename Derived>
13301 ExprResult
13302 TreeTransform<Derived>::TransformCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
13303   if (auto *Dtor = E->getTemporary()->getDestructor())
13304     SemaRef.MarkFunctionReferenced(E->getBeginLoc(),
13305                                    const_cast<CXXDestructorDecl *>(Dtor));
13306   return getDerived().TransformExpr(E->getSubExpr());
13307 }
13308 
13309 /// Transform a C++ expression that contains cleanups that should
13310 /// be run after the expression is evaluated.
13311 ///
13312 /// Since ExprWithCleanups nodes are implicitly generated, we
13313 /// just transform the subexpression and return that.
13314 template<typename Derived>
13315 ExprResult
13316 TreeTransform<Derived>::TransformExprWithCleanups(ExprWithCleanups *E) {
13317   return getDerived().TransformExpr(E->getSubExpr());
13318 }
13319 
13320 template<typename Derived>
13321 ExprResult
13322 TreeTransform<Derived>::TransformCXXTemporaryObjectExpr(
13323                                                     CXXTemporaryObjectExpr *E) {
13324   TypeSourceInfo *T =
13325       getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
13326   if (!T)
13327     return ExprError();
13328 
13329   CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
13330       getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
13331   if (!Constructor)
13332     return ExprError();
13333 
13334   bool ArgumentChanged = false;
13335   SmallVector<Expr*, 8> Args;
13336   Args.reserve(E->getNumArgs());
13337   {
13338     EnterExpressionEvaluationContext Context(
13339         getSema(), EnterExpressionEvaluationContext::InitList,
13340         E->isListInitialization());
13341     if (TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
13342                        &ArgumentChanged))
13343       return ExprError();
13344   }
13345 
13346   if (!getDerived().AlwaysRebuild() &&
13347       T == E->getTypeSourceInfo() &&
13348       Constructor == E->getConstructor() &&
13349       !ArgumentChanged) {
13350     // FIXME: Instantiation-specific
13351     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
13352     return SemaRef.MaybeBindToTemporary(E);
13353   }
13354 
13355   // FIXME: We should just pass E->isListInitialization(), but we're not
13356   // prepared to handle list-initialization without a child InitListExpr.
13357   SourceLocation LParenLoc = T->getTypeLoc().getEndLoc();
13358   return getDerived().RebuildCXXTemporaryObjectExpr(
13359       T, LParenLoc, Args, E->getEndLoc(),
13360       /*ListInitialization=*/LParenLoc.isInvalid());
13361 }
13362 
13363 template<typename Derived>
13364 ExprResult
13365 TreeTransform<Derived>::TransformLambdaExpr(LambdaExpr *E) {
13366   // Transform any init-capture expressions before entering the scope of the
13367   // lambda body, because they are not semantically within that scope.
13368   typedef std::pair<ExprResult, QualType> InitCaptureInfoTy;
13369   struct TransformedInitCapture {
13370     // The location of the ... if the result is retaining a pack expansion.
13371     SourceLocation EllipsisLoc;
13372     // Zero or more expansions of the init-capture.
13373     SmallVector<InitCaptureInfoTy, 4> Expansions;
13374   };
13375   SmallVector<TransformedInitCapture, 4> InitCaptures;
13376   InitCaptures.resize(E->explicit_capture_end() - E->explicit_capture_begin());
13377   for (LambdaExpr::capture_iterator C = E->capture_begin(),
13378                                     CEnd = E->capture_end();
13379        C != CEnd; ++C) {
13380     if (!E->isInitCapture(C))
13381       continue;
13382 
13383     TransformedInitCapture &Result = InitCaptures[C - E->capture_begin()];
13384     auto *OldVD = cast<VarDecl>(C->getCapturedVar());
13385 
13386     auto SubstInitCapture = [&](SourceLocation EllipsisLoc,
13387                                 std::optional<unsigned> NumExpansions) {
13388       ExprResult NewExprInitResult = getDerived().TransformInitializer(
13389           OldVD->getInit(), OldVD->getInitStyle() == VarDecl::CallInit);
13390 
13391       if (NewExprInitResult.isInvalid()) {
13392         Result.Expansions.push_back(InitCaptureInfoTy(ExprError(), QualType()));
13393         return;
13394       }
13395       Expr *NewExprInit = NewExprInitResult.get();
13396 
13397       QualType NewInitCaptureType =
13398           getSema().buildLambdaInitCaptureInitialization(
13399               C->getLocation(), C->getCaptureKind() == LCK_ByRef,
13400               EllipsisLoc, NumExpansions, OldVD->getIdentifier(),
13401               cast<VarDecl>(C->getCapturedVar())->getInitStyle() !=
13402                   VarDecl::CInit,
13403               NewExprInit);
13404       Result.Expansions.push_back(
13405           InitCaptureInfoTy(NewExprInit, NewInitCaptureType));
13406     };
13407 
13408     // If this is an init-capture pack, consider expanding the pack now.
13409     if (OldVD->isParameterPack()) {
13410       PackExpansionTypeLoc ExpansionTL = OldVD->getTypeSourceInfo()
13411                                              ->getTypeLoc()
13412                                              .castAs<PackExpansionTypeLoc>();
13413       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13414       SemaRef.collectUnexpandedParameterPacks(OldVD->getInit(), Unexpanded);
13415 
13416       // Determine whether the set of unexpanded parameter packs can and should
13417       // be expanded.
13418       bool Expand = true;
13419       bool RetainExpansion = false;
13420       std::optional<unsigned> OrigNumExpansions =
13421           ExpansionTL.getTypePtr()->getNumExpansions();
13422       std::optional<unsigned> NumExpansions = OrigNumExpansions;
13423       if (getDerived().TryExpandParameterPacks(
13424               ExpansionTL.getEllipsisLoc(),
13425               OldVD->getInit()->getSourceRange(), Unexpanded, Expand,
13426               RetainExpansion, NumExpansions))
13427         return ExprError();
13428       if (Expand) {
13429         for (unsigned I = 0; I != *NumExpansions; ++I) {
13430           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
13431           SubstInitCapture(SourceLocation(), std::nullopt);
13432         }
13433       }
13434       if (!Expand || RetainExpansion) {
13435         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
13436         SubstInitCapture(ExpansionTL.getEllipsisLoc(), NumExpansions);
13437         Result.EllipsisLoc = ExpansionTL.getEllipsisLoc();
13438       }
13439     } else {
13440       SubstInitCapture(SourceLocation(), std::nullopt);
13441     }
13442   }
13443 
13444   LambdaScopeInfo *LSI = getSema().PushLambdaScope();
13445   Sema::FunctionScopeRAII FuncScopeCleanup(getSema());
13446 
13447   // Create the local class that will describe the lambda.
13448 
13449   // FIXME: DependencyKind below is wrong when substituting inside a templated
13450   // context that isn't a DeclContext (such as a variable template), or when
13451   // substituting an unevaluated lambda inside of a function's parameter's type
13452   // - as parameter types are not instantiated from within a function's DC. We
13453   // use evaluation contexts to distinguish the function parameter case.
13454   CXXRecordDecl::LambdaDependencyKind DependencyKind =
13455       CXXRecordDecl::LDK_Unknown;
13456   if ((getSema().isUnevaluatedContext() ||
13457        getSema().isConstantEvaluatedContext()) &&
13458       (getSema().CurContext->isFileContext() ||
13459        !getSema().CurContext->getParent()->isDependentContext()))
13460     DependencyKind = CXXRecordDecl::LDK_NeverDependent;
13461 
13462   CXXRecordDecl *OldClass = E->getLambdaClass();
13463   CXXRecordDecl *Class = getSema().createLambdaClosureType(
13464       E->getIntroducerRange(), /*Info=*/nullptr, DependencyKind,
13465       E->getCaptureDefault());
13466   getDerived().transformedLocalDecl(OldClass, {Class});
13467 
13468   CXXMethodDecl *NewCallOperator =
13469       getSema().CreateLambdaCallOperator(E->getIntroducerRange(), Class);
13470   NewCallOperator->setLexicalDeclContext(getSema().CurContext);
13471 
13472   // Enter the scope of the lambda.
13473   getSema().buildLambdaScope(LSI, NewCallOperator, E->getIntroducerRange(),
13474                              E->getCaptureDefault(), E->getCaptureDefaultLoc(),
13475                              E->hasExplicitParameters(), E->isMutable());
13476 
13477   // Introduce the context of the call operator.
13478   Sema::ContextRAII SavedContext(getSema(), NewCallOperator,
13479                                  /*NewThisContext*/false);
13480 
13481   bool Invalid = false;
13482 
13483   // Transform captures.
13484   for (LambdaExpr::capture_iterator C = E->capture_begin(),
13485                                  CEnd = E->capture_end();
13486        C != CEnd; ++C) {
13487     // When we hit the first implicit capture, tell Sema that we've finished
13488     // the list of explicit captures.
13489     if (C->isImplicit())
13490       break;
13491 
13492     // Capturing 'this' is trivial.
13493     if (C->capturesThis()) {
13494       getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit(),
13495                                     /*BuildAndDiagnose*/ true, nullptr,
13496                                     C->getCaptureKind() == LCK_StarThis);
13497       continue;
13498     }
13499     // Captured expression will be recaptured during captured variables
13500     // rebuilding.
13501     if (C->capturesVLAType())
13502       continue;
13503 
13504     // Rebuild init-captures, including the implied field declaration.
13505     if (E->isInitCapture(C)) {
13506       TransformedInitCapture &NewC = InitCaptures[C - E->capture_begin()];
13507 
13508       auto *OldVD = cast<VarDecl>(C->getCapturedVar());
13509       llvm::SmallVector<Decl*, 4> NewVDs;
13510 
13511       for (InitCaptureInfoTy &Info : NewC.Expansions) {
13512         ExprResult Init = Info.first;
13513         QualType InitQualType = Info.second;
13514         if (Init.isInvalid() || InitQualType.isNull()) {
13515           Invalid = true;
13516           break;
13517         }
13518         VarDecl *NewVD = getSema().createLambdaInitCaptureVarDecl(
13519             OldVD->getLocation(), InitQualType, NewC.EllipsisLoc,
13520             OldVD->getIdentifier(), OldVD->getInitStyle(), Init.get(),
13521             getSema().CurContext);
13522         if (!NewVD) {
13523           Invalid = true;
13524           break;
13525         }
13526         NewVDs.push_back(NewVD);
13527         getSema().addInitCapture(LSI, NewVD, C->getCaptureKind() == LCK_ByRef);
13528       }
13529 
13530       if (Invalid)
13531         break;
13532 
13533       getDerived().transformedLocalDecl(OldVD, NewVDs);
13534       continue;
13535     }
13536 
13537     assert(C->capturesVariable() && "unexpected kind of lambda capture");
13538 
13539     // Determine the capture kind for Sema.
13540     Sema::TryCaptureKind Kind
13541       = C->isImplicit()? Sema::TryCapture_Implicit
13542                        : C->getCaptureKind() == LCK_ByCopy
13543                            ? Sema::TryCapture_ExplicitByVal
13544                            : Sema::TryCapture_ExplicitByRef;
13545     SourceLocation EllipsisLoc;
13546     if (C->isPackExpansion()) {
13547       UnexpandedParameterPack Unexpanded(C->getCapturedVar(), C->getLocation());
13548       bool ShouldExpand = false;
13549       bool RetainExpansion = false;
13550       std::optional<unsigned> NumExpansions;
13551       if (getDerived().TryExpandParameterPacks(C->getEllipsisLoc(),
13552                                                C->getLocation(),
13553                                                Unexpanded,
13554                                                ShouldExpand, RetainExpansion,
13555                                                NumExpansions)) {
13556         Invalid = true;
13557         continue;
13558       }
13559 
13560       if (ShouldExpand) {
13561         // The transform has determined that we should perform an expansion;
13562         // transform and capture each of the arguments.
13563         // expansion of the pattern. Do so.
13564         auto *Pack = cast<VarDecl>(C->getCapturedVar());
13565         for (unsigned I = 0; I != *NumExpansions; ++I) {
13566           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
13567           VarDecl *CapturedVar
13568             = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
13569                                                                Pack));
13570           if (!CapturedVar) {
13571             Invalid = true;
13572             continue;
13573           }
13574 
13575           // Capture the transformed variable.
13576           getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind);
13577         }
13578 
13579         // FIXME: Retain a pack expansion if RetainExpansion is true.
13580 
13581         continue;
13582       }
13583 
13584       EllipsisLoc = C->getEllipsisLoc();
13585     }
13586 
13587     // Transform the captured variable.
13588     auto *CapturedVar = cast_or_null<ValueDecl>(
13589         getDerived().TransformDecl(C->getLocation(), C->getCapturedVar()));
13590     if (!CapturedVar || CapturedVar->isInvalidDecl()) {
13591       Invalid = true;
13592       continue;
13593     }
13594 
13595     // Capture the transformed variable.
13596     getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind,
13597                                  EllipsisLoc);
13598   }
13599   getSema().finishLambdaExplicitCaptures(LSI);
13600 
13601   // Transform the template parameters, and add them to the current
13602   // instantiation scope. The null case is handled correctly.
13603   auto TPL = getDerived().TransformTemplateParameterList(
13604       E->getTemplateParameterList());
13605   LSI->GLTemplateParameterList = TPL;
13606   if (TPL)
13607     getSema().AddTemplateParametersToLambdaCallOperator(NewCallOperator, Class,
13608                                                         TPL);
13609 
13610   // Transform the type of the original lambda's call operator.
13611   // The transformation MUST be done in the CurrentInstantiationScope since
13612   // it introduces a mapping of the original to the newly created
13613   // transformed parameters.
13614   TypeSourceInfo *NewCallOpTSI = nullptr;
13615   {
13616     auto OldCallOpTypeLoc =
13617         E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
13618 
13619     auto TransformFunctionProtoTypeLoc =
13620         [this](TypeLocBuilder &TLB, FunctionProtoTypeLoc FPTL) -> QualType {
13621       SmallVector<QualType, 4> ExceptionStorage;
13622       TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
13623       return this->TransformFunctionProtoType(
13624           TLB, FPTL, nullptr, Qualifiers(),
13625           [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
13626             return This->TransformExceptionSpec(FPTL.getBeginLoc(), ESI,
13627                                                 ExceptionStorage, Changed);
13628           });
13629     };
13630 
13631     QualType NewCallOpType;
13632     TypeLocBuilder NewCallOpTLBuilder;
13633 
13634     if (auto ATL = OldCallOpTypeLoc.getAs<AttributedTypeLoc>()) {
13635       NewCallOpType = this->TransformAttributedType(
13636           NewCallOpTLBuilder, ATL,
13637           [&](TypeLocBuilder &TLB, TypeLoc TL) -> QualType {
13638             return TransformFunctionProtoTypeLoc(
13639                 TLB, TL.castAs<FunctionProtoTypeLoc>());
13640           });
13641     } else {
13642       auto FPTL = OldCallOpTypeLoc.castAs<FunctionProtoTypeLoc>();
13643       NewCallOpType = TransformFunctionProtoTypeLoc(NewCallOpTLBuilder, FPTL);
13644     }
13645 
13646     if (NewCallOpType.isNull())
13647       return ExprError();
13648     NewCallOpTSI =
13649         NewCallOpTLBuilder.getTypeSourceInfo(getSema().Context, NewCallOpType);
13650   }
13651 
13652   ArrayRef<ParmVarDecl *> Params;
13653   if (auto ATL = NewCallOpTSI->getTypeLoc().getAs<AttributedTypeLoc>()) {
13654     Params = ATL.getModifiedLoc().castAs<FunctionProtoTypeLoc>().getParams();
13655   } else {
13656     auto FPTL = NewCallOpTSI->getTypeLoc().castAs<FunctionProtoTypeLoc>();
13657     Params = FPTL.getParams();
13658   }
13659 
13660   getSema().CompleteLambdaCallOperator(
13661       NewCallOperator, E->getCallOperator()->getLocation(),
13662       E->getCallOperator()->getInnerLocStart(),
13663       E->getCallOperator()->getTrailingRequiresClause(), NewCallOpTSI,
13664       E->getCallOperator()->getConstexprKind(),
13665       E->getCallOperator()->getStorageClass(), Params,
13666       E->hasExplicitResultType());
13667 
13668   getDerived().transformAttrs(E->getCallOperator(), NewCallOperator);
13669   getDerived().transformedLocalDecl(E->getCallOperator(), {NewCallOperator});
13670 
13671   {
13672     // Number the lambda for linkage purposes if necessary.
13673     Sema::ContextRAII ManglingContext(getSema(), Class->getDeclContext());
13674 
13675     std::optional<CXXRecordDecl::LambdaNumbering> Numbering;
13676     if (getDerived().ReplacingOriginal()) {
13677       Numbering = OldClass->getLambdaNumbering();
13678     }
13679 
13680     getSema().handleLambdaNumbering(Class, NewCallOperator, Numbering);
13681   }
13682 
13683   // FIXME: Sema's lambda-building mechanism expects us to push an expression
13684   // evaluation context even if we're not transforming the function body.
13685   getSema().PushExpressionEvaluationContext(
13686       Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
13687 
13688   Sema::CodeSynthesisContext C;
13689   C.Kind = clang::Sema::CodeSynthesisContext::LambdaExpressionSubstitution;
13690   C.PointOfInstantiation = E->getBody()->getBeginLoc();
13691   getSema().pushCodeSynthesisContext(C);
13692 
13693   // Instantiate the body of the lambda expression.
13694   StmtResult Body =
13695       Invalid ? StmtError() : getDerived().TransformLambdaBody(E, E->getBody());
13696 
13697   getSema().popCodeSynthesisContext();
13698 
13699   // ActOnLambda* will pop the function scope for us.
13700   FuncScopeCleanup.disable();
13701 
13702   if (Body.isInvalid()) {
13703     SavedContext.pop();
13704     getSema().ActOnLambdaError(E->getBeginLoc(), /*CurScope=*/nullptr,
13705                                /*IsInstantiation=*/true);
13706     return ExprError();
13707   }
13708 
13709   // Copy the LSI before ActOnFinishFunctionBody removes it.
13710   // FIXME: This is dumb. Store the lambda information somewhere that outlives
13711   // the call operator.
13712   auto LSICopy = *LSI;
13713   getSema().ActOnFinishFunctionBody(NewCallOperator, Body.get(),
13714                                     /*IsInstantiation*/ true);
13715   SavedContext.pop();
13716 
13717   return getSema().BuildLambdaExpr(E->getBeginLoc(), Body.get()->getEndLoc(),
13718                                    &LSICopy);
13719 }
13720 
13721 template<typename Derived>
13722 StmtResult
13723 TreeTransform<Derived>::TransformLambdaBody(LambdaExpr *E, Stmt *S) {
13724   return TransformStmt(S);
13725 }
13726 
13727 template<typename Derived>
13728 StmtResult
13729 TreeTransform<Derived>::SkipLambdaBody(LambdaExpr *E, Stmt *S) {
13730   // Transform captures.
13731   for (LambdaExpr::capture_iterator C = E->capture_begin(),
13732                                  CEnd = E->capture_end();
13733        C != CEnd; ++C) {
13734     // When we hit the first implicit capture, tell Sema that we've finished
13735     // the list of explicit captures.
13736     if (!C->isImplicit())
13737       continue;
13738 
13739     // Capturing 'this' is trivial.
13740     if (C->capturesThis()) {
13741       getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit(),
13742                                     /*BuildAndDiagnose*/ true, nullptr,
13743                                     C->getCaptureKind() == LCK_StarThis);
13744       continue;
13745     }
13746     // Captured expression will be recaptured during captured variables
13747     // rebuilding.
13748     if (C->capturesVLAType())
13749       continue;
13750 
13751     assert(C->capturesVariable() && "unexpected kind of lambda capture");
13752     assert(!E->isInitCapture(C) && "implicit init-capture?");
13753 
13754     // Transform the captured variable.
13755     VarDecl *CapturedVar = cast_or_null<VarDecl>(
13756         getDerived().TransformDecl(C->getLocation(), C->getCapturedVar()));
13757     if (!CapturedVar || CapturedVar->isInvalidDecl())
13758       return StmtError();
13759 
13760     // Capture the transformed variable.
13761     getSema().tryCaptureVariable(CapturedVar, C->getLocation());
13762   }
13763 
13764   return S;
13765 }
13766 
13767 template<typename Derived>
13768 ExprResult
13769 TreeTransform<Derived>::TransformCXXUnresolvedConstructExpr(
13770                                                   CXXUnresolvedConstructExpr *E) {
13771   TypeSourceInfo *T =
13772       getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
13773   if (!T)
13774     return ExprError();
13775 
13776   bool ArgumentChanged = false;
13777   SmallVector<Expr*, 8> Args;
13778   Args.reserve(E->getNumArgs());
13779   {
13780     EnterExpressionEvaluationContext Context(
13781         getSema(), EnterExpressionEvaluationContext::InitList,
13782         E->isListInitialization());
13783     if (getDerived().TransformExprs(E->arg_begin(), E->getNumArgs(), true, Args,
13784                                     &ArgumentChanged))
13785       return ExprError();
13786   }
13787 
13788   if (!getDerived().AlwaysRebuild() &&
13789       T == E->getTypeSourceInfo() &&
13790       !ArgumentChanged)
13791     return E;
13792 
13793   // FIXME: we're faking the locations of the commas
13794   return getDerived().RebuildCXXUnresolvedConstructExpr(
13795       T, E->getLParenLoc(), Args, E->getRParenLoc(), E->isListInitialization());
13796 }
13797 
13798 template<typename Derived>
13799 ExprResult
13800 TreeTransform<Derived>::TransformCXXDependentScopeMemberExpr(
13801                                              CXXDependentScopeMemberExpr *E) {
13802   // Transform the base of the expression.
13803   ExprResult Base((Expr*) nullptr);
13804   Expr *OldBase;
13805   QualType BaseType;
13806   QualType ObjectType;
13807   if (!E->isImplicitAccess()) {
13808     OldBase = E->getBase();
13809     Base = getDerived().TransformExpr(OldBase);
13810     if (Base.isInvalid())
13811       return ExprError();
13812 
13813     // Start the member reference and compute the object's type.
13814     ParsedType ObjectTy;
13815     bool MayBePseudoDestructor = false;
13816     Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
13817                                                 E->getOperatorLoc(),
13818                                       E->isArrow()? tok::arrow : tok::period,
13819                                                 ObjectTy,
13820                                                 MayBePseudoDestructor);
13821     if (Base.isInvalid())
13822       return ExprError();
13823 
13824     ObjectType = ObjectTy.get();
13825     BaseType = ((Expr*) Base.get())->getType();
13826   } else {
13827     OldBase = nullptr;
13828     BaseType = getDerived().TransformType(E->getBaseType());
13829     ObjectType = BaseType->castAs<PointerType>()->getPointeeType();
13830   }
13831 
13832   // Transform the first part of the nested-name-specifier that qualifies
13833   // the member name.
13834   NamedDecl *FirstQualifierInScope
13835     = getDerived().TransformFirstQualifierInScope(
13836                                             E->getFirstQualifierFoundInScope(),
13837                                             E->getQualifierLoc().getBeginLoc());
13838 
13839   NestedNameSpecifierLoc QualifierLoc;
13840   if (E->getQualifier()) {
13841     QualifierLoc
13842       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc(),
13843                                                      ObjectType,
13844                                                      FirstQualifierInScope);
13845     if (!QualifierLoc)
13846       return ExprError();
13847   }
13848 
13849   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
13850 
13851   // TODO: If this is a conversion-function-id, verify that the
13852   // destination type name (if present) resolves the same way after
13853   // instantiation as it did in the local scope.
13854 
13855   DeclarationNameInfo NameInfo
13856     = getDerived().TransformDeclarationNameInfo(E->getMemberNameInfo());
13857   if (!NameInfo.getName())
13858     return ExprError();
13859 
13860   if (!E->hasExplicitTemplateArgs()) {
13861     // This is a reference to a member without an explicitly-specified
13862     // template argument list. Optimize for this common case.
13863     if (!getDerived().AlwaysRebuild() &&
13864         Base.get() == OldBase &&
13865         BaseType == E->getBaseType() &&
13866         QualifierLoc == E->getQualifierLoc() &&
13867         NameInfo.getName() == E->getMember() &&
13868         FirstQualifierInScope == E->getFirstQualifierFoundInScope())
13869       return E;
13870 
13871     return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
13872                                                        BaseType,
13873                                                        E->isArrow(),
13874                                                        E->getOperatorLoc(),
13875                                                        QualifierLoc,
13876                                                        TemplateKWLoc,
13877                                                        FirstQualifierInScope,
13878                                                        NameInfo,
13879                                                        /*TemplateArgs*/nullptr);
13880   }
13881 
13882   TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
13883   if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
13884                                               E->getNumTemplateArgs(),
13885                                               TransArgs))
13886     return ExprError();
13887 
13888   return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
13889                                                      BaseType,
13890                                                      E->isArrow(),
13891                                                      E->getOperatorLoc(),
13892                                                      QualifierLoc,
13893                                                      TemplateKWLoc,
13894                                                      FirstQualifierInScope,
13895                                                      NameInfo,
13896                                                      &TransArgs);
13897 }
13898 
13899 template <typename Derived>
13900 ExprResult TreeTransform<Derived>::TransformUnresolvedMemberExpr(
13901     UnresolvedMemberExpr *Old) {
13902   // Transform the base of the expression.
13903   ExprResult Base((Expr *)nullptr);
13904   QualType BaseType;
13905   if (!Old->isImplicitAccess()) {
13906     Base = getDerived().TransformExpr(Old->getBase());
13907     if (Base.isInvalid())
13908       return ExprError();
13909     Base =
13910         getSema().PerformMemberExprBaseConversion(Base.get(), Old->isArrow());
13911     if (Base.isInvalid())
13912       return ExprError();
13913     BaseType = Base.get()->getType();
13914   } else {
13915     BaseType = getDerived().TransformType(Old->getBaseType());
13916   }
13917 
13918   NestedNameSpecifierLoc QualifierLoc;
13919   if (Old->getQualifierLoc()) {
13920     QualifierLoc =
13921         getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
13922     if (!QualifierLoc)
13923       return ExprError();
13924   }
13925 
13926   SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
13927 
13928   LookupResult R(SemaRef, Old->getMemberNameInfo(), Sema::LookupOrdinaryName);
13929 
13930   // Transform the declaration set.
13931   if (TransformOverloadExprDecls(Old, /*RequiresADL*/ false, R))
13932     return ExprError();
13933 
13934   // Determine the naming class.
13935   if (Old->getNamingClass()) {
13936     CXXRecordDecl *NamingClass = cast_or_null<CXXRecordDecl>(
13937         getDerived().TransformDecl(Old->getMemberLoc(), Old->getNamingClass()));
13938     if (!NamingClass)
13939       return ExprError();
13940 
13941     R.setNamingClass(NamingClass);
13942   }
13943 
13944   TemplateArgumentListInfo TransArgs;
13945   if (Old->hasExplicitTemplateArgs()) {
13946     TransArgs.setLAngleLoc(Old->getLAngleLoc());
13947     TransArgs.setRAngleLoc(Old->getRAngleLoc());
13948     if (getDerived().TransformTemplateArguments(
13949             Old->getTemplateArgs(), Old->getNumTemplateArgs(), TransArgs))
13950       return ExprError();
13951   }
13952 
13953   // FIXME: to do this check properly, we will need to preserve the
13954   // first-qualifier-in-scope here, just in case we had a dependent
13955   // base (and therefore couldn't do the check) and a
13956   // nested-name-qualifier (and therefore could do the lookup).
13957   NamedDecl *FirstQualifierInScope = nullptr;
13958 
13959   return getDerived().RebuildUnresolvedMemberExpr(
13960       Base.get(), BaseType, Old->getOperatorLoc(), Old->isArrow(), QualifierLoc,
13961       TemplateKWLoc, FirstQualifierInScope, R,
13962       (Old->hasExplicitTemplateArgs() ? &TransArgs : nullptr));
13963 }
13964 
13965 template<typename Derived>
13966 ExprResult
13967 TreeTransform<Derived>::TransformCXXNoexceptExpr(CXXNoexceptExpr *E) {
13968   EnterExpressionEvaluationContext Unevaluated(
13969       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
13970   ExprResult SubExpr = getDerived().TransformExpr(E->getOperand());
13971   if (SubExpr.isInvalid())
13972     return ExprError();
13973 
13974   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getOperand())
13975     return E;
13976 
13977   return getDerived().RebuildCXXNoexceptExpr(E->getSourceRange(),SubExpr.get());
13978 }
13979 
13980 template<typename Derived>
13981 ExprResult
13982 TreeTransform<Derived>::TransformPackExpansionExpr(PackExpansionExpr *E) {
13983   ExprResult Pattern = getDerived().TransformExpr(E->getPattern());
13984   if (Pattern.isInvalid())
13985     return ExprError();
13986 
13987   if (!getDerived().AlwaysRebuild() && Pattern.get() == E->getPattern())
13988     return E;
13989 
13990   return getDerived().RebuildPackExpansion(Pattern.get(), E->getEllipsisLoc(),
13991                                            E->getNumExpansions());
13992 }
13993 
13994 template<typename Derived>
13995 ExprResult
13996 TreeTransform<Derived>::TransformSizeOfPackExpr(SizeOfPackExpr *E) {
13997   // If E is not value-dependent, then nothing will change when we transform it.
13998   // Note: This is an instantiation-centric view.
13999   if (!E->isValueDependent())
14000     return E;
14001 
14002   EnterExpressionEvaluationContext Unevaluated(
14003       getSema(), Sema::ExpressionEvaluationContext::Unevaluated);
14004 
14005   ArrayRef<TemplateArgument> PackArgs;
14006   TemplateArgument ArgStorage;
14007 
14008   // Find the argument list to transform.
14009   if (E->isPartiallySubstituted()) {
14010     PackArgs = E->getPartialArguments();
14011   } else if (E->isValueDependent()) {
14012     UnexpandedParameterPack Unexpanded(E->getPack(), E->getPackLoc());
14013     bool ShouldExpand = false;
14014     bool RetainExpansion = false;
14015     std::optional<unsigned> NumExpansions;
14016     if (getDerived().TryExpandParameterPacks(E->getOperatorLoc(), E->getPackLoc(),
14017                                              Unexpanded,
14018                                              ShouldExpand, RetainExpansion,
14019                                              NumExpansions))
14020       return ExprError();
14021 
14022     // If we need to expand the pack, build a template argument from it and
14023     // expand that.
14024     if (ShouldExpand) {
14025       auto *Pack = E->getPack();
14026       if (auto *TTPD = dyn_cast<TemplateTypeParmDecl>(Pack)) {
14027         ArgStorage = getSema().Context.getPackExpansionType(
14028             getSema().Context.getTypeDeclType(TTPD), std::nullopt);
14029       } else if (auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Pack)) {
14030         ArgStorage = TemplateArgument(TemplateName(TTPD), std::nullopt);
14031       } else {
14032         auto *VD = cast<ValueDecl>(Pack);
14033         ExprResult DRE = getSema().BuildDeclRefExpr(
14034             VD, VD->getType().getNonLValueExprType(getSema().Context),
14035             VD->getType()->isReferenceType() ? VK_LValue : VK_PRValue,
14036             E->getPackLoc());
14037         if (DRE.isInvalid())
14038           return ExprError();
14039         ArgStorage = new (getSema().Context)
14040             PackExpansionExpr(getSema().Context.DependentTy, DRE.get(),
14041                               E->getPackLoc(), std::nullopt);
14042       }
14043       PackArgs = ArgStorage;
14044     }
14045   }
14046 
14047   // If we're not expanding the pack, just transform the decl.
14048   if (!PackArgs.size()) {
14049     auto *Pack = cast_or_null<NamedDecl>(
14050         getDerived().TransformDecl(E->getPackLoc(), E->getPack()));
14051     if (!Pack)
14052       return ExprError();
14053     return getDerived().RebuildSizeOfPackExpr(
14054         E->getOperatorLoc(), Pack, E->getPackLoc(), E->getRParenLoc(),
14055         std::nullopt, std::nullopt);
14056   }
14057 
14058   // Try to compute the result without performing a partial substitution.
14059   std::optional<unsigned> Result = 0;
14060   for (const TemplateArgument &Arg : PackArgs) {
14061     if (!Arg.isPackExpansion()) {
14062       Result = *Result + 1;
14063       continue;
14064     }
14065 
14066     TemplateArgumentLoc ArgLoc;
14067     InventTemplateArgumentLoc(Arg, ArgLoc);
14068 
14069     // Find the pattern of the pack expansion.
14070     SourceLocation Ellipsis;
14071     std::optional<unsigned> OrigNumExpansions;
14072     TemplateArgumentLoc Pattern =
14073         getSema().getTemplateArgumentPackExpansionPattern(ArgLoc, Ellipsis,
14074                                                           OrigNumExpansions);
14075 
14076     // Substitute under the pack expansion. Do not expand the pack (yet).
14077     TemplateArgumentLoc OutPattern;
14078     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
14079     if (getDerived().TransformTemplateArgument(Pattern, OutPattern,
14080                                                /*Uneval*/ true))
14081       return true;
14082 
14083     // See if we can determine the number of arguments from the result.
14084     std::optional<unsigned> NumExpansions =
14085         getSema().getFullyPackExpandedSize(OutPattern.getArgument());
14086     if (!NumExpansions) {
14087       // No: we must be in an alias template expansion, and we're going to need
14088       // to actually expand the packs.
14089       Result = std::nullopt;
14090       break;
14091     }
14092 
14093     Result = *Result + *NumExpansions;
14094   }
14095 
14096   // Common case: we could determine the number of expansions without
14097   // substituting.
14098   if (Result)
14099     return getDerived().RebuildSizeOfPackExpr(
14100         E->getOperatorLoc(), E->getPack(), E->getPackLoc(), E->getRParenLoc(),
14101         *Result, std::nullopt);
14102 
14103   TemplateArgumentListInfo TransformedPackArgs(E->getPackLoc(),
14104                                                E->getPackLoc());
14105   {
14106     TemporaryBase Rebase(*this, E->getPackLoc(), getBaseEntity());
14107     typedef TemplateArgumentLocInventIterator<
14108         Derived, const TemplateArgument*> PackLocIterator;
14109     if (TransformTemplateArguments(PackLocIterator(*this, PackArgs.begin()),
14110                                    PackLocIterator(*this, PackArgs.end()),
14111                                    TransformedPackArgs, /*Uneval*/true))
14112       return ExprError();
14113   }
14114 
14115   // Check whether we managed to fully-expand the pack.
14116   // FIXME: Is it possible for us to do so and not hit the early exit path?
14117   SmallVector<TemplateArgument, 8> Args;
14118   bool PartialSubstitution = false;
14119   for (auto &Loc : TransformedPackArgs.arguments()) {
14120     Args.push_back(Loc.getArgument());
14121     if (Loc.getArgument().isPackExpansion())
14122       PartialSubstitution = true;
14123   }
14124 
14125   if (PartialSubstitution)
14126     return getDerived().RebuildSizeOfPackExpr(
14127         E->getOperatorLoc(), E->getPack(), E->getPackLoc(), E->getRParenLoc(),
14128         std::nullopt, Args);
14129 
14130   return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
14131                                             E->getPackLoc(), E->getRParenLoc(),
14132                                             Args.size(), std::nullopt);
14133 }
14134 
14135 template<typename Derived>
14136 ExprResult
14137 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmPackExpr(
14138                                           SubstNonTypeTemplateParmPackExpr *E) {
14139   // Default behavior is to do nothing with this transformation.
14140   return E;
14141 }
14142 
14143 template<typename Derived>
14144 ExprResult
14145 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmExpr(
14146                                           SubstNonTypeTemplateParmExpr *E) {
14147   // Default behavior is to do nothing with this transformation.
14148   return E;
14149 }
14150 
14151 template<typename Derived>
14152 ExprResult
14153 TreeTransform<Derived>::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
14154   // Default behavior is to do nothing with this transformation.
14155   return E;
14156 }
14157 
14158 template<typename Derived>
14159 ExprResult
14160 TreeTransform<Derived>::TransformMaterializeTemporaryExpr(
14161                                                   MaterializeTemporaryExpr *E) {
14162   return getDerived().TransformExpr(E->getSubExpr());
14163 }
14164 
14165 template<typename Derived>
14166 ExprResult
14167 TreeTransform<Derived>::TransformCXXFoldExpr(CXXFoldExpr *E) {
14168   UnresolvedLookupExpr *Callee = nullptr;
14169   if (Expr *OldCallee = E->getCallee()) {
14170     ExprResult CalleeResult = getDerived().TransformExpr(OldCallee);
14171     if (CalleeResult.isInvalid())
14172       return ExprError();
14173     Callee = cast<UnresolvedLookupExpr>(CalleeResult.get());
14174   }
14175 
14176   Expr *Pattern = E->getPattern();
14177 
14178   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
14179   getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
14180   assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
14181 
14182   // Determine whether the set of unexpanded parameter packs can and should
14183   // be expanded.
14184   bool Expand = true;
14185   bool RetainExpansion = false;
14186   std::optional<unsigned> OrigNumExpansions = E->getNumExpansions(),
14187                           NumExpansions = OrigNumExpansions;
14188   if (getDerived().TryExpandParameterPacks(E->getEllipsisLoc(),
14189                                            Pattern->getSourceRange(),
14190                                            Unexpanded,
14191                                            Expand, RetainExpansion,
14192                                            NumExpansions))
14193     return true;
14194 
14195   if (!Expand) {
14196     // Do not expand any packs here, just transform and rebuild a fold
14197     // expression.
14198     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
14199 
14200     ExprResult LHS =
14201         E->getLHS() ? getDerived().TransformExpr(E->getLHS()) : ExprResult();
14202     if (LHS.isInvalid())
14203       return true;
14204 
14205     ExprResult RHS =
14206         E->getRHS() ? getDerived().TransformExpr(E->getRHS()) : ExprResult();
14207     if (RHS.isInvalid())
14208       return true;
14209 
14210     if (!getDerived().AlwaysRebuild() &&
14211         LHS.get() == E->getLHS() && RHS.get() == E->getRHS())
14212       return E;
14213 
14214     return getDerived().RebuildCXXFoldExpr(
14215         Callee, E->getBeginLoc(), LHS.get(), E->getOperator(),
14216         E->getEllipsisLoc(), RHS.get(), E->getEndLoc(), NumExpansions);
14217   }
14218 
14219   // Formally a fold expression expands to nested parenthesized expressions.
14220   // Enforce this limit to avoid creating trees so deep we can't safely traverse
14221   // them.
14222   if (NumExpansions && SemaRef.getLangOpts().BracketDepth < NumExpansions) {
14223     SemaRef.Diag(E->getEllipsisLoc(),
14224                  clang::diag::err_fold_expression_limit_exceeded)
14225         << *NumExpansions << SemaRef.getLangOpts().BracketDepth
14226         << E->getSourceRange();
14227     SemaRef.Diag(E->getEllipsisLoc(), diag::note_bracket_depth);
14228     return ExprError();
14229   }
14230 
14231   // The transform has determined that we should perform an elementwise
14232   // expansion of the pattern. Do so.
14233   ExprResult Result = getDerived().TransformExpr(E->getInit());
14234   if (Result.isInvalid())
14235     return true;
14236   bool LeftFold = E->isLeftFold();
14237 
14238   // If we're retaining an expansion for a right fold, it is the innermost
14239   // component and takes the init (if any).
14240   if (!LeftFold && RetainExpansion) {
14241     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
14242 
14243     ExprResult Out = getDerived().TransformExpr(Pattern);
14244     if (Out.isInvalid())
14245       return true;
14246 
14247     Result = getDerived().RebuildCXXFoldExpr(
14248         Callee, E->getBeginLoc(), Out.get(), E->getOperator(),
14249         E->getEllipsisLoc(), Result.get(), E->getEndLoc(), OrigNumExpansions);
14250     if (Result.isInvalid())
14251       return true;
14252   }
14253 
14254   for (unsigned I = 0; I != *NumExpansions; ++I) {
14255     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(
14256         getSema(), LeftFold ? I : *NumExpansions - I - 1);
14257     ExprResult Out = getDerived().TransformExpr(Pattern);
14258     if (Out.isInvalid())
14259       return true;
14260 
14261     if (Out.get()->containsUnexpandedParameterPack()) {
14262       // We still have a pack; retain a pack expansion for this slice.
14263       Result = getDerived().RebuildCXXFoldExpr(
14264           Callee, E->getBeginLoc(), LeftFold ? Result.get() : Out.get(),
14265           E->getOperator(), E->getEllipsisLoc(),
14266           LeftFold ? Out.get() : Result.get(), E->getEndLoc(),
14267           OrigNumExpansions);
14268     } else if (Result.isUsable()) {
14269       // We've got down to a single element; build a binary operator.
14270       Expr *LHS = LeftFold ? Result.get() : Out.get();
14271       Expr *RHS = LeftFold ? Out.get() : Result.get();
14272       if (Callee) {
14273         UnresolvedSet<16> Functions;
14274         Functions.append(Callee->decls_begin(), Callee->decls_end());
14275         Result = getDerived().RebuildCXXOperatorCallExpr(
14276             BinaryOperator::getOverloadedOperator(E->getOperator()),
14277             E->getEllipsisLoc(), Callee->getBeginLoc(), Callee->requiresADL(),
14278             Functions, LHS, RHS);
14279       } else {
14280         Result = getDerived().RebuildBinaryOperator(E->getEllipsisLoc(),
14281                                                     E->getOperator(), LHS, RHS);
14282       }
14283     } else
14284       Result = Out;
14285 
14286     if (Result.isInvalid())
14287       return true;
14288   }
14289 
14290   // If we're retaining an expansion for a left fold, it is the outermost
14291   // component and takes the complete expansion so far as its init (if any).
14292   if (LeftFold && RetainExpansion) {
14293     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
14294 
14295     ExprResult Out = getDerived().TransformExpr(Pattern);
14296     if (Out.isInvalid())
14297       return true;
14298 
14299     Result = getDerived().RebuildCXXFoldExpr(
14300         Callee, E->getBeginLoc(), Result.get(), E->getOperator(),
14301         E->getEllipsisLoc(), Out.get(), E->getEndLoc(), OrigNumExpansions);
14302     if (Result.isInvalid())
14303       return true;
14304   }
14305 
14306   // If we had no init and an empty pack, and we're not retaining an expansion,
14307   // then produce a fallback value or error.
14308   if (Result.isUnset())
14309     return getDerived().RebuildEmptyCXXFoldExpr(E->getEllipsisLoc(),
14310                                                 E->getOperator());
14311 
14312   return Result;
14313 }
14314 
14315 template <typename Derived>
14316 ExprResult
14317 TreeTransform<Derived>::TransformCXXParenListInitExpr(CXXParenListInitExpr *E) {
14318   SmallVector<Expr *, 4> TransformedInits;
14319   ArrayRef<Expr *> InitExprs = E->getInitExprs();
14320   if (TransformExprs(InitExprs.data(), InitExprs.size(), true,
14321                      TransformedInits))
14322     return ExprError();
14323 
14324   return getDerived().RebuildParenListExpr(E->getBeginLoc(), TransformedInits,
14325                                            E->getEndLoc());
14326 }
14327 
14328 template<typename Derived>
14329 ExprResult
14330 TreeTransform<Derived>::TransformCXXStdInitializerListExpr(
14331     CXXStdInitializerListExpr *E) {
14332   return getDerived().TransformExpr(E->getSubExpr());
14333 }
14334 
14335 template<typename Derived>
14336 ExprResult
14337 TreeTransform<Derived>::TransformObjCStringLiteral(ObjCStringLiteral *E) {
14338   return SemaRef.MaybeBindToTemporary(E);
14339 }
14340 
14341 template<typename Derived>
14342 ExprResult
14343 TreeTransform<Derived>::TransformObjCBoolLiteralExpr(ObjCBoolLiteralExpr *E) {
14344   return E;
14345 }
14346 
14347 template<typename Derived>
14348 ExprResult
14349 TreeTransform<Derived>::TransformObjCBoxedExpr(ObjCBoxedExpr *E) {
14350   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
14351   if (SubExpr.isInvalid())
14352     return ExprError();
14353 
14354   if (!getDerived().AlwaysRebuild() &&
14355       SubExpr.get() == E->getSubExpr())
14356     return E;
14357 
14358   return getDerived().RebuildObjCBoxedExpr(E->getSourceRange(), SubExpr.get());
14359 }
14360 
14361 template<typename Derived>
14362 ExprResult
14363 TreeTransform<Derived>::TransformObjCArrayLiteral(ObjCArrayLiteral *E) {
14364   // Transform each of the elements.
14365   SmallVector<Expr *, 8> Elements;
14366   bool ArgChanged = false;
14367   if (getDerived().TransformExprs(E->getElements(), E->getNumElements(),
14368                                   /*IsCall=*/false, Elements, &ArgChanged))
14369     return ExprError();
14370 
14371   if (!getDerived().AlwaysRebuild() && !ArgChanged)
14372     return SemaRef.MaybeBindToTemporary(E);
14373 
14374   return getDerived().RebuildObjCArrayLiteral(E->getSourceRange(),
14375                                               Elements.data(),
14376                                               Elements.size());
14377 }
14378 
14379 template<typename Derived>
14380 ExprResult
14381 TreeTransform<Derived>::TransformObjCDictionaryLiteral(
14382                                                     ObjCDictionaryLiteral *E) {
14383   // Transform each of the elements.
14384   SmallVector<ObjCDictionaryElement, 8> Elements;
14385   bool ArgChanged = false;
14386   for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
14387     ObjCDictionaryElement OrigElement = E->getKeyValueElement(I);
14388 
14389     if (OrigElement.isPackExpansion()) {
14390       // This key/value element is a pack expansion.
14391       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
14392       getSema().collectUnexpandedParameterPacks(OrigElement.Key, Unexpanded);
14393       getSema().collectUnexpandedParameterPacks(OrigElement.Value, Unexpanded);
14394       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
14395 
14396       // Determine whether the set of unexpanded parameter packs can
14397       // and should be expanded.
14398       bool Expand = true;
14399       bool RetainExpansion = false;
14400       std::optional<unsigned> OrigNumExpansions = OrigElement.NumExpansions;
14401       std::optional<unsigned> NumExpansions = OrigNumExpansions;
14402       SourceRange PatternRange(OrigElement.Key->getBeginLoc(),
14403                                OrigElement.Value->getEndLoc());
14404       if (getDerived().TryExpandParameterPacks(OrigElement.EllipsisLoc,
14405                                                PatternRange, Unexpanded, Expand,
14406                                                RetainExpansion, NumExpansions))
14407         return ExprError();
14408 
14409       if (!Expand) {
14410         // The transform has determined that we should perform a simple
14411         // transformation on the pack expansion, producing another pack
14412         // expansion.
14413         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
14414         ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
14415         if (Key.isInvalid())
14416           return ExprError();
14417 
14418         if (Key.get() != OrigElement.Key)
14419           ArgChanged = true;
14420 
14421         ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
14422         if (Value.isInvalid())
14423           return ExprError();
14424 
14425         if (Value.get() != OrigElement.Value)
14426           ArgChanged = true;
14427 
14428         ObjCDictionaryElement Expansion = {
14429           Key.get(), Value.get(), OrigElement.EllipsisLoc, NumExpansions
14430         };
14431         Elements.push_back(Expansion);
14432         continue;
14433       }
14434 
14435       // Record right away that the argument was changed.  This needs
14436       // to happen even if the array expands to nothing.
14437       ArgChanged = true;
14438 
14439       // The transform has determined that we should perform an elementwise
14440       // expansion of the pattern. Do so.
14441       for (unsigned I = 0; I != *NumExpansions; ++I) {
14442         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
14443         ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
14444         if (Key.isInvalid())
14445           return ExprError();
14446 
14447         ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
14448         if (Value.isInvalid())
14449           return ExprError();
14450 
14451         ObjCDictionaryElement Element = {
14452           Key.get(), Value.get(), SourceLocation(), NumExpansions
14453         };
14454 
14455         // If any unexpanded parameter packs remain, we still have a
14456         // pack expansion.
14457         // FIXME: Can this really happen?
14458         if (Key.get()->containsUnexpandedParameterPack() ||
14459             Value.get()->containsUnexpandedParameterPack())
14460           Element.EllipsisLoc = OrigElement.EllipsisLoc;
14461 
14462         Elements.push_back(Element);
14463       }
14464 
14465       // FIXME: Retain a pack expansion if RetainExpansion is true.
14466 
14467       // We've finished with this pack expansion.
14468       continue;
14469     }
14470 
14471     // Transform and check key.
14472     ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
14473     if (Key.isInvalid())
14474       return ExprError();
14475 
14476     if (Key.get() != OrigElement.Key)
14477       ArgChanged = true;
14478 
14479     // Transform and check value.
14480     ExprResult Value
14481       = getDerived().TransformExpr(OrigElement.Value);
14482     if (Value.isInvalid())
14483       return ExprError();
14484 
14485     if (Value.get() != OrigElement.Value)
14486       ArgChanged = true;
14487 
14488     ObjCDictionaryElement Element = {Key.get(), Value.get(), SourceLocation(),
14489                                      std::nullopt};
14490     Elements.push_back(Element);
14491   }
14492 
14493   if (!getDerived().AlwaysRebuild() && !ArgChanged)
14494     return SemaRef.MaybeBindToTemporary(E);
14495 
14496   return getDerived().RebuildObjCDictionaryLiteral(E->getSourceRange(),
14497                                                    Elements);
14498 }
14499 
14500 template<typename Derived>
14501 ExprResult
14502 TreeTransform<Derived>::TransformObjCEncodeExpr(ObjCEncodeExpr *E) {
14503   TypeSourceInfo *EncodedTypeInfo
14504     = getDerived().TransformType(E->getEncodedTypeSourceInfo());
14505   if (!EncodedTypeInfo)
14506     return ExprError();
14507 
14508   if (!getDerived().AlwaysRebuild() &&
14509       EncodedTypeInfo == E->getEncodedTypeSourceInfo())
14510     return E;
14511 
14512   return getDerived().RebuildObjCEncodeExpr(E->getAtLoc(),
14513                                             EncodedTypeInfo,
14514                                             E->getRParenLoc());
14515 }
14516 
14517 template<typename Derived>
14518 ExprResult TreeTransform<Derived>::
14519 TransformObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr *E) {
14520   // This is a kind of implicit conversion, and it needs to get dropped
14521   // and recomputed for the same general reasons that ImplicitCastExprs
14522   // do, as well a more specific one: this expression is only valid when
14523   // it appears *immediately* as an argument expression.
14524   return getDerived().TransformExpr(E->getSubExpr());
14525 }
14526 
14527 template<typename Derived>
14528 ExprResult TreeTransform<Derived>::
14529 TransformObjCBridgedCastExpr(ObjCBridgedCastExpr *E) {
14530   TypeSourceInfo *TSInfo
14531     = getDerived().TransformType(E->getTypeInfoAsWritten());
14532   if (!TSInfo)
14533     return ExprError();
14534 
14535   ExprResult Result = getDerived().TransformExpr(E->getSubExpr());
14536   if (Result.isInvalid())
14537     return ExprError();
14538 
14539   if (!getDerived().AlwaysRebuild() &&
14540       TSInfo == E->getTypeInfoAsWritten() &&
14541       Result.get() == E->getSubExpr())
14542     return E;
14543 
14544   return SemaRef.BuildObjCBridgedCast(E->getLParenLoc(), E->getBridgeKind(),
14545                                       E->getBridgeKeywordLoc(), TSInfo,
14546                                       Result.get());
14547 }
14548 
14549 template <typename Derived>
14550 ExprResult TreeTransform<Derived>::TransformObjCAvailabilityCheckExpr(
14551     ObjCAvailabilityCheckExpr *E) {
14552   return E;
14553 }
14554 
14555 template<typename Derived>
14556 ExprResult
14557 TreeTransform<Derived>::TransformObjCMessageExpr(ObjCMessageExpr *E) {
14558   // Transform arguments.
14559   bool ArgChanged = false;
14560   SmallVector<Expr*, 8> Args;
14561   Args.reserve(E->getNumArgs());
14562   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), false, Args,
14563                                   &ArgChanged))
14564     return ExprError();
14565 
14566   if (E->getReceiverKind() == ObjCMessageExpr::Class) {
14567     // Class message: transform the receiver type.
14568     TypeSourceInfo *ReceiverTypeInfo
14569       = getDerived().TransformType(E->getClassReceiverTypeInfo());
14570     if (!ReceiverTypeInfo)
14571       return ExprError();
14572 
14573     // If nothing changed, just retain the existing message send.
14574     if (!getDerived().AlwaysRebuild() &&
14575         ReceiverTypeInfo == E->getClassReceiverTypeInfo() && !ArgChanged)
14576       return SemaRef.MaybeBindToTemporary(E);
14577 
14578     // Build a new class message send.
14579     SmallVector<SourceLocation, 16> SelLocs;
14580     E->getSelectorLocs(SelLocs);
14581     return getDerived().RebuildObjCMessageExpr(ReceiverTypeInfo,
14582                                                E->getSelector(),
14583                                                SelLocs,
14584                                                E->getMethodDecl(),
14585                                                E->getLeftLoc(),
14586                                                Args,
14587                                                E->getRightLoc());
14588   }
14589   else if (E->getReceiverKind() == ObjCMessageExpr::SuperClass ||
14590            E->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
14591     if (!E->getMethodDecl())
14592       return ExprError();
14593 
14594     // Build a new class message send to 'super'.
14595     SmallVector<SourceLocation, 16> SelLocs;
14596     E->getSelectorLocs(SelLocs);
14597     return getDerived().RebuildObjCMessageExpr(E->getSuperLoc(),
14598                                                E->getSelector(),
14599                                                SelLocs,
14600                                                E->getReceiverType(),
14601                                                E->getMethodDecl(),
14602                                                E->getLeftLoc(),
14603                                                Args,
14604                                                E->getRightLoc());
14605   }
14606 
14607   // Instance message: transform the receiver
14608   assert(E->getReceiverKind() == ObjCMessageExpr::Instance &&
14609          "Only class and instance messages may be instantiated");
14610   ExprResult Receiver
14611     = getDerived().TransformExpr(E->getInstanceReceiver());
14612   if (Receiver.isInvalid())
14613     return ExprError();
14614 
14615   // If nothing changed, just retain the existing message send.
14616   if (!getDerived().AlwaysRebuild() &&
14617       Receiver.get() == E->getInstanceReceiver() && !ArgChanged)
14618     return SemaRef.MaybeBindToTemporary(E);
14619 
14620   // Build a new instance message send.
14621   SmallVector<SourceLocation, 16> SelLocs;
14622   E->getSelectorLocs(SelLocs);
14623   return getDerived().RebuildObjCMessageExpr(Receiver.get(),
14624                                              E->getSelector(),
14625                                              SelLocs,
14626                                              E->getMethodDecl(),
14627                                              E->getLeftLoc(),
14628                                              Args,
14629                                              E->getRightLoc());
14630 }
14631 
14632 template<typename Derived>
14633 ExprResult
14634 TreeTransform<Derived>::TransformObjCSelectorExpr(ObjCSelectorExpr *E) {
14635   return E;
14636 }
14637 
14638 template<typename Derived>
14639 ExprResult
14640 TreeTransform<Derived>::TransformObjCProtocolExpr(ObjCProtocolExpr *E) {
14641   return E;
14642 }
14643 
14644 template<typename Derived>
14645 ExprResult
14646 TreeTransform<Derived>::TransformObjCIvarRefExpr(ObjCIvarRefExpr *E) {
14647   // Transform the base expression.
14648   ExprResult Base = getDerived().TransformExpr(E->getBase());
14649   if (Base.isInvalid())
14650     return ExprError();
14651 
14652   // We don't need to transform the ivar; it will never change.
14653 
14654   // If nothing changed, just retain the existing expression.
14655   if (!getDerived().AlwaysRebuild() &&
14656       Base.get() == E->getBase())
14657     return E;
14658 
14659   return getDerived().RebuildObjCIvarRefExpr(Base.get(), E->getDecl(),
14660                                              E->getLocation(),
14661                                              E->isArrow(), E->isFreeIvar());
14662 }
14663 
14664 template<typename Derived>
14665 ExprResult
14666 TreeTransform<Derived>::TransformObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
14667   // 'super' and types never change. Property never changes. Just
14668   // retain the existing expression.
14669   if (!E->isObjectReceiver())
14670     return E;
14671 
14672   // Transform the base expression.
14673   ExprResult Base = getDerived().TransformExpr(E->getBase());
14674   if (Base.isInvalid())
14675     return ExprError();
14676 
14677   // We don't need to transform the property; it will never change.
14678 
14679   // If nothing changed, just retain the existing expression.
14680   if (!getDerived().AlwaysRebuild() &&
14681       Base.get() == E->getBase())
14682     return E;
14683 
14684   if (E->isExplicitProperty())
14685     return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
14686                                                    E->getExplicitProperty(),
14687                                                    E->getLocation());
14688 
14689   return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
14690                                                  SemaRef.Context.PseudoObjectTy,
14691                                                  E->getImplicitPropertyGetter(),
14692                                                  E->getImplicitPropertySetter(),
14693                                                  E->getLocation());
14694 }
14695 
14696 template<typename Derived>
14697 ExprResult
14698 TreeTransform<Derived>::TransformObjCSubscriptRefExpr(ObjCSubscriptRefExpr *E) {
14699   // Transform the base expression.
14700   ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
14701   if (Base.isInvalid())
14702     return ExprError();
14703 
14704   // Transform the key expression.
14705   ExprResult Key = getDerived().TransformExpr(E->getKeyExpr());
14706   if (Key.isInvalid())
14707     return ExprError();
14708 
14709   // If nothing changed, just retain the existing expression.
14710   if (!getDerived().AlwaysRebuild() &&
14711       Key.get() == E->getKeyExpr() && Base.get() == E->getBaseExpr())
14712     return E;
14713 
14714   return getDerived().RebuildObjCSubscriptRefExpr(E->getRBracket(),
14715                                                   Base.get(), Key.get(),
14716                                                   E->getAtIndexMethodDecl(),
14717                                                   E->setAtIndexMethodDecl());
14718 }
14719 
14720 template<typename Derived>
14721 ExprResult
14722 TreeTransform<Derived>::TransformObjCIsaExpr(ObjCIsaExpr *E) {
14723   // Transform the base expression.
14724   ExprResult Base = getDerived().TransformExpr(E->getBase());
14725   if (Base.isInvalid())
14726     return ExprError();
14727 
14728   // If nothing changed, just retain the existing expression.
14729   if (!getDerived().AlwaysRebuild() &&
14730       Base.get() == E->getBase())
14731     return E;
14732 
14733   return getDerived().RebuildObjCIsaExpr(Base.get(), E->getIsaMemberLoc(),
14734                                          E->getOpLoc(),
14735                                          E->isArrow());
14736 }
14737 
14738 template<typename Derived>
14739 ExprResult
14740 TreeTransform<Derived>::TransformShuffleVectorExpr(ShuffleVectorExpr *E) {
14741   bool ArgumentChanged = false;
14742   SmallVector<Expr*, 8> SubExprs;
14743   SubExprs.reserve(E->getNumSubExprs());
14744   if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
14745                                   SubExprs, &ArgumentChanged))
14746     return ExprError();
14747 
14748   if (!getDerived().AlwaysRebuild() &&
14749       !ArgumentChanged)
14750     return E;
14751 
14752   return getDerived().RebuildShuffleVectorExpr(E->getBuiltinLoc(),
14753                                                SubExprs,
14754                                                E->getRParenLoc());
14755 }
14756 
14757 template<typename Derived>
14758 ExprResult
14759 TreeTransform<Derived>::TransformConvertVectorExpr(ConvertVectorExpr *E) {
14760   ExprResult SrcExpr = getDerived().TransformExpr(E->getSrcExpr());
14761   if (SrcExpr.isInvalid())
14762     return ExprError();
14763 
14764   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
14765   if (!Type)
14766     return ExprError();
14767 
14768   if (!getDerived().AlwaysRebuild() &&
14769       Type == E->getTypeSourceInfo() &&
14770       SrcExpr.get() == E->getSrcExpr())
14771     return E;
14772 
14773   return getDerived().RebuildConvertVectorExpr(E->getBuiltinLoc(),
14774                                                SrcExpr.get(), Type,
14775                                                E->getRParenLoc());
14776 }
14777 
14778 template<typename Derived>
14779 ExprResult
14780 TreeTransform<Derived>::TransformBlockExpr(BlockExpr *E) {
14781   BlockDecl *oldBlock = E->getBlockDecl();
14782 
14783   SemaRef.ActOnBlockStart(E->getCaretLocation(), /*Scope=*/nullptr);
14784   BlockScopeInfo *blockScope = SemaRef.getCurBlock();
14785 
14786   blockScope->TheDecl->setIsVariadic(oldBlock->isVariadic());
14787   blockScope->TheDecl->setBlockMissingReturnType(
14788                          oldBlock->blockMissingReturnType());
14789 
14790   SmallVector<ParmVarDecl*, 4> params;
14791   SmallVector<QualType, 4> paramTypes;
14792 
14793   const FunctionProtoType *exprFunctionType = E->getFunctionType();
14794 
14795   // Parameter substitution.
14796   Sema::ExtParameterInfoBuilder extParamInfos;
14797   if (getDerived().TransformFunctionTypeParams(
14798           E->getCaretLocation(), oldBlock->parameters(), nullptr,
14799           exprFunctionType->getExtParameterInfosOrNull(), paramTypes, &params,
14800           extParamInfos)) {
14801     getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
14802     return ExprError();
14803   }
14804 
14805   QualType exprResultType =
14806       getDerived().TransformType(exprFunctionType->getReturnType());
14807 
14808   auto epi = exprFunctionType->getExtProtoInfo();
14809   epi.ExtParameterInfos = extParamInfos.getPointerOrNull(paramTypes.size());
14810 
14811   QualType functionType =
14812     getDerived().RebuildFunctionProtoType(exprResultType, paramTypes, epi);
14813   blockScope->FunctionType = functionType;
14814 
14815   // Set the parameters on the block decl.
14816   if (!params.empty())
14817     blockScope->TheDecl->setParams(params);
14818 
14819   if (!oldBlock->blockMissingReturnType()) {
14820     blockScope->HasImplicitReturnType = false;
14821     blockScope->ReturnType = exprResultType;
14822   }
14823 
14824   // Transform the body
14825   StmtResult body = getDerived().TransformStmt(E->getBody());
14826   if (body.isInvalid()) {
14827     getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
14828     return ExprError();
14829   }
14830 
14831 #ifndef NDEBUG
14832   // In builds with assertions, make sure that we captured everything we
14833   // captured before.
14834   if (!SemaRef.getDiagnostics().hasErrorOccurred()) {
14835     for (const auto &I : oldBlock->captures()) {
14836       VarDecl *oldCapture = I.getVariable();
14837 
14838       // Ignore parameter packs.
14839       if (oldCapture->isParameterPack())
14840         continue;
14841 
14842       VarDecl *newCapture =
14843         cast<VarDecl>(getDerived().TransformDecl(E->getCaretLocation(),
14844                                                  oldCapture));
14845       assert(blockScope->CaptureMap.count(newCapture));
14846     }
14847 
14848     // The this pointer may not be captured by the instantiated block, even when
14849     // it's captured by the original block, if the expression causing the
14850     // capture is in the discarded branch of a constexpr if statement.
14851     assert((!blockScope->isCXXThisCaptured() || oldBlock->capturesCXXThis()) &&
14852            "this pointer isn't captured in the old block");
14853   }
14854 #endif
14855 
14856   return SemaRef.ActOnBlockStmtExpr(E->getCaretLocation(), body.get(),
14857                                     /*Scope=*/nullptr);
14858 }
14859 
14860 template<typename Derived>
14861 ExprResult
14862 TreeTransform<Derived>::TransformAsTypeExpr(AsTypeExpr *E) {
14863   ExprResult SrcExpr = getDerived().TransformExpr(E->getSrcExpr());
14864   if (SrcExpr.isInvalid())
14865     return ExprError();
14866 
14867   QualType Type = getDerived().TransformType(E->getType());
14868 
14869   return SemaRef.BuildAsTypeExpr(SrcExpr.get(), Type, E->getBuiltinLoc(),
14870                                  E->getRParenLoc());
14871 }
14872 
14873 template<typename Derived>
14874 ExprResult
14875 TreeTransform<Derived>::TransformAtomicExpr(AtomicExpr *E) {
14876   bool ArgumentChanged = false;
14877   SmallVector<Expr*, 8> SubExprs;
14878   SubExprs.reserve(E->getNumSubExprs());
14879   if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
14880                                   SubExprs, &ArgumentChanged))
14881     return ExprError();
14882 
14883   if (!getDerived().AlwaysRebuild() &&
14884       !ArgumentChanged)
14885     return E;
14886 
14887   return getDerived().RebuildAtomicExpr(E->getBuiltinLoc(), SubExprs,
14888                                         E->getOp(), E->getRParenLoc());
14889 }
14890 
14891 //===----------------------------------------------------------------------===//
14892 // Type reconstruction
14893 //===----------------------------------------------------------------------===//
14894 
14895 template<typename Derived>
14896 QualType TreeTransform<Derived>::RebuildPointerType(QualType PointeeType,
14897                                                     SourceLocation Star) {
14898   return SemaRef.BuildPointerType(PointeeType, Star,
14899                                   getDerived().getBaseEntity());
14900 }
14901 
14902 template<typename Derived>
14903 QualType TreeTransform<Derived>::RebuildBlockPointerType(QualType PointeeType,
14904                                                          SourceLocation Star) {
14905   return SemaRef.BuildBlockPointerType(PointeeType, Star,
14906                                        getDerived().getBaseEntity());
14907 }
14908 
14909 template<typename Derived>
14910 QualType
14911 TreeTransform<Derived>::RebuildReferenceType(QualType ReferentType,
14912                                              bool WrittenAsLValue,
14913                                              SourceLocation Sigil) {
14914   return SemaRef.BuildReferenceType(ReferentType, WrittenAsLValue,
14915                                     Sigil, getDerived().getBaseEntity());
14916 }
14917 
14918 template<typename Derived>
14919 QualType
14920 TreeTransform<Derived>::RebuildMemberPointerType(QualType PointeeType,
14921                                                  QualType ClassType,
14922                                                  SourceLocation Sigil) {
14923   return SemaRef.BuildMemberPointerType(PointeeType, ClassType, Sigil,
14924                                         getDerived().getBaseEntity());
14925 }
14926 
14927 template<typename Derived>
14928 QualType TreeTransform<Derived>::RebuildObjCTypeParamType(
14929            const ObjCTypeParamDecl *Decl,
14930            SourceLocation ProtocolLAngleLoc,
14931            ArrayRef<ObjCProtocolDecl *> Protocols,
14932            ArrayRef<SourceLocation> ProtocolLocs,
14933            SourceLocation ProtocolRAngleLoc) {
14934   return SemaRef.BuildObjCTypeParamType(Decl,
14935                                         ProtocolLAngleLoc, Protocols,
14936                                         ProtocolLocs, ProtocolRAngleLoc,
14937                                         /*FailOnError=*/true);
14938 }
14939 
14940 template<typename Derived>
14941 QualType TreeTransform<Derived>::RebuildObjCObjectType(
14942            QualType BaseType,
14943            SourceLocation Loc,
14944            SourceLocation TypeArgsLAngleLoc,
14945            ArrayRef<TypeSourceInfo *> TypeArgs,
14946            SourceLocation TypeArgsRAngleLoc,
14947            SourceLocation ProtocolLAngleLoc,
14948            ArrayRef<ObjCProtocolDecl *> Protocols,
14949            ArrayRef<SourceLocation> ProtocolLocs,
14950            SourceLocation ProtocolRAngleLoc) {
14951   return SemaRef.BuildObjCObjectType(BaseType, Loc, TypeArgsLAngleLoc, TypeArgs,
14952                                      TypeArgsRAngleLoc, ProtocolLAngleLoc,
14953                                      Protocols, ProtocolLocs, ProtocolRAngleLoc,
14954                                      /*FailOnError=*/true,
14955                                      /*Rebuilding=*/true);
14956 }
14957 
14958 template<typename Derived>
14959 QualType TreeTransform<Derived>::RebuildObjCObjectPointerType(
14960            QualType PointeeType,
14961            SourceLocation Star) {
14962   return SemaRef.Context.getObjCObjectPointerType(PointeeType);
14963 }
14964 
14965 template <typename Derived>
14966 QualType TreeTransform<Derived>::RebuildArrayType(
14967     QualType ElementType, ArraySizeModifier SizeMod, const llvm::APInt *Size,
14968     Expr *SizeExpr, unsigned IndexTypeQuals, SourceRange BracketsRange) {
14969   if (SizeExpr || !Size)
14970     return SemaRef.BuildArrayType(ElementType, SizeMod, SizeExpr,
14971                                   IndexTypeQuals, BracketsRange,
14972                                   getDerived().getBaseEntity());
14973 
14974   QualType Types[] = {
14975     SemaRef.Context.UnsignedCharTy, SemaRef.Context.UnsignedShortTy,
14976     SemaRef.Context.UnsignedIntTy, SemaRef.Context.UnsignedLongTy,
14977     SemaRef.Context.UnsignedLongLongTy, SemaRef.Context.UnsignedInt128Ty
14978   };
14979   QualType SizeType;
14980   for (const auto &T : Types)
14981     if (Size->getBitWidth() == SemaRef.Context.getIntWidth(T)) {
14982       SizeType = T;
14983       break;
14984     }
14985 
14986   // Note that we can return a VariableArrayType here in the case where
14987   // the element type was a dependent VariableArrayType.
14988   IntegerLiteral *ArraySize
14989       = IntegerLiteral::Create(SemaRef.Context, *Size, SizeType,
14990                                /*FIXME*/BracketsRange.getBegin());
14991   return SemaRef.BuildArrayType(ElementType, SizeMod, ArraySize,
14992                                 IndexTypeQuals, BracketsRange,
14993                                 getDerived().getBaseEntity());
14994 }
14995 
14996 template <typename Derived>
14997 QualType TreeTransform<Derived>::RebuildConstantArrayType(
14998     QualType ElementType, ArraySizeModifier SizeMod, const llvm::APInt &Size,
14999     Expr *SizeExpr, unsigned IndexTypeQuals, SourceRange BracketsRange) {
15000   return getDerived().RebuildArrayType(ElementType, SizeMod, &Size, SizeExpr,
15001                                         IndexTypeQuals, BracketsRange);
15002 }
15003 
15004 template <typename Derived>
15005 QualType TreeTransform<Derived>::RebuildIncompleteArrayType(
15006     QualType ElementType, ArraySizeModifier SizeMod, unsigned IndexTypeQuals,
15007     SourceRange BracketsRange) {
15008   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr, nullptr,
15009                                        IndexTypeQuals, BracketsRange);
15010 }
15011 
15012 template <typename Derived>
15013 QualType TreeTransform<Derived>::RebuildVariableArrayType(
15014     QualType ElementType, ArraySizeModifier SizeMod, Expr *SizeExpr,
15015     unsigned IndexTypeQuals, SourceRange BracketsRange) {
15016   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
15017                                        SizeExpr,
15018                                        IndexTypeQuals, BracketsRange);
15019 }
15020 
15021 template <typename Derived>
15022 QualType TreeTransform<Derived>::RebuildDependentSizedArrayType(
15023     QualType ElementType, ArraySizeModifier SizeMod, Expr *SizeExpr,
15024     unsigned IndexTypeQuals, SourceRange BracketsRange) {
15025   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
15026                                        SizeExpr,
15027                                        IndexTypeQuals, BracketsRange);
15028 }
15029 
15030 template <typename Derived>
15031 QualType TreeTransform<Derived>::RebuildDependentAddressSpaceType(
15032     QualType PointeeType, Expr *AddrSpaceExpr, SourceLocation AttributeLoc) {
15033   return SemaRef.BuildAddressSpaceAttr(PointeeType, AddrSpaceExpr,
15034                                           AttributeLoc);
15035 }
15036 
15037 template <typename Derived>
15038 QualType TreeTransform<Derived>::RebuildVectorType(QualType ElementType,
15039                                                    unsigned NumElements,
15040                                                    VectorKind VecKind) {
15041   // FIXME: semantic checking!
15042   return SemaRef.Context.getVectorType(ElementType, NumElements, VecKind);
15043 }
15044 
15045 template <typename Derived>
15046 QualType TreeTransform<Derived>::RebuildDependentVectorType(
15047     QualType ElementType, Expr *SizeExpr, SourceLocation AttributeLoc,
15048     VectorKind VecKind) {
15049   return SemaRef.BuildVectorType(ElementType, SizeExpr, AttributeLoc);
15050 }
15051 
15052 template<typename Derived>
15053 QualType TreeTransform<Derived>::RebuildExtVectorType(QualType ElementType,
15054                                                       unsigned NumElements,
15055                                                  SourceLocation AttributeLoc) {
15056   llvm::APInt numElements(SemaRef.Context.getIntWidth(SemaRef.Context.IntTy),
15057                           NumElements, true);
15058   IntegerLiteral *VectorSize
15059     = IntegerLiteral::Create(SemaRef.Context, numElements, SemaRef.Context.IntTy,
15060                              AttributeLoc);
15061   return SemaRef.BuildExtVectorType(ElementType, VectorSize, AttributeLoc);
15062 }
15063 
15064 template<typename Derived>
15065 QualType
15066 TreeTransform<Derived>::RebuildDependentSizedExtVectorType(QualType ElementType,
15067                                                            Expr *SizeExpr,
15068                                                   SourceLocation AttributeLoc) {
15069   return SemaRef.BuildExtVectorType(ElementType, SizeExpr, AttributeLoc);
15070 }
15071 
15072 template <typename Derived>
15073 QualType TreeTransform<Derived>::RebuildConstantMatrixType(
15074     QualType ElementType, unsigned NumRows, unsigned NumColumns) {
15075   return SemaRef.Context.getConstantMatrixType(ElementType, NumRows,
15076                                                NumColumns);
15077 }
15078 
15079 template <typename Derived>
15080 QualType TreeTransform<Derived>::RebuildDependentSizedMatrixType(
15081     QualType ElementType, Expr *RowExpr, Expr *ColumnExpr,
15082     SourceLocation AttributeLoc) {
15083   return SemaRef.BuildMatrixType(ElementType, RowExpr, ColumnExpr,
15084                                  AttributeLoc);
15085 }
15086 
15087 template<typename Derived>
15088 QualType TreeTransform<Derived>::RebuildFunctionProtoType(
15089     QualType T,
15090     MutableArrayRef<QualType> ParamTypes,
15091     const FunctionProtoType::ExtProtoInfo &EPI) {
15092   return SemaRef.BuildFunctionType(T, ParamTypes,
15093                                    getDerived().getBaseLocation(),
15094                                    getDerived().getBaseEntity(),
15095                                    EPI);
15096 }
15097 
15098 template<typename Derived>
15099 QualType TreeTransform<Derived>::RebuildFunctionNoProtoType(QualType T) {
15100   return SemaRef.Context.getFunctionNoProtoType(T);
15101 }
15102 
15103 template<typename Derived>
15104 QualType TreeTransform<Derived>::RebuildUnresolvedUsingType(SourceLocation Loc,
15105                                                             Decl *D) {
15106   assert(D && "no decl found");
15107   if (D->isInvalidDecl()) return QualType();
15108 
15109   // FIXME: Doesn't account for ObjCInterfaceDecl!
15110   if (auto *UPD = dyn_cast<UsingPackDecl>(D)) {
15111     // A valid resolved using typename pack expansion decl can have multiple
15112     // UsingDecls, but they must each have exactly one type, and it must be
15113     // the same type in every case. But we must have at least one expansion!
15114     if (UPD->expansions().empty()) {
15115       getSema().Diag(Loc, diag::err_using_pack_expansion_empty)
15116           << UPD->isCXXClassMember() << UPD;
15117       return QualType();
15118     }
15119 
15120     // We might still have some unresolved types. Try to pick a resolved type
15121     // if we can. The final instantiation will check that the remaining
15122     // unresolved types instantiate to the type we pick.
15123     QualType FallbackT;
15124     QualType T;
15125     for (auto *E : UPD->expansions()) {
15126       QualType ThisT = RebuildUnresolvedUsingType(Loc, E);
15127       if (ThisT.isNull())
15128         continue;
15129       else if (ThisT->getAs<UnresolvedUsingType>())
15130         FallbackT = ThisT;
15131       else if (T.isNull())
15132         T = ThisT;
15133       else
15134         assert(getSema().Context.hasSameType(ThisT, T) &&
15135                "mismatched resolved types in using pack expansion");
15136     }
15137     return T.isNull() ? FallbackT : T;
15138   } else if (auto *Using = dyn_cast<UsingDecl>(D)) {
15139     assert(Using->hasTypename() &&
15140            "UnresolvedUsingTypenameDecl transformed to non-typename using");
15141 
15142     // A valid resolved using typename decl points to exactly one type decl.
15143     assert(++Using->shadow_begin() == Using->shadow_end());
15144 
15145     UsingShadowDecl *Shadow = *Using->shadow_begin();
15146     if (SemaRef.DiagnoseUseOfDecl(Shadow->getTargetDecl(), Loc))
15147       return QualType();
15148     return SemaRef.Context.getUsingType(
15149         Shadow, SemaRef.Context.getTypeDeclType(
15150                     cast<TypeDecl>(Shadow->getTargetDecl())));
15151   } else {
15152     assert(isa<UnresolvedUsingTypenameDecl>(D) &&
15153            "UnresolvedUsingTypenameDecl transformed to non-using decl");
15154     return SemaRef.Context.getTypeDeclType(
15155         cast<UnresolvedUsingTypenameDecl>(D));
15156   }
15157 }
15158 
15159 template <typename Derived>
15160 QualType TreeTransform<Derived>::RebuildTypeOfExprType(Expr *E, SourceLocation,
15161                                                        TypeOfKind Kind) {
15162   return SemaRef.BuildTypeofExprType(E, Kind);
15163 }
15164 
15165 template<typename Derived>
15166 QualType TreeTransform<Derived>::RebuildTypeOfType(QualType Underlying,
15167                                                    TypeOfKind Kind) {
15168   return SemaRef.Context.getTypeOfType(Underlying, Kind);
15169 }
15170 
15171 template <typename Derived>
15172 QualType TreeTransform<Derived>::RebuildDecltypeType(Expr *E, SourceLocation) {
15173   return SemaRef.BuildDecltypeType(E);
15174 }
15175 
15176 template<typename Derived>
15177 QualType TreeTransform<Derived>::RebuildUnaryTransformType(QualType BaseType,
15178                                             UnaryTransformType::UTTKind UKind,
15179                                             SourceLocation Loc) {
15180   return SemaRef.BuildUnaryTransformType(BaseType, UKind, Loc);
15181 }
15182 
15183 template<typename Derived>
15184 QualType TreeTransform<Derived>::RebuildTemplateSpecializationType(
15185                                                       TemplateName Template,
15186                                              SourceLocation TemplateNameLoc,
15187                                      TemplateArgumentListInfo &TemplateArgs) {
15188   return SemaRef.CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
15189 }
15190 
15191 template<typename Derived>
15192 QualType TreeTransform<Derived>::RebuildAtomicType(QualType ValueType,
15193                                                    SourceLocation KWLoc) {
15194   return SemaRef.BuildAtomicType(ValueType, KWLoc);
15195 }
15196 
15197 template<typename Derived>
15198 QualType TreeTransform<Derived>::RebuildPipeType(QualType ValueType,
15199                                                  SourceLocation KWLoc,
15200                                                  bool isReadPipe) {
15201   return isReadPipe ? SemaRef.BuildReadPipeType(ValueType, KWLoc)
15202                     : SemaRef.BuildWritePipeType(ValueType, KWLoc);
15203 }
15204 
15205 template <typename Derived>
15206 QualType TreeTransform<Derived>::RebuildBitIntType(bool IsUnsigned,
15207                                                    unsigned NumBits,
15208                                                    SourceLocation Loc) {
15209   llvm::APInt NumBitsAP(SemaRef.Context.getIntWidth(SemaRef.Context.IntTy),
15210                         NumBits, true);
15211   IntegerLiteral *Bits = IntegerLiteral::Create(SemaRef.Context, NumBitsAP,
15212                                                 SemaRef.Context.IntTy, Loc);
15213   return SemaRef.BuildBitIntType(IsUnsigned, Bits, Loc);
15214 }
15215 
15216 template <typename Derived>
15217 QualType TreeTransform<Derived>::RebuildDependentBitIntType(
15218     bool IsUnsigned, Expr *NumBitsExpr, SourceLocation Loc) {
15219   return SemaRef.BuildBitIntType(IsUnsigned, NumBitsExpr, Loc);
15220 }
15221 
15222 template<typename Derived>
15223 TemplateName
15224 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
15225                                             bool TemplateKW,
15226                                             TemplateDecl *Template) {
15227   return SemaRef.Context.getQualifiedTemplateName(SS.getScopeRep(), TemplateKW,
15228                                                   TemplateName(Template));
15229 }
15230 
15231 template<typename Derived>
15232 TemplateName
15233 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
15234                                             SourceLocation TemplateKWLoc,
15235                                             const IdentifierInfo &Name,
15236                                             SourceLocation NameLoc,
15237                                             QualType ObjectType,
15238                                             NamedDecl *FirstQualifierInScope,
15239                                             bool AllowInjectedClassName) {
15240   UnqualifiedId TemplateName;
15241   TemplateName.setIdentifier(&Name, NameLoc);
15242   Sema::TemplateTy Template;
15243   getSema().ActOnTemplateName(/*Scope=*/nullptr, SS, TemplateKWLoc,
15244                               TemplateName, ParsedType::make(ObjectType),
15245                               /*EnteringContext=*/false, Template,
15246                               AllowInjectedClassName);
15247   return Template.get();
15248 }
15249 
15250 template<typename Derived>
15251 TemplateName
15252 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
15253                                             SourceLocation TemplateKWLoc,
15254                                             OverloadedOperatorKind Operator,
15255                                             SourceLocation NameLoc,
15256                                             QualType ObjectType,
15257                                             bool AllowInjectedClassName) {
15258   UnqualifiedId Name;
15259   // FIXME: Bogus location information.
15260   SourceLocation SymbolLocations[3] = { NameLoc, NameLoc, NameLoc };
15261   Name.setOperatorFunctionId(NameLoc, Operator, SymbolLocations);
15262   Sema::TemplateTy Template;
15263   getSema().ActOnTemplateName(
15264       /*Scope=*/nullptr, SS, TemplateKWLoc, Name, ParsedType::make(ObjectType),
15265       /*EnteringContext=*/false, Template, AllowInjectedClassName);
15266   return Template.get();
15267 }
15268 
15269 template <typename Derived>
15270 ExprResult TreeTransform<Derived>::RebuildCXXOperatorCallExpr(
15271     OverloadedOperatorKind Op, SourceLocation OpLoc, SourceLocation CalleeLoc,
15272     bool RequiresADL, const UnresolvedSetImpl &Functions, Expr *First,
15273     Expr *Second) {
15274   bool isPostIncDec = Second && (Op == OO_PlusPlus || Op == OO_MinusMinus);
15275 
15276   if (First->getObjectKind() == OK_ObjCProperty) {
15277     BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
15278     if (BinaryOperator::isAssignmentOp(Opc))
15279       return SemaRef.checkPseudoObjectAssignment(/*Scope=*/nullptr, OpLoc, Opc,
15280                                                  First, Second);
15281     ExprResult Result = SemaRef.CheckPlaceholderExpr(First);
15282     if (Result.isInvalid())
15283       return ExprError();
15284     First = Result.get();
15285   }
15286 
15287   if (Second && Second->getObjectKind() == OK_ObjCProperty) {
15288     ExprResult Result = SemaRef.CheckPlaceholderExpr(Second);
15289     if (Result.isInvalid())
15290       return ExprError();
15291     Second = Result.get();
15292   }
15293 
15294   // Determine whether this should be a builtin operation.
15295   if (Op == OO_Subscript) {
15296     if (!First->getType()->isOverloadableType() &&
15297         !Second->getType()->isOverloadableType())
15298       return getSema().CreateBuiltinArraySubscriptExpr(First, CalleeLoc, Second,
15299                                                        OpLoc);
15300   } else if (Op == OO_Arrow) {
15301     // It is possible that the type refers to a RecoveryExpr created earlier
15302     // in the tree transformation.
15303     if (First->getType()->isDependentType())
15304       return ExprError();
15305     // -> is never a builtin operation.
15306     return SemaRef.BuildOverloadedArrowExpr(nullptr, First, OpLoc);
15307   } else if (Second == nullptr || isPostIncDec) {
15308     if (!First->getType()->isOverloadableType() ||
15309         (Op == OO_Amp && getSema().isQualifiedMemberAccess(First))) {
15310       // The argument is not of overloadable type, or this is an expression
15311       // of the form &Class::member, so try to create a built-in unary
15312       // operation.
15313       UnaryOperatorKind Opc
15314         = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
15315 
15316       return getSema().CreateBuiltinUnaryOp(OpLoc, Opc, First);
15317     }
15318   } else {
15319     if (!First->getType()->isOverloadableType() &&
15320         !Second->getType()->isOverloadableType()) {
15321       // Neither of the arguments is an overloadable type, so try to
15322       // create a built-in binary operation.
15323       BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
15324       ExprResult Result
15325         = SemaRef.CreateBuiltinBinOp(OpLoc, Opc, First, Second);
15326       if (Result.isInvalid())
15327         return ExprError();
15328 
15329       return Result;
15330     }
15331   }
15332 
15333   // Add any functions found via argument-dependent lookup.
15334   Expr *Args[2] = { First, Second };
15335   unsigned NumArgs = 1 + (Second != nullptr);
15336 
15337   // Create the overloaded operator invocation for unary operators.
15338   if (NumArgs == 1 || isPostIncDec) {
15339     UnaryOperatorKind Opc
15340       = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
15341     return SemaRef.CreateOverloadedUnaryOp(OpLoc, Opc, Functions, First,
15342                                            RequiresADL);
15343   }
15344 
15345   // Create the overloaded operator invocation for binary operators.
15346   BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
15347   ExprResult Result = SemaRef.CreateOverloadedBinOp(
15348       OpLoc, Opc, Functions, Args[0], Args[1], RequiresADL);
15349   if (Result.isInvalid())
15350     return ExprError();
15351 
15352   return Result;
15353 }
15354 
15355 template<typename Derived>
15356 ExprResult
15357 TreeTransform<Derived>::RebuildCXXPseudoDestructorExpr(Expr *Base,
15358                                                      SourceLocation OperatorLoc,
15359                                                        bool isArrow,
15360                                                        CXXScopeSpec &SS,
15361                                                      TypeSourceInfo *ScopeType,
15362                                                        SourceLocation CCLoc,
15363                                                        SourceLocation TildeLoc,
15364                                         PseudoDestructorTypeStorage Destroyed) {
15365   QualType BaseType = Base->getType();
15366   if (Base->isTypeDependent() || Destroyed.getIdentifier() ||
15367       (!isArrow && !BaseType->getAs<RecordType>()) ||
15368       (isArrow && BaseType->getAs<PointerType>() &&
15369        !BaseType->castAs<PointerType>()->getPointeeType()
15370                                               ->template getAs<RecordType>())){
15371     // This pseudo-destructor expression is still a pseudo-destructor.
15372     return SemaRef.BuildPseudoDestructorExpr(
15373         Base, OperatorLoc, isArrow ? tok::arrow : tok::period, SS, ScopeType,
15374         CCLoc, TildeLoc, Destroyed);
15375   }
15376 
15377   TypeSourceInfo *DestroyedType = Destroyed.getTypeSourceInfo();
15378   DeclarationName Name(SemaRef.Context.DeclarationNames.getCXXDestructorName(
15379                  SemaRef.Context.getCanonicalType(DestroyedType->getType())));
15380   DeclarationNameInfo NameInfo(Name, Destroyed.getLocation());
15381   NameInfo.setNamedTypeInfo(DestroyedType);
15382 
15383   // The scope type is now known to be a valid nested name specifier
15384   // component. Tack it on to the end of the nested name specifier.
15385   if (ScopeType) {
15386     if (!ScopeType->getType()->getAs<TagType>()) {
15387       getSema().Diag(ScopeType->getTypeLoc().getBeginLoc(),
15388                      diag::err_expected_class_or_namespace)
15389           << ScopeType->getType() << getSema().getLangOpts().CPlusPlus;
15390       return ExprError();
15391     }
15392     SS.Extend(SemaRef.Context, SourceLocation(), ScopeType->getTypeLoc(),
15393               CCLoc);
15394   }
15395 
15396   SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
15397   return getSema().BuildMemberReferenceExpr(Base, BaseType,
15398                                             OperatorLoc, isArrow,
15399                                             SS, TemplateKWLoc,
15400                                             /*FIXME: FirstQualifier*/ nullptr,
15401                                             NameInfo,
15402                                             /*TemplateArgs*/ nullptr,
15403                                             /*S*/nullptr);
15404 }
15405 
15406 template<typename Derived>
15407 StmtResult
15408 TreeTransform<Derived>::TransformCapturedStmt(CapturedStmt *S) {
15409   SourceLocation Loc = S->getBeginLoc();
15410   CapturedDecl *CD = S->getCapturedDecl();
15411   unsigned NumParams = CD->getNumParams();
15412   unsigned ContextParamPos = CD->getContextParamPosition();
15413   SmallVector<Sema::CapturedParamNameType, 4> Params;
15414   for (unsigned I = 0; I < NumParams; ++I) {
15415     if (I != ContextParamPos) {
15416       Params.push_back(
15417              std::make_pair(
15418                   CD->getParam(I)->getName(),
15419                   getDerived().TransformType(CD->getParam(I)->getType())));
15420     } else {
15421       Params.push_back(std::make_pair(StringRef(), QualType()));
15422     }
15423   }
15424   getSema().ActOnCapturedRegionStart(Loc, /*CurScope*/nullptr,
15425                                      S->getCapturedRegionKind(), Params);
15426   StmtResult Body;
15427   {
15428     Sema::CompoundScopeRAII CompoundScope(getSema());
15429     Body = getDerived().TransformStmt(S->getCapturedStmt());
15430   }
15431 
15432   if (Body.isInvalid()) {
15433     getSema().ActOnCapturedRegionError();
15434     return StmtError();
15435   }
15436 
15437   return getSema().ActOnCapturedRegionEnd(Body.get());
15438 }
15439 
15440 } // end namespace clang
15441 
15442 #endif // LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H
15443